config.c 159 KB

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