config.c 163 KB

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