config.c 158 KB

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