config.c 181 KB

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