config.c 156 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2007, Roger Dingledine, Nick Mathewson. */
  4. /* See LICENSE for licensing information */
  5. /* $Id$ */
  6. const char config_c_id[] = \
  7. "$Id$";
  8. /**
  9. * \file config.c
  10. * \brief Code to parse and interpret configuration files.
  11. **/
  12. #define CONFIG_PRIVATE
  13. #include "or.h"
  14. #ifdef MS_WINDOWS
  15. #include <shlobj.h>
  16. #endif
  17. /** Enumeration of types which option values can take */
  18. typedef enum config_type_t {
  19. CONFIG_TYPE_STRING = 0, /**< An arbitrary string. */
  20. CONFIG_TYPE_UINT, /**< A non-negative integer less than MAX_INT */
  21. CONFIG_TYPE_INTERVAL, /**< A number of seconds, with optional units*/
  22. CONFIG_TYPE_MEMUNIT, /**< A number of bytes, with optional units*/
  23. CONFIG_TYPE_DOUBLE, /**< A floating-point value */
  24. CONFIG_TYPE_BOOL, /**< A boolean value, expressed as 0 or 1. */
  25. CONFIG_TYPE_ISOTIME, /**< An ISO-formated time relative to GMT. */
  26. CONFIG_TYPE_CSV, /**< A list of strings, separated by commas and
  27. * optional whitespace. */
  28. CONFIG_TYPE_LINELIST, /**< Uninterpreted config lines */
  29. CONFIG_TYPE_LINELIST_S, /**< Uninterpreted, context-sensitive config lines,
  30. * mixed with other keywords. */
  31. CONFIG_TYPE_LINELIST_V, /**< Catch-all "virtual" option to summarize
  32. * context-sensitive config lines when fetching.
  33. */
  34. CONFIG_TYPE_OBSOLETE, /**< Obsolete (ignored) option. */
  35. } config_type_t;
  36. /** An abbreviation for a configuration option allowed on the command line. */
  37. typedef struct config_abbrev_t {
  38. const char *abbreviated;
  39. const char *full;
  40. int commandline_only;
  41. int warn;
  42. } config_abbrev_t;
  43. /* Handy macro for declaring "In the config file or on the command line,
  44. * you can abbreviate <b>tok</b>s as <b>tok</b>". */
  45. #define PLURAL(tok) { #tok, #tok "s", 0, 0 }
  46. /* A list of command-line abbreviations. */
  47. static config_abbrev_t _option_abbrevs[] = {
  48. PLURAL(ExitNode),
  49. PLURAL(EntryNode),
  50. PLURAL(ExcludeNode),
  51. PLURAL(FirewallPort),
  52. PLURAL(LongLivedPort),
  53. PLURAL(HiddenServiceNode),
  54. PLURAL(HiddenServiceExcludeNode),
  55. PLURAL(NumCpu),
  56. PLURAL(RendNode),
  57. PLURAL(RendExcludeNode),
  58. PLURAL(StrictEntryNode),
  59. PLURAL(StrictExitNode),
  60. { "l", "Log", 1, 0},
  61. { "AllowUnverifiedNodes", "AllowInvalidNodes", 0, 0},
  62. { "AutomapHostSuffixes", "AutomapHostsSuffixes", 0, 0},
  63. { "AutomapHostOnResolve", "AutomapHostsOnResolve", 0, 0},
  64. { "BandwidthRateBytes", "BandwidthRate", 0, 0},
  65. { "BandwidthBurstBytes", "BandwidthBurst", 0, 0},
  66. { "DirFetchPostPeriod", "StatusFetchPeriod", 0, 0},
  67. { "MaxConn", "ConnLimit", 0, 1},
  68. { "ORBindAddress", "ORListenAddress", 0, 0},
  69. { "DirBindAddress", "DirListenAddress", 0, 0},
  70. { "SocksBindAddress", "SocksListenAddress", 0, 0},
  71. { "UseHelperNodes", "UseEntryGuards", 0, 0},
  72. { "NumHelperNodes", "NumEntryGuards", 0, 0},
  73. { "UseEntryNodes", "UseEntryGuards", 0, 0},
  74. { "NumEntryNodes", "NumEntryGuards", 0, 0},
  75. { "ResolvConf", "ServerDNSResolvConfFile", 0, 1},
  76. { "SearchDomains", "ServerDNSSearchDomains", 0, 1},
  77. { NULL, NULL, 0, 0},
  78. };
  79. /* A list of state-file abbreviations, for compatibility. */
  80. static config_abbrev_t _state_abbrevs[] = {
  81. { "AccountingBytesReadInterval", "AccountingBytesReadInInterval", 0, 0 },
  82. { "HelperNode", "EntryGuard", 0, 0 },
  83. { "HelperNodeDownSince", "EntryGuardDownSince", 0, 0 },
  84. { "HelperNodeUnlistedSince", "EntryGuardUnlistedSince", 0, 0 },
  85. { "EntryNode", "EntryGuard", 0, 0 },
  86. { "EntryNodeDownSince", "EntryGuardDownSince", 0, 0 },
  87. { "EntryNodeUnlistedSince", "EntryGuardUnlistedSince", 0, 0 },
  88. { NULL, NULL, 0, 0},
  89. };
  90. #undef PLURAL
  91. /** A variable allowed in the configuration file or on the command line. */
  92. typedef struct config_var_t {
  93. const char *name; /**< The full keyword (case insensitive). */
  94. config_type_t type; /**< How to interpret the type and turn it into a
  95. * value. */
  96. off_t var_offset; /**< Offset of the corresponding member of or_options_t. */
  97. const char *initvalue; /**< String (or null) describing initial value. */
  98. } config_var_t;
  99. /** An entry for config_vars: "The option <b>name</b> has type
  100. * CONFIG_TYPE_<b>conftype</b>, and corresponds to
  101. * or_options_t.<b>member</b>"
  102. */
  103. #define VAR(name,conftype,member,initvalue) \
  104. { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_options_t, member), \
  105. initvalue }
  106. /** An entry for config_vars: "The option <b>name</b> is obsolete." */
  107. #define OBSOLETE(name) { name, CONFIG_TYPE_OBSOLETE, 0, NULL }
  108. /** Array of configuration options. Until we disallow nonstandard
  109. * abbreviations, order is significant, since the first matching option will
  110. * be chosen first.
  111. */
  112. static config_var_t _option_vars[] = {
  113. OBSOLETE("AccountingMaxKB"),
  114. VAR("AccountingMax", MEMUNIT, AccountingMax, "0 bytes"),
  115. VAR("AccountingStart", STRING, AccountingStart, NULL),
  116. VAR("Address", STRING, Address, NULL),
  117. VAR("AllowInvalidNodes", CSV, AllowInvalidNodes,
  118. "middle,rendezvous"),
  119. VAR("AllowNonRFC953Hostnames", BOOL, AllowNonRFC953Hostnames, "0"),
  120. VAR("AssumeReachable", BOOL, AssumeReachable, "0"),
  121. VAR("AuthDirBadExit", LINELIST, AuthDirBadExit, NULL),
  122. VAR("AuthDirInvalid", LINELIST, AuthDirInvalid, NULL),
  123. VAR("AuthDirReject", LINELIST, AuthDirReject, NULL),
  124. VAR("AuthDirRejectUnlisted",BOOL, AuthDirRejectUnlisted,"0"),
  125. VAR("AuthDirListBadExits", BOOL, AuthDirListBadExits, "0"),
  126. VAR("AuthoritativeDirectory",BOOL, AuthoritativeDir, "0"),
  127. VAR("AutomapHostsOnResolve",BOOL, AutomapHostsOnResolve,"0"),
  128. VAR("AutomapHostsSuffixes",CSV, AutomapHostsSuffixes, ".onion,.exit"),
  129. VAR("AvoidDiskWrites", BOOL, AvoidDiskWrites, "0"),
  130. VAR("BandwidthBurst", MEMUNIT, BandwidthBurst, "6 MB"),
  131. VAR("BandwidthRate", MEMUNIT, BandwidthRate, "3 MB"),
  132. VAR("BridgeAuthoritativeDir", BOOL, BridgeAuthoritativeDir, "0"),
  133. VAR("Bridge", LINELIST, Bridges, NULL),
  134. VAR("CircuitBuildTimeout", INTERVAL, CircuitBuildTimeout, "1 minute"),
  135. VAR("CircuitIdleTimeout", INTERVAL, CircuitIdleTimeout, "1 hour"),
  136. VAR("ClientOnly", BOOL, ClientOnly, "0"),
  137. VAR("ConnLimit", UINT, ConnLimit, "1000"),
  138. VAR("ConstrainedSockets", BOOL, ConstrainedSockets, "0"),
  139. VAR("ConstrainedSockSize", MEMUNIT, ConstrainedSockSize, "8192"),
  140. VAR("ContactInfo", STRING, ContactInfo, NULL),
  141. VAR("ControlListenAddress",LINELIST, ControlListenAddress, NULL),
  142. VAR("ControlPort", UINT, ControlPort, "0"),
  143. VAR("ControlSocket", LINELIST, ControlSocket, NULL),
  144. VAR("CookieAuthentication",BOOL, CookieAuthentication, "0"),
  145. VAR("DataDirectory", STRING, DataDirectory, NULL),
  146. OBSOLETE("DebugLogFile"),
  147. VAR("DirAllowPrivateAddresses",BOOL, DirAllowPrivateAddresses, NULL),
  148. VAR("DirListenAddress", LINELIST, DirListenAddress, NULL),
  149. OBSOLETE("DirFetchPeriod"),
  150. VAR("DirPolicy", LINELIST, DirPolicy, NULL),
  151. VAR("DirPort", UINT, DirPort, "0"),
  152. OBSOLETE("DirPostPeriod"),
  153. VAR("DirServer", LINELIST, DirServers, NULL),
  154. VAR("DNSPort", UINT, DNSPort, "0"),
  155. VAR("DNSListenAddress", LINELIST, DNSListenAddress, NULL),
  156. VAR("DownloadExtraInfo", BOOL, DownloadExtraInfo, "0"),
  157. VAR("EnforceDistinctSubnets", BOOL, EnforceDistinctSubnets,"1"),
  158. VAR("EntryNodes", STRING, EntryNodes, NULL),
  159. VAR("ExcludeNodes", STRING, ExcludeNodes, NULL),
  160. VAR("ExitNodes", STRING, ExitNodes, NULL),
  161. VAR("ExitPolicy", LINELIST, ExitPolicy, NULL),
  162. VAR("ExitPolicyRejectPrivate", BOOL, ExitPolicyRejectPrivate, "1"),
  163. VAR("FascistFirewall", BOOL, FascistFirewall, "0"),
  164. VAR("FirewallPorts", CSV, FirewallPorts, ""),
  165. VAR("FastFirstHopPK", BOOL, FastFirstHopPK, "1"),
  166. VAR("FetchServerDescriptors",BOOL, FetchServerDescriptors,"1"),
  167. VAR("FetchHidServDescriptors",BOOL, FetchHidServDescriptors, "1"),
  168. VAR("FetchUselessDescriptors",BOOL, FetchUselessDescriptors, "0"),
  169. VAR("Group", STRING, Group, NULL),
  170. VAR("HardwareAccel", BOOL, HardwareAccel, "0"),
  171. VAR("HashedControlPassword",STRING, HashedControlPassword, NULL),
  172. VAR("HiddenServiceDir", LINELIST_S, RendConfigLines, NULL),
  173. VAR("HiddenServiceExcludeNodes", LINELIST_S, RendConfigLines, NULL),
  174. VAR("HiddenServiceNodes", LINELIST_S, RendConfigLines, NULL),
  175. VAR("HiddenServiceOptions",LINELIST_V, RendConfigLines, NULL),
  176. VAR("HiddenServicePort", LINELIST_S, RendConfigLines, NULL),
  177. VAR("HSAuthoritativeDir", BOOL, HSAuthoritativeDir, "0"),
  178. VAR("HSAuthorityRecordStats",BOOL, HSAuthorityRecordStats,"0"),
  179. VAR("HttpProxy", STRING, HttpProxy, NULL),
  180. VAR("HttpProxyAuthenticator",STRING, HttpProxyAuthenticator,NULL),
  181. VAR("HttpsProxy", STRING, HttpsProxy, NULL),
  182. VAR("HttpsProxyAuthenticator",STRING,HttpsProxyAuthenticator,NULL),
  183. OBSOLETE("IgnoreVersion"),
  184. VAR("KeepalivePeriod", INTERVAL, KeepalivePeriod, "5 minutes"),
  185. VAR("Log", LINELIST, Logs, NULL),
  186. OBSOLETE("LinkPadding"),
  187. OBSOLETE("LogLevel"),
  188. OBSOLETE("LogFile"),
  189. VAR("LongLivedPorts", CSV, LongLivedPorts,
  190. "21,22,706,1863,5050,5190,5222,5223,6667,6697,8300"),
  191. VAR("MapAddress", LINELIST, AddressMap, NULL),
  192. VAR("MaxAdvertisedBandwidth",MEMUNIT,MaxAdvertisedBandwidth,"1 GB"),
  193. VAR("MaxCircuitDirtiness", INTERVAL, MaxCircuitDirtiness, "10 minutes"),
  194. VAR("MaxOnionsPending", UINT, MaxOnionsPending, "100"),
  195. OBSOLETE("MonthlyAccountingStart"),
  196. VAR("MyFamily", STRING, MyFamily, NULL),
  197. VAR("NewCircuitPeriod", INTERVAL, NewCircuitPeriod, "30 seconds"),
  198. VAR("NamingAuthoritativeDirectory",BOOL, NamingAuthoritativeDir, "0"),
  199. VAR("NatdListenAddress", LINELIST, NatdListenAddress, NULL),
  200. VAR("NatdPort", UINT, NatdPort, "0"),
  201. VAR("Nickname", STRING, Nickname, NULL),
  202. VAR("NoPublish", BOOL, NoPublish, "0"),
  203. VAR("NodeFamily", LINELIST, NodeFamilies, NULL),
  204. VAR("NumCpus", UINT, NumCpus, "1"),
  205. VAR("NumEntryGuards", UINT, NumEntryGuards, "3"),
  206. VAR("ORListenAddress", LINELIST, ORListenAddress, NULL),
  207. VAR("ORPort", UINT, ORPort, "0"),
  208. VAR("OutboundBindAddress", STRING, OutboundBindAddress, NULL),
  209. OBSOLETE("PathlenCoinWeight"),
  210. VAR("PidFile", STRING, PidFile, NULL),
  211. VAR("PreferTunneledDirConns", BOOL, PreferTunneledDirConns, "0"),
  212. VAR("ProtocolWarnings", BOOL, ProtocolWarnings, "0"),
  213. VAR("PublishServerDescriptor", CSV, PublishServerDescriptor,"v1,v2"),
  214. VAR("PublishHidServDescriptors",BOOL,PublishHidServDescriptors, "1"),
  215. VAR("ReachableAddresses", LINELIST, ReachableAddresses, NULL),
  216. VAR("ReachableDirAddresses",LINELIST,ReachableDirAddresses,NULL),
  217. VAR("ReachableORAddresses",LINELIST, ReachableORAddresses, NULL),
  218. VAR("RecommendedVersions", LINELIST, RecommendedVersions, NULL),
  219. VAR("RecommendedClientVersions", LINELIST, RecommendedClientVersions, NULL),
  220. VAR("RecommendedServerVersions", LINELIST, RecommendedServerVersions, NULL),
  221. VAR("RedirectExit", LINELIST, RedirectExit, NULL),
  222. VAR("RelayBandwidthBurst", MEMUNIT, RelayBandwidthBurst, "0"),
  223. VAR("RelayBandwidthRate", MEMUNIT, RelayBandwidthRate, "0"),
  224. VAR("RendExcludeNodes", STRING, RendExcludeNodes, NULL),
  225. VAR("RendNodes", STRING, RendNodes, NULL),
  226. VAR("RendPostPeriod", INTERVAL, RendPostPeriod, "1 hour"),
  227. VAR("RephistTrackTime", INTERVAL, RephistTrackTime, "24 hours"),
  228. OBSOLETE("RouterFile"),
  229. VAR("RunAsDaemon", BOOL, RunAsDaemon, "0"),
  230. VAR("RunTesting", BOOL, RunTesting, "0"),
  231. VAR("SafeLogging", BOOL, SafeLogging, "1"),
  232. VAR("SafeSocks", BOOL, SafeSocks, "0"),
  233. VAR("ServerDNSAllowNonRFC953Hostnames",
  234. BOOL, ServerDNSAllowNonRFC953Hostnames, "0"),
  235. VAR("ServerDNSDetectHijacking",BOOL, ServerDNSDetectHijacking,"1"),
  236. VAR("ServerDNSResolvConfFile", STRING, ServerDNSResolvConfFile, NULL),
  237. VAR("ServerDNSSearchDomains", BOOL, ServerDNSSearchDomains, "0"),
  238. VAR("ServerDNSTestAddresses", CSV, ServerDNSTestAddresses,
  239. "www.google.com,www.mit.edu,www.yahoo.com,www.slashdot.org"),
  240. VAR("ShutdownWaitLength", INTERVAL, ShutdownWaitLength, "30 seconds"),
  241. VAR("SocksListenAddress", LINELIST, SocksListenAddress, NULL),
  242. VAR("SocksPolicy", LINELIST, SocksPolicy, NULL),
  243. VAR("SocksPort", UINT, SocksPort, "9050"),
  244. VAR("SocksTimeout", INTERVAL, SocksTimeout, "2 minutes"),
  245. OBSOLETE("StatusFetchPeriod"),
  246. VAR("StrictEntryNodes", BOOL, StrictEntryNodes, "0"),
  247. VAR("StrictExitNodes", BOOL, StrictExitNodes, "0"),
  248. OBSOLETE("SysLog"),
  249. VAR("TestSocks", BOOL, TestSocks, "0"),
  250. VAR("TestVia", STRING, TestVia, NULL),
  251. VAR("TrackHostExits", CSV, TrackHostExits, NULL),
  252. VAR("TrackHostExitsExpire",INTERVAL, TrackHostExitsExpire, "30 minutes"),
  253. OBSOLETE("TrafficShaping"),
  254. VAR("TransListenAddress", LINELIST, TransListenAddress, NULL),
  255. VAR("TransPort", UINT, TransPort, "0"),
  256. VAR("TunnelDirConns", BOOL, TunnelDirConns, "0"),
  257. VAR("UpdateBridgesFromAuthority",BOOL,UpdateBridgesFromAuthority,"0"),
  258. VAR("UseBridges", BOOL, UseBridges, "0"),
  259. VAR("UseEntryGuards", BOOL, UseEntryGuards, "1"),
  260. VAR("User", STRING, User, NULL),
  261. VAR("V1AuthoritativeDirectory",BOOL, V1AuthoritativeDir, "0"),
  262. VAR("V2AuthoritativeDirectory",BOOL, V2AuthoritativeDir, "0"),
  263. VAR("V3AuthoritativeDirectory",BOOL, V3AuthoritativeDir, "0"),
  264. VAR("VersioningAuthoritativeDirectory",BOOL,VersioningAuthoritativeDir, "0"),
  265. VAR("VirtualAddrNetwork", STRING, VirtualAddrNetwork, "127.192.0.0/10"),
  266. VAR("__AllDirActionsPrivate",BOOL, AllDirActionsPrivate, "0"),
  267. VAR("__DisablePredictedCircuits",BOOL,DisablePredictedCircuits,"0"),
  268. VAR("__LeaveStreamsUnattached", BOOL,LeaveStreamsUnattached, "0"),
  269. { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
  270. };
  271. #undef VAR
  272. #define VAR(name,conftype,member,initvalue) \
  273. { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_state_t, member), \
  274. initvalue }
  275. static config_var_t _state_vars[] = {
  276. VAR("AccountingBytesReadInInterval", MEMUNIT,
  277. AccountingBytesReadInInterval, NULL),
  278. VAR("AccountingBytesWrittenInInterval", MEMUNIT,
  279. AccountingBytesWrittenInInterval, NULL),
  280. VAR("AccountingExpectedUsage", MEMUNIT, AccountingExpectedUsage, NULL),
  281. VAR("AccountingIntervalStart", ISOTIME, AccountingIntervalStart, NULL),
  282. VAR("AccountingSecondsActive", INTERVAL, AccountingSecondsActive, NULL),
  283. VAR("EntryGuard", LINELIST_S, EntryGuards, NULL),
  284. VAR("EntryGuardDownSince", LINELIST_S, EntryGuards, NULL),
  285. VAR("EntryGuardUnlistedSince", LINELIST_S, EntryGuards, NULL),
  286. VAR("EntryGuards", LINELIST_V, EntryGuards, NULL),
  287. VAR("BWHistoryReadEnds", ISOTIME, BWHistoryReadEnds, NULL),
  288. VAR("BWHistoryReadInterval", UINT, BWHistoryReadInterval, "900"),
  289. VAR("BWHistoryReadValues", CSV, BWHistoryReadValues, ""),
  290. VAR("BWHistoryWriteEnds", ISOTIME, BWHistoryWriteEnds, NULL),
  291. VAR("BWHistoryWriteInterval", UINT, BWHistoryWriteInterval, "900"),
  292. VAR("BWHistoryWriteValues", CSV, BWHistoryWriteValues, ""),
  293. VAR("TorVersion", STRING, TorVersion, NULL),
  294. VAR("LastRotatedOnionKey", ISOTIME, LastRotatedOnionKey, NULL),
  295. VAR("LastWritten", ISOTIME, LastWritten, NULL),
  296. { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
  297. };
  298. #undef VAR
  299. #undef OBSOLETE
  300. /** Represents an English description of a configuration variable; used when
  301. * generating configuration file comments. */
  302. typedef struct config_var_description_t {
  303. const char *name;
  304. const char *description;
  305. } config_var_description_t;
  306. static config_var_description_t options_description[] = {
  307. /* ==== general options */
  308. { "AvoidDiskWrites", "If non-zero, try to write to disk less frequently than"
  309. " we would otherwise." },
  310. { "BandwidthRate", "A token bucket limits the average incoming bandwidth on "
  311. "this node to the specified number of bytes per second." },
  312. { "BandwidthBurst", "Limit the maximum token buffer size (also known as "
  313. "burst) to the given number of bytes." },
  314. { "ConnLimit", "Maximum number of simultaneous sockets allowed." },
  315. { "ConstrainedSockets", "Shrink tx and rx buffers for sockets to avoid "
  316. "system limits on vservers and related environments. See man page for "
  317. "more information regarding this option." },
  318. { "ConstrainedSockSize", "Limit socket buffers to this size when "
  319. "ConstrainedSockets is enabled." },
  320. /* ControlListenAddress */
  321. { "ControlPort", "If set, Tor will accept connections from the same machine "
  322. "(localhost only) on this port, and allow those connections to control "
  323. "the Tor process using the Tor Control Protocol (described in"
  324. "control-spec.txt).", },
  325. { "CookieAuthentication", "If this option is set to 1, don't allow any "
  326. "connections to the control port except when the connecting process "
  327. "can read a file that Tor creates in its data directory." },
  328. { "DataDirectory", "Store working data, state, keys, and caches here." },
  329. { "DirServer", "Tor only trusts directories signed with one of these "
  330. "servers' keys. Used to override the standard list of directory "
  331. "authorities." },
  332. /* { "FastFirstHopPK", "" }, */
  333. /* FetchServerDescriptors, FetchHidServDescriptors,
  334. * FetchUselessDescriptors */
  335. { "Group", "On startup, setgid to this group." },
  336. { "HardwareAccel", "If set, Tor tries to use hardware crypto accelerators "
  337. "when it can." },
  338. /* HashedControlPassword */
  339. { "HTTPProxy", "Force Tor to make all HTTP directory requests through this "
  340. "host:port (or host:80 if port is not set)." },
  341. { "HTTPProxyAuthenticator", "A username:password pair to be used with "
  342. "HTTPProxy." },
  343. { "HTTPSProxy", "Force Tor to make all TLS (SSL) connectinos through this "
  344. "host:port (or host:80 if port is not set)." },
  345. { "HTTPSProxyAuthenticator", "A username:password pair to be used with "
  346. "HTTPSProxy." },
  347. { "KeepalivePeriod", "Send a padding cell every N seconds to keep firewalls "
  348. "from closing our connections while Tor is not in use." },
  349. { "Log", "Where to send logging messages. Format is "
  350. "minSeverity[-maxSeverity] (stderr|stdout|syslog|file FILENAME)." },
  351. { "OutboundBindAddress", "Make all outbound connections originate from the "
  352. "provided IP address (only useful for multiple network interfaces)." },
  353. { "PIDFile", "On startup, write our PID to this file. On clean shutdown, "
  354. "remove the file." },
  355. { "PreferTunneledDirConns", "If non-zero, avoid directory servers that "
  356. "don't support tunneled conncetions." },
  357. /* PreferTunneledDirConns */
  358. /* ProtocolWarnings */
  359. /* RephistTrackTime */
  360. { "RunAsDaemon", "If set, Tor forks and daemonizes to the background when "
  361. "started. Unix only." },
  362. { "SafeLogging", "If set to 0, Tor logs potentially sensitive strings "
  363. "rather than replacing them with the string [scrubbed]." },
  364. { "TunnelDirConns", "If non-zero, when a directory server we contact "
  365. "supports it, we will build a one-hop circuit and make an encrypted "
  366. "connection via its ORPort." },
  367. { "User", "On startup, setuid to this user" },
  368. /* ==== client options */
  369. { "AllowInvalidNodes", "Where on our circuits should Tor allow servers "
  370. "that the directory authorities haven't called \"valid\"?" },
  371. { "AllowNonRFC953Hostnames", "If set to 1, we don't automatically reject "
  372. "hostnames for having invalid characters." },
  373. /* CircuitBuildTimeout, CircuitIdleTimeout */
  374. { "ClientOnly", "If set to 1, Tor will under no circumstances run as a "
  375. "server, even if ORPort is enabled." },
  376. { "EntryNodes", "A list of preferred entry nodes to use for the first hop "
  377. "in circuits, when possible." },
  378. /* { "EnforceDistinctSubnets" , "" }, */
  379. { "ExitNodes", "A list of preferred nodes to use for the last hop in "
  380. "circuits, when possible." },
  381. { "ExcludeNodes", "A list of nodes never to use when building a circuit." },
  382. { "FascistFirewall", "If set, Tor will only create outgoing connections to "
  383. "servers running on the ports listed in FirewallPorts." },
  384. { "FirewallPorts", "A list of ports that we can connect to. Only used "
  385. "when FascistFirewall is set." },
  386. { "LongLivedPorts", "A list of ports for services that tend to require "
  387. "high-uptime connections." },
  388. { "MapAddress", "Force Tor to treat all requests for one address as if "
  389. "they were for another." },
  390. { "NewCircuitPeriod", "Force Tor to consider whether to build a new circuit "
  391. "every NUM seconds." },
  392. { "MaxCircuitDirtiness", "Do not attach new streams to a circuit that has "
  393. "been used more than this many seconds ago." },
  394. /* NatdPort, NatdListenAddress */
  395. { "NodeFamily", "A list of servers that constitute a 'family' and should "
  396. "never be used in the same circuit." },
  397. { "NumEntryGuards", "How many entry guards should we keep at a time?" },
  398. /* PathlenCoinWeight */
  399. { "ReachableAddresses", "Addresses we can connect to, as IP/bits:port-port. "
  400. "By default, we assume all addresses are reachable." },
  401. /* reachablediraddresses, reachableoraddresses. */
  402. { "RendNodes", "A list of preferred nodes to use for a rendezvous point, "
  403. "when possible." },
  404. { "RendExcludenodes", "A list of nodes never to use as rendezvous points." },
  405. /* SafeSOCKS */
  406. { "SOCKSPort", "The port where we listen for SOCKS connections from "
  407. "applications." },
  408. { "SOCKSListenAddress", "Bind to this address to listen to connections from "
  409. "SOCKS-speaking applications." },
  410. { "SOCKSPolicy", "Set an entry policy to limit which addresses can connect "
  411. "to the SOCKSPort." },
  412. /* SocksTimeout */
  413. { "StrictExitNodes", "If set, Tor will fail to operate when none of the "
  414. "configured ExitNodes can be used." },
  415. { "StrictEntryNodes", "If set, Tor will fail to operate when none of the "
  416. "configured EntryNodes can be used." },
  417. /* TestSocks */
  418. { "TrackHostsExit", "Hosts and domains which should, if possible, be "
  419. "accessed from the same exit node each time we connect to them." },
  420. { "TrackHostsExitExpire", "Time after which we forget which exit we were "
  421. "using to connect to hosts in TrackHostsExit." },
  422. /* "TransPort", "TransListenAddress */
  423. { "UseEntryGuards", "Set to 0 if we want to pick from the whole set of "
  424. "servers for the first position in each circuit, rather than picking a "
  425. "set of 'Guards' to prevent profiling attacks." },
  426. /* === server options */
  427. { "Address", "The advertised (external) address we should use." },
  428. /* Accounting* options. */
  429. /* AssumeReachable */
  430. { "ContactInfo", "Administrative contact information to advertise for this "
  431. "server." },
  432. { "ExitPolicy", "Address/port ranges for which to accept or reject outgoing "
  433. "connections on behalf of Tor users." },
  434. /* { "ExitPolicyRejectPrivate, "" }, */
  435. { "MaxAdvertisedBandwidth", "If set, we will not advertise more than this "
  436. "amount of bandwidth for our bandwidth rate, regardless of how much "
  437. "bandwidth we actually detect." },
  438. { "MaxOnionsPending", "Reject new attempts to extend circuits when we "
  439. "already have this many pending." },
  440. { "MyFamily", "Declare a list of other servers as belonging to the same "
  441. "family as this one, so that clients will not use two from the same "
  442. "family in the same circuit." },
  443. { "Nickname", "Set the server nickname." },
  444. { "NoPublish", "{DEPRECATED}" },
  445. { "NumCPUs", "How many processes to use at once for public-key crypto." },
  446. { "ORPort", "Advertise this port to listen for connections from Tor clients "
  447. "and servers." },
  448. { "ORListenAddress", "Bind to this address to listen for connections from "
  449. "clients and servers, instead of the default 0.0.0.0:ORPort." },
  450. { "PublishServerDescriptors", "Set to \"\" to keep the server from "
  451. "uploading info to the directory authorities." },
  452. /*{ "RedirectExit", "When an outgoing connection tries to connect to a "
  453. *"given address, redirect it to another address instead." },
  454. */
  455. /* ServerDNS: DetectHijacking, ResolvConfFile, SearchDomains */
  456. { "ShutdownWaitLength", "Wait this long for clients to finish when "
  457. "shutting down because of a SIGINT." },
  458. /* { "TestVia", } */
  459. /* === directory cache options */
  460. { "DirPort", "Serve directory information from this port, and act as a "
  461. "directory cache." },
  462. { "DirListenAddress", "Bind to this address to listen for connections from "
  463. "clients and servers, instead of the default 0.0.0.0:DirPort." },
  464. { "DirPolicy", "Set a policy to limit who can connect to the directory "
  465. "port" },
  466. /* Authority options: AuthDirBadExit, AuthDirInvalid, AuthDirReject,
  467. * AuthDirRejectUnlisted, AuthDirListBadExits, AuthoritativeDirectory,
  468. * DirAllowPrivateAddresses, HSAuthoritativeDir,
  469. * NamingAuthoritativeDirectory, RecommendedVersions,
  470. * RecommendedClientVersions, RecommendedServerVersions, RendPostPeriod,
  471. * RunTesting, V1AuthoritativeDirectory, VersioningAuthoritativeDirectory, */
  472. /* Hidden service options: HiddenService: dir,excludenodes, nodes,
  473. * options, port. PublishHidServDescriptor */
  474. /* Nonpersistent options: __LeaveStreamsUnattached, __AllDirActionsPrivate */
  475. { NULL, NULL },
  476. };
  477. static config_var_description_t state_description[] = {
  478. { "AccountingBytesReadInInterval",
  479. "How many bytes have we read in this accounting period?" },
  480. { "AccountingBytesWrittenInInterval",
  481. "How many bytes have we written in this accounting period?" },
  482. { "AccountingExpectedUsage",
  483. "How many bytes did we expect to use per minute? (0 for no estimate.)" },
  484. { "AccountingIntervalStart", "When did this accounting period begin?" },
  485. { "AccountingSecondsActive", "How long have we been awake in this period?" },
  486. { "BWHistoryReadEnds", "When does the last-recorded read-interval end?" },
  487. { "BWHistoryReadInterval", "How long is each read-interval (in seconds)?" },
  488. { "BWHistoryReadValues", "Number of bytes read in each interval." },
  489. { "BWHistoryWriteEnds", "When does the last-recorded write-interval end?" },
  490. { "BWHistoryWriteInterval", "How long is each write-interval (in seconds)?"},
  491. { "BWHistoryWriteValues", "Number of bytes written in each interval." },
  492. { "EntryGuard", "One of the nodes we have chosen as a fixed entry" },
  493. { "EntryGuardDownSince",
  494. "The last entry guard has been unreachable since this time." },
  495. { "EntryGuardUnlistedSince",
  496. "The last entry guard has been unusable since this time." },
  497. { "LastRotatedOnionKey",
  498. "The last time at which we changed the medium-term private key used for "
  499. "building circuits." },
  500. { "LastWritten", "When was this state file last regenerated?" },
  501. { "TorVersion", "Which version of Tor generated this state file?" },
  502. { NULL, NULL },
  503. };
  504. /** Type of a callback to validate whether a given configuration is
  505. * well-formed and consistent. See options_trial_assign() for documentation
  506. * of arguments. */
  507. typedef int (*validate_fn_t)(void*,void*,int,char**);
  508. /** Information on the keys, value types, key-to-struct-member mappings,
  509. * variable descriptions, validation functions, and abbreviations for a
  510. * configuration or storage format. */
  511. typedef struct {
  512. size_t size; /**< Size of the struct that everything gets parsed into. */
  513. uint32_t magic; /**< Required 'magic value' to make sure we have a struct
  514. * of the right type. */
  515. off_t magic_offset; /**< Offset of the magic value within the struct. */
  516. config_abbrev_t *abbrevs; /**< List of abbreviations that we expand when
  517. * parsing this format. */
  518. config_var_t *vars; /**< List of variables we recognize, their default
  519. * values, and where we stick them in the structure. */
  520. validate_fn_t validate_fn; /**< Function to validate config. */
  521. /** Documentation for configuration variables. */
  522. config_var_description_t *descriptions;
  523. /** If present, extra is a LINELIST variable for unrecognized
  524. * lines. Otherwise, unrecognized lines are an error. */
  525. config_var_t *extra;
  526. } config_format_t;
  527. /** Macro: assert that <b>cfg</b> has the right magic field for format
  528. * <b>fmt</b>. */
  529. #define CHECK(fmt, cfg) STMT_BEGIN \
  530. tor_assert(fmt && cfg); \
  531. tor_assert((fmt)->magic == \
  532. *(uint32_t*)STRUCT_VAR_P(cfg,fmt->magic_offset)); \
  533. STMT_END
  534. static void config_line_append(config_line_t **lst,
  535. const char *key, const char *val);
  536. static void option_clear(config_format_t *fmt, or_options_t *options,
  537. config_var_t *var);
  538. static void option_reset(config_format_t *fmt, or_options_t *options,
  539. config_var_t *var, int use_defaults);
  540. static void config_free(config_format_t *fmt, void *options);
  541. static int option_is_same(config_format_t *fmt,
  542. or_options_t *o1, or_options_t *o2,
  543. const char *name);
  544. static or_options_t *options_dup(config_format_t *fmt, or_options_t *old);
  545. static int options_validate(or_options_t *old_options, or_options_t *options,
  546. int from_setconf, char **msg);
  547. static int options_act_reversible(or_options_t *old_options, char **msg);
  548. static int options_act(or_options_t *old_options);
  549. static int options_transition_allowed(or_options_t *old, or_options_t *new,
  550. char **msg);
  551. static int options_transition_affects_workers(or_options_t *old_options,
  552. or_options_t *new_options);
  553. static int options_transition_affects_descriptor(or_options_t *old_options,
  554. or_options_t *new_options);
  555. static int check_nickname_list(const char *lst, const char *name, char **msg);
  556. static void config_register_addressmaps(or_options_t *options);
  557. static int parse_bridge_line(const char *line, int validate_only);
  558. static int parse_dir_server_line(const char *line, int validate_only);
  559. static int parse_redirect_line(smartlist_t *result,
  560. config_line_t *line, char **msg);
  561. static int parse_log_severity_range(const char *range, int *min_out,
  562. int *max_out);
  563. static int validate_data_directory(or_options_t *options);
  564. static int write_configuration_file(const char *fname, or_options_t *options);
  565. static config_line_t *get_assigned_option(config_format_t *fmt,
  566. or_options_t *options, const char *key);
  567. static void config_init(config_format_t *fmt, void *options);
  568. static int or_state_validate(or_state_t *old_options, or_state_t *options,
  569. int from_setconf, char **msg);
  570. static uint64_t config_parse_memunit(const char *s, int *ok);
  571. static int config_parse_interval(const char *s, int *ok);
  572. static void print_svn_version(void);
  573. static void init_libevent(void);
  574. static int opt_streq(const char *s1, const char *s2);
  575. /** Versions of libevent. */
  576. typedef enum {
  577. /* Note: we compare these, so it's important that "old" precede everything,
  578. * and that "other" come last. */
  579. LE_OLD=0, LE_10C, LE_10D, LE_10E, LE_11, LE_11A, LE_11B, LE_12, LE_12A,
  580. LE_13, LE_13A, LE_13B,
  581. LE_OTHER
  582. } le_version_t;
  583. static le_version_t decode_libevent_version(void);
  584. #if defined(HAVE_EVENT_GET_VERSION) && defined(HAVE_EVENT_GET_METHOD)
  585. static void check_libevent_version(const char *m, int server);
  586. #endif
  587. /** Magic value for or_options_t. */
  588. #define OR_OPTIONS_MAGIC 9090909
  589. /** Configuration format for or_options_t. */
  590. static config_format_t options_format = {
  591. sizeof(or_options_t),
  592. OR_OPTIONS_MAGIC,
  593. STRUCT_OFFSET(or_options_t, _magic),
  594. _option_abbrevs,
  595. _option_vars,
  596. (validate_fn_t)options_validate,
  597. options_description,
  598. NULL
  599. };
  600. /** Magic value for or_state_t. */
  601. #define OR_STATE_MAGIC 0x57A73f57
  602. /** "Extra" variable in the state that receives lines we can't parse. This
  603. * lets us preserve options from versions of Tor newer than us. */
  604. static config_var_t state_extra_var = {
  605. "__extra", CONFIG_TYPE_LINELIST, STRUCT_OFFSET(or_state_t, ExtraLines), NULL
  606. };
  607. /** Configuration format for or_state_t. */
  608. static config_format_t state_format = {
  609. sizeof(or_state_t),
  610. OR_STATE_MAGIC,
  611. STRUCT_OFFSET(or_state_t, _magic),
  612. _state_abbrevs,
  613. _state_vars,
  614. (validate_fn_t)or_state_validate,
  615. state_description,
  616. &state_extra_var,
  617. };
  618. /*
  619. * Functions to read and write the global options pointer.
  620. */
  621. /** Command-line and config-file options. */
  622. static or_options_t *global_options = NULL;
  623. /** Name of most recently read torrc file. */
  624. static char *torrc_fname = NULL;
  625. /** Persistent serialized state. */
  626. static or_state_t *global_state = NULL;
  627. /** Allocate an empty configuration object of a given format type. */
  628. static void *
  629. config_alloc(config_format_t *fmt)
  630. {
  631. void *opts = tor_malloc_zero(fmt->size);
  632. *(uint32_t*)STRUCT_VAR_P(opts, fmt->magic_offset) = fmt->magic;
  633. CHECK(fmt, opts);
  634. return opts;
  635. }
  636. /** Return the currently configured options. */
  637. or_options_t *
  638. get_options(void)
  639. {
  640. tor_assert(global_options);
  641. return global_options;
  642. }
  643. /** Change the current global options to contain <b>new_val</b> instead of
  644. * their current value; take action based on the new value; free the old value
  645. * as necessary.
  646. */
  647. int
  648. set_options(or_options_t *new_val, char **msg)
  649. {
  650. or_options_t *old_options = global_options;
  651. global_options = new_val;
  652. /* Note that we pass the *old* options below, for comparison. It
  653. * pulls the new options directly out of global_options. */
  654. if (options_act_reversible(old_options, msg)<0) {
  655. tor_assert(*msg);
  656. global_options = old_options;
  657. return -1;
  658. }
  659. if (options_act(old_options) < 0) { /* acting on the options failed. die. */
  660. log_err(LD_BUG,
  661. "Acting on config options left us in a broken state. Dying.");
  662. exit(1);
  663. }
  664. if (old_options)
  665. config_free(&options_format, old_options);
  666. return 0;
  667. }
  668. extern const char tor_svn_revision[]; /* from tor_main.c */
  669. static char *_version = NULL;
  670. /** Return the current Tor version, possibly */
  671. const char *
  672. get_version(void)
  673. {
  674. if (_version == NULL) {
  675. if (strlen(tor_svn_revision)) {
  676. size_t len = strlen(VERSION)+strlen(tor_svn_revision)+8;
  677. _version = tor_malloc(len);
  678. tor_snprintf(_version, len, "%s (r%s)", VERSION, tor_svn_revision);
  679. } else {
  680. _version = tor_strdup(VERSION);
  681. }
  682. }
  683. return _version;
  684. }
  685. /** Release all memory and resources held by global configuration structures.
  686. */
  687. void
  688. config_free_all(void)
  689. {
  690. if (global_options) {
  691. config_free(&options_format, global_options);
  692. global_options = NULL;
  693. }
  694. if (global_state) {
  695. config_free(&state_format, global_state);
  696. global_state = NULL;
  697. }
  698. tor_free(torrc_fname);
  699. tor_free(_version);
  700. }
  701. /** If options->SafeLogging is on, return a not very useful string,
  702. * else return address.
  703. */
  704. const char *
  705. safe_str(const char *address)
  706. {
  707. if (!address) { /* XXX020 eventually turn this into an assert */
  708. log_warn(LD_BUG, "safe_str() called with NULL address.");
  709. return "EMPTY";
  710. }
  711. if (get_options()->SafeLogging)
  712. return "[scrubbed]";
  713. else
  714. return address;
  715. }
  716. /** Equivalent to escaped(safe_str(address)). See reentrancy note on
  717. * escaped(): don't use this outside the main thread, or twice in the same
  718. * log statement. */
  719. const char *
  720. escaped_safe_str(const char *address)
  721. {
  722. if (get_options()->SafeLogging)
  723. return "[scrubbed]";
  724. else
  725. return escaped(address);
  726. }
  727. /** Add the default directory servers directly into the trusted dir list. */
  728. static void
  729. add_default_trusted_dirservers(void)
  730. {
  731. int i;
  732. const char *dirservers[] = {
  733. /* eventually we should mark moria1 as "v1only" */
  734. "moria1 v1 orport=9001 128.31.0.34:9031 "
  735. "FFCB 46DB 1339 DA84 674C 70D7 CB58 6434 C437 0441",
  736. "moria2 v1 orport=9002 128.31.0.34:9032 "
  737. "719B E45D E224 B607 C537 07D0 E214 3E2D 423E 74CF",
  738. "tor26 v1 orport=443 86.59.21.38:80 "
  739. "847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D",
  740. "lefkada orport=443 140.247.60.64:80 "
  741. "38D4 F5FC F7B1 0232 28B8 95EA 56ED E7D5 CCDC AF32",
  742. "dizum 194.109.206.212:80 "
  743. "7EA6 EAD6 FD83 083C 538F 4403 8BBF A077 587D D755",
  744. NULL
  745. };
  746. for (i=0; dirservers[i]; i++)
  747. parse_dir_server_line(dirservers[i], 0);
  748. }
  749. /** Fetch the active option list, and take actions based on it. All of the
  750. * things we do should survive being done repeatedly. If present,
  751. * <b>old_options</b> contains the previous value of the options.
  752. *
  753. * Return 0 if all goes well, return -1 if things went badly.
  754. */
  755. static int
  756. options_act_reversible(or_options_t *old_options, char **msg)
  757. {
  758. smartlist_t *new_listeners = smartlist_create();
  759. smartlist_t *replaced_listeners = smartlist_create();
  760. static int libevent_initialized = 0;
  761. or_options_t *options = get_options();
  762. int running_tor = options->command == CMD_RUN_TOR;
  763. int set_conn_limit = 0;
  764. int r = -1;
  765. int logs_marked = 0;
  766. /* Daemonize _first_, since we only want to open most of this stuff in
  767. * the subprocess. */
  768. if (running_tor && options->RunAsDaemon) {
  769. /* No need to roll back, since you can't change the value. */
  770. start_daemon();
  771. }
  772. #ifndef HAVE_SYS_UN_H
  773. if (options->ControlSocket) {
  774. *msg = tor_strdup("Unix domain sockets (ControlSocket) not supported"
  775. " on this OS/with this build.");
  776. goto rollback;
  777. }
  778. #endif
  779. if (running_tor) {
  780. /* We need to set the connection limit before we can open the listeners. */
  781. options->_ConnLimit =
  782. set_max_file_descriptors((unsigned)options->ConnLimit, MAXCONNECTIONS);
  783. if (options->_ConnLimit < 0) {
  784. *msg = tor_strdup("Problem with ConnLimit value. See logs for details.");
  785. goto rollback;
  786. }
  787. set_conn_limit = 1;
  788. /* Set up libevent. (We need to do this before we can register the
  789. * listeners as listeners.) */
  790. if (running_tor && !libevent_initialized) {
  791. init_libevent();
  792. libevent_initialized = 1;
  793. }
  794. /* Launch the listeners. (We do this before we setuid, so we can bind to
  795. * ports under 1024.) */
  796. if (retry_all_listeners(replaced_listeners, new_listeners) < 0) {
  797. *msg = tor_strdup("Failed to bind one of the listener ports.");
  798. goto rollback;
  799. }
  800. }
  801. /* Setuid/setgid as appropriate */
  802. if (options->User || options->Group) {
  803. if (switch_id(options->User, options->Group) != 0) {
  804. /* No need to roll back, since you can't change the value. */
  805. *msg = tor_strdup("Problem with User or Group value. "
  806. "See logs for details.");
  807. goto done;
  808. }
  809. }
  810. /* Ensure data directory is private; create if possible. */
  811. if (check_private_dir(options->DataDirectory, CPD_CREATE)<0) {
  812. char buf[1024];
  813. int tmp = tor_snprintf(buf, sizeof(buf),
  814. "Couldn't access/create private data directory \"%s\"",
  815. options->DataDirectory);
  816. *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
  817. goto done;
  818. /* No need to roll back, since you can't change the value. */
  819. }
  820. /* Bail out at this point if we're not going to be a client or server:
  821. * we don't run Tor itself. */
  822. if (!running_tor)
  823. goto commit;
  824. mark_logs_temp(); /* Close current logs once new logs are open. */
  825. logs_marked = 1;
  826. if (options_init_logs(options, 0)<0) { /* Configure the log(s) */
  827. *msg = tor_strdup("Failed to init Log options. See logs for details.");
  828. goto rollback;
  829. }
  830. commit:
  831. r = 0;
  832. if (logs_marked) {
  833. close_temp_logs();
  834. add_callback_log(LOG_ERR, LOG_ERR, control_event_logmsg);
  835. control_adjust_event_log_severity();
  836. }
  837. SMARTLIST_FOREACH(replaced_listeners, connection_t *, conn,
  838. {
  839. log_notice(LD_NET, "Closing old %s on %s:%d",
  840. conn_type_to_string(conn->type), conn->address, conn->port);
  841. connection_close_immediate(conn);
  842. connection_mark_for_close(conn);
  843. });
  844. goto done;
  845. rollback:
  846. r = -1;
  847. tor_assert(*msg);
  848. if (logs_marked) {
  849. rollback_log_changes();
  850. control_adjust_event_log_severity();
  851. }
  852. if (set_conn_limit && old_options)
  853. set_max_file_descriptors((unsigned)old_options->ConnLimit,MAXCONNECTIONS);
  854. SMARTLIST_FOREACH(new_listeners, connection_t *, conn,
  855. {
  856. log_notice(LD_NET, "Closing partially-constructed listener %s on %s:%d",
  857. conn_type_to_string(conn->type), conn->address, conn->port);
  858. connection_close_immediate(conn);
  859. connection_mark_for_close(conn);
  860. });
  861. done:
  862. smartlist_free(new_listeners);
  863. smartlist_free(replaced_listeners);
  864. return r;
  865. }
  866. /** Fetch the active option list, and take actions based on it. All of the
  867. * things we do should survive being done repeatedly. If present,
  868. * <b>old_options</b> contains the previous value of the options.
  869. *
  870. * Return 0 if all goes well, return -1 if it's time to die.
  871. *
  872. * Note: We haven't moved all the "act on new configuration" logic
  873. * here yet. Some is still in do_hup() and other places.
  874. */
  875. static int
  876. options_act(or_options_t *old_options)
  877. {
  878. config_line_t *cl;
  879. char *fn;
  880. size_t len;
  881. or_options_t *options = get_options();
  882. int running_tor = options->command == CMD_RUN_TOR;
  883. char *msg;
  884. clear_trusted_dir_servers();
  885. if (options->DirServers) {
  886. for (cl = options->DirServers; cl; cl = cl->next) {
  887. if (parse_dir_server_line(cl->value, 0)<0) {
  888. log_warn(LD_BUG,
  889. "Previously validated DirServer line could not be added!");
  890. return -1;
  891. }
  892. }
  893. } else {
  894. add_default_trusted_dirservers();
  895. }
  896. clear_bridge_list();
  897. if (options->Bridges) {
  898. for (cl = options->Bridges; cl; cl = cl->next) {
  899. if (parse_bridge_line(cl->value, 0)<0) {
  900. log_warn(LD_BUG,
  901. "Previously validated Bridge line could not be added!");
  902. return -1;
  903. }
  904. }
  905. }
  906. if (running_tor && rend_config_services(options, 0)<0) {
  907. log_warn(LD_BUG,
  908. "Previously validated hidden services line could not be added!");
  909. return -1;
  910. }
  911. if (running_tor) {
  912. len = strlen(options->DataDirectory)+32;
  913. fn = tor_malloc(len);
  914. tor_snprintf(fn, len, "%s"PATH_SEPARATOR"cached-status",
  915. options->DataDirectory);
  916. if (check_private_dir(fn, CPD_CREATE) != 0) {
  917. log_warn(LD_CONFIG,
  918. "Couldn't access/create private data directory \"%s\"", fn);
  919. tor_free(fn);
  920. return -1;
  921. }
  922. tor_free(fn);
  923. }
  924. /* Load state */
  925. if (! global_state)
  926. if (or_state_load())
  927. return -1;
  928. /* Bail out at this point if we're not going to be a client or server:
  929. * we want to not fork, and to log stuff to stderr. */
  930. if (options->command != CMD_RUN_TOR)
  931. return 0;
  932. {
  933. smartlist_t *sl = smartlist_create();
  934. char *errmsg = NULL;
  935. for (cl = options->RedirectExit; cl; cl = cl->next) {
  936. if (parse_redirect_line(sl, cl, &errmsg)<0) {
  937. log_warn(LD_CONFIG, "%s", errmsg);
  938. tor_free(errmsg);
  939. return -1;
  940. }
  941. }
  942. set_exit_redirects(sl);
  943. }
  944. /* Finish backgrounding the process */
  945. if (running_tor && options->RunAsDaemon) {
  946. /* We may be calling this for the n'th time (on SIGHUP), but it's safe. */
  947. finish_daemon(options->DataDirectory);
  948. }
  949. /* Write our pid to the pid file. If we do not have write permissions we
  950. * will log a warning */
  951. if (running_tor && options->PidFile)
  952. write_pidfile(options->PidFile);
  953. /* Register addressmap directives */
  954. config_register_addressmaps(options);
  955. parse_virtual_addr_network(options->VirtualAddrNetwork, 0, &msg);
  956. /* Update address policies. */
  957. policies_parse_from_options(options);
  958. init_cookie_authentication(options->CookieAuthentication);
  959. /* reload keys as needed for rendezvous services. */
  960. if (rend_service_load_keys()<0) {
  961. log_warn(LD_GENERAL,"Error loading rendezvous service keys");
  962. return -1;
  963. }
  964. /* Set up accounting */
  965. if (accounting_parse_options(options, 0)<0) {
  966. log_warn(LD_CONFIG,"Error in accounting options");
  967. return -1;
  968. }
  969. if (accounting_is_enabled(options))
  970. configure_accounting(time(NULL));
  971. if (!running_tor)
  972. return 0;
  973. /* Check for transitions that need action. */
  974. if (old_options) {
  975. if (options->UseEntryGuards && !old_options->UseEntryGuards) {
  976. log_info(LD_CIRC,
  977. "Switching to entry guards; abandoning previous circuits");
  978. circuit_mark_all_unused_circs();
  979. circuit_expire_all_dirty_circs();
  980. }
  981. if (options_transition_affects_workers(old_options, options)) {
  982. log_info(LD_GENERAL,
  983. "Worker-related options changed. Rotating workers.");
  984. if (server_mode(options) && !server_mode(old_options)) {
  985. if (init_keys() < 0) {
  986. log_warn(LD_BUG,"Error initializing keys; exiting");
  987. return -1;
  988. }
  989. ip_address_changed(0);
  990. if (has_completed_circuit || !any_predicted_circuits(time(NULL)))
  991. inform_testing_reachability();
  992. }
  993. cpuworkers_rotate();
  994. if (dns_reset())
  995. return -1;
  996. } else {
  997. if (dns_reset())
  998. return -1;
  999. }
  1000. /* XXXX020 init_keys() again if v3authoritativedir is newly set. */
  1001. }
  1002. /* Check if we need to parse and add the EntryNodes config option. */
  1003. if (options->EntryNodes &&
  1004. (!old_options ||
  1005. !opt_streq(old_options->EntryNodes, options->EntryNodes)))
  1006. entry_nodes_should_be_added();
  1007. /* Since our options changed, we might need to regenerate and upload our
  1008. * server descriptor.
  1009. */
  1010. if (!old_options ||
  1011. options_transition_affects_descriptor(old_options, options))
  1012. mark_my_descriptor_dirty();
  1013. return 0;
  1014. }
  1015. /*
  1016. * Functions to parse config options
  1017. */
  1018. /** If <b>option</b> is an official abbreviation for a longer option,
  1019. * return the longer option. Otherwise return <b>option</b>.
  1020. * If <b>command_line</b> is set, apply all abbreviations. Otherwise, only
  1021. * apply abbreviations that work for the config file and the command line.
  1022. * If <b>warn_obsolete</b> is set, warn about deprecated names. */
  1023. static const char *
  1024. expand_abbrev(config_format_t *fmt, const char *option, int command_line,
  1025. int warn_obsolete)
  1026. {
  1027. int i;
  1028. if (! fmt->abbrevs)
  1029. return option;
  1030. for (i=0; fmt->abbrevs[i].abbreviated; ++i) {
  1031. /* Abbreviations are casei. */
  1032. if (!strcasecmp(option,fmt->abbrevs[i].abbreviated) &&
  1033. (command_line || !fmt->abbrevs[i].commandline_only)) {
  1034. if (warn_obsolete && fmt->abbrevs[i].warn) {
  1035. log_warn(LD_CONFIG,
  1036. "The configuration option '%s' is deprecated; "
  1037. "use '%s' instead.",
  1038. fmt->abbrevs[i].abbreviated,
  1039. fmt->abbrevs[i].full);
  1040. }
  1041. return fmt->abbrevs[i].full;
  1042. }
  1043. }
  1044. return option;
  1045. }
  1046. /** Helper: Read a list of configuration options from the command line.
  1047. * If successful, put them in *<b>result</b> and return 0, and return
  1048. * -1 and leave *<b>result</b> alone. */
  1049. static int
  1050. config_get_commandlines(int argc, char **argv, config_line_t **result)
  1051. {
  1052. config_line_t *front = NULL;
  1053. config_line_t **new = &front;
  1054. char *s;
  1055. int i = 1;
  1056. while (i < argc) {
  1057. if (!strcmp(argv[i],"-f") ||
  1058. !strcmp(argv[i],"--hash-password")) {
  1059. i += 2; /* command-line option with argument. ignore them. */
  1060. continue;
  1061. } else if (!strcmp(argv[i],"--list-fingerprint") ||
  1062. !strcmp(argv[i],"--verify-config") ||
  1063. !strcmp(argv[i],"--ignore-missing-torrc")) {
  1064. i += 1; /* command-line option. ignore it. */
  1065. continue;
  1066. } else if (!strcmp(argv[i],"--nt-service") ||
  1067. !strcmp(argv[i],"-nt-service")) {
  1068. i += 1;
  1069. continue;
  1070. }
  1071. if (i == argc-1) {
  1072. log_warn(LD_CONFIG,"Command-line option '%s' with no value. Failing.",
  1073. argv[i]);
  1074. config_free_lines(front);
  1075. return -1;
  1076. }
  1077. *new = tor_malloc_zero(sizeof(config_line_t));
  1078. s = argv[i];
  1079. while (*s == '-')
  1080. s++;
  1081. (*new)->key = tor_strdup(expand_abbrev(&options_format, s, 1, 1));
  1082. (*new)->value = tor_strdup(argv[i+1]);
  1083. (*new)->next = NULL;
  1084. log(LOG_DEBUG, LD_CONFIG, "Commandline: parsed keyword '%s', value '%s'",
  1085. (*new)->key, (*new)->value);
  1086. new = &((*new)->next);
  1087. i += 2;
  1088. }
  1089. *result = front;
  1090. return 0;
  1091. }
  1092. /** Helper: allocate a new configuration option mapping 'key' to 'val',
  1093. * append it to *<b>lst</b>. */
  1094. static void
  1095. config_line_append(config_line_t **lst,
  1096. const char *key,
  1097. const char *val)
  1098. {
  1099. config_line_t *newline;
  1100. newline = tor_malloc(sizeof(config_line_t));
  1101. newline->key = tor_strdup(key);
  1102. newline->value = tor_strdup(val);
  1103. newline->next = NULL;
  1104. while (*lst)
  1105. lst = &((*lst)->next);
  1106. (*lst) = newline;
  1107. }
  1108. /** Helper: parse the config string and strdup into key/value
  1109. * strings. Set *result to the list, or NULL if parsing the string
  1110. * failed. Return 0 on success, -1 on failure. Warn and ignore any
  1111. * misformatted lines. Modifies the contents of <b>string</b>. */
  1112. int
  1113. config_get_lines(char *string, config_line_t **result)
  1114. {
  1115. config_line_t *list = NULL, **next;
  1116. char *k, *v;
  1117. next = &list;
  1118. do {
  1119. string = parse_line_from_str(string, &k, &v);
  1120. if (!string) {
  1121. config_free_lines(list);
  1122. return -1;
  1123. }
  1124. if (k && v) {
  1125. /* This list can get long, so we keep a pointer to the end of it
  1126. * rather than using config_line_append over and over and getting n^2
  1127. * performance. This is the only really long list. */
  1128. *next = tor_malloc(sizeof(config_line_t));
  1129. (*next)->key = tor_strdup(k);
  1130. (*next)->value = tor_strdup(v);
  1131. (*next)->next = NULL;
  1132. next = &((*next)->next);
  1133. }
  1134. } while (*string);
  1135. *result = list;
  1136. return 0;
  1137. }
  1138. /**
  1139. * Free all the configuration lines on the linked list <b>front</b>.
  1140. */
  1141. void
  1142. config_free_lines(config_line_t *front)
  1143. {
  1144. config_line_t *tmp;
  1145. while (front) {
  1146. tmp = front;
  1147. front = tmp->next;
  1148. tor_free(tmp->key);
  1149. tor_free(tmp->value);
  1150. tor_free(tmp);
  1151. }
  1152. }
  1153. /** Return the description for a given configuration variable, or NULL if no
  1154. * description exists. */
  1155. static const char *
  1156. config_find_description(config_format_t *fmt, const char *name)
  1157. {
  1158. int i;
  1159. for (i=0; fmt->descriptions[i].name; ++i) {
  1160. if (!strcasecmp(name, fmt->descriptions[i].name))
  1161. return fmt->descriptions[i].description;
  1162. }
  1163. return NULL;
  1164. }
  1165. /** If <b>key</b> is a configuration option, return the corresponding
  1166. * config_var_t. Otherwise, if <b>key</b> is a non-standard abbreviation,
  1167. * warn, and return the corresponding config_var_t. Otherwise return NULL.
  1168. */
  1169. static config_var_t *
  1170. config_find_option(config_format_t *fmt, const char *key)
  1171. {
  1172. int i;
  1173. size_t keylen = strlen(key);
  1174. if (!keylen)
  1175. return NULL; /* if they say "--" on the commandline, it's not an option */
  1176. /* First, check for an exact (case-insensitive) match */
  1177. for (i=0; fmt->vars[i].name; ++i) {
  1178. if (!strcasecmp(key, fmt->vars[i].name)) {
  1179. return &fmt->vars[i];
  1180. }
  1181. }
  1182. /* If none, check for an abbreviated match */
  1183. for (i=0; fmt->vars[i].name; ++i) {
  1184. if (!strncasecmp(key, fmt->vars[i].name, keylen)) {
  1185. log_warn(LD_CONFIG, "The abbreviation '%s' is deprecated. "
  1186. "Please use '%s' instead",
  1187. key, fmt->vars[i].name);
  1188. return &fmt->vars[i];
  1189. }
  1190. }
  1191. /* Okay, unrecognized option */
  1192. return NULL;
  1193. }
  1194. /*
  1195. * Functions to assign config options.
  1196. */
  1197. /** <b>c</b>-\>key is known to be a real key. Update <b>options</b>
  1198. * with <b>c</b>-\>value and return 0, or return -1 if bad value.
  1199. *
  1200. * Called from config_assign_line() and option_reset().
  1201. */
  1202. static int
  1203. config_assign_value(config_format_t *fmt, or_options_t *options,
  1204. config_line_t *c, char **msg)
  1205. {
  1206. int i, r, ok;
  1207. char buf[1024];
  1208. config_var_t *var;
  1209. void *lvalue;
  1210. CHECK(fmt, options);
  1211. var = config_find_option(fmt, c->key);
  1212. tor_assert(var);
  1213. lvalue = STRUCT_VAR_P(options, var->var_offset);
  1214. switch (var->type) {
  1215. case CONFIG_TYPE_UINT:
  1216. i = tor_parse_long(c->value, 10, 0, INT_MAX, &ok, NULL);
  1217. if (!ok) {
  1218. r = tor_snprintf(buf, sizeof(buf),
  1219. "Int keyword '%s %s' is malformed or out of bounds.",
  1220. c->key, c->value);
  1221. *msg = tor_strdup(r >= 0 ? buf : "internal error");
  1222. return -1;
  1223. }
  1224. *(int *)lvalue = i;
  1225. break;
  1226. case CONFIG_TYPE_INTERVAL: {
  1227. i = config_parse_interval(c->value, &ok);
  1228. if (!ok) {
  1229. r = tor_snprintf(buf, sizeof(buf),
  1230. "Interval '%s %s' is malformed or out of bounds.",
  1231. c->key, c->value);
  1232. *msg = tor_strdup(r >= 0 ? buf : "internal error");
  1233. return -1;
  1234. }
  1235. *(int *)lvalue = i;
  1236. break;
  1237. }
  1238. case CONFIG_TYPE_MEMUNIT: {
  1239. uint64_t u64 = config_parse_memunit(c->value, &ok);
  1240. if (!ok) {
  1241. r = tor_snprintf(buf, sizeof(buf),
  1242. "Value '%s %s' is malformed or out of bounds.",
  1243. c->key, c->value);
  1244. *msg = tor_strdup(r >= 0 ? buf : "internal error");
  1245. return -1;
  1246. }
  1247. *(uint64_t *)lvalue = u64;
  1248. break;
  1249. }
  1250. case CONFIG_TYPE_BOOL:
  1251. i = tor_parse_long(c->value, 10, 0, 1, &ok, NULL);
  1252. if (!ok) {
  1253. r = tor_snprintf(buf, sizeof(buf),
  1254. "Boolean '%s %s' expects 0 or 1.",
  1255. c->key, c->value);
  1256. *msg = tor_strdup(r >= 0 ? buf : "internal error");
  1257. return -1;
  1258. }
  1259. *(int *)lvalue = i;
  1260. break;
  1261. case CONFIG_TYPE_STRING:
  1262. tor_free(*(char **)lvalue);
  1263. *(char **)lvalue = tor_strdup(c->value);
  1264. break;
  1265. case CONFIG_TYPE_DOUBLE:
  1266. *(double *)lvalue = atof(c->value);
  1267. break;
  1268. case CONFIG_TYPE_ISOTIME:
  1269. if (parse_iso_time(c->value, (time_t *)lvalue)) {
  1270. r = tor_snprintf(buf, sizeof(buf),
  1271. "Invalid time '%s' for keyword '%s'", c->value, c->key);
  1272. *msg = tor_strdup(r >= 0 ? buf : "internal error");
  1273. return -1;
  1274. }
  1275. break;
  1276. case CONFIG_TYPE_CSV:
  1277. if (*(smartlist_t**)lvalue) {
  1278. SMARTLIST_FOREACH(*(smartlist_t**)lvalue, char *, cp, tor_free(cp));
  1279. smartlist_clear(*(smartlist_t**)lvalue);
  1280. } else {
  1281. *(smartlist_t**)lvalue = smartlist_create();
  1282. }
  1283. smartlist_split_string(*(smartlist_t**)lvalue, c->value, ",",
  1284. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1285. break;
  1286. case CONFIG_TYPE_LINELIST:
  1287. case CONFIG_TYPE_LINELIST_S:
  1288. config_line_append((config_line_t**)lvalue, c->key, c->value);
  1289. break;
  1290. case CONFIG_TYPE_OBSOLETE:
  1291. log_warn(LD_CONFIG, "Skipping obsolete configuration option '%s'", c->key);
  1292. break;
  1293. case CONFIG_TYPE_LINELIST_V:
  1294. r = tor_snprintf(buf, sizeof(buf),
  1295. "You may not provide a value for virtual option '%s'", c->key);
  1296. *msg = tor_strdup(r >= 0 ? buf : "internal error");
  1297. return -1;
  1298. default:
  1299. tor_assert(0);
  1300. break;
  1301. }
  1302. return 0;
  1303. }
  1304. /** If <b>c</b> is a syntactically valid configuration line, update
  1305. * <b>options</b> with its value and return 0. Otherwise return -1 for bad
  1306. * key, -2 for bad value.
  1307. *
  1308. * If <b>clear_first</b> is set, clear the value first. Then if
  1309. * <b>use_defaults</b> is set, set the value to the default.
  1310. *
  1311. * Called from config_assign().
  1312. */
  1313. static int
  1314. config_assign_line(config_format_t *fmt, or_options_t *options,
  1315. config_line_t *c, int use_defaults,
  1316. int clear_first, char **msg)
  1317. {
  1318. config_var_t *var;
  1319. CHECK(fmt, options);
  1320. var = config_find_option(fmt, c->key);
  1321. if (!var) {
  1322. if (fmt->extra) {
  1323. void *lvalue = STRUCT_VAR_P(options, fmt->extra->var_offset);
  1324. log_info(LD_CONFIG,
  1325. "Found unrecognized option '%s'; saving it.", c->key);
  1326. config_line_append((config_line_t**)lvalue, c->key, c->value);
  1327. return 0;
  1328. } else {
  1329. char buf[1024];
  1330. int tmp = tor_snprintf(buf, sizeof(buf),
  1331. "Unknown option '%s'. Failing.", c->key);
  1332. *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
  1333. return -1;
  1334. }
  1335. }
  1336. /* Put keyword into canonical case. */
  1337. if (strcmp(var->name, c->key)) {
  1338. tor_free(c->key);
  1339. c->key = tor_strdup(var->name);
  1340. }
  1341. if (!strlen(c->value)) {
  1342. /* reset or clear it, then return */
  1343. if (!clear_first) {
  1344. if (var->type == CONFIG_TYPE_LINELIST ||
  1345. var->type == CONFIG_TYPE_LINELIST_S) {
  1346. /* We got an empty linelist from the torrc or commandline.
  1347. As a special case, call this an error. Warn and ignore. */
  1348. log_warn(LD_CONFIG,
  1349. "Linelist option '%s' has no value. Skipping.", c->key);
  1350. } else { /* not already cleared */
  1351. option_reset(fmt, options, var, use_defaults);
  1352. }
  1353. }
  1354. return 0;
  1355. }
  1356. if (config_assign_value(fmt, options, c, msg) < 0)
  1357. return -2;
  1358. return 0;
  1359. }
  1360. /** Restore the option named <b>key</b> in options to its default value.
  1361. * Called from config_assign(). */
  1362. static void
  1363. config_reset_line(config_format_t *fmt, or_options_t *options,
  1364. const char *key, int use_defaults)
  1365. {
  1366. config_var_t *var;
  1367. CHECK(fmt, options);
  1368. var = config_find_option(fmt, key);
  1369. if (!var)
  1370. return; /* give error on next pass. */
  1371. option_reset(fmt, options, var, use_defaults);
  1372. }
  1373. /** Return true iff key is a valid configuration option. */
  1374. int
  1375. option_is_recognized(const char *key)
  1376. {
  1377. config_var_t *var = config_find_option(&options_format, key);
  1378. return (var != NULL);
  1379. }
  1380. /** Return the canonical name of a configuration option. */
  1381. const char *
  1382. option_get_canonical_name(const char *key)
  1383. {
  1384. config_var_t *var = config_find_option(&options_format, key);
  1385. return var->name;
  1386. }
  1387. /** Return a canonicalized list of the options assigned for key.
  1388. */
  1389. config_line_t *
  1390. option_get_assignment(or_options_t *options, const char *key)
  1391. {
  1392. return get_assigned_option(&options_format, options, key);
  1393. }
  1394. /** Return a newly allocated deep copy of the lines in <b>inp</b>. */
  1395. static config_line_t *
  1396. config_lines_dup(const config_line_t *inp)
  1397. {
  1398. config_line_t *result = NULL;
  1399. config_line_t **next_out = &result;
  1400. while (inp) {
  1401. *next_out = tor_malloc(sizeof(config_line_t));
  1402. (*next_out)->key = tor_strdup(inp->key);
  1403. (*next_out)->value = tor_strdup(inp->value);
  1404. inp = inp->next;
  1405. next_out = &((*next_out)->next);
  1406. }
  1407. (*next_out) = NULL;
  1408. return result;
  1409. }
  1410. /** Return newly allocated line or lines corresponding to <b>key</b> in the
  1411. * configuration <b>options</b>. Return NULL if no such key exists. */
  1412. static config_line_t *
  1413. get_assigned_option(config_format_t *fmt, or_options_t *options,
  1414. const char *key)
  1415. /* XXXX argument is options, but fmt is provided. Inconsistent. */
  1416. {
  1417. config_var_t *var;
  1418. const void *value;
  1419. char buf[32];
  1420. config_line_t *result;
  1421. tor_assert(options && key);
  1422. CHECK(fmt, options);
  1423. var = config_find_option(fmt, key);
  1424. if (!var) {
  1425. log_warn(LD_CONFIG, "Unknown option '%s'. Failing.", key);
  1426. return NULL;
  1427. }
  1428. value = STRUCT_VAR_P(options, var->var_offset);
  1429. result = tor_malloc_zero(sizeof(config_line_t));
  1430. result->key = tor_strdup(var->name);
  1431. switch (var->type)
  1432. {
  1433. case CONFIG_TYPE_STRING:
  1434. if (*(char**)value) {
  1435. result->value = tor_strdup(*(char**)value);
  1436. } else {
  1437. tor_free(result->key);
  1438. tor_free(result);
  1439. return NULL;
  1440. }
  1441. break;
  1442. case CONFIG_TYPE_ISOTIME:
  1443. if (*(time_t*)value) {
  1444. result->value = tor_malloc(ISO_TIME_LEN+1);
  1445. format_iso_time(result->value, *(time_t*)value);
  1446. } else {
  1447. tor_free(result->key);
  1448. tor_free(result);
  1449. }
  1450. break;
  1451. case CONFIG_TYPE_INTERVAL:
  1452. case CONFIG_TYPE_UINT:
  1453. /* This means every or_options_t uint or bool element
  1454. * needs to be an int. Not, say, a uint16_t or char. */
  1455. tor_snprintf(buf, sizeof(buf), "%d", *(int*)value);
  1456. result->value = tor_strdup(buf);
  1457. break;
  1458. case CONFIG_TYPE_MEMUNIT:
  1459. tor_snprintf(buf, sizeof(buf), U64_FORMAT,
  1460. U64_PRINTF_ARG(*(uint64_t*)value));
  1461. result->value = tor_strdup(buf);
  1462. break;
  1463. case CONFIG_TYPE_DOUBLE:
  1464. tor_snprintf(buf, sizeof(buf), "%f", *(double*)value);
  1465. result->value = tor_strdup(buf);
  1466. break;
  1467. case CONFIG_TYPE_BOOL:
  1468. result->value = tor_strdup(*(int*)value ? "1" : "0");
  1469. break;
  1470. case CONFIG_TYPE_CSV:
  1471. if (*(smartlist_t**)value)
  1472. result->value =
  1473. smartlist_join_strings(*(smartlist_t**)value, ",", 0, NULL);
  1474. else
  1475. result->value = tor_strdup("");
  1476. break;
  1477. case CONFIG_TYPE_OBSOLETE:
  1478. log_warn(LD_CONFIG,
  1479. "You asked me for the value of an obsolete config option '%s'.",
  1480. key);
  1481. tor_free(result->key);
  1482. tor_free(result);
  1483. return NULL;
  1484. case CONFIG_TYPE_LINELIST_S:
  1485. log_warn(LD_CONFIG,
  1486. "Can't return context-sensitive '%s' on its own", key);
  1487. tor_free(result->key);
  1488. tor_free(result);
  1489. return NULL;
  1490. case CONFIG_TYPE_LINELIST:
  1491. case CONFIG_TYPE_LINELIST_V:
  1492. tor_free(result->key);
  1493. tor_free(result);
  1494. return config_lines_dup(*(const config_line_t**)value);
  1495. default:
  1496. tor_free(result->key);
  1497. tor_free(result);
  1498. log_warn(LD_BUG,"Unknown type %d for known key '%s'",
  1499. var->type, key);
  1500. return NULL;
  1501. }
  1502. return result;
  1503. }
  1504. /** Iterate through the linked list of requested options <b>list</b>.
  1505. * For each item, convert as appropriate and assign to <b>options</b>.
  1506. * If an item is unrecognized, set *msg and return -1 immediately,
  1507. * else return 0 for success.
  1508. *
  1509. * If <b>clear_first</b>, interpret config options as replacing (not
  1510. * extending) their previous values. If <b>clear_first</b> is set,
  1511. * then <b>use_defaults</b> to decide if you set to defaults after
  1512. * clearing, or make the value 0 or NULL.
  1513. *
  1514. * Here are the use cases:
  1515. * 1. A non-empty AllowInvalid line in your torrc. Appends to current
  1516. * if linelist, replaces current if csv.
  1517. * 2. An empty AllowInvalid line in your torrc. Should clear it.
  1518. * 3. "RESETCONF AllowInvalid" sets it to default.
  1519. * 4. "SETCONF AllowInvalid" makes it NULL.
  1520. * 5. "SETCONF AllowInvalid=foo" clears it and sets it to "foo".
  1521. *
  1522. * Use_defaults Clear_first
  1523. * 0 0 "append"
  1524. * 1 0 undefined, don't use
  1525. * 0 1 "set to null first"
  1526. * 1 1 "set to defaults first"
  1527. * Return 0 on success, -1 on bad key, -2 on bad value.
  1528. *
  1529. * As an additional special case, if a LINELIST config option has
  1530. * no value and clear_first is 0, then warn and ignore it.
  1531. */
  1532. /*
  1533. There are three call cases for config_assign() currently.
  1534. Case one: Torrc entry
  1535. options_init_from_torrc() calls config_assign(0, 0)
  1536. calls config_assign_line(0, 0).
  1537. if value is empty, calls option_reset(0) and returns.
  1538. calls config_assign_value(), appends.
  1539. Case two: setconf
  1540. options_trial_assign() calls config_assign(0, 1)
  1541. calls config_reset_line(0)
  1542. calls option_reset(0)
  1543. calls option_clear().
  1544. calls config_assign_line(0, 1).
  1545. if value is empty, returns.
  1546. calls config_assign_value(), appends.
  1547. Case three: resetconf
  1548. options_trial_assign() calls config_assign(1, 1)
  1549. calls config_reset_line(1)
  1550. calls option_reset(1)
  1551. calls option_clear().
  1552. calls config_assign_value(default)
  1553. calls config_assign_line(1, 1).
  1554. returns.
  1555. */
  1556. static int
  1557. config_assign(config_format_t *fmt, void *options, config_line_t *list,
  1558. int use_defaults, int clear_first, char **msg)
  1559. {
  1560. config_line_t *p;
  1561. CHECK(fmt, options);
  1562. /* pass 1: normalize keys */
  1563. for (p = list; p; p = p->next) {
  1564. const char *full = expand_abbrev(fmt, p->key, 0, 1);
  1565. if (strcmp(full,p->key)) {
  1566. tor_free(p->key);
  1567. p->key = tor_strdup(full);
  1568. }
  1569. }
  1570. /* pass 2: if we're reading from a resetting source, clear all
  1571. * mentioned config options, and maybe set to their defaults. */
  1572. if (clear_first) {
  1573. for (p = list; p; p = p->next)
  1574. config_reset_line(fmt, options, p->key, use_defaults);
  1575. }
  1576. /* pass 3: assign. */
  1577. while (list) {
  1578. int r;
  1579. if ((r=config_assign_line(fmt, options, list, use_defaults,
  1580. clear_first, msg)))
  1581. return r;
  1582. list = list->next;
  1583. }
  1584. return 0;
  1585. }
  1586. /** Try assigning <b>list</b> to the global options. You do this by duping
  1587. * options, assigning list to the new one, then validating it. If it's
  1588. * ok, then throw out the old one and stick with the new one. Else,
  1589. * revert to old and return failure. Return 0 on success, -1 on bad
  1590. * keys, -2 on bad values, -3 on bad transition, and -4 on failed-to-set.
  1591. *
  1592. * If not success, point *<b>msg</b> to a newly allocated string describing
  1593. * what went wrong.
  1594. */
  1595. int
  1596. options_trial_assign(config_line_t *list, int use_defaults,
  1597. int clear_first, char **msg)
  1598. {
  1599. int r;
  1600. or_options_t *trial_options = options_dup(&options_format, get_options());
  1601. if ((r=config_assign(&options_format, trial_options,
  1602. list, use_defaults, clear_first, msg)) < 0) {
  1603. config_free(&options_format, trial_options);
  1604. return r;
  1605. }
  1606. if (options_validate(get_options(), trial_options, 1, msg) < 0) {
  1607. config_free(&options_format, trial_options);
  1608. return -2;
  1609. }
  1610. if (options_transition_allowed(get_options(), trial_options, msg) < 0) {
  1611. config_free(&options_format, trial_options);
  1612. return -3;
  1613. }
  1614. if (set_options(trial_options, msg)<0) {
  1615. config_free(&options_format, trial_options);
  1616. return -4;
  1617. }
  1618. /* we liked it. put it in place. */
  1619. return 0;
  1620. }
  1621. /** Reset config option <b>var</b> to 0, 0.0, NULL, or the equivalent.
  1622. * Called from option_reset() and config_free(). */
  1623. static void
  1624. option_clear(config_format_t *fmt, or_options_t *options, config_var_t *var)
  1625. {
  1626. void *lvalue = STRUCT_VAR_P(options, var->var_offset);
  1627. (void)fmt; /* unused */
  1628. switch (var->type) {
  1629. case CONFIG_TYPE_STRING:
  1630. tor_free(*(char**)lvalue);
  1631. break;
  1632. case CONFIG_TYPE_DOUBLE:
  1633. *(double*)lvalue = 0.0;
  1634. break;
  1635. case CONFIG_TYPE_ISOTIME:
  1636. *(time_t*)lvalue = 0;
  1637. case CONFIG_TYPE_INTERVAL:
  1638. case CONFIG_TYPE_UINT:
  1639. case CONFIG_TYPE_BOOL:
  1640. *(int*)lvalue = 0;
  1641. break;
  1642. case CONFIG_TYPE_MEMUNIT:
  1643. *(uint64_t*)lvalue = 0;
  1644. break;
  1645. case CONFIG_TYPE_CSV:
  1646. if (*(smartlist_t**)lvalue) {
  1647. SMARTLIST_FOREACH(*(smartlist_t **)lvalue, char *, cp, tor_free(cp));
  1648. smartlist_free(*(smartlist_t **)lvalue);
  1649. *(smartlist_t **)lvalue = NULL;
  1650. }
  1651. break;
  1652. case CONFIG_TYPE_LINELIST:
  1653. case CONFIG_TYPE_LINELIST_S:
  1654. config_free_lines(*(config_line_t **)lvalue);
  1655. *(config_line_t **)lvalue = NULL;
  1656. break;
  1657. case CONFIG_TYPE_LINELIST_V:
  1658. /* handled by linelist_s. */
  1659. break;
  1660. case CONFIG_TYPE_OBSOLETE:
  1661. break;
  1662. }
  1663. }
  1664. /** Clear the option indexed by <b>var</b> in <b>options</b>. Then if
  1665. * <b>use_defaults</b>, set it to its default value.
  1666. * Called by config_init() and option_reset_line() and option_assign_line(). */
  1667. static void
  1668. option_reset(config_format_t *fmt, or_options_t *options,
  1669. config_var_t *var, int use_defaults)
  1670. {
  1671. config_line_t *c;
  1672. char *msg = NULL;
  1673. CHECK(fmt, options);
  1674. option_clear(fmt, options, var); /* clear it first */
  1675. if (!use_defaults)
  1676. return; /* all done */
  1677. if (var->initvalue) {
  1678. c = tor_malloc_zero(sizeof(config_line_t));
  1679. c->key = tor_strdup(var->name);
  1680. c->value = tor_strdup(var->initvalue);
  1681. if (config_assign_value(fmt, options, c, &msg) < 0) {
  1682. log_warn(LD_BUG, "Failed to assign default: %s", msg);
  1683. tor_free(msg); /* if this happens it's a bug */
  1684. }
  1685. config_free_lines(c);
  1686. }
  1687. }
  1688. /** Print a usage message for tor. */
  1689. static void
  1690. print_usage(void)
  1691. {
  1692. printf(
  1693. "Copyright 2001-2007 Roger Dingledine, Nick Mathewson.\n\n"
  1694. "tor -f <torrc> [args]\n"
  1695. "See man page for options, or http://tor.eff.org/ for documentation.\n");
  1696. }
  1697. /** Print all non-obsolete torrc options. */
  1698. static void
  1699. list_torrc_options(void)
  1700. {
  1701. int i;
  1702. smartlist_t *lines = smartlist_create();
  1703. for (i = 0; _option_vars[i].name; ++i) {
  1704. config_var_t *var = &_option_vars[i];
  1705. const char *desc;
  1706. if (var->type == CONFIG_TYPE_OBSOLETE ||
  1707. var->type == CONFIG_TYPE_LINELIST_V)
  1708. continue;
  1709. desc = config_find_description(&options_format, var->name);
  1710. printf("%s\n", var->name);
  1711. if (desc) {
  1712. wrap_string(lines, desc, 76, " ", " ");
  1713. SMARTLIST_FOREACH(lines, char *, cp, {
  1714. printf("%s", cp);
  1715. tor_free(cp);
  1716. });
  1717. smartlist_clear(lines);
  1718. }
  1719. }
  1720. }
  1721. /** Last value actually set by resolve_my_address. */
  1722. static uint32_t last_resolved_addr = 0;
  1723. /**
  1724. * Based on <b>options-\>Address</b>, guess our public IP address and put it
  1725. * (in host order) into *<b>addr_out</b>. If <b>hostname_out</b> is provided,
  1726. * set *<b>hostname_out</b> to a new string holding the hostname we used to
  1727. * get the address. Return 0 if all is well, or -1 if we can't find a suitable
  1728. * public IP address.
  1729. */
  1730. int
  1731. resolve_my_address(int warn_severity, or_options_t *options,
  1732. uint32_t *addr_out, char **hostname_out)
  1733. {
  1734. struct in_addr in;
  1735. struct hostent *rent;
  1736. char hostname[256];
  1737. int explicit_ip=1;
  1738. int explicit_hostname=1;
  1739. int from_interface=0;
  1740. char tmpbuf[INET_NTOA_BUF_LEN];
  1741. const char *address = options->Address;
  1742. int notice_severity = warn_severity <= LOG_NOTICE ?
  1743. LOG_NOTICE : warn_severity;
  1744. tor_assert(addr_out);
  1745. if (address && *address) {
  1746. strlcpy(hostname, address, sizeof(hostname));
  1747. } else { /* then we need to guess our address */
  1748. explicit_ip = 0; /* it's implicit */
  1749. explicit_hostname = 0; /* it's implicit */
  1750. if (gethostname(hostname, sizeof(hostname)) < 0) {
  1751. log_fn(warn_severity, LD_NET,"Error obtaining local hostname");
  1752. return -1;
  1753. }
  1754. log_debug(LD_CONFIG,"Guessed local host name as '%s'",hostname);
  1755. }
  1756. /* now we know hostname. resolve it and keep only the IP address */
  1757. if (tor_inet_aton(hostname, &in) == 0) {
  1758. /* then we have to resolve it */
  1759. explicit_ip = 0;
  1760. rent = (struct hostent *)gethostbyname(hostname);
  1761. if (!rent) {
  1762. uint32_t interface_ip;
  1763. if (explicit_hostname) {
  1764. log_fn(warn_severity, LD_CONFIG,
  1765. "Could not resolve local Address '%s'. Failing.", hostname);
  1766. return -1;
  1767. }
  1768. log_fn(notice_severity, LD_CONFIG,
  1769. "Could not resolve guessed local hostname '%s'. "
  1770. "Trying something else.", hostname);
  1771. if (get_interface_address(warn_severity, &interface_ip)) {
  1772. log_fn(warn_severity, LD_CONFIG,
  1773. "Could not get local interface IP address. Failing.");
  1774. return -1;
  1775. }
  1776. from_interface = 1;
  1777. in.s_addr = htonl(interface_ip);
  1778. tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
  1779. log_fn(notice_severity, LD_CONFIG, "Learned IP address '%s' for "
  1780. "local interface. Using that.", tmpbuf);
  1781. strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
  1782. } else {
  1783. tor_assert(rent->h_length == 4);
  1784. memcpy(&in.s_addr, rent->h_addr, rent->h_length);
  1785. if (!explicit_hostname &&
  1786. is_internal_IP(ntohl(in.s_addr), 0)) {
  1787. uint32_t interface_ip;
  1788. tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
  1789. log_fn(notice_severity, LD_CONFIG, "Guessed local hostname '%s' "
  1790. "resolves to a private IP address (%s). Trying something "
  1791. "else.", hostname, tmpbuf);
  1792. if (get_interface_address(warn_severity, &interface_ip)) {
  1793. log_fn(warn_severity, LD_CONFIG,
  1794. "Could not get local interface IP address. Too bad.");
  1795. } else if (is_internal_IP(interface_ip, 0)) {
  1796. struct in_addr in2;
  1797. in2.s_addr = htonl(interface_ip);
  1798. tor_inet_ntoa(&in2,tmpbuf,sizeof(tmpbuf));
  1799. log_fn(notice_severity, LD_CONFIG,
  1800. "Interface IP address '%s' is a private address too. "
  1801. "Ignoring.", tmpbuf);
  1802. } else {
  1803. from_interface = 1;
  1804. in.s_addr = htonl(interface_ip);
  1805. tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
  1806. log_fn(notice_severity, LD_CONFIG,
  1807. "Learned IP address '%s' for local interface."
  1808. " Using that.", tmpbuf);
  1809. strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
  1810. }
  1811. }
  1812. }
  1813. }
  1814. tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
  1815. if (is_internal_IP(ntohl(in.s_addr), 0) &&
  1816. options->_PublishServerDescriptor) {
  1817. /* make sure we're ok with publishing an internal IP */
  1818. if (!options->DirServers) {
  1819. /* if they are using the default dirservers, disallow internal IPs
  1820. * always. */
  1821. log_fn(warn_severity, LD_CONFIG,
  1822. "Address '%s' resolves to private IP address '%s'. "
  1823. "Tor servers that use the default DirServers must have public "
  1824. "IP addresses.", hostname, tmpbuf);
  1825. return -1;
  1826. }
  1827. if (!explicit_ip) {
  1828. /* even if they've set their own dirservers, require an explicit IP if
  1829. * they're using an internal address. */
  1830. log_fn(warn_severity, LD_CONFIG, "Address '%s' resolves to private "
  1831. "IP address '%s'. Please set the Address config option to be "
  1832. "the IP address you want to use.", hostname, tmpbuf);
  1833. return -1;
  1834. }
  1835. }
  1836. log_debug(LD_CONFIG, "Resolved Address to '%s'.", tmpbuf);
  1837. *addr_out = ntohl(in.s_addr);
  1838. if (last_resolved_addr && last_resolved_addr != *addr_out) {
  1839. /* Leave this as a notice, regardless of the requested severity,
  1840. * at least until dynamic IP address support becomes bulletproof. */
  1841. log_notice(LD_NET, "Your IP address seems to have changed. Updating.");
  1842. ip_address_changed(0);
  1843. }
  1844. if (last_resolved_addr != *addr_out) {
  1845. const char *method;
  1846. const char *h = hostname;
  1847. if (explicit_ip) {
  1848. method = "CONFIGURED";
  1849. h = NULL;
  1850. } else if (explicit_hostname) {
  1851. method = "RESOLVED";
  1852. } else if (from_interface) {
  1853. method = "INTERFACE";
  1854. h = NULL;
  1855. } else {
  1856. method = "GETHOSTNAME";
  1857. }
  1858. control_event_server_status(LOG_NOTICE,
  1859. "EXTERNAL_ADDRESS ADDRESS=%s METHOD=%s %s%s",
  1860. tmpbuf, method, h?"HOSTNAME=":"", h);
  1861. }
  1862. last_resolved_addr = *addr_out;
  1863. if (hostname_out)
  1864. *hostname_out = tor_strdup(hostname);
  1865. return 0;
  1866. }
  1867. /** Return true iff <b>ip</b> (in host order) is judged to be on the
  1868. * same network as us, or on a private network.
  1869. */
  1870. int
  1871. is_local_IP(uint32_t ip)
  1872. {
  1873. if (is_internal_IP(ip, 0))
  1874. return 1;
  1875. /* Check whether ip is on the same /24 as we are. */
  1876. if (get_options()->EnforceDistinctSubnets == 0)
  1877. return 0;
  1878. /* It's possible that this next check will hit before the first time
  1879. * resolve_my_address actually succeeds. (For clients, it is likely that
  1880. * resolve_my_address will never be called at all). In those cases,
  1881. * last_resolved_addr will be 0, and so checking to see whether ip is on the
  1882. * same /24 as last_resolved_addr will be the same as checking whether it
  1883. * was on net 0, which is already done by is_internal_IP.
  1884. */
  1885. if ((last_resolved_addr & 0xffffff00ul) == (ip & 0xffffff00ul))
  1886. return 1;
  1887. return 0;
  1888. }
  1889. /** Called when we don't have a nickname set. Try to guess a good nickname
  1890. * based on the hostname, and return it in a newly allocated string. If we
  1891. * can't, return NULL and let the caller warn if it wants to. */
  1892. static char *
  1893. get_default_nickname(void)
  1894. {
  1895. static const char * const bad_default_nicknames[] = {
  1896. "localhost",
  1897. NULL,
  1898. };
  1899. char localhostname[256];
  1900. char *cp, *out, *outp;
  1901. int i;
  1902. if (gethostname(localhostname, sizeof(localhostname)) < 0)
  1903. return NULL;
  1904. /* Put it in lowercase; stop at the first dot. */
  1905. if ((cp = strchr(localhostname, '.')))
  1906. *cp = '\0';
  1907. tor_strlower(localhostname);
  1908. /* Strip invalid characters. */
  1909. cp = localhostname;
  1910. out = outp = tor_malloc(strlen(localhostname) + 1);
  1911. while (*cp) {
  1912. if (strchr(LEGAL_NICKNAME_CHARACTERS, *cp))
  1913. *outp++ = *cp++;
  1914. else
  1915. cp++;
  1916. }
  1917. *outp = '\0';
  1918. /* Enforce length. */
  1919. if (strlen(out) > MAX_NICKNAME_LEN)
  1920. out[MAX_NICKNAME_LEN]='\0';
  1921. /* Check for dumb names. */
  1922. for (i = 0; bad_default_nicknames[i]; ++i) {
  1923. if (!strcmp(out, bad_default_nicknames[i])) {
  1924. tor_free(out);
  1925. return NULL;
  1926. }
  1927. }
  1928. return out;
  1929. }
  1930. /** Release storage held by <b>options</b>. */
  1931. static void
  1932. config_free(config_format_t *fmt, void *options)
  1933. {
  1934. int i;
  1935. tor_assert(options);
  1936. for (i=0; fmt->vars[i].name; ++i)
  1937. option_clear(fmt, options, &(fmt->vars[i]));
  1938. if (fmt->extra) {
  1939. config_line_t **linep = STRUCT_VAR_P(options, fmt->extra->var_offset);
  1940. config_free_lines(*linep);
  1941. *linep = NULL;
  1942. }
  1943. tor_free(options);
  1944. }
  1945. /** Return true iff a and b contain identical keys and values in identical
  1946. * order. */
  1947. static int
  1948. config_lines_eq(config_line_t *a, config_line_t *b)
  1949. {
  1950. while (a && b) {
  1951. if (strcasecmp(a->key, b->key) || strcmp(a->value, b->value))
  1952. return 0;
  1953. a = a->next;
  1954. b = b->next;
  1955. }
  1956. if (a || b)
  1957. return 0;
  1958. return 1;
  1959. }
  1960. /** Return true iff the option <b>var</b> has the same value in <b>o1</b>
  1961. * and <b>o2</b>. Must not be called for LINELIST_S or OBSOLETE options.
  1962. */
  1963. static int
  1964. option_is_same(config_format_t *fmt,
  1965. or_options_t *o1, or_options_t *o2, const char *name)
  1966. {
  1967. config_line_t *c1, *c2;
  1968. int r = 1;
  1969. CHECK(fmt, o1);
  1970. CHECK(fmt, o2);
  1971. c1 = get_assigned_option(fmt, o1, name);
  1972. c2 = get_assigned_option(fmt, o2, name);
  1973. r = config_lines_eq(c1, c2);
  1974. config_free_lines(c1);
  1975. config_free_lines(c2);
  1976. return r;
  1977. }
  1978. /** Copy storage held by <b>old</b> into a new or_options_t and return it. */
  1979. static or_options_t *
  1980. options_dup(config_format_t *fmt, or_options_t *old)
  1981. {
  1982. or_options_t *newopts;
  1983. int i;
  1984. config_line_t *line;
  1985. newopts = config_alloc(fmt);
  1986. for (i=0; fmt->vars[i].name; ++i) {
  1987. if (fmt->vars[i].type == CONFIG_TYPE_LINELIST_S)
  1988. continue;
  1989. if (fmt->vars[i].type == CONFIG_TYPE_OBSOLETE)
  1990. continue;
  1991. line = get_assigned_option(fmt, old, fmt->vars[i].name);
  1992. if (line) {
  1993. char *msg = NULL;
  1994. if (config_assign(fmt, newopts, line, 0, 0, &msg) < 0) {
  1995. log_err(LD_BUG, "Config_get_assigned_option() generated "
  1996. "something we couldn't config_assign(): %s", msg);
  1997. tor_free(msg);
  1998. tor_assert(0);
  1999. }
  2000. }
  2001. config_free_lines(line);
  2002. }
  2003. return newopts;
  2004. }
  2005. /** Return a new empty or_options_t. Used for testing. */
  2006. or_options_t *
  2007. options_new(void)
  2008. {
  2009. return config_alloc(&options_format);
  2010. }
  2011. /** Set <b>options</b> to hold reasonable defaults for most options.
  2012. * Each option defaults to zero. */
  2013. void
  2014. options_init(or_options_t *options)
  2015. {
  2016. config_init(&options_format, options);
  2017. }
  2018. /* Set all vars in the configuration object 'options' to their default
  2019. * values. */
  2020. static void
  2021. config_init(config_format_t *fmt, void *options)
  2022. {
  2023. int i;
  2024. config_var_t *var;
  2025. CHECK(fmt, options);
  2026. for (i=0; fmt->vars[i].name; ++i) {
  2027. var = &fmt->vars[i];
  2028. if (!var->initvalue)
  2029. continue; /* defaults to NULL or 0 */
  2030. option_reset(fmt, options, var, 1);
  2031. }
  2032. }
  2033. /** Allocate and return a new string holding the written-out values of the vars
  2034. * in 'options'. If 'minimal', do not write out any default-valued vars.
  2035. * Else, if comment_defaults, write default values as comments.
  2036. */
  2037. static char *
  2038. config_dump(config_format_t *fmt, void *options, int minimal,
  2039. int comment_defaults)
  2040. {
  2041. smartlist_t *elements;
  2042. or_options_t *defaults;
  2043. config_line_t *line, *assigned;
  2044. char *result;
  2045. int i;
  2046. const char *desc;
  2047. char *msg = NULL;
  2048. defaults = config_alloc(fmt);
  2049. config_init(fmt, defaults);
  2050. /* XXX use a 1 here so we don't add a new log line while dumping */
  2051. if (fmt->validate_fn(NULL,defaults, 1, &msg) < 0) {
  2052. log_err(LD_BUG, "Failed to validate default config.");
  2053. tor_free(msg);
  2054. tor_assert(0);
  2055. }
  2056. elements = smartlist_create();
  2057. for (i=0; fmt->vars[i].name; ++i) {
  2058. int comment_option = 0;
  2059. if (fmt->vars[i].type == CONFIG_TYPE_OBSOLETE ||
  2060. fmt->vars[i].type == CONFIG_TYPE_LINELIST_S)
  2061. continue;
  2062. /* Don't save 'hidden' control variables. */
  2063. if (!strcmpstart(fmt->vars[i].name, "__"))
  2064. continue;
  2065. if (minimal && option_is_same(fmt, options, defaults, fmt->vars[i].name))
  2066. continue;
  2067. else if (comment_defaults &&
  2068. option_is_same(fmt, options, defaults, fmt->vars[i].name))
  2069. comment_option = 1;
  2070. desc = config_find_description(fmt, fmt->vars[i].name);
  2071. line = assigned = get_assigned_option(fmt, options, fmt->vars[i].name);
  2072. if (line && desc) {
  2073. /* Only dump the description if there's something to describe. */
  2074. wrap_string(elements, desc, 78, "# ", "# ");
  2075. }
  2076. for (; line; line = line->next) {
  2077. size_t len = strlen(line->key) + strlen(line->value) + 5;
  2078. char *tmp;
  2079. tmp = tor_malloc(len);
  2080. if (tor_snprintf(tmp, len, "%s%s %s\n",
  2081. comment_option ? "# " : "",
  2082. line->key, line->value)<0) {
  2083. log_err(LD_BUG,"Internal error writing option value");
  2084. tor_assert(0);
  2085. }
  2086. smartlist_add(elements, tmp);
  2087. }
  2088. config_free_lines(assigned);
  2089. }
  2090. if (fmt->extra) {
  2091. line = *(config_line_t**)STRUCT_VAR_P(options, fmt->extra->var_offset);
  2092. for (; line; line = line->next) {
  2093. size_t len = strlen(line->key) + strlen(line->value) + 3;
  2094. char *tmp;
  2095. tmp = tor_malloc(len);
  2096. if (tor_snprintf(tmp, len, "%s %s\n", line->key, line->value)<0) {
  2097. log_err(LD_BUG,"Internal error writing option value");
  2098. tor_assert(0);
  2099. }
  2100. smartlist_add(elements, tmp);
  2101. }
  2102. }
  2103. result = smartlist_join_strings(elements, "", 0, NULL);
  2104. SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
  2105. smartlist_free(elements);
  2106. config_free(fmt, defaults);
  2107. return result;
  2108. }
  2109. /** Return a string containing a possible configuration file that would give
  2110. * the configuration in <b>options</b>. If <b>minimal</b> is true, do not
  2111. * include options that are the same as Tor's defaults.
  2112. */
  2113. char *
  2114. options_dump(or_options_t *options, int minimal)
  2115. {
  2116. return config_dump(&options_format, options, minimal, 0);
  2117. }
  2118. /** Return 0 if every element of sl is a string holding a decimal
  2119. * representation of a port number, or if sl is NULL.
  2120. * Otherwise set *msg and return -1. */
  2121. static int
  2122. validate_ports_csv(smartlist_t *sl, const char *name, char **msg)
  2123. {
  2124. int i;
  2125. char buf[1024];
  2126. tor_assert(name);
  2127. if (!sl)
  2128. return 0;
  2129. SMARTLIST_FOREACH(sl, const char *, cp,
  2130. {
  2131. i = atoi(cp);
  2132. if (i < 1 || i > 65535) {
  2133. int r = tor_snprintf(buf, sizeof(buf),
  2134. "Port '%s' out of range in %s", cp, name);
  2135. *msg = tor_strdup(r >= 0 ? buf : "internal error");
  2136. return -1;
  2137. }
  2138. });
  2139. return 0;
  2140. }
  2141. /** If <b>value</b> exceeds ROUTER_MAX_DECLARED_BANDWIDTH, write
  2142. * a complaint into *<b>msg</b> using string <b>desc</b>, and return -1.
  2143. * Else return 0.
  2144. */
  2145. static int
  2146. ensure_bandwidth_cap(uint64_t *value, const char *desc, char **msg)
  2147. {
  2148. int r;
  2149. char buf[1024];
  2150. if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
  2151. /* This handles an understandable special case where somebody says "2gb"
  2152. * whereas our actual maximum is 2gb-1 (INT_MAX) */
  2153. --*value;
  2154. }
  2155. if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
  2156. r = tor_snprintf(buf, sizeof(buf), "%s ("U64_FORMAT") must be at most %d",
  2157. desc, U64_PRINTF_ARG(*value),
  2158. ROUTER_MAX_DECLARED_BANDWIDTH);
  2159. *msg = tor_strdup(r >= 0 ? buf : "internal error");
  2160. return -1;
  2161. }
  2162. return 0;
  2163. }
  2164. /** Parse an authority type from <b>list</b> and write it to *<b>auth</b>. If
  2165. * <b>compatible</b> is non-zero, treat "1" as "v1,v2" and treat "0" as "".
  2166. * Return 0 on success or -(idx of first bad member) if not a recognized
  2167. * authority type.
  2168. */
  2169. static int
  2170. parse_authority_type_from_list(smartlist_t *list, authority_type_t *auth,
  2171. int compatible)
  2172. {
  2173. tor_assert(auth);
  2174. *auth = NO_AUTHORITY;
  2175. if (!list) /* empty list, answer is none */
  2176. return 0;
  2177. SMARTLIST_FOREACH(list, const char *, string, {
  2178. if (!strcasecmp(string, "v1"))
  2179. *auth |= V1_AUTHORITY;
  2180. else if (compatible && !strcmp(string, "1"))
  2181. *auth |= V1_AUTHORITY | V2_AUTHORITY;
  2182. else if (!strcasecmp(string, "v2"))
  2183. *auth |= V2_AUTHORITY;
  2184. else if (!strcasecmp(string, "v3"))
  2185. *auth |= V3_AUTHORITY;
  2186. else if (!strcasecmp(string, "bridge"))
  2187. *auth |= BRIDGE_AUTHORITY;
  2188. else if (!strcasecmp(string, "hidserv"))
  2189. *auth |= HIDSERV_AUTHORITY;
  2190. else if (!strcasecmp(string, "") || (compatible && !strcmp(string, "0")))
  2191. /* no authority */;
  2192. else
  2193. return - string_sl_idx;
  2194. });
  2195. return 0;
  2196. }
  2197. /** Lowest allowable value for RendPostPeriod; if this is too low, hidden
  2198. * services can overload the directory system. */
  2199. #define MIN_REND_POST_PERIOD (10*60)
  2200. /** Highest allowable value for RendPostPeriod. */
  2201. #define MAX_DIR_PERIOD (MIN_ONION_KEY_LIFETIME/2)
  2202. /** Return 0 if every setting in <b>options</b> is reasonable, and a
  2203. * permissible transition from <b>old_options</b>. Else return -1.
  2204. * Should have no side effects, except for normalizing the contents of
  2205. * <b>options</b>.
  2206. *
  2207. * On error, tor_strdup an error explanation into *<b>msg</b>.
  2208. *
  2209. * XXX
  2210. * If <b>from_setconf</b>, we were called by the controller, and our
  2211. * Log line should stay empty. If it's 0, then give us a default log
  2212. * if there are no logs defined.
  2213. */
  2214. static int
  2215. options_validate(or_options_t *old_options, or_options_t *options,
  2216. int from_setconf, char **msg)
  2217. {
  2218. int i, r;
  2219. config_line_t *cl;
  2220. const char *uname = get_uname();
  2221. char buf[1024];
  2222. #define REJECT(arg) \
  2223. STMT_BEGIN *msg = tor_strdup(arg); return -1; STMT_END
  2224. #define COMPLAIN(arg) STMT_BEGIN log(LOG_WARN, LD_CONFIG, arg); STMT_END
  2225. tor_assert(msg);
  2226. *msg = NULL;
  2227. if (options->ORPort < 0 || options->ORPort > 65535)
  2228. REJECT("ORPort option out of bounds.");
  2229. if (server_mode(options) &&
  2230. (!strcmpstart(uname, "Windows 95") ||
  2231. !strcmpstart(uname, "Windows 98") ||
  2232. !strcmpstart(uname, "Windows Me"))) {
  2233. log(LOG_WARN, LD_CONFIG, "Tor is running as a server, but you are "
  2234. "running %s; this probably won't work. See "
  2235. "http://wiki.noreply.org/noreply/TheOnionRouter/TorFAQ#ServerOS "
  2236. "for details.", uname);
  2237. }
  2238. if (options->ORPort == 0 && options->ORListenAddress != NULL)
  2239. REJECT("ORPort must be defined if ORListenAddress is defined.");
  2240. if (options->DirPort == 0 && options->DirListenAddress != NULL)
  2241. REJECT("DirPort must be defined if DirListenAddress is defined.");
  2242. if (options->DNSPort == 0 && options->DNSListenAddress != NULL)
  2243. REJECT("DNSPort must be defined if DNSListenAddress is defined.");
  2244. if (options->ControlPort == 0 && options->ControlListenAddress != NULL)
  2245. REJECT("ControlPort must be defined if ControlListenAddress is defined.");
  2246. if (options->TransPort == 0 && options->TransListenAddress != NULL)
  2247. REJECT("TransPort must be defined if TransListenAddress is defined.");
  2248. if (options->NatdPort == 0 && options->NatdListenAddress != NULL)
  2249. REJECT("NatdPort must be defined if NatdListenAddress is defined.");
  2250. /* Don't gripe about SocksPort 0 with SocksListenAddress set; a standard
  2251. * configuration does this. */
  2252. for (i = 0; i < 3; ++i) {
  2253. int is_socks = i==0;
  2254. int is_trans = i==1;
  2255. config_line_t *line, *opt, *old;
  2256. const char *tp;
  2257. if (is_socks) {
  2258. opt = options->SocksListenAddress;
  2259. old = old_options ? old_options->SocksListenAddress : NULL;
  2260. tp = "SOCKS proxy";
  2261. } else if (is_trans) {
  2262. opt = options->TransListenAddress;
  2263. old = old_options ? old_options->TransListenAddress : NULL;
  2264. tp = "transparent proxy";
  2265. } else {
  2266. opt = options->NatdListenAddress;
  2267. old = old_options ? old_options->NatdListenAddress : NULL;
  2268. tp = "natd proxy";
  2269. }
  2270. for (line = opt; line; line = line->next) {
  2271. char *address = NULL;
  2272. uint16_t port;
  2273. uint32_t addr;
  2274. if (parse_addr_port(LOG_WARN, line->value, &address, &addr, &port)<0)
  2275. continue; /* We'll warn about this later. */
  2276. if (!is_internal_IP(addr, 1) &&
  2277. (!old_options || !config_lines_eq(old, opt))) {
  2278. log_warn(LD_CONFIG,
  2279. "You specified a public address '%s' for a %s. Other "
  2280. "people on the Internet might find your computer and use it as "
  2281. "an open %s. Please don't allow this unless you have "
  2282. "a good reason.", address, tp, tp);
  2283. }
  2284. tor_free(address);
  2285. }
  2286. }
  2287. if (validate_data_directory(options)<0)
  2288. REJECT("Invalid DataDirectory");
  2289. if (options->Nickname == NULL) {
  2290. if (server_mode(options)) {
  2291. if (!(options->Nickname = get_default_nickname())) {
  2292. log_notice(LD_CONFIG, "Couldn't pick a nickname based on "
  2293. "our hostname; using %s instead.", UNNAMED_ROUTER_NICKNAME);
  2294. options->Nickname = tor_strdup(UNNAMED_ROUTER_NICKNAME);
  2295. } else {
  2296. log_notice(LD_CONFIG, "Choosing default nickname '%s'",
  2297. options->Nickname);
  2298. }
  2299. }
  2300. } else {
  2301. if (!is_legal_nickname(options->Nickname)) {
  2302. r = tor_snprintf(buf, sizeof(buf),
  2303. "Nickname '%s' is wrong length or contains illegal characters.",
  2304. options->Nickname);
  2305. *msg = tor_strdup(r >= 0 ? buf : "internal error");
  2306. return -1;
  2307. }
  2308. }
  2309. if (server_mode(options) && !options->ContactInfo)
  2310. log(LOG_NOTICE, LD_CONFIG, "Your ContactInfo config option is not set. "
  2311. "Please consider setting it, so we can contact you if your server is "
  2312. "misconfigured or something else goes wrong.");
  2313. /* Special case on first boot if no Log options are given. */
  2314. if (!options->Logs && !options->RunAsDaemon && !from_setconf)
  2315. config_line_append(&options->Logs, "Log", "notice stdout");
  2316. if (options_init_logs(options, 1)<0) /* Validate the log(s) */
  2317. REJECT("Failed to validate Log options. See logs for details.");
  2318. if (options->NoPublish) {
  2319. log(LOG_WARN, LD_CONFIG,
  2320. "NoPublish is obsolete. Use PublishServerDescriptor instead.");
  2321. SMARTLIST_FOREACH(options->PublishServerDescriptor, char *, s,
  2322. tor_free(s));
  2323. smartlist_clear(options->PublishServerDescriptor);
  2324. }
  2325. if (authdir_mode(options)) {
  2326. /* confirm that our address isn't broken, so we can complain now */
  2327. uint32_t tmp;
  2328. if (resolve_my_address(LOG_WARN, options, &tmp, NULL) < 0)
  2329. REJECT("Failed to resolve/guess local address. See logs for details.");
  2330. }
  2331. #ifndef MS_WINDOWS
  2332. if (options->RunAsDaemon && torrc_fname && path_is_relative(torrc_fname))
  2333. REJECT("Can't use a relative path to torrc when RunAsDaemon is set.");
  2334. #endif
  2335. if (options->SocksPort < 0 || options->SocksPort > 65535)
  2336. REJECT("SocksPort option out of bounds.");
  2337. if (options->DNSPort < 0 || options->DNSPort > 65535)
  2338. REJECT("DNSPort option out of bounds.");
  2339. if (options->TransPort < 0 || options->TransPort > 65535)
  2340. REJECT("TransPort option out of bounds.");
  2341. if (options->NatdPort < 0 || options->NatdPort > 65535)
  2342. REJECT("NatdPort option out of bounds.");
  2343. if (options->SocksPort == 0 && options->TransPort == 0 &&
  2344. options->NatdPort == 0 && options->ORPort == 0)
  2345. REJECT("SocksPort, TransPort, NatdPort, and ORPort are all undefined? "
  2346. "Quitting.");
  2347. if (options->ControlPort < 0 || options->ControlPort > 65535)
  2348. REJECT("ControlPort option out of bounds.");
  2349. if (options->DirPort < 0 || options->DirPort > 65535)
  2350. REJECT("DirPort option out of bounds.");
  2351. #ifndef USE_TRANSPARENT
  2352. if (options->TransPort || options->TransListenAddress)
  2353. REJECT("TransPort and TransListenAddress are disabled in this build.");
  2354. #endif
  2355. if (options->StrictExitNodes &&
  2356. (!options->ExitNodes || !strlen(options->ExitNodes)) &&
  2357. (!old_options ||
  2358. (old_options->StrictExitNodes != options->StrictExitNodes) ||
  2359. (!opt_streq(old_options->ExitNodes, options->ExitNodes))))
  2360. COMPLAIN("StrictExitNodes set, but no ExitNodes listed.");
  2361. if (options->StrictEntryNodes &&
  2362. (!options->EntryNodes || !strlen(options->EntryNodes)) &&
  2363. (!old_options ||
  2364. (old_options->StrictEntryNodes != options->StrictEntryNodes) ||
  2365. (!opt_streq(old_options->EntryNodes, options->EntryNodes))))
  2366. COMPLAIN("StrictEntryNodes set, but no EntryNodes listed.");
  2367. if (options->AuthoritativeDir) {
  2368. if (!options->ContactInfo)
  2369. REJECT("Authoritative directory servers must set ContactInfo");
  2370. if (options->V1AuthoritativeDir && !options->RecommendedVersions)
  2371. REJECT("V1 auth dir servers must set RecommendedVersions.");
  2372. if (!options->RecommendedClientVersions)
  2373. options->RecommendedClientVersions =
  2374. config_lines_dup(options->RecommendedVersions);
  2375. if (!options->RecommendedServerVersions)
  2376. options->RecommendedServerVersions =
  2377. config_lines_dup(options->RecommendedVersions);
  2378. if (options->VersioningAuthoritativeDir &&
  2379. (!options->RecommendedClientVersions ||
  2380. !options->RecommendedServerVersions))
  2381. REJECT("Versioning auth dir servers must set Recommended*Versions.");
  2382. if (options->UseEntryGuards) {
  2383. log_info(LD_CONFIG, "Authoritative directory servers can't set "
  2384. "UseEntryGuards. Disabling.");
  2385. options->UseEntryGuards = 0;
  2386. }
  2387. if (!options->DownloadExtraInfo) {
  2388. log_info(LD_CONFIG, "Authoritative directories always try to download "
  2389. "extra-info documents. Setting DownloadExtraInfo.");
  2390. options->DownloadExtraInfo = 1;
  2391. }
  2392. /* XXXX020 Check that at least one of Bridge/HS/V1/V2/V2{AuthoritativeDir}
  2393. * is set. */
  2394. }
  2395. if (options->AuthoritativeDir && !options->DirPort)
  2396. REJECT("Running as authoritative directory, but no DirPort set.");
  2397. if (options->AuthoritativeDir && !options->ORPort)
  2398. REJECT("Running as authoritative directory, but no ORPort set.");
  2399. if (options->AuthoritativeDir && options->ClientOnly)
  2400. REJECT("Running as authoritative directory, but ClientOnly also set.");
  2401. if (options->HSAuthorityRecordStats && !options->HSAuthoritativeDir)
  2402. REJECT("HSAuthorityRecordStats is set but we're not running as "
  2403. "a hidden service authority.");
  2404. if (options->ConnLimit <= 0) {
  2405. r = tor_snprintf(buf, sizeof(buf),
  2406. "ConnLimit must be greater than 0, but was set to %d",
  2407. options->ConnLimit);
  2408. *msg = tor_strdup(r >= 0 ? buf : "internal error");
  2409. return -1;
  2410. }
  2411. if (validate_ports_csv(options->FirewallPorts, "FirewallPorts", msg) < 0)
  2412. return -1;
  2413. if (validate_ports_csv(options->LongLivedPorts, "LongLivedPorts", msg) < 0)
  2414. return -1;
  2415. if (options->FascistFirewall && !options->ReachableAddresses) {
  2416. if (options->FirewallPorts && smartlist_len(options->FirewallPorts)) {
  2417. /* We already have firewall ports set, so migrate them to
  2418. * ReachableAddresses, which will set ReachableORAddresses and
  2419. * ReachableDirAddresses if they aren't set explicitly. */
  2420. smartlist_t *instead = smartlist_create();
  2421. config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
  2422. new_line->key = tor_strdup("ReachableAddresses");
  2423. /* If we're configured with the old format, we need to prepend some
  2424. * open ports. */
  2425. SMARTLIST_FOREACH(options->FirewallPorts, const char *, portno,
  2426. {
  2427. int p = atoi(portno);
  2428. char *s;
  2429. if (p<0) continue;
  2430. s = tor_malloc(16);
  2431. tor_snprintf(s, 16, "*:%d", p);
  2432. smartlist_add(instead, s);
  2433. });
  2434. new_line->value = smartlist_join_strings(instead,",",0,NULL);
  2435. /* These have been deprecated since 0.1.1.5-alpha-cvs */
  2436. log(LOG_NOTICE, LD_CONFIG,
  2437. "Converting FascistFirewall and FirewallPorts "
  2438. "config options to new format: \"ReachableAddresses %s\"",
  2439. new_line->value);
  2440. options->ReachableAddresses = new_line;
  2441. SMARTLIST_FOREACH(instead, char *, cp, tor_free(cp));
  2442. smartlist_free(instead);
  2443. } else {
  2444. /* We do not have FirewallPorts set, so add 80 to
  2445. * ReachableDirAddresses, and 443 to ReachableORAddresses. */
  2446. if (!options->ReachableDirAddresses) {
  2447. config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
  2448. new_line->key = tor_strdup("ReachableDirAddresses");
  2449. new_line->value = tor_strdup("*:80");
  2450. options->ReachableDirAddresses = new_line;
  2451. log(LOG_NOTICE, LD_CONFIG, "Converting FascistFirewall config option "
  2452. "to new format: \"ReachableDirAddresses *:80\"");
  2453. }
  2454. if (!options->ReachableORAddresses) {
  2455. config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
  2456. new_line->key = tor_strdup("ReachableORAddresses");
  2457. new_line->value = tor_strdup("*:443");
  2458. options->ReachableORAddresses = new_line;
  2459. log(LOG_NOTICE, LD_CONFIG, "Converting FascistFirewall config option "
  2460. "to new format: \"ReachableORAddresses *:443\"");
  2461. }
  2462. }
  2463. }
  2464. for (i=0; i<3; i++) {
  2465. config_line_t **linep =
  2466. (i==0) ? &options->ReachableAddresses :
  2467. (i==1) ? &options->ReachableORAddresses :
  2468. &options->ReachableDirAddresses;
  2469. if (!*linep)
  2470. continue;
  2471. /* We need to end with a reject *:*, not an implicit accept *:* */
  2472. for (;;) {
  2473. if (!strcmp((*linep)->value, "reject *:*")) /* already there */
  2474. break;
  2475. linep = &((*linep)->next);
  2476. if (!*linep) {
  2477. *linep = tor_malloc_zero(sizeof(config_line_t));
  2478. (*linep)->key = tor_strdup(
  2479. (i==0) ? "ReachableAddresses" :
  2480. (i==1) ? "ReachableORAddresses" :
  2481. "ReachableDirAddresses");
  2482. (*linep)->value = tor_strdup("reject *:*");
  2483. break;
  2484. }
  2485. }
  2486. }
  2487. if ((options->ReachableAddresses ||
  2488. options->ReachableORAddresses ||
  2489. options->ReachableDirAddresses) &&
  2490. server_mode(options))
  2491. REJECT("Servers must be able to freely connect to the rest "
  2492. "of the Internet, so they must not set Reachable*Addresses "
  2493. "or FascistFirewall.");
  2494. options->_AllowInvalid = 0;
  2495. if (options->AllowInvalidNodes) {
  2496. SMARTLIST_FOREACH(options->AllowInvalidNodes, const char *, cp, {
  2497. if (!strcasecmp(cp, "entry"))
  2498. options->_AllowInvalid |= ALLOW_INVALID_ENTRY;
  2499. else if (!strcasecmp(cp, "exit"))
  2500. options->_AllowInvalid |= ALLOW_INVALID_EXIT;
  2501. else if (!strcasecmp(cp, "middle"))
  2502. options->_AllowInvalid |= ALLOW_INVALID_MIDDLE;
  2503. else if (!strcasecmp(cp, "introduction"))
  2504. options->_AllowInvalid |= ALLOW_INVALID_INTRODUCTION;
  2505. else if (!strcasecmp(cp, "rendezvous"))
  2506. options->_AllowInvalid |= ALLOW_INVALID_RENDEZVOUS;
  2507. else {
  2508. r = tor_snprintf(buf, sizeof(buf),
  2509. "Unrecognized value '%s' in AllowInvalidNodes", cp);
  2510. *msg = tor_strdup(r >= 0 ? buf : "internal error");
  2511. return -1;
  2512. }
  2513. });
  2514. }
  2515. if ((i = parse_authority_type_from_list(options->PublishServerDescriptor,
  2516. &options->_PublishServerDescriptor, 1) < 0)) {
  2517. r = tor_snprintf(buf, sizeof(buf),
  2518. "Unrecognized value '%s' for PublishServerDescriptor",
  2519. (char*)smartlist_get(options->PublishServerDescriptor, -i));
  2520. *msg = tor_strdup(r >= 0 ? buf : "internal error");
  2521. return -1;
  2522. }
  2523. if (options->RendPostPeriod < MIN_REND_POST_PERIOD) {
  2524. log(LOG_WARN,LD_CONFIG,"RendPostPeriod option must be at least %d seconds."
  2525. " Clipping.", MIN_REND_POST_PERIOD);
  2526. options->RendPostPeriod = MIN_REND_POST_PERIOD;
  2527. }
  2528. if (options->RendPostPeriod > MAX_DIR_PERIOD) {
  2529. log(LOG_WARN, LD_CONFIG, "RendPostPeriod is too large; clipping to %ds.",
  2530. MAX_DIR_PERIOD);
  2531. options->RendPostPeriod = MAX_DIR_PERIOD;
  2532. }
  2533. if (options->KeepalivePeriod < 1)
  2534. REJECT("KeepalivePeriod option must be positive.");
  2535. if (ensure_bandwidth_cap(&options->BandwidthRate,
  2536. "BandwidthRate", msg) < 0)
  2537. return -1;
  2538. if (ensure_bandwidth_cap(&options->BandwidthBurst,
  2539. "BandwidthBurst", msg) < 0)
  2540. return -1;
  2541. if (ensure_bandwidth_cap(&options->MaxAdvertisedBandwidth,
  2542. "MaxAdvertisedBandwidth", msg) < 0)
  2543. return -1;
  2544. if (ensure_bandwidth_cap(&options->RelayBandwidthRate,
  2545. "RelayBandwidthRate", msg) < 0)
  2546. return -1;
  2547. if (ensure_bandwidth_cap(&options->RelayBandwidthBurst,
  2548. "RelayBandwidthBurst", msg) < 0)
  2549. return -1;
  2550. if (server_mode(options)) {
  2551. if (options->BandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH*2) {
  2552. r = tor_snprintf(buf, sizeof(buf),
  2553. "BandwidthRate is set to %d bytes/second. "
  2554. "For servers, it must be at least %d.",
  2555. (int)options->BandwidthRate,
  2556. ROUTER_REQUIRED_MIN_BANDWIDTH*2);
  2557. *msg = tor_strdup(r >= 0 ? buf : "internal error");
  2558. return -1;
  2559. } else if (options->MaxAdvertisedBandwidth <
  2560. ROUTER_REQUIRED_MIN_BANDWIDTH) {
  2561. r = tor_snprintf(buf, sizeof(buf),
  2562. "MaxAdvertisedBandwidth is set to %d bytes/second. "
  2563. "For servers, it must be at least %d.",
  2564. (int)options->MaxAdvertisedBandwidth,
  2565. ROUTER_REQUIRED_MIN_BANDWIDTH);
  2566. *msg = tor_strdup(r >= 0 ? buf : "internal error");
  2567. return -1;
  2568. }
  2569. if (options->RelayBandwidthRate > options->RelayBandwidthBurst)
  2570. REJECT("RelayBandwidthBurst must be at least equal "
  2571. "to RelayBandwidthRate.");
  2572. if (options->RelayBandwidthRate &&
  2573. options->RelayBandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH) {
  2574. r = tor_snprintf(buf, sizeof(buf),
  2575. "RelayBandwidthRate is set to %d bytes/second. "
  2576. "For servers, it must be at least %d.",
  2577. (int)options->RelayBandwidthRate,
  2578. ROUTER_REQUIRED_MIN_BANDWIDTH);
  2579. *msg = tor_strdup(r >= 0 ? buf : "internal error");
  2580. return -1;
  2581. }
  2582. }
  2583. if (options->BandwidthRate > options->BandwidthBurst)
  2584. REJECT("BandwidthBurst must be at least equal to BandwidthRate.");
  2585. if (accounting_parse_options(options, 1)<0)
  2586. REJECT("Failed to parse accounting options. See logs for details.");
  2587. if (options->HttpProxy) { /* parse it now */
  2588. if (parse_addr_port(LOG_WARN, options->HttpProxy, NULL,
  2589. &options->HttpProxyAddr, &options->HttpProxyPort) < 0)
  2590. REJECT("HttpProxy failed to parse or resolve. Please fix.");
  2591. if (options->HttpProxyPort == 0) { /* give it a default */
  2592. options->HttpProxyPort = 80;
  2593. }
  2594. }
  2595. if (options->HttpProxyAuthenticator) {
  2596. if (strlen(options->HttpProxyAuthenticator) >= 48)
  2597. REJECT("HttpProxyAuthenticator is too long (>= 48 chars).");
  2598. }
  2599. if (options->HttpsProxy) { /* parse it now */
  2600. if (parse_addr_port(LOG_WARN, options->HttpsProxy, NULL,
  2601. &options->HttpsProxyAddr, &options->HttpsProxyPort) <0)
  2602. REJECT("HttpsProxy failed to parse or resolve. Please fix.");
  2603. if (options->HttpsProxyPort == 0) { /* give it a default */
  2604. options->HttpsProxyPort = 443;
  2605. }
  2606. }
  2607. if (options->HttpsProxyAuthenticator) {
  2608. if (strlen(options->HttpsProxyAuthenticator) >= 48)
  2609. REJECT("HttpsProxyAuthenticator is too long (>= 48 chars).");
  2610. }
  2611. if (options->HashedControlPassword) {
  2612. if (decode_hashed_password(NULL, options->HashedControlPassword)<0)
  2613. REJECT("Bad HashedControlPassword: wrong length or bad encoding");
  2614. }
  2615. if (options->HashedControlPassword && options->CookieAuthentication)
  2616. REJECT("Cannot set both HashedControlPassword and CookieAuthentication");
  2617. if (options->ControlListenAddress) {
  2618. int all_are_local = 1;
  2619. config_line_t *ln;
  2620. for (ln = options->ControlListenAddress; ln; ln = ln->next) {
  2621. if (strcmpstart(ln->value, "127."))
  2622. all_are_local = 0;
  2623. }
  2624. if (!all_are_local) {
  2625. if (!options->HashedControlPassword && !options->CookieAuthentication) {
  2626. log_warn(LD_CONFIG, "You have a ControlListenAddress set to accept "
  2627. "connections from a non-local address. This means that "
  2628. "any program on the internet can reconfigure your Tor. "
  2629. "That's so bad that I'm closing your ControlPort for you.");
  2630. options->ControlPort = 0;
  2631. } else {
  2632. log_warn(LD_CONFIG, "You have a ControlListenAddress set to accept "
  2633. "connections from a non-local address. This means that "
  2634. "programs not running on your computer can reconfigure your "
  2635. "Tor. That's pretty bad!");
  2636. }
  2637. }
  2638. }
  2639. if (options->ControlPort && !options->HashedControlPassword &&
  2640. !options->CookieAuthentication) {
  2641. log_warn(LD_CONFIG, "ControlPort is open, but no authentication method "
  2642. "has been configured. This means that any program on your "
  2643. "computer can reconfigure your Tor. That's bad! You should "
  2644. "upgrade your Tor controller as soon as possible.");
  2645. }
  2646. if (options->UseEntryGuards && ! options->NumEntryGuards)
  2647. REJECT("Cannot enable UseEntryGuards with NumEntryGuards set to 0");
  2648. if (check_nickname_list(options->ExitNodes, "ExitNodes", msg))
  2649. return -1;
  2650. if (check_nickname_list(options->EntryNodes, "EntryNodes", msg))
  2651. return -1;
  2652. if (check_nickname_list(options->ExcludeNodes, "ExcludeNodes", msg))
  2653. return -1;
  2654. if (check_nickname_list(options->RendNodes, "RendNodes", msg))
  2655. return -1;
  2656. if (check_nickname_list(options->RendNodes, "RendExcludeNodes", msg))
  2657. return -1;
  2658. if (check_nickname_list(options->TestVia, "TestVia", msg))
  2659. return -1;
  2660. if (check_nickname_list(options->MyFamily, "MyFamily", msg))
  2661. return -1;
  2662. for (cl = options->NodeFamilies; cl; cl = cl->next) {
  2663. if (check_nickname_list(cl->value, "NodeFamily", msg))
  2664. return -1;
  2665. }
  2666. if (validate_addr_policies(options, msg) < 0)
  2667. return -1;
  2668. for (cl = options->RedirectExit; cl; cl = cl->next) {
  2669. if (parse_redirect_line(NULL, cl, msg)<0)
  2670. return -1;
  2671. }
  2672. if (options->DirServers) {
  2673. if (!old_options ||
  2674. !config_lines_eq(options->DirServers, old_options->DirServers))
  2675. COMPLAIN("You have used DirServer to specify directory authorities in "
  2676. "your configuration. This is potentially dangerous: it can "
  2677. "make you look different from all other Tor users, and hurt "
  2678. "your anonymity. Even if you've specified the same "
  2679. "authorities as Tor uses by default, the defaults could "
  2680. "change in the future. Be sure you know what you're doing.");
  2681. for (cl = options->DirServers; cl; cl = cl->next) {
  2682. if (parse_dir_server_line(cl->value, 1)<0)
  2683. REJECT("DirServer line did not parse. See logs for details.");
  2684. }
  2685. }
  2686. if (options->UseBridges && !options->Bridges)
  2687. REJECT("If you set UseBridges, you must specify at least one bridge.");
  2688. if (options->UseBridges && !options->TunnelDirConns)
  2689. REJECT("If you set UseBridges, you must set TunnelDirConns.");
  2690. if (options->Bridges) {
  2691. for (cl = options->Bridges; cl; cl = cl->next) {
  2692. if (parse_bridge_line(cl->value, 1)<0)
  2693. REJECT("Bridge line did not parse. See logs for details.");
  2694. }
  2695. }
  2696. if (options->ConstrainedSockets) {
  2697. /* If the user wants to constrain socket buffer use, make sure the desired
  2698. * limit is between MIN|MAX_TCPSOCK_BUFFER in k increments. */
  2699. if (options->ConstrainedSockSize < MIN_CONSTRAINED_TCP_BUFFER ||
  2700. options->ConstrainedSockSize > MAX_CONSTRAINED_TCP_BUFFER ||
  2701. options->ConstrainedSockSize % 1024) {
  2702. r = tor_snprintf(buf, sizeof(buf),
  2703. "ConstrainedSockSize is invalid. Must be a value between %d and %d "
  2704. "in 1024 byte increments.",
  2705. MIN_CONSTRAINED_TCP_BUFFER, MAX_CONSTRAINED_TCP_BUFFER);
  2706. *msg = tor_strdup(r >= 0 ? buf : "internal error");
  2707. return -1;
  2708. }
  2709. if (options->DirPort) {
  2710. /* Providing cached directory entries while system TCP buffers are scarce
  2711. * will exacerbate the socket errors. Suggest that this be disabled. */
  2712. COMPLAIN("You have requested constrained socket buffers while also "
  2713. "serving directory entries via DirPort. It is strongly "
  2714. "suggested that you disable serving directory requests when "
  2715. "system TCP buffer resources are scarce.");
  2716. }
  2717. }
  2718. if (rend_config_services(options, 1) < 0)
  2719. REJECT("Failed to configure rendezvous options. See logs for details.");
  2720. if (parse_virtual_addr_network(options->VirtualAddrNetwork, 1, NULL)<0)
  2721. return -1;
  2722. if (options->PreferTunneledDirConns && !options->TunnelDirConns)
  2723. REJECT("Must set TunnelDirConns if PreferTunneledDirConns is set.");
  2724. if (options->AutomapHostsSuffixes) {
  2725. SMARTLIST_FOREACH(options->AutomapHostsSuffixes, char *, suf,
  2726. {
  2727. size_t len = strlen(suf);
  2728. if (len && suf[len-1] == '.')
  2729. suf[len-1] = '\0';
  2730. });
  2731. }
  2732. return 0;
  2733. #undef REJECT
  2734. #undef COMPLAIN
  2735. }
  2736. /** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
  2737. * equal strings. */
  2738. static int
  2739. opt_streq(const char *s1, const char *s2)
  2740. {
  2741. if (!s1 && !s2)
  2742. return 1;
  2743. else if (s1 && s2 && !strcmp(s1,s2))
  2744. return 1;
  2745. else
  2746. return 0;
  2747. }
  2748. /** Check if any of the previous options have changed but aren't allowed to. */
  2749. static int
  2750. options_transition_allowed(or_options_t *old, or_options_t *new_val,
  2751. char **msg)
  2752. {
  2753. if (!old)
  2754. return 0;
  2755. if (!opt_streq(old->PidFile, new_val->PidFile)) {
  2756. *msg = tor_strdup("PidFile is not allowed to change.");
  2757. return -1;
  2758. }
  2759. if (old->RunAsDaemon != new_val->RunAsDaemon) {
  2760. *msg = tor_strdup("While Tor is running, changing RunAsDaemon "
  2761. "is not allowed.");
  2762. return -1;
  2763. }
  2764. if (strcmp(old->DataDirectory,new_val->DataDirectory)!=0) {
  2765. char buf[1024];
  2766. int r = tor_snprintf(buf, sizeof(buf),
  2767. "While Tor is running, changing DataDirectory "
  2768. "(\"%s\"->\"%s\") is not allowed.",
  2769. old->DataDirectory, new_val->DataDirectory);
  2770. *msg = tor_strdup(r >= 0 ? buf : "internal error");
  2771. return -1;
  2772. }
  2773. if (!opt_streq(old->User, new_val->User)) {
  2774. *msg = tor_strdup("While Tor is running, changing User is not allowed.");
  2775. return -1;
  2776. }
  2777. if (!opt_streq(old->Group, new_val->Group)) {
  2778. *msg = tor_strdup("While Tor is running, changing Group is not allowed.");
  2779. return -1;
  2780. }
  2781. if (old->HardwareAccel != new_val->HardwareAccel) {
  2782. *msg = tor_strdup("While Tor is running, changing HardwareAccel is "
  2783. "not allowed.");
  2784. return -1;
  2785. }
  2786. return 0;
  2787. }
  2788. /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
  2789. * will require us to rotate the cpu and dns workers; else return 0. */
  2790. static int
  2791. options_transition_affects_workers(or_options_t *old_options,
  2792. or_options_t *new_options)
  2793. {
  2794. if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
  2795. old_options->NumCpus != new_options->NumCpus ||
  2796. old_options->ORPort != new_options->ORPort ||
  2797. old_options->ServerDNSSearchDomains !=
  2798. new_options->ServerDNSSearchDomains ||
  2799. old_options->SafeLogging != new_options->SafeLogging ||
  2800. old_options->ClientOnly != new_options->ClientOnly ||
  2801. !config_lines_eq(old_options->Logs, new_options->Logs))
  2802. return 1;
  2803. /* Check whether log options match. */
  2804. /* Nothing that changed matters. */
  2805. return 0;
  2806. }
  2807. /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
  2808. * will require us to generate a new descriptor; else return 0. */
  2809. static int
  2810. options_transition_affects_descriptor(or_options_t *old_options,
  2811. or_options_t *new_options)
  2812. {
  2813. if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
  2814. !opt_streq(old_options->Nickname,new_options->Nickname) ||
  2815. !opt_streq(old_options->Address,new_options->Address) ||
  2816. !config_lines_eq(old_options->ExitPolicy,new_options->ExitPolicy) ||
  2817. old_options->ORPort != new_options->ORPort ||
  2818. old_options->DirPort != new_options->DirPort ||
  2819. old_options->ClientOnly != new_options->ClientOnly ||
  2820. old_options->NoPublish != new_options->NoPublish ||
  2821. old_options->_PublishServerDescriptor !=
  2822. new_options->_PublishServerDescriptor ||
  2823. old_options->BandwidthRate != new_options->BandwidthRate ||
  2824. old_options->BandwidthBurst != new_options->BandwidthBurst ||
  2825. !opt_streq(old_options->ContactInfo, new_options->ContactInfo) ||
  2826. !opt_streq(old_options->MyFamily, new_options->MyFamily) ||
  2827. !opt_streq(old_options->AccountingStart, new_options->AccountingStart) ||
  2828. old_options->AccountingMax != new_options->AccountingMax)
  2829. return 1;
  2830. return 0;
  2831. }
  2832. #ifdef MS_WINDOWS
  2833. /** Return the directory on windows where we expect to find our application
  2834. * data. */
  2835. static char *
  2836. get_windows_conf_root(void)
  2837. {
  2838. static int is_set = 0;
  2839. static char path[MAX_PATH+1];
  2840. LPITEMIDLIST idl;
  2841. IMalloc *m;
  2842. HRESULT result;
  2843. if (is_set)
  2844. return path;
  2845. /* Find X:\documents and settings\username\application data\ .
  2846. * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
  2847. */
  2848. if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL, CSIDL_APPDATA,
  2849. &idl))) {
  2850. GetCurrentDirectory(MAX_PATH, path);
  2851. is_set = 1;
  2852. log_warn(LD_CONFIG,
  2853. "I couldn't find your application data folder: are you "
  2854. "running an ancient version of Windows 95? Defaulting to \"%s\"",
  2855. path);
  2856. return path;
  2857. }
  2858. /* Convert the path from an "ID List" (whatever that is!) to a path. */
  2859. result = SHGetPathFromIDList(idl, path);
  2860. /* Now we need to free the */
  2861. SHGetMalloc(&m);
  2862. if (m) {
  2863. m->lpVtbl->Free(m, idl);
  2864. m->lpVtbl->Release(m);
  2865. }
  2866. if (!SUCCEEDED(result)) {
  2867. return NULL;
  2868. }
  2869. strlcat(path,"\\tor",MAX_PATH);
  2870. is_set = 1;
  2871. return path;
  2872. }
  2873. #endif
  2874. /** Return the default location for our torrc file. */
  2875. static const char *
  2876. get_default_conf_file(void)
  2877. {
  2878. #ifdef MS_WINDOWS
  2879. static char path[MAX_PATH+1];
  2880. strlcpy(path, get_windows_conf_root(), MAX_PATH);
  2881. strlcat(path,"\\torrc",MAX_PATH);
  2882. return path;
  2883. #else
  2884. return (CONFDIR "/torrc");
  2885. #endif
  2886. }
  2887. /** Verify whether lst is a string containing valid-looking space-separated
  2888. * nicknames, or NULL. Return 0 on success. Warn and return -1 on failure.
  2889. */
  2890. static int
  2891. check_nickname_list(const char *lst, const char *name, char **msg)
  2892. {
  2893. int r = 0;
  2894. smartlist_t *sl;
  2895. if (!lst)
  2896. return 0;
  2897. sl = smartlist_create();
  2898. smartlist_split_string(sl, lst, ",", SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2899. SMARTLIST_FOREACH(sl, const char *, s,
  2900. {
  2901. if (!is_legal_nickname_or_hexdigest(s)) {
  2902. char buf[1024];
  2903. int tmp = tor_snprintf(buf, sizeof(buf),
  2904. "Invalid nickname '%s' in %s line", s, name);
  2905. *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
  2906. r = -1;
  2907. break;
  2908. }
  2909. });
  2910. SMARTLIST_FOREACH(sl, char *, s, tor_free(s));
  2911. smartlist_free(sl);
  2912. return r;
  2913. }
  2914. /** Read a configuration file into <b>options</b>, finding the configuration
  2915. * file location based on the command line. After loading the options,
  2916. * validate them for consistency, then take actions based on them.
  2917. * Return 0 if success, -1 if failure. */
  2918. int
  2919. options_init_from_torrc(int argc, char **argv)
  2920. {
  2921. or_options_t *oldoptions, *newoptions;
  2922. config_line_t *cl;
  2923. char *cf=NULL, *fname=NULL, *errmsg=NULL;
  2924. int i, retval;
  2925. int using_default_torrc;
  2926. int ignore_missing_torrc;
  2927. static char **backup_argv;
  2928. static int backup_argc;
  2929. if (argv) { /* first time we're called. save commandline args */
  2930. backup_argv = argv;
  2931. backup_argc = argc;
  2932. oldoptions = NULL;
  2933. } else { /* we're reloading. need to clean up old options first. */
  2934. argv = backup_argv;
  2935. argc = backup_argc;
  2936. oldoptions = get_options();
  2937. }
  2938. if (argc > 1 && (!strcmp(argv[1], "-h") || !strcmp(argv[1],"--help"))) {
  2939. print_usage();
  2940. exit(0);
  2941. }
  2942. if (argc > 1 && !strcmp(argv[1], "--list-torrc-options")) {
  2943. /* For documenting validating whether we've documented everything. */
  2944. list_torrc_options();
  2945. exit(0);
  2946. }
  2947. if (argc > 1 && (!strcmp(argv[1],"--version"))) {
  2948. printf("Tor version %s.\n",get_version());
  2949. if (argc > 2 && (!strcmp(argv[2],"--version"))) {
  2950. print_svn_version();
  2951. }
  2952. exit(0);
  2953. }
  2954. newoptions = tor_malloc_zero(sizeof(or_options_t));
  2955. newoptions->_magic = OR_OPTIONS_MAGIC;
  2956. options_init(newoptions);
  2957. /* learn config file name */
  2958. fname = NULL;
  2959. using_default_torrc = 1;
  2960. ignore_missing_torrc = 0;
  2961. newoptions->command = CMD_RUN_TOR;
  2962. for (i = 1; i < argc; ++i) {
  2963. if (i < argc-1 && !strcmp(argv[i],"-f")) {
  2964. if (fname) {
  2965. log(LOG_WARN, LD_CONFIG, "Duplicate -f options on command line.");
  2966. tor_free(fname);
  2967. }
  2968. #ifdef MS_WINDOWS
  2969. /* XXX one day we might want to extend expand_filename to work
  2970. * under Windows as well. */
  2971. fname = tor_strdup(argv[i+1]);
  2972. #else
  2973. fname = expand_filename(argv[i+1]);
  2974. #endif
  2975. using_default_torrc = 0;
  2976. ++i;
  2977. } else if (!strcmp(argv[i],"--ignore-missing-torrc")) {
  2978. ignore_missing_torrc = 1;
  2979. } else if (!strcmp(argv[i],"--list-fingerprint")) {
  2980. newoptions->command = CMD_LIST_FINGERPRINT;
  2981. } else if (!strcmp(argv[i],"--hash-password")) {
  2982. newoptions->command = CMD_HASH_PASSWORD;
  2983. newoptions->command_arg = tor_strdup( (i < argc-1) ? argv[i+1] : "");
  2984. ++i;
  2985. } else if (!strcmp(argv[i],"--verify-config")) {
  2986. newoptions->command = CMD_VERIFY_CONFIG;
  2987. }
  2988. }
  2989. if (using_default_torrc) {
  2990. /* didn't find one, try CONFDIR */
  2991. const char *dflt = get_default_conf_file();
  2992. if (dflt && file_status(dflt) == FN_FILE) {
  2993. fname = tor_strdup(dflt);
  2994. } else {
  2995. #ifndef MS_WINDOWS
  2996. char *fn;
  2997. fn = expand_filename("~/.torrc");
  2998. if (fn && file_status(fn) == FN_FILE) {
  2999. fname = fn;
  3000. } else {
  3001. tor_free(fn);
  3002. fname = tor_strdup(dflt);
  3003. }
  3004. #else
  3005. fname = tor_strdup(dflt);
  3006. #endif
  3007. }
  3008. }
  3009. tor_assert(fname);
  3010. log(LOG_DEBUG, LD_CONFIG, "Opening config file \"%s\"", fname);
  3011. tor_free(torrc_fname);
  3012. torrc_fname = fname;
  3013. /* get config lines, assign them */
  3014. if (file_status(fname) != FN_FILE ||
  3015. !(cf = read_file_to_str(fname,0,NULL))) {
  3016. if (using_default_torrc == 1 || ignore_missing_torrc ) {
  3017. log(LOG_NOTICE, LD_CONFIG, "Configuration file \"%s\" not present, "
  3018. "using reasonable defaults.", fname);
  3019. tor_free(fname); /* sets fname to NULL */
  3020. torrc_fname = NULL;
  3021. } else {
  3022. log(LOG_WARN, LD_CONFIG,
  3023. "Unable to open configuration file \"%s\".", fname);
  3024. goto err;
  3025. }
  3026. } else { /* it opened successfully. use it. */
  3027. retval = config_get_lines(cf, &cl);
  3028. tor_free(cf);
  3029. if (retval < 0)
  3030. goto err;
  3031. retval = config_assign(&options_format, newoptions, cl, 0, 0, &errmsg);
  3032. config_free_lines(cl);
  3033. if (retval < 0)
  3034. goto err;
  3035. }
  3036. /* Go through command-line variables too */
  3037. if (config_get_commandlines(argc, argv, &cl) < 0)
  3038. goto err;
  3039. retval = config_assign(&options_format, newoptions, cl, 0, 0, &errmsg);
  3040. config_free_lines(cl);
  3041. if (retval < 0)
  3042. goto err;
  3043. /* Validate newoptions */
  3044. if (options_validate(oldoptions, newoptions, 0, &errmsg) < 0)
  3045. goto err;
  3046. if (options_transition_allowed(oldoptions, newoptions, &errmsg) < 0)
  3047. goto err;
  3048. if (set_options(newoptions, &errmsg))
  3049. goto err; /* frees and replaces old options */
  3050. return 0;
  3051. err:
  3052. tor_free(fname);
  3053. torrc_fname = NULL;
  3054. config_free(&options_format, newoptions);
  3055. if (errmsg) {
  3056. log(LOG_WARN,LD_CONFIG,"Failed to parse/validate config: %s", errmsg);
  3057. tor_free(errmsg);
  3058. }
  3059. return -1;
  3060. }
  3061. /** Return the location for our configuration file.
  3062. */
  3063. const char *
  3064. get_torrc_fname(void)
  3065. {
  3066. if (torrc_fname)
  3067. return torrc_fname;
  3068. else
  3069. return get_default_conf_file();
  3070. }
  3071. /** Adjust the address map mased on the MapAddress elements in the
  3072. * configuration <b>options</b>
  3073. */
  3074. static void
  3075. config_register_addressmaps(or_options_t *options)
  3076. {
  3077. smartlist_t *elts;
  3078. config_line_t *opt;
  3079. char *from, *to;
  3080. addressmap_clear_configured();
  3081. elts = smartlist_create();
  3082. for (opt = options->AddressMap; opt; opt = opt->next) {
  3083. smartlist_split_string(elts, opt->value, NULL,
  3084. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
  3085. if (smartlist_len(elts) >= 2) {
  3086. from = smartlist_get(elts,0);
  3087. to = smartlist_get(elts,1);
  3088. if (address_is_invalid_destination(to, 1)) {
  3089. log_warn(LD_CONFIG,
  3090. "Skipping invalid argument '%s' to MapAddress", to);
  3091. } else {
  3092. addressmap_register(from, tor_strdup(to), 0);
  3093. if (smartlist_len(elts)>2) {
  3094. log_warn(LD_CONFIG,"Ignoring extra arguments to MapAddress.");
  3095. }
  3096. }
  3097. } else {
  3098. log_warn(LD_CONFIG,"MapAddress '%s' has too few arguments. Ignoring.",
  3099. opt->value);
  3100. }
  3101. SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
  3102. smartlist_clear(elts);
  3103. }
  3104. smartlist_free(elts);
  3105. }
  3106. /** If <b>range</b> is of the form MIN-MAX, for MIN and MAX both
  3107. * recognized log severity levels, set *<b>min_out</b> to MIN and
  3108. * *<b>max_out</b> to MAX and return 0. Else, if <b>range</b> is of
  3109. * the form MIN, act as if MIN-err had been specified. Else, warn and
  3110. * return -1.
  3111. */
  3112. static int
  3113. parse_log_severity_range(const char *range, int *min_out, int *max_out)
  3114. {
  3115. int levelMin, levelMax;
  3116. const char *cp;
  3117. cp = strchr(range, '-');
  3118. if (cp) {
  3119. if (cp == range) {
  3120. levelMin = LOG_DEBUG;
  3121. } else {
  3122. char *tmp_sev = tor_strndup(range, cp - range);
  3123. levelMin = parse_log_level(tmp_sev);
  3124. if (levelMin < 0) {
  3125. log_warn(LD_CONFIG, "Unrecognized minimum log severity '%s': must be "
  3126. "one of err|warn|notice|info|debug", tmp_sev);
  3127. tor_free(tmp_sev);
  3128. return -1;
  3129. }
  3130. tor_free(tmp_sev);
  3131. }
  3132. if (!*(cp+1)) {
  3133. levelMax = LOG_ERR;
  3134. } else {
  3135. levelMax = parse_log_level(cp+1);
  3136. if (levelMax < 0) {
  3137. log_warn(LD_CONFIG, "Unrecognized maximum log severity '%s': must be "
  3138. "one of err|warn|notice|info|debug", cp+1);
  3139. return -1;
  3140. }
  3141. }
  3142. } else {
  3143. levelMin = parse_log_level(range);
  3144. if (levelMin < 0) {
  3145. log_warn(LD_CONFIG, "Unrecognized log severity '%s': must be one of "
  3146. "err|warn|notice|info|debug", range);
  3147. return -1;
  3148. }
  3149. levelMax = LOG_ERR;
  3150. }
  3151. *min_out = levelMin;
  3152. *max_out = levelMax;
  3153. return 0;
  3154. }
  3155. /**
  3156. * Initialize the logs based on the configuration file.
  3157. */
  3158. int
  3159. options_init_logs(or_options_t *options, int validate_only)
  3160. {
  3161. config_line_t *opt;
  3162. int ok;
  3163. smartlist_t *elts;
  3164. int daemon =
  3165. #ifdef MS_WINDOWS
  3166. 0;
  3167. #else
  3168. options->RunAsDaemon;
  3169. #endif
  3170. ok = 1;
  3171. elts = smartlist_create();
  3172. for (opt = options->Logs; opt; opt = opt->next) {
  3173. int levelMin=LOG_DEBUG, levelMax=LOG_ERR;
  3174. smartlist_split_string(elts, opt->value, NULL,
  3175. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 3);
  3176. if (smartlist_len(elts) == 0) {
  3177. log_warn(LD_CONFIG, "No arguments to Log option 'Log %s'", opt->value);
  3178. ok = 0; goto cleanup;
  3179. }
  3180. if (parse_log_severity_range(smartlist_get(elts,0), &levelMin,
  3181. &levelMax)) {
  3182. ok = 0; goto cleanup;
  3183. }
  3184. if (smartlist_len(elts) < 2) { /* only loglevels were provided */
  3185. if (!validate_only) {
  3186. if (daemon) {
  3187. log_warn(LD_CONFIG,
  3188. "Can't log to stdout with RunAsDaemon set; skipping stdout");
  3189. } else {
  3190. add_stream_log(levelMin, levelMax, "<stdout>", stdout);
  3191. }
  3192. }
  3193. goto cleanup;
  3194. }
  3195. if (!strcasecmp(smartlist_get(elts,1), "file")) {
  3196. if (smartlist_len(elts) != 3) {
  3197. log_warn(LD_CONFIG, "Bad syntax on file Log option 'Log %s'",
  3198. opt->value);
  3199. ok = 0; goto cleanup;
  3200. }
  3201. if (!validate_only) {
  3202. if (add_file_log(levelMin, levelMax, smartlist_get(elts, 2)) < 0) {
  3203. log_warn(LD_CONFIG, "Couldn't open file for 'Log %s'", opt->value);
  3204. ok = 0;
  3205. }
  3206. }
  3207. goto cleanup;
  3208. }
  3209. if (smartlist_len(elts) != 2) {
  3210. log_warn(LD_CONFIG, "Wrong number of arguments on Log option 'Log %s'",
  3211. opt->value);
  3212. ok = 0; goto cleanup;
  3213. }
  3214. if (!strcasecmp(smartlist_get(elts,1), "stdout")) {
  3215. if (daemon) {
  3216. log_warn(LD_CONFIG, "Can't log to stdout with RunAsDaemon set.");
  3217. ok = 0; goto cleanup;
  3218. }
  3219. if (!validate_only) {
  3220. add_stream_log(levelMin, levelMax, "<stdout>", stdout);
  3221. }
  3222. } else if (!strcasecmp(smartlist_get(elts,1), "stderr")) {
  3223. if (daemon) {
  3224. log_warn(LD_CONFIG, "Can't log to stderr with RunAsDaemon set.");
  3225. ok = 0; goto cleanup;
  3226. }
  3227. if (!validate_only) {
  3228. add_stream_log(levelMin, levelMax, "<stderr>", stderr);
  3229. }
  3230. } else if (!strcasecmp(smartlist_get(elts,1), "syslog")) {
  3231. #ifdef HAVE_SYSLOG_H
  3232. if (!validate_only)
  3233. add_syslog_log(levelMin, levelMax);
  3234. #else
  3235. log_warn(LD_CONFIG, "Syslog is not supported on this system. Sorry.");
  3236. #endif
  3237. } else {
  3238. log_warn(LD_CONFIG, "Unrecognized log type %s",
  3239. (const char*)smartlist_get(elts,1));
  3240. if (strchr(smartlist_get(elts,1), '/') ||
  3241. strchr(smartlist_get(elts,1), '\\')) {
  3242. log_warn(LD_CONFIG, "Did you mean to say 'Log %s file %s' ?",
  3243. (const char *)smartlist_get(elts,0),
  3244. (const char *)smartlist_get(elts,1));
  3245. }
  3246. ok = 0; goto cleanup;
  3247. }
  3248. cleanup:
  3249. SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
  3250. smartlist_clear(elts);
  3251. }
  3252. smartlist_free(elts);
  3253. return ok?0:-1;
  3254. }
  3255. /** Parse a single RedirectExit line's contents from <b>line</b>. If
  3256. * they are valid, and <b>result</b> is not NULL, add an element to
  3257. * <b>result</b> and return 0. Else if they are valid, return 0.
  3258. * Else set *msg and return -1. */
  3259. static int
  3260. parse_redirect_line(smartlist_t *result, config_line_t *line, char **msg)
  3261. {
  3262. smartlist_t *elements = NULL;
  3263. exit_redirect_t *r;
  3264. tor_assert(line);
  3265. r = tor_malloc_zero(sizeof(exit_redirect_t));
  3266. elements = smartlist_create();
  3267. smartlist_split_string(elements, line->value, NULL,
  3268. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  3269. if (smartlist_len(elements) != 2) {
  3270. *msg = tor_strdup("Wrong number of elements in RedirectExit line");
  3271. goto err;
  3272. }
  3273. if (parse_addr_and_port_range(smartlist_get(elements,0),&r->addr,
  3274. &r->maskbits,&r->port_min,&r->port_max)) {
  3275. *msg = tor_strdup("Error parsing source address in RedirectExit line");
  3276. goto err;
  3277. }
  3278. if (0==strcasecmp(smartlist_get(elements,1), "pass")) {
  3279. r->is_redirect = 0;
  3280. } else {
  3281. if (parse_addr_port(LOG_WARN, smartlist_get(elements,1),NULL,
  3282. &r->addr_dest, &r->port_dest)) {
  3283. *msg = tor_strdup("Error parsing dest address in RedirectExit line");
  3284. goto err;
  3285. }
  3286. r->is_redirect = 1;
  3287. }
  3288. goto done;
  3289. err:
  3290. tor_free(r);
  3291. done:
  3292. SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
  3293. smartlist_free(elements);
  3294. if (r) {
  3295. if (result)
  3296. smartlist_add(result, r);
  3297. else
  3298. tor_free(r);
  3299. return 0;
  3300. } else {
  3301. tor_assert(*msg);
  3302. return -1;
  3303. }
  3304. }
  3305. /** Read the contents of a Bridge line from <b>line</b>. Return 0
  3306. * if the line is well-formed, and -1 if it isn't. If
  3307. * <b>validate_only</b> is 0, and the line is well-formed, then add
  3308. * the bridge described in the line to our internal bridge list. */
  3309. static int
  3310. parse_bridge_line(const char *line, int validate_only)
  3311. {
  3312. smartlist_t *items = NULL;
  3313. int r;
  3314. char *addrport=NULL, *address=NULL, *fingerprint=NULL;
  3315. uint32_t addr = 0;
  3316. uint16_t port = 0;
  3317. char digest[DIGEST_LEN];
  3318. items = smartlist_create();
  3319. smartlist_split_string(items, line, NULL,
  3320. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
  3321. if (smartlist_len(items) < 1) {
  3322. log_warn(LD_CONFIG, "Too few arguments to Bridge line.");
  3323. goto err;
  3324. }
  3325. addrport = smartlist_get(items, 0);
  3326. smartlist_del_keeporder(items, 0);
  3327. if (parse_addr_port(LOG_WARN, addrport, &address, &addr, &port)<0) {
  3328. log_warn(LD_CONFIG, "Error parsing Bridge address '%s'", addrport);
  3329. goto err;
  3330. }
  3331. if (!port) {
  3332. log_warn(LD_CONFIG, "Missing port in Bridge address '%s'",addrport);
  3333. goto err;
  3334. }
  3335. if (smartlist_len(items)) {
  3336. fingerprint = smartlist_join_strings(items, "", 0, NULL);
  3337. if (strlen(fingerprint) != HEX_DIGEST_LEN) {
  3338. log_warn(LD_CONFIG, "Key digest for Bridge is wrong length.");
  3339. goto err;
  3340. }
  3341. if (base16_decode(digest, DIGEST_LEN, fingerprint, HEX_DIGEST_LEN)<0) {
  3342. log_warn(LD_CONFIG, "Unable to decode Bridge key digest.");
  3343. goto err;
  3344. }
  3345. }
  3346. if (!validate_only) {
  3347. log_debug(LD_DIR, "Bridge at %s:%d (%s)", address,
  3348. (int)port,
  3349. fingerprint ? fingerprint : "no key listed");
  3350. bridge_add_from_config(addr, port, fingerprint ? digest : NULL);
  3351. }
  3352. r = 0;
  3353. goto done;
  3354. err:
  3355. r = -1;
  3356. done:
  3357. SMARTLIST_FOREACH(items, char*, s, tor_free(s));
  3358. smartlist_free(items);
  3359. tor_free(addrport);
  3360. tor_free(address);
  3361. tor_free(fingerprint);
  3362. return r;
  3363. }
  3364. /** Read the contents of a DirServer line from <b>line</b>. Return 0
  3365. * if the line is well-formed, and -1 if it isn't. If
  3366. * <b>validate_only</b> is 0, and the line is well-formed, then add
  3367. * the dirserver described in the line as a valid authority. */
  3368. static int
  3369. parse_dir_server_line(const char *line, int validate_only)
  3370. {
  3371. smartlist_t *items = NULL;
  3372. int r;
  3373. char *addrport=NULL, *address=NULL, *nickname=NULL, *fingerprint=NULL;
  3374. uint16_t dir_port = 0, or_port = 0;
  3375. char digest[DIGEST_LEN];
  3376. char v3_digest[DIGEST_LEN];
  3377. authority_type_t type = V2_AUTHORITY;
  3378. int is_not_hidserv_authority = 0, is_not_v2_authority = 0;
  3379. items = smartlist_create();
  3380. smartlist_split_string(items, line, NULL,
  3381. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
  3382. if (smartlist_len(items) < 1) {
  3383. log_warn(LD_CONFIG, "No arguments on DirServer line.");
  3384. goto err;
  3385. }
  3386. if (is_legal_nickname(smartlist_get(items, 0))) {
  3387. nickname = smartlist_get(items, 0);
  3388. smartlist_del_keeporder(items, 0);
  3389. }
  3390. while (smartlist_len(items)) {
  3391. char *flag = smartlist_get(items, 0);
  3392. if (TOR_ISDIGIT(flag[0]))
  3393. break;
  3394. if (!strcasecmp(flag, "v1")) {
  3395. type |= (V1_AUTHORITY | HIDSERV_AUTHORITY);
  3396. } else if (!strcasecmp(flag, "hs")) {
  3397. type |= HIDSERV_AUTHORITY;
  3398. } else if (!strcasecmp(flag, "no-hs")) {
  3399. is_not_hidserv_authority = 1;
  3400. } else if (!strcasecmp(flag, "bridge")) {
  3401. type |= BRIDGE_AUTHORITY;
  3402. } else if (!strcasecmp(flag, "no-v2")) {
  3403. is_not_v2_authority = 1;
  3404. } else if (!strcasecmpstart(flag, "orport=")) {
  3405. int ok;
  3406. char *portstring = flag + strlen("orport=");
  3407. or_port = (uint16_t) tor_parse_long(portstring, 10, 1, 65535, &ok, NULL);
  3408. if (!ok)
  3409. log_warn(LD_CONFIG, "Invalid orport '%s' on DirServer line.",
  3410. portstring);
  3411. } else if (!strcasecmpstart(flag, "v3ident=")) {
  3412. char *idstr = flag + strlen("v3ident=");
  3413. if (strlen(idstr) != HEX_DIGEST_LEN ||
  3414. base16_decode(v3_digest, DIGEST_LEN, idstr, HEX_DIGEST_LEN)<0) {
  3415. log_warn(LD_CONFIG, "Bad v3 identity digest '%s' on DirServer line",
  3416. flag);
  3417. } else {
  3418. type |= V3_AUTHORITY;
  3419. }
  3420. } else {
  3421. log_warn(LD_CONFIG, "Unrecognized flag '%s' on DirServer line",
  3422. flag);
  3423. }
  3424. tor_free(flag);
  3425. smartlist_del_keeporder(items, 0);
  3426. }
  3427. if (is_not_hidserv_authority)
  3428. type &= ~HIDSERV_AUTHORITY;
  3429. if (is_not_v2_authority)
  3430. type &= ~V2_AUTHORITY;
  3431. if (smartlist_len(items) < 2) {
  3432. log_warn(LD_CONFIG, "Too few arguments to DirServer line.");
  3433. goto err;
  3434. }
  3435. addrport = smartlist_get(items, 0);
  3436. smartlist_del_keeporder(items, 0);
  3437. if (parse_addr_port(LOG_WARN, addrport, &address, NULL, &dir_port)<0) {
  3438. log_warn(LD_CONFIG, "Error parsing DirServer address '%s'", addrport);
  3439. goto err;
  3440. }
  3441. if (!dir_port) {
  3442. log_warn(LD_CONFIG, "Missing port in DirServer address '%s'",addrport);
  3443. goto err;
  3444. }
  3445. fingerprint = smartlist_join_strings(items, "", 0, NULL);
  3446. if (strlen(fingerprint) != HEX_DIGEST_LEN) {
  3447. log_warn(LD_CONFIG, "Key digest for DirServer is wrong length %d.",
  3448. (int)strlen(fingerprint));
  3449. goto err;
  3450. }
  3451. if (base16_decode(digest, DIGEST_LEN, fingerprint, HEX_DIGEST_LEN)<0) {
  3452. log_warn(LD_CONFIG, "Unable to decode DirServer key digest.");
  3453. goto err;
  3454. }
  3455. if (!validate_only) {
  3456. log_debug(LD_DIR, "Trusted dirserver at %s:%d (%s)", address,
  3457. (int)dir_port,
  3458. (char*)smartlist_get(items,0));
  3459. add_trusted_dir_server(nickname, address, dir_port, or_port, digest, type);
  3460. }
  3461. r = 0;
  3462. goto done;
  3463. err:
  3464. r = -1;
  3465. done:
  3466. SMARTLIST_FOREACH(items, char*, s, tor_free(s));
  3467. smartlist_free(items);
  3468. tor_free(addrport);
  3469. tor_free(address);
  3470. tor_free(nickname);
  3471. tor_free(fingerprint);
  3472. return r;
  3473. }
  3474. /** Adjust the value of options->DataDirectory, or fill it in if it's
  3475. * absent. Return 0 on success, -1 on failure. */
  3476. static int
  3477. normalize_data_directory(or_options_t *options)
  3478. {
  3479. #ifdef MS_WINDOWS
  3480. char *p;
  3481. if (options->DataDirectory)
  3482. return 0; /* all set */
  3483. p = tor_malloc(MAX_PATH);
  3484. strlcpy(p,get_windows_conf_root(),MAX_PATH);
  3485. options->DataDirectory = p;
  3486. return 0;
  3487. #else
  3488. const char *d = options->DataDirectory;
  3489. if (!d)
  3490. d = "~/.tor";
  3491. if (strncmp(d,"~/",2) == 0) {
  3492. char *fn = expand_filename(d);
  3493. if (!fn) {
  3494. log_warn(LD_CONFIG,"Failed to expand filename \"%s\".", d);
  3495. return -1;
  3496. }
  3497. if (!options->DataDirectory && !strcmp(fn,"/.tor")) {
  3498. /* If our homedir is /, we probably don't want to use it. */
  3499. /* Default to LOCALSTATEDIR/tor which is probably closer to what we
  3500. * want. */
  3501. log_warn(LD_CONFIG,
  3502. "Default DataDirectory is \"~/.tor\". This expands to "
  3503. "\"%s\", which is probably not what you want. Using "
  3504. "\"%s"PATH_SEPARATOR"tor\" instead", fn, LOCALSTATEDIR);
  3505. tor_free(fn);
  3506. fn = tor_strdup(LOCALSTATEDIR PATH_SEPARATOR "tor");
  3507. }
  3508. tor_free(options->DataDirectory);
  3509. options->DataDirectory = fn;
  3510. }
  3511. return 0;
  3512. #endif
  3513. }
  3514. /** Check and normalize the value of options->DataDirectory; return 0 if it
  3515. * sane, -1 otherwise. */
  3516. static int
  3517. validate_data_directory(or_options_t *options)
  3518. {
  3519. if (normalize_data_directory(options) < 0)
  3520. return -1;
  3521. tor_assert(options->DataDirectory);
  3522. if (strlen(options->DataDirectory) > (512-128)) {
  3523. log_warn(LD_CONFIG, "DataDirectory is too long.");
  3524. return -1;
  3525. }
  3526. return 0;
  3527. }
  3528. /** This string must remain the same forevermore. It is how we
  3529. * recognize that the torrc file doesn't need to be backed up. */
  3530. #define GENERATED_FILE_PREFIX "# This file was generated by Tor; " \
  3531. "if you edit it, comments will not be preserved"
  3532. /** This string can change; it tries to give the reader an idea
  3533. * that editing this file by hand is not a good plan. */
  3534. #define GENERATED_FILE_COMMENT "# The old torrc file was renamed " \
  3535. "to torrc.orig.1 or similar, and Tor will ignore it"
  3536. /** Save a configuration file for the configuration in <b>options</b>
  3537. * into the file <b>fname</b>. If the file already exists, and
  3538. * doesn't begin with GENERATED_FILE_PREFIX, rename it. Otherwise
  3539. * replace it. Return 0 on success, -1 on failure. */
  3540. static int
  3541. write_configuration_file(const char *fname, or_options_t *options)
  3542. {
  3543. char *old_val=NULL, *new_val=NULL, *new_conf=NULL;
  3544. int rename_old = 0, r;
  3545. size_t len;
  3546. if (fname) {
  3547. switch (file_status(fname)) {
  3548. case FN_FILE:
  3549. old_val = read_file_to_str(fname, 0, NULL);
  3550. if (strcmpstart(old_val, GENERATED_FILE_PREFIX)) {
  3551. rename_old = 1;
  3552. }
  3553. tor_free(old_val);
  3554. break;
  3555. case FN_NOENT:
  3556. break;
  3557. case FN_ERROR:
  3558. case FN_DIR:
  3559. default:
  3560. log_warn(LD_CONFIG,
  3561. "Config file \"%s\" is not a file? Failing.", fname);
  3562. return -1;
  3563. }
  3564. }
  3565. if (!(new_conf = options_dump(options, 1))) {
  3566. log_warn(LD_BUG, "Couldn't get configuration string");
  3567. goto err;
  3568. }
  3569. len = strlen(new_conf)+256;
  3570. new_val = tor_malloc(len);
  3571. tor_snprintf(new_val, len, "%s\n%s\n\n%s",
  3572. GENERATED_FILE_PREFIX, GENERATED_FILE_COMMENT, new_conf);
  3573. if (rename_old) {
  3574. int i = 1;
  3575. size_t fn_tmp_len = strlen(fname)+32;
  3576. char *fn_tmp;
  3577. tor_assert(fn_tmp_len > strlen(fname)); /*check for overflow*/
  3578. fn_tmp = tor_malloc(fn_tmp_len);
  3579. while (1) {
  3580. if (tor_snprintf(fn_tmp, fn_tmp_len, "%s.orig.%d", fname, i)<0) {
  3581. log_warn(LD_BUG, "tor_snprintf failed inexplicably");
  3582. tor_free(fn_tmp);
  3583. goto err;
  3584. }
  3585. if (file_status(fn_tmp) == FN_NOENT)
  3586. break;
  3587. ++i;
  3588. }
  3589. log_notice(LD_CONFIG, "Renaming old configuration file to \"%s\"", fn_tmp);
  3590. if (rename(fname, fn_tmp) < 0) {
  3591. log_warn(LD_FS,
  3592. "Couldn't rename configuration file \"%s\" to \"%s\": %s",
  3593. fname, fn_tmp, strerror(errno));
  3594. tor_free(fn_tmp);
  3595. goto err;
  3596. }
  3597. tor_free(fn_tmp);
  3598. }
  3599. if (write_str_to_file(fname, new_val, 0) < 0)
  3600. goto err;
  3601. r = 0;
  3602. goto done;
  3603. err:
  3604. r = -1;
  3605. done:
  3606. tor_free(new_val);
  3607. tor_free(new_conf);
  3608. return r;
  3609. }
  3610. /**
  3611. * Save the current configuration file value to disk. Return 0 on
  3612. * success, -1 on failure.
  3613. **/
  3614. int
  3615. options_save_current(void)
  3616. {
  3617. if (torrc_fname) {
  3618. /* This fails if we can't write to our configuration file.
  3619. *
  3620. * If we try falling back to datadirectory or something, we have a better
  3621. * chance of saving the configuration, but a better chance of doing
  3622. * something the user never expected. Let's just warn instead. */
  3623. return write_configuration_file(torrc_fname, get_options());
  3624. }
  3625. return write_configuration_file(get_default_conf_file(), get_options());
  3626. }
  3627. /** Mapping from a unit name to a multiplier for converting that unit into a
  3628. * base unit. */
  3629. struct unit_table_t {
  3630. const char *unit;
  3631. uint64_t multiplier;
  3632. };
  3633. static struct unit_table_t memory_units[] = {
  3634. { "", 1 },
  3635. { "b", 1<< 0 },
  3636. { "byte", 1<< 0 },
  3637. { "bytes", 1<< 0 },
  3638. { "kb", 1<<10 },
  3639. { "kilobyte", 1<<10 },
  3640. { "kilobytes", 1<<10 },
  3641. { "m", 1<<20 },
  3642. { "mb", 1<<20 },
  3643. { "megabyte", 1<<20 },
  3644. { "megabytes", 1<<20 },
  3645. { "gb", 1<<30 },
  3646. { "gigabyte", 1<<30 },
  3647. { "gigabytes", 1<<30 },
  3648. { "tb", U64_LITERAL(1)<<40 },
  3649. { "terabyte", U64_LITERAL(1)<<40 },
  3650. { "terabytes", U64_LITERAL(1)<<40 },
  3651. { NULL, 0 },
  3652. };
  3653. static struct unit_table_t time_units[] = {
  3654. { "", 1 },
  3655. { "second", 1 },
  3656. { "seconds", 1 },
  3657. { "minute", 60 },
  3658. { "minutes", 60 },
  3659. { "hour", 60*60 },
  3660. { "hours", 60*60 },
  3661. { "day", 24*60*60 },
  3662. { "days", 24*60*60 },
  3663. { "week", 7*24*60*60 },
  3664. { "weeks", 7*24*60*60 },
  3665. { NULL, 0 },
  3666. };
  3667. /** Parse a string <b>val</b> containing a number, zero or more
  3668. * spaces, and an optional unit string. If the unit appears in the
  3669. * table <b>u</b>, then multiply the number by the unit multiplier.
  3670. * On success, set *<b>ok</b> to 1 and return this product.
  3671. * Otherwise, set *<b>ok</b> to 0.
  3672. */
  3673. static uint64_t
  3674. config_parse_units(const char *val, struct unit_table_t *u, int *ok)
  3675. {
  3676. uint64_t v;
  3677. char *cp;
  3678. tor_assert(ok);
  3679. v = tor_parse_uint64(val, 10, 0, UINT64_MAX, ok, &cp);
  3680. if (!*ok)
  3681. return 0;
  3682. if (!cp) {
  3683. *ok = 1;
  3684. return v;
  3685. }
  3686. while (TOR_ISSPACE(*cp))
  3687. ++cp;
  3688. for ( ;u->unit;++u) {
  3689. if (!strcasecmp(u->unit, cp)) {
  3690. v *= u->multiplier;
  3691. *ok = 1;
  3692. return v;
  3693. }
  3694. }
  3695. log_warn(LD_CONFIG, "Unknown unit '%s'.", cp);
  3696. *ok = 0;
  3697. return 0;
  3698. }
  3699. /** Parse a string in the format "number unit", where unit is a unit of
  3700. * information (byte, KB, M, etc). On success, set *<b>ok</b> to true
  3701. * and return the number of bytes specified. Otherwise, set
  3702. * *<b>ok</b> to false and return 0. */
  3703. static uint64_t
  3704. config_parse_memunit(const char *s, int *ok)
  3705. {
  3706. return config_parse_units(s, memory_units, ok);
  3707. }
  3708. /** Parse a string in the format "number unit", where unit is a unit of time.
  3709. * On success, set *<b>ok</b> to true and return the number of seconds in
  3710. * the provided interval. Otherwise, set *<b>ok</b> to 0 and return -1.
  3711. */
  3712. static int
  3713. config_parse_interval(const char *s, int *ok)
  3714. {
  3715. uint64_t r;
  3716. r = config_parse_units(s, time_units, ok);
  3717. if (!ok)
  3718. return -1;
  3719. if (r > INT_MAX) {
  3720. log_warn(LD_CONFIG, "Interval '%s' is too long", s);
  3721. *ok = 0;
  3722. return -1;
  3723. }
  3724. return (int)r;
  3725. }
  3726. /**
  3727. * Initialize the libevent library.
  3728. */
  3729. static void
  3730. init_libevent(void)
  3731. {
  3732. configure_libevent_logging();
  3733. /* If the kernel complains that some method (say, epoll) doesn't
  3734. * exist, we don't care about it, since libevent will cope.
  3735. */
  3736. suppress_libevent_log_msg("Function not implemented");
  3737. #ifdef __APPLE__
  3738. if (decode_libevent_version() < LE_11B) {
  3739. setenv("EVENT_NOKQUEUE","1",1);
  3740. } else if (!getenv("EVENT_NOKQUEUE")) {
  3741. const char *ver = NULL;
  3742. #ifdef HAVE_EVENT_GET_VERSION
  3743. ver = event_get_version();
  3744. #endif
  3745. /* If we're 1.1b or later, we'd better have get_version() */
  3746. tor_assert(ver);
  3747. log(LOG_NOTICE, LD_GENERAL, "Enabling experimental OS X kqueue support "
  3748. "with libevent %s. If this turns out to not work, "
  3749. "set the environment variable EVENT_NOKQUEUE, and tell the Tor "
  3750. "developers.", ver);
  3751. }
  3752. #endif
  3753. event_init();
  3754. suppress_libevent_log_msg(NULL);
  3755. #if defined(HAVE_EVENT_GET_VERSION) && defined(HAVE_EVENT_GET_METHOD)
  3756. /* Making this a NOTICE for now so we can link bugs to a libevent versions
  3757. * or methods better. */
  3758. log(LOG_NOTICE, LD_GENERAL,
  3759. "Initialized libevent version %s using method %s. Good.",
  3760. event_get_version(), event_get_method());
  3761. check_libevent_version(event_get_method(), get_options()->ORPort != 0);
  3762. #else
  3763. log(LOG_NOTICE, LD_GENERAL,
  3764. "Initialized old libevent (version 1.0b or earlier).");
  3765. log(LOG_WARN, LD_GENERAL,
  3766. "You have a *VERY* old version of libevent. It is likely to be buggy; "
  3767. "please build Tor with a more recent version.");
  3768. #endif
  3769. }
  3770. #if defined(HAVE_EVENT_GET_VERSION) && defined(HAVE_EVENT_GET_METHOD)
  3771. /** Table mapping return value of event_get_version() to le_version_t. */
  3772. static const struct {
  3773. const char *name; le_version_t version;
  3774. } le_version_table[] = {
  3775. /* earlier versions don't have get_version. */
  3776. { "1.0c", LE_10C },
  3777. { "1.0d", LE_10D },
  3778. { "1.0e", LE_10E },
  3779. { "1.1", LE_11 },
  3780. { "1.1a", LE_11A },
  3781. { "1.1b", LE_11B },
  3782. { "1.2", LE_12 },
  3783. { "1.2a", LE_12A },
  3784. { "1.3", LE_13 },
  3785. { "1.3a", LE_13A },
  3786. { "1.3b", LE_13B },
  3787. { NULL, LE_OTHER }
  3788. };
  3789. /** Return the le_version_t for the current version of libevent. If the
  3790. * version is very new, return LE_OTHER. If the version is so old that it
  3791. * doesn't support event_get_version(), return LE_OLD. */
  3792. static le_version_t
  3793. decode_libevent_version(void)
  3794. {
  3795. const char *v = event_get_version();
  3796. int i;
  3797. for (i=0; le_version_table[i].name; ++i) {
  3798. if (!strcmp(le_version_table[i].name, v)) {
  3799. return le_version_table[i].version;
  3800. }
  3801. }
  3802. return LE_OTHER;
  3803. }
  3804. /**
  3805. * Compare the given libevent method and version to a list of versions
  3806. * which are known not to work. Warn the user as appropriate.
  3807. */
  3808. static void
  3809. check_libevent_version(const char *m, int server)
  3810. {
  3811. int buggy = 0, iffy = 0, slow = 0, thread_unsafe = 0;
  3812. le_version_t version;
  3813. const char *v = event_get_version();
  3814. const char *badness = NULL;
  3815. const char *sad_os = "";
  3816. version = decode_libevent_version();
  3817. /* XXX Would it be worthwhile disabling the methods that we know
  3818. * are buggy, rather than just warning about them and then proceeding
  3819. * to use them? If so, we should probably not wrap this whole thing
  3820. * in HAVE_EVENT_GET_VERSION and HAVE_EVENT_GET_METHOD. -RD */
  3821. /* XXXX The problem is that it's not trivial to get libevent to change it's
  3822. * method once it's initialized, and it's not trivial to tell what method it
  3823. * will use without initializing it. I guess we could preemptively disable
  3824. * buggy libevent modes based on the version _before_ initializing it,
  3825. * though, but then there's no good way (afaict) to warn "I would have used
  3826. * kqueue, but instead I'm using select." -NM */
  3827. if (!strcmp(m, "kqueue")) {
  3828. if (version < LE_11B)
  3829. buggy = 1;
  3830. } else if (!strcmp(m, "epoll")) {
  3831. if (version < LE_11)
  3832. iffy = 1;
  3833. } else if (!strcmp(m, "poll")) {
  3834. if (version < LE_10E)
  3835. buggy = 1;
  3836. else if (version < LE_11)
  3837. slow = 1;
  3838. } else if (!strcmp(m, "select")) {
  3839. if (version < LE_11)
  3840. slow = 1;
  3841. } else if (!strcmp(m, "win32")) {
  3842. if (version < LE_11B)
  3843. buggy = 1;
  3844. }
  3845. /* Libevent versions before 1.3b do very badly on operating systems with
  3846. * user-space threading implementations. */
  3847. #if defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__)
  3848. if (server && version < LE_13B) {
  3849. thread_unsafe = 1;
  3850. sad_os = "BSD variants";
  3851. }
  3852. #elif defined(__APPLE__) || defined(__darwin__)
  3853. if (server && version < LE_13B) {
  3854. thread_unsafe = 1;
  3855. sad_os = "Mac OS X";
  3856. }
  3857. #endif
  3858. if (thread_unsafe) {
  3859. log(LOG_WARN, LD_GENERAL,
  3860. "Libevent version %s often crashes when running a Tor server with %s. "
  3861. "Please use the latest version of libevent (1.3b or later)",v,sad_os);
  3862. badness = "BROKEN";
  3863. } else if (buggy) {
  3864. log(LOG_WARN, LD_GENERAL,
  3865. "There are known bugs in using %s with libevent %s. "
  3866. "Please use the latest version of libevent.", m, v);
  3867. badness = "BROKEN";
  3868. } else if (iffy) {
  3869. log(LOG_WARN, LD_GENERAL,
  3870. "There are minor bugs in using %s with libevent %s. "
  3871. "You may want to use the latest version of libevent.", m, v);
  3872. badness = "BUGGY";
  3873. } else if (slow && server) {
  3874. log(LOG_WARN, LD_GENERAL,
  3875. "libevent %s can be very slow with %s. "
  3876. "When running a server, please use the latest version of libevent.",
  3877. v,m);
  3878. badness = "SLOW";
  3879. }
  3880. if (badness) {
  3881. control_event_general_status(LOG_WARN,
  3882. "BAD_LIBEVENT VERSION=%s METHOD=%s BADNESS=%s RECOVERED=NO",
  3883. v, m, badness);
  3884. }
  3885. }
  3886. #else
  3887. static le_version_t
  3888. decode_libevent_version(void)
  3889. {
  3890. return LE_OLD;
  3891. }
  3892. #endif
  3893. /** Return the persistent state struct for this Tor. */
  3894. or_state_t *
  3895. get_or_state(void)
  3896. {
  3897. tor_assert(global_state);
  3898. return global_state;
  3899. }
  3900. /** Return the filename used to write and read the persistent state. */
  3901. static char *
  3902. get_or_state_fname(void)
  3903. {
  3904. char *fname = NULL;
  3905. or_options_t *options = get_options();
  3906. size_t len = strlen(options->DataDirectory) + 16;
  3907. fname = tor_malloc(len);
  3908. tor_snprintf(fname, len, "%s"PATH_SEPARATOR"state", options->DataDirectory);
  3909. return fname;
  3910. }
  3911. /** Return 0 if every setting in <b>state</b> is reasonable, and a
  3912. * permissible transition from <b>old_state</b>. Else warn and return -1.
  3913. * Should have no side effects, except for normalizing the contents of
  3914. * <b>state</b>.
  3915. */
  3916. /* XXX from_setconf is here because of bug 238 */
  3917. static int
  3918. or_state_validate(or_state_t *old_state, or_state_t *state,
  3919. int from_setconf, char **msg)
  3920. {
  3921. /* We don't use these; only options do. Still, we need to match that
  3922. * signature. */
  3923. (void) from_setconf;
  3924. (void) old_state;
  3925. if (entry_guards_parse_state(state, 0, msg)<0) {
  3926. return -1;
  3927. }
  3928. if (state->TorVersion) {
  3929. tor_version_t v;
  3930. if (tor_version_parse(state->TorVersion, &v)) {
  3931. log_warn(LD_GENERAL, "Can't parse Tor version '%s' from your state "
  3932. "file. Proceeding anyway.", state->TorVersion);
  3933. } else { /* take action based on v */
  3934. if (tor_version_as_new_as(state->TorVersion, "0.1.1.10-alpha") &&
  3935. !tor_version_as_new_as(state->TorVersion, "0.1.1.16-rc-cvs")) {
  3936. log_notice(LD_CONFIG, "Detected state file from buggy version '%s'. "
  3937. "Enabling workaround to choose working entry guards.",
  3938. state->TorVersion);
  3939. config_free_lines(state->EntryGuards);
  3940. state->EntryGuards = NULL;
  3941. }
  3942. }
  3943. }
  3944. return 0;
  3945. }
  3946. /** Replace the current persistent state with <b>new_state</b> */
  3947. static void
  3948. or_state_set(or_state_t *new_state)
  3949. {
  3950. char *err = NULL;
  3951. tor_assert(new_state);
  3952. if (global_state)
  3953. config_free(&state_format, global_state);
  3954. global_state = new_state;
  3955. if (entry_guards_parse_state(global_state, 1, &err)<0) {
  3956. log_warn(LD_GENERAL,"%s",err);
  3957. tor_free(err);
  3958. }
  3959. if (rep_hist_load_state(global_state, &err)<0) {
  3960. log_warn(LD_GENERAL,"Unparseable bandwidth history state: %s",err);
  3961. tor_free(err);
  3962. }
  3963. }
  3964. /** Reload the persistent state from disk, generating a new state as needed.
  3965. * Return 0 on success, less than 0 on failure.
  3966. */
  3967. int
  3968. or_state_load(void)
  3969. {
  3970. or_state_t *new_state = NULL;
  3971. char *contents = NULL, *fname;
  3972. char *errmsg = NULL;
  3973. int r = -1, badstate = 0;
  3974. fname = get_or_state_fname();
  3975. switch (file_status(fname)) {
  3976. case FN_FILE:
  3977. if (!(contents = read_file_to_str(fname, 0, NULL))) {
  3978. log_warn(LD_FS, "Unable to read state file \"%s\"", fname);
  3979. goto done;
  3980. }
  3981. break;
  3982. case FN_NOENT:
  3983. break;
  3984. case FN_ERROR:
  3985. case FN_DIR:
  3986. default:
  3987. log_warn(LD_GENERAL,"State file \"%s\" is not a file? Failing.", fname);
  3988. goto done;
  3989. }
  3990. new_state = tor_malloc_zero(sizeof(or_state_t));
  3991. new_state->_magic = OR_STATE_MAGIC;
  3992. config_init(&state_format, new_state);
  3993. if (contents) {
  3994. config_line_t *lines=NULL;
  3995. int assign_retval;
  3996. if (config_get_lines(contents, &lines)<0)
  3997. goto done;
  3998. assign_retval = config_assign(&state_format, new_state,
  3999. lines, 0, 0, &errmsg);
  4000. config_free_lines(lines);
  4001. if (assign_retval<0)
  4002. badstate = 1;
  4003. if (errmsg) {
  4004. log_warn(LD_GENERAL, "%s", errmsg);
  4005. tor_free(errmsg);
  4006. }
  4007. }
  4008. if (!badstate && or_state_validate(NULL, new_state, 1, &errmsg) < 0)
  4009. badstate = 1;
  4010. if (errmsg) {
  4011. log_warn(LD_GENERAL, "%s", errmsg);
  4012. tor_free(errmsg);
  4013. }
  4014. if (badstate && !contents) {
  4015. log_warn(LD_BUG, "Uh oh. We couldn't even validate our own default state."
  4016. " This is a bug in Tor.");
  4017. goto done;
  4018. } else if (badstate && contents) {
  4019. int i;
  4020. file_status_t status;
  4021. size_t len = strlen(fname)+16;
  4022. char *fname2 = tor_malloc(len);
  4023. for (i = 0; i < 100; ++i) {
  4024. tor_snprintf(fname2, len, "%s.%d", fname, i);
  4025. status = file_status(fname2);
  4026. if (status == FN_NOENT)
  4027. break;
  4028. }
  4029. if (i == 100) {
  4030. log_warn(LD_BUG, "Unable to parse state in \"%s\"; too many saved bad "
  4031. "state files to move aside. Discarding the old state file.",
  4032. fname);
  4033. unlink(fname);
  4034. } else {
  4035. log_warn(LD_BUG, "Unable to parse state in \"%s\". Moving it aside "
  4036. "to \"%s\". This could be a bug in Tor; please tell "
  4037. "the developers.", fname, fname2);
  4038. rename(fname, fname2);
  4039. }
  4040. tor_free(fname2);
  4041. tor_free(contents);
  4042. config_free(&state_format, new_state);
  4043. new_state = tor_malloc_zero(sizeof(or_state_t));
  4044. new_state->_magic = OR_STATE_MAGIC;
  4045. config_init(&state_format, new_state);
  4046. } else if (contents) {
  4047. log_info(LD_GENERAL, "Loaded state from \"%s\"", fname);
  4048. } else {
  4049. log_info(LD_GENERAL, "Initialized state");
  4050. }
  4051. or_state_set(new_state);
  4052. new_state = NULL;
  4053. if (!contents) {
  4054. global_state->next_write = 0;
  4055. or_state_save(time(NULL));
  4056. }
  4057. r = 0;
  4058. done:
  4059. tor_free(fname);
  4060. tor_free(contents);
  4061. if (new_state)
  4062. config_free(&state_format, new_state);
  4063. return r;
  4064. }
  4065. /** Write the persistent state to disk. Return 0 for success, <0 on failure. */
  4066. int
  4067. or_state_save(time_t now)
  4068. {
  4069. char *state, *contents;
  4070. char tbuf[ISO_TIME_LEN+1];
  4071. size_t len;
  4072. char *fname;
  4073. tor_assert(global_state);
  4074. if (global_state->next_write > now)
  4075. return 0;
  4076. /* Call everything else that might dirty the state even more, in order
  4077. * to avoid redundant writes. */
  4078. entry_guards_update_state(global_state);
  4079. rep_hist_update_state(global_state);
  4080. if (accounting_is_enabled(get_options()))
  4081. accounting_run_housekeeping(now);
  4082. global_state->LastWritten = time(NULL);
  4083. tor_free(global_state->TorVersion);
  4084. len = strlen(get_version())+8;
  4085. global_state->TorVersion = tor_malloc(len);
  4086. tor_snprintf(global_state->TorVersion, len, "Tor %s", get_version());
  4087. state = config_dump(&state_format, global_state, 1, 0);
  4088. len = strlen(state)+256;
  4089. contents = tor_malloc(len);
  4090. format_local_iso_time(tbuf, time(NULL));
  4091. tor_snprintf(contents, len,
  4092. "# Tor state file last generated on %s local time\n"
  4093. "# Other times below are in GMT\n"
  4094. "# You *do not* need to edit this file.\n\n%s",
  4095. tbuf, state);
  4096. tor_free(state);
  4097. fname = get_or_state_fname();
  4098. if (write_str_to_file(fname, contents, 0)<0) {
  4099. log_warn(LD_FS, "Unable to write state to file \"%s\"", fname);
  4100. tor_free(fname);
  4101. tor_free(contents);
  4102. return -1;
  4103. }
  4104. log_info(LD_GENERAL, "Saved state to \"%s\"", fname);
  4105. tor_free(fname);
  4106. tor_free(contents);
  4107. global_state->next_write = TIME_MAX;
  4108. return 0;
  4109. }
  4110. /** Helper to implement GETINFO functions about configuration variables (not
  4111. * their values). Given a "config/names" question, set *<b>answer</b> to a
  4112. * new string describing the supported configuration variables and their
  4113. * types. */
  4114. int
  4115. getinfo_helper_config(control_connection_t *conn,
  4116. const char *question, char **answer)
  4117. {
  4118. (void) conn;
  4119. if (!strcmp(question, "config/names")) {
  4120. smartlist_t *sl = smartlist_create();
  4121. int i;
  4122. for (i = 0; _option_vars[i].name; ++i) {
  4123. config_var_t *var = &_option_vars[i];
  4124. const char *type, *desc;
  4125. char *line;
  4126. size_t len;
  4127. desc = config_find_description(&options_format, var->name);
  4128. switch (var->type) {
  4129. case CONFIG_TYPE_STRING: type = "String"; break;
  4130. case CONFIG_TYPE_UINT: type = "Integer"; break;
  4131. case CONFIG_TYPE_INTERVAL: type = "TimeInterval"; break;
  4132. case CONFIG_TYPE_MEMUNIT: type = "DataSize"; break;
  4133. case CONFIG_TYPE_DOUBLE: type = "Float"; break;
  4134. case CONFIG_TYPE_BOOL: type = "Boolean"; break;
  4135. case CONFIG_TYPE_ISOTIME: type = "Time"; break;
  4136. case CONFIG_TYPE_CSV: type = "CommaList"; break;
  4137. case CONFIG_TYPE_LINELIST: type = "LineList"; break;
  4138. case CONFIG_TYPE_LINELIST_S: type = "Dependant"; break;
  4139. case CONFIG_TYPE_LINELIST_V: type = "Virtual"; break;
  4140. default:
  4141. case CONFIG_TYPE_OBSOLETE:
  4142. type = NULL; break;
  4143. }
  4144. if (!type)
  4145. continue;
  4146. len = strlen(var->name)+strlen(type)+16;
  4147. if (desc)
  4148. len += strlen(desc);
  4149. line = tor_malloc(len);
  4150. if (desc)
  4151. tor_snprintf(line, len, "%s %s %s\n",var->name,type,desc);
  4152. else
  4153. tor_snprintf(line, len, "%s %s\n",var->name,type);
  4154. smartlist_add(sl, line);
  4155. }
  4156. *answer = smartlist_join_strings(sl, "", 0, NULL);
  4157. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  4158. smartlist_free(sl);
  4159. }
  4160. return 0;
  4161. }
  4162. #include "aes.h"
  4163. #include "ht.h"
  4164. #include "test.h"
  4165. extern const char aes_c_id[];
  4166. extern const char compat_c_id[];
  4167. extern const char container_c_id[];
  4168. extern const char crypto_c_id[];
  4169. extern const char log_c_id[];
  4170. extern const char torgzip_c_id[];
  4171. extern const char tortls_c_id[];
  4172. extern const char util_c_id[];
  4173. extern const char buffers_c_id[];
  4174. extern const char circuitbuild_c_id[];
  4175. extern const char circuitlist_c_id[];
  4176. extern const char circuituse_c_id[];
  4177. extern const char command_c_id[];
  4178. // extern const char config_c_id[];
  4179. extern const char connection_c_id[];
  4180. extern const char connection_edge_c_id[];
  4181. extern const char connection_or_c_id[];
  4182. extern const char control_c_id[];
  4183. extern const char cpuworker_c_id[];
  4184. extern const char directory_c_id[];
  4185. extern const char dirserv_c_id[];
  4186. extern const char dns_c_id[];
  4187. extern const char hibernate_c_id[];
  4188. extern const char main_c_id[];
  4189. extern const char onion_c_id[];
  4190. extern const char policies_c_id[];
  4191. extern const char relay_c_id[];
  4192. extern const char rendclient_c_id[];
  4193. extern const char rendcommon_c_id[];
  4194. extern const char rendmid_c_id[];
  4195. extern const char rendservice_c_id[];
  4196. extern const char rephist_c_id[];
  4197. extern const char router_c_id[];
  4198. extern const char routerlist_c_id[];
  4199. extern const char routerparse_c_id[];
  4200. /** Dump the version of every file to the log. */
  4201. static void
  4202. print_svn_version(void)
  4203. {
  4204. puts(AES_H_ID);
  4205. puts(COMPAT_H_ID);
  4206. puts(CONTAINER_H_ID);
  4207. puts(CRYPTO_H_ID);
  4208. puts(HT_H_ID);
  4209. puts(TEST_H_ID);
  4210. puts(LOG_H_ID);
  4211. puts(TORGZIP_H_ID);
  4212. puts(TORINT_H_ID);
  4213. puts(TORTLS_H_ID);
  4214. puts(UTIL_H_ID);
  4215. puts(aes_c_id);
  4216. puts(compat_c_id);
  4217. puts(container_c_id);
  4218. puts(crypto_c_id);
  4219. puts(log_c_id);
  4220. puts(torgzip_c_id);
  4221. puts(tortls_c_id);
  4222. puts(util_c_id);
  4223. puts(OR_H_ID);
  4224. puts(buffers_c_id);
  4225. puts(circuitbuild_c_id);
  4226. puts(circuitlist_c_id);
  4227. puts(circuituse_c_id);
  4228. puts(command_c_id);
  4229. puts(config_c_id);
  4230. puts(connection_c_id);
  4231. puts(connection_edge_c_id);
  4232. puts(connection_or_c_id);
  4233. puts(control_c_id);
  4234. puts(cpuworker_c_id);
  4235. puts(directory_c_id);
  4236. puts(dirserv_c_id);
  4237. puts(dns_c_id);
  4238. puts(hibernate_c_id);
  4239. puts(main_c_id);
  4240. puts(onion_c_id);
  4241. puts(policies_c_id);
  4242. puts(relay_c_id);
  4243. puts(rendclient_c_id);
  4244. puts(rendcommon_c_id);
  4245. puts(rendmid_c_id);
  4246. puts(rendservice_c_id);
  4247. puts(rephist_c_id);
  4248. puts(router_c_id);
  4249. puts(routerlist_c_id);
  4250. puts(routerparse_c_id);
  4251. }