config.c 182 KB

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