config.c 222 KB

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