config.c 184 KB

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