config.c 189 KB

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