config.c 243 KB

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