config.c 246 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355
  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-2012, 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 "util.h"
  34. #include "routerlist.h"
  35. #include "transports.h"
  36. #ifdef _WIN32
  37. #include <shlobj.h>
  38. #endif
  39. #include "procmon.h"
  40. /* From main.c */
  41. extern int quiet_level;
  42. /** Enumeration of types which option values can take */
  43. typedef enum config_type_t {
  44. CONFIG_TYPE_STRING = 0, /**< An arbitrary string. */
  45. CONFIG_TYPE_FILENAME, /**< A filename: some prefixes get expanded. */
  46. CONFIG_TYPE_UINT, /**< A non-negative integer less than MAX_INT */
  47. CONFIG_TYPE_INT, /**< Any integer. */
  48. CONFIG_TYPE_PORT, /**< A port from 1...65535, 0 for "not set", or
  49. * "auto". */
  50. CONFIG_TYPE_INTERVAL, /**< A number of seconds, with optional units*/
  51. CONFIG_TYPE_MSEC_INTERVAL,/**< A number of milliseconds, with optional
  52. * units */
  53. CONFIG_TYPE_MEMUNIT, /**< A number of bytes, with optional units*/
  54. CONFIG_TYPE_DOUBLE, /**< A floating-point value */
  55. CONFIG_TYPE_BOOL, /**< A boolean value, expressed as 0 or 1. */
  56. CONFIG_TYPE_AUTOBOOL, /**< A boolean+auto value, expressed 0 for false,
  57. * 1 for true, and -1 for auto */
  58. CONFIG_TYPE_ISOTIME, /**< An ISO-formatted time relative to GMT. */
  59. CONFIG_TYPE_CSV, /**< A list of strings, separated by commas and
  60. * optional whitespace. */
  61. CONFIG_TYPE_LINELIST, /**< Uninterpreted config lines */
  62. CONFIG_TYPE_LINELIST_S, /**< Uninterpreted, context-sensitive config lines,
  63. * mixed with other keywords. */
  64. CONFIG_TYPE_LINELIST_V, /**< Catch-all "virtual" option to summarize
  65. * context-sensitive config lines when fetching.
  66. */
  67. CONFIG_TYPE_ROUTERSET, /**< A list of router names, addrs, and fps,
  68. * parsed into a routerset_t. */
  69. CONFIG_TYPE_OBSOLETE, /**< Obsolete (ignored) option. */
  70. } config_type_t;
  71. /** An abbreviation for a configuration option allowed on the command line. */
  72. typedef struct config_abbrev_t {
  73. const char *abbreviated;
  74. const char *full;
  75. int commandline_only;
  76. int warn;
  77. } config_abbrev_t;
  78. /* Handy macro for declaring "In the config file or on the command line,
  79. * you can abbreviate <b>tok</b>s as <b>tok</b>". */
  80. #define PLURAL(tok) { #tok, #tok "s", 0, 0 }
  81. /** A list of abbreviations and aliases to map command-line options, obsolete
  82. * option names, or alternative option names, to their current values. */
  83. static config_abbrev_t _option_abbrevs[] = {
  84. PLURAL(AuthDirBadDirCC),
  85. PLURAL(AuthDirBadExitCC),
  86. PLURAL(AuthDirInvalidCC),
  87. PLURAL(AuthDirRejectCC),
  88. PLURAL(ExitNode),
  89. PLURAL(EntryNode),
  90. PLURAL(ExcludeNode),
  91. PLURAL(FirewallPort),
  92. PLURAL(LongLivedPort),
  93. PLURAL(HiddenServiceNode),
  94. PLURAL(HiddenServiceExcludeNode),
  95. PLURAL(NumCPU),
  96. PLURAL(RendNode),
  97. PLURAL(RendExcludeNode),
  98. PLURAL(StrictEntryNode),
  99. PLURAL(StrictExitNode),
  100. PLURAL(StrictNode),
  101. { "l", "Log", 1, 0},
  102. { "AllowUnverifiedNodes", "AllowInvalidNodes", 0, 0},
  103. { "AutomapHostSuffixes", "AutomapHostsSuffixes", 0, 0},
  104. { "AutomapHostOnResolve", "AutomapHostsOnResolve", 0, 0},
  105. { "BandwidthRateBytes", "BandwidthRate", 0, 0},
  106. { "BandwidthBurstBytes", "BandwidthBurst", 0, 0},
  107. { "DirFetchPostPeriod", "StatusFetchPeriod", 0, 0},
  108. { "MaxConn", "ConnLimit", 0, 1},
  109. { "ORBindAddress", "ORListenAddress", 0, 0},
  110. { "DirBindAddress", "DirListenAddress", 0, 0},
  111. { "SocksBindAddress", "SocksListenAddress", 0, 0},
  112. { "UseHelperNodes", "UseEntryGuards", 0, 0},
  113. { "NumHelperNodes", "NumEntryGuards", 0, 0},
  114. { "UseEntryNodes", "UseEntryGuards", 0, 0},
  115. { "NumEntryNodes", "NumEntryGuards", 0, 0},
  116. { "ResolvConf", "ServerDNSResolvConfFile", 0, 1},
  117. { "SearchDomains", "ServerDNSSearchDomains", 0, 1},
  118. { "ServerDNSAllowBrokenResolvConf", "ServerDNSAllowBrokenConfig", 0, 0},
  119. { "PreferTunnelledDirConns", "PreferTunneledDirConns", 0, 0},
  120. { "BridgeAuthoritativeDirectory", "BridgeAuthoritativeDir", 0, 0},
  121. { "HashedControlPassword", "__HashedControlSessionPassword", 1, 0},
  122. { "StrictEntryNodes", "StrictNodes", 0, 1},
  123. { "StrictExitNodes", "StrictNodes", 0, 1},
  124. { NULL, NULL, 0, 0},
  125. };
  126. /** A list of state-file "abbreviations," for compatibility. */
  127. static config_abbrev_t _state_abbrevs[] = {
  128. { "AccountingBytesReadInterval", "AccountingBytesReadInInterval", 0, 0 },
  129. { "HelperNode", "EntryGuard", 0, 0 },
  130. { "HelperNodeDownSince", "EntryGuardDownSince", 0, 0 },
  131. { "HelperNodeUnlistedSince", "EntryGuardUnlistedSince", 0, 0 },
  132. { "EntryNode", "EntryGuard", 0, 0 },
  133. { "EntryNodeDownSince", "EntryGuardDownSince", 0, 0 },
  134. { "EntryNodeUnlistedSince", "EntryGuardUnlistedSince", 0, 0 },
  135. { NULL, NULL, 0, 0},
  136. };
  137. #undef PLURAL
  138. /** A variable allowed in the configuration file or on the command line. */
  139. typedef struct config_var_t {
  140. const char *name; /**< The full keyword (case insensitive). */
  141. config_type_t type; /**< How to interpret the type and turn it into a
  142. * value. */
  143. off_t var_offset; /**< Offset of the corresponding member of or_options_t. */
  144. const char *initvalue; /**< String (or null) describing initial value. */
  145. } config_var_t;
  146. /** An entry for config_vars: "The option <b>name</b> has type
  147. * CONFIG_TYPE_<b>conftype</b>, and corresponds to
  148. * or_options_t.<b>member</b>"
  149. */
  150. #define VAR(name,conftype,member,initvalue) \
  151. { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_options_t, member), \
  152. initvalue }
  153. /** As VAR, but the option name and member name are the same. */
  154. #define V(member,conftype,initvalue) \
  155. VAR(#member, conftype, member, initvalue)
  156. /** An entry for config_vars: "The option <b>name</b> is obsolete." */
  157. #define OBSOLETE(name) { name, CONFIG_TYPE_OBSOLETE, 0, NULL }
  158. #define VPORT(member,conftype,initvalue) \
  159. VAR(#member, conftype, member ## _lines, initvalue)
  160. /** Array of configuration options. Until we disallow nonstandard
  161. * abbreviations, order is significant, since the first matching option will
  162. * be chosen first.
  163. */
  164. static config_var_t _option_vars[] = {
  165. OBSOLETE("AccountingMaxKB"),
  166. V(AccountingMax, MEMUNIT, "0 bytes"),
  167. V(AccountingStart, STRING, NULL),
  168. V(Address, STRING, NULL),
  169. V(AllowDotExit, BOOL, "0"),
  170. V(AllowInvalidNodes, CSV, "middle,rendezvous"),
  171. V(AllowNonRFC953Hostnames, BOOL, "0"),
  172. V(AllowSingleHopCircuits, BOOL, "0"),
  173. V(AllowSingleHopExits, BOOL, "0"),
  174. V(AlternateBridgeAuthority, LINELIST, NULL),
  175. V(AlternateDirAuthority, LINELIST, NULL),
  176. V(AlternateHSAuthority, LINELIST, NULL),
  177. V(AssumeReachable, BOOL, "0"),
  178. V(AuthDirBadDir, LINELIST, NULL),
  179. V(AuthDirBadDirCCs, CSV, ""),
  180. V(AuthDirBadExit, LINELIST, NULL),
  181. V(AuthDirBadExitCCs, CSV, ""),
  182. V(AuthDirInvalid, LINELIST, NULL),
  183. V(AuthDirInvalidCCs, CSV, ""),
  184. V(AuthDirFastGuarantee, MEMUNIT, "100 KB"),
  185. V(AuthDirGuardBWGuarantee, MEMUNIT, "250 KB"),
  186. V(AuthDirReject, LINELIST, NULL),
  187. V(AuthDirRejectCCs, CSV, ""),
  188. V(AuthDirRejectUnlisted, BOOL, "0"),
  189. V(AuthDirListBadDirs, BOOL, "0"),
  190. V(AuthDirListBadExits, BOOL, "0"),
  191. V(AuthDirMaxServersPerAddr, UINT, "2"),
  192. V(AuthDirMaxServersPerAuthAddr,UINT, "5"),
  193. V(AuthDirHasIPv6Connectivity, AUTOBOOL, "auto"),
  194. V(AuthDirPublishIPv6, BOOL, "0"),
  195. VAR("AuthoritativeDirectory", BOOL, AuthoritativeDir, "0"),
  196. V(AutomapHostsOnResolve, BOOL, "0"),
  197. V(AutomapHostsSuffixes, CSV, ".onion,.exit"),
  198. V(AvoidDiskWrites, BOOL, "0"),
  199. V(BandwidthBurst, MEMUNIT, "10 MB"),
  200. V(BandwidthRate, MEMUNIT, "5 MB"),
  201. V(BridgeAuthoritativeDir, BOOL, "0"),
  202. VAR("Bridge", LINELIST, Bridges, NULL),
  203. V(BridgePassword, STRING, NULL),
  204. V(BridgeRecordUsageByCountry, BOOL, "1"),
  205. V(BridgeRelay, BOOL, "0"),
  206. V(CellStatistics, BOOL, "0"),
  207. V(LearnCircuitBuildTimeout, BOOL, "1"),
  208. V(CircuitBuildTimeout, INTERVAL, "0"),
  209. V(CircuitIdleTimeout, INTERVAL, "1 hour"),
  210. V(CircuitStreamTimeout, INTERVAL, "0"),
  211. V(CircuitPriorityHalflife, DOUBLE, "-100.0"), /*negative:'Use default'*/
  212. V(ClientDNSRejectInternalAddresses, BOOL,"1"),
  213. V(ClientOnly, BOOL, "0"),
  214. V(ClientPreferIPv6ORPort, BOOL, "0"),
  215. V(ClientRejectInternalAddresses, BOOL, "1"),
  216. V(ClientTransportPlugin, LINELIST, NULL),
  217. V(ClientUseIPv6, BOOL, "0"),
  218. V(ConsensusParams, STRING, NULL),
  219. V(ConnLimit, UINT, "1000"),
  220. V(ConnDirectionStatistics, BOOL, "0"),
  221. V(ConstrainedSockets, BOOL, "0"),
  222. V(ConstrainedSockSize, MEMUNIT, "8192"),
  223. V(ContactInfo, STRING, NULL),
  224. V(ControlListenAddress, LINELIST, NULL),
  225. VPORT(ControlPort, LINELIST, NULL),
  226. V(ControlPortFileGroupReadable,BOOL, "0"),
  227. V(ControlPortWriteToFile, FILENAME, NULL),
  228. V(ControlSocket, LINELIST, NULL),
  229. V(ControlSocketsGroupWritable, BOOL, "0"),
  230. V(CookieAuthentication, BOOL, "0"),
  231. V(CookieAuthFileGroupReadable, BOOL, "0"),
  232. V(CookieAuthFile, STRING, NULL),
  233. V(CountPrivateBandwidth, BOOL, "0"),
  234. V(DataDirectory, FILENAME, NULL),
  235. OBSOLETE("DebugLogFile"),
  236. V(DisableNetwork, BOOL, "0"),
  237. V(DirAllowPrivateAddresses, BOOL, "0"),
  238. V(TestingAuthDirTimeToLearnReachability, INTERVAL, "30 minutes"),
  239. V(DirListenAddress, LINELIST, NULL),
  240. OBSOLETE("DirFetchPeriod"),
  241. V(DirPolicy, LINELIST, NULL),
  242. VPORT(DirPort, LINELIST, NULL),
  243. V(DirPortFrontPage, FILENAME, NULL),
  244. OBSOLETE("DirPostPeriod"),
  245. OBSOLETE("DirRecordUsageByCountry"),
  246. OBSOLETE("DirRecordUsageGranularity"),
  247. OBSOLETE("DirRecordUsageRetainIPs"),
  248. OBSOLETE("DirRecordUsageSaveInterval"),
  249. V(DirReqStatistics, BOOL, "1"),
  250. VAR("DirServer", LINELIST, DirServers, NULL),
  251. V(DisableAllSwap, BOOL, "0"),
  252. V(DisableDebuggerAttachment, BOOL, "1"),
  253. V(DisableIOCP, BOOL, "1"),
  254. V(DynamicDHGroups, BOOL, "0"),
  255. VPORT(DNSPort, LINELIST, NULL),
  256. V(DNSListenAddress, LINELIST, NULL),
  257. V(DownloadExtraInfo, BOOL, "0"),
  258. V(EnforceDistinctSubnets, BOOL, "1"),
  259. V(EntryNodes, ROUTERSET, NULL),
  260. V(EntryStatistics, BOOL, "0"),
  261. V(TestingEstimatedDescriptorPropagationTime, INTERVAL, "10 minutes"),
  262. V(ExcludeNodes, ROUTERSET, NULL),
  263. V(ExcludeExitNodes, ROUTERSET, NULL),
  264. V(ExcludeSingleHopRelays, BOOL, "1"),
  265. V(ExitNodes, ROUTERSET, NULL),
  266. V(ExitPolicy, LINELIST, NULL),
  267. V(ExitPolicyRejectPrivate, BOOL, "1"),
  268. V(ExitPortStatistics, BOOL, "0"),
  269. V(ExtendAllowPrivateAddresses, BOOL, "0"),
  270. V(ExtraInfoStatistics, BOOL, "1"),
  271. #if defined (WINCE)
  272. V(FallbackNetworkstatusFile, FILENAME, "fallback-consensus"),
  273. #else
  274. V(FallbackNetworkstatusFile, FILENAME,
  275. SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "fallback-consensus"),
  276. #endif
  277. V(FascistFirewall, BOOL, "0"),
  278. V(FirewallPorts, CSV, ""),
  279. V(FastFirstHopPK, BOOL, "1"),
  280. V(FetchDirInfoEarly, BOOL, "0"),
  281. V(FetchDirInfoExtraEarly, BOOL, "0"),
  282. V(FetchServerDescriptors, BOOL, "1"),
  283. V(FetchHidServDescriptors, BOOL, "1"),
  284. V(FetchUselessDescriptors, BOOL, "0"),
  285. V(FetchV2Networkstatus, BOOL, "0"),
  286. #ifdef _WIN32
  287. V(GeoIPFile, FILENAME, "<default>"),
  288. #else
  289. V(GeoIPFile, FILENAME,
  290. SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "geoip"),
  291. #endif
  292. OBSOLETE("GiveGuardFlagTo_CVE_2011_2768_VulnerableRelays"),
  293. OBSOLETE("Group"),
  294. V(HardwareAccel, BOOL, "0"),
  295. V(HeartbeatPeriod, INTERVAL, "6 hours"),
  296. V(AccelName, STRING, NULL),
  297. V(AccelDir, FILENAME, NULL),
  298. V(HashedControlPassword, LINELIST, NULL),
  299. V(HidServDirectoryV2, BOOL, "1"),
  300. VAR("HiddenServiceDir", LINELIST_S, RendConfigLines, NULL),
  301. OBSOLETE("HiddenServiceExcludeNodes"),
  302. OBSOLETE("HiddenServiceNodes"),
  303. VAR("HiddenServiceOptions",LINELIST_V, RendConfigLines, NULL),
  304. VAR("HiddenServicePort", LINELIST_S, RendConfigLines, NULL),
  305. VAR("HiddenServiceVersion",LINELIST_S, RendConfigLines, NULL),
  306. VAR("HiddenServiceAuthorizeClient",LINELIST_S,RendConfigLines, NULL),
  307. V(HidServAuth, LINELIST, NULL),
  308. V(HSAuthoritativeDir, BOOL, "0"),
  309. OBSOLETE("HSAuthorityRecordStats"),
  310. V(CloseHSClientCircuitsImmediatelyOnTimeout, BOOL, "0"),
  311. V(CloseHSServiceRendCircuitsImmediatelyOnTimeout, BOOL, "0"),
  312. V(HTTPProxy, STRING, NULL),
  313. V(HTTPProxyAuthenticator, STRING, NULL),
  314. V(HTTPSProxy, STRING, NULL),
  315. V(HTTPSProxyAuthenticator, STRING, NULL),
  316. VAR("ServerTransportPlugin", LINELIST, ServerTransportPlugin, NULL),
  317. V(Socks4Proxy, STRING, NULL),
  318. V(Socks5Proxy, STRING, NULL),
  319. V(Socks5ProxyUsername, STRING, NULL),
  320. V(Socks5ProxyPassword, STRING, NULL),
  321. OBSOLETE("IgnoreVersion"),
  322. V(KeepalivePeriod, INTERVAL, "5 minutes"),
  323. VAR("Log", LINELIST, Logs, NULL),
  324. V(LogMessageDomains, BOOL, "0"),
  325. OBSOLETE("LinkPadding"),
  326. OBSOLETE("LogLevel"),
  327. OBSOLETE("LogFile"),
  328. V(LogTimeGranularity, MSEC_INTERVAL, "1 second"),
  329. V(LongLivedPorts, CSV,
  330. "21,22,706,1863,5050,5190,5222,5223,6523,6667,6697,8300"),
  331. VAR("MapAddress", LINELIST, AddressMap, NULL),
  332. V(MaxAdvertisedBandwidth, MEMUNIT, "1 GB"),
  333. V(MaxCircuitDirtiness, INTERVAL, "10 minutes"),
  334. V(MaxClientCircuitsPending, UINT, "32"),
  335. V(MaxOnionsPending, UINT, "100"),
  336. OBSOLETE("MonthlyAccountingStart"),
  337. V(MyFamily, STRING, NULL),
  338. V(NewCircuitPeriod, INTERVAL, "30 seconds"),
  339. VAR("NamingAuthoritativeDirectory",BOOL, NamingAuthoritativeDir, "0"),
  340. V(NATDListenAddress, LINELIST, NULL),
  341. VPORT(NATDPort, LINELIST, NULL),
  342. V(Nickname, STRING, NULL),
  343. V(WarnUnsafeSocks, BOOL, "1"),
  344. OBSOLETE("NoPublish"),
  345. VAR("NodeFamily", LINELIST, NodeFamilies, NULL),
  346. V(NumCPUs, UINT, "0"),
  347. V(NumEntryGuards, UINT, "3"),
  348. V(ORListenAddress, LINELIST, NULL),
  349. VPORT(ORPort, LINELIST, NULL),
  350. V(OutboundBindAddress, STRING, NULL),
  351. V(PathBiasCircThreshold, INT, "-1"),
  352. V(PathBiasNoticeRate, DOUBLE, "-1"),
  353. V(PathBiasDisableRate, DOUBLE, "-1"),
  354. V(PathBiasScaleThreshold, INT, "-1"),
  355. V(PathBiasScaleFactor, INT, "-1"),
  356. OBSOLETE("PathlenCoinWeight"),
  357. V(PerConnBWBurst, MEMUNIT, "0"),
  358. V(PerConnBWRate, MEMUNIT, "0"),
  359. V(PidFile, STRING, NULL),
  360. V(TestingTorNetwork, BOOL, "0"),
  361. V(OptimisticData, AUTOBOOL, "auto"),
  362. V(PortForwarding, BOOL, "0"),
  363. V(PortForwardingHelper, FILENAME, "tor-fw-helper"),
  364. V(PreferTunneledDirConns, BOOL, "1"),
  365. V(ProtocolWarnings, BOOL, "0"),
  366. V(PublishServerDescriptor, CSV, "1"),
  367. V(PublishHidServDescriptors, BOOL, "1"),
  368. V(ReachableAddresses, LINELIST, NULL),
  369. V(ReachableDirAddresses, LINELIST, NULL),
  370. V(ReachableORAddresses, LINELIST, NULL),
  371. V(RecommendedVersions, LINELIST, NULL),
  372. V(RecommendedClientVersions, LINELIST, NULL),
  373. V(RecommendedServerVersions, LINELIST, NULL),
  374. OBSOLETE("RedirectExit"),
  375. V(RefuseUnknownExits, AUTOBOOL, "auto"),
  376. V(RejectPlaintextPorts, CSV, ""),
  377. V(RelayBandwidthBurst, MEMUNIT, "0"),
  378. V(RelayBandwidthRate, MEMUNIT, "0"),
  379. OBSOLETE("RendExcludeNodes"),
  380. OBSOLETE("RendNodes"),
  381. V(RendPostPeriod, INTERVAL, "1 hour"),
  382. V(RephistTrackTime, INTERVAL, "24 hours"),
  383. OBSOLETE("RouterFile"),
  384. V(RunAsDaemon, BOOL, "0"),
  385. // V(RunTesting, BOOL, "0"),
  386. OBSOLETE("RunTesting"), // currently unused
  387. V(SafeLogging, STRING, "1"),
  388. V(SafeSocks, BOOL, "0"),
  389. V(ServerDNSAllowBrokenConfig, BOOL, "1"),
  390. V(ServerDNSAllowNonRFC953Hostnames, BOOL,"0"),
  391. V(ServerDNSDetectHijacking, BOOL, "1"),
  392. V(ServerDNSRandomizeCase, BOOL, "1"),
  393. V(ServerDNSResolvConfFile, STRING, NULL),
  394. V(ServerDNSSearchDomains, BOOL, "0"),
  395. V(ServerDNSTestAddresses, CSV,
  396. "www.google.com,www.mit.edu,www.yahoo.com,www.slashdot.org"),
  397. V(ShutdownWaitLength, INTERVAL, "30 seconds"),
  398. V(SocksListenAddress, LINELIST, NULL),
  399. V(SocksPolicy, LINELIST, NULL),
  400. VPORT(SocksPort, LINELIST, NULL),
  401. V(SocksTimeout, INTERVAL, "2 minutes"),
  402. OBSOLETE("StatusFetchPeriod"),
  403. V(StrictNodes, BOOL, "0"),
  404. OBSOLETE("SysLog"),
  405. V(TestSocks, BOOL, "0"),
  406. OBSOLETE("TestVia"),
  407. V(TokenBucketRefillInterval, MSEC_INTERVAL, "100 msec"),
  408. V(Tor2webMode, BOOL, "0"),
  409. V(TrackHostExits, CSV, NULL),
  410. V(TrackHostExitsExpire, INTERVAL, "30 minutes"),
  411. OBSOLETE("TrafficShaping"),
  412. V(TransListenAddress, LINELIST, NULL),
  413. VPORT(TransPort, LINELIST, NULL),
  414. V(TunnelDirConns, BOOL, "1"),
  415. V(UpdateBridgesFromAuthority, BOOL, "0"),
  416. V(UseBridges, BOOL, "0"),
  417. V(UseEntryGuards, BOOL, "1"),
  418. V(UseMicrodescriptors, AUTOBOOL, "auto"),
  419. V(User, STRING, NULL),
  420. V(UserspaceIOCPBuffers, BOOL, "0"),
  421. VAR("V1AuthoritativeDirectory",BOOL, V1AuthoritativeDir, "0"),
  422. VAR("V2AuthoritativeDirectory",BOOL, V2AuthoritativeDir, "0"),
  423. VAR("V3AuthoritativeDirectory",BOOL, V3AuthoritativeDir, "0"),
  424. V(TestingV3AuthInitialVotingInterval, INTERVAL, "30 minutes"),
  425. V(TestingV3AuthInitialVoteDelay, INTERVAL, "5 minutes"),
  426. V(TestingV3AuthInitialDistDelay, INTERVAL, "5 minutes"),
  427. V(V3AuthVotingInterval, INTERVAL, "1 hour"),
  428. V(V3AuthVoteDelay, INTERVAL, "5 minutes"),
  429. V(V3AuthDistDelay, INTERVAL, "5 minutes"),
  430. V(V3AuthNIntervalsValid, UINT, "3"),
  431. V(V3AuthUseLegacyKey, BOOL, "0"),
  432. V(V3BandwidthsFile, FILENAME, NULL),
  433. VAR("VersioningAuthoritativeDirectory",BOOL,VersioningAuthoritativeDir, "0"),
  434. V(VirtualAddrNetwork, STRING, "127.192.0.0/10"),
  435. V(WarnPlaintextPorts, CSV, "23,109,110,143"),
  436. V(_UseFilteringSSLBufferevents, BOOL, "0"),
  437. VAR("__ReloadTorrcOnSIGHUP", BOOL, ReloadTorrcOnSIGHUP, "1"),
  438. VAR("__AllDirActionsPrivate", BOOL, AllDirActionsPrivate, "0"),
  439. VAR("__DisablePredictedCircuits",BOOL,DisablePredictedCircuits, "0"),
  440. VAR("__LeaveStreamsUnattached",BOOL, LeaveStreamsUnattached, "0"),
  441. VAR("__HashedControlSessionPassword", LINELIST, HashedControlSessionPassword,
  442. NULL),
  443. VAR("__OwningControllerProcess",STRING,OwningControllerProcess, NULL),
  444. V(MinUptimeHidServDirectoryV2, INTERVAL, "25 hours"),
  445. V(VoteOnHidServDirectoriesV2, BOOL, "1"),
  446. V(_UsingTestNetworkDefaults, BOOL, "0"),
  447. { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
  448. };
  449. /** Override default values with these if the user sets the TestingTorNetwork
  450. * option. */
  451. static const config_var_t testing_tor_network_defaults[] = {
  452. V(ServerDNSAllowBrokenConfig, BOOL, "1"),
  453. V(DirAllowPrivateAddresses, BOOL, "1"),
  454. V(EnforceDistinctSubnets, BOOL, "0"),
  455. V(AssumeReachable, BOOL, "1"),
  456. V(AuthDirMaxServersPerAddr, UINT, "0"),
  457. V(AuthDirMaxServersPerAuthAddr,UINT, "0"),
  458. V(ClientDNSRejectInternalAddresses, BOOL,"0"),
  459. V(ClientRejectInternalAddresses, BOOL, "0"),
  460. V(CountPrivateBandwidth, BOOL, "1"),
  461. V(ExitPolicyRejectPrivate, BOOL, "0"),
  462. V(ExtendAllowPrivateAddresses, BOOL, "1"),
  463. V(V3AuthVotingInterval, INTERVAL, "5 minutes"),
  464. V(V3AuthVoteDelay, INTERVAL, "20 seconds"),
  465. V(V3AuthDistDelay, INTERVAL, "20 seconds"),
  466. V(TestingV3AuthInitialVotingInterval, INTERVAL, "5 minutes"),
  467. V(TestingV3AuthInitialVoteDelay, INTERVAL, "20 seconds"),
  468. V(TestingV3AuthInitialDistDelay, INTERVAL, "20 seconds"),
  469. V(TestingAuthDirTimeToLearnReachability, INTERVAL, "0 minutes"),
  470. V(TestingEstimatedDescriptorPropagationTime, INTERVAL, "0 minutes"),
  471. V(MinUptimeHidServDirectoryV2, INTERVAL, "0 minutes"),
  472. V(_UsingTestNetworkDefaults, BOOL, "1"),
  473. { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
  474. };
  475. #undef VAR
  476. #define VAR(name,conftype,member,initvalue) \
  477. { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_state_t, member), \
  478. initvalue }
  479. /** Array of "state" variables saved to the ~/.tor/state file. */
  480. static config_var_t _state_vars[] = {
  481. /* Remember to document these in state-contents.txt ! */
  482. V(AccountingBytesReadInInterval, MEMUNIT, NULL),
  483. V(AccountingBytesWrittenInInterval, MEMUNIT, NULL),
  484. V(AccountingExpectedUsage, MEMUNIT, NULL),
  485. V(AccountingIntervalStart, ISOTIME, NULL),
  486. V(AccountingSecondsActive, INTERVAL, NULL),
  487. V(AccountingSecondsToReachSoftLimit,INTERVAL, NULL),
  488. V(AccountingSoftLimitHitAt, ISOTIME, NULL),
  489. V(AccountingBytesAtSoftLimit, MEMUNIT, NULL),
  490. VAR("EntryGuard", LINELIST_S, EntryGuards, NULL),
  491. VAR("EntryGuardDownSince", LINELIST_S, EntryGuards, NULL),
  492. VAR("EntryGuardUnlistedSince", LINELIST_S, EntryGuards, NULL),
  493. VAR("EntryGuardAddedBy", LINELIST_S, EntryGuards, NULL),
  494. VAR("EntryGuardPathBias", LINELIST_S, EntryGuards, NULL),
  495. V(EntryGuards, LINELIST_V, NULL),
  496. VAR("TransportProxy", LINELIST_S, TransportProxies, NULL),
  497. V(TransportProxies, LINELIST_V, NULL),
  498. V(BWHistoryReadEnds, ISOTIME, NULL),
  499. V(BWHistoryReadInterval, UINT, "900"),
  500. V(BWHistoryReadValues, CSV, ""),
  501. V(BWHistoryReadMaxima, CSV, ""),
  502. V(BWHistoryWriteEnds, ISOTIME, NULL),
  503. V(BWHistoryWriteInterval, UINT, "900"),
  504. V(BWHistoryWriteValues, CSV, ""),
  505. V(BWHistoryWriteMaxima, CSV, ""),
  506. V(BWHistoryDirReadEnds, ISOTIME, NULL),
  507. V(BWHistoryDirReadInterval, UINT, "900"),
  508. V(BWHistoryDirReadValues, CSV, ""),
  509. V(BWHistoryDirReadMaxima, CSV, ""),
  510. V(BWHistoryDirWriteEnds, ISOTIME, NULL),
  511. V(BWHistoryDirWriteInterval, UINT, "900"),
  512. V(BWHistoryDirWriteValues, CSV, ""),
  513. V(BWHistoryDirWriteMaxima, CSV, ""),
  514. V(TorVersion, STRING, NULL),
  515. V(LastRotatedOnionKey, ISOTIME, NULL),
  516. V(LastWritten, ISOTIME, NULL),
  517. V(TotalBuildTimes, UINT, NULL),
  518. V(CircuitBuildAbandonedCount, UINT, "0"),
  519. VAR("CircuitBuildTimeBin", LINELIST_S, BuildtimeHistogram, NULL),
  520. VAR("BuildtimeHistogram", LINELIST_V, BuildtimeHistogram, NULL),
  521. { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
  522. };
  523. #undef VAR
  524. #undef V
  525. #undef OBSOLETE
  526. /** Represents an English description of a configuration variable; used when
  527. * generating configuration file comments. */
  528. typedef struct config_var_description_t {
  529. const char *name;
  530. const char *description;
  531. } config_var_description_t;
  532. /** Type of a callback to validate whether a given configuration is
  533. * well-formed and consistent. See options_trial_assign() for documentation
  534. * of arguments. */
  535. typedef int (*validate_fn_t)(void*,void*,int,char**);
  536. /** Information on the keys, value types, key-to-struct-member mappings,
  537. * variable descriptions, validation functions, and abbreviations for a
  538. * configuration or storage format. */
  539. typedef struct {
  540. size_t size; /**< Size of the struct that everything gets parsed into. */
  541. uint32_t magic; /**< Required 'magic value' to make sure we have a struct
  542. * of the right type. */
  543. off_t magic_offset; /**< Offset of the magic value within the struct. */
  544. config_abbrev_t *abbrevs; /**< List of abbreviations that we expand when
  545. * parsing this format. */
  546. config_var_t *vars; /**< List of variables we recognize, their default
  547. * values, and where we stick them in the structure. */
  548. validate_fn_t validate_fn; /**< Function to validate config. */
  549. /** If present, extra is a LINELIST variable for unrecognized
  550. * lines. Otherwise, unrecognized lines are an error. */
  551. config_var_t *extra;
  552. } config_format_t;
  553. /** Macro: assert that <b>cfg</b> has the right magic field for format
  554. * <b>fmt</b>. */
  555. #define CHECK(fmt, cfg) STMT_BEGIN \
  556. tor_assert(fmt && cfg); \
  557. tor_assert((fmt)->magic == \
  558. *(uint32_t*)STRUCT_VAR_P(cfg,fmt->magic_offset)); \
  559. STMT_END
  560. #ifdef _WIN32
  561. static char *get_windows_conf_root(void);
  562. #endif
  563. static void config_line_append(config_line_t **lst,
  564. const char *key, const char *val);
  565. static void option_clear(const config_format_t *fmt, or_options_t *options,
  566. const config_var_t *var);
  567. static void option_reset(const config_format_t *fmt, or_options_t *options,
  568. const config_var_t *var, int use_defaults);
  569. static void config_free(const config_format_t *fmt, void *options);
  570. static int config_lines_eq(config_line_t *a, config_line_t *b);
  571. static int config_count_key(const config_line_t *a, const char *key);
  572. static int option_is_same(const config_format_t *fmt,
  573. const or_options_t *o1, const or_options_t *o2,
  574. const char *name);
  575. static or_options_t *options_dup(const config_format_t *fmt,
  576. const or_options_t *old);
  577. static int options_validate(or_options_t *old_options,
  578. or_options_t *options,
  579. int from_setconf, char **msg);
  580. static int options_act_reversible(const or_options_t *old_options, char **msg);
  581. static int options_act(const or_options_t *old_options);
  582. static int options_transition_allowed(const or_options_t *old,
  583. const or_options_t *new,
  584. char **msg);
  585. static int options_transition_affects_workers(
  586. const or_options_t *old_options, const or_options_t *new_options);
  587. static int options_transition_affects_descriptor(
  588. const or_options_t *old_options, const or_options_t *new_options);
  589. static int check_nickname_list(const char *lst, const char *name, char **msg);
  590. static int parse_bridge_line(const char *line, int validate_only);
  591. static int parse_client_transport_line(const char *line, int validate_only);
  592. static int parse_server_transport_line(const char *line, int validate_only);
  593. static int parse_dir_server_line(const char *line,
  594. dirinfo_type_t required_type,
  595. int validate_only);
  596. static void port_cfg_free(port_cfg_t *port);
  597. static int parse_ports(or_options_t *options, int validate_only,
  598. char **msg_out, int *n_ports_out);
  599. static int check_server_ports(const smartlist_t *ports,
  600. const or_options_t *options);
  601. static int validate_data_directory(or_options_t *options);
  602. static int write_configuration_file(const char *fname,
  603. const or_options_t *options);
  604. static config_line_t *get_assigned_option(const config_format_t *fmt,
  605. const void *options, const char *key,
  606. int escape_val);
  607. static void config_init(const config_format_t *fmt, void *options);
  608. static int or_state_validate(or_state_t *old_options, or_state_t *options,
  609. int from_setconf, char **msg);
  610. static int or_state_load(void);
  611. static int options_init_logs(or_options_t *options, int validate_only);
  612. static uint64_t config_parse_memunit(const char *s, int *ok);
  613. static int config_parse_msec_interval(const char *s, int *ok);
  614. static int config_parse_interval(const char *s, int *ok);
  615. static void init_libevent(const or_options_t *options);
  616. static int opt_streq(const char *s1, const char *s2);
  617. /** Magic value for or_options_t. */
  618. #define OR_OPTIONS_MAGIC 9090909
  619. /** Configuration format for or_options_t. */
  620. static config_format_t options_format = {
  621. sizeof(or_options_t),
  622. OR_OPTIONS_MAGIC,
  623. STRUCT_OFFSET(or_options_t, _magic),
  624. _option_abbrevs,
  625. _option_vars,
  626. (validate_fn_t)options_validate,
  627. NULL
  628. };
  629. /** Magic value for or_state_t. */
  630. #define OR_STATE_MAGIC 0x57A73f57
  631. /** "Extra" variable in the state that receives lines we can't parse. This
  632. * lets us preserve options from versions of Tor newer than us. */
  633. static config_var_t state_extra_var = {
  634. "__extra", CONFIG_TYPE_LINELIST, STRUCT_OFFSET(or_state_t, ExtraLines), NULL
  635. };
  636. /** Configuration format for or_state_t. */
  637. static const config_format_t state_format = {
  638. sizeof(or_state_t),
  639. OR_STATE_MAGIC,
  640. STRUCT_OFFSET(or_state_t, _magic),
  641. _state_abbrevs,
  642. _state_vars,
  643. (validate_fn_t)or_state_validate,
  644. &state_extra_var,
  645. };
  646. /*
  647. * Functions to read and write the global options pointer.
  648. */
  649. /** Command-line and config-file options. */
  650. static or_options_t *global_options = NULL;
  651. /** The fallback options_t object; this is where we look for options not
  652. * in torrc before we fall back to Tor's defaults. */
  653. static or_options_t *global_default_options = NULL;
  654. /** Name of most recently read torrc file. */
  655. static char *torrc_fname = NULL;
  656. /** Name of the most recently read torrc-defaults file.*/
  657. static char *torrc_defaults_fname;
  658. /** Persistent serialized state. */
  659. static or_state_t *global_state = NULL;
  660. /** Configuration Options set by command line. */
  661. static config_line_t *global_cmdline_options = NULL;
  662. /** Contents of most recently read DirPortFrontPage file. */
  663. static char *global_dirfrontpagecontents = NULL;
  664. /** List of port_cfg_t for all configured ports. */
  665. static smartlist_t *configured_ports = NULL;
  666. /** Return the contents of our frontpage string, or NULL if not configured. */
  667. const char *
  668. get_dirportfrontpage(void)
  669. {
  670. return global_dirfrontpagecontents;
  671. }
  672. /** Allocate an empty configuration object of a given format type. */
  673. static void *
  674. config_alloc(const config_format_t *fmt)
  675. {
  676. void *opts = tor_malloc_zero(fmt->size);
  677. *(uint32_t*)STRUCT_VAR_P(opts, fmt->magic_offset) = fmt->magic;
  678. CHECK(fmt, opts);
  679. return opts;
  680. }
  681. /** Return the currently configured options. */
  682. or_options_t *
  683. get_options_mutable(void)
  684. {
  685. tor_assert(global_options);
  686. return global_options;
  687. }
  688. /** Returns the currently configured options */
  689. const or_options_t *
  690. get_options(void)
  691. {
  692. return get_options_mutable();
  693. }
  694. /** Change the current global options to contain <b>new_val</b> instead of
  695. * their current value; take action based on the new value; free the old value
  696. * as necessary. Returns 0 on success, -1 on failure.
  697. */
  698. int
  699. set_options(or_options_t *new_val, char **msg)
  700. {
  701. int i;
  702. smartlist_t *elements;
  703. config_line_t *line;
  704. or_options_t *old_options = global_options;
  705. global_options = new_val;
  706. /* Note that we pass the *old* options below, for comparison. It
  707. * pulls the new options directly out of global_options. */
  708. if (options_act_reversible(old_options, msg)<0) {
  709. tor_assert(*msg);
  710. global_options = old_options;
  711. return -1;
  712. }
  713. if (options_act(old_options) < 0) { /* acting on the options failed. die. */
  714. log_err(LD_BUG,
  715. "Acting on config options left us in a broken state. Dying.");
  716. exit(1);
  717. }
  718. /* Issues a CONF_CHANGED event to notify controller of the change. If Tor is
  719. * just starting up then the old_options will be undefined. */
  720. if (old_options && old_options != global_options) {
  721. elements = smartlist_new();
  722. for (i=0; options_format.vars[i].name; ++i) {
  723. const config_var_t *var = &options_format.vars[i];
  724. const char *var_name = var->name;
  725. if (var->type == CONFIG_TYPE_LINELIST_S ||
  726. var->type == CONFIG_TYPE_OBSOLETE) {
  727. continue;
  728. }
  729. if (!option_is_same(&options_format, new_val, old_options, var_name)) {
  730. line = get_assigned_option(&options_format, new_val, var_name, 1);
  731. if (line) {
  732. for (; line; line = line->next) {
  733. smartlist_add(elements, line->key);
  734. smartlist_add(elements, line->value);
  735. }
  736. } else {
  737. smartlist_add(elements, (char*)options_format.vars[i].name);
  738. smartlist_add(elements, NULL);
  739. }
  740. }
  741. }
  742. control_event_conf_changed(elements);
  743. smartlist_free(elements);
  744. }
  745. if (old_options != global_options)
  746. config_free(&options_format, old_options);
  747. return 0;
  748. }
  749. extern const char tor_git_revision[]; /* from tor_main.c */
  750. /** The version of this Tor process, as parsed. */
  751. static char *the_tor_version = NULL;
  752. /** A shorter version of this Tor process's version, for export in our router
  753. * descriptor. (Does not include the git version, if any.) */
  754. static char *the_short_tor_version = NULL;
  755. /** Return the current Tor version. */
  756. const char *
  757. get_version(void)
  758. {
  759. if (the_tor_version == NULL) {
  760. if (strlen(tor_git_revision)) {
  761. tor_asprintf(&the_tor_version, "%s (git-%s)", get_short_version(),
  762. tor_git_revision);
  763. } else {
  764. the_tor_version = tor_strdup(get_short_version());
  765. }
  766. }
  767. return the_tor_version;
  768. }
  769. /** Return the current Tor version, without any git tag. */
  770. const char *
  771. get_short_version(void)
  772. {
  773. if (the_short_tor_version == NULL) {
  774. #ifdef TOR_BUILD_TAG
  775. tor_asprintf(&the_short_tor_version, "%s (%s)", VERSION, TOR_BUILD_TAG);
  776. #else
  777. the_short_tor_version = tor_strdup(VERSION);
  778. #endif
  779. }
  780. return the_short_tor_version;
  781. }
  782. /** Release additional memory allocated in options
  783. */
  784. static void
  785. or_options_free(or_options_t *options)
  786. {
  787. if (!options)
  788. return;
  789. routerset_free(options->_ExcludeExitNodesUnion);
  790. if (options->NodeFamilySets) {
  791. SMARTLIST_FOREACH(options->NodeFamilySets, routerset_t *,
  792. rs, routerset_free(rs));
  793. smartlist_free(options->NodeFamilySets);
  794. }
  795. tor_free(options->_BridgePassword_AuthDigest);
  796. config_free(&options_format, options);
  797. }
  798. /** Release all memory and resources held by global configuration structures.
  799. */
  800. void
  801. config_free_all(void)
  802. {
  803. or_options_free(global_options);
  804. global_options = NULL;
  805. or_options_free(global_default_options);
  806. global_default_options = NULL;
  807. config_free(&state_format, global_state);
  808. global_state = NULL;
  809. config_free_lines(global_cmdline_options);
  810. global_cmdline_options = NULL;
  811. if (configured_ports) {
  812. SMARTLIST_FOREACH(configured_ports,
  813. port_cfg_t *, p, tor_free(p));
  814. smartlist_free(configured_ports);
  815. configured_ports = NULL;
  816. }
  817. tor_free(torrc_fname);
  818. tor_free(torrc_defaults_fname);
  819. tor_free(the_tor_version);
  820. tor_free(global_dirfrontpagecontents);
  821. }
  822. /** Make <b>address</b> -- a piece of information related to our operation as
  823. * a client -- safe to log according to the settings in options->SafeLogging,
  824. * and return it.
  825. *
  826. * (We return "[scrubbed]" if SafeLogging is "1", and address otherwise.)
  827. */
  828. const char *
  829. safe_str_client(const char *address)
  830. {
  831. tor_assert(address);
  832. if (get_options()->_SafeLogging == SAFELOG_SCRUB_ALL)
  833. return "[scrubbed]";
  834. else
  835. return address;
  836. }
  837. /** Make <b>address</b> -- a piece of information of unspecified sensitivity
  838. * -- safe to log according to the settings in options->SafeLogging, and
  839. * return it.
  840. *
  841. * (We return "[scrubbed]" if SafeLogging is anything besides "0", and address
  842. * otherwise.)
  843. */
  844. const char *
  845. safe_str(const char *address)
  846. {
  847. tor_assert(address);
  848. if (get_options()->_SafeLogging != SAFELOG_SCRUB_NONE)
  849. return "[scrubbed]";
  850. else
  851. return address;
  852. }
  853. /** Equivalent to escaped(safe_str_client(address)). See reentrancy note on
  854. * escaped(): don't use this outside the main thread, or twice in the same
  855. * log statement. */
  856. const char *
  857. escaped_safe_str_client(const char *address)
  858. {
  859. if (get_options()->_SafeLogging == SAFELOG_SCRUB_ALL)
  860. return "[scrubbed]";
  861. else
  862. return escaped(address);
  863. }
  864. /** Equivalent to escaped(safe_str(address)). See reentrancy note on
  865. * escaped(): don't use this outside the main thread, or twice in the same
  866. * log statement. */
  867. const char *
  868. escaped_safe_str(const char *address)
  869. {
  870. if (get_options()->_SafeLogging != SAFELOG_SCRUB_NONE)
  871. return "[scrubbed]";
  872. else
  873. return escaped(address);
  874. }
  875. /** Add the default directory authorities directly into the trusted dir list,
  876. * but only add them insofar as they share bits with <b>type</b>. */
  877. static void
  878. add_default_trusted_dir_authorities(dirinfo_type_t type)
  879. {
  880. int i;
  881. const char *dirservers[] = {
  882. "moria1 orport=9101 no-v2 "
  883. "v3ident=D586D18309DED4CD6D57C18FDB97EFA96D330566 "
  884. "128.31.0.39:9131 9695 DFC3 5FFE B861 329B 9F1A B04C 4639 7020 CE31",
  885. "tor26 v1 orport=443 v3ident=14C131DFC5C6F93646BE72FA1401C02A8DF2E8B4 "
  886. "86.59.21.38:80 847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D",
  887. "dizum orport=443 v3ident=E8A9C45EDE6D711294FADF8E7951F4DE6CA56B58 "
  888. "194.109.206.212:80 7EA6 EAD6 FD83 083C 538F 4403 8BBF A077 587D D755",
  889. "Tonga orport=443 bridge no-v2 82.94.251.203:80 "
  890. "4A0C CD2D DC79 9508 3D73 F5D6 6710 0C8A 5831 F16D",
  891. "turtles orport=9090 no-v2 "
  892. "v3ident=27B6B5996C426270A5C95488AA5BCEB6BCC86956 "
  893. "76.73.17.194:9030 F397 038A DC51 3361 35E7 B80B D99C A384 4360 292B",
  894. "gabelmoo orport=443 no-v2 "
  895. "v3ident=ED03BB616EB2F60BEC80151114BB25CEF515B226 "
  896. "212.112.245.170:80 F204 4413 DAC2 E02E 3D6B CF47 35A1 9BCA 1DE9 7281",
  897. "dannenberg orport=443 no-v2 "
  898. "v3ident=585769C78764D58426B8B52B6651A5A71137189A "
  899. "193.23.244.244:80 7BE6 83E6 5D48 1413 21C5 ED92 F075 C553 64AC 7123",
  900. "urras orport=80 no-v2 v3ident=80550987E1D626E3EBA5E5E75A458DE0626D088C "
  901. "208.83.223.34:443 0AD3 FA88 4D18 F89E EA2D 89C0 1937 9E0E 7FD9 4417",
  902. "maatuska orport=80 no-v2 "
  903. "v3ident=49015F787433103580E3B66A1707A00E60F2D15B "
  904. "171.25.193.9:443 BD6A 8292 55CB 08E6 6FBE 7D37 4836 3586 E46B 3810",
  905. NULL
  906. };
  907. for (i=0; dirservers[i]; i++) {
  908. if (parse_dir_server_line(dirservers[i], type, 0)<0) {
  909. log_err(LD_BUG, "Couldn't parse internal dirserver line %s",
  910. dirservers[i]);
  911. }
  912. }
  913. }
  914. /** Look at all the config options for using alternate directory
  915. * authorities, and make sure none of them are broken. Also, warn the
  916. * user if we changed any dangerous ones.
  917. */
  918. static int
  919. validate_dir_authorities(or_options_t *options, or_options_t *old_options)
  920. {
  921. config_line_t *cl;
  922. if (options->DirServers &&
  923. (options->AlternateDirAuthority || options->AlternateBridgeAuthority ||
  924. options->AlternateHSAuthority)) {
  925. log_warn(LD_CONFIG,
  926. "You cannot set both DirServers and Alternate*Authority.");
  927. return -1;
  928. }
  929. /* do we want to complain to the user about being partitionable? */
  930. if ((options->DirServers &&
  931. (!old_options ||
  932. !config_lines_eq(options->DirServers, old_options->DirServers))) ||
  933. (options->AlternateDirAuthority &&
  934. (!old_options ||
  935. !config_lines_eq(options->AlternateDirAuthority,
  936. old_options->AlternateDirAuthority)))) {
  937. log_warn(LD_CONFIG,
  938. "You have used DirServer or AlternateDirAuthority to "
  939. "specify alternate directory authorities in "
  940. "your configuration. This is potentially dangerous: it can "
  941. "make you look different from all other Tor users, and hurt "
  942. "your anonymity. Even if you've specified the same "
  943. "authorities as Tor uses by default, the defaults could "
  944. "change in the future. Be sure you know what you're doing.");
  945. }
  946. /* Now go through the four ways you can configure an alternate
  947. * set of directory authorities, and make sure none are broken. */
  948. for (cl = options->DirServers; cl; cl = cl->next)
  949. if (parse_dir_server_line(cl->value, NO_DIRINFO, 1)<0)
  950. return -1;
  951. for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
  952. if (parse_dir_server_line(cl->value, NO_DIRINFO, 1)<0)
  953. return -1;
  954. for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
  955. if (parse_dir_server_line(cl->value, NO_DIRINFO, 1)<0)
  956. return -1;
  957. for (cl = options->AlternateHSAuthority; cl; cl = cl->next)
  958. if (parse_dir_server_line(cl->value, NO_DIRINFO, 1)<0)
  959. return -1;
  960. return 0;
  961. }
  962. /** Look at all the config options and assign new dir authorities
  963. * as appropriate.
  964. */
  965. static int
  966. consider_adding_dir_authorities(const or_options_t *options,
  967. const or_options_t *old_options)
  968. {
  969. config_line_t *cl;
  970. int need_to_update =
  971. !smartlist_len(router_get_trusted_dir_servers()) || !old_options ||
  972. !config_lines_eq(options->DirServers, old_options->DirServers) ||
  973. !config_lines_eq(options->AlternateBridgeAuthority,
  974. old_options->AlternateBridgeAuthority) ||
  975. !config_lines_eq(options->AlternateDirAuthority,
  976. old_options->AlternateDirAuthority) ||
  977. !config_lines_eq(options->AlternateHSAuthority,
  978. old_options->AlternateHSAuthority);
  979. if (!need_to_update)
  980. return 0; /* all done */
  981. /* Start from a clean slate. */
  982. clear_trusted_dir_servers();
  983. if (!options->DirServers) {
  984. /* then we may want some of the defaults */
  985. dirinfo_type_t type = NO_DIRINFO;
  986. if (!options->AlternateBridgeAuthority)
  987. type |= BRIDGE_DIRINFO;
  988. if (!options->AlternateDirAuthority)
  989. type |= V1_DIRINFO | V2_DIRINFO | V3_DIRINFO | EXTRAINFO_DIRINFO |
  990. MICRODESC_DIRINFO;
  991. if (!options->AlternateHSAuthority)
  992. type |= HIDSERV_DIRINFO;
  993. add_default_trusted_dir_authorities(type);
  994. }
  995. for (cl = options->DirServers; cl; cl = cl->next)
  996. if (parse_dir_server_line(cl->value, NO_DIRINFO, 0)<0)
  997. return -1;
  998. for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
  999. if (parse_dir_server_line(cl->value, NO_DIRINFO, 0)<0)
  1000. return -1;
  1001. for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
  1002. if (parse_dir_server_line(cl->value, NO_DIRINFO, 0)<0)
  1003. return -1;
  1004. for (cl = options->AlternateHSAuthority; cl; cl = cl->next)
  1005. if (parse_dir_server_line(cl->value, NO_DIRINFO, 0)<0)
  1006. return -1;
  1007. return 0;
  1008. }
  1009. /** Fetch the active option list, and take actions based on it. All of the
  1010. * things we do should survive being done repeatedly. If present,
  1011. * <b>old_options</b> contains the previous value of the options.
  1012. *
  1013. * Return 0 if all goes well, return -1 if things went badly.
  1014. */
  1015. static int
  1016. options_act_reversible(const or_options_t *old_options, char **msg)
  1017. {
  1018. smartlist_t *new_listeners = smartlist_new();
  1019. smartlist_t *replaced_listeners = smartlist_new();
  1020. static int libevent_initialized = 0;
  1021. or_options_t *options = get_options_mutable();
  1022. int running_tor = options->command == CMD_RUN_TOR;
  1023. int set_conn_limit = 0;
  1024. int r = -1;
  1025. int logs_marked = 0;
  1026. /* Daemonize _first_, since we only want to open most of this stuff in
  1027. * the subprocess. Libevent bases can't be reliably inherited across
  1028. * processes. */
  1029. if (running_tor && options->RunAsDaemon) {
  1030. /* No need to roll back, since you can't change the value. */
  1031. start_daemon();
  1032. }
  1033. #ifndef HAVE_SYS_UN_H
  1034. if (options->ControlSocket || options->ControlSocketsGroupWritable) {
  1035. *msg = tor_strdup("Unix domain sockets (ControlSocket) not supported "
  1036. "on this OS/with this build.");
  1037. goto rollback;
  1038. }
  1039. #else
  1040. if (options->ControlSocketsGroupWritable && !options->ControlSocket) {
  1041. *msg = tor_strdup("Setting ControlSocketGroupWritable without setting"
  1042. "a ControlSocket makes no sense.");
  1043. goto rollback;
  1044. }
  1045. #endif
  1046. if (running_tor) {
  1047. int n_ports=0;
  1048. /* We need to set the connection limit before we can open the listeners. */
  1049. if (set_max_file_descriptors((unsigned)options->ConnLimit,
  1050. &options->_ConnLimit) < 0) {
  1051. *msg = tor_strdup("Problem with ConnLimit value. See logs for details.");
  1052. goto rollback;
  1053. }
  1054. set_conn_limit = 1;
  1055. /* Set up libevent. (We need to do this before we can register the
  1056. * listeners as listeners.) */
  1057. if (running_tor && !libevent_initialized) {
  1058. init_libevent(options);
  1059. libevent_initialized = 1;
  1060. }
  1061. /* Adjust the port configuration so we can launch listeners. */
  1062. if (parse_ports(options, 0, msg, &n_ports)) {
  1063. if (!*msg)
  1064. *msg = tor_strdup("Unexpected problem parsing port config");
  1065. goto rollback;
  1066. }
  1067. /* Set the hibernation state appropriately.*/
  1068. consider_hibernation(time(NULL));
  1069. /* Launch the listeners. (We do this before we setuid, so we can bind to
  1070. * ports under 1024.) We don't want to rebind if we're hibernating. If
  1071. * networking is disabled, this will close all but the control listeners,
  1072. * but disable those. */
  1073. if (!we_are_hibernating()) {
  1074. if (retry_all_listeners(replaced_listeners, new_listeners,
  1075. options->DisableNetwork) < 0) {
  1076. *msg = tor_strdup("Failed to bind one of the listener ports.");
  1077. goto rollback;
  1078. }
  1079. }
  1080. if (options->DisableNetwork) {
  1081. /* Aggressively close non-controller stuff, NOW */
  1082. log_notice(LD_NET, "DisableNetwork is set. Tor will not make or accept "
  1083. "non-control network connections. Shutting down all existing "
  1084. "connections.");
  1085. connection_mark_all_noncontrol_connections();
  1086. }
  1087. }
  1088. #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
  1089. /* Open /dev/pf before dropping privileges. */
  1090. if (options->TransPort_set) {
  1091. if (get_pf_socket() < 0) {
  1092. *msg = tor_strdup("Unable to open /dev/pf for transparent proxy.");
  1093. goto rollback;
  1094. }
  1095. }
  1096. #endif
  1097. /* Attempt to lock all current and future memory with mlockall() only once */
  1098. if (options->DisableAllSwap) {
  1099. if (tor_mlockall() == -1) {
  1100. *msg = tor_strdup("DisableAllSwap failure. Do you have proper "
  1101. "permissions?");
  1102. goto done;
  1103. }
  1104. }
  1105. /* Setuid/setgid as appropriate */
  1106. if (options->User) {
  1107. if (switch_id(options->User) != 0) {
  1108. /* No need to roll back, since you can't change the value. */
  1109. *msg = tor_strdup("Problem with User value. See logs for details.");
  1110. goto done;
  1111. }
  1112. }
  1113. /* Ensure data directory is private; create if possible. */
  1114. if (check_private_dir(options->DataDirectory,
  1115. running_tor ? CPD_CREATE : CPD_CHECK,
  1116. options->User)<0) {
  1117. tor_asprintf(msg,
  1118. "Couldn't access/create private data directory \"%s\"",
  1119. options->DataDirectory);
  1120. goto done;
  1121. /* No need to roll back, since you can't change the value. */
  1122. }
  1123. /* Write control ports to disk as appropriate */
  1124. control_ports_write_to_file();
  1125. if (directory_caches_v2_dir_info(options)) {
  1126. char *fn = NULL;
  1127. tor_asprintf(&fn, "%s"PATH_SEPARATOR"cached-status",
  1128. options->DataDirectory);
  1129. if (check_private_dir(fn, running_tor ? CPD_CREATE : CPD_CHECK,
  1130. options->User) < 0) {
  1131. tor_asprintf(msg,
  1132. "Couldn't access/create private data directory \"%s\"", fn);
  1133. tor_free(fn);
  1134. goto done;
  1135. }
  1136. tor_free(fn);
  1137. }
  1138. /* Bail out at this point if we're not going to be a client or server:
  1139. * we don't run Tor itself. */
  1140. if (!running_tor)
  1141. goto commit;
  1142. mark_logs_temp(); /* Close current logs once new logs are open. */
  1143. logs_marked = 1;
  1144. if (options_init_logs(options, 0)<0) { /* Configure the log(s) */
  1145. *msg = tor_strdup("Failed to init Log options. See logs for details.");
  1146. goto rollback;
  1147. }
  1148. commit:
  1149. r = 0;
  1150. if (logs_marked) {
  1151. log_severity_list_t *severity =
  1152. tor_malloc_zero(sizeof(log_severity_list_t));
  1153. close_temp_logs();
  1154. add_callback_log(severity, control_event_logmsg);
  1155. control_adjust_event_log_severity();
  1156. tor_free(severity);
  1157. }
  1158. SMARTLIST_FOREACH(replaced_listeners, connection_t *, conn,
  1159. {
  1160. log_notice(LD_NET, "Closing old %s on %s:%d",
  1161. conn_type_to_string(conn->type), conn->address, conn->port);
  1162. connection_close_immediate(conn);
  1163. connection_mark_for_close(conn);
  1164. });
  1165. goto done;
  1166. rollback:
  1167. r = -1;
  1168. tor_assert(*msg);
  1169. if (logs_marked) {
  1170. rollback_log_changes();
  1171. control_adjust_event_log_severity();
  1172. }
  1173. if (set_conn_limit && old_options)
  1174. set_max_file_descriptors((unsigned)old_options->ConnLimit,
  1175. &options->_ConnLimit);
  1176. SMARTLIST_FOREACH(new_listeners, connection_t *, conn,
  1177. {
  1178. log_notice(LD_NET, "Closing partially-constructed %s on %s:%d",
  1179. conn_type_to_string(conn->type), conn->address, conn->port);
  1180. connection_close_immediate(conn);
  1181. connection_mark_for_close(conn);
  1182. });
  1183. done:
  1184. smartlist_free(new_listeners);
  1185. smartlist_free(replaced_listeners);
  1186. return r;
  1187. }
  1188. /** If we need to have a GEOIP ip-to-country map to run with our configured
  1189. * options, return 1 and set *<b>reason_out</b> to a description of why. */
  1190. int
  1191. options_need_geoip_info(const or_options_t *options, const char **reason_out)
  1192. {
  1193. int bridge_usage =
  1194. options->BridgeRelay && options->BridgeRecordUsageByCountry;
  1195. int routerset_usage =
  1196. routerset_needs_geoip(options->EntryNodes) ||
  1197. routerset_needs_geoip(options->ExitNodes) ||
  1198. routerset_needs_geoip(options->ExcludeExitNodes) ||
  1199. routerset_needs_geoip(options->ExcludeNodes);
  1200. if (routerset_usage && reason_out) {
  1201. *reason_out = "We've been configured to use (or avoid) nodes in certain "
  1202. "countries, and we need GEOIP information to figure out which ones they "
  1203. "are.";
  1204. } else if (bridge_usage && reason_out) {
  1205. *reason_out = "We've been configured to see which countries can access "
  1206. "us as a bridge, and we need GEOIP information to tell which countries "
  1207. "clients are in.";
  1208. }
  1209. return bridge_usage || routerset_usage;
  1210. }
  1211. /** Return the bandwidthrate that we are going to report to the authorities
  1212. * based on the config options. */
  1213. uint32_t
  1214. get_effective_bwrate(const or_options_t *options)
  1215. {
  1216. uint64_t bw = options->BandwidthRate;
  1217. if (bw > options->MaxAdvertisedBandwidth)
  1218. bw = options->MaxAdvertisedBandwidth;
  1219. if (options->RelayBandwidthRate > 0 && bw > options->RelayBandwidthRate)
  1220. bw = options->RelayBandwidthRate;
  1221. /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
  1222. return (uint32_t)bw;
  1223. }
  1224. /** Return the bandwidthburst that we are going to report to the authorities
  1225. * based on the config options. */
  1226. uint32_t
  1227. get_effective_bwburst(const or_options_t *options)
  1228. {
  1229. uint64_t bw = options->BandwidthBurst;
  1230. if (options->RelayBandwidthBurst > 0 && bw > options->RelayBandwidthBurst)
  1231. bw = options->RelayBandwidthBurst;
  1232. /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
  1233. return (uint32_t)bw;
  1234. }
  1235. /** Return True if any changes from <b>old_options</b> to
  1236. * <b>new_options</b> needs us to refresh our TLS context. */
  1237. static int
  1238. options_transition_requires_fresh_tls_context(const or_options_t *old_options,
  1239. const or_options_t *new_options)
  1240. {
  1241. tor_assert(new_options);
  1242. if (!old_options)
  1243. return 0;
  1244. if ((old_options->DynamicDHGroups != new_options->DynamicDHGroups)) {
  1245. return 1;
  1246. }
  1247. return 0;
  1248. }
  1249. /** Fetch the active option list, and take actions based on it. All of the
  1250. * things we do should survive being done repeatedly. If present,
  1251. * <b>old_options</b> contains the previous value of the options.
  1252. *
  1253. * Return 0 if all goes well, return -1 if it's time to die.
  1254. *
  1255. * Note: We haven't moved all the "act on new configuration" logic
  1256. * here yet. Some is still in do_hup() and other places.
  1257. */
  1258. static int
  1259. options_act(const or_options_t *old_options)
  1260. {
  1261. config_line_t *cl;
  1262. or_options_t *options = get_options_mutable();
  1263. int running_tor = options->command == CMD_RUN_TOR;
  1264. char *msg;
  1265. const int transition_affects_workers =
  1266. old_options && options_transition_affects_workers(old_options, options);
  1267. /* disable ptrace and later, other basic debugging techniques */
  1268. {
  1269. /* Remember if we already disabled debugger attachment */
  1270. static int disabled_debugger_attach = 0;
  1271. /* Remember if we already warned about being configured not to disable
  1272. * debugger attachment */
  1273. static int warned_debugger_attach = 0;
  1274. /* Don't disable debugger attachment when we're running the unit tests. */
  1275. if (options->DisableDebuggerAttachment && !disabled_debugger_attach &&
  1276. running_tor) {
  1277. int ok = tor_disable_debugger_attach();
  1278. if (warned_debugger_attach && ok == 1) {
  1279. log_notice(LD_CONFIG, "Disabled attaching debuggers for unprivileged "
  1280. "users.");
  1281. }
  1282. disabled_debugger_attach = (ok == 1);
  1283. } else if (!options->DisableDebuggerAttachment &&
  1284. !warned_debugger_attach) {
  1285. log_notice(LD_CONFIG, "Not disabling debugger attaching for "
  1286. "unprivileged users.");
  1287. warned_debugger_attach = 1;
  1288. }
  1289. }
  1290. if (running_tor && !have_lockfile()) {
  1291. if (try_locking(options, 1) < 0)
  1292. return -1;
  1293. }
  1294. if (consider_adding_dir_authorities(options, old_options) < 0)
  1295. return -1;
  1296. #ifdef NON_ANONYMOUS_MODE_ENABLED
  1297. log(LOG_WARN, LD_GENERAL, "This copy of Tor was compiled to run in a "
  1298. "non-anonymous mode. It will provide NO ANONYMITY.");
  1299. #endif
  1300. #ifdef ENABLE_TOR2WEB_MODE
  1301. if (!options->Tor2webMode) {
  1302. log_err(LD_CONFIG, "This copy of Tor was compiled to run in "
  1303. "'tor2web mode'. It can only be run with the Tor2webMode torrc "
  1304. "option enabled.");
  1305. return -1;
  1306. }
  1307. #else
  1308. if (options->Tor2webMode) {
  1309. log_err(LD_CONFIG, "This copy of Tor was not compiled to run in "
  1310. "'tor2web mode'. It cannot be run with the Tor2webMode torrc "
  1311. "option enabled. To enable Tor2webMode recompile with the "
  1312. "--enable-tor2webmode option.");
  1313. return -1;
  1314. }
  1315. #endif
  1316. if (options->Bridges) {
  1317. mark_bridge_list();
  1318. for (cl = options->Bridges; cl; cl = cl->next) {
  1319. if (parse_bridge_line(cl->value, 0)<0) {
  1320. log_warn(LD_BUG,
  1321. "Previously validated Bridge line could not be added!");
  1322. return -1;
  1323. }
  1324. }
  1325. sweep_bridge_list();
  1326. }
  1327. if (running_tor && rend_config_services(options, 0)<0) {
  1328. log_warn(LD_BUG,
  1329. "Previously validated hidden services line could not be added!");
  1330. return -1;
  1331. }
  1332. if (running_tor && rend_parse_service_authorization(options, 0) < 0) {
  1333. log_warn(LD_BUG, "Previously validated client authorization for "
  1334. "hidden services could not be added!");
  1335. return -1;
  1336. }
  1337. /* Load state */
  1338. if (! global_state && running_tor) {
  1339. if (or_state_load())
  1340. return -1;
  1341. rep_hist_load_mtbf_data(time(NULL));
  1342. }
  1343. mark_transport_list();
  1344. pt_prepare_proxy_list_for_config_read();
  1345. if (options->ClientTransportPlugin) {
  1346. for (cl = options->ClientTransportPlugin; cl; cl = cl->next) {
  1347. if (parse_client_transport_line(cl->value, 0)<0) {
  1348. log_warn(LD_BUG,
  1349. "Previously validated ClientTransportPlugin line "
  1350. "could not be added!");
  1351. return -1;
  1352. }
  1353. }
  1354. }
  1355. if (options->ServerTransportPlugin && server_mode(options)) {
  1356. for (cl = options->ServerTransportPlugin; cl; cl = cl->next) {
  1357. if (parse_server_transport_line(cl->value, 0)<0) {
  1358. log_warn(LD_BUG,
  1359. "Previously validated ServerTransportPlugin line "
  1360. "could not be added!");
  1361. return -1;
  1362. }
  1363. }
  1364. }
  1365. sweep_transport_list();
  1366. sweep_proxy_list();
  1367. /* Bail out at this point if we're not going to be a client or server:
  1368. * we want to not fork, and to log stuff to stderr. */
  1369. if (!running_tor)
  1370. return 0;
  1371. /* Finish backgrounding the process */
  1372. if (options->RunAsDaemon) {
  1373. /* We may be calling this for the n'th time (on SIGHUP), but it's safe. */
  1374. finish_daemon(options->DataDirectory);
  1375. }
  1376. /* If needed, generate a new TLS DH prime according to the current torrc. */
  1377. if (server_mode(options) && options->DynamicDHGroups) {
  1378. char *keydir = get_datadir_fname("keys");
  1379. if (check_private_dir(keydir, CPD_CREATE, options->User)) {
  1380. tor_free(keydir);
  1381. return -1;
  1382. }
  1383. tor_free(keydir);
  1384. if (!old_options || !old_options->DynamicDHGroups) {
  1385. char *fname = get_datadir_fname2("keys", "dynamic_dh_params");
  1386. crypto_set_tls_dh_prime(fname);
  1387. tor_free(fname);
  1388. }
  1389. } else { /* clients don't need a dynamic DH prime. */
  1390. crypto_set_tls_dh_prime(NULL);
  1391. }
  1392. /* We want to reinit keys as needed before we do much of anything else:
  1393. keys are important, and other things can depend on them. */
  1394. if (transition_affects_workers ||
  1395. (options->V3AuthoritativeDir && (!old_options ||
  1396. !old_options->V3AuthoritativeDir))) {
  1397. if (init_keys() < 0) {
  1398. log_warn(LD_BUG,"Error initializing keys; exiting");
  1399. return -1;
  1400. }
  1401. } else if (old_options &&
  1402. options_transition_requires_fresh_tls_context(old_options,
  1403. options)) {
  1404. if (router_initialize_tls_context() < 0) {
  1405. log_warn(LD_BUG,"Error initializing TLS context.");
  1406. return -1;
  1407. }
  1408. }
  1409. /* Write our PID to the PID file. If we do not have write permissions we
  1410. * will log a warning */
  1411. if (options->PidFile)
  1412. write_pidfile(options->PidFile);
  1413. /* Register addressmap directives */
  1414. config_register_addressmaps(options);
  1415. parse_virtual_addr_network(options->VirtualAddrNetwork, 0, &msg);
  1416. /* Update address policies. */
  1417. if (policies_parse_from_options(options) < 0) {
  1418. /* This should be impossible, but let's be sure. */
  1419. log_warn(LD_BUG,"Error parsing already-validated policy options.");
  1420. return -1;
  1421. }
  1422. if (init_cookie_authentication(options->CookieAuthentication) < 0) {
  1423. log_warn(LD_CONFIG,"Error creating cookie authentication file.");
  1424. return -1;
  1425. }
  1426. monitor_owning_controller_process(options->OwningControllerProcess);
  1427. /* reload keys as needed for rendezvous services. */
  1428. if (rend_service_load_all_keys()<0) {
  1429. log_warn(LD_GENERAL,"Error loading rendezvous service keys");
  1430. return -1;
  1431. }
  1432. /* Set up accounting */
  1433. if (accounting_parse_options(options, 0)<0) {
  1434. log_warn(LD_CONFIG,"Error in accounting options");
  1435. return -1;
  1436. }
  1437. if (accounting_is_enabled(options))
  1438. configure_accounting(time(NULL));
  1439. #ifdef USE_BUFFEREVENTS
  1440. /* If we're using the bufferevents implementation and our rate limits
  1441. * changed, we need to tell the rate-limiting system about it. */
  1442. if (!old_options ||
  1443. old_options->BandwidthRate != options->BandwidthRate ||
  1444. old_options->BandwidthBurst != options->BandwidthBurst ||
  1445. old_options->RelayBandwidthRate != options->RelayBandwidthRate ||
  1446. old_options->RelayBandwidthBurst != options->RelayBandwidthBurst)
  1447. connection_bucket_init();
  1448. #endif
  1449. /* Change the cell EWMA settings */
  1450. cell_ewma_set_scale_factor(options, networkstatus_get_latest_consensus());
  1451. /* Update the BridgePassword's hashed version as needed. We store this as a
  1452. * digest so that we can do side-channel-proof comparisons on it.
  1453. */
  1454. if (options->BridgePassword) {
  1455. char *http_authenticator;
  1456. http_authenticator = alloc_http_authenticator(options->BridgePassword);
  1457. if (!http_authenticator) {
  1458. log_warn(LD_BUG, "Unable to allocate HTTP authenticator. Not setting "
  1459. "BridgePassword.");
  1460. return -1;
  1461. }
  1462. options->_BridgePassword_AuthDigest = tor_malloc(DIGEST256_LEN);
  1463. crypto_digest256(options->_BridgePassword_AuthDigest,
  1464. http_authenticator, strlen(http_authenticator),
  1465. DIGEST_SHA256);
  1466. tor_free(http_authenticator);
  1467. }
  1468. /* Check for transitions that need action. */
  1469. if (old_options) {
  1470. int revise_trackexithosts = 0;
  1471. int revise_automap_entries = 0;
  1472. if ((options->UseEntryGuards && !old_options->UseEntryGuards) ||
  1473. options->UseBridges != old_options->UseBridges ||
  1474. (options->UseBridges &&
  1475. !config_lines_eq(options->Bridges, old_options->Bridges)) ||
  1476. !routerset_equal(old_options->ExcludeNodes,options->ExcludeNodes) ||
  1477. !routerset_equal(old_options->ExcludeExitNodes,
  1478. options->ExcludeExitNodes) ||
  1479. !routerset_equal(old_options->EntryNodes, options->EntryNodes) ||
  1480. !routerset_equal(old_options->ExitNodes, options->ExitNodes) ||
  1481. options->StrictNodes != old_options->StrictNodes) {
  1482. log_info(LD_CIRC,
  1483. "Changed to using entry guards or bridges, or changed "
  1484. "preferred or excluded node lists. "
  1485. "Abandoning previous circuits.");
  1486. circuit_mark_all_unused_circs();
  1487. circuit_expire_all_dirty_circs();
  1488. revise_trackexithosts = 1;
  1489. }
  1490. if (!smartlist_strings_eq(old_options->TrackHostExits,
  1491. options->TrackHostExits))
  1492. revise_trackexithosts = 1;
  1493. if (revise_trackexithosts)
  1494. addressmap_clear_excluded_trackexithosts(options);
  1495. if (!options->AutomapHostsOnResolve) {
  1496. if (old_options->AutomapHostsOnResolve)
  1497. revise_automap_entries = 1;
  1498. } else {
  1499. if (!smartlist_strings_eq(old_options->AutomapHostsSuffixes,
  1500. options->AutomapHostsSuffixes))
  1501. revise_automap_entries = 1;
  1502. else if (!opt_streq(old_options->VirtualAddrNetwork,
  1503. options->VirtualAddrNetwork))
  1504. revise_automap_entries = 1;
  1505. }
  1506. if (revise_automap_entries)
  1507. addressmap_clear_invalid_automaps(options);
  1508. /* How long should we delay counting bridge stats after becoming a bridge?
  1509. * We use this so we don't count people who used our bridge thinking it is
  1510. * a relay. If you change this, don't forget to change the log message
  1511. * below. It's 4 hours (the time it takes to stop being used by clients)
  1512. * plus some extra time for clock skew. */
  1513. #define RELAY_BRIDGE_STATS_DELAY (6 * 60 * 60)
  1514. if (! bool_eq(options->BridgeRelay, old_options->BridgeRelay)) {
  1515. int was_relay = 0;
  1516. if (options->BridgeRelay) {
  1517. time_t int_start = time(NULL);
  1518. if (config_lines_eq(old_options->ORPort_lines,options->ORPort_lines)) {
  1519. int_start += RELAY_BRIDGE_STATS_DELAY;
  1520. was_relay = 1;
  1521. }
  1522. geoip_bridge_stats_init(int_start);
  1523. log_info(LD_CONFIG, "We are acting as a bridge now. Starting new "
  1524. "GeoIP stats interval%s.", was_relay ? " in 6 "
  1525. "hours from now" : "");
  1526. } else {
  1527. geoip_bridge_stats_term();
  1528. log_info(LD_GENERAL, "We are no longer acting as a bridge. "
  1529. "Forgetting GeoIP stats.");
  1530. }
  1531. }
  1532. if (transition_affects_workers) {
  1533. log_info(LD_GENERAL,
  1534. "Worker-related options changed. Rotating workers.");
  1535. if (server_mode(options) && !server_mode(old_options)) {
  1536. ip_address_changed(0);
  1537. if (can_complete_circuit || !any_predicted_circuits(time(NULL)))
  1538. inform_testing_reachability();
  1539. }
  1540. cpuworkers_rotate();
  1541. if (dns_reset())
  1542. return -1;
  1543. } else {
  1544. if (dns_reset())
  1545. return -1;
  1546. }
  1547. if (options->PerConnBWRate != old_options->PerConnBWRate ||
  1548. options->PerConnBWBurst != old_options->PerConnBWBurst)
  1549. connection_or_update_token_buckets(get_connection_array(), options);
  1550. }
  1551. /* Maybe load geoip file */
  1552. if (options->GeoIPFile &&
  1553. ((!old_options || !opt_streq(old_options->GeoIPFile, options->GeoIPFile))
  1554. || !geoip_is_loaded())) {
  1555. /* XXXX Don't use this "<default>" junk; make our filename options
  1556. * understand prefixes somehow. -NM */
  1557. /* XXXX024 Reload GeoIPFile on SIGHUP. -NM */
  1558. char *actual_fname = tor_strdup(options->GeoIPFile);
  1559. #ifdef _WIN32
  1560. if (!strcmp(actual_fname, "<default>")) {
  1561. const char *conf_root = get_windows_conf_root();
  1562. tor_free(actual_fname);
  1563. tor_asprintf(&actual_fname, "%s\\geoip", conf_root);
  1564. }
  1565. #endif
  1566. geoip_load_file(actual_fname, options);
  1567. tor_free(actual_fname);
  1568. }
  1569. if (options->CellStatistics || options->DirReqStatistics ||
  1570. options->EntryStatistics || options->ExitPortStatistics ||
  1571. options->ConnDirectionStatistics ||
  1572. options->BridgeAuthoritativeDir) {
  1573. time_t now = time(NULL);
  1574. int print_notice = 0;
  1575. /* If we aren't acting as a server, we can't collect stats anyway. */
  1576. if (!server_mode(options)) {
  1577. options->CellStatistics = 0;
  1578. options->DirReqStatistics = 0;
  1579. options->EntryStatistics = 0;
  1580. options->ExitPortStatistics = 0;
  1581. }
  1582. if ((!old_options || !old_options->CellStatistics) &&
  1583. options->CellStatistics) {
  1584. rep_hist_buffer_stats_init(now);
  1585. print_notice = 1;
  1586. }
  1587. if ((!old_options || !old_options->DirReqStatistics) &&
  1588. options->DirReqStatistics) {
  1589. if (geoip_is_loaded()) {
  1590. geoip_dirreq_stats_init(now);
  1591. print_notice = 1;
  1592. } else {
  1593. options->DirReqStatistics = 0;
  1594. /* Don't warn Tor clients, they don't use statistics */
  1595. if (options->ORPort_set)
  1596. log_notice(LD_CONFIG, "Configured to measure directory request "
  1597. "statistics, but no GeoIP database found. "
  1598. "Please specify a GeoIP database using the "
  1599. "GeoIPFile option.");
  1600. }
  1601. }
  1602. if ((!old_options || !old_options->EntryStatistics) &&
  1603. options->EntryStatistics && !should_record_bridge_info(options)) {
  1604. if (geoip_is_loaded()) {
  1605. geoip_entry_stats_init(now);
  1606. print_notice = 1;
  1607. } else {
  1608. options->EntryStatistics = 0;
  1609. log_notice(LD_CONFIG, "Configured to measure entry node "
  1610. "statistics, but no GeoIP database found. "
  1611. "Please specify a GeoIP database using the "
  1612. "GeoIPFile option.");
  1613. }
  1614. }
  1615. if ((!old_options || !old_options->ExitPortStatistics) &&
  1616. options->ExitPortStatistics) {
  1617. rep_hist_exit_stats_init(now);
  1618. print_notice = 1;
  1619. }
  1620. if ((!old_options || !old_options->ConnDirectionStatistics) &&
  1621. options->ConnDirectionStatistics) {
  1622. rep_hist_conn_stats_init(now);
  1623. }
  1624. if ((!old_options || !old_options->BridgeAuthoritativeDir) &&
  1625. options->BridgeAuthoritativeDir) {
  1626. rep_hist_desc_stats_init(now);
  1627. print_notice = 1;
  1628. }
  1629. if (print_notice)
  1630. log_notice(LD_CONFIG, "Configured to measure statistics. Look for "
  1631. "the *-stats files that will first be written to the "
  1632. "data directory in 24 hours from now.");
  1633. }
  1634. if (old_options && old_options->CellStatistics &&
  1635. !options->CellStatistics)
  1636. rep_hist_buffer_stats_term();
  1637. if (old_options && old_options->DirReqStatistics &&
  1638. !options->DirReqStatistics)
  1639. geoip_dirreq_stats_term();
  1640. if (old_options && old_options->EntryStatistics &&
  1641. !options->EntryStatistics)
  1642. geoip_entry_stats_term();
  1643. if (old_options && old_options->ExitPortStatistics &&
  1644. !options->ExitPortStatistics)
  1645. rep_hist_exit_stats_term();
  1646. if (old_options && old_options->ConnDirectionStatistics &&
  1647. !options->ConnDirectionStatistics)
  1648. rep_hist_conn_stats_term();
  1649. if (old_options && old_options->BridgeAuthoritativeDir &&
  1650. !options->BridgeAuthoritativeDir)
  1651. rep_hist_desc_stats_term();
  1652. /* Check if we need to parse and add the EntryNodes config option. */
  1653. if (options->EntryNodes &&
  1654. (!old_options ||
  1655. !routerset_equal(old_options->EntryNodes,options->EntryNodes) ||
  1656. !routerset_equal(old_options->ExcludeNodes,options->ExcludeNodes)))
  1657. entry_nodes_should_be_added();
  1658. /* Since our options changed, we might need to regenerate and upload our
  1659. * server descriptor.
  1660. */
  1661. if (!old_options ||
  1662. options_transition_affects_descriptor(old_options, options))
  1663. mark_my_descriptor_dirty("config change");
  1664. /* We may need to reschedule some directory stuff if our status changed. */
  1665. if (old_options) {
  1666. if (authdir_mode_v3(options) && !authdir_mode_v3(old_options))
  1667. dirvote_recalculate_timing(options, time(NULL));
  1668. if (!bool_eq(directory_fetches_dir_info_early(options),
  1669. directory_fetches_dir_info_early(old_options)) ||
  1670. !bool_eq(directory_fetches_dir_info_later(options),
  1671. directory_fetches_dir_info_later(old_options))) {
  1672. /* Make sure update_router_have_min_dir_info gets called. */
  1673. router_dir_info_changed();
  1674. /* We might need to download a new consensus status later or sooner than
  1675. * we had expected. */
  1676. update_consensus_networkstatus_fetch_time(time(NULL));
  1677. }
  1678. }
  1679. /* Load the webpage we're going to serve every time someone asks for '/' on
  1680. our DirPort. */
  1681. tor_free(global_dirfrontpagecontents);
  1682. if (options->DirPortFrontPage) {
  1683. global_dirfrontpagecontents =
  1684. read_file_to_str(options->DirPortFrontPage, 0, NULL);
  1685. if (!global_dirfrontpagecontents) {
  1686. log_warn(LD_CONFIG,
  1687. "DirPortFrontPage file '%s' not found. Continuing anyway.",
  1688. options->DirPortFrontPage);
  1689. }
  1690. }
  1691. return 0;
  1692. }
  1693. /*
  1694. * Functions to parse config options
  1695. */
  1696. /** If <b>option</b> is an official abbreviation for a longer option,
  1697. * return the longer option. Otherwise return <b>option</b>.
  1698. * If <b>command_line</b> is set, apply all abbreviations. Otherwise, only
  1699. * apply abbreviations that work for the config file and the command line.
  1700. * If <b>warn_obsolete</b> is set, warn about deprecated names. */
  1701. static const char *
  1702. expand_abbrev(const config_format_t *fmt, const char *option, int command_line,
  1703. int warn_obsolete)
  1704. {
  1705. int i;
  1706. if (! fmt->abbrevs)
  1707. return option;
  1708. for (i=0; fmt->abbrevs[i].abbreviated; ++i) {
  1709. /* Abbreviations are case insensitive. */
  1710. if (!strcasecmp(option,fmt->abbrevs[i].abbreviated) &&
  1711. (command_line || !fmt->abbrevs[i].commandline_only)) {
  1712. if (warn_obsolete && fmt->abbrevs[i].warn) {
  1713. log_warn(LD_CONFIG,
  1714. "The configuration option '%s' is deprecated; "
  1715. "use '%s' instead.",
  1716. fmt->abbrevs[i].abbreviated,
  1717. fmt->abbrevs[i].full);
  1718. }
  1719. /* Keep going through the list in case we want to rewrite it more.
  1720. * (We could imagine recursing here, but I don't want to get the
  1721. * user into an infinite loop if we craft our list wrong.) */
  1722. option = fmt->abbrevs[i].full;
  1723. }
  1724. }
  1725. return option;
  1726. }
  1727. /** Helper: Read a list of configuration options from the command line.
  1728. * If successful, put them in *<b>result</b> and return 0, and return
  1729. * -1 and leave *<b>result</b> alone. */
  1730. static int
  1731. config_get_commandlines(int argc, char **argv, config_line_t **result)
  1732. {
  1733. config_line_t *front = NULL;
  1734. config_line_t **new = &front;
  1735. char *s;
  1736. int i = 1;
  1737. while (i < argc) {
  1738. unsigned command = CONFIG_LINE_NORMAL;
  1739. int want_arg = 1;
  1740. if (!strcmp(argv[i],"-f") ||
  1741. !strcmp(argv[i],"--defaults-torrc") ||
  1742. !strcmp(argv[i],"--hash-password")) {
  1743. i += 2; /* command-line option with argument. ignore them. */
  1744. continue;
  1745. } else if (!strcmp(argv[i],"--list-fingerprint") ||
  1746. !strcmp(argv[i],"--verify-config") ||
  1747. !strcmp(argv[i],"--ignore-missing-torrc") ||
  1748. !strcmp(argv[i],"--quiet") ||
  1749. !strcmp(argv[i],"--hush")) {
  1750. i += 1; /* command-line option. ignore it. */
  1751. continue;
  1752. } else if (!strcmp(argv[i],"--nt-service") ||
  1753. !strcmp(argv[i],"-nt-service")) {
  1754. i += 1;
  1755. continue;
  1756. }
  1757. *new = tor_malloc_zero(sizeof(config_line_t));
  1758. s = argv[i];
  1759. /* Each keyword may be prefixed with one or two dashes. */
  1760. if (*s == '-')
  1761. s++;
  1762. if (*s == '-')
  1763. s++;
  1764. /* Figure out the command, if any. */
  1765. if (*s == '+') {
  1766. s++;
  1767. command = CONFIG_LINE_APPEND;
  1768. } else if (*s == '/') {
  1769. s++;
  1770. command = CONFIG_LINE_CLEAR;
  1771. /* A 'clear' command has no argument. */
  1772. want_arg = 0;
  1773. }
  1774. if (want_arg && i == argc-1) {
  1775. log_warn(LD_CONFIG,"Command-line option '%s' with no value. Failing.",
  1776. argv[i]);
  1777. config_free_lines(front);
  1778. return -1;
  1779. }
  1780. (*new)->key = tor_strdup(expand_abbrev(&options_format, s, 1, 1));
  1781. (*new)->value = want_arg ? tor_strdup(argv[i+1]) : tor_strdup("");
  1782. (*new)->command = command;
  1783. (*new)->next = NULL;
  1784. log(LOG_DEBUG, LD_CONFIG, "command line: parsed keyword '%s', value '%s'",
  1785. (*new)->key, (*new)->value);
  1786. new = &((*new)->next);
  1787. i += want_arg ? 2 : 1;
  1788. }
  1789. *result = front;
  1790. return 0;
  1791. }
  1792. /** Helper: allocate a new configuration option mapping 'key' to 'val',
  1793. * append it to *<b>lst</b>. */
  1794. static void
  1795. config_line_append(config_line_t **lst,
  1796. const char *key,
  1797. const char *val)
  1798. {
  1799. config_line_t *newline;
  1800. newline = tor_malloc_zero(sizeof(config_line_t));
  1801. newline->key = tor_strdup(key);
  1802. newline->value = tor_strdup(val);
  1803. newline->next = NULL;
  1804. while (*lst)
  1805. lst = &((*lst)->next);
  1806. (*lst) = newline;
  1807. }
  1808. /** Helper: parse the config string and strdup into key/value
  1809. * strings. Set *result to the list, or NULL if parsing the string
  1810. * failed. Return 0 on success, -1 on failure. Warn and ignore any
  1811. * misformatted lines.
  1812. *
  1813. * If <b>extended</b> is set, then treat keys beginning with / and with + as
  1814. * indicating "clear" and "append" respectively. */
  1815. int
  1816. config_get_lines(const char *string, config_line_t **result, int extended)
  1817. {
  1818. config_line_t *list = NULL, **next;
  1819. char *k, *v;
  1820. next = &list;
  1821. do {
  1822. k = v = NULL;
  1823. string = parse_config_line_from_str(string, &k, &v);
  1824. if (!string) {
  1825. config_free_lines(list);
  1826. tor_free(k);
  1827. tor_free(v);
  1828. return -1;
  1829. }
  1830. if (k && v) {
  1831. unsigned command = CONFIG_LINE_NORMAL;
  1832. if (extended) {
  1833. if (k[0] == '+') {
  1834. char *k_new = tor_strdup(k+1);
  1835. tor_free(k);
  1836. k = k_new;
  1837. command = CONFIG_LINE_APPEND;
  1838. } else if (k[0] == '/') {
  1839. char *k_new = tor_strdup(k+1);
  1840. tor_free(k);
  1841. k = k_new;
  1842. tor_free(v);
  1843. v = tor_strdup("");
  1844. command = CONFIG_LINE_CLEAR;
  1845. }
  1846. }
  1847. /* This list can get long, so we keep a pointer to the end of it
  1848. * rather than using config_line_append over and over and getting
  1849. * n^2 performance. */
  1850. *next = tor_malloc_zero(sizeof(config_line_t));
  1851. (*next)->key = k;
  1852. (*next)->value = v;
  1853. (*next)->next = NULL;
  1854. (*next)->command = command;
  1855. next = &((*next)->next);
  1856. } else {
  1857. tor_free(k);
  1858. tor_free(v);
  1859. }
  1860. } while (*string);
  1861. *result = list;
  1862. return 0;
  1863. }
  1864. /**
  1865. * Free all the configuration lines on the linked list <b>front</b>.
  1866. */
  1867. void
  1868. config_free_lines(config_line_t *front)
  1869. {
  1870. config_line_t *tmp;
  1871. while (front) {
  1872. tmp = front;
  1873. front = tmp->next;
  1874. tor_free(tmp->key);
  1875. tor_free(tmp->value);
  1876. tor_free(tmp);
  1877. }
  1878. }
  1879. /** As config_find_option, but return a non-const pointer. */
  1880. static config_var_t *
  1881. config_find_option_mutable(config_format_t *fmt, const char *key)
  1882. {
  1883. int i;
  1884. size_t keylen = strlen(key);
  1885. if (!keylen)
  1886. return NULL; /* if they say "--" on the command line, it's not an option */
  1887. /* First, check for an exact (case-insensitive) match */
  1888. for (i=0; fmt->vars[i].name; ++i) {
  1889. if (!strcasecmp(key, fmt->vars[i].name)) {
  1890. return &fmt->vars[i];
  1891. }
  1892. }
  1893. /* If none, check for an abbreviated match */
  1894. for (i=0; fmt->vars[i].name; ++i) {
  1895. if (!strncasecmp(key, fmt->vars[i].name, keylen)) {
  1896. log_warn(LD_CONFIG, "The abbreviation '%s' is deprecated. "
  1897. "Please use '%s' instead",
  1898. key, fmt->vars[i].name);
  1899. return &fmt->vars[i];
  1900. }
  1901. }
  1902. /* Okay, unrecognized option */
  1903. return NULL;
  1904. }
  1905. /** If <b>key</b> is a configuration option, return the corresponding const
  1906. * config_var_t. Otherwise, if <b>key</b> is a non-standard abbreviation,
  1907. * warn, and return the corresponding const config_var_t. Otherwise return
  1908. * NULL.
  1909. */
  1910. static const config_var_t *
  1911. config_find_option(const config_format_t *fmt, const char *key)
  1912. {
  1913. return config_find_option_mutable((config_format_t*)fmt, key);
  1914. }
  1915. /** Return the number of option entries in <b>fmt</b>. */
  1916. static int
  1917. config_count_options(const config_format_t *fmt)
  1918. {
  1919. int i;
  1920. for (i=0; fmt->vars[i].name; ++i)
  1921. ;
  1922. return i;
  1923. }
  1924. /*
  1925. * Functions to assign config options.
  1926. */
  1927. /** <b>c</b>-\>key is known to be a real key. Update <b>options</b>
  1928. * with <b>c</b>-\>value and return 0, or return -1 if bad value.
  1929. *
  1930. * Called from config_assign_line() and option_reset().
  1931. */
  1932. static int
  1933. config_assign_value(const config_format_t *fmt, or_options_t *options,
  1934. config_line_t *c, char **msg)
  1935. {
  1936. int i, ok;
  1937. const config_var_t *var;
  1938. void *lvalue;
  1939. CHECK(fmt, options);
  1940. var = config_find_option(fmt, c->key);
  1941. tor_assert(var);
  1942. lvalue = STRUCT_VAR_P(options, var->var_offset);
  1943. switch (var->type) {
  1944. case CONFIG_TYPE_PORT:
  1945. if (!strcasecmp(c->value, "auto")) {
  1946. *(int *)lvalue = CFG_AUTO_PORT;
  1947. break;
  1948. }
  1949. /* fall through */
  1950. case CONFIG_TYPE_INT:
  1951. case CONFIG_TYPE_UINT:
  1952. i = (int)tor_parse_long(c->value, 10,
  1953. var->type==CONFIG_TYPE_INT ? INT_MIN : 0,
  1954. var->type==CONFIG_TYPE_PORT ? 65535 : INT_MAX,
  1955. &ok, NULL);
  1956. if (!ok) {
  1957. tor_asprintf(msg,
  1958. "Int keyword '%s %s' is malformed or out of bounds.",
  1959. c->key, c->value);
  1960. return -1;
  1961. }
  1962. *(int *)lvalue = i;
  1963. break;
  1964. case CONFIG_TYPE_INTERVAL: {
  1965. i = config_parse_interval(c->value, &ok);
  1966. if (!ok) {
  1967. tor_asprintf(msg,
  1968. "Interval '%s %s' is malformed or out of bounds.",
  1969. c->key, c->value);
  1970. return -1;
  1971. }
  1972. *(int *)lvalue = i;
  1973. break;
  1974. }
  1975. case CONFIG_TYPE_MSEC_INTERVAL: {
  1976. i = config_parse_msec_interval(c->value, &ok);
  1977. if (!ok) {
  1978. tor_asprintf(msg,
  1979. "Msec interval '%s %s' is malformed or out of bounds.",
  1980. c->key, c->value);
  1981. return -1;
  1982. }
  1983. *(int *)lvalue = i;
  1984. break;
  1985. }
  1986. case CONFIG_TYPE_MEMUNIT: {
  1987. uint64_t u64 = config_parse_memunit(c->value, &ok);
  1988. if (!ok) {
  1989. tor_asprintf(msg,
  1990. "Value '%s %s' is malformed or out of bounds.",
  1991. c->key, c->value);
  1992. return -1;
  1993. }
  1994. *(uint64_t *)lvalue = u64;
  1995. break;
  1996. }
  1997. case CONFIG_TYPE_BOOL:
  1998. i = (int)tor_parse_long(c->value, 10, 0, 1, &ok, NULL);
  1999. if (!ok) {
  2000. tor_asprintf(msg,
  2001. "Boolean '%s %s' expects 0 or 1.",
  2002. c->key, c->value);
  2003. return -1;
  2004. }
  2005. *(int *)lvalue = i;
  2006. break;
  2007. case CONFIG_TYPE_AUTOBOOL:
  2008. if (!strcmp(c->value, "auto"))
  2009. *(int *)lvalue = -1;
  2010. else if (!strcmp(c->value, "0"))
  2011. *(int *)lvalue = 0;
  2012. else if (!strcmp(c->value, "1"))
  2013. *(int *)lvalue = 1;
  2014. else {
  2015. tor_asprintf(msg, "Boolean '%s %s' expects 0, 1, or 'auto'.",
  2016. c->key, c->value);
  2017. return -1;
  2018. }
  2019. break;
  2020. case CONFIG_TYPE_STRING:
  2021. case CONFIG_TYPE_FILENAME:
  2022. tor_free(*(char **)lvalue);
  2023. *(char **)lvalue = tor_strdup(c->value);
  2024. break;
  2025. case CONFIG_TYPE_DOUBLE:
  2026. *(double *)lvalue = atof(c->value);
  2027. break;
  2028. case CONFIG_TYPE_ISOTIME:
  2029. if (parse_iso_time(c->value, (time_t *)lvalue)) {
  2030. tor_asprintf(msg,
  2031. "Invalid time '%s' for keyword '%s'", c->value, c->key);
  2032. return -1;
  2033. }
  2034. break;
  2035. case CONFIG_TYPE_ROUTERSET:
  2036. if (*(routerset_t**)lvalue) {
  2037. routerset_free(*(routerset_t**)lvalue);
  2038. }
  2039. *(routerset_t**)lvalue = routerset_new();
  2040. if (routerset_parse(*(routerset_t**)lvalue, c->value, c->key)<0) {
  2041. tor_asprintf(msg, "Invalid exit list '%s' for option '%s'",
  2042. c->value, c->key);
  2043. return -1;
  2044. }
  2045. break;
  2046. case CONFIG_TYPE_CSV:
  2047. if (*(smartlist_t**)lvalue) {
  2048. SMARTLIST_FOREACH(*(smartlist_t**)lvalue, char *, cp, tor_free(cp));
  2049. smartlist_clear(*(smartlist_t**)lvalue);
  2050. } else {
  2051. *(smartlist_t**)lvalue = smartlist_new();
  2052. }
  2053. smartlist_split_string(*(smartlist_t**)lvalue, c->value, ",",
  2054. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2055. break;
  2056. case CONFIG_TYPE_LINELIST:
  2057. case CONFIG_TYPE_LINELIST_S:
  2058. {
  2059. config_line_t *lastval = *(config_line_t**)lvalue;
  2060. if (lastval && lastval->fragile) {
  2061. if (c->command != CONFIG_LINE_APPEND) {
  2062. config_free_lines(lastval);
  2063. *(config_line_t**)lvalue = NULL;
  2064. } else {
  2065. lastval->fragile = 0;
  2066. }
  2067. }
  2068. config_line_append((config_line_t**)lvalue, c->key, c->value);
  2069. }
  2070. break;
  2071. case CONFIG_TYPE_OBSOLETE:
  2072. log_warn(LD_CONFIG, "Skipping obsolete configuration option '%s'", c->key);
  2073. break;
  2074. case CONFIG_TYPE_LINELIST_V:
  2075. tor_asprintf(msg,
  2076. "You may not provide a value for virtual option '%s'", c->key);
  2077. return -1;
  2078. default:
  2079. tor_assert(0);
  2080. break;
  2081. }
  2082. return 0;
  2083. }
  2084. /** Mark every linelist in <b>options</b> "fragile", so that fresh assignments
  2085. * to it will replace old ones. */
  2086. static void
  2087. config_mark_lists_fragile(const config_format_t *fmt, or_options_t *options)
  2088. {
  2089. int i;
  2090. tor_assert(fmt);
  2091. tor_assert(options);
  2092. for (i = 0; fmt->vars[i].name; ++i) {
  2093. const config_var_t *var = &fmt->vars[i];
  2094. config_line_t *list;
  2095. if (var->type != CONFIG_TYPE_LINELIST &&
  2096. var->type != CONFIG_TYPE_LINELIST_V)
  2097. continue;
  2098. list = *(config_line_t **)STRUCT_VAR_P(options, var->var_offset);
  2099. if (list)
  2100. list->fragile = 1;
  2101. }
  2102. }
  2103. /** If <b>c</b> is a syntactically valid configuration line, update
  2104. * <b>options</b> with its value and return 0. Otherwise return -1 for bad
  2105. * key, -2 for bad value.
  2106. *
  2107. * If <b>clear_first</b> is set, clear the value first. Then if
  2108. * <b>use_defaults</b> is set, set the value to the default.
  2109. *
  2110. * Called from config_assign().
  2111. */
  2112. static int
  2113. config_assign_line(const config_format_t *fmt, or_options_t *options,
  2114. config_line_t *c, int use_defaults,
  2115. int clear_first, bitarray_t *options_seen, char **msg)
  2116. {
  2117. const config_var_t *var;
  2118. CHECK(fmt, options);
  2119. var = config_find_option(fmt, c->key);
  2120. if (!var) {
  2121. if (fmt->extra) {
  2122. void *lvalue = STRUCT_VAR_P(options, fmt->extra->var_offset);
  2123. log_info(LD_CONFIG,
  2124. "Found unrecognized option '%s'; saving it.", c->key);
  2125. config_line_append((config_line_t**)lvalue, c->key, c->value);
  2126. return 0;
  2127. } else {
  2128. tor_asprintf(msg,
  2129. "Unknown option '%s'. Failing.", c->key);
  2130. return -1;
  2131. }
  2132. }
  2133. /* Put keyword into canonical case. */
  2134. if (strcmp(var->name, c->key)) {
  2135. tor_free(c->key);
  2136. c->key = tor_strdup(var->name);
  2137. }
  2138. if (!strlen(c->value)) {
  2139. /* reset or clear it, then return */
  2140. if (!clear_first) {
  2141. if ((var->type == CONFIG_TYPE_LINELIST ||
  2142. var->type == CONFIG_TYPE_LINELIST_S) &&
  2143. c->command != CONFIG_LINE_CLEAR) {
  2144. /* We got an empty linelist from the torrc or command line.
  2145. As a special case, call this an error. Warn and ignore. */
  2146. log_warn(LD_CONFIG,
  2147. "Linelist option '%s' has no value. Skipping.", c->key);
  2148. } else { /* not already cleared */
  2149. option_reset(fmt, options, var, use_defaults);
  2150. }
  2151. }
  2152. return 0;
  2153. } else if (c->command == CONFIG_LINE_CLEAR && !clear_first) {
  2154. option_reset(fmt, options, var, use_defaults);
  2155. }
  2156. if (options_seen && (var->type != CONFIG_TYPE_LINELIST &&
  2157. var->type != CONFIG_TYPE_LINELIST_S)) {
  2158. /* We're tracking which options we've seen, and this option is not
  2159. * supposed to occur more than once. */
  2160. int var_index = (int)(var - fmt->vars);
  2161. if (bitarray_is_set(options_seen, var_index)) {
  2162. log_warn(LD_CONFIG, "Option '%s' used more than once; all but the last "
  2163. "value will be ignored.", var->name);
  2164. }
  2165. bitarray_set(options_seen, var_index);
  2166. }
  2167. if (config_assign_value(fmt, options, c, msg) < 0)
  2168. return -2;
  2169. return 0;
  2170. }
  2171. /** Restore the option named <b>key</b> in options to its default value.
  2172. * Called from config_assign(). */
  2173. static void
  2174. config_reset_line(const config_format_t *fmt, or_options_t *options,
  2175. const char *key, int use_defaults)
  2176. {
  2177. const config_var_t *var;
  2178. CHECK(fmt, options);
  2179. var = config_find_option(fmt, key);
  2180. if (!var)
  2181. return; /* give error on next pass. */
  2182. option_reset(fmt, options, var, use_defaults);
  2183. }
  2184. /** Return true iff key is a valid configuration option. */
  2185. int
  2186. option_is_recognized(const char *key)
  2187. {
  2188. const config_var_t *var = config_find_option(&options_format, key);
  2189. return (var != NULL);
  2190. }
  2191. /** Return the canonical name of a configuration option, or NULL
  2192. * if no such option exists. */
  2193. const char *
  2194. option_get_canonical_name(const char *key)
  2195. {
  2196. const config_var_t *var = config_find_option(&options_format, key);
  2197. return var ? var->name : NULL;
  2198. }
  2199. /** Return a canonical list of the options assigned for key.
  2200. */
  2201. config_line_t *
  2202. option_get_assignment(const or_options_t *options, const char *key)
  2203. {
  2204. return get_assigned_option(&options_format, options, key, 1);
  2205. }
  2206. /** Return true iff value needs to be quoted and escaped to be used in
  2207. * a configuration file. */
  2208. static int
  2209. config_value_needs_escape(const char *value)
  2210. {
  2211. if (*value == '\"')
  2212. return 1;
  2213. while (*value) {
  2214. switch (*value)
  2215. {
  2216. case '\r':
  2217. case '\n':
  2218. case '#':
  2219. /* Note: quotes and backspaces need special handling when we are using
  2220. * quotes, not otherwise, so they don't trigger escaping on their
  2221. * own. */
  2222. return 1;
  2223. default:
  2224. if (!TOR_ISPRINT(*value))
  2225. return 1;
  2226. }
  2227. ++value;
  2228. }
  2229. return 0;
  2230. }
  2231. /** Return a newly allocated deep copy of the lines in <b>inp</b>. */
  2232. static config_line_t *
  2233. config_lines_dup(const config_line_t *inp)
  2234. {
  2235. config_line_t *result = NULL;
  2236. config_line_t **next_out = &result;
  2237. while (inp) {
  2238. *next_out = tor_malloc_zero(sizeof(config_line_t));
  2239. (*next_out)->key = tor_strdup(inp->key);
  2240. (*next_out)->value = tor_strdup(inp->value);
  2241. inp = inp->next;
  2242. next_out = &((*next_out)->next);
  2243. }
  2244. (*next_out) = NULL;
  2245. return result;
  2246. }
  2247. /** Return newly allocated line or lines corresponding to <b>key</b> in the
  2248. * configuration <b>options</b>. If <b>escape_val</b> is true and a
  2249. * value needs to be quoted before it's put in a config file, quote and
  2250. * escape that value. Return NULL if no such key exists. */
  2251. static config_line_t *
  2252. get_assigned_option(const config_format_t *fmt, const void *options,
  2253. const char *key, int escape_val)
  2254. {
  2255. const config_var_t *var;
  2256. const void *value;
  2257. config_line_t *result;
  2258. tor_assert(options && key);
  2259. CHECK(fmt, options);
  2260. var = config_find_option(fmt, key);
  2261. if (!var) {
  2262. log_warn(LD_CONFIG, "Unknown option '%s'. Failing.", key);
  2263. return NULL;
  2264. }
  2265. value = STRUCT_VAR_P(options, var->var_offset);
  2266. result = tor_malloc_zero(sizeof(config_line_t));
  2267. result->key = tor_strdup(var->name);
  2268. switch (var->type)
  2269. {
  2270. case CONFIG_TYPE_STRING:
  2271. case CONFIG_TYPE_FILENAME:
  2272. if (*(char**)value) {
  2273. result->value = tor_strdup(*(char**)value);
  2274. } else {
  2275. tor_free(result->key);
  2276. tor_free(result);
  2277. return NULL;
  2278. }
  2279. break;
  2280. case CONFIG_TYPE_ISOTIME:
  2281. if (*(time_t*)value) {
  2282. result->value = tor_malloc(ISO_TIME_LEN+1);
  2283. format_iso_time(result->value, *(time_t*)value);
  2284. } else {
  2285. tor_free(result->key);
  2286. tor_free(result);
  2287. }
  2288. escape_val = 0; /* Can't need escape. */
  2289. break;
  2290. case CONFIG_TYPE_PORT:
  2291. if (*(int*)value == CFG_AUTO_PORT) {
  2292. result->value = tor_strdup("auto");
  2293. escape_val = 0;
  2294. break;
  2295. }
  2296. /* fall through */
  2297. case CONFIG_TYPE_INTERVAL:
  2298. case CONFIG_TYPE_MSEC_INTERVAL:
  2299. case CONFIG_TYPE_UINT:
  2300. case CONFIG_TYPE_INT:
  2301. /* This means every or_options_t uint or bool element
  2302. * needs to be an int. Not, say, a uint16_t or char. */
  2303. tor_asprintf(&result->value, "%d", *(int*)value);
  2304. escape_val = 0; /* Can't need escape. */
  2305. break;
  2306. case CONFIG_TYPE_MEMUNIT:
  2307. tor_asprintf(&result->value, U64_FORMAT,
  2308. U64_PRINTF_ARG(*(uint64_t*)value));
  2309. escape_val = 0; /* Can't need escape. */
  2310. break;
  2311. case CONFIG_TYPE_DOUBLE:
  2312. tor_asprintf(&result->value, "%f", *(double*)value);
  2313. escape_val = 0; /* Can't need escape. */
  2314. break;
  2315. case CONFIG_TYPE_AUTOBOOL:
  2316. if (*(int*)value == -1) {
  2317. result->value = tor_strdup("auto");
  2318. escape_val = 0;
  2319. break;
  2320. }
  2321. /* fall through */
  2322. case CONFIG_TYPE_BOOL:
  2323. result->value = tor_strdup(*(int*)value ? "1" : "0");
  2324. escape_val = 0; /* Can't need escape. */
  2325. break;
  2326. case CONFIG_TYPE_ROUTERSET:
  2327. result->value = routerset_to_string(*(routerset_t**)value);
  2328. break;
  2329. case CONFIG_TYPE_CSV:
  2330. if (*(smartlist_t**)value)
  2331. result->value =
  2332. smartlist_join_strings(*(smartlist_t**)value, ",", 0, NULL);
  2333. else
  2334. result->value = tor_strdup("");
  2335. break;
  2336. case CONFIG_TYPE_OBSOLETE:
  2337. log_fn(LOG_PROTOCOL_WARN, LD_CONFIG,
  2338. "You asked me for the value of an obsolete config option '%s'.",
  2339. key);
  2340. tor_free(result->key);
  2341. tor_free(result);
  2342. return NULL;
  2343. case CONFIG_TYPE_LINELIST_S:
  2344. log_warn(LD_CONFIG,
  2345. "Can't return context-sensitive '%s' on its own", key);
  2346. tor_free(result->key);
  2347. tor_free(result);
  2348. return NULL;
  2349. case CONFIG_TYPE_LINELIST:
  2350. case CONFIG_TYPE_LINELIST_V:
  2351. tor_free(result->key);
  2352. tor_free(result);
  2353. result = config_lines_dup(*(const config_line_t**)value);
  2354. break;
  2355. default:
  2356. tor_free(result->key);
  2357. tor_free(result);
  2358. log_warn(LD_BUG,"Unknown type %d for known key '%s'",
  2359. var->type, key);
  2360. return NULL;
  2361. }
  2362. if (escape_val) {
  2363. config_line_t *line;
  2364. for (line = result; line; line = line->next) {
  2365. if (line->value && config_value_needs_escape(line->value)) {
  2366. char *newval = esc_for_log(line->value);
  2367. tor_free(line->value);
  2368. line->value = newval;
  2369. }
  2370. }
  2371. }
  2372. return result;
  2373. }
  2374. /** Iterate through the linked list of requested options <b>list</b>.
  2375. * For each item, convert as appropriate and assign to <b>options</b>.
  2376. * If an item is unrecognized, set *msg and return -1 immediately,
  2377. * else return 0 for success.
  2378. *
  2379. * If <b>clear_first</b>, interpret config options as replacing (not
  2380. * extending) their previous values. If <b>clear_first</b> is set,
  2381. * then <b>use_defaults</b> to decide if you set to defaults after
  2382. * clearing, or make the value 0 or NULL.
  2383. *
  2384. * Here are the use cases:
  2385. * 1. A non-empty AllowInvalid line in your torrc. Appends to current
  2386. * if linelist, replaces current if csv.
  2387. * 2. An empty AllowInvalid line in your torrc. Should clear it.
  2388. * 3. "RESETCONF AllowInvalid" sets it to default.
  2389. * 4. "SETCONF AllowInvalid" makes it NULL.
  2390. * 5. "SETCONF AllowInvalid=foo" clears it and sets it to "foo".
  2391. *
  2392. * Use_defaults Clear_first
  2393. * 0 0 "append"
  2394. * 1 0 undefined, don't use
  2395. * 0 1 "set to null first"
  2396. * 1 1 "set to defaults first"
  2397. * Return 0 on success, -1 on bad key, -2 on bad value.
  2398. *
  2399. * As an additional special case, if a LINELIST config option has
  2400. * no value and clear_first is 0, then warn and ignore it.
  2401. */
  2402. /*
  2403. There are three call cases for config_assign() currently.
  2404. Case one: Torrc entry
  2405. options_init_from_torrc() calls config_assign(0, 0)
  2406. calls config_assign_line(0, 0).
  2407. if value is empty, calls option_reset(0) and returns.
  2408. calls config_assign_value(), appends.
  2409. Case two: setconf
  2410. options_trial_assign() calls config_assign(0, 1)
  2411. calls config_reset_line(0)
  2412. calls option_reset(0)
  2413. calls option_clear().
  2414. calls config_assign_line(0, 1).
  2415. if value is empty, returns.
  2416. calls config_assign_value(), appends.
  2417. Case three: resetconf
  2418. options_trial_assign() calls config_assign(1, 1)
  2419. calls config_reset_line(1)
  2420. calls option_reset(1)
  2421. calls option_clear().
  2422. calls config_assign_value(default)
  2423. calls config_assign_line(1, 1).
  2424. returns.
  2425. */
  2426. static int
  2427. config_assign(const config_format_t *fmt, void *options, config_line_t *list,
  2428. int use_defaults, int clear_first, char **msg)
  2429. {
  2430. config_line_t *p;
  2431. bitarray_t *options_seen;
  2432. const int n_options = config_count_options(fmt);
  2433. CHECK(fmt, options);
  2434. /* pass 1: normalize keys */
  2435. for (p = list; p; p = p->next) {
  2436. const char *full = expand_abbrev(fmt, p->key, 0, 1);
  2437. if (strcmp(full,p->key)) {
  2438. tor_free(p->key);
  2439. p->key = tor_strdup(full);
  2440. }
  2441. }
  2442. /* pass 2: if we're reading from a resetting source, clear all
  2443. * mentioned config options, and maybe set to their defaults. */
  2444. if (clear_first) {
  2445. for (p = list; p; p = p->next)
  2446. config_reset_line(fmt, options, p->key, use_defaults);
  2447. }
  2448. options_seen = bitarray_init_zero(n_options);
  2449. /* pass 3: assign. */
  2450. while (list) {
  2451. int r;
  2452. if ((r=config_assign_line(fmt, options, list, use_defaults,
  2453. clear_first, options_seen, msg))) {
  2454. bitarray_free(options_seen);
  2455. return r;
  2456. }
  2457. list = list->next;
  2458. }
  2459. bitarray_free(options_seen);
  2460. /** Now we're done assigning a group of options to the configuration.
  2461. * Subsequent group assignments should _replace_ linelists, not extend
  2462. * them. */
  2463. config_mark_lists_fragile(fmt, options);
  2464. return 0;
  2465. }
  2466. /** Try assigning <b>list</b> to the global options. You do this by duping
  2467. * options, assigning list to the new one, then validating it. If it's
  2468. * ok, then throw out the old one and stick with the new one. Else,
  2469. * revert to old and return failure. Return SETOPT_OK on success, or
  2470. * a setopt_err_t on failure.
  2471. *
  2472. * If not success, point *<b>msg</b> to a newly allocated string describing
  2473. * what went wrong.
  2474. */
  2475. setopt_err_t
  2476. options_trial_assign(config_line_t *list, int use_defaults,
  2477. int clear_first, char **msg)
  2478. {
  2479. int r;
  2480. or_options_t *trial_options = options_dup(&options_format, get_options());
  2481. if ((r=config_assign(&options_format, trial_options,
  2482. list, use_defaults, clear_first, msg)) < 0) {
  2483. config_free(&options_format, trial_options);
  2484. return r;
  2485. }
  2486. if (options_validate(get_options_mutable(), trial_options, 1, msg) < 0) {
  2487. config_free(&options_format, trial_options);
  2488. return SETOPT_ERR_PARSE; /*XXX make this a separate return value. */
  2489. }
  2490. if (options_transition_allowed(get_options(), trial_options, msg) < 0) {
  2491. config_free(&options_format, trial_options);
  2492. return SETOPT_ERR_TRANSITION;
  2493. }
  2494. if (set_options(trial_options, msg)<0) {
  2495. config_free(&options_format, trial_options);
  2496. return SETOPT_ERR_SETTING;
  2497. }
  2498. /* we liked it. put it in place. */
  2499. return SETOPT_OK;
  2500. }
  2501. /** Reset config option <b>var</b> to 0, 0.0, NULL, or the equivalent.
  2502. * Called from option_reset() and config_free(). */
  2503. static void
  2504. option_clear(const config_format_t *fmt, or_options_t *options,
  2505. const config_var_t *var)
  2506. {
  2507. void *lvalue = STRUCT_VAR_P(options, var->var_offset);
  2508. (void)fmt; /* unused */
  2509. switch (var->type) {
  2510. case CONFIG_TYPE_STRING:
  2511. case CONFIG_TYPE_FILENAME:
  2512. tor_free(*(char**)lvalue);
  2513. break;
  2514. case CONFIG_TYPE_DOUBLE:
  2515. *(double*)lvalue = 0.0;
  2516. break;
  2517. case CONFIG_TYPE_ISOTIME:
  2518. *(time_t*)lvalue = 0;
  2519. break;
  2520. case CONFIG_TYPE_INTERVAL:
  2521. case CONFIG_TYPE_MSEC_INTERVAL:
  2522. case CONFIG_TYPE_UINT:
  2523. case CONFIG_TYPE_INT:
  2524. case CONFIG_TYPE_PORT:
  2525. case CONFIG_TYPE_BOOL:
  2526. *(int*)lvalue = 0;
  2527. break;
  2528. case CONFIG_TYPE_AUTOBOOL:
  2529. *(int*)lvalue = -1;
  2530. break;
  2531. case CONFIG_TYPE_MEMUNIT:
  2532. *(uint64_t*)lvalue = 0;
  2533. break;
  2534. case CONFIG_TYPE_ROUTERSET:
  2535. if (*(routerset_t**)lvalue) {
  2536. routerset_free(*(routerset_t**)lvalue);
  2537. *(routerset_t**)lvalue = NULL;
  2538. }
  2539. break;
  2540. case CONFIG_TYPE_CSV:
  2541. if (*(smartlist_t**)lvalue) {
  2542. SMARTLIST_FOREACH(*(smartlist_t **)lvalue, char *, cp, tor_free(cp));
  2543. smartlist_free(*(smartlist_t **)lvalue);
  2544. *(smartlist_t **)lvalue = NULL;
  2545. }
  2546. break;
  2547. case CONFIG_TYPE_LINELIST:
  2548. case CONFIG_TYPE_LINELIST_S:
  2549. config_free_lines(*(config_line_t **)lvalue);
  2550. *(config_line_t **)lvalue = NULL;
  2551. break;
  2552. case CONFIG_TYPE_LINELIST_V:
  2553. /* handled by linelist_s. */
  2554. break;
  2555. case CONFIG_TYPE_OBSOLETE:
  2556. break;
  2557. }
  2558. }
  2559. /** Clear the option indexed by <b>var</b> in <b>options</b>. Then if
  2560. * <b>use_defaults</b>, set it to its default value.
  2561. * Called by config_init() and option_reset_line() and option_assign_line(). */
  2562. static void
  2563. option_reset(const config_format_t *fmt, or_options_t *options,
  2564. const config_var_t *var, int use_defaults)
  2565. {
  2566. config_line_t *c;
  2567. char *msg = NULL;
  2568. CHECK(fmt, options);
  2569. option_clear(fmt, options, var); /* clear it first */
  2570. if (!use_defaults)
  2571. return; /* all done */
  2572. if (var->initvalue) {
  2573. c = tor_malloc_zero(sizeof(config_line_t));
  2574. c->key = tor_strdup(var->name);
  2575. c->value = tor_strdup(var->initvalue);
  2576. if (config_assign_value(fmt, options, c, &msg) < 0) {
  2577. log_warn(LD_BUG, "Failed to assign default: %s", msg);
  2578. tor_free(msg); /* if this happens it's a bug */
  2579. }
  2580. config_free_lines(c);
  2581. }
  2582. }
  2583. /** Print a usage message for tor. */
  2584. static void
  2585. print_usage(void)
  2586. {
  2587. printf(
  2588. "Copyright (c) 2001-2004, Roger Dingledine\n"
  2589. "Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson\n"
  2590. "Copyright (c) 2007-2012, The Tor Project, Inc.\n\n"
  2591. "tor -f <torrc> [args]\n"
  2592. "See man page for options, or https://www.torproject.org/ for "
  2593. "documentation.\n");
  2594. }
  2595. /** Print all non-obsolete torrc options. */
  2596. static void
  2597. list_torrc_options(void)
  2598. {
  2599. int i;
  2600. smartlist_t *lines = smartlist_new();
  2601. for (i = 0; _option_vars[i].name; ++i) {
  2602. const config_var_t *var = &_option_vars[i];
  2603. if (var->type == CONFIG_TYPE_OBSOLETE ||
  2604. var->type == CONFIG_TYPE_LINELIST_V)
  2605. continue;
  2606. printf("%s\n", var->name);
  2607. }
  2608. smartlist_free(lines);
  2609. }
  2610. /** Last value actually set by resolve_my_address. */
  2611. static uint32_t last_resolved_addr = 0;
  2612. /**
  2613. * Based on <b>options-\>Address</b>, guess our public IP address and put it
  2614. * (in host order) into *<b>addr_out</b>. If <b>hostname_out</b> is provided,
  2615. * set *<b>hostname_out</b> to a new string holding the hostname we used to
  2616. * get the address. Return 0 if all is well, or -1 if we can't find a suitable
  2617. * public IP address.
  2618. * XXXX ipv6
  2619. */
  2620. int
  2621. resolve_my_address(int warn_severity, const or_options_t *options,
  2622. uint32_t *addr_out, char **hostname_out)
  2623. {
  2624. struct in_addr in;
  2625. uint32_t addr; /* host order */
  2626. char hostname[256];
  2627. int explicit_ip=1;
  2628. int explicit_hostname=1;
  2629. int from_interface=0;
  2630. char *addr_string = NULL;
  2631. const char *address = options->Address;
  2632. int notice_severity = warn_severity <= LOG_NOTICE ?
  2633. LOG_NOTICE : warn_severity;
  2634. tor_assert(addr_out);
  2635. if (address && *address) {
  2636. strlcpy(hostname, address, sizeof(hostname));
  2637. } else { /* then we need to guess our address */
  2638. explicit_ip = 0; /* it's implicit */
  2639. explicit_hostname = 0; /* it's implicit */
  2640. if (gethostname(hostname, sizeof(hostname)) < 0) {
  2641. log_fn(warn_severity, LD_NET,"Error obtaining local hostname");
  2642. return -1;
  2643. }
  2644. log_debug(LD_CONFIG,"Guessed local host name as '%s'",hostname);
  2645. }
  2646. /* now we know hostname. resolve it and keep only the IP address */
  2647. if (tor_inet_aton(hostname, &in) == 0) {
  2648. /* then we have to resolve it */
  2649. explicit_ip = 0;
  2650. if (tor_lookup_hostname(hostname, &addr)) { /* failed to resolve */
  2651. uint32_t interface_ip; /* host order */
  2652. if (explicit_hostname) {
  2653. log_fn(warn_severity, LD_CONFIG,
  2654. "Could not resolve local Address '%s'. Failing.", hostname);
  2655. return -1;
  2656. }
  2657. log_fn(notice_severity, LD_CONFIG,
  2658. "Could not resolve guessed local hostname '%s'. "
  2659. "Trying something else.", hostname);
  2660. if (get_interface_address(warn_severity, &interface_ip)) {
  2661. log_fn(warn_severity, LD_CONFIG,
  2662. "Could not get local interface IP address. Failing.");
  2663. return -1;
  2664. }
  2665. from_interface = 1;
  2666. addr = interface_ip;
  2667. log_fn(notice_severity, LD_CONFIG, "Learned IP address '%s' for "
  2668. "local interface. Using that.", fmt_addr32(addr));
  2669. strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
  2670. } else { /* resolved hostname into addr */
  2671. if (!explicit_hostname &&
  2672. is_internal_IP(addr, 0)) {
  2673. uint32_t interface_ip;
  2674. log_fn(notice_severity, LD_CONFIG, "Guessed local hostname '%s' "
  2675. "resolves to a private IP address (%s). Trying something "
  2676. "else.", hostname, fmt_addr32(addr));
  2677. if (get_interface_address(warn_severity, &interface_ip)) {
  2678. log_fn(warn_severity, LD_CONFIG,
  2679. "Could not get local interface IP address. Too bad.");
  2680. } else if (is_internal_IP(interface_ip, 0)) {
  2681. log_fn(notice_severity, LD_CONFIG,
  2682. "Interface IP address '%s' is a private address too. "
  2683. "Ignoring.", fmt_addr32(interface_ip));
  2684. } else {
  2685. from_interface = 1;
  2686. addr = interface_ip;
  2687. log_fn(notice_severity, LD_CONFIG,
  2688. "Learned IP address '%s' for local interface."
  2689. " Using that.", fmt_addr32(addr));
  2690. strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
  2691. }
  2692. }
  2693. }
  2694. } else {
  2695. addr = ntohl(in.s_addr); /* set addr so that addr_string is not
  2696. * illformed */
  2697. }
  2698. addr_string = tor_dup_ip(addr);
  2699. if (is_internal_IP(addr, 0)) {
  2700. /* make sure we're ok with publishing an internal IP */
  2701. if (!options->DirServers && !options->AlternateDirAuthority) {
  2702. /* if they are using the default dirservers, disallow internal IPs
  2703. * always. */
  2704. log_fn(warn_severity, LD_CONFIG,
  2705. "Address '%s' resolves to private IP address '%s'. "
  2706. "Tor servers that use the default DirServers must have public "
  2707. "IP addresses.", hostname, addr_string);
  2708. tor_free(addr_string);
  2709. return -1;
  2710. }
  2711. if (!explicit_ip) {
  2712. /* even if they've set their own dirservers, require an explicit IP if
  2713. * they're using an internal address. */
  2714. log_fn(warn_severity, LD_CONFIG, "Address '%s' resolves to private "
  2715. "IP address '%s'. Please set the Address config option to be "
  2716. "the IP address you want to use.", hostname, addr_string);
  2717. tor_free(addr_string);
  2718. return -1;
  2719. }
  2720. }
  2721. log_debug(LD_CONFIG, "Resolved Address to '%s'.", fmt_addr32(addr));
  2722. *addr_out = addr;
  2723. if (last_resolved_addr && last_resolved_addr != *addr_out) {
  2724. /* Leave this as a notice, regardless of the requested severity,
  2725. * at least until dynamic IP address support becomes bulletproof. */
  2726. log_notice(LD_NET,
  2727. "Your IP address seems to have changed to %s. Updating.",
  2728. addr_string);
  2729. ip_address_changed(0);
  2730. }
  2731. if (last_resolved_addr != *addr_out) {
  2732. const char *method;
  2733. const char *h = hostname;
  2734. if (explicit_ip) {
  2735. method = "CONFIGURED";
  2736. h = NULL;
  2737. } else if (explicit_hostname) {
  2738. method = "RESOLVED";
  2739. } else if (from_interface) {
  2740. method = "INTERFACE";
  2741. h = NULL;
  2742. } else {
  2743. method = "GETHOSTNAME";
  2744. }
  2745. control_event_server_status(LOG_NOTICE,
  2746. "EXTERNAL_ADDRESS ADDRESS=%s METHOD=%s %s%s",
  2747. addr_string, method, h?"HOSTNAME=":"", h);
  2748. }
  2749. last_resolved_addr = *addr_out;
  2750. if (hostname_out)
  2751. *hostname_out = tor_strdup(hostname);
  2752. tor_free(addr_string);
  2753. return 0;
  2754. }
  2755. /** Return true iff <b>addr</b> is judged to be on the same network as us, or
  2756. * on a private network.
  2757. */
  2758. int
  2759. is_local_addr(const tor_addr_t *addr)
  2760. {
  2761. if (tor_addr_is_internal(addr, 0))
  2762. return 1;
  2763. /* Check whether ip is on the same /24 as we are. */
  2764. if (get_options()->EnforceDistinctSubnets == 0)
  2765. return 0;
  2766. if (tor_addr_family(addr) == AF_INET) {
  2767. /*XXXX023 IP6 what corresponds to an /24? */
  2768. uint32_t ip = tor_addr_to_ipv4h(addr);
  2769. /* It's possible that this next check will hit before the first time
  2770. * resolve_my_address actually succeeds. (For clients, it is likely that
  2771. * resolve_my_address will never be called at all). In those cases,
  2772. * last_resolved_addr will be 0, and so checking to see whether ip is on
  2773. * the same /24 as last_resolved_addr will be the same as checking whether
  2774. * it was on net 0, which is already done by is_internal_IP.
  2775. */
  2776. if ((last_resolved_addr & (uint32_t)0xffffff00ul)
  2777. == (ip & (uint32_t)0xffffff00ul))
  2778. return 1;
  2779. }
  2780. return 0;
  2781. }
  2782. /** Release storage held by <b>options</b>. */
  2783. static void
  2784. config_free(const config_format_t *fmt, void *options)
  2785. {
  2786. int i;
  2787. if (!options)
  2788. return;
  2789. tor_assert(fmt);
  2790. for (i=0; fmt->vars[i].name; ++i)
  2791. option_clear(fmt, options, &(fmt->vars[i]));
  2792. if (fmt->extra) {
  2793. config_line_t **linep = STRUCT_VAR_P(options, fmt->extra->var_offset);
  2794. config_free_lines(*linep);
  2795. *linep = NULL;
  2796. }
  2797. tor_free(options);
  2798. }
  2799. /** Return true iff a and b contain identical keys and values in identical
  2800. * order. */
  2801. static int
  2802. config_lines_eq(config_line_t *a, config_line_t *b)
  2803. {
  2804. while (a && b) {
  2805. if (strcasecmp(a->key, b->key) || strcmp(a->value, b->value))
  2806. return 0;
  2807. a = a->next;
  2808. b = b->next;
  2809. }
  2810. if (a || b)
  2811. return 0;
  2812. return 1;
  2813. }
  2814. /** Return the number of lines in <b>a</b> whose key is <b>key</b>. */
  2815. static int
  2816. config_count_key(const config_line_t *a, const char *key)
  2817. {
  2818. int n = 0;
  2819. while (a) {
  2820. if (!strcasecmp(a->key, key)) {
  2821. ++n;
  2822. }
  2823. a = a->next;
  2824. }
  2825. return n;
  2826. }
  2827. /** Return true iff the option <b>name</b> has the same value in <b>o1</b>
  2828. * and <b>o2</b>. Must not be called for LINELIST_S or OBSOLETE options.
  2829. */
  2830. static int
  2831. option_is_same(const config_format_t *fmt,
  2832. const or_options_t *o1, const or_options_t *o2,
  2833. const char *name)
  2834. {
  2835. config_line_t *c1, *c2;
  2836. int r = 1;
  2837. CHECK(fmt, o1);
  2838. CHECK(fmt, o2);
  2839. c1 = get_assigned_option(fmt, o1, name, 0);
  2840. c2 = get_assigned_option(fmt, o2, name, 0);
  2841. r = config_lines_eq(c1, c2);
  2842. config_free_lines(c1);
  2843. config_free_lines(c2);
  2844. return r;
  2845. }
  2846. /** Copy storage held by <b>old</b> into a new or_options_t and return it. */
  2847. static or_options_t *
  2848. options_dup(const config_format_t *fmt, const or_options_t *old)
  2849. {
  2850. or_options_t *newopts;
  2851. int i;
  2852. config_line_t *line;
  2853. newopts = config_alloc(fmt);
  2854. for (i=0; fmt->vars[i].name; ++i) {
  2855. if (fmt->vars[i].type == CONFIG_TYPE_LINELIST_S)
  2856. continue;
  2857. if (fmt->vars[i].type == CONFIG_TYPE_OBSOLETE)
  2858. continue;
  2859. line = get_assigned_option(fmt, old, fmt->vars[i].name, 0);
  2860. if (line) {
  2861. char *msg = NULL;
  2862. if (config_assign(fmt, newopts, line, 0, 0, &msg) < 0) {
  2863. log_err(LD_BUG, "Config_get_assigned_option() generated "
  2864. "something we couldn't config_assign(): %s", msg);
  2865. tor_free(msg);
  2866. tor_assert(0);
  2867. }
  2868. }
  2869. config_free_lines(line);
  2870. }
  2871. return newopts;
  2872. }
  2873. /** Return a new empty or_options_t. Used for testing. */
  2874. or_options_t *
  2875. options_new(void)
  2876. {
  2877. return config_alloc(&options_format);
  2878. }
  2879. /** Set <b>options</b> to hold reasonable defaults for most options.
  2880. * Each option defaults to zero. */
  2881. void
  2882. options_init(or_options_t *options)
  2883. {
  2884. config_init(&options_format, options);
  2885. }
  2886. /** Set all vars in the configuration object <b>options</b> to their default
  2887. * values. */
  2888. static void
  2889. config_init(const config_format_t *fmt, void *options)
  2890. {
  2891. int i;
  2892. const config_var_t *var;
  2893. CHECK(fmt, options);
  2894. for (i=0; fmt->vars[i].name; ++i) {
  2895. var = &fmt->vars[i];
  2896. if (!var->initvalue)
  2897. continue; /* defaults to NULL or 0 */
  2898. option_reset(fmt, options, var, 1);
  2899. }
  2900. }
  2901. /** Allocate and return a new string holding the written-out values of the vars
  2902. * in 'options'. If 'minimal', do not write out any default-valued vars.
  2903. * Else, if comment_defaults, write default values as comments.
  2904. */
  2905. static char *
  2906. config_dump(const config_format_t *fmt, const void *default_options,
  2907. const void *options, int minimal,
  2908. int comment_defaults)
  2909. {
  2910. smartlist_t *elements;
  2911. const or_options_t *defaults = default_options;
  2912. void *defaults_tmp = NULL;
  2913. config_line_t *line, *assigned;
  2914. char *result;
  2915. int i;
  2916. char *msg = NULL;
  2917. if (defaults == NULL) {
  2918. defaults = defaults_tmp = config_alloc(fmt);
  2919. config_init(fmt, defaults_tmp);
  2920. }
  2921. /* XXX use a 1 here so we don't add a new log line while dumping */
  2922. if (default_options == NULL) {
  2923. if (fmt->validate_fn(NULL, defaults_tmp, 1, &msg) < 0) {
  2924. log_err(LD_BUG, "Failed to validate default config.");
  2925. tor_free(msg);
  2926. tor_assert(0);
  2927. }
  2928. }
  2929. elements = smartlist_new();
  2930. for (i=0; fmt->vars[i].name; ++i) {
  2931. int comment_option = 0;
  2932. if (fmt->vars[i].type == CONFIG_TYPE_OBSOLETE ||
  2933. fmt->vars[i].type == CONFIG_TYPE_LINELIST_S)
  2934. continue;
  2935. /* Don't save 'hidden' control variables. */
  2936. if (!strcmpstart(fmt->vars[i].name, "__"))
  2937. continue;
  2938. if (minimal && option_is_same(fmt, options, defaults, fmt->vars[i].name))
  2939. continue;
  2940. else if (comment_defaults &&
  2941. option_is_same(fmt, options, defaults, fmt->vars[i].name))
  2942. comment_option = 1;
  2943. line = assigned = get_assigned_option(fmt, options, fmt->vars[i].name, 1);
  2944. for (; line; line = line->next) {
  2945. smartlist_add_asprintf(elements, "%s%s %s\n",
  2946. comment_option ? "# " : "",
  2947. line->key, line->value);
  2948. }
  2949. config_free_lines(assigned);
  2950. }
  2951. if (fmt->extra) {
  2952. line = *(config_line_t**)STRUCT_VAR_P(options, fmt->extra->var_offset);
  2953. for (; line; line = line->next) {
  2954. smartlist_add_asprintf(elements, "%s %s\n", line->key, line->value);
  2955. }
  2956. }
  2957. result = smartlist_join_strings(elements, "", 0, NULL);
  2958. SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
  2959. smartlist_free(elements);
  2960. if (defaults_tmp)
  2961. config_free(fmt, defaults_tmp);
  2962. return result;
  2963. }
  2964. /** Return a string containing a possible configuration file that would give
  2965. * the configuration in <b>options</b>. If <b>minimal</b> is true, do not
  2966. * include options that are the same as Tor's defaults.
  2967. */
  2968. char *
  2969. options_dump(const or_options_t *options, int minimal)
  2970. {
  2971. return config_dump(&options_format, global_default_options,
  2972. options, minimal, 0);
  2973. }
  2974. /** Return 0 if every element of sl is a string holding a decimal
  2975. * representation of a port number, or if sl is NULL.
  2976. * Otherwise set *msg and return -1. */
  2977. static int
  2978. validate_ports_csv(smartlist_t *sl, const char *name, char **msg)
  2979. {
  2980. int i;
  2981. tor_assert(name);
  2982. if (!sl)
  2983. return 0;
  2984. SMARTLIST_FOREACH(sl, const char *, cp,
  2985. {
  2986. i = atoi(cp);
  2987. if (i < 1 || i > 65535) {
  2988. tor_asprintf(msg, "Port '%s' out of range in %s", cp, name);
  2989. return -1;
  2990. }
  2991. });
  2992. return 0;
  2993. }
  2994. /** If <b>value</b> exceeds ROUTER_MAX_DECLARED_BANDWIDTH, write
  2995. * a complaint into *<b>msg</b> using string <b>desc</b>, and return -1.
  2996. * Else return 0.
  2997. */
  2998. static int
  2999. ensure_bandwidth_cap(uint64_t *value, const char *desc, char **msg)
  3000. {
  3001. if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
  3002. /* This handles an understandable special case where somebody says "2gb"
  3003. * whereas our actual maximum is 2gb-1 (INT_MAX) */
  3004. --*value;
  3005. }
  3006. if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
  3007. tor_asprintf(msg, "%s ("U64_FORMAT") must be at most %d",
  3008. desc, U64_PRINTF_ARG(*value),
  3009. ROUTER_MAX_DECLARED_BANDWIDTH);
  3010. return -1;
  3011. }
  3012. return 0;
  3013. }
  3014. /** Parse an authority type from <b>options</b>-\>PublishServerDescriptor
  3015. * and write it to <b>options</b>-\>_PublishServerDescriptor. Treat "1"
  3016. * as "v2,v3" unless BridgeRelay is 1, in which case treat it as "bridge".
  3017. * Treat "0" as "".
  3018. * Return 0 on success or -1 if not a recognized authority type (in which
  3019. * case the value of _PublishServerDescriptor is undefined). */
  3020. static int
  3021. compute_publishserverdescriptor(or_options_t *options)
  3022. {
  3023. smartlist_t *list = options->PublishServerDescriptor;
  3024. dirinfo_type_t *auth = &options->_PublishServerDescriptor;
  3025. *auth = NO_DIRINFO;
  3026. if (!list) /* empty list, answer is none */
  3027. return 0;
  3028. SMARTLIST_FOREACH_BEGIN(list, const char *, string) {
  3029. if (!strcasecmp(string, "v1"))
  3030. *auth |= V1_DIRINFO;
  3031. else if (!strcmp(string, "1"))
  3032. if (options->BridgeRelay)
  3033. *auth |= BRIDGE_DIRINFO;
  3034. else
  3035. *auth |= V2_DIRINFO | V3_DIRINFO;
  3036. else if (!strcasecmp(string, "v2"))
  3037. *auth |= V2_DIRINFO;
  3038. else if (!strcasecmp(string, "v3"))
  3039. *auth |= V3_DIRINFO;
  3040. else if (!strcasecmp(string, "bridge"))
  3041. *auth |= BRIDGE_DIRINFO;
  3042. else if (!strcasecmp(string, "hidserv"))
  3043. log_warn(LD_CONFIG,
  3044. "PublishServerDescriptor hidserv is invalid. See "
  3045. "PublishHidServDescriptors.");
  3046. else if (!strcasecmp(string, "") || !strcmp(string, "0"))
  3047. /* no authority */;
  3048. else
  3049. return -1;
  3050. } SMARTLIST_FOREACH_END(string);
  3051. return 0;
  3052. }
  3053. /** Lowest allowable value for RendPostPeriod; if this is too low, hidden
  3054. * services can overload the directory system. */
  3055. #define MIN_REND_POST_PERIOD (10*60)
  3056. /** Highest allowable value for RendPostPeriod. */
  3057. #define MAX_DIR_PERIOD (MIN_ONION_KEY_LIFETIME/2)
  3058. /** Lowest allowable value for MaxCircuitDirtiness; if this is too low, Tor
  3059. * will generate too many circuits and potentially overload the network. */
  3060. #define MIN_MAX_CIRCUIT_DIRTINESS 10
  3061. /** Lowest allowable value for CircuitStreamTimeout; if this is too low, Tor
  3062. * will generate too many circuits and potentially overload the network. */
  3063. #define MIN_CIRCUIT_STREAM_TIMEOUT 10
  3064. /** Lowest allowable value for HeartbeatPeriod; if this is too low, we might
  3065. * expose more information than we're comfortable with. */
  3066. #define MIN_HEARTBEAT_PERIOD (30*60)
  3067. /** Lowest recommended value for CircuitBuildTimeout; if it is set too low
  3068. * and LearnCircuitBuildTimeout is off, the failure rate for circuit
  3069. * construction may be very high. In that case, if it is set below this
  3070. * threshold emit a warning.
  3071. * */
  3072. #define RECOMMENDED_MIN_CIRCUIT_BUILD_TIMEOUT (10)
  3073. /** Return 0 if every setting in <b>options</b> is reasonable, and a
  3074. * permissible transition from <b>old_options</b>. Else return -1.
  3075. * Should have no side effects, except for normalizing the contents of
  3076. * <b>options</b>.
  3077. *
  3078. * On error, tor_strdup an error explanation into *<b>msg</b>.
  3079. *
  3080. * XXX
  3081. * If <b>from_setconf</b>, we were called by the controller, and our
  3082. * Log line should stay empty. If it's 0, then give us a default log
  3083. * if there are no logs defined.
  3084. */
  3085. static int
  3086. options_validate(or_options_t *old_options, or_options_t *options,
  3087. int from_setconf, char **msg)
  3088. {
  3089. int i;
  3090. config_line_t *cl;
  3091. const char *uname = get_uname();
  3092. int n_ports=0;
  3093. #define REJECT(arg) \
  3094. STMT_BEGIN *msg = tor_strdup(arg); return -1; STMT_END
  3095. #define COMPLAIN(arg) STMT_BEGIN log(LOG_WARN, LD_CONFIG, arg); STMT_END
  3096. tor_assert(msg);
  3097. *msg = NULL;
  3098. if (server_mode(options) &&
  3099. (!strcmpstart(uname, "Windows 95") ||
  3100. !strcmpstart(uname, "Windows 98") ||
  3101. !strcmpstart(uname, "Windows Me"))) {
  3102. log(LOG_WARN, LD_CONFIG, "Tor is running as a server, but you are "
  3103. "running %s; this probably won't work. See "
  3104. "https://wiki.torproject.org/TheOnionRouter/TorFAQ#ServerOS "
  3105. "for details.", uname);
  3106. }
  3107. if (parse_ports(options, 1, msg, &n_ports) < 0)
  3108. return -1;
  3109. if (validate_data_directory(options)<0)
  3110. REJECT("Invalid DataDirectory");
  3111. if (options->Nickname == NULL) {
  3112. if (server_mode(options)) {
  3113. options->Nickname = tor_strdup(UNNAMED_ROUTER_NICKNAME);
  3114. }
  3115. } else {
  3116. if (!is_legal_nickname(options->Nickname)) {
  3117. tor_asprintf(msg,
  3118. "Nickname '%s' is wrong length or contains illegal characters.",
  3119. options->Nickname);
  3120. return -1;
  3121. }
  3122. }
  3123. if (server_mode(options) && !options->ContactInfo)
  3124. log(LOG_NOTICE, LD_CONFIG, "Your ContactInfo config option is not set. "
  3125. "Please consider setting it, so we can contact you if your server is "
  3126. "misconfigured or something else goes wrong.");
  3127. /* Special case on first boot if no Log options are given. */
  3128. if (!options->Logs && !options->RunAsDaemon && !from_setconf) {
  3129. if (quiet_level == 0)
  3130. config_line_append(&options->Logs, "Log", "notice stdout");
  3131. else if (quiet_level == 1)
  3132. config_line_append(&options->Logs, "Log", "warn stdout");
  3133. }
  3134. if (options_init_logs(options, 1)<0) /* Validate the log(s) */
  3135. REJECT("Failed to validate Log options. See logs for details.");
  3136. if (authdir_mode(options)) {
  3137. /* confirm that our address isn't broken, so we can complain now */
  3138. uint32_t tmp;
  3139. if (resolve_my_address(LOG_WARN, options, &tmp, NULL) < 0)
  3140. REJECT("Failed to resolve/guess local address. See logs for details.");
  3141. }
  3142. #ifndef _WIN32
  3143. if (options->RunAsDaemon && torrc_fname && path_is_relative(torrc_fname))
  3144. REJECT("Can't use a relative path to torrc when RunAsDaemon is set.");
  3145. #endif
  3146. /* XXXX require that the only port not be DirPort? */
  3147. /* XXXX require that at least one port be listened-upon. */
  3148. if (n_ports == 0 && !options->RendConfigLines)
  3149. log(LOG_WARN, LD_CONFIG,
  3150. "SocksPort, TransPort, NATDPort, DNSPort, and ORPort are all "
  3151. "undefined, and there aren't any hidden services configured. "
  3152. "Tor will still run, but probably won't do anything.");
  3153. #ifndef USE_TRANSPARENT
  3154. /* XXXX024 I think we can remove this TransListenAddress */
  3155. if (options->TransPort_set || options->TransListenAddress)
  3156. REJECT("TransPort and TransListenAddress are disabled in this build.");
  3157. #endif
  3158. if (options->TokenBucketRefillInterval <= 0
  3159. || options->TokenBucketRefillInterval > 1000) {
  3160. REJECT("TokenBucketRefillInterval must be between 1 and 1000 inclusive.");
  3161. }
  3162. if (options->ExcludeExitNodes || options->ExcludeNodes) {
  3163. options->_ExcludeExitNodesUnion = routerset_new();
  3164. routerset_union(options->_ExcludeExitNodesUnion,options->ExcludeExitNodes);
  3165. routerset_union(options->_ExcludeExitNodesUnion,options->ExcludeNodes);
  3166. }
  3167. if (options->NodeFamilies) {
  3168. options->NodeFamilySets = smartlist_new();
  3169. for (cl = options->NodeFamilies; cl; cl = cl->next) {
  3170. routerset_t *rs = routerset_new();
  3171. if (routerset_parse(rs, cl->value, cl->key) == 0) {
  3172. smartlist_add(options->NodeFamilySets, rs);
  3173. } else {
  3174. routerset_free(rs);
  3175. }
  3176. }
  3177. }
  3178. if (options->ExcludeNodes && options->StrictNodes) {
  3179. COMPLAIN("You have asked to exclude certain relays from all positions "
  3180. "in your circuits. Expect hidden services and other Tor "
  3181. "features to be broken in unpredictable ways.");
  3182. }
  3183. if (options->AuthoritativeDir) {
  3184. if (!options->ContactInfo && !options->TestingTorNetwork)
  3185. REJECT("Authoritative directory servers must set ContactInfo");
  3186. if (options->V1AuthoritativeDir && !options->RecommendedVersions)
  3187. REJECT("V1 authoritative dir servers must set RecommendedVersions.");
  3188. if (!options->RecommendedClientVersions)
  3189. options->RecommendedClientVersions =
  3190. config_lines_dup(options->RecommendedVersions);
  3191. if (!options->RecommendedServerVersions)
  3192. options->RecommendedServerVersions =
  3193. config_lines_dup(options->RecommendedVersions);
  3194. if (options->VersioningAuthoritativeDir &&
  3195. (!options->RecommendedClientVersions ||
  3196. !options->RecommendedServerVersions))
  3197. REJECT("Versioning authoritative dir servers must set "
  3198. "Recommended*Versions.");
  3199. if (options->UseEntryGuards) {
  3200. log_info(LD_CONFIG, "Authoritative directory servers can't set "
  3201. "UseEntryGuards. Disabling.");
  3202. options->UseEntryGuards = 0;
  3203. }
  3204. if (!options->DownloadExtraInfo && authdir_mode_any_main(options)) {
  3205. log_info(LD_CONFIG, "Authoritative directories always try to download "
  3206. "extra-info documents. Setting DownloadExtraInfo.");
  3207. options->DownloadExtraInfo = 1;
  3208. }
  3209. if (!(options->BridgeAuthoritativeDir || options->HSAuthoritativeDir ||
  3210. options->V1AuthoritativeDir || options->V2AuthoritativeDir ||
  3211. options->V3AuthoritativeDir))
  3212. REJECT("AuthoritativeDir is set, but none of "
  3213. "(Bridge/HS/V1/V2/V3)AuthoritativeDir is set.");
  3214. /* If we have a v3bandwidthsfile and it's broken, complain on startup */
  3215. if (options->V3BandwidthsFile && !old_options) {
  3216. dirserv_read_measured_bandwidths(options->V3BandwidthsFile, NULL);
  3217. }
  3218. }
  3219. if (options->AuthoritativeDir && !options->DirPort_set)
  3220. REJECT("Running as authoritative directory, but no DirPort set.");
  3221. if (options->AuthoritativeDir && !options->ORPort_set)
  3222. REJECT("Running as authoritative directory, but no ORPort set.");
  3223. if (options->AuthoritativeDir && options->ClientOnly)
  3224. REJECT("Running as authoritative directory, but ClientOnly also set.");
  3225. if (options->FetchDirInfoExtraEarly && !options->FetchDirInfoEarly)
  3226. REJECT("FetchDirInfoExtraEarly requires that you also set "
  3227. "FetchDirInfoEarly");
  3228. if (options->HSAuthoritativeDir && proxy_mode(options))
  3229. REJECT("Running as authoritative v0 HS directory, but also configured "
  3230. "as a client.");
  3231. if (options->ConnLimit <= 0) {
  3232. tor_asprintf(msg,
  3233. "ConnLimit must be greater than 0, but was set to %d",
  3234. options->ConnLimit);
  3235. return -1;
  3236. }
  3237. if (options->MaxClientCircuitsPending <= 0 ||
  3238. options->MaxClientCircuitsPending > MAX_MAX_CLIENT_CIRCUITS_PENDING) {
  3239. tor_asprintf(msg,
  3240. "MaxClientCircuitsPending must be between 1 and %d, but "
  3241. "was set to %d", MAX_MAX_CLIENT_CIRCUITS_PENDING,
  3242. options->MaxClientCircuitsPending);
  3243. return -1;
  3244. }
  3245. if (validate_ports_csv(options->FirewallPorts, "FirewallPorts", msg) < 0)
  3246. return -1;
  3247. if (validate_ports_csv(options->LongLivedPorts, "LongLivedPorts", msg) < 0)
  3248. return -1;
  3249. if (validate_ports_csv(options->RejectPlaintextPorts,
  3250. "RejectPlaintextPorts", msg) < 0)
  3251. return -1;
  3252. if (validate_ports_csv(options->WarnPlaintextPorts,
  3253. "WarnPlaintextPorts", msg) < 0)
  3254. return -1;
  3255. if (options->FascistFirewall && !options->ReachableAddresses) {
  3256. if (options->FirewallPorts && smartlist_len(options->FirewallPorts)) {
  3257. /* We already have firewall ports set, so migrate them to
  3258. * ReachableAddresses, which will set ReachableORAddresses and
  3259. * ReachableDirAddresses if they aren't set explicitly. */
  3260. smartlist_t *instead = smartlist_new();
  3261. config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
  3262. new_line->key = tor_strdup("ReachableAddresses");
  3263. /* If we're configured with the old format, we need to prepend some
  3264. * open ports. */
  3265. SMARTLIST_FOREACH(options->FirewallPorts, const char *, portno,
  3266. {
  3267. int p = atoi(portno);
  3268. if (p<0) continue;
  3269. smartlist_add_asprintf(instead, "*:%d", p);
  3270. });
  3271. new_line->value = smartlist_join_strings(instead,",",0,NULL);
  3272. /* These have been deprecated since 0.1.1.5-alpha-cvs */
  3273. log(LOG_NOTICE, LD_CONFIG,
  3274. "Converting FascistFirewall and FirewallPorts "
  3275. "config options to new format: \"ReachableAddresses %s\"",
  3276. new_line->value);
  3277. options->ReachableAddresses = new_line;
  3278. SMARTLIST_FOREACH(instead, char *, cp, tor_free(cp));
  3279. smartlist_free(instead);
  3280. } else {
  3281. /* We do not have FirewallPorts set, so add 80 to
  3282. * ReachableDirAddresses, and 443 to ReachableORAddresses. */
  3283. if (!options->ReachableDirAddresses) {
  3284. config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
  3285. new_line->key = tor_strdup("ReachableDirAddresses");
  3286. new_line->value = tor_strdup("*:80");
  3287. options->ReachableDirAddresses = new_line;
  3288. log(LOG_NOTICE, LD_CONFIG, "Converting FascistFirewall config option "
  3289. "to new format: \"ReachableDirAddresses *:80\"");
  3290. }
  3291. if (!options->ReachableORAddresses) {
  3292. config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
  3293. new_line->key = tor_strdup("ReachableORAddresses");
  3294. new_line->value = tor_strdup("*:443");
  3295. options->ReachableORAddresses = new_line;
  3296. log(LOG_NOTICE, LD_CONFIG, "Converting FascistFirewall config option "
  3297. "to new format: \"ReachableORAddresses *:443\"");
  3298. }
  3299. }
  3300. }
  3301. for (i=0; i<3; i++) {
  3302. config_line_t **linep =
  3303. (i==0) ? &options->ReachableAddresses :
  3304. (i==1) ? &options->ReachableORAddresses :
  3305. &options->ReachableDirAddresses;
  3306. if (!*linep)
  3307. continue;
  3308. /* We need to end with a reject *:*, not an implicit accept *:* */
  3309. for (;;) {
  3310. if (!strcmp((*linep)->value, "reject *:*")) /* already there */
  3311. break;
  3312. linep = &((*linep)->next);
  3313. if (!*linep) {
  3314. *linep = tor_malloc_zero(sizeof(config_line_t));
  3315. (*linep)->key = tor_strdup(
  3316. (i==0) ? "ReachableAddresses" :
  3317. (i==1) ? "ReachableORAddresses" :
  3318. "ReachableDirAddresses");
  3319. (*linep)->value = tor_strdup("reject *:*");
  3320. break;
  3321. }
  3322. }
  3323. }
  3324. if ((options->ReachableAddresses ||
  3325. options->ReachableORAddresses ||
  3326. options->ReachableDirAddresses) &&
  3327. server_mode(options))
  3328. REJECT("Servers must be able to freely connect to the rest "
  3329. "of the Internet, so they must not set Reachable*Addresses "
  3330. "or FascistFirewall.");
  3331. if (options->UseBridges &&
  3332. server_mode(options))
  3333. REJECT("Servers must be able to freely connect to the rest "
  3334. "of the Internet, so they must not set UseBridges.");
  3335. /* If both of these are set, we'll end up with funny behavior where we
  3336. * demand enough entrynodes be up and running else we won't build
  3337. * circuits, yet we never actually use them. */
  3338. if (options->UseBridges && options->EntryNodes)
  3339. REJECT("You cannot set both UseBridges and EntryNodes.");
  3340. if (options->EntryNodes && !options->UseEntryGuards)
  3341. log_warn(LD_CONFIG, "EntryNodes is set, but UseEntryGuards is disabled. "
  3342. "EntryNodes will be ignored.");
  3343. options->_AllowInvalid = 0;
  3344. if (options->AllowInvalidNodes) {
  3345. SMARTLIST_FOREACH_BEGIN(options->AllowInvalidNodes, const char *, cp) {
  3346. if (!strcasecmp(cp, "entry"))
  3347. options->_AllowInvalid |= ALLOW_INVALID_ENTRY;
  3348. else if (!strcasecmp(cp, "exit"))
  3349. options->_AllowInvalid |= ALLOW_INVALID_EXIT;
  3350. else if (!strcasecmp(cp, "middle"))
  3351. options->_AllowInvalid |= ALLOW_INVALID_MIDDLE;
  3352. else if (!strcasecmp(cp, "introduction"))
  3353. options->_AllowInvalid |= ALLOW_INVALID_INTRODUCTION;
  3354. else if (!strcasecmp(cp, "rendezvous"))
  3355. options->_AllowInvalid |= ALLOW_INVALID_RENDEZVOUS;
  3356. else {
  3357. tor_asprintf(msg,
  3358. "Unrecognized value '%s' in AllowInvalidNodes", cp);
  3359. return -1;
  3360. }
  3361. } SMARTLIST_FOREACH_END(cp);
  3362. }
  3363. if (!options->SafeLogging ||
  3364. !strcasecmp(options->SafeLogging, "0")) {
  3365. options->_SafeLogging = SAFELOG_SCRUB_NONE;
  3366. } else if (!strcasecmp(options->SafeLogging, "relay")) {
  3367. options->_SafeLogging = SAFELOG_SCRUB_RELAY;
  3368. } else if (!strcasecmp(options->SafeLogging, "1")) {
  3369. options->_SafeLogging = SAFELOG_SCRUB_ALL;
  3370. } else {
  3371. tor_asprintf(msg,
  3372. "Unrecognized value '%s' in SafeLogging",
  3373. escaped(options->SafeLogging));
  3374. return -1;
  3375. }
  3376. if (compute_publishserverdescriptor(options) < 0) {
  3377. tor_asprintf(msg, "Unrecognized value in PublishServerDescriptor");
  3378. return -1;
  3379. }
  3380. if ((options->BridgeRelay
  3381. || options->_PublishServerDescriptor & BRIDGE_DIRINFO)
  3382. && (options->_PublishServerDescriptor
  3383. & (V1_DIRINFO|V2_DIRINFO|V3_DIRINFO))) {
  3384. REJECT("Bridges are not supposed to publish router descriptors to the "
  3385. "directory authorities. Please correct your "
  3386. "PublishServerDescriptor line.");
  3387. }
  3388. if (options->BridgeRelay && options->DirPort_set) {
  3389. log_warn(LD_CONFIG, "Can't set a DirPort on a bridge relay; disabling "
  3390. "DirPort");
  3391. config_free_lines(options->DirPort_lines);
  3392. options->DirPort_lines = NULL;
  3393. options->DirPort_set = 0;
  3394. }
  3395. if (options->MinUptimeHidServDirectoryV2 < 0) {
  3396. log_warn(LD_CONFIG, "MinUptimeHidServDirectoryV2 option must be at "
  3397. "least 0 seconds. Changing to 0.");
  3398. options->MinUptimeHidServDirectoryV2 = 0;
  3399. }
  3400. if (options->RendPostPeriod < MIN_REND_POST_PERIOD) {
  3401. log_warn(LD_CONFIG, "RendPostPeriod option is too short; "
  3402. "raising to %d seconds.", MIN_REND_POST_PERIOD);
  3403. options->RendPostPeriod = MIN_REND_POST_PERIOD;
  3404. }
  3405. if (options->RendPostPeriod > MAX_DIR_PERIOD) {
  3406. log_warn(LD_CONFIG, "RendPostPeriod is too large; clipping to %ds.",
  3407. MAX_DIR_PERIOD);
  3408. options->RendPostPeriod = MAX_DIR_PERIOD;
  3409. }
  3410. if (options->Tor2webMode && options->LearnCircuitBuildTimeout) {
  3411. /* LearnCircuitBuildTimeout and Tor2webMode are incompatible in
  3412. * two ways:
  3413. *
  3414. * - LearnCircuitBuildTimeout results in a low CBT, which
  3415. * Tor2webMode's use of one-hop rendezvous circuits lowers
  3416. * much further, producing *far* too many timeouts.
  3417. *
  3418. * - The adaptive CBT code does not update its timeout estimate
  3419. * using build times for single-hop circuits.
  3420. *
  3421. * If we fix both of these issues someday, we should test
  3422. * Tor2webMode with LearnCircuitBuildTimeout on again. */
  3423. log_notice(LD_CONFIG,"Tor2webMode is enabled; turning "
  3424. "LearnCircuitBuildTimeout off.");
  3425. options->LearnCircuitBuildTimeout = 0;
  3426. }
  3427. if (!(options->LearnCircuitBuildTimeout) &&
  3428. options->CircuitBuildTimeout < RECOMMENDED_MIN_CIRCUIT_BUILD_TIMEOUT) {
  3429. log_warn(LD_CONFIG,
  3430. "CircuitBuildTimeout is shorter (%d seconds) than recommended "
  3431. "(%d seconds), and LearnCircuitBuildTimeout is disabled. "
  3432. "If tor isn't working, raise this value or enable "
  3433. "LearnCircuitBuildTimeout.",
  3434. options->CircuitBuildTimeout,
  3435. RECOMMENDED_MIN_CIRCUIT_BUILD_TIMEOUT );
  3436. }
  3437. if (options->MaxCircuitDirtiness < MIN_MAX_CIRCUIT_DIRTINESS) {
  3438. log_warn(LD_CONFIG, "MaxCircuitDirtiness option is too short; "
  3439. "raising to %d seconds.", MIN_MAX_CIRCUIT_DIRTINESS);
  3440. options->MaxCircuitDirtiness = MIN_MAX_CIRCUIT_DIRTINESS;
  3441. }
  3442. if (options->CircuitStreamTimeout &&
  3443. options->CircuitStreamTimeout < MIN_CIRCUIT_STREAM_TIMEOUT) {
  3444. log_warn(LD_CONFIG, "CircuitStreamTimeout option is too short; "
  3445. "raising to %d seconds.", MIN_CIRCUIT_STREAM_TIMEOUT);
  3446. options->CircuitStreamTimeout = MIN_CIRCUIT_STREAM_TIMEOUT;
  3447. }
  3448. if (options->HeartbeatPeriod &&
  3449. options->HeartbeatPeriod < MIN_HEARTBEAT_PERIOD) {
  3450. log_warn(LD_CONFIG, "HeartbeatPeriod option is too short; "
  3451. "raising to %d seconds.", MIN_HEARTBEAT_PERIOD);
  3452. options->HeartbeatPeriod = MIN_HEARTBEAT_PERIOD;
  3453. }
  3454. if (options->KeepalivePeriod < 1)
  3455. REJECT("KeepalivePeriod option must be positive.");
  3456. if (ensure_bandwidth_cap(&options->BandwidthRate,
  3457. "BandwidthRate", msg) < 0)
  3458. return -1;
  3459. if (ensure_bandwidth_cap(&options->BandwidthBurst,
  3460. "BandwidthBurst", msg) < 0)
  3461. return -1;
  3462. if (ensure_bandwidth_cap(&options->MaxAdvertisedBandwidth,
  3463. "MaxAdvertisedBandwidth", msg) < 0)
  3464. return -1;
  3465. if (ensure_bandwidth_cap(&options->RelayBandwidthRate,
  3466. "RelayBandwidthRate", msg) < 0)
  3467. return -1;
  3468. if (ensure_bandwidth_cap(&options->RelayBandwidthBurst,
  3469. "RelayBandwidthBurst", msg) < 0)
  3470. return -1;
  3471. if (ensure_bandwidth_cap(&options->PerConnBWRate,
  3472. "PerConnBWRate", msg) < 0)
  3473. return -1;
  3474. if (ensure_bandwidth_cap(&options->PerConnBWBurst,
  3475. "PerConnBWBurst", msg) < 0)
  3476. return -1;
  3477. if (ensure_bandwidth_cap(&options->AuthDirFastGuarantee,
  3478. "AuthDirFastGuarantee", msg) < 0)
  3479. return -1;
  3480. if (ensure_bandwidth_cap(&options->AuthDirGuardBWGuarantee,
  3481. "AuthDirGuardBWGuarantee", msg) < 0)
  3482. return -1;
  3483. if (options->RelayBandwidthRate && !options->RelayBandwidthBurst)
  3484. options->RelayBandwidthBurst = options->RelayBandwidthRate;
  3485. if (options->RelayBandwidthBurst && !options->RelayBandwidthRate)
  3486. options->RelayBandwidthRate = options->RelayBandwidthBurst;
  3487. if (server_mode(options)) {
  3488. if (options->BandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH) {
  3489. tor_asprintf(msg,
  3490. "BandwidthRate is set to %d bytes/second. "
  3491. "For servers, it must be at least %d.",
  3492. (int)options->BandwidthRate,
  3493. ROUTER_REQUIRED_MIN_BANDWIDTH);
  3494. return -1;
  3495. } else if (options->MaxAdvertisedBandwidth <
  3496. ROUTER_REQUIRED_MIN_BANDWIDTH/2) {
  3497. tor_asprintf(msg,
  3498. "MaxAdvertisedBandwidth is set to %d bytes/second. "
  3499. "For servers, it must be at least %d.",
  3500. (int)options->MaxAdvertisedBandwidth,
  3501. ROUTER_REQUIRED_MIN_BANDWIDTH/2);
  3502. return -1;
  3503. }
  3504. if (options->RelayBandwidthRate &&
  3505. options->RelayBandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH) {
  3506. tor_asprintf(msg,
  3507. "RelayBandwidthRate is set to %d bytes/second. "
  3508. "For servers, it must be at least %d.",
  3509. (int)options->RelayBandwidthRate,
  3510. ROUTER_REQUIRED_MIN_BANDWIDTH);
  3511. return -1;
  3512. }
  3513. }
  3514. if (options->RelayBandwidthRate > options->RelayBandwidthBurst)
  3515. REJECT("RelayBandwidthBurst must be at least equal "
  3516. "to RelayBandwidthRate.");
  3517. if (options->BandwidthRate > options->BandwidthBurst)
  3518. REJECT("BandwidthBurst must be at least equal to BandwidthRate.");
  3519. /* if they set relaybandwidth* really high but left bandwidth*
  3520. * at the default, raise the defaults. */
  3521. if (options->RelayBandwidthRate > options->BandwidthRate)
  3522. options->BandwidthRate = options->RelayBandwidthRate;
  3523. if (options->RelayBandwidthBurst > options->BandwidthBurst)
  3524. options->BandwidthBurst = options->RelayBandwidthBurst;
  3525. if (accounting_parse_options(options, 1)<0)
  3526. REJECT("Failed to parse accounting options. See logs for details.");
  3527. if (options->AccountingMax) {
  3528. if (options->RendConfigLines && server_mode(options)) {
  3529. log_warn(LD_CONFIG, "Using accounting with a hidden service and an "
  3530. "ORPort is risky: your hidden service(s) and your public "
  3531. "address will all turn off at the same time, which may alert "
  3532. "observers that they are being run by the same party.");
  3533. } else if (config_count_key(options->RendConfigLines,
  3534. "HiddenServiceDir") > 1) {
  3535. log_warn(LD_CONFIG, "Using accounting with multiple hidden services is "
  3536. "risky: they will all turn off at the same time, which may "
  3537. "alert observers that they are being run by the same party.");
  3538. }
  3539. }
  3540. if (options->HTTPProxy) { /* parse it now */
  3541. if (tor_addr_port_lookup(options->HTTPProxy,
  3542. &options->HTTPProxyAddr, &options->HTTPProxyPort) < 0)
  3543. REJECT("HTTPProxy failed to parse or resolve. Please fix.");
  3544. if (options->HTTPProxyPort == 0) { /* give it a default */
  3545. options->HTTPProxyPort = 80;
  3546. }
  3547. }
  3548. if (options->HTTPProxyAuthenticator) {
  3549. if (strlen(options->HTTPProxyAuthenticator) >= 512)
  3550. REJECT("HTTPProxyAuthenticator is too long (>= 512 chars).");
  3551. }
  3552. if (options->HTTPSProxy) { /* parse it now */
  3553. if (tor_addr_port_lookup(options->HTTPSProxy,
  3554. &options->HTTPSProxyAddr, &options->HTTPSProxyPort) <0)
  3555. REJECT("HTTPSProxy failed to parse or resolve. Please fix.");
  3556. if (options->HTTPSProxyPort == 0) { /* give it a default */
  3557. options->HTTPSProxyPort = 443;
  3558. }
  3559. }
  3560. if (options->HTTPSProxyAuthenticator) {
  3561. if (strlen(options->HTTPSProxyAuthenticator) >= 512)
  3562. REJECT("HTTPSProxyAuthenticator is too long (>= 512 chars).");
  3563. }
  3564. if (options->Socks4Proxy) { /* parse it now */
  3565. if (tor_addr_port_lookup(options->Socks4Proxy,
  3566. &options->Socks4ProxyAddr,
  3567. &options->Socks4ProxyPort) <0)
  3568. REJECT("Socks4Proxy failed to parse or resolve. Please fix.");
  3569. if (options->Socks4ProxyPort == 0) { /* give it a default */
  3570. options->Socks4ProxyPort = 1080;
  3571. }
  3572. }
  3573. if (options->Socks5Proxy) { /* parse it now */
  3574. if (tor_addr_port_lookup(options->Socks5Proxy,
  3575. &options->Socks5ProxyAddr,
  3576. &options->Socks5ProxyPort) <0)
  3577. REJECT("Socks5Proxy failed to parse or resolve. Please fix.");
  3578. if (options->Socks5ProxyPort == 0) { /* give it a default */
  3579. options->Socks5ProxyPort = 1080;
  3580. }
  3581. }
  3582. /* Check if more than one proxy type has been enabled. */
  3583. if (!!options->Socks4Proxy + !!options->Socks5Proxy +
  3584. !!options->HTTPSProxy + !!options->ClientTransportPlugin > 1)
  3585. REJECT("You have configured more than one proxy type. "
  3586. "(Socks4Proxy|Socks5Proxy|HTTPSProxy|ClientTransportPlugin)");
  3587. /* Check if the proxies will give surprising behavior. */
  3588. if (options->HTTPProxy && !(options->Socks4Proxy ||
  3589. options->Socks5Proxy ||
  3590. options->HTTPSProxy)) {
  3591. log_warn(LD_CONFIG, "HTTPProxy configured, but no SOCKS proxy or "
  3592. "HTTPS proxy configured. Watch out: this configuration will "
  3593. "proxy unencrypted directory connections only.");
  3594. }
  3595. if (options->Socks5ProxyUsername) {
  3596. size_t len;
  3597. len = strlen(options->Socks5ProxyUsername);
  3598. if (len < 1 || len > 255)
  3599. REJECT("Socks5ProxyUsername must be between 1 and 255 characters.");
  3600. if (!options->Socks5ProxyPassword)
  3601. REJECT("Socks5ProxyPassword must be included with Socks5ProxyUsername.");
  3602. len = strlen(options->Socks5ProxyPassword);
  3603. if (len < 1 || len > 255)
  3604. REJECT("Socks5ProxyPassword must be between 1 and 255 characters.");
  3605. } else if (options->Socks5ProxyPassword)
  3606. REJECT("Socks5ProxyPassword must be included with Socks5ProxyUsername.");
  3607. if (options->HashedControlPassword) {
  3608. smartlist_t *sl = decode_hashed_passwords(options->HashedControlPassword);
  3609. if (!sl) {
  3610. REJECT("Bad HashedControlPassword: wrong length or bad encoding");
  3611. } else {
  3612. SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
  3613. smartlist_free(sl);
  3614. }
  3615. }
  3616. if (options->HashedControlSessionPassword) {
  3617. smartlist_t *sl = decode_hashed_passwords(
  3618. options->HashedControlSessionPassword);
  3619. if (!sl) {
  3620. REJECT("Bad HashedControlSessionPassword: wrong length or bad encoding");
  3621. } else {
  3622. SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
  3623. smartlist_free(sl);
  3624. }
  3625. }
  3626. if (options->OwningControllerProcess) {
  3627. const char *validate_pspec_msg = NULL;
  3628. if (tor_validate_process_specifier(options->OwningControllerProcess,
  3629. &validate_pspec_msg)) {
  3630. tor_asprintf(msg, "Bad OwningControllerProcess: %s",
  3631. validate_pspec_msg);
  3632. return -1;
  3633. }
  3634. }
  3635. if (options->ControlPort_set && !options->HashedControlPassword &&
  3636. !options->HashedControlSessionPassword &&
  3637. !options->CookieAuthentication) {
  3638. log_warn(LD_CONFIG, "ControlPort is open, but no authentication method "
  3639. "has been configured. This means that any program on your "
  3640. "computer can reconfigure your Tor. That's bad! You should "
  3641. "upgrade your Tor controller as soon as possible.");
  3642. }
  3643. if (options->CookieAuthFileGroupReadable && !options->CookieAuthFile) {
  3644. log_warn(LD_CONFIG, "CookieAuthFileGroupReadable is set, but will have "
  3645. "no effect: you must specify an explicit CookieAuthFile to "
  3646. "have it group-readable.");
  3647. }
  3648. if (options->UseEntryGuards && ! options->NumEntryGuards)
  3649. REJECT("Cannot enable UseEntryGuards with NumEntryGuards set to 0");
  3650. if (options->MyFamily && options->BridgeRelay) {
  3651. log_warn(LD_CONFIG, "Listing a family for a bridge relay is not "
  3652. "supported: it can reveal bridge fingerprints to censors. "
  3653. "You should also make sure you aren't listing this bridge's "
  3654. "fingerprint in any other MyFamily.");
  3655. }
  3656. if (check_nickname_list(options->MyFamily, "MyFamily", msg))
  3657. return -1;
  3658. for (cl = options->NodeFamilies; cl; cl = cl->next) {
  3659. routerset_t *rs = routerset_new();
  3660. if (routerset_parse(rs, cl->value, cl->key)) {
  3661. routerset_free(rs);
  3662. return -1;
  3663. }
  3664. routerset_free(rs);
  3665. }
  3666. if (validate_addr_policies(options, msg) < 0)
  3667. return -1;
  3668. if (validate_dir_authorities(options, old_options) < 0)
  3669. REJECT("Directory authority line did not parse. See logs for details.");
  3670. if (options->UseBridges && !options->Bridges)
  3671. REJECT("If you set UseBridges, you must specify at least one bridge.");
  3672. if (options->UseBridges && !options->TunnelDirConns)
  3673. REJECT("If you set UseBridges, you must set TunnelDirConns.");
  3674. for (cl = options->Bridges; cl; cl = cl->next) {
  3675. if (parse_bridge_line(cl->value, 1)<0)
  3676. REJECT("Bridge line did not parse. See logs for details.");
  3677. }
  3678. for (cl = options->ClientTransportPlugin; cl; cl = cl->next) {
  3679. if (parse_client_transport_line(cl->value, 1)<0)
  3680. REJECT("Transport line did not parse. See logs for details.");
  3681. }
  3682. for (cl = options->ServerTransportPlugin; cl; cl = cl->next) {
  3683. if (parse_server_transport_line(cl->value, 1)<0)
  3684. REJECT("Server transport line did not parse. See logs for details.");
  3685. }
  3686. if (options->ServerTransportPlugin && !server_mode(options)) {
  3687. log_notice(LD_GENERAL, "Tor is not configured as a relay but you specified"
  3688. " a ServerTransportPlugin line (%s). The ServerTransportPlugin "
  3689. "line will be ignored.",
  3690. escaped(options->ServerTransportPlugin->value));
  3691. }
  3692. if (options->ConstrainedSockets) {
  3693. /* If the user wants to constrain socket buffer use, make sure the desired
  3694. * limit is between MIN|MAX_TCPSOCK_BUFFER in k increments. */
  3695. if (options->ConstrainedSockSize < MIN_CONSTRAINED_TCP_BUFFER ||
  3696. options->ConstrainedSockSize > MAX_CONSTRAINED_TCP_BUFFER ||
  3697. options->ConstrainedSockSize % 1024) {
  3698. tor_asprintf(msg,
  3699. "ConstrainedSockSize is invalid. Must be a value between %d and %d "
  3700. "in 1024 byte increments.",
  3701. MIN_CONSTRAINED_TCP_BUFFER, MAX_CONSTRAINED_TCP_BUFFER);
  3702. return -1;
  3703. }
  3704. if (options->DirPort_set) {
  3705. /* Providing cached directory entries while system TCP buffers are scarce
  3706. * will exacerbate the socket errors. Suggest that this be disabled. */
  3707. COMPLAIN("You have requested constrained socket buffers while also "
  3708. "serving directory entries via DirPort. It is strongly "
  3709. "suggested that you disable serving directory requests when "
  3710. "system TCP buffer resources are scarce.");
  3711. }
  3712. }
  3713. if (options->V3AuthVoteDelay + options->V3AuthDistDelay >=
  3714. options->V3AuthVotingInterval/2) {
  3715. REJECT("V3AuthVoteDelay plus V3AuthDistDelay must be less than half "
  3716. "V3AuthVotingInterval");
  3717. }
  3718. if (options->V3AuthVoteDelay < MIN_VOTE_SECONDS)
  3719. REJECT("V3AuthVoteDelay is way too low.");
  3720. if (options->V3AuthDistDelay < MIN_DIST_SECONDS)
  3721. REJECT("V3AuthDistDelay is way too low.");
  3722. if (options->V3AuthNIntervalsValid < 2)
  3723. REJECT("V3AuthNIntervalsValid must be at least 2.");
  3724. if (options->V3AuthVotingInterval < MIN_VOTE_INTERVAL) {
  3725. REJECT("V3AuthVotingInterval is insanely low.");
  3726. } else if (options->V3AuthVotingInterval > 24*60*60) {
  3727. REJECT("V3AuthVotingInterval is insanely high.");
  3728. } else if (((24*60*60) % options->V3AuthVotingInterval) != 0) {
  3729. COMPLAIN("V3AuthVotingInterval does not divide evenly into 24 hours.");
  3730. }
  3731. if (rend_config_services(options, 1) < 0)
  3732. REJECT("Failed to configure rendezvous options. See logs for details.");
  3733. /* Parse client-side authorization for hidden services. */
  3734. if (rend_parse_service_authorization(options, 1) < 0)
  3735. REJECT("Failed to configure client authorization for hidden services. "
  3736. "See logs for details.");
  3737. if (parse_virtual_addr_network(options->VirtualAddrNetwork, 1, NULL)<0)
  3738. return -1;
  3739. if (options->PreferTunneledDirConns && !options->TunnelDirConns)
  3740. REJECT("Must set TunnelDirConns if PreferTunneledDirConns is set.");
  3741. if ((options->Socks4Proxy || options->Socks5Proxy) &&
  3742. !options->HTTPProxy && !options->PreferTunneledDirConns)
  3743. REJECT("When Socks4Proxy or Socks5Proxy is configured, "
  3744. "PreferTunneledDirConns and TunnelDirConns must both be "
  3745. "set to 1, or HTTPProxy must be configured.");
  3746. if (options->AutomapHostsSuffixes) {
  3747. SMARTLIST_FOREACH(options->AutomapHostsSuffixes, char *, suf,
  3748. {
  3749. size_t len = strlen(suf);
  3750. if (len && suf[len-1] == '.')
  3751. suf[len-1] = '\0';
  3752. });
  3753. }
  3754. if (options->TestingTorNetwork &&
  3755. !(options->DirServers ||
  3756. (options->AlternateDirAuthority &&
  3757. options->AlternateBridgeAuthority))) {
  3758. REJECT("TestingTorNetwork may only be configured in combination with "
  3759. "a non-default set of DirServer or both of AlternateDirAuthority "
  3760. "and AlternateBridgeAuthority configured.");
  3761. }
  3762. if (options->AllowSingleHopExits && !options->DirServers) {
  3763. COMPLAIN("You have set AllowSingleHopExits; now your relay will allow "
  3764. "others to make one-hop exits. However, since by default most "
  3765. "clients avoid relays that set this option, most clients will "
  3766. "ignore you.");
  3767. }
  3768. /*XXXX checking for defaults manually like this is a bit fragile.*/
  3769. /* Keep changes to hard-coded values synchronous to man page and default
  3770. * values table. */
  3771. if (options->TestingV3AuthInitialVotingInterval != 30*60 &&
  3772. !options->TestingTorNetwork && !options->_UsingTestNetworkDefaults) {
  3773. REJECT("TestingV3AuthInitialVotingInterval may only be changed in testing "
  3774. "Tor networks!");
  3775. } else if (options->TestingV3AuthInitialVotingInterval < MIN_VOTE_INTERVAL) {
  3776. REJECT("TestingV3AuthInitialVotingInterval is insanely low.");
  3777. } else if (((30*60) % options->TestingV3AuthInitialVotingInterval) != 0) {
  3778. REJECT("TestingV3AuthInitialVotingInterval does not divide evenly into "
  3779. "30 minutes.");
  3780. }
  3781. if (options->TestingV3AuthInitialVoteDelay != 5*60 &&
  3782. !options->TestingTorNetwork && !options->_UsingTestNetworkDefaults) {
  3783. REJECT("TestingV3AuthInitialVoteDelay may only be changed in testing "
  3784. "Tor networks!");
  3785. } else if (options->TestingV3AuthInitialVoteDelay < MIN_VOTE_SECONDS) {
  3786. REJECT("TestingV3AuthInitialVoteDelay is way too low.");
  3787. }
  3788. if (options->TestingV3AuthInitialDistDelay != 5*60 &&
  3789. !options->TestingTorNetwork && !options->_UsingTestNetworkDefaults) {
  3790. REJECT("TestingV3AuthInitialDistDelay may only be changed in testing "
  3791. "Tor networks!");
  3792. } else if (options->TestingV3AuthInitialDistDelay < MIN_DIST_SECONDS) {
  3793. REJECT("TestingV3AuthInitialDistDelay is way too low.");
  3794. }
  3795. if (options->TestingV3AuthInitialVoteDelay +
  3796. options->TestingV3AuthInitialDistDelay >=
  3797. options->TestingV3AuthInitialVotingInterval/2) {
  3798. REJECT("TestingV3AuthInitialVoteDelay plus TestingV3AuthInitialDistDelay "
  3799. "must be less than half TestingV3AuthInitialVotingInterval");
  3800. }
  3801. if (options->TestingAuthDirTimeToLearnReachability != 30*60 &&
  3802. !options->TestingTorNetwork && !options->_UsingTestNetworkDefaults) {
  3803. REJECT("TestingAuthDirTimeToLearnReachability may only be changed in "
  3804. "testing Tor networks!");
  3805. } else if (options->TestingAuthDirTimeToLearnReachability < 0) {
  3806. REJECT("TestingAuthDirTimeToLearnReachability must be non-negative.");
  3807. } else if (options->TestingAuthDirTimeToLearnReachability > 2*60*60) {
  3808. COMPLAIN("TestingAuthDirTimeToLearnReachability is insanely high.");
  3809. }
  3810. if (options->TestingEstimatedDescriptorPropagationTime != 10*60 &&
  3811. !options->TestingTorNetwork && !options->_UsingTestNetworkDefaults) {
  3812. REJECT("TestingEstimatedDescriptorPropagationTime may only be changed in "
  3813. "testing Tor networks!");
  3814. } else if (options->TestingEstimatedDescriptorPropagationTime < 0) {
  3815. REJECT("TestingEstimatedDescriptorPropagationTime must be non-negative.");
  3816. } else if (options->TestingEstimatedDescriptorPropagationTime > 60*60) {
  3817. COMPLAIN("TestingEstimatedDescriptorPropagationTime is insanely high.");
  3818. }
  3819. if (options->TestingTorNetwork) {
  3820. log_warn(LD_CONFIG, "TestingTorNetwork is set. This will make your node "
  3821. "almost unusable in the public Tor network, and is "
  3822. "therefore only advised if you are building a "
  3823. "testing Tor network!");
  3824. }
  3825. if (options->AccelName && !options->HardwareAccel)
  3826. options->HardwareAccel = 1;
  3827. if (options->AccelDir && !options->AccelName)
  3828. REJECT("Can't use hardware crypto accelerator dir without engine name.");
  3829. if (options->PublishServerDescriptor)
  3830. SMARTLIST_FOREACH(options->PublishServerDescriptor, const char *, pubdes, {
  3831. if (!strcmp(pubdes, "1") || !strcmp(pubdes, "0"))
  3832. if (smartlist_len(options->PublishServerDescriptor) > 1) {
  3833. COMPLAIN("You have passed a list of multiple arguments to the "
  3834. "PublishServerDescriptor option that includes 0 or 1. "
  3835. "0 or 1 should only be used as the sole argument. "
  3836. "This configuration will be rejected in a future release.");
  3837. break;
  3838. }
  3839. });
  3840. if (options->BridgeRelay == 1 && ! options->ORPort_set)
  3841. REJECT("BridgeRelay is 1, ORPort is not set. This is an invalid "
  3842. "combination.");
  3843. return 0;
  3844. #undef REJECT
  3845. #undef COMPLAIN
  3846. }
  3847. /** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
  3848. * equal strings. */
  3849. static int
  3850. opt_streq(const char *s1, const char *s2)
  3851. {
  3852. return 0 == strcmp_opt(s1, s2);
  3853. }
  3854. /** Check if any of the previous options have changed but aren't allowed to. */
  3855. static int
  3856. options_transition_allowed(const or_options_t *old,
  3857. const or_options_t *new_val,
  3858. char **msg)
  3859. {
  3860. if (!old)
  3861. return 0;
  3862. if (!opt_streq(old->PidFile, new_val->PidFile)) {
  3863. *msg = tor_strdup("PidFile is not allowed to change.");
  3864. return -1;
  3865. }
  3866. if (old->RunAsDaemon != new_val->RunAsDaemon) {
  3867. *msg = tor_strdup("While Tor is running, changing RunAsDaemon "
  3868. "is not allowed.");
  3869. return -1;
  3870. }
  3871. if (strcmp(old->DataDirectory,new_val->DataDirectory)!=0) {
  3872. tor_asprintf(msg,
  3873. "While Tor is running, changing DataDirectory "
  3874. "(\"%s\"->\"%s\") is not allowed.",
  3875. old->DataDirectory, new_val->DataDirectory);
  3876. return -1;
  3877. }
  3878. if (!opt_streq(old->User, new_val->User)) {
  3879. *msg = tor_strdup("While Tor is running, changing User is not allowed.");
  3880. return -1;
  3881. }
  3882. if ((old->HardwareAccel != new_val->HardwareAccel)
  3883. || !opt_streq(old->AccelName, new_val->AccelName)
  3884. || !opt_streq(old->AccelDir, new_val->AccelDir)) {
  3885. *msg = tor_strdup("While Tor is running, changing OpenSSL hardware "
  3886. "acceleration engine is not allowed.");
  3887. return -1;
  3888. }
  3889. if (old->TestingTorNetwork != new_val->TestingTorNetwork) {
  3890. *msg = tor_strdup("While Tor is running, changing TestingTorNetwork "
  3891. "is not allowed.");
  3892. return -1;
  3893. }
  3894. if (old->DisableAllSwap != new_val->DisableAllSwap) {
  3895. *msg = tor_strdup("While Tor is running, changing DisableAllSwap "
  3896. "is not allowed.");
  3897. return -1;
  3898. }
  3899. if (old->TokenBucketRefillInterval != new_val->TokenBucketRefillInterval) {
  3900. *msg = tor_strdup("While Tor is running, changing TokenBucketRefill"
  3901. "Interval is not allowed");
  3902. return -1;
  3903. }
  3904. if (old->DisableIOCP != new_val->DisableIOCP) {
  3905. *msg = tor_strdup("While Tor is running, changing DisableIOCP "
  3906. "is not allowed.");
  3907. return -1;
  3908. }
  3909. if (old->DisableDebuggerAttachment &&
  3910. !new_val->DisableDebuggerAttachment) {
  3911. *msg = tor_strdup("While Tor is running, disabling "
  3912. "DisableDebuggerAttachment is not allowed.");
  3913. return -1;
  3914. }
  3915. return 0;
  3916. }
  3917. /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
  3918. * will require us to rotate the CPU and DNS workers; else return 0. */
  3919. static int
  3920. options_transition_affects_workers(const or_options_t *old_options,
  3921. const or_options_t *new_options)
  3922. {
  3923. if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
  3924. old_options->NumCPUs != new_options->NumCPUs ||
  3925. !config_lines_eq(old_options->ORPort_lines, new_options->ORPort_lines) ||
  3926. old_options->ServerDNSSearchDomains !=
  3927. new_options->ServerDNSSearchDomains ||
  3928. old_options->_SafeLogging != new_options->_SafeLogging ||
  3929. old_options->ClientOnly != new_options->ClientOnly ||
  3930. public_server_mode(old_options) != public_server_mode(new_options) ||
  3931. !config_lines_eq(old_options->Logs, new_options->Logs) ||
  3932. old_options->LogMessageDomains != new_options->LogMessageDomains)
  3933. return 1;
  3934. /* Check whether log options match. */
  3935. /* Nothing that changed matters. */
  3936. return 0;
  3937. }
  3938. /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
  3939. * will require us to generate a new descriptor; else return 0. */
  3940. static int
  3941. options_transition_affects_descriptor(const or_options_t *old_options,
  3942. const or_options_t *new_options)
  3943. {
  3944. /* XXX We can be smarter here. If your DirPort isn't being
  3945. * published and you just turned it off, no need to republish. Etc. */
  3946. if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
  3947. !opt_streq(old_options->Nickname,new_options->Nickname) ||
  3948. !opt_streq(old_options->Address,new_options->Address) ||
  3949. !config_lines_eq(old_options->ExitPolicy,new_options->ExitPolicy) ||
  3950. old_options->ExitPolicyRejectPrivate !=
  3951. new_options->ExitPolicyRejectPrivate ||
  3952. !config_lines_eq(old_options->ORPort_lines,
  3953. new_options->ORPort_lines) ||
  3954. !config_lines_eq(old_options->DirPort_lines,
  3955. new_options->DirPort_lines) ||
  3956. old_options->ClientOnly != new_options->ClientOnly ||
  3957. old_options->DisableNetwork != new_options->DisableNetwork ||
  3958. old_options->_PublishServerDescriptor !=
  3959. new_options->_PublishServerDescriptor ||
  3960. get_effective_bwrate(old_options) != get_effective_bwrate(new_options) ||
  3961. get_effective_bwburst(old_options) !=
  3962. get_effective_bwburst(new_options) ||
  3963. !opt_streq(old_options->ContactInfo, new_options->ContactInfo) ||
  3964. !opt_streq(old_options->MyFamily, new_options->MyFamily) ||
  3965. !opt_streq(old_options->AccountingStart, new_options->AccountingStart) ||
  3966. old_options->AccountingMax != new_options->AccountingMax ||
  3967. public_server_mode(old_options) != public_server_mode(new_options))
  3968. return 1;
  3969. return 0;
  3970. }
  3971. #ifdef _WIN32
  3972. /** Return the directory on windows where we expect to find our application
  3973. * data. */
  3974. static char *
  3975. get_windows_conf_root(void)
  3976. {
  3977. static int is_set = 0;
  3978. static char path[MAX_PATH*2+1];
  3979. TCHAR tpath[MAX_PATH] = {0};
  3980. LPITEMIDLIST idl;
  3981. IMalloc *m;
  3982. HRESULT result;
  3983. if (is_set)
  3984. return path;
  3985. /* Find X:\documents and settings\username\application data\ .
  3986. * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
  3987. */
  3988. #ifdef ENABLE_LOCAL_APPDATA
  3989. #define APPDATA_PATH CSIDL_LOCAL_APPDATA
  3990. #else
  3991. #define APPDATA_PATH CSIDL_APPDATA
  3992. #endif
  3993. if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL, APPDATA_PATH, &idl))) {
  3994. getcwd(path,MAX_PATH);
  3995. is_set = 1;
  3996. log_warn(LD_CONFIG,
  3997. "I couldn't find your application data folder: are you "
  3998. "running an ancient version of Windows 95? Defaulting to \"%s\"",
  3999. path);
  4000. return path;
  4001. }
  4002. /* Convert the path from an "ID List" (whatever that is!) to a path. */
  4003. result = SHGetPathFromIDList(idl, tpath);
  4004. #ifdef UNICODE
  4005. wcstombs(path,tpath,sizeof(path));
  4006. path[sizeof(path)-1] = '\0';
  4007. #else
  4008. strlcpy(path,tpath,sizeof(path));
  4009. #endif
  4010. /* Now we need to free the memory that the path-idl was stored in. In
  4011. * typical Windows fashion, we can't just call 'free()' on it. */
  4012. SHGetMalloc(&m);
  4013. if (m) {
  4014. m->lpVtbl->Free(m, idl);
  4015. m->lpVtbl->Release(m);
  4016. }
  4017. if (!SUCCEEDED(result)) {
  4018. return NULL;
  4019. }
  4020. strlcat(path,"\\tor",MAX_PATH);
  4021. is_set = 1;
  4022. return path;
  4023. }
  4024. #endif
  4025. /** Return the default location for our torrc file (if <b>defaults_file</b> is
  4026. * false), or for the torrc-defaults file (if <b>defaults_file</b> is true). */
  4027. static const char *
  4028. get_default_conf_file(int defaults_file)
  4029. {
  4030. #ifdef _WIN32
  4031. if (defaults_file) {
  4032. static char defaults_path[MAX_PATH+1];
  4033. tor_snprintf(defaults_path, MAX_PATH, "%s\\torrc-defaults",
  4034. get_windows_conf_root());
  4035. return defaults_path;
  4036. } else {
  4037. static char path[MAX_PATH+1];
  4038. tor_snprintf(path, MAX_PATH, "%s\\torrc",
  4039. get_windows_conf_root());
  4040. return path;
  4041. }
  4042. #else
  4043. return defaults_file ? CONFDIR "/torrc-defaults" : CONFDIR "/torrc";
  4044. #endif
  4045. }
  4046. /** Verify whether lst is a string containing valid-looking comma-separated
  4047. * nicknames, or NULL. Return 0 on success. Warn and return -1 on failure.
  4048. */
  4049. static int
  4050. check_nickname_list(const char *lst, const char *name, char **msg)
  4051. {
  4052. int r = 0;
  4053. smartlist_t *sl;
  4054. if (!lst)
  4055. return 0;
  4056. sl = smartlist_new();
  4057. smartlist_split_string(sl, lst, ",",
  4058. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK|SPLIT_STRIP_SPACE, 0);
  4059. SMARTLIST_FOREACH(sl, const char *, s,
  4060. {
  4061. if (!is_legal_nickname_or_hexdigest(s)) {
  4062. tor_asprintf(msg, "Invalid nickname '%s' in %s line", s, name);
  4063. r = -1;
  4064. break;
  4065. }
  4066. });
  4067. SMARTLIST_FOREACH(sl, char *, s, tor_free(s));
  4068. smartlist_free(sl);
  4069. return r;
  4070. }
  4071. /** Learn config file name from command line arguments, or use the default.
  4072. *
  4073. * If <b>defaults_file</b> is true, we're looking for torrc-defaults;
  4074. * otherwise, we're looking for the regular torrc_file.
  4075. *
  4076. * Set *<b>using_default_fname</b> to true if we're using the default
  4077. * configuration file name; or false if we've set it from the command line.
  4078. *
  4079. * Set *<b>ignore_missing_torrc</b> to true if we should ignore the resulting
  4080. * filename if it doesn't exist.
  4081. */
  4082. static char *
  4083. find_torrc_filename(int argc, char **argv,
  4084. int defaults_file,
  4085. int *using_default_fname, int *ignore_missing_torrc)
  4086. {
  4087. char *fname=NULL;
  4088. int i;
  4089. const char *fname_opt = defaults_file ? "--defaults-torrc" : "-f";
  4090. const char *ignore_opt = defaults_file ? NULL : "--ignore-missing-torrc";
  4091. if (defaults_file)
  4092. *ignore_missing_torrc = 1;
  4093. for (i = 1; i < argc; ++i) {
  4094. if (i < argc-1 && !strcmp(argv[i],fname_opt)) {
  4095. if (fname) {
  4096. log(LOG_WARN, LD_CONFIG, "Duplicate %s options on command line.",
  4097. fname_opt);
  4098. tor_free(fname);
  4099. }
  4100. fname = expand_filename(argv[i+1]);
  4101. {
  4102. char *absfname;
  4103. absfname = make_path_absolute(fname);
  4104. tor_free(fname);
  4105. fname = absfname;
  4106. }
  4107. *using_default_fname = 0;
  4108. ++i;
  4109. } else if (ignore_opt && !strcmp(argv[i],ignore_opt)) {
  4110. *ignore_missing_torrc = 1;
  4111. }
  4112. }
  4113. if (*using_default_fname) {
  4114. /* didn't find one, try CONFDIR */
  4115. const char *dflt = get_default_conf_file(defaults_file);
  4116. if (dflt && file_status(dflt) == FN_FILE) {
  4117. fname = tor_strdup(dflt);
  4118. } else {
  4119. #ifndef _WIN32
  4120. char *fn = NULL;
  4121. if (!defaults_file)
  4122. fn = expand_filename("~/.torrc");
  4123. if (fn && file_status(fn) == FN_FILE) {
  4124. fname = fn;
  4125. } else {
  4126. tor_free(fn);
  4127. fname = tor_strdup(dflt);
  4128. }
  4129. #else
  4130. fname = tor_strdup(dflt);
  4131. #endif
  4132. }
  4133. }
  4134. return fname;
  4135. }
  4136. /** Load a configuration file from disk, setting torrc_fname or
  4137. * torrc_defaults_fname if successful.
  4138. *
  4139. * If <b>defaults_file</b> is true, load torrc-defaults; otherwise load torrc.
  4140. *
  4141. * Return the contents of the file on success, and NULL on failure.
  4142. */
  4143. static char *
  4144. load_torrc_from_disk(int argc, char **argv, int defaults_file)
  4145. {
  4146. char *fname=NULL;
  4147. char *cf = NULL;
  4148. int using_default_torrc = 1;
  4149. int ignore_missing_torrc = 0;
  4150. char **fname_var = defaults_file ? &torrc_defaults_fname : &torrc_fname;
  4151. fname = find_torrc_filename(argc, argv, defaults_file,
  4152. &using_default_torrc, &ignore_missing_torrc);
  4153. tor_assert(fname);
  4154. log(LOG_DEBUG, LD_CONFIG, "Opening config file \"%s\"", fname);
  4155. tor_free(*fname_var);
  4156. *fname_var = fname;
  4157. /* Open config file */
  4158. if (file_status(fname) != FN_FILE ||
  4159. !(cf = read_file_to_str(fname,0,NULL))) {
  4160. if (using_default_torrc == 1 || ignore_missing_torrc) {
  4161. if (!defaults_file)
  4162. log(LOG_NOTICE, LD_CONFIG, "Configuration file \"%s\" not present, "
  4163. "using reasonable defaults.", fname);
  4164. tor_free(fname); /* sets fname to NULL */
  4165. *fname_var = NULL;
  4166. cf = tor_strdup("");
  4167. } else {
  4168. log(LOG_WARN, LD_CONFIG,
  4169. "Unable to open configuration file \"%s\".", fname);
  4170. goto err;
  4171. }
  4172. } else {
  4173. log(LOG_NOTICE, LD_CONFIG, "Read configuration file \"%s\".", fname);
  4174. }
  4175. return cf;
  4176. err:
  4177. tor_free(fname);
  4178. *fname_var = NULL;
  4179. return NULL;
  4180. }
  4181. /** Read a configuration file into <b>options</b>, finding the configuration
  4182. * file location based on the command line. After loading the file
  4183. * call options_init_from_string() to load the config.
  4184. * Return 0 if success, -1 if failure. */
  4185. int
  4186. options_init_from_torrc(int argc, char **argv)
  4187. {
  4188. char *cf=NULL, *cf_defaults=NULL;
  4189. int i, command;
  4190. int retval = -1;
  4191. static char **backup_argv;
  4192. static int backup_argc;
  4193. char *command_arg = NULL;
  4194. char *errmsg=NULL;
  4195. if (argv) { /* first time we're called. save command line args */
  4196. backup_argv = argv;
  4197. backup_argc = argc;
  4198. } else { /* we're reloading. need to clean up old options first. */
  4199. argv = backup_argv;
  4200. argc = backup_argc;
  4201. }
  4202. if (argc > 1 && (!strcmp(argv[1], "-h") || !strcmp(argv[1],"--help"))) {
  4203. print_usage();
  4204. exit(0);
  4205. }
  4206. if (argc > 1 && !strcmp(argv[1], "--list-torrc-options")) {
  4207. /* For documenting validating whether we've documented everything. */
  4208. list_torrc_options();
  4209. exit(0);
  4210. }
  4211. if (argc > 1 && (!strcmp(argv[1],"--version"))) {
  4212. printf("Tor version %s.\n",get_version());
  4213. exit(0);
  4214. }
  4215. if (argc > 1 && (!strcmp(argv[1],"--digests"))) {
  4216. printf("Tor version %s.\n",get_version());
  4217. printf("%s", libor_get_digests());
  4218. printf("%s", tor_get_digests());
  4219. exit(0);
  4220. }
  4221. /* Go through command-line variables */
  4222. if (!global_cmdline_options) {
  4223. /* Or we could redo the list every time we pass this place.
  4224. * It does not really matter */
  4225. if (config_get_commandlines(argc, argv, &global_cmdline_options) < 0) {
  4226. goto err;
  4227. }
  4228. }
  4229. command = CMD_RUN_TOR;
  4230. for (i = 1; i < argc; ++i) {
  4231. if (!strcmp(argv[i],"--list-fingerprint")) {
  4232. command = CMD_LIST_FINGERPRINT;
  4233. } else if (!strcmp(argv[i],"--hash-password")) {
  4234. command = CMD_HASH_PASSWORD;
  4235. command_arg = tor_strdup( (i < argc-1) ? argv[i+1] : "");
  4236. ++i;
  4237. } else if (!strcmp(argv[i],"--verify-config")) {
  4238. command = CMD_VERIFY_CONFIG;
  4239. }
  4240. }
  4241. if (command == CMD_HASH_PASSWORD) {
  4242. cf = tor_strdup("");
  4243. } else {
  4244. cf_defaults = load_torrc_from_disk(argc, argv, 1);
  4245. cf = load_torrc_from_disk(argc, argv, 0);
  4246. if (!cf)
  4247. goto err;
  4248. }
  4249. retval = options_init_from_string(cf_defaults, cf, command, command_arg,
  4250. &errmsg);
  4251. err:
  4252. tor_free(cf);
  4253. tor_free(cf_defaults);
  4254. if (errmsg) {
  4255. log(LOG_WARN,LD_CONFIG,"%s", errmsg);
  4256. tor_free(errmsg);
  4257. }
  4258. return retval < 0 ? -1 : 0;
  4259. }
  4260. /** Load the options from the configuration in <b>cf</b>, validate
  4261. * them for consistency and take actions based on them.
  4262. *
  4263. * Return 0 if success, negative on error:
  4264. * * -1 for general errors.
  4265. * * -2 for failure to parse/validate,
  4266. * * -3 for transition not allowed
  4267. * * -4 for error while setting the new options
  4268. */
  4269. setopt_err_t
  4270. options_init_from_string(const char *cf_defaults, const char *cf,
  4271. int command, const char *command_arg,
  4272. char **msg)
  4273. {
  4274. or_options_t *oldoptions, *newoptions, *newdefaultoptions=NULL;
  4275. config_line_t *cl;
  4276. int retval, i;
  4277. setopt_err_t err = SETOPT_ERR_MISC;
  4278. tor_assert(msg);
  4279. oldoptions = global_options; /* get_options unfortunately asserts if
  4280. this is the first time we run*/
  4281. newoptions = tor_malloc_zero(sizeof(or_options_t));
  4282. newoptions->_magic = OR_OPTIONS_MAGIC;
  4283. options_init(newoptions);
  4284. newoptions->command = command;
  4285. newoptions->command_arg = command_arg;
  4286. for (i = 0; i < 2; ++i) {
  4287. const char *body = i==0 ? cf_defaults : cf;
  4288. if (!body)
  4289. continue;
  4290. /* get config lines, assign them */
  4291. retval = config_get_lines(body, &cl, 1);
  4292. if (retval < 0) {
  4293. err = SETOPT_ERR_PARSE;
  4294. goto err;
  4295. }
  4296. retval = config_assign(&options_format, newoptions, cl, 0, 0, msg);
  4297. config_free_lines(cl);
  4298. if (retval < 0) {
  4299. err = SETOPT_ERR_PARSE;
  4300. goto err;
  4301. }
  4302. if (i==0)
  4303. newdefaultoptions = options_dup(&options_format, newoptions);
  4304. }
  4305. /* Go through command-line variables too */
  4306. retval = config_assign(&options_format, newoptions,
  4307. global_cmdline_options, 0, 0, msg);
  4308. if (retval < 0) {
  4309. err = SETOPT_ERR_PARSE;
  4310. goto err;
  4311. }
  4312. /* If this is a testing network configuration, change defaults
  4313. * for a list of dependent config options, re-initialize newoptions
  4314. * with the new defaults, and assign all options to it second time. */
  4315. if (newoptions->TestingTorNetwork) {
  4316. /* XXXX this is a bit of a kludge. perhaps there's a better way to do
  4317. * this? We could, for example, make the parsing algorithm do two passes
  4318. * over the configuration. If it finds any "suite" options like
  4319. * TestingTorNetwork, it could change the defaults before its second pass.
  4320. * Not urgent so long as this seems to work, but at any sign of trouble,
  4321. * let's clean it up. -NM */
  4322. /* Change defaults. */
  4323. int i;
  4324. for (i = 0; testing_tor_network_defaults[i].name; ++i) {
  4325. const config_var_t *new_var = &testing_tor_network_defaults[i];
  4326. config_var_t *old_var =
  4327. config_find_option_mutable(&options_format, new_var->name);
  4328. tor_assert(new_var);
  4329. tor_assert(old_var);
  4330. old_var->initvalue = new_var->initvalue;
  4331. }
  4332. /* Clear newoptions and re-initialize them with new defaults. */
  4333. config_free(&options_format, newoptions);
  4334. config_free(&options_format, newdefaultoptions);
  4335. newdefaultoptions = NULL;
  4336. newoptions = tor_malloc_zero(sizeof(or_options_t));
  4337. newoptions->_magic = OR_OPTIONS_MAGIC;
  4338. options_init(newoptions);
  4339. newoptions->command = command;
  4340. newoptions->command_arg = command_arg;
  4341. /* Assign all options a second time. */
  4342. for (i = 0; i < 2; ++i) {
  4343. const char *body = i==0 ? cf_defaults : cf;
  4344. if (!body)
  4345. continue;
  4346. /* get config lines, assign them */
  4347. retval = config_get_lines(body, &cl, 1);
  4348. if (retval < 0) {
  4349. err = SETOPT_ERR_PARSE;
  4350. goto err;
  4351. }
  4352. retval = config_assign(&options_format, newoptions, cl, 0, 0, msg);
  4353. config_free_lines(cl);
  4354. if (retval < 0) {
  4355. err = SETOPT_ERR_PARSE;
  4356. goto err;
  4357. }
  4358. if (i==0)
  4359. newdefaultoptions = options_dup(&options_format, newoptions);
  4360. }
  4361. /* Assign command-line variables a second time too */
  4362. retval = config_assign(&options_format, newoptions,
  4363. global_cmdline_options, 0, 0, msg);
  4364. if (retval < 0) {
  4365. err = SETOPT_ERR_PARSE;
  4366. goto err;
  4367. }
  4368. }
  4369. /* Validate newoptions */
  4370. if (options_validate(oldoptions, newoptions, 0, msg) < 0) {
  4371. err = SETOPT_ERR_PARSE; /*XXX make this a separate return value.*/
  4372. goto err;
  4373. }
  4374. if (options_transition_allowed(oldoptions, newoptions, msg) < 0) {
  4375. err = SETOPT_ERR_TRANSITION;
  4376. goto err;
  4377. }
  4378. if (set_options(newoptions, msg)) {
  4379. err = SETOPT_ERR_SETTING;
  4380. goto err; /* frees and replaces old options */
  4381. }
  4382. config_free(&options_format, global_default_options);
  4383. global_default_options = newdefaultoptions;
  4384. return SETOPT_OK;
  4385. err:
  4386. config_free(&options_format, newoptions);
  4387. config_free(&options_format, newdefaultoptions);
  4388. if (*msg) {
  4389. char *old_msg = *msg;
  4390. tor_asprintf(msg, "Failed to parse/validate config: %s", old_msg);
  4391. tor_free(old_msg);
  4392. }
  4393. return err;
  4394. }
  4395. /** Return the location for our configuration file.
  4396. */
  4397. const char *
  4398. get_torrc_fname(int defaults_fname)
  4399. {
  4400. const char *fname = defaults_fname ? torrc_defaults_fname : torrc_fname;
  4401. if (fname)
  4402. return fname;
  4403. else
  4404. return get_default_conf_file(defaults_fname);
  4405. }
  4406. /** Adjust the address map based on the MapAddress elements in the
  4407. * configuration <b>options</b>
  4408. */
  4409. void
  4410. config_register_addressmaps(const or_options_t *options)
  4411. {
  4412. smartlist_t *elts;
  4413. config_line_t *opt;
  4414. const char *from, *to, *msg;
  4415. addressmap_clear_configured();
  4416. elts = smartlist_new();
  4417. for (opt = options->AddressMap; opt; opt = opt->next) {
  4418. smartlist_split_string(elts, opt->value, NULL,
  4419. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
  4420. if (smartlist_len(elts) < 2) {
  4421. log_warn(LD_CONFIG,"MapAddress '%s' has too few arguments. Ignoring.",
  4422. opt->value);
  4423. goto cleanup;
  4424. }
  4425. from = smartlist_get(elts,0);
  4426. to = smartlist_get(elts,1);
  4427. if (to[0] == '.' || from[0] == '.') {
  4428. log_warn(LD_CONFIG,"MapAddress '%s' is ambiguous - address starts with a"
  4429. "'.'. Ignoring.",opt->value);
  4430. goto cleanup;
  4431. }
  4432. if (addressmap_register_auto(from, to, 0, ADDRMAPSRC_TORRC, &msg) < 0) {
  4433. log_warn(LD_CONFIG,"MapAddress '%s' failed: %s. Ignoring.", opt->value,
  4434. msg);
  4435. goto cleanup;
  4436. }
  4437. if (smartlist_len(elts) > 2)
  4438. log_warn(LD_CONFIG,"Ignoring extra arguments to MapAddress.");
  4439. cleanup:
  4440. SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
  4441. smartlist_clear(elts);
  4442. }
  4443. smartlist_free(elts);
  4444. }
  4445. /** As addressmap_register(), but detect the wildcarded status of "from" and
  4446. * "to", and do not steal a reference to <b>to</b>. */
  4447. /* XXXX024 move to connection_edge.c */
  4448. int
  4449. addressmap_register_auto(const char *from, const char *to,
  4450. time_t expires,
  4451. addressmap_entry_source_t addrmap_source,
  4452. const char **msg)
  4453. {
  4454. int from_wildcard = 0, to_wildcard = 0;
  4455. *msg = "whoops, forgot the error message";
  4456. if (1) {
  4457. if (!strcmp(to, "*") || !strcmp(from, "*")) {
  4458. *msg = "can't remap from or to *";
  4459. return -1;
  4460. }
  4461. /* Detect asterisks in expressions of type: '*.example.com' */
  4462. if (!strncmp(from,"*.",2)) {
  4463. from += 2;
  4464. from_wildcard = 1;
  4465. }
  4466. if (!strncmp(to,"*.",2)) {
  4467. to += 2;
  4468. to_wildcard = 1;
  4469. }
  4470. if (to_wildcard && !from_wildcard) {
  4471. *msg = "can only use wildcard (i.e. '*.') if 'from' address "
  4472. "uses wildcard also";
  4473. return -1;
  4474. }
  4475. if (address_is_invalid_destination(to, 1)) {
  4476. *msg = "destination is invalid";
  4477. return -1;
  4478. }
  4479. addressmap_register(from, tor_strdup(to), expires, addrmap_source,
  4480. from_wildcard, to_wildcard);
  4481. }
  4482. return 0;
  4483. }
  4484. /**
  4485. * Initialize the logs based on the configuration file.
  4486. */
  4487. static int
  4488. options_init_logs(or_options_t *options, int validate_only)
  4489. {
  4490. config_line_t *opt;
  4491. int ok;
  4492. smartlist_t *elts;
  4493. int daemon =
  4494. #ifdef _WIN32
  4495. 0;
  4496. #else
  4497. options->RunAsDaemon;
  4498. #endif
  4499. if (options->LogTimeGranularity <= 0) {
  4500. log_warn(LD_CONFIG, "Log time granularity '%d' has to be positive.",
  4501. options->LogTimeGranularity);
  4502. return -1;
  4503. } else if (1000 % options->LogTimeGranularity != 0 &&
  4504. options->LogTimeGranularity % 1000 != 0) {
  4505. int granularity = options->LogTimeGranularity;
  4506. if (granularity < 40) {
  4507. do granularity++;
  4508. while (1000 % granularity != 0);
  4509. } else if (granularity < 1000) {
  4510. granularity = 1000 / granularity;
  4511. while (1000 % granularity != 0)
  4512. granularity--;
  4513. granularity = 1000 / granularity;
  4514. } else {
  4515. granularity = 1000 * ((granularity / 1000) + 1);
  4516. }
  4517. log_warn(LD_CONFIG, "Log time granularity '%d' has to be either a "
  4518. "divisor or a multiple of 1 second. Changing to "
  4519. "'%d'.",
  4520. options->LogTimeGranularity, granularity);
  4521. if (!validate_only)
  4522. set_log_time_granularity(granularity);
  4523. } else {
  4524. if (!validate_only)
  4525. set_log_time_granularity(options->LogTimeGranularity);
  4526. }
  4527. ok = 1;
  4528. elts = smartlist_new();
  4529. for (opt = options->Logs; opt; opt = opt->next) {
  4530. log_severity_list_t *severity;
  4531. const char *cfg = opt->value;
  4532. severity = tor_malloc_zero(sizeof(log_severity_list_t));
  4533. if (parse_log_severity_config(&cfg, severity) < 0) {
  4534. log_warn(LD_CONFIG, "Couldn't parse log levels in Log option 'Log %s'",
  4535. opt->value);
  4536. ok = 0; goto cleanup;
  4537. }
  4538. smartlist_split_string(elts, cfg, NULL,
  4539. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
  4540. if (smartlist_len(elts) == 0)
  4541. smartlist_add(elts, tor_strdup("stdout"));
  4542. if (smartlist_len(elts) == 1 &&
  4543. (!strcasecmp(smartlist_get(elts,0), "stdout") ||
  4544. !strcasecmp(smartlist_get(elts,0), "stderr"))) {
  4545. int err = smartlist_len(elts) &&
  4546. !strcasecmp(smartlist_get(elts,0), "stderr");
  4547. if (!validate_only) {
  4548. if (daemon) {
  4549. log_warn(LD_CONFIG,
  4550. "Can't log to %s with RunAsDaemon set; skipping stdout",
  4551. err?"stderr":"stdout");
  4552. } else {
  4553. add_stream_log(severity, err?"<stderr>":"<stdout>",
  4554. fileno(err?stderr:stdout));
  4555. }
  4556. }
  4557. goto cleanup;
  4558. }
  4559. if (smartlist_len(elts) == 1 &&
  4560. !strcasecmp(smartlist_get(elts,0), "syslog")) {
  4561. #ifdef HAVE_SYSLOG_H
  4562. if (!validate_only) {
  4563. add_syslog_log(severity);
  4564. }
  4565. #else
  4566. log_warn(LD_CONFIG, "Syslog is not supported on this system. Sorry.");
  4567. #endif
  4568. goto cleanup;
  4569. }
  4570. if (smartlist_len(elts) == 2 &&
  4571. !strcasecmp(smartlist_get(elts,0), "file")) {
  4572. if (!validate_only) {
  4573. char *fname = expand_filename(smartlist_get(elts, 1));
  4574. if (add_file_log(severity, fname) < 0) {
  4575. log_warn(LD_CONFIG, "Couldn't open file for 'Log %s': %s",
  4576. opt->value, strerror(errno));
  4577. ok = 0;
  4578. }
  4579. tor_free(fname);
  4580. }
  4581. goto cleanup;
  4582. }
  4583. log_warn(LD_CONFIG, "Bad syntax on file Log option 'Log %s'",
  4584. opt->value);
  4585. ok = 0; goto cleanup;
  4586. cleanup:
  4587. SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
  4588. smartlist_clear(elts);
  4589. tor_free(severity);
  4590. }
  4591. smartlist_free(elts);
  4592. if (ok && !validate_only)
  4593. logs_set_domain_logging(options->LogMessageDomains);
  4594. return ok?0:-1;
  4595. }
  4596. /** Read the contents of a Bridge line from <b>line</b>. Return 0
  4597. * if the line is well-formed, and -1 if it isn't. If
  4598. * <b>validate_only</b> is 0, and the line is well-formed, then add
  4599. * the bridge described in the line to our internal bridge list. */
  4600. static int
  4601. parse_bridge_line(const char *line, int validate_only)
  4602. {
  4603. smartlist_t *items = NULL;
  4604. int r;
  4605. char *addrport=NULL, *fingerprint=NULL;
  4606. char *transport_name=NULL;
  4607. char *field1=NULL;
  4608. tor_addr_t addr;
  4609. uint16_t port = 0;
  4610. char digest[DIGEST_LEN];
  4611. items = smartlist_new();
  4612. smartlist_split_string(items, line, NULL,
  4613. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
  4614. if (smartlist_len(items) < 1) {
  4615. log_warn(LD_CONFIG, "Too few arguments to Bridge line.");
  4616. goto err;
  4617. }
  4618. /* field1 is either a transport name or addrport */
  4619. field1 = smartlist_get(items, 0);
  4620. smartlist_del_keeporder(items, 0);
  4621. if (!(strstr(field1, ".") || strstr(field1, ":"))) {
  4622. /* new-style bridge line */
  4623. transport_name = field1;
  4624. if (smartlist_len(items) < 1) {
  4625. log_warn(LD_CONFIG, "Too few items to Bridge line.");
  4626. goto err;
  4627. }
  4628. addrport = smartlist_get(items, 0);
  4629. smartlist_del_keeporder(items, 0);
  4630. } else {
  4631. addrport = field1;
  4632. }
  4633. if (tor_addr_port_lookup(addrport, &addr, &port)<0) {
  4634. log_warn(LD_CONFIG, "Error parsing Bridge address '%s'", addrport);
  4635. goto err;
  4636. }
  4637. if (!port) {
  4638. log_info(LD_CONFIG,
  4639. "Bridge address '%s' has no port; using default port 443.",
  4640. addrport);
  4641. port = 443;
  4642. }
  4643. if (smartlist_len(items)) {
  4644. fingerprint = smartlist_join_strings(items, "", 0, NULL);
  4645. if (strlen(fingerprint) != HEX_DIGEST_LEN) {
  4646. log_warn(LD_CONFIG, "Key digest for Bridge is wrong length.");
  4647. goto err;
  4648. }
  4649. if (base16_decode(digest, DIGEST_LEN, fingerprint, HEX_DIGEST_LEN)<0) {
  4650. log_warn(LD_CONFIG, "Unable to decode Bridge key digest.");
  4651. goto err;
  4652. }
  4653. }
  4654. if (!validate_only) {
  4655. log_debug(LD_DIR, "Bridge at %s:%d (transport: %s) (%s)",
  4656. fmt_addr(&addr), (int)port,
  4657. transport_name ? transport_name : "no transport",
  4658. fingerprint ? fingerprint : "no key listed");
  4659. bridge_add_from_config(&addr, port,
  4660. fingerprint ? digest : NULL, transport_name);
  4661. }
  4662. r = 0;
  4663. goto done;
  4664. err:
  4665. r = -1;
  4666. done:
  4667. SMARTLIST_FOREACH(items, char*, s, tor_free(s));
  4668. smartlist_free(items);
  4669. tor_free(addrport);
  4670. tor_free(transport_name);
  4671. tor_free(fingerprint);
  4672. return r;
  4673. }
  4674. /** Read the contents of a ClientTransportPlugin line from
  4675. * <b>line</b>. Return 0 if the line is well-formed, and -1 if it
  4676. * isn't.
  4677. *
  4678. * If <b>validate_only</b> is 0, and the line is well-formed:
  4679. * - If it's an external proxy line, add the transport described in the line to
  4680. * our internal transport list.
  4681. * - If it's a managed proxy line, launch the managed proxy. */
  4682. static int
  4683. parse_client_transport_line(const char *line, int validate_only)
  4684. {
  4685. smartlist_t *items = NULL;
  4686. int r;
  4687. char *field2=NULL;
  4688. const char *transports=NULL;
  4689. smartlist_t *transport_list=NULL;
  4690. char *addrport=NULL;
  4691. tor_addr_t addr;
  4692. uint16_t port = 0;
  4693. int socks_ver=PROXY_NONE;
  4694. /* managed proxy options */
  4695. int is_managed=0;
  4696. char **proxy_argv=NULL;
  4697. char **tmp=NULL;
  4698. int proxy_argc,i;
  4699. int line_length;
  4700. items = smartlist_new();
  4701. smartlist_split_string(items, line, NULL,
  4702. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
  4703. line_length = smartlist_len(items);
  4704. if (line_length < 3) {
  4705. log_warn(LD_CONFIG, "Too few arguments on ClientTransportPlugin line.");
  4706. goto err;
  4707. }
  4708. /* Get the first line element, split it to commas into
  4709. transport_list (in case it's multiple transports) and validate
  4710. the transport names. */
  4711. transports = smartlist_get(items, 0);
  4712. transport_list = smartlist_new();
  4713. smartlist_split_string(transport_list, transports, ",",
  4714. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  4715. SMARTLIST_FOREACH_BEGIN(transport_list, const char *, transport_name) {
  4716. if (!string_is_C_identifier(transport_name)) {
  4717. log_warn(LD_CONFIG, "Transport name is not a C identifier (%s).",
  4718. transport_name);
  4719. goto err;
  4720. }
  4721. } SMARTLIST_FOREACH_END(transport_name);
  4722. /* field2 is either a SOCKS version or "exec" */
  4723. field2 = smartlist_get(items, 1);
  4724. if (!strcmp(field2,"socks4")) {
  4725. socks_ver = PROXY_SOCKS4;
  4726. } else if (!strcmp(field2,"socks5")) {
  4727. socks_ver = PROXY_SOCKS5;
  4728. } else if (!strcmp(field2,"exec")) {
  4729. is_managed=1;
  4730. } else {
  4731. log_warn(LD_CONFIG, "Strange ClientTransportPlugin field '%s'.",
  4732. field2);
  4733. goto err;
  4734. }
  4735. if (is_managed) { /* managed */
  4736. if (!validate_only) { /* if we are not just validating, use the
  4737. rest of the line as the argv of the proxy
  4738. to be launched */
  4739. proxy_argc = line_length-2;
  4740. tor_assert(proxy_argc > 0);
  4741. proxy_argv = tor_malloc_zero(sizeof(char*)*(proxy_argc+1));
  4742. tmp = proxy_argv;
  4743. for (i=0;i<proxy_argc;i++) { /* store arguments */
  4744. *tmp++ = smartlist_get(items, 2);
  4745. smartlist_del_keeporder(items, 2);
  4746. }
  4747. *tmp = NULL; /*terminated with NULL, just like execve() likes it*/
  4748. /* kickstart the thing */
  4749. pt_kickstart_client_proxy(transport_list, proxy_argv);
  4750. }
  4751. } else { /* external */
  4752. if (smartlist_len(transport_list) != 1) {
  4753. log_warn(LD_CONFIG, "You can't have an external proxy with "
  4754. "more than one transports.");
  4755. goto err;
  4756. }
  4757. addrport = smartlist_get(items, 2);
  4758. if (tor_addr_port_lookup(addrport, &addr, &port)<0) {
  4759. log_warn(LD_CONFIG, "Error parsing transport "
  4760. "address '%s'", addrport);
  4761. goto err;
  4762. }
  4763. if (!port) {
  4764. log_warn(LD_CONFIG,
  4765. "Transport address '%s' has no port.", addrport);
  4766. goto err;
  4767. }
  4768. if (!validate_only) {
  4769. transport_add_from_config(&addr, port, smartlist_get(transport_list, 0),
  4770. socks_ver);
  4771. log_info(LD_DIR, "Transport '%s' found at %s:%d",
  4772. transports, fmt_addr(&addr), (int)port);
  4773. }
  4774. }
  4775. r = 0;
  4776. goto done;
  4777. err:
  4778. r = -1;
  4779. done:
  4780. SMARTLIST_FOREACH(items, char*, s, tor_free(s));
  4781. smartlist_free(items);
  4782. if (transport_list) {
  4783. SMARTLIST_FOREACH(transport_list, char*, s, tor_free(s));
  4784. smartlist_free(transport_list);
  4785. }
  4786. return r;
  4787. }
  4788. /** Read the contents of a ServerTransportPlugin line from
  4789. * <b>line</b>. Return 0 if the line is well-formed, and -1 if it
  4790. * isn't.
  4791. * If <b>validate_only</b> is 0, the line is well-formed, and it's a
  4792. * managed proxy line, launch the managed proxy. */
  4793. static int
  4794. parse_server_transport_line(const char *line, int validate_only)
  4795. {
  4796. smartlist_t *items = NULL;
  4797. int r;
  4798. const char *transports=NULL;
  4799. smartlist_t *transport_list=NULL;
  4800. char *type=NULL;
  4801. char *addrport=NULL;
  4802. tor_addr_t addr;
  4803. uint16_t port = 0;
  4804. /* managed proxy options */
  4805. int is_managed=0;
  4806. char **proxy_argv=NULL;
  4807. char **tmp=NULL;
  4808. int proxy_argc,i;
  4809. int line_length;
  4810. items = smartlist_new();
  4811. smartlist_split_string(items, line, NULL,
  4812. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
  4813. line_length = smartlist_len(items);
  4814. if (line_length < 3) {
  4815. log_warn(LD_CONFIG, "Too few arguments on ServerTransportPlugin line.");
  4816. goto err;
  4817. }
  4818. /* Get the first line element, split it to commas into
  4819. transport_list (in case it's multiple transports) and validate
  4820. the transport names. */
  4821. transports = smartlist_get(items, 0);
  4822. transport_list = smartlist_new();
  4823. smartlist_split_string(transport_list, transports, ",",
  4824. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  4825. SMARTLIST_FOREACH_BEGIN(transport_list, const char *, transport_name) {
  4826. if (!string_is_C_identifier(transport_name)) {
  4827. log_warn(LD_CONFIG, "Transport name is not a C identifier (%s).",
  4828. transport_name);
  4829. goto err;
  4830. }
  4831. } SMARTLIST_FOREACH_END(transport_name);
  4832. type = smartlist_get(items, 1);
  4833. if (!strcmp(type, "exec")) {
  4834. is_managed=1;
  4835. } else if (!strcmp(type, "proxy")) {
  4836. is_managed=0;
  4837. } else {
  4838. log_warn(LD_CONFIG, "Strange ServerTransportPlugin type '%s'", type);
  4839. goto err;
  4840. }
  4841. if (is_managed) { /* managed */
  4842. if (!validate_only) {
  4843. proxy_argc = line_length-2;
  4844. tor_assert(proxy_argc > 0);
  4845. proxy_argv = tor_malloc_zero(sizeof(char*)*(proxy_argc+1));
  4846. tmp = proxy_argv;
  4847. for (i=0;i<proxy_argc;i++) { /* store arguments */
  4848. *tmp++ = smartlist_get(items, 2);
  4849. smartlist_del_keeporder(items, 2);
  4850. }
  4851. *tmp = NULL; /*terminated with NULL, just like execve() likes it*/
  4852. /* kickstart the thing */
  4853. pt_kickstart_server_proxy(transport_list, proxy_argv);
  4854. }
  4855. } else { /* external */
  4856. if (smartlist_len(transport_list) != 1) {
  4857. log_warn(LD_CONFIG, "You can't have an external proxy with "
  4858. "more than one transports.");
  4859. goto err;
  4860. }
  4861. addrport = smartlist_get(items, 2);
  4862. if (tor_addr_port_lookup(addrport, &addr, &port)<0) {
  4863. log_warn(LD_CONFIG, "Error parsing transport "
  4864. "address '%s'", addrport);
  4865. goto err;
  4866. }
  4867. if (!port) {
  4868. log_warn(LD_CONFIG,
  4869. "Transport address '%s' has no port.", addrport);
  4870. goto err;
  4871. }
  4872. if (!validate_only) {
  4873. log_info(LD_DIR, "Server transport '%s' at %s:%d.",
  4874. transports, fmt_addr(&addr), (int)port);
  4875. }
  4876. }
  4877. r = 0;
  4878. goto done;
  4879. err:
  4880. r = -1;
  4881. done:
  4882. SMARTLIST_FOREACH(items, char*, s, tor_free(s));
  4883. smartlist_free(items);
  4884. if (transport_list) {
  4885. SMARTLIST_FOREACH(transport_list, char*, s, tor_free(s));
  4886. smartlist_free(transport_list);
  4887. }
  4888. return r;
  4889. }
  4890. /** Read the contents of a DirServer line from <b>line</b>. If
  4891. * <b>validate_only</b> is 0, and the line is well-formed, and it
  4892. * shares any bits with <b>required_type</b> or <b>required_type</b>
  4893. * is 0, then add the dirserver described in the line (minus whatever
  4894. * bits it's missing) as a valid authority. Return 0 on success,
  4895. * or -1 if the line isn't well-formed or if we can't add it. */
  4896. static int
  4897. parse_dir_server_line(const char *line, dirinfo_type_t required_type,
  4898. int validate_only)
  4899. {
  4900. smartlist_t *items = NULL;
  4901. int r;
  4902. char *addrport=NULL, *address=NULL, *nickname=NULL, *fingerprint=NULL;
  4903. uint16_t dir_port = 0, or_port = 0;
  4904. char digest[DIGEST_LEN];
  4905. char v3_digest[DIGEST_LEN];
  4906. dirinfo_type_t type = V2_DIRINFO;
  4907. int is_not_hidserv_authority = 0, is_not_v2_authority = 0;
  4908. items = smartlist_new();
  4909. smartlist_split_string(items, line, NULL,
  4910. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
  4911. if (smartlist_len(items) < 1) {
  4912. log_warn(LD_CONFIG, "No arguments on DirServer line.");
  4913. goto err;
  4914. }
  4915. if (is_legal_nickname(smartlist_get(items, 0))) {
  4916. nickname = smartlist_get(items, 0);
  4917. smartlist_del_keeporder(items, 0);
  4918. }
  4919. while (smartlist_len(items)) {
  4920. char *flag = smartlist_get(items, 0);
  4921. if (TOR_ISDIGIT(flag[0]))
  4922. break;
  4923. if (!strcasecmp(flag, "v1")) {
  4924. type |= (V1_DIRINFO | HIDSERV_DIRINFO);
  4925. } else if (!strcasecmp(flag, "hs")) {
  4926. type |= HIDSERV_DIRINFO;
  4927. } else if (!strcasecmp(flag, "no-hs")) {
  4928. is_not_hidserv_authority = 1;
  4929. } else if (!strcasecmp(flag, "bridge")) {
  4930. type |= BRIDGE_DIRINFO;
  4931. } else if (!strcasecmp(flag, "no-v2")) {
  4932. is_not_v2_authority = 1;
  4933. } else if (!strcasecmpstart(flag, "orport=")) {
  4934. int ok;
  4935. char *portstring = flag + strlen("orport=");
  4936. or_port = (uint16_t) tor_parse_long(portstring, 10, 1, 65535, &ok, NULL);
  4937. if (!ok)
  4938. log_warn(LD_CONFIG, "Invalid orport '%s' on DirServer line.",
  4939. portstring);
  4940. } else if (!strcasecmpstart(flag, "v3ident=")) {
  4941. char *idstr = flag + strlen("v3ident=");
  4942. if (strlen(idstr) != HEX_DIGEST_LEN ||
  4943. base16_decode(v3_digest, DIGEST_LEN, idstr, HEX_DIGEST_LEN)<0) {
  4944. log_warn(LD_CONFIG, "Bad v3 identity digest '%s' on DirServer line",
  4945. flag);
  4946. } else {
  4947. type |= V3_DIRINFO|EXTRAINFO_DIRINFO|MICRODESC_DIRINFO;
  4948. }
  4949. } else {
  4950. log_warn(LD_CONFIG, "Unrecognized flag '%s' on DirServer line",
  4951. flag);
  4952. }
  4953. tor_free(flag);
  4954. smartlist_del_keeporder(items, 0);
  4955. }
  4956. if (is_not_hidserv_authority)
  4957. type &= ~HIDSERV_DIRINFO;
  4958. if (is_not_v2_authority)
  4959. type &= ~V2_DIRINFO;
  4960. if (smartlist_len(items) < 2) {
  4961. log_warn(LD_CONFIG, "Too few arguments to DirServer line.");
  4962. goto err;
  4963. }
  4964. addrport = smartlist_get(items, 0);
  4965. smartlist_del_keeporder(items, 0);
  4966. if (addr_port_lookup(LOG_WARN, addrport, &address, NULL, &dir_port)<0) {
  4967. log_warn(LD_CONFIG, "Error parsing DirServer address '%s'", addrport);
  4968. goto err;
  4969. }
  4970. if (!dir_port) {
  4971. log_warn(LD_CONFIG, "Missing port in DirServer address '%s'",addrport);
  4972. goto err;
  4973. }
  4974. fingerprint = smartlist_join_strings(items, "", 0, NULL);
  4975. if (strlen(fingerprint) != HEX_DIGEST_LEN) {
  4976. log_warn(LD_CONFIG, "Key digest for DirServer is wrong length %d.",
  4977. (int)strlen(fingerprint));
  4978. goto err;
  4979. }
  4980. if (!strcmp(fingerprint, "E623F7625FBE0C87820F11EC5F6D5377ED816294")) {
  4981. /* a known bad fingerprint. refuse to use it. We can remove this
  4982. * clause once Tor 0.1.2.17 is obsolete. */
  4983. log_warn(LD_CONFIG, "Dangerous dirserver line. To correct, erase your "
  4984. "torrc file (%s), or reinstall Tor and use the default torrc.",
  4985. get_torrc_fname(0));
  4986. goto err;
  4987. }
  4988. if (base16_decode(digest, DIGEST_LEN, fingerprint, HEX_DIGEST_LEN)<0) {
  4989. log_warn(LD_CONFIG, "Unable to decode DirServer key digest.");
  4990. goto err;
  4991. }
  4992. if (!validate_only && (!required_type || required_type & type)) {
  4993. if (required_type)
  4994. type &= required_type; /* pare down what we think of them as an
  4995. * authority for. */
  4996. log_debug(LD_DIR, "Trusted %d dirserver at %s:%d (%s)", (int)type,
  4997. address, (int)dir_port, (char*)smartlist_get(items,0));
  4998. if (!add_trusted_dir_server(nickname, address, dir_port, or_port,
  4999. digest, v3_digest, type))
  5000. goto err;
  5001. }
  5002. r = 0;
  5003. goto done;
  5004. err:
  5005. r = -1;
  5006. done:
  5007. SMARTLIST_FOREACH(items, char*, s, tor_free(s));
  5008. smartlist_free(items);
  5009. tor_free(addrport);
  5010. tor_free(address);
  5011. tor_free(nickname);
  5012. tor_free(fingerprint);
  5013. return r;
  5014. }
  5015. /** Free all storage held in <b>port</b> */
  5016. static void
  5017. port_cfg_free(port_cfg_t *port)
  5018. {
  5019. tor_free(port);
  5020. }
  5021. /** Warn for every port in <b>ports</b> that is on a publicly routable
  5022. * address. */
  5023. static void
  5024. warn_nonlocal_client_ports(const smartlist_t *ports, const char *portname)
  5025. {
  5026. SMARTLIST_FOREACH_BEGIN(ports, const port_cfg_t *, port) {
  5027. if (port->is_unix_addr) {
  5028. /* Unix sockets aren't accessible over a network. */
  5029. } else if (!tor_addr_is_internal(&port->addr, 1)) {
  5030. log_warn(LD_CONFIG, "You specified a public address for %sPort. "
  5031. "Other people on the Internet might find your computer and "
  5032. "use it as an open proxy. Please don't allow this unless you "
  5033. "have a good reason.", portname);
  5034. } else if (!tor_addr_is_loopback(&port->addr)) {
  5035. log_notice(LD_CONFIG, "You configured a non-loopback address for "
  5036. "%sPort. This allows everybody on your local network to use "
  5037. "your machine as a proxy. Make sure this is what you wanted.",
  5038. portname);
  5039. }
  5040. } SMARTLIST_FOREACH_END(port);
  5041. }
  5042. /** Given a list of port_cfg_t in <b>ports</b>, warn any controller port there
  5043. * is listening on any non-loopback address. If <b>forbid</b> is true,
  5044. * then emit a stronger warning and remove the port from the list.
  5045. */
  5046. static void
  5047. warn_nonlocal_controller_ports(smartlist_t *ports, unsigned forbid)
  5048. {
  5049. int warned = 0;
  5050. SMARTLIST_FOREACH_BEGIN(ports, port_cfg_t *, port) {
  5051. if (port->type != CONN_TYPE_CONTROL_LISTENER)
  5052. continue;
  5053. if (port->is_unix_addr)
  5054. continue;
  5055. if (!tor_addr_is_loopback(&port->addr)) {
  5056. if (forbid) {
  5057. if (!warned)
  5058. log_warn(LD_CONFIG,
  5059. "You have a ControlPort set to accept "
  5060. "unauthenticated connections from a non-local address. "
  5061. "This means that programs not running on your computer "
  5062. "can reconfigure your Tor, without even having to guess a "
  5063. "password. That's so bad that I'm closing your ControlPort "
  5064. "for you. If you need to control your Tor remotely, try "
  5065. "enabling authentication and using a tool like stunnel or "
  5066. "ssh to encrypt remote access.");
  5067. warned = 1;
  5068. port_cfg_free(port);
  5069. SMARTLIST_DEL_CURRENT(ports, port);
  5070. } else {
  5071. log_warn(LD_CONFIG, "You have a ControlPort set to accept "
  5072. "connections from a non-local address. This means that "
  5073. "programs not running on your computer can reconfigure your "
  5074. "Tor. That's pretty bad, since the controller "
  5075. "protocol isn't encrypted! Maybe you should just listen on "
  5076. "127.0.0.1 and use a tool like stunnel or ssh to encrypt "
  5077. "remote connections to your control port.");
  5078. return; /* No point in checking the rest */
  5079. }
  5080. }
  5081. } SMARTLIST_FOREACH_END(port);
  5082. }
  5083. #define CL_PORT_NO_OPTIONS (1u<<0)
  5084. #define CL_PORT_WARN_NONLOCAL (1u<<1)
  5085. #define CL_PORT_ALLOW_EXTRA_LISTENADDR (1u<<2)
  5086. #define CL_PORT_SERVER_OPTIONS (1u<<3)
  5087. #define CL_PORT_FORBID_NONLOCAL (1u<<4)
  5088. /**
  5089. * Parse port configuration for a single port type.
  5090. *
  5091. * Read entries of the "FooPort" type from the list <b>ports</b>, and
  5092. * entries of the "FooListenAddress" type from the list
  5093. * <b>listenaddrs</b>. Two syntaxes are supported: a legacy syntax
  5094. * where FooPort is at most a single entry containing a port number and
  5095. * where FooListenAddress has any number of address:port combinations;
  5096. * and a new syntax where there are no FooListenAddress entries and
  5097. * where FooPort can have any number of entries of the format
  5098. * "[Address:][Port] IsolationOptions".
  5099. *
  5100. * In log messages, describe the port type as <b>portname</b>.
  5101. *
  5102. * If no address is specified, default to <b>defaultaddr</b>. If no
  5103. * FooPort is given, default to defaultport (if 0, there is no default).
  5104. *
  5105. * If CL_PORT_NO_OPTIONS is set in <b>flags</b>, do not allow stream
  5106. * isolation options in the FooPort entries.
  5107. *
  5108. * If CL_PORT_WARN_NONLOCAL is set in <b>flags</b>, warn if any of the
  5109. * ports are not on a local address. If CL_PORT_FORBID_NONLOCAL is set,
  5110. * this is a contrl port with no password set: don't even allow it.
  5111. *
  5112. * Unless CL_PORT_ALLOW_EXTRA_LISTENADDR is set in <b>flags</b>, warn
  5113. * if FooListenAddress is set but FooPort is 0.
  5114. *
  5115. * If CL_PORT_SERVER_OPTIONS is set in <b>flags</b>, do not allow stream
  5116. * isolation options in the FooPort entries; instead allow the
  5117. * server-port option set.
  5118. *
  5119. * On success, if <b>out</b> is given, add a new port_cfg_t entry to
  5120. * <b>out</b> for every port that the client should listen on. Return 0
  5121. * on success, -1 on failure.
  5122. */
  5123. static int
  5124. parse_port_config(smartlist_t *out,
  5125. const config_line_t *ports,
  5126. const config_line_t *listenaddrs,
  5127. const char *portname,
  5128. int listener_type,
  5129. const char *defaultaddr,
  5130. int defaultport,
  5131. unsigned flags)
  5132. {
  5133. smartlist_t *elts;
  5134. int retval = -1;
  5135. const unsigned is_control = (listener_type == CONN_TYPE_CONTROL_LISTENER);
  5136. const unsigned allow_no_options = flags & CL_PORT_NO_OPTIONS;
  5137. const unsigned use_server_options = flags & CL_PORT_SERVER_OPTIONS;
  5138. const unsigned warn_nonlocal = flags & CL_PORT_WARN_NONLOCAL;
  5139. const unsigned forbid_nonlocal = flags & CL_PORT_FORBID_NONLOCAL;
  5140. const unsigned allow_spurious_listenaddr =
  5141. flags & CL_PORT_ALLOW_EXTRA_LISTENADDR;
  5142. int got_zero_port=0, got_nonzero_port=0;
  5143. /* FooListenAddress is deprecated; let's make it work like it used to work,
  5144. * though. */
  5145. if (listenaddrs) {
  5146. int mainport = defaultport;
  5147. if (ports && ports->next) {
  5148. log_warn(LD_CONFIG, "%sListenAddress can't be used when there are "
  5149. "multiple %sPort lines", portname, portname);
  5150. return -1;
  5151. } else if (ports) {
  5152. if (!strcmp(ports->value, "auto")) {
  5153. mainport = CFG_AUTO_PORT;
  5154. } else {
  5155. int ok;
  5156. mainport = (int)tor_parse_long(ports->value, 10, 0, 65535, &ok, NULL);
  5157. if (!ok) {
  5158. log_warn(LD_CONFIG, "%sListenAddress can only be used with a single "
  5159. "%sPort with value \"auto\" or 1-65535 and no options set.",
  5160. portname, portname);
  5161. return -1;
  5162. }
  5163. }
  5164. }
  5165. if (mainport == 0) {
  5166. if (allow_spurious_listenaddr)
  5167. return 1; /*DOCDOC*/
  5168. log_warn(LD_CONFIG, "%sPort must be defined if %sListenAddress is used",
  5169. portname, portname);
  5170. return -1;
  5171. }
  5172. if (use_server_options && out) {
  5173. /* Add a no_listen port. */
  5174. port_cfg_t *cfg = tor_malloc_zero(sizeof(port_cfg_t));
  5175. cfg->type = listener_type;
  5176. cfg->port = mainport;
  5177. tor_addr_make_unspec(&cfg->addr); /* Server ports default to 0.0.0.0 */
  5178. cfg->no_listen = 1;
  5179. cfg->ipv4_only = 1;
  5180. smartlist_add(out, cfg);
  5181. }
  5182. for (; listenaddrs; listenaddrs = listenaddrs->next) {
  5183. tor_addr_t addr;
  5184. uint16_t port = 0;
  5185. if (tor_addr_port_lookup(listenaddrs->value, &addr, &port) < 0) {
  5186. log_warn(LD_CONFIG, "Unable to parse %sListenAddress '%s'",
  5187. portname, listenaddrs->value);
  5188. return -1;
  5189. }
  5190. if (out) {
  5191. port_cfg_t *cfg = tor_malloc_zero(sizeof(port_cfg_t));
  5192. cfg->type = listener_type;
  5193. cfg->port = port ? port : mainport;
  5194. tor_addr_copy(&cfg->addr, &addr);
  5195. cfg->session_group = SESSION_GROUP_UNSET;
  5196. cfg->isolation_flags = ISO_DEFAULT;
  5197. cfg->no_advertise = 1;
  5198. smartlist_add(out, cfg);
  5199. }
  5200. }
  5201. if (warn_nonlocal && out) {
  5202. if (is_control)
  5203. warn_nonlocal_controller_ports(out, forbid_nonlocal);
  5204. else
  5205. warn_nonlocal_client_ports(out, portname);
  5206. }
  5207. return 0;
  5208. } /* end if (listenaddrs) */
  5209. /* No ListenAddress lines. If there's no FooPort, then maybe make a default
  5210. * one. */
  5211. if (! ports) {
  5212. if (defaultport && out) {
  5213. port_cfg_t *cfg = tor_malloc_zero(sizeof(port_cfg_t));
  5214. cfg->type = listener_type;
  5215. cfg->port = defaultport;
  5216. tor_addr_parse(&cfg->addr, defaultaddr);
  5217. cfg->session_group = SESSION_GROUP_UNSET;
  5218. cfg->isolation_flags = ISO_DEFAULT;
  5219. smartlist_add(out, cfg);
  5220. }
  5221. return 0;
  5222. }
  5223. /* At last we can actually parse the FooPort lines. The syntax is:
  5224. * [Addr:](Port|auto) [Options].*/
  5225. elts = smartlist_new();
  5226. for (; ports; ports = ports->next) {
  5227. tor_addr_t addr;
  5228. int port;
  5229. int sessiongroup = SESSION_GROUP_UNSET;
  5230. unsigned isolation = ISO_DEFAULT;
  5231. char *addrport;
  5232. uint16_t ptmp=0;
  5233. int ok;
  5234. int no_listen = 0, no_advertise = 0, all_addrs = 0,
  5235. ipv4_only = 0, ipv6_only = 0;
  5236. smartlist_split_string(elts, ports->value, NULL,
  5237. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  5238. if (smartlist_len(elts) == 0) {
  5239. log_warn(LD_CONFIG, "Invalid %sPort line with no value", portname);
  5240. goto err;
  5241. }
  5242. if (allow_no_options && smartlist_len(elts) > 1) {
  5243. log_warn(LD_CONFIG, "Too many options on %sPort line", portname);
  5244. goto err;
  5245. }
  5246. /* Now parse the addr/port value */
  5247. addrport = smartlist_get(elts, 0);
  5248. if (!strcmp(addrport, "auto")) {
  5249. port = CFG_AUTO_PORT;
  5250. tor_addr_parse(&addr, defaultaddr);
  5251. } else if (!strcasecmpend(addrport, ":auto")) {
  5252. char *addrtmp = tor_strndup(addrport, strlen(addrport)-5);
  5253. port = CFG_AUTO_PORT;
  5254. if (tor_addr_port_lookup(addrtmp, &addr, &ptmp)<0 || ptmp) {
  5255. log_warn(LD_CONFIG, "Invalid address '%s' for %sPort",
  5256. escaped(addrport), portname);
  5257. tor_free(addrtmp);
  5258. goto err;
  5259. }
  5260. } else {
  5261. /* Try parsing integer port before address, because, who knows?
  5262. "9050" might be a valid address. */
  5263. port = (int) tor_parse_long(addrport, 10, 0, 65535, &ok, NULL);
  5264. if (ok) {
  5265. tor_addr_parse(&addr, defaultaddr);
  5266. } else if (tor_addr_port_lookup(addrport, &addr, &ptmp) == 0) {
  5267. if (ptmp == 0) {
  5268. log_warn(LD_CONFIG, "%sPort line has address but no port", portname);
  5269. goto err;
  5270. }
  5271. port = ptmp;
  5272. } else {
  5273. log_warn(LD_CONFIG, "Couldn't parse address '%s' for %sPort",
  5274. escaped(addrport), portname);
  5275. goto err;
  5276. }
  5277. }
  5278. /* Now parse the rest of the options, if any. */
  5279. if (use_server_options) {
  5280. /* This is a server port; parse advertising options */
  5281. SMARTLIST_FOREACH_BEGIN(elts, char *, elt) {
  5282. if (elt_sl_idx == 0)
  5283. continue; /* Skip addr:port */
  5284. if (!strcasecmp(elt, "NoAdvertise")) {
  5285. no_advertise = 1;
  5286. } else if (!strcasecmp(elt, "NoListen")) {
  5287. no_listen = 1;
  5288. #if 0
  5289. /* not implemented yet. */
  5290. } else if (!strcasecmp(elt, "AllAddrs")) {
  5291. all_addrs = 1;
  5292. #endif
  5293. } else if (!strcasecmp(elt, "IPv4Only")) {
  5294. ipv4_only = 1;
  5295. } else if (!strcasecmp(elt, "IPv6Only")) {
  5296. ipv6_only = 1;
  5297. } else {
  5298. log_warn(LD_CONFIG, "Unrecognized %sPort option '%s'",
  5299. portname, escaped(elt));
  5300. }
  5301. } SMARTLIST_FOREACH_END(elt);
  5302. if (no_advertise && no_listen) {
  5303. log_warn(LD_CONFIG, "Tried to set both NoListen and NoAdvertise "
  5304. "on %sPort line '%s'",
  5305. portname, escaped(ports->value));
  5306. goto err;
  5307. }
  5308. if (ipv4_only && ipv6_only) {
  5309. log_warn(LD_CONFIG, "Tried to set both IPv4Only and IPv6Only "
  5310. "on %sPort line '%s'",
  5311. portname, escaped(ports->value));
  5312. goto err;
  5313. }
  5314. if (ipv4_only && tor_addr_family(&addr) == AF_INET6) {
  5315. log_warn(LD_CONFIG, "Could not interpret %sPort address as IPv6",
  5316. portname);
  5317. goto err;
  5318. }
  5319. if (ipv6_only && tor_addr_family(&addr) == AF_INET) {
  5320. log_warn(LD_CONFIG, "Could not interpret %sPort address as IPv4",
  5321. portname);
  5322. goto err;
  5323. }
  5324. } else {
  5325. /* This is a client port; parse isolation options */
  5326. SMARTLIST_FOREACH_BEGIN(elts, char *, elt) {
  5327. int no = 0, isoflag = 0;
  5328. const char *elt_orig = elt;
  5329. if (elt_sl_idx == 0)
  5330. continue; /* Skip addr:port */
  5331. if (!strcasecmpstart(elt, "SessionGroup=")) {
  5332. int group = (int)tor_parse_long(elt+strlen("SessionGroup="),
  5333. 10, 0, INT_MAX, &ok, NULL);
  5334. if (!ok) {
  5335. log_warn(LD_CONFIG, "Invalid %sPort option '%s'",
  5336. portname, escaped(elt));
  5337. goto err;
  5338. }
  5339. if (sessiongroup >= 0) {
  5340. log_warn(LD_CONFIG, "Multiple SessionGroup options on %sPort",
  5341. portname);
  5342. goto err;
  5343. }
  5344. sessiongroup = group;
  5345. continue;
  5346. }
  5347. if (!strcasecmpstart(elt, "No")) {
  5348. no = 1;
  5349. elt += 2;
  5350. }
  5351. if (!strcasecmpend(elt, "s"))
  5352. elt[strlen(elt)-1] = '\0'; /* kill plurals. */
  5353. if (!strcasecmp(elt, "IsolateDestPort")) {
  5354. isoflag = ISO_DESTPORT;
  5355. } else if (!strcasecmp(elt, "IsolateDestAddr")) {
  5356. isoflag = ISO_DESTADDR;
  5357. } else if (!strcasecmp(elt, "IsolateSOCKSAuth")) {
  5358. isoflag = ISO_SOCKSAUTH;
  5359. } else if (!strcasecmp(elt, "IsolateClientProtocol")) {
  5360. isoflag = ISO_CLIENTPROTO;
  5361. } else if (!strcasecmp(elt, "IsolateClientAddr")) {
  5362. isoflag = ISO_CLIENTADDR;
  5363. } else {
  5364. log_warn(LD_CONFIG, "Unrecognized %sPort option '%s'",
  5365. portname, escaped(elt_orig));
  5366. }
  5367. if (no) {
  5368. isolation &= ~isoflag;
  5369. } else {
  5370. isolation |= isoflag;
  5371. }
  5372. } SMARTLIST_FOREACH_END(elt);
  5373. }
  5374. if (port)
  5375. got_nonzero_port = 1;
  5376. else
  5377. got_zero_port = 1;
  5378. if (out && port) {
  5379. port_cfg_t *cfg = tor_malloc_zero(sizeof(port_cfg_t));
  5380. tor_addr_copy(&cfg->addr, &addr);
  5381. cfg->port = port;
  5382. cfg->type = listener_type;
  5383. cfg->isolation_flags = isolation;
  5384. cfg->session_group = sessiongroup;
  5385. cfg->no_advertise = no_advertise;
  5386. cfg->no_listen = no_listen;
  5387. cfg->all_addrs = all_addrs;
  5388. cfg->ipv4_only = ipv4_only;
  5389. cfg->ipv6_only = ipv6_only;
  5390. smartlist_add(out, cfg);
  5391. }
  5392. SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
  5393. smartlist_clear(elts);
  5394. }
  5395. if (warn_nonlocal && out) {
  5396. if (is_control)
  5397. warn_nonlocal_controller_ports(out, forbid_nonlocal);
  5398. else
  5399. warn_nonlocal_client_ports(out, portname);
  5400. }
  5401. if (got_zero_port && got_nonzero_port) {
  5402. log_warn(LD_CONFIG, "You specified a nonzero %sPort along with '%sPort 0' "
  5403. "in the same configuration. Did you mean to disable %sPort or "
  5404. "not?", portname, portname, portname);
  5405. goto err;
  5406. }
  5407. retval = 0;
  5408. err:
  5409. SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
  5410. smartlist_free(elts);
  5411. return retval;
  5412. }
  5413. /** Parse a list of config_line_t for an AF_UNIX unix socket listener option
  5414. * from <b>cfg</b> and add them to <b>out</b>. No fancy options are
  5415. * supported: the line contains nothing but the path to the AF_UNIX socket. */
  5416. static int
  5417. parse_unix_socket_config(smartlist_t *out, const config_line_t *cfg,
  5418. int listener_type)
  5419. {
  5420. if (!out)
  5421. return 0;
  5422. for ( ; cfg; cfg = cfg->next) {
  5423. size_t len = strlen(cfg->value);
  5424. port_cfg_t *port = tor_malloc_zero(sizeof(port_cfg_t) + len + 1);
  5425. port->is_unix_addr = 1;
  5426. memcpy(port->unix_addr, cfg->value, len+1);
  5427. port->type = listener_type;
  5428. smartlist_add(out, port);
  5429. }
  5430. return 0;
  5431. }
  5432. /** Return the number of ports which are actually going to listen with type
  5433. * <b>listenertype</b>. Do not count no_listen ports. Do not count unix
  5434. * sockets. */
  5435. static int
  5436. count_real_listeners(const smartlist_t *ports, int listenertype)
  5437. {
  5438. int n = 0;
  5439. SMARTLIST_FOREACH_BEGIN(ports, port_cfg_t *, port) {
  5440. if (port->no_listen || port->is_unix_addr)
  5441. continue;
  5442. if (port->type != listenertype)
  5443. continue;
  5444. ++n;
  5445. } SMARTLIST_FOREACH_END(port);
  5446. return n;
  5447. }
  5448. /** Parse all client port types (Socks, DNS, Trans, NATD) from
  5449. * <b>options</b>. On success, set *<b>n_ports_out</b> to the number
  5450. * of ports that are listed, update the *Port_set values in
  5451. * <b>options</b>, and return 0. On failure, set *<b>msg</b> to a
  5452. * description of the problem and return -1.
  5453. *
  5454. * If <b>validate_only</b> is false, set configured_client_ports to the
  5455. * new list of ports parsed from <b>options</b>.
  5456. **/
  5457. static int
  5458. parse_ports(or_options_t *options, int validate_only,
  5459. char **msg, int *n_ports_out)
  5460. {
  5461. smartlist_t *ports;
  5462. int retval = -1;
  5463. ports = smartlist_new();
  5464. *n_ports_out = 0;
  5465. if (parse_port_config(ports,
  5466. options->SocksPort_lines, options->SocksListenAddress,
  5467. "Socks", CONN_TYPE_AP_LISTENER,
  5468. "127.0.0.1", 9050,
  5469. CL_PORT_WARN_NONLOCAL|CL_PORT_ALLOW_EXTRA_LISTENADDR) < 0) {
  5470. *msg = tor_strdup("Invalid SocksPort/SocksListenAddress configuration");
  5471. goto err;
  5472. }
  5473. if (parse_port_config(ports,
  5474. options->DNSPort_lines, options->DNSListenAddress,
  5475. "DNS", CONN_TYPE_AP_DNS_LISTENER,
  5476. "127.0.0.1", 0,
  5477. CL_PORT_WARN_NONLOCAL) < 0) {
  5478. *msg = tor_strdup("Invalid DNSPort/DNSListenAddress configuration");
  5479. goto err;
  5480. }
  5481. if (parse_port_config(ports,
  5482. options->TransPort_lines, options->TransListenAddress,
  5483. "Trans", CONN_TYPE_AP_TRANS_LISTENER,
  5484. "127.0.0.1", 0,
  5485. CL_PORT_WARN_NONLOCAL) < 0) {
  5486. *msg = tor_strdup("Invalid TransPort/TransListenAddress configuration");
  5487. goto err;
  5488. }
  5489. if (parse_port_config(ports,
  5490. options->NATDPort_lines, options->NATDListenAddress,
  5491. "NATD", CONN_TYPE_AP_NATD_LISTENER,
  5492. "127.0.0.1", 0,
  5493. CL_PORT_WARN_NONLOCAL) < 0) {
  5494. *msg = tor_strdup("Invalid NatdPort/NatdListenAddress configuration");
  5495. goto err;
  5496. }
  5497. {
  5498. unsigned control_port_flags = CL_PORT_NO_OPTIONS | CL_PORT_WARN_NONLOCAL;
  5499. const int any_passwords = (options->HashedControlPassword ||
  5500. options->HashedControlSessionPassword ||
  5501. options->CookieAuthentication);
  5502. if (! any_passwords)
  5503. control_port_flags |= CL_PORT_FORBID_NONLOCAL;
  5504. if (parse_port_config(ports,
  5505. options->ControlPort_lines,
  5506. options->ControlListenAddress,
  5507. "Control", CONN_TYPE_CONTROL_LISTENER,
  5508. "127.0.0.1", 0,
  5509. control_port_flags) < 0) {
  5510. *msg = tor_strdup("Invalid ControlPort/ControlListenAddress "
  5511. "configuration");
  5512. goto err;
  5513. }
  5514. if (parse_unix_socket_config(ports,
  5515. options->ControlSocket,
  5516. CONN_TYPE_CONTROL_LISTENER) < 0) {
  5517. *msg = tor_strdup("Invalid ControlSocket configuration");
  5518. goto err;
  5519. }
  5520. }
  5521. if (! options->ClientOnly) {
  5522. if (parse_port_config(ports,
  5523. options->ORPort_lines, options->ORListenAddress,
  5524. "OR", CONN_TYPE_OR_LISTENER,
  5525. "0.0.0.0", 0,
  5526. CL_PORT_SERVER_OPTIONS) < 0) {
  5527. *msg = tor_strdup("Invalid ORPort/ORListenAddress configuration");
  5528. goto err;
  5529. }
  5530. if (parse_port_config(ports,
  5531. options->DirPort_lines, options->DirListenAddress,
  5532. "Dir", CONN_TYPE_DIR_LISTENER,
  5533. "0.0.0.0", 0,
  5534. CL_PORT_SERVER_OPTIONS) < 0) {
  5535. *msg = tor_strdup("Invalid DirPort/DirListenAddress configuration");
  5536. goto err;
  5537. }
  5538. }
  5539. if (check_server_ports(ports, options) < 0) {
  5540. *msg = tor_strdup("Misconfigured server ports");
  5541. goto err;
  5542. }
  5543. *n_ports_out = smartlist_len(ports);
  5544. retval = 0;
  5545. /* Update the *Port_set options. The !! here is to force a boolean out of
  5546. an integer. */
  5547. options->ORPort_set =
  5548. !! count_real_listeners(ports, CONN_TYPE_OR_LISTENER);
  5549. options->SocksPort_set =
  5550. !! count_real_listeners(ports, CONN_TYPE_AP_LISTENER);
  5551. options->TransPort_set =
  5552. !! count_real_listeners(ports, CONN_TYPE_AP_TRANS_LISTENER);
  5553. options->NATDPort_set =
  5554. !! count_real_listeners(ports, CONN_TYPE_AP_NATD_LISTENER);
  5555. options->ControlPort_set =
  5556. !! count_real_listeners(ports, CONN_TYPE_CONTROL_LISTENER);
  5557. options->DirPort_set =
  5558. !! count_real_listeners(ports, CONN_TYPE_DIR_LISTENER);
  5559. options->DNSPort_set =
  5560. !! count_real_listeners(ports, CONN_TYPE_AP_DNS_LISTENER);
  5561. if (!validate_only) {
  5562. if (configured_ports) {
  5563. SMARTLIST_FOREACH(configured_ports,
  5564. port_cfg_t *, p, port_cfg_free(p));
  5565. smartlist_free(configured_ports);
  5566. }
  5567. configured_ports = ports;
  5568. ports = NULL; /* prevent free below. */
  5569. }
  5570. err:
  5571. if (ports) {
  5572. SMARTLIST_FOREACH(ports, port_cfg_t *, p, port_cfg_free(p));
  5573. smartlist_free(ports);
  5574. }
  5575. return retval;
  5576. }
  5577. /** Given a list of <b>port_cfg_t</b> in <b>ports</b>, check them for internal
  5578. * consistency and warn as appropriate. */
  5579. static int
  5580. check_server_ports(const smartlist_t *ports,
  5581. const or_options_t *options)
  5582. {
  5583. int n_orport_advertised = 0;
  5584. int n_orport_advertised_ipv4 = 0;
  5585. int n_orport_listeners = 0;
  5586. int n_dirport_advertised = 0;
  5587. int n_dirport_listeners = 0;
  5588. int n_low_port = 0;
  5589. int r = 0;
  5590. SMARTLIST_FOREACH_BEGIN(ports, const port_cfg_t *, port) {
  5591. if (port->type == CONN_TYPE_DIR_LISTENER) {
  5592. if (! port->no_advertise)
  5593. ++n_dirport_advertised;
  5594. if (! port->no_listen)
  5595. ++n_dirport_listeners;
  5596. } else if (port->type == CONN_TYPE_OR_LISTENER) {
  5597. if (! port->no_advertise) {
  5598. ++n_orport_advertised;
  5599. if (tor_addr_family(&port->addr) == AF_INET ||
  5600. (tor_addr_family(&port->addr) == AF_UNSPEC && !port->ipv6_only))
  5601. ++n_orport_advertised_ipv4;
  5602. }
  5603. if (! port->no_listen)
  5604. ++n_orport_listeners;
  5605. } else {
  5606. continue;
  5607. }
  5608. #ifndef _WIN32
  5609. if (!port->no_advertise && port->port < 1024)
  5610. ++n_low_port;
  5611. #endif
  5612. } SMARTLIST_FOREACH_END(port);
  5613. if (n_orport_advertised && !n_orport_listeners) {
  5614. log_warn(LD_CONFIG, "We are advertising an ORPort, but not actually "
  5615. "listening on one.");
  5616. r = -1;
  5617. }
  5618. if (n_dirport_advertised && !n_dirport_listeners) {
  5619. log_warn(LD_CONFIG, "We are advertising a DirPort, but not actually "
  5620. "listening on one.");
  5621. r = -1;
  5622. }
  5623. if (n_dirport_advertised > 1) {
  5624. log_warn(LD_CONFIG, "Can't advertise more than one DirPort.");
  5625. r = -1;
  5626. }
  5627. if (n_orport_advertised && !n_orport_advertised_ipv4 &&
  5628. !options->BridgeRelay) {
  5629. log_warn(LD_CONFIG, "Configured non-bridge only to listen on an IPv6 "
  5630. "address.");
  5631. r = -1;
  5632. }
  5633. if (n_low_port && options->AccountingMax) {
  5634. log(LOG_WARN, LD_CONFIG,
  5635. "You have set AccountingMax to use hibernation. You have also "
  5636. "chosen a low DirPort or OrPort. This combination can make Tor stop "
  5637. "working when it tries to re-attach the port after a period of "
  5638. "hibernation. Please choose a different port or turn off "
  5639. "hibernation unless you know this combination will work on your "
  5640. "platform.");
  5641. }
  5642. return r;
  5643. }
  5644. /** Return a list of port_cfg_t for client ports parsed from the
  5645. * options. */
  5646. const smartlist_t *
  5647. get_configured_ports(void)
  5648. {
  5649. if (!configured_ports)
  5650. configured_ports = smartlist_new();
  5651. return configured_ports;
  5652. }
  5653. /** Return an address:port string representation of the address
  5654. * where the first <b>listener_type</b> listener waits for
  5655. * connections. Return NULL if we couldn't find a listener. The
  5656. * string is allocated on the heap and it's the responsibility of the
  5657. * caller to free it after use.
  5658. *
  5659. * This function is meant to be used by the pluggable transport proxy
  5660. * spawning code, please make sure that it fits your purposes before
  5661. * using it. */
  5662. char *
  5663. get_first_listener_addrport_string(int listener_type)
  5664. {
  5665. static const char *ipv4_localhost = "127.0.0.1";
  5666. static const char *ipv6_localhost = "[::1]";
  5667. const char *address;
  5668. uint16_t port;
  5669. char *string = NULL;
  5670. if (!configured_ports)
  5671. return NULL;
  5672. SMARTLIST_FOREACH_BEGIN(configured_ports, const port_cfg_t *, cfg) {
  5673. if (cfg->no_listen)
  5674. continue;
  5675. if (cfg->type == listener_type &&
  5676. tor_addr_family(&cfg->addr) != AF_UNSPEC) {
  5677. /* We found the first listener of the type we are interested in! */
  5678. /* If a listener is listening on INADDR_ANY, assume that it's
  5679. also listening on 127.0.0.1, and point the transport proxy
  5680. there: */
  5681. if (tor_addr_is_null(&cfg->addr))
  5682. address = tor_addr_is_v4(&cfg->addr) ? ipv4_localhost : ipv6_localhost;
  5683. else
  5684. address = fmt_and_decorate_addr(&cfg->addr);
  5685. /* If a listener is configured with port 'auto', we are forced
  5686. to iterate all listener connections and find out in which
  5687. port it ended up listening: */
  5688. if (cfg->port == CFG_AUTO_PORT) {
  5689. port = router_get_active_listener_port_by_type(listener_type);
  5690. if (!port)
  5691. return NULL;
  5692. } else {
  5693. port = cfg->port;
  5694. }
  5695. tor_asprintf(&string, "%s:%u", address, port);
  5696. return string;
  5697. }
  5698. } SMARTLIST_FOREACH_END(cfg);
  5699. return NULL;
  5700. }
  5701. /** Return the first advertised port of type <b>listener_type</b> in
  5702. <b>address_family</b>. */
  5703. int
  5704. get_first_advertised_port_by_type_af(int listener_type, int address_family)
  5705. {
  5706. if (!configured_ports)
  5707. return 0;
  5708. SMARTLIST_FOREACH_BEGIN(configured_ports, const port_cfg_t *, cfg) {
  5709. if (cfg->type == listener_type &&
  5710. !cfg->no_advertise &&
  5711. (tor_addr_family(&cfg->addr) == address_family ||
  5712. tor_addr_family(&cfg->addr) == AF_UNSPEC)) {
  5713. if (tor_addr_family(&cfg->addr) != AF_UNSPEC ||
  5714. (address_family == AF_INET && !cfg->ipv6_only) ||
  5715. (address_family == AF_INET6 && !cfg->ipv4_only)) {
  5716. return cfg->port;
  5717. }
  5718. }
  5719. } SMARTLIST_FOREACH_END(cfg);
  5720. return 0;
  5721. }
  5722. /** Adjust the value of options->DataDirectory, or fill it in if it's
  5723. * absent. Return 0 on success, -1 on failure. */
  5724. static int
  5725. normalize_data_directory(or_options_t *options)
  5726. {
  5727. #ifdef _WIN32
  5728. char *p;
  5729. if (options->DataDirectory)
  5730. return 0; /* all set */
  5731. p = tor_malloc(MAX_PATH);
  5732. strlcpy(p,get_windows_conf_root(),MAX_PATH);
  5733. options->DataDirectory = p;
  5734. return 0;
  5735. #else
  5736. const char *d = options->DataDirectory;
  5737. if (!d)
  5738. d = "~/.tor";
  5739. if (strncmp(d,"~/",2) == 0) {
  5740. char *fn = expand_filename(d);
  5741. if (!fn) {
  5742. log_warn(LD_CONFIG,"Failed to expand filename \"%s\".", d);
  5743. return -1;
  5744. }
  5745. if (!options->DataDirectory && !strcmp(fn,"/.tor")) {
  5746. /* If our homedir is /, we probably don't want to use it. */
  5747. /* Default to LOCALSTATEDIR/tor which is probably closer to what we
  5748. * want. */
  5749. log_warn(LD_CONFIG,
  5750. "Default DataDirectory is \"~/.tor\". This expands to "
  5751. "\"%s\", which is probably not what you want. Using "
  5752. "\"%s"PATH_SEPARATOR"tor\" instead", fn, LOCALSTATEDIR);
  5753. tor_free(fn);
  5754. fn = tor_strdup(LOCALSTATEDIR PATH_SEPARATOR "tor");
  5755. }
  5756. tor_free(options->DataDirectory);
  5757. options->DataDirectory = fn;
  5758. }
  5759. return 0;
  5760. #endif
  5761. }
  5762. /** Check and normalize the value of options->DataDirectory; return 0 if it
  5763. * is sane, -1 otherwise. */
  5764. static int
  5765. validate_data_directory(or_options_t *options)
  5766. {
  5767. if (normalize_data_directory(options) < 0)
  5768. return -1;
  5769. tor_assert(options->DataDirectory);
  5770. if (strlen(options->DataDirectory) > (512-128)) {
  5771. log_warn(LD_CONFIG, "DataDirectory is too long.");
  5772. return -1;
  5773. }
  5774. return 0;
  5775. }
  5776. /** This string must remain the same forevermore. It is how we
  5777. * recognize that the torrc file doesn't need to be backed up. */
  5778. #define GENERATED_FILE_PREFIX "# This file was generated by Tor; " \
  5779. "if you edit it, comments will not be preserved"
  5780. /** This string can change; it tries to give the reader an idea
  5781. * that editing this file by hand is not a good plan. */
  5782. #define GENERATED_FILE_COMMENT "# The old torrc file was renamed " \
  5783. "to torrc.orig.1 or similar, and Tor will ignore it"
  5784. /** Save a configuration file for the configuration in <b>options</b>
  5785. * into the file <b>fname</b>. If the file already exists, and
  5786. * doesn't begin with GENERATED_FILE_PREFIX, rename it. Otherwise
  5787. * replace it. Return 0 on success, -1 on failure. */
  5788. static int
  5789. write_configuration_file(const char *fname, const or_options_t *options)
  5790. {
  5791. char *old_val=NULL, *new_val=NULL, *new_conf=NULL;
  5792. int rename_old = 0, r;
  5793. tor_assert(fname);
  5794. switch (file_status(fname)) {
  5795. case FN_FILE:
  5796. old_val = read_file_to_str(fname, 0, NULL);
  5797. if (!old_val || strcmpstart(old_val, GENERATED_FILE_PREFIX)) {
  5798. rename_old = 1;
  5799. }
  5800. tor_free(old_val);
  5801. break;
  5802. case FN_NOENT:
  5803. break;
  5804. case FN_ERROR:
  5805. case FN_DIR:
  5806. default:
  5807. log_warn(LD_CONFIG,
  5808. "Config file \"%s\" is not a file? Failing.", fname);
  5809. return -1;
  5810. }
  5811. if (!(new_conf = options_dump(options, 1))) {
  5812. log_warn(LD_BUG, "Couldn't get configuration string");
  5813. goto err;
  5814. }
  5815. tor_asprintf(&new_val, "%s\n%s\n\n%s",
  5816. GENERATED_FILE_PREFIX, GENERATED_FILE_COMMENT, new_conf);
  5817. if (rename_old) {
  5818. int i = 1;
  5819. char *fn_tmp = NULL;
  5820. while (1) {
  5821. tor_asprintf(&fn_tmp, "%s.orig.%d", fname, i);
  5822. if (file_status(fn_tmp) == FN_NOENT)
  5823. break;
  5824. tor_free(fn_tmp);
  5825. ++i;
  5826. }
  5827. log_notice(LD_CONFIG, "Renaming old configuration file to \"%s\"", fn_tmp);
  5828. if (rename(fname, fn_tmp) < 0) {
  5829. log_warn(LD_FS,
  5830. "Couldn't rename configuration file \"%s\" to \"%s\": %s",
  5831. fname, fn_tmp, strerror(errno));
  5832. tor_free(fn_tmp);
  5833. goto err;
  5834. }
  5835. tor_free(fn_tmp);
  5836. }
  5837. if (write_str_to_file(fname, new_val, 0) < 0)
  5838. goto err;
  5839. r = 0;
  5840. goto done;
  5841. err:
  5842. r = -1;
  5843. done:
  5844. tor_free(new_val);
  5845. tor_free(new_conf);
  5846. return r;
  5847. }
  5848. /**
  5849. * Save the current configuration file value to disk. Return 0 on
  5850. * success, -1 on failure.
  5851. **/
  5852. int
  5853. options_save_current(void)
  5854. {
  5855. /* This fails if we can't write to our configuration file.
  5856. *
  5857. * If we try falling back to datadirectory or something, we have a better
  5858. * chance of saving the configuration, but a better chance of doing
  5859. * something the user never expected. */
  5860. return write_configuration_file(get_torrc_fname(0), get_options());
  5861. }
  5862. /** Mapping from a unit name to a multiplier for converting that unit into a
  5863. * base unit. Used by config_parse_unit. */
  5864. struct unit_table_t {
  5865. const char *unit; /**< The name of the unit */
  5866. uint64_t multiplier; /**< How many of the base unit appear in this unit */
  5867. };
  5868. /** Table to map the names of memory units to the number of bytes they
  5869. * contain. */
  5870. static struct unit_table_t memory_units[] = {
  5871. { "", 1 },
  5872. { "b", 1<< 0 },
  5873. { "byte", 1<< 0 },
  5874. { "bytes", 1<< 0 },
  5875. { "kb", 1<<10 },
  5876. { "kbyte", 1<<10 },
  5877. { "kbytes", 1<<10 },
  5878. { "kilobyte", 1<<10 },
  5879. { "kilobytes", 1<<10 },
  5880. { "m", 1<<20 },
  5881. { "mb", 1<<20 },
  5882. { "mbyte", 1<<20 },
  5883. { "mbytes", 1<<20 },
  5884. { "megabyte", 1<<20 },
  5885. { "megabytes", 1<<20 },
  5886. { "gb", 1<<30 },
  5887. { "gbyte", 1<<30 },
  5888. { "gbytes", 1<<30 },
  5889. { "gigabyte", 1<<30 },
  5890. { "gigabytes", 1<<30 },
  5891. { "tb", U64_LITERAL(1)<<40 },
  5892. { "terabyte", U64_LITERAL(1)<<40 },
  5893. { "terabytes", U64_LITERAL(1)<<40 },
  5894. { NULL, 0 },
  5895. };
  5896. /** Table to map the names of time units to the number of seconds they
  5897. * contain. */
  5898. static struct unit_table_t time_units[] = {
  5899. { "", 1 },
  5900. { "second", 1 },
  5901. { "seconds", 1 },
  5902. { "minute", 60 },
  5903. { "minutes", 60 },
  5904. { "hour", 60*60 },
  5905. { "hours", 60*60 },
  5906. { "day", 24*60*60 },
  5907. { "days", 24*60*60 },
  5908. { "week", 7*24*60*60 },
  5909. { "weeks", 7*24*60*60 },
  5910. { NULL, 0 },
  5911. };
  5912. /** Table to map the names of time units to the number of milliseconds
  5913. * they contain. */
  5914. static struct unit_table_t time_msec_units[] = {
  5915. { "", 1 },
  5916. { "msec", 1 },
  5917. { "millisecond", 1 },
  5918. { "milliseconds", 1 },
  5919. { "second", 1000 },
  5920. { "seconds", 1000 },
  5921. { "minute", 60*1000 },
  5922. { "minutes", 60*1000 },
  5923. { "hour", 60*60*1000 },
  5924. { "hours", 60*60*1000 },
  5925. { "day", 24*60*60*1000 },
  5926. { "days", 24*60*60*1000 },
  5927. { "week", 7*24*60*60*1000 },
  5928. { "weeks", 7*24*60*60*1000 },
  5929. { NULL, 0 },
  5930. };
  5931. /** Parse a string <b>val</b> containing a number, zero or more
  5932. * spaces, and an optional unit string. If the unit appears in the
  5933. * table <b>u</b>, then multiply the number by the unit multiplier.
  5934. * On success, set *<b>ok</b> to 1 and return this product.
  5935. * Otherwise, set *<b>ok</b> to 0.
  5936. */
  5937. static uint64_t
  5938. config_parse_units(const char *val, struct unit_table_t *u, int *ok)
  5939. {
  5940. uint64_t v = 0;
  5941. double d = 0;
  5942. int use_float = 0;
  5943. char *cp;
  5944. tor_assert(ok);
  5945. v = tor_parse_uint64(val, 10, 0, UINT64_MAX, ok, &cp);
  5946. if (!*ok || (cp && *cp == '.')) {
  5947. d = tor_parse_double(val, 0, UINT64_MAX, ok, &cp);
  5948. if (!*ok)
  5949. goto done;
  5950. use_float = 1;
  5951. }
  5952. if (!cp) {
  5953. *ok = 1;
  5954. v = use_float ? DBL_TO_U64(d) : v;
  5955. goto done;
  5956. }
  5957. cp = (char*) eat_whitespace(cp);
  5958. for ( ;u->unit;++u) {
  5959. if (!strcasecmp(u->unit, cp)) {
  5960. if (use_float)
  5961. v = u->multiplier * d;
  5962. else
  5963. v *= u->multiplier;
  5964. *ok = 1;
  5965. goto done;
  5966. }
  5967. }
  5968. log_warn(LD_CONFIG, "Unknown unit '%s'.", cp);
  5969. *ok = 0;
  5970. done:
  5971. if (*ok)
  5972. return v;
  5973. else
  5974. return 0;
  5975. }
  5976. /** Parse a string in the format "number unit", where unit is a unit of
  5977. * information (byte, KB, M, etc). On success, set *<b>ok</b> to true
  5978. * and return the number of bytes specified. Otherwise, set
  5979. * *<b>ok</b> to false and return 0. */
  5980. static uint64_t
  5981. config_parse_memunit(const char *s, int *ok)
  5982. {
  5983. uint64_t u = config_parse_units(s, memory_units, ok);
  5984. return u;
  5985. }
  5986. /** Parse a string in the format "number unit", where unit is a unit of
  5987. * time in milliseconds. On success, set *<b>ok</b> to true and return
  5988. * the number of milliseconds in the provided interval. Otherwise, set
  5989. * *<b>ok</b> to 0 and return -1. */
  5990. static int
  5991. config_parse_msec_interval(const char *s, int *ok)
  5992. {
  5993. uint64_t r;
  5994. r = config_parse_units(s, time_msec_units, ok);
  5995. if (!ok)
  5996. return -1;
  5997. if (r > INT_MAX) {
  5998. log_warn(LD_CONFIG, "Msec interval '%s' is too long", s);
  5999. *ok = 0;
  6000. return -1;
  6001. }
  6002. return (int)r;
  6003. }
  6004. /** Parse a string in the format "number unit", where unit is a unit of time.
  6005. * On success, set *<b>ok</b> to true and return the number of seconds in
  6006. * the provided interval. Otherwise, set *<b>ok</b> to 0 and return -1.
  6007. */
  6008. static int
  6009. config_parse_interval(const char *s, int *ok)
  6010. {
  6011. uint64_t r;
  6012. r = config_parse_units(s, time_units, ok);
  6013. if (!ok)
  6014. return -1;
  6015. if (r > INT_MAX) {
  6016. log_warn(LD_CONFIG, "Interval '%s' is too long", s);
  6017. *ok = 0;
  6018. return -1;
  6019. }
  6020. return (int)r;
  6021. }
  6022. /** Return the number of cpus configured in <b>options</b>. If we are
  6023. * told to auto-detect the number of cpus, return the auto-detected number. */
  6024. int
  6025. get_num_cpus(const or_options_t *options)
  6026. {
  6027. if (options->NumCPUs == 0) {
  6028. int n = compute_num_cpus();
  6029. return (n >= 1) ? n : 1;
  6030. } else {
  6031. return options->NumCPUs;
  6032. }
  6033. }
  6034. /**
  6035. * Initialize the libevent library.
  6036. */
  6037. static void
  6038. init_libevent(const or_options_t *options)
  6039. {
  6040. const char *badness=NULL;
  6041. tor_libevent_cfg cfg;
  6042. tor_assert(options);
  6043. configure_libevent_logging();
  6044. /* If the kernel complains that some method (say, epoll) doesn't
  6045. * exist, we don't care about it, since libevent will cope.
  6046. */
  6047. suppress_libevent_log_msg("Function not implemented");
  6048. tor_check_libevent_header_compatibility();
  6049. memset(&cfg, 0, sizeof(cfg));
  6050. cfg.disable_iocp = options->DisableIOCP;
  6051. cfg.num_cpus = get_num_cpus(options);
  6052. cfg.msec_per_tick = options->TokenBucketRefillInterval;
  6053. tor_libevent_initialize(&cfg);
  6054. suppress_libevent_log_msg(NULL);
  6055. tor_check_libevent_version(tor_libevent_get_method(),
  6056. server_mode(get_options()),
  6057. &badness);
  6058. if (badness) {
  6059. const char *v = tor_libevent_get_version_str();
  6060. const char *m = tor_libevent_get_method();
  6061. control_event_general_status(LOG_WARN,
  6062. "BAD_LIBEVENT VERSION=%s METHOD=%s BADNESS=%s RECOVERED=NO",
  6063. v, m, badness);
  6064. }
  6065. }
  6066. /** Return the persistent state struct for this Tor. */
  6067. or_state_t *
  6068. get_or_state(void)
  6069. {
  6070. tor_assert(global_state);
  6071. return global_state;
  6072. }
  6073. /** Return a newly allocated string holding a filename relative to the data
  6074. * directory. If <b>sub1</b> is present, it is the first path component after
  6075. * the data directory. If <b>sub2</b> is also present, it is the second path
  6076. * component after the data directory. If <b>suffix</b> is present, it
  6077. * is appended to the filename.
  6078. *
  6079. * Examples:
  6080. * get_datadir_fname2_suffix("a", NULL, NULL) -> $DATADIR/a
  6081. * get_datadir_fname2_suffix("a", NULL, ".tmp") -> $DATADIR/a.tmp
  6082. * get_datadir_fname2_suffix("a", "b", ".tmp") -> $DATADIR/a/b/.tmp
  6083. * get_datadir_fname2_suffix("a", "b", NULL) -> $DATADIR/a/b
  6084. *
  6085. * Note: Consider using the get_datadir_fname* macros in or.h.
  6086. */
  6087. char *
  6088. options_get_datadir_fname2_suffix(const or_options_t *options,
  6089. const char *sub1, const char *sub2,
  6090. const char *suffix)
  6091. {
  6092. char *fname = NULL;
  6093. size_t len;
  6094. tor_assert(options);
  6095. tor_assert(options->DataDirectory);
  6096. tor_assert(sub1 || !sub2); /* If sub2 is present, sub1 must be present. */
  6097. len = strlen(options->DataDirectory);
  6098. if (sub1) {
  6099. len += strlen(sub1)+1;
  6100. if (sub2)
  6101. len += strlen(sub2)+1;
  6102. }
  6103. if (suffix)
  6104. len += strlen(suffix);
  6105. len++;
  6106. fname = tor_malloc(len);
  6107. if (sub1) {
  6108. if (sub2) {
  6109. tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s"PATH_SEPARATOR"%s",
  6110. options->DataDirectory, sub1, sub2);
  6111. } else {
  6112. tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s",
  6113. options->DataDirectory, sub1);
  6114. }
  6115. } else {
  6116. strlcpy(fname, options->DataDirectory, len);
  6117. }
  6118. if (suffix)
  6119. strlcat(fname, suffix, len);
  6120. return fname;
  6121. }
  6122. /** Return true if <b>line</b> is a valid state TransportProxy line.
  6123. * Return false otherwise. */
  6124. static int
  6125. state_transport_line_is_valid(const char *line)
  6126. {
  6127. smartlist_t *items = NULL;
  6128. char *addrport=NULL;
  6129. tor_addr_t addr;
  6130. uint16_t port = 0;
  6131. int r;
  6132. items = smartlist_new();
  6133. smartlist_split_string(items, line, NULL,
  6134. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
  6135. if (smartlist_len(items) != 2) {
  6136. log_warn(LD_CONFIG, "state: Not enough arguments in TransportProxy line.");
  6137. goto err;
  6138. }
  6139. addrport = smartlist_get(items, 1);
  6140. if (tor_addr_port_lookup(addrport, &addr, &port) < 0) {
  6141. log_warn(LD_CONFIG, "state: Could not parse addrport.");
  6142. goto err;
  6143. }
  6144. if (!port) {
  6145. log_warn(LD_CONFIG, "state: Transport line did not contain port.");
  6146. goto err;
  6147. }
  6148. r = 1;
  6149. goto done;
  6150. err:
  6151. r = 0;
  6152. done:
  6153. SMARTLIST_FOREACH(items, char*, s, tor_free(s));
  6154. smartlist_free(items);
  6155. return r;
  6156. }
  6157. /** Return 0 if all TransportProxy lines in <b>state</b> are well
  6158. * formed. Otherwise, return -1. */
  6159. static int
  6160. validate_transports_in_state(or_state_t *state)
  6161. {
  6162. int broken = 0;
  6163. config_line_t *line;
  6164. for (line = state->TransportProxies ; line ; line = line->next) {
  6165. tor_assert(!strcmp(line->key, "TransportProxy"));
  6166. if (!state_transport_line_is_valid(line->value))
  6167. broken = 1;
  6168. }
  6169. if (broken)
  6170. log_warn(LD_CONFIG, "state: State file seems to be broken.");
  6171. return 0;
  6172. }
  6173. /** Return 0 if every setting in <b>state</b> is reasonable, and a
  6174. * permissible transition from <b>old_state</b>. Else warn and return -1.
  6175. * Should have no side effects, except for normalizing the contents of
  6176. * <b>state</b>.
  6177. */
  6178. /* XXX from_setconf is here because of bug 238 */
  6179. static int
  6180. or_state_validate(or_state_t *old_state, or_state_t *state,
  6181. int from_setconf, char **msg)
  6182. {
  6183. /* We don't use these; only options do. Still, we need to match that
  6184. * signature. */
  6185. (void) from_setconf;
  6186. (void) old_state;
  6187. if (entry_guards_parse_state(state, 0, msg)<0)
  6188. return -1;
  6189. if (validate_transports_in_state(state)<0)
  6190. return -1;
  6191. return 0;
  6192. }
  6193. /** Replace the current persistent state with <b>new_state</b> */
  6194. static int
  6195. or_state_set(or_state_t *new_state)
  6196. {
  6197. char *err = NULL;
  6198. int ret = 0;
  6199. tor_assert(new_state);
  6200. config_free(&state_format, global_state);
  6201. global_state = new_state;
  6202. if (entry_guards_parse_state(global_state, 1, &err)<0) {
  6203. log_warn(LD_GENERAL,"%s",err);
  6204. tor_free(err);
  6205. ret = -1;
  6206. }
  6207. if (rep_hist_load_state(global_state, &err)<0) {
  6208. log_warn(LD_GENERAL,"Unparseable bandwidth history state: %s",err);
  6209. tor_free(err);
  6210. ret = -1;
  6211. }
  6212. if (circuit_build_times_parse_state(&circ_times, global_state) < 0) {
  6213. ret = -1;
  6214. }
  6215. return ret;
  6216. }
  6217. /**
  6218. * Save a broken state file to a backup location.
  6219. */
  6220. static void
  6221. or_state_save_broken(char *fname)
  6222. {
  6223. int i;
  6224. file_status_t status;
  6225. char *fname2 = NULL;
  6226. for (i = 0; i < 100; ++i) {
  6227. tor_asprintf(&fname2, "%s.%d", fname, i);
  6228. status = file_status(fname2);
  6229. if (status == FN_NOENT)
  6230. break;
  6231. tor_free(fname2);
  6232. }
  6233. if (i == 100) {
  6234. log_warn(LD_BUG, "Unable to parse state in \"%s\"; too many saved bad "
  6235. "state files to move aside. Discarding the old state file.",
  6236. fname);
  6237. unlink(fname);
  6238. } else {
  6239. log_warn(LD_BUG, "Unable to parse state in \"%s\". Moving it aside "
  6240. "to \"%s\". This could be a bug in Tor; please tell "
  6241. "the developers.", fname, fname2);
  6242. if (rename(fname, fname2) < 0) {
  6243. log_warn(LD_BUG, "Weirdly, I couldn't even move the state aside. The "
  6244. "OS gave an error of %s", strerror(errno));
  6245. }
  6246. }
  6247. tor_free(fname2);
  6248. }
  6249. /** Reload the persistent state from disk, generating a new state as needed.
  6250. * Return 0 on success, less than 0 on failure.
  6251. */
  6252. static int
  6253. or_state_load(void)
  6254. {
  6255. or_state_t *new_state = NULL;
  6256. char *contents = NULL, *fname;
  6257. char *errmsg = NULL;
  6258. int r = -1, badstate = 0;
  6259. fname = get_datadir_fname("state");
  6260. switch (file_status(fname)) {
  6261. case FN_FILE:
  6262. if (!(contents = read_file_to_str(fname, 0, NULL))) {
  6263. log_warn(LD_FS, "Unable to read state file \"%s\"", fname);
  6264. goto done;
  6265. }
  6266. break;
  6267. case FN_NOENT:
  6268. break;
  6269. case FN_ERROR:
  6270. case FN_DIR:
  6271. default:
  6272. log_warn(LD_GENERAL,"State file \"%s\" is not a file? Failing.", fname);
  6273. goto done;
  6274. }
  6275. new_state = tor_malloc_zero(sizeof(or_state_t));
  6276. new_state->_magic = OR_STATE_MAGIC;
  6277. config_init(&state_format, new_state);
  6278. if (contents) {
  6279. config_line_t *lines=NULL;
  6280. int assign_retval;
  6281. if (config_get_lines(contents, &lines, 0)<0)
  6282. goto done;
  6283. assign_retval = config_assign(&state_format, new_state,
  6284. lines, 0, 0, &errmsg);
  6285. config_free_lines(lines);
  6286. if (assign_retval<0)
  6287. badstate = 1;
  6288. if (errmsg) {
  6289. log_warn(LD_GENERAL, "%s", errmsg);
  6290. tor_free(errmsg);
  6291. }
  6292. }
  6293. if (!badstate && or_state_validate(NULL, new_state, 1, &errmsg) < 0)
  6294. badstate = 1;
  6295. if (errmsg) {
  6296. log_warn(LD_GENERAL, "%s", errmsg);
  6297. tor_free(errmsg);
  6298. }
  6299. if (badstate && !contents) {
  6300. log_warn(LD_BUG, "Uh oh. We couldn't even validate our own default state."
  6301. " This is a bug in Tor.");
  6302. goto done;
  6303. } else if (badstate && contents) {
  6304. or_state_save_broken(fname);
  6305. tor_free(contents);
  6306. config_free(&state_format, new_state);
  6307. new_state = tor_malloc_zero(sizeof(or_state_t));
  6308. new_state->_magic = OR_STATE_MAGIC;
  6309. config_init(&state_format, new_state);
  6310. } else if (contents) {
  6311. log_info(LD_GENERAL, "Loaded state from \"%s\"", fname);
  6312. } else {
  6313. log_info(LD_GENERAL, "Initialized state");
  6314. }
  6315. if (or_state_set(new_state) == -1) {
  6316. or_state_save_broken(fname);
  6317. }
  6318. new_state = NULL;
  6319. if (!contents) {
  6320. global_state->next_write = 0;
  6321. or_state_save(time(NULL));
  6322. }
  6323. r = 0;
  6324. done:
  6325. tor_free(fname);
  6326. tor_free(contents);
  6327. if (new_state)
  6328. config_free(&state_format, new_state);
  6329. return r;
  6330. }
  6331. /** Did the last time we tried to write the state file fail? If so, we
  6332. * should consider disabling such features as preemptive circuit generation
  6333. * to compute circuit-build-time. */
  6334. static int last_state_file_write_failed = 0;
  6335. /** Return whether the state file failed to write last time we tried. */
  6336. int
  6337. did_last_state_file_write_fail(void)
  6338. {
  6339. return last_state_file_write_failed;
  6340. }
  6341. /** If writing the state to disk fails, try again after this many seconds. */
  6342. #define STATE_WRITE_RETRY_INTERVAL 3600
  6343. /** If we're a relay, how often should we checkpoint our state file even
  6344. * if nothing else dirties it? This will checkpoint ongoing stats like
  6345. * bandwidth used, per-country user stats, etc. */
  6346. #define STATE_RELAY_CHECKPOINT_INTERVAL (12*60*60)
  6347. /** Write the persistent state to disk. Return 0 for success, <0 on failure. */
  6348. int
  6349. or_state_save(time_t now)
  6350. {
  6351. char *state, *contents;
  6352. char tbuf[ISO_TIME_LEN+1];
  6353. char *fname;
  6354. tor_assert(global_state);
  6355. if (global_state->next_write > now)
  6356. return 0;
  6357. /* Call everything else that might dirty the state even more, in order
  6358. * to avoid redundant writes. */
  6359. entry_guards_update_state(global_state);
  6360. rep_hist_update_state(global_state);
  6361. circuit_build_times_update_state(&circ_times, global_state);
  6362. if (accounting_is_enabled(get_options()))
  6363. accounting_run_housekeeping(now);
  6364. global_state->LastWritten = now;
  6365. tor_free(global_state->TorVersion);
  6366. tor_asprintf(&global_state->TorVersion, "Tor %s", get_version());
  6367. state = config_dump(&state_format, NULL, global_state, 1, 0);
  6368. format_local_iso_time(tbuf, now);
  6369. tor_asprintf(&contents,
  6370. "# Tor state file last generated on %s local time\n"
  6371. "# Other times below are in GMT\n"
  6372. "# You *do not* need to edit this file.\n\n%s",
  6373. tbuf, state);
  6374. tor_free(state);
  6375. fname = get_datadir_fname("state");
  6376. if (write_str_to_file(fname, contents, 0)<0) {
  6377. log_warn(LD_FS, "Unable to write state to file \"%s\"; "
  6378. "will try again later", fname);
  6379. last_state_file_write_failed = 1;
  6380. tor_free(fname);
  6381. tor_free(contents);
  6382. /* Try again after STATE_WRITE_RETRY_INTERVAL (or sooner, if the state
  6383. * changes sooner). */
  6384. global_state->next_write = now + STATE_WRITE_RETRY_INTERVAL;
  6385. return -1;
  6386. }
  6387. last_state_file_write_failed = 0;
  6388. log_info(LD_GENERAL, "Saved state to \"%s\"", fname);
  6389. tor_free(fname);
  6390. tor_free(contents);
  6391. if (server_mode(get_options()))
  6392. global_state->next_write = now + STATE_RELAY_CHECKPOINT_INTERVAL;
  6393. else
  6394. global_state->next_write = TIME_MAX;
  6395. return 0;
  6396. }
  6397. /** Return the config line for transport <b>transport</b> in the current state.
  6398. * Return NULL if there is no config line for <b>transport</b>. */
  6399. static config_line_t *
  6400. get_transport_in_state_by_name(const char *transport)
  6401. {
  6402. or_state_t *or_state = get_or_state();
  6403. config_line_t *line;
  6404. config_line_t *ret = NULL;
  6405. smartlist_t *items = NULL;
  6406. for (line = or_state->TransportProxies ; line ; line = line->next) {
  6407. tor_assert(!strcmp(line->key, "TransportProxy"));
  6408. items = smartlist_new();
  6409. smartlist_split_string(items, line->value, NULL,
  6410. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
  6411. if (smartlist_len(items) != 2) /* broken state */
  6412. goto done;
  6413. if (!strcmp(smartlist_get(items, 0), transport)) {
  6414. ret = line;
  6415. goto done;
  6416. }
  6417. SMARTLIST_FOREACH(items, char*, s, tor_free(s));
  6418. smartlist_free(items);
  6419. items = NULL;
  6420. }
  6421. done:
  6422. if (items) {
  6423. SMARTLIST_FOREACH(items, char*, s, tor_free(s));
  6424. smartlist_free(items);
  6425. }
  6426. return ret;
  6427. }
  6428. /** Return string containing the address:port part of the
  6429. * TransportProxy <b>line</b> for transport <b>transport</b>.
  6430. * If the line is corrupted, return NULL. */
  6431. static const char *
  6432. get_transport_bindaddr(const char *line, const char *transport)
  6433. {
  6434. char *line_tmp = NULL;
  6435. if (strlen(line) < strlen(transport) + 2) {
  6436. goto broken_state;
  6437. } else {
  6438. /* line should start with the name of the transport and a space.
  6439. (for example, "obfs2 127.0.0.1:47245") */
  6440. tor_asprintf(&line_tmp, "%s ", transport);
  6441. if (strcmpstart(line, line_tmp))
  6442. goto broken_state;
  6443. tor_free(line_tmp);
  6444. return (line+strlen(transport)+1);
  6445. }
  6446. broken_state:
  6447. tor_free(line_tmp);
  6448. return NULL;
  6449. }
  6450. /** Return a string containing the address:port that a proxy transport
  6451. * should bind on. The string is stored on the heap and must be freed
  6452. * by the caller of this function. */
  6453. char *
  6454. get_stored_bindaddr_for_server_transport(const char *transport)
  6455. {
  6456. char *default_addrport = NULL;
  6457. const char *stored_bindaddr = NULL;
  6458. config_line_t *line = get_transport_in_state_by_name(transport);
  6459. if (!line) /* Found no references in state for this transport. */
  6460. goto no_bindaddr_found;
  6461. stored_bindaddr = get_transport_bindaddr(line->value, transport);
  6462. if (stored_bindaddr) /* found stored bindaddr in state file. */
  6463. return tor_strdup(stored_bindaddr);
  6464. no_bindaddr_found:
  6465. /** If we didn't find references for this pluggable transport in the
  6466. state file, we should instruct the pluggable transport proxy to
  6467. listen on INADDR_ANY on a random ephemeral port. */
  6468. tor_asprintf(&default_addrport, "%s:%s", fmt_addr32(INADDR_ANY), "0");
  6469. return default_addrport;
  6470. }
  6471. /** Save <b>transport</b> listening on <b>addr</b>:<b>port</b> to
  6472. state */
  6473. void
  6474. save_transport_to_state(const char *transport,
  6475. const tor_addr_t *addr, uint16_t port)
  6476. {
  6477. or_state_t *state = get_or_state();
  6478. char *transport_addrport=NULL;
  6479. /** find where to write on the state */
  6480. config_line_t **next, *line;
  6481. /* see if this transport is already stored in state */
  6482. config_line_t *transport_line =
  6483. get_transport_in_state_by_name(transport);
  6484. if (transport_line) { /* if transport already exists in state... */
  6485. const char *prev_bindaddr = /* get its addrport... */
  6486. get_transport_bindaddr(transport_line->value, transport);
  6487. tor_asprintf(&transport_addrport, "%s:%d", fmt_addr(addr), (int)port);
  6488. /* if transport in state has the same address as this one, life is good */
  6489. if (!strcmp(prev_bindaddr, transport_addrport)) {
  6490. log_info(LD_CONFIG, "Transport seems to have spawned on its usual "
  6491. "address:port.");
  6492. goto done;
  6493. } else { /* if addrport in state is different than the one we got */
  6494. log_info(LD_CONFIG, "Transport seems to have spawned on different "
  6495. "address:port. Let's update the state file with the new "
  6496. "address:port");
  6497. tor_free(transport_line->value); /* free the old line */
  6498. tor_asprintf(&transport_line->value, "%s %s:%d", transport,
  6499. fmt_addr(addr),
  6500. (int) port); /* replace old addrport line with new line */
  6501. }
  6502. } else { /* never seen this one before; save it in state for next time */
  6503. log_info(LD_CONFIG, "It's the first time we see this transport. "
  6504. "Let's save its address:port");
  6505. next = &state->TransportProxies;
  6506. /* find the last TransportProxy line in the state and point 'next'
  6507. right after it */
  6508. line = state->TransportProxies;
  6509. while (line) {
  6510. next = &(line->next);
  6511. line = line->next;
  6512. }
  6513. /* allocate space for the new line and fill it in */
  6514. *next = line = tor_malloc_zero(sizeof(config_line_t));
  6515. line->key = tor_strdup("TransportProxy");
  6516. tor_asprintf(&line->value, "%s %s:%d", transport,
  6517. fmt_addr(addr), (int) port);
  6518. next = &(line->next);
  6519. }
  6520. if (!get_options()->AvoidDiskWrites)
  6521. or_state_mark_dirty(state, 0);
  6522. done:
  6523. tor_free(transport_addrport);
  6524. }
  6525. /** Given a file name check to see whether the file exists but has not been
  6526. * modified for a very long time. If so, remove it. */
  6527. void
  6528. remove_file_if_very_old(const char *fname, time_t now)
  6529. {
  6530. #define VERY_OLD_FILE_AGE (28*24*60*60)
  6531. struct stat st;
  6532. if (stat(fname, &st)==0 && st.st_mtime < now-VERY_OLD_FILE_AGE) {
  6533. char buf[ISO_TIME_LEN+1];
  6534. format_local_iso_time(buf, st.st_mtime);
  6535. log_notice(LD_GENERAL, "Obsolete file %s hasn't been modified since %s. "
  6536. "Removing it.", fname, buf);
  6537. unlink(fname);
  6538. }
  6539. }
  6540. /** Return a smartlist of ports that must be forwarded by
  6541. * tor-fw-helper. The smartlist contains the ports in a string format
  6542. * that is understandable by tor-fw-helper. */
  6543. smartlist_t *
  6544. get_list_of_ports_to_forward(void)
  6545. {
  6546. smartlist_t *ports_to_forward = smartlist_new();
  6547. int port = 0;
  6548. /** XXX TODO tor-fw-helper does not support forwarding ports to
  6549. other hosts than the local one. If the user is binding to a
  6550. different IP address, tor-fw-helper won't work. */
  6551. port = get_primary_or_port(); /* Get ORPort */
  6552. if (port)
  6553. smartlist_add_asprintf(ports_to_forward, "%d:%d", port, port);
  6554. port = get_primary_dir_port(); /* Get DirPort */
  6555. if (port)
  6556. smartlist_add_asprintf(ports_to_forward, "%d:%d", port, port);
  6557. /* Get ports of transport proxies */
  6558. smartlist_t *transport_ports = get_transport_proxy_ports();
  6559. if (transport_ports) {
  6560. smartlist_add_all(ports_to_forward, transport_ports);
  6561. smartlist_free(transport_ports);
  6562. }
  6563. if (!smartlist_len(ports_to_forward)) {
  6564. smartlist_free(ports_to_forward);
  6565. ports_to_forward = NULL;
  6566. }
  6567. return ports_to_forward;
  6568. }
  6569. /** Helper to implement GETINFO functions about configuration variables (not
  6570. * their values). Given a "config/names" question, set *<b>answer</b> to a
  6571. * new string describing the supported configuration variables and their
  6572. * types. */
  6573. int
  6574. getinfo_helper_config(control_connection_t *conn,
  6575. const char *question, char **answer,
  6576. const char **errmsg)
  6577. {
  6578. (void) conn;
  6579. (void) errmsg;
  6580. if (!strcmp(question, "config/names")) {
  6581. smartlist_t *sl = smartlist_new();
  6582. int i;
  6583. for (i = 0; _option_vars[i].name; ++i) {
  6584. const config_var_t *var = &_option_vars[i];
  6585. const char *type;
  6586. switch (var->type) {
  6587. case CONFIG_TYPE_STRING: type = "String"; break;
  6588. case CONFIG_TYPE_FILENAME: type = "Filename"; break;
  6589. case CONFIG_TYPE_UINT: type = "Integer"; break;
  6590. case CONFIG_TYPE_INT: type = "SignedInteger"; break;
  6591. case CONFIG_TYPE_PORT: type = "Port"; break;
  6592. case CONFIG_TYPE_INTERVAL: type = "TimeInterval"; break;
  6593. case CONFIG_TYPE_MSEC_INTERVAL: type = "TimeMsecInterval"; break;
  6594. case CONFIG_TYPE_MEMUNIT: type = "DataSize"; break;
  6595. case CONFIG_TYPE_DOUBLE: type = "Float"; break;
  6596. case CONFIG_TYPE_BOOL: type = "Boolean"; break;
  6597. case CONFIG_TYPE_AUTOBOOL: type = "Boolean+Auto"; break;
  6598. case CONFIG_TYPE_ISOTIME: type = "Time"; break;
  6599. case CONFIG_TYPE_ROUTERSET: type = "RouterList"; break;
  6600. case CONFIG_TYPE_CSV: type = "CommaList"; break;
  6601. case CONFIG_TYPE_LINELIST: type = "LineList"; break;
  6602. case CONFIG_TYPE_LINELIST_S: type = "Dependant"; break;
  6603. case CONFIG_TYPE_LINELIST_V: type = "Virtual"; break;
  6604. default:
  6605. case CONFIG_TYPE_OBSOLETE:
  6606. type = NULL; break;
  6607. }
  6608. if (!type)
  6609. continue;
  6610. smartlist_add_asprintf(sl, "%s %s\n",var->name,type);
  6611. }
  6612. *answer = smartlist_join_strings(sl, "", 0, NULL);
  6613. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  6614. smartlist_free(sl);
  6615. } else if (!strcmp(question, "config/defaults")) {
  6616. smartlist_t *sl = smartlist_new();
  6617. int i;
  6618. for (i = 0; _option_vars[i].name; ++i) {
  6619. const config_var_t *var = &_option_vars[i];
  6620. if (var->initvalue != NULL) {
  6621. char *val = esc_for_log(var->initvalue);
  6622. smartlist_add_asprintf(sl, "%s %s\n",var->name,val);
  6623. tor_free(val);
  6624. }
  6625. }
  6626. *answer = smartlist_join_strings(sl, "", 0, NULL);
  6627. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  6628. smartlist_free(sl);
  6629. }
  6630. return 0;
  6631. }