config.c 153 KB

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