config.c 181 KB

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