config.c 177 KB

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