config.c 172 KB

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