config.c 145 KB

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