config.c 163 KB

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