config.c 299 KB

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