config.c 179 KB

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