config.c 159 KB

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