config.c 226 KB

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