config.c 153 KB

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