config.c 282 KB

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