config.c 278 KB

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