config.c 167 KB

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