control.c 264 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898
  1. /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  2. * Copyright (c) 2007-2018, The Tor Project, Inc. */
  3. /* See LICENSE for licensing information */
  4. /**
  5. * \file control.c
  6. * \brief Implementation for Tor's control-socket interface.
  7. *
  8. * A "controller" is an external program that monitors and controls a Tor
  9. * instance via a text-based protocol. It connects to Tor via a connection
  10. * to a local socket.
  11. *
  12. * The protocol is line-driven. The controller sends commands terminated by a
  13. * CRLF. Tor sends lines that are either <em>replies</em> to what the
  14. * controller has said, or <em>events</em> that Tor sends to the controller
  15. * asynchronously based on occurrences in the Tor network model.
  16. *
  17. * See the control-spec.txt file in the torspec.git repository for full
  18. * details on protocol.
  19. *
  20. * This module generally has two kinds of entry points: those based on having
  21. * received a command on a controller socket, which are handled in
  22. * connection_control_process_inbuf(), and dispatched to individual functions
  23. * with names like control_handle_COMMANDNAME(); and those based on events
  24. * that occur elsewhere in Tor, which are handled by functions with names like
  25. * control_event_EVENTTYPE().
  26. *
  27. * Controller events are not sent immediately; rather, they are inserted into
  28. * the queued_control_events array, and flushed later from
  29. * flush_queued_events_cb(). Doing this simplifies our callgraph greatly,
  30. * by limiting the number of places in Tor that can call back into the network
  31. * stack.
  32. **/
  33. #define CONTROL_PRIVATE
  34. #include "core/or/or.h"
  35. #include "app/config/config.h"
  36. #include "app/config/confparse.h"
  37. #include "app/main/main.h"
  38. #include "core/mainloop/connection.h"
  39. #include "core/mainloop/mainloop.h"
  40. #include "core/or/channel.h"
  41. #include "core/or/channeltls.h"
  42. #include "core/or/circuitbuild.h"
  43. #include "core/or/circuitlist.h"
  44. #include "core/or/circuitstats.h"
  45. #include "core/or/circuituse.h"
  46. #include "core/or/command.h"
  47. #include "core/or/connection_edge.h"
  48. #include "core/or/connection_or.h"
  49. #include "core/or/policies.h"
  50. #include "core/or/reasons.h"
  51. #include "core/or/versions.h"
  52. #include "core/proto/proto_control0.h"
  53. #include "core/proto/proto_http.h"
  54. #include "feature/client/addressmap.h"
  55. #include "feature/client/bridges.h"
  56. #include "feature/client/dnsserv.h"
  57. #include "feature/client/entrynodes.h"
  58. #include "feature/control/control.h"
  59. #include "feature/control/fmt_serverstatus.h"
  60. #include "feature/control/getinfo_geoip.h"
  61. #include "feature/dircache/dirserv.h"
  62. #include "feature/dirclient/dirclient.h"
  63. #include "feature/dirclient/dlstatus.h"
  64. #include "feature/dircommon/directory.h"
  65. #include "feature/hibernate/hibernate.h"
  66. #include "feature/hs/hs_cache.h"
  67. #include "feature/hs/hs_common.h"
  68. #include "feature/hs/hs_control.h"
  69. #include "feature/hs_common/shared_random_client.h"
  70. #include "feature/nodelist/authcert.h"
  71. #include "feature/nodelist/dirlist.h"
  72. #include "feature/nodelist/microdesc.h"
  73. #include "feature/nodelist/networkstatus.h"
  74. #include "feature/nodelist/nodelist.h"
  75. #include "feature/nodelist/routerinfo.h"
  76. #include "feature/nodelist/routerlist.h"
  77. #include "feature/relay/router.h"
  78. #include "feature/relay/routermode.h"
  79. #include "feature/relay/selftest.h"
  80. #include "feature/rend/rendclient.h"
  81. #include "feature/rend/rendcommon.h"
  82. #include "feature/rend/rendparse.h"
  83. #include "feature/rend/rendservice.h"
  84. #include "feature/stats/geoip_stats.h"
  85. #include "feature/stats/predict_ports.h"
  86. #include "lib/container/buffers.h"
  87. #include "lib/crypt_ops/crypto_rand.h"
  88. #include "lib/crypt_ops/crypto_util.h"
  89. #include "lib/encoding/confline.h"
  90. #include "lib/evloop/compat_libevent.h"
  91. #include "feature/dircache/cached_dir_st.h"
  92. #include "feature/control/control_connection_st.h"
  93. #include "core/or/cpath_build_state_st.h"
  94. #include "core/or/entry_connection_st.h"
  95. #include "feature/nodelist/extrainfo_st.h"
  96. #include "feature/nodelist/networkstatus_st.h"
  97. #include "feature/nodelist/node_st.h"
  98. #include "core/or/or_connection_st.h"
  99. #include "core/or/or_circuit_st.h"
  100. #include "core/or/origin_circuit_st.h"
  101. #include "feature/nodelist/microdesc_st.h"
  102. #include "feature/rend/rend_authorized_client_st.h"
  103. #include "feature/rend/rend_encoded_v2_service_descriptor_st.h"
  104. #include "feature/rend/rend_service_descriptor_st.h"
  105. #include "feature/nodelist/routerinfo_st.h"
  106. #include "feature/nodelist/routerlist_st.h"
  107. #include "core/or/socks_request_st.h"
  108. #ifdef HAVE_UNISTD_H
  109. #include <unistd.h>
  110. #endif
  111. #ifdef HAVE_SYS_STAT_H
  112. #include <sys/stat.h>
  113. #endif
  114. #ifndef _WIN32
  115. #include <pwd.h>
  116. #include <sys/resource.h>
  117. #endif
  118. #include "lib/crypt_ops/crypto_s2k.h"
  119. #include "lib/evloop/procmon.h"
  120. #include "lib/evloop/compat_libevent.h"
  121. /** Yield true iff <b>s</b> is the state of a control_connection_t that has
  122. * finished authentication and is accepting commands. */
  123. #define STATE_IS_OPEN(s) ((s) == CONTROL_CONN_STATE_OPEN)
  124. /** Bitfield: The bit 1&lt;&lt;e is set if <b>any</b> open control
  125. * connection is interested in events of type <b>e</b>. We use this
  126. * so that we can decide to skip generating event messages that nobody
  127. * has interest in without having to walk over the global connection
  128. * list to find out.
  129. **/
  130. typedef uint64_t event_mask_t;
  131. /** An event mask of all the events that any controller is interested in
  132. * receiving. */
  133. static event_mask_t global_event_mask = 0;
  134. /** True iff we have disabled log messages from being sent to the controller */
  135. static int disable_log_messages = 0;
  136. /** Macro: true if any control connection is interested in events of type
  137. * <b>e</b>. */
  138. #define EVENT_IS_INTERESTING(e) \
  139. (!! (global_event_mask & EVENT_MASK_(e)))
  140. /** Macro: true if any event from the bitfield 'e' is interesting. */
  141. #define ANY_EVENT_IS_INTERESTING(e) \
  142. (!! (global_event_mask & (e)))
  143. /** If we're using cookie-type authentication, how long should our cookies be?
  144. */
  145. #define AUTHENTICATION_COOKIE_LEN 32
  146. /** If true, we've set authentication_cookie to a secret code and
  147. * stored it to disk. */
  148. static int authentication_cookie_is_set = 0;
  149. /** If authentication_cookie_is_set, a secret cookie that we've stored to disk
  150. * and which we're using to authenticate controllers. (If the controller can
  151. * read it off disk, it has permission to connect.) */
  152. static uint8_t *authentication_cookie = NULL;
  153. #define SAFECOOKIE_SERVER_TO_CONTROLLER_CONSTANT \
  154. "Tor safe cookie authentication server-to-controller hash"
  155. #define SAFECOOKIE_CONTROLLER_TO_SERVER_CONSTANT \
  156. "Tor safe cookie authentication controller-to-server hash"
  157. #define SAFECOOKIE_SERVER_NONCE_LEN DIGEST256_LEN
  158. /** The list of onion services that have been added via ADD_ONION that do not
  159. * belong to any particular control connection.
  160. */
  161. static smartlist_t *detached_onion_services = NULL;
  162. /** A sufficiently large size to record the last bootstrap phase string. */
  163. #define BOOTSTRAP_MSG_LEN 1024
  164. /** What was the last bootstrap phase message we sent? We keep track
  165. * of this so we can respond to getinfo status/bootstrap-phase queries. */
  166. static char last_sent_bootstrap_message[BOOTSTRAP_MSG_LEN];
  167. static void connection_printf_to_buf(control_connection_t *conn,
  168. const char *format, ...)
  169. CHECK_PRINTF(2,3);
  170. static void send_control_event_impl(uint16_t event,
  171. const char *format, va_list ap)
  172. CHECK_PRINTF(2,0);
  173. static int control_event_status(int type, int severity, const char *format,
  174. va_list args)
  175. CHECK_PRINTF(3,0);
  176. static void send_control_done(control_connection_t *conn);
  177. static void send_control_event(uint16_t event,
  178. const char *format, ...)
  179. CHECK_PRINTF(2,3);
  180. static int handle_control_setconf(control_connection_t *conn, uint32_t len,
  181. char *body);
  182. static int handle_control_resetconf(control_connection_t *conn, uint32_t len,
  183. char *body);
  184. static int handle_control_getconf(control_connection_t *conn, uint32_t len,
  185. const char *body);
  186. static int handle_control_loadconf(control_connection_t *conn, uint32_t len,
  187. const char *body);
  188. static int handle_control_setevents(control_connection_t *conn, uint32_t len,
  189. const char *body);
  190. static int handle_control_authenticate(control_connection_t *conn,
  191. uint32_t len,
  192. const char *body);
  193. static int handle_control_signal(control_connection_t *conn, uint32_t len,
  194. const char *body);
  195. static int handle_control_mapaddress(control_connection_t *conn, uint32_t len,
  196. const char *body);
  197. static char *list_getinfo_options(void);
  198. static int handle_control_getinfo(control_connection_t *conn, uint32_t len,
  199. const char *body);
  200. static int handle_control_extendcircuit(control_connection_t *conn,
  201. uint32_t len,
  202. const char *body);
  203. static int handle_control_setcircuitpurpose(control_connection_t *conn,
  204. uint32_t len, const char *body);
  205. static int handle_control_attachstream(control_connection_t *conn,
  206. uint32_t len,
  207. const char *body);
  208. static int handle_control_postdescriptor(control_connection_t *conn,
  209. uint32_t len,
  210. const char *body);
  211. static int handle_control_redirectstream(control_connection_t *conn,
  212. uint32_t len,
  213. const char *body);
  214. static int handle_control_closestream(control_connection_t *conn, uint32_t len,
  215. const char *body);
  216. static int handle_control_closecircuit(control_connection_t *conn,
  217. uint32_t len,
  218. const char *body);
  219. static int handle_control_resolve(control_connection_t *conn, uint32_t len,
  220. const char *body);
  221. static int handle_control_usefeature(control_connection_t *conn,
  222. uint32_t len,
  223. const char *body);
  224. static int handle_control_hsfetch(control_connection_t *conn, uint32_t len,
  225. const char *body);
  226. static int handle_control_hspost(control_connection_t *conn, uint32_t len,
  227. const char *body);
  228. static int handle_control_add_onion(control_connection_t *conn, uint32_t len,
  229. const char *body);
  230. static int handle_control_del_onion(control_connection_t *conn, uint32_t len,
  231. const char *body);
  232. static int write_stream_target_to_buf(entry_connection_t *conn, char *buf,
  233. size_t len);
  234. static void orconn_target_get_name(char *buf, size_t len,
  235. or_connection_t *conn);
  236. static int get_cached_network_liveness(void);
  237. static void set_cached_network_liveness(int liveness);
  238. static void flush_queued_events_cb(mainloop_event_t *event, void *arg);
  239. static char * download_status_to_string(const download_status_t *dl);
  240. static void control_get_bytes_rw_last_sec(uint64_t *r, uint64_t *w);
  241. /** Convert a connection_t* to an control_connection_t*; assert if the cast is
  242. * invalid. */
  243. control_connection_t *
  244. TO_CONTROL_CONN(connection_t *c)
  245. {
  246. tor_assert(c->magic == CONTROL_CONNECTION_MAGIC);
  247. return DOWNCAST(control_connection_t, c);
  248. }
  249. /** Given a control event code for a message event, return the corresponding
  250. * log severity. */
  251. static inline int
  252. event_to_log_severity(int event)
  253. {
  254. switch (event) {
  255. case EVENT_DEBUG_MSG: return LOG_DEBUG;
  256. case EVENT_INFO_MSG: return LOG_INFO;
  257. case EVENT_NOTICE_MSG: return LOG_NOTICE;
  258. case EVENT_WARN_MSG: return LOG_WARN;
  259. case EVENT_ERR_MSG: return LOG_ERR;
  260. default: return -1;
  261. }
  262. }
  263. /** Given a log severity, return the corresponding control event code. */
  264. static inline int
  265. log_severity_to_event(int severity)
  266. {
  267. switch (severity) {
  268. case LOG_DEBUG: return EVENT_DEBUG_MSG;
  269. case LOG_INFO: return EVENT_INFO_MSG;
  270. case LOG_NOTICE: return EVENT_NOTICE_MSG;
  271. case LOG_WARN: return EVENT_WARN_MSG;
  272. case LOG_ERR: return EVENT_ERR_MSG;
  273. default: return -1;
  274. }
  275. }
  276. /** Helper: clear bandwidth counters of all origin circuits. */
  277. static void
  278. clear_circ_bw_fields(void)
  279. {
  280. origin_circuit_t *ocirc;
  281. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  282. if (!CIRCUIT_IS_ORIGIN(circ))
  283. continue;
  284. ocirc = TO_ORIGIN_CIRCUIT(circ);
  285. ocirc->n_written_circ_bw = ocirc->n_read_circ_bw = 0;
  286. ocirc->n_overhead_written_circ_bw = ocirc->n_overhead_read_circ_bw = 0;
  287. ocirc->n_delivered_written_circ_bw = ocirc->n_delivered_read_circ_bw = 0;
  288. }
  289. SMARTLIST_FOREACH_END(circ);
  290. }
  291. /** Set <b>global_event_mask*</b> to the bitwise OR of each live control
  292. * connection's event_mask field. */
  293. void
  294. control_update_global_event_mask(void)
  295. {
  296. smartlist_t *conns = get_connection_array();
  297. event_mask_t old_mask, new_mask;
  298. old_mask = global_event_mask;
  299. int any_old_per_sec_events = control_any_per_second_event_enabled();
  300. global_event_mask = 0;
  301. SMARTLIST_FOREACH(conns, connection_t *, _conn,
  302. {
  303. if (_conn->type == CONN_TYPE_CONTROL &&
  304. STATE_IS_OPEN(_conn->state)) {
  305. control_connection_t *conn = TO_CONTROL_CONN(_conn);
  306. global_event_mask |= conn->event_mask;
  307. }
  308. });
  309. new_mask = global_event_mask;
  310. /* Handle the aftermath. Set up the log callback to tell us only what
  311. * we want to hear...*/
  312. control_adjust_event_log_severity();
  313. /* Macro: true if ev was false before and is true now. */
  314. #define NEWLY_ENABLED(ev) \
  315. (! (old_mask & (ev)) && (new_mask & (ev)))
  316. /* ...then, if we've started logging stream or circ bw, clear the
  317. * appropriate fields. */
  318. if (NEWLY_ENABLED(EVENT_STREAM_BANDWIDTH_USED)) {
  319. SMARTLIST_FOREACH(conns, connection_t *, conn,
  320. {
  321. if (conn->type == CONN_TYPE_AP) {
  322. edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
  323. edge_conn->n_written = edge_conn->n_read = 0;
  324. }
  325. });
  326. }
  327. if (NEWLY_ENABLED(EVENT_CIRC_BANDWIDTH_USED)) {
  328. clear_circ_bw_fields();
  329. }
  330. if (NEWLY_ENABLED(EVENT_BANDWIDTH_USED)) {
  331. uint64_t r, w;
  332. control_get_bytes_rw_last_sec(&r, &w);
  333. }
  334. if (any_old_per_sec_events != control_any_per_second_event_enabled()) {
  335. reschedule_per_second_timer();
  336. }
  337. #undef NEWLY_ENABLED
  338. }
  339. /** Adjust the log severities that result in control_event_logmsg being called
  340. * to match the severity of log messages that any controllers are interested
  341. * in. */
  342. void
  343. control_adjust_event_log_severity(void)
  344. {
  345. int i;
  346. int min_log_event=EVENT_ERR_MSG, max_log_event=EVENT_DEBUG_MSG;
  347. for (i = EVENT_DEBUG_MSG; i <= EVENT_ERR_MSG; ++i) {
  348. if (EVENT_IS_INTERESTING(i)) {
  349. min_log_event = i;
  350. break;
  351. }
  352. }
  353. for (i = EVENT_ERR_MSG; i >= EVENT_DEBUG_MSG; --i) {
  354. if (EVENT_IS_INTERESTING(i)) {
  355. max_log_event = i;
  356. break;
  357. }
  358. }
  359. if (EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL)) {
  360. if (min_log_event > EVENT_NOTICE_MSG)
  361. min_log_event = EVENT_NOTICE_MSG;
  362. if (max_log_event < EVENT_ERR_MSG)
  363. max_log_event = EVENT_ERR_MSG;
  364. }
  365. if (min_log_event <= max_log_event)
  366. change_callback_log_severity(event_to_log_severity(min_log_event),
  367. event_to_log_severity(max_log_event),
  368. control_event_logmsg);
  369. else
  370. change_callback_log_severity(LOG_ERR, LOG_ERR,
  371. control_event_logmsg);
  372. }
  373. /** Return true iff the event with code <b>c</b> is being sent to any current
  374. * control connection. This is useful if the amount of work needed to prepare
  375. * to call the appropriate control_event_...() function is high.
  376. */
  377. int
  378. control_event_is_interesting(int event)
  379. {
  380. return EVENT_IS_INTERESTING(event);
  381. }
  382. /** Return true if any event that needs to fire once a second is enabled. */
  383. int
  384. control_any_per_second_event_enabled(void)
  385. {
  386. return ANY_EVENT_IS_INTERESTING(
  387. EVENT_MASK_(EVENT_BANDWIDTH_USED) |
  388. EVENT_MASK_(EVENT_CELL_STATS) |
  389. EVENT_MASK_(EVENT_CIRC_BANDWIDTH_USED) |
  390. EVENT_MASK_(EVENT_CONN_BW) |
  391. EVENT_MASK_(EVENT_STREAM_BANDWIDTH_USED)
  392. );
  393. }
  394. /* The value of 'get_bytes_read()' the previous time that
  395. * control_get_bytes_rw_last_sec() as called. */
  396. static uint64_t stats_prev_n_read = 0;
  397. /* The value of 'get_bytes_written()' the previous time that
  398. * control_get_bytes_rw_last_sec() as called. */
  399. static uint64_t stats_prev_n_written = 0;
  400. /**
  401. * Set <b>n_read</b> and <b>n_written</b> to the total number of bytes read
  402. * and written by Tor since the last call to this function.
  403. *
  404. * Call this only from the main thread.
  405. */
  406. static void
  407. control_get_bytes_rw_last_sec(uint64_t *n_read,
  408. uint64_t *n_written)
  409. {
  410. const uint64_t stats_n_bytes_read = get_bytes_read();
  411. const uint64_t stats_n_bytes_written = get_bytes_written();
  412. *n_read = stats_n_bytes_read - stats_prev_n_read;
  413. *n_written = stats_n_bytes_written - stats_prev_n_written;
  414. stats_prev_n_read = stats_n_bytes_read;
  415. stats_prev_n_written = stats_n_bytes_written;
  416. }
  417. /**
  418. * Run all the controller events (if any) that are scheduled to trigger once
  419. * per second.
  420. */
  421. void
  422. control_per_second_events(void)
  423. {
  424. if (!control_any_per_second_event_enabled())
  425. return;
  426. uint64_t bytes_read, bytes_written;
  427. control_get_bytes_rw_last_sec(&bytes_read, &bytes_written);
  428. control_event_bandwidth_used((uint32_t)bytes_read,(uint32_t)bytes_written);
  429. control_event_stream_bandwidth_used();
  430. control_event_conn_bandwidth_used();
  431. control_event_circ_bandwidth_used();
  432. control_event_circuit_cell_stats();
  433. }
  434. /** Append a NUL-terminated string <b>s</b> to the end of
  435. * <b>conn</b>-\>outbuf.
  436. */
  437. static inline void
  438. connection_write_str_to_buf(const char *s, control_connection_t *conn)
  439. {
  440. size_t len = strlen(s);
  441. connection_buf_add(s, len, TO_CONN(conn));
  442. }
  443. /** Given a <b>len</b>-character string in <b>data</b>, made of lines
  444. * terminated by CRLF, allocate a new string in *<b>out</b>, and copy the
  445. * contents of <b>data</b> into *<b>out</b>, adding a period before any period
  446. * that appears at the start of a line, and adding a period-CRLF line at
  447. * the end. Replace all LF characters sequences with CRLF. Return the number
  448. * of bytes in *<b>out</b>.
  449. */
  450. STATIC size_t
  451. write_escaped_data(const char *data, size_t len, char **out)
  452. {
  453. tor_assert(len < SIZE_MAX - 9);
  454. size_t sz_out = len+8+1;
  455. char *outp;
  456. const char *start = data, *end;
  457. size_t i;
  458. int start_of_line;
  459. for (i=0; i < len; ++i) {
  460. if (data[i] == '\n') {
  461. sz_out += 2; /* Maybe add a CR; maybe add a dot. */
  462. if (sz_out >= SIZE_T_CEILING) {
  463. log_warn(LD_BUG, "Input to write_escaped_data was too long");
  464. *out = tor_strdup(".\r\n");
  465. return 3;
  466. }
  467. }
  468. }
  469. *out = outp = tor_malloc(sz_out);
  470. end = data+len;
  471. start_of_line = 1;
  472. while (data < end) {
  473. if (*data == '\n') {
  474. if (data > start && data[-1] != '\r')
  475. *outp++ = '\r';
  476. start_of_line = 1;
  477. } else if (*data == '.') {
  478. if (start_of_line) {
  479. start_of_line = 0;
  480. *outp++ = '.';
  481. }
  482. } else {
  483. start_of_line = 0;
  484. }
  485. *outp++ = *data++;
  486. }
  487. if (outp < *out+2 || fast_memcmp(outp-2, "\r\n", 2)) {
  488. *outp++ = '\r';
  489. *outp++ = '\n';
  490. }
  491. *outp++ = '.';
  492. *outp++ = '\r';
  493. *outp++ = '\n';
  494. *outp = '\0'; /* NUL-terminate just in case. */
  495. tor_assert(outp >= *out);
  496. tor_assert((size_t)(outp - *out) <= sz_out);
  497. return outp - *out;
  498. }
  499. /** Given a <b>len</b>-character string in <b>data</b>, made of lines
  500. * terminated by CRLF, allocate a new string in *<b>out</b>, and copy
  501. * the contents of <b>data</b> into *<b>out</b>, removing any period
  502. * that appears at the start of a line, and replacing all CRLF sequences
  503. * with LF. Return the number of
  504. * bytes in *<b>out</b>. */
  505. STATIC size_t
  506. read_escaped_data(const char *data, size_t len, char **out)
  507. {
  508. char *outp;
  509. const char *next;
  510. const char *end;
  511. *out = outp = tor_malloc(len+1);
  512. end = data+len;
  513. while (data < end) {
  514. /* we're at the start of a line. */
  515. if (*data == '.')
  516. ++data;
  517. next = memchr(data, '\n', end-data);
  518. if (next) {
  519. size_t n_to_copy = next-data;
  520. /* Don't copy a CR that precedes this LF. */
  521. if (n_to_copy && *(next-1) == '\r')
  522. --n_to_copy;
  523. memcpy(outp, data, n_to_copy);
  524. outp += n_to_copy;
  525. data = next+1; /* This will point at the start of the next line,
  526. * or the end of the string, or a period. */
  527. } else {
  528. memcpy(outp, data, end-data);
  529. outp += (end-data);
  530. *outp = '\0';
  531. return outp - *out;
  532. }
  533. *outp++ = '\n';
  534. }
  535. *outp = '\0';
  536. return outp - *out;
  537. }
  538. /** If the first <b>in_len_max</b> characters in <b>start</b> contain a
  539. * double-quoted string with escaped characters, return the length of that
  540. * string (as encoded, including quotes). Otherwise return -1. */
  541. static inline int
  542. get_escaped_string_length(const char *start, size_t in_len_max,
  543. int *chars_out)
  544. {
  545. const char *cp, *end;
  546. int chars = 0;
  547. if (*start != '\"')
  548. return -1;
  549. cp = start+1;
  550. end = start+in_len_max;
  551. /* Calculate length. */
  552. while (1) {
  553. if (cp >= end) {
  554. return -1; /* Too long. */
  555. } else if (*cp == '\\') {
  556. if (++cp == end)
  557. return -1; /* Can't escape EOS. */
  558. ++cp;
  559. ++chars;
  560. } else if (*cp == '\"') {
  561. break;
  562. } else {
  563. ++cp;
  564. ++chars;
  565. }
  566. }
  567. if (chars_out)
  568. *chars_out = chars;
  569. return (int)(cp - start+1);
  570. }
  571. /** As decode_escaped_string, but does not decode the string: copies the
  572. * entire thing, including quotation marks. */
  573. static const char *
  574. extract_escaped_string(const char *start, size_t in_len_max,
  575. char **out, size_t *out_len)
  576. {
  577. int length = get_escaped_string_length(start, in_len_max, NULL);
  578. if (length<0)
  579. return NULL;
  580. *out_len = length;
  581. *out = tor_strndup(start, *out_len);
  582. return start+length;
  583. }
  584. /** Given a pointer to a string starting at <b>start</b> containing
  585. * <b>in_len_max</b> characters, decode a string beginning with one double
  586. * quote, containing any number of non-quote characters or characters escaped
  587. * with a backslash, and ending with a final double quote. Place the resulting
  588. * string (unquoted, unescaped) into a newly allocated string in *<b>out</b>;
  589. * store its length in <b>out_len</b>. On success, return a pointer to the
  590. * character immediately following the escaped string. On failure, return
  591. * NULL. */
  592. static const char *
  593. decode_escaped_string(const char *start, size_t in_len_max,
  594. char **out, size_t *out_len)
  595. {
  596. const char *cp, *end;
  597. char *outp;
  598. int len, n_chars = 0;
  599. len = get_escaped_string_length(start, in_len_max, &n_chars);
  600. if (len<0)
  601. return NULL;
  602. end = start+len-1; /* Index of last quote. */
  603. tor_assert(*end == '\"');
  604. outp = *out = tor_malloc(len+1);
  605. *out_len = n_chars;
  606. cp = start+1;
  607. while (cp < end) {
  608. if (*cp == '\\')
  609. ++cp;
  610. *outp++ = *cp++;
  611. }
  612. *outp = '\0';
  613. tor_assert((outp - *out) == (int)*out_len);
  614. return end+1;
  615. }
  616. /** Create and add a new controller connection on <b>sock</b>. If
  617. * <b>CC_LOCAL_FD_IS_OWNER</b> is set in <b>flags</b>, this Tor process should
  618. * exit when the connection closes. If <b>CC_LOCAL_FD_IS_AUTHENTICATED</b>
  619. * is set, then the connection does not need to authenticate.
  620. */
  621. int
  622. control_connection_add_local_fd(tor_socket_t sock, unsigned flags)
  623. {
  624. if (BUG(! SOCKET_OK(sock)))
  625. return -1;
  626. const int is_owner = !!(flags & CC_LOCAL_FD_IS_OWNER);
  627. const int is_authenticated = !!(flags & CC_LOCAL_FD_IS_AUTHENTICATED);
  628. control_connection_t *control_conn = control_connection_new(AF_UNSPEC);
  629. connection_t *conn = TO_CONN(control_conn);
  630. conn->s = sock;
  631. tor_addr_make_unspec(&conn->addr);
  632. conn->port = 1;
  633. conn->address = tor_strdup("<local socket>");
  634. /* We take ownership of this socket so that later, when we close it,
  635. * we don't freak out. */
  636. tor_take_socket_ownership(sock);
  637. if (set_socket_nonblocking(sock) < 0 ||
  638. connection_add(conn) < 0) {
  639. connection_free(conn);
  640. return -1;
  641. }
  642. control_conn->is_owning_control_connection = is_owner;
  643. if (connection_init_accepted_conn(conn, NULL) < 0) {
  644. connection_mark_for_close(conn);
  645. return -1;
  646. }
  647. if (is_authenticated) {
  648. conn->state = CONTROL_CONN_STATE_OPEN;
  649. }
  650. return 0;
  651. }
  652. /** Acts like sprintf, but writes its formatted string to the end of
  653. * <b>conn</b>-\>outbuf. */
  654. static void
  655. connection_printf_to_buf(control_connection_t *conn, const char *format, ...)
  656. {
  657. va_list ap;
  658. char *buf = NULL;
  659. int len;
  660. va_start(ap,format);
  661. len = tor_vasprintf(&buf, format, ap);
  662. va_end(ap);
  663. if (len < 0) {
  664. log_err(LD_BUG, "Unable to format string for controller.");
  665. tor_assert(0);
  666. }
  667. connection_buf_add(buf, (size_t)len, TO_CONN(conn));
  668. tor_free(buf);
  669. }
  670. /** Write all of the open control ports to ControlPortWriteToFile */
  671. void
  672. control_ports_write_to_file(void)
  673. {
  674. smartlist_t *lines;
  675. char *joined = NULL;
  676. const or_options_t *options = get_options();
  677. if (!options->ControlPortWriteToFile)
  678. return;
  679. lines = smartlist_new();
  680. SMARTLIST_FOREACH_BEGIN(get_connection_array(), const connection_t *, conn) {
  681. if (conn->type != CONN_TYPE_CONTROL_LISTENER || conn->marked_for_close)
  682. continue;
  683. #ifdef AF_UNIX
  684. if (conn->socket_family == AF_UNIX) {
  685. smartlist_add_asprintf(lines, "UNIX_PORT=%s\n", conn->address);
  686. continue;
  687. }
  688. #endif /* defined(AF_UNIX) */
  689. smartlist_add_asprintf(lines, "PORT=%s:%d\n", conn->address, conn->port);
  690. } SMARTLIST_FOREACH_END(conn);
  691. joined = smartlist_join_strings(lines, "", 0, NULL);
  692. if (write_str_to_file(options->ControlPortWriteToFile, joined, 0) < 0) {
  693. log_warn(LD_CONTROL, "Writing %s failed: %s",
  694. options->ControlPortWriteToFile, strerror(errno));
  695. }
  696. #ifndef _WIN32
  697. if (options->ControlPortFileGroupReadable) {
  698. if (chmod(options->ControlPortWriteToFile, 0640)) {
  699. log_warn(LD_FS,"Unable to make %s group-readable.",
  700. options->ControlPortWriteToFile);
  701. }
  702. }
  703. #endif /* !defined(_WIN32) */
  704. tor_free(joined);
  705. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  706. smartlist_free(lines);
  707. }
  708. /** Send a "DONE" message down the control connection <b>conn</b>. */
  709. static void
  710. send_control_done(control_connection_t *conn)
  711. {
  712. connection_write_str_to_buf("250 OK\r\n", conn);
  713. }
  714. /** Represents an event that's queued to be sent to one or more
  715. * controllers. */
  716. typedef struct queued_event_s {
  717. uint16_t event;
  718. char *msg;
  719. } queued_event_t;
  720. /** Pointer to int. If this is greater than 0, we don't allow new events to be
  721. * queued. */
  722. static tor_threadlocal_t block_event_queue_flag;
  723. /** Holds a smartlist of queued_event_t objects that may need to be sent
  724. * to one or more controllers */
  725. static smartlist_t *queued_control_events = NULL;
  726. /** True if the flush_queued_events_event is pending. */
  727. static int flush_queued_event_pending = 0;
  728. /** Lock to protect the above fields. */
  729. static tor_mutex_t *queued_control_events_lock = NULL;
  730. /** An event that should fire in order to flush the contents of
  731. * queued_control_events. */
  732. static mainloop_event_t *flush_queued_events_event = NULL;
  733. void
  734. control_initialize_event_queue(void)
  735. {
  736. if (queued_control_events == NULL) {
  737. queued_control_events = smartlist_new();
  738. }
  739. if (flush_queued_events_event == NULL) {
  740. struct event_base *b = tor_libevent_get_base();
  741. if (b) {
  742. flush_queued_events_event =
  743. mainloop_event_new(flush_queued_events_cb, NULL);
  744. tor_assert(flush_queued_events_event);
  745. }
  746. }
  747. if (queued_control_events_lock == NULL) {
  748. queued_control_events_lock = tor_mutex_new();
  749. tor_threadlocal_init(&block_event_queue_flag);
  750. }
  751. }
  752. static int *
  753. get_block_event_queue(void)
  754. {
  755. int *val = tor_threadlocal_get(&block_event_queue_flag);
  756. if (PREDICT_UNLIKELY(val == NULL)) {
  757. val = tor_malloc_zero(sizeof(int));
  758. tor_threadlocal_set(&block_event_queue_flag, val);
  759. }
  760. return val;
  761. }
  762. /** Helper: inserts an event on the list of events queued to be sent to
  763. * one or more controllers, and schedules the events to be flushed if needed.
  764. *
  765. * This function takes ownership of <b>msg</b>, and may free it.
  766. *
  767. * We queue these events rather than send them immediately in order to break
  768. * the dependency in our callgraph from code that generates events for the
  769. * controller, and the network layer at large. Otherwise, nearly every
  770. * interesting part of Tor would potentially call every other interesting part
  771. * of Tor.
  772. */
  773. MOCK_IMPL(STATIC void,
  774. queue_control_event_string,(uint16_t event, char *msg))
  775. {
  776. /* This is redundant with checks done elsewhere, but it's a last-ditch
  777. * attempt to avoid queueing something we shouldn't have to queue. */
  778. if (PREDICT_UNLIKELY( ! EVENT_IS_INTERESTING(event) )) {
  779. tor_free(msg);
  780. return;
  781. }
  782. int *block_event_queue = get_block_event_queue();
  783. if (*block_event_queue) {
  784. tor_free(msg);
  785. return;
  786. }
  787. queued_event_t *ev = tor_malloc(sizeof(*ev));
  788. ev->event = event;
  789. ev->msg = msg;
  790. /* No queueing an event while queueing an event */
  791. ++*block_event_queue;
  792. tor_mutex_acquire(queued_control_events_lock);
  793. tor_assert(queued_control_events);
  794. smartlist_add(queued_control_events, ev);
  795. int activate_event = 0;
  796. if (! flush_queued_event_pending && in_main_thread()) {
  797. activate_event = 1;
  798. flush_queued_event_pending = 1;
  799. }
  800. tor_mutex_release(queued_control_events_lock);
  801. --*block_event_queue;
  802. /* We just put an event on the queue; mark the queue to be
  803. * flushed. We only do this from the main thread for now; otherwise,
  804. * we'd need to incur locking overhead in Libevent or use a socket.
  805. */
  806. if (activate_event) {
  807. tor_assert(flush_queued_events_event);
  808. mainloop_event_activate(flush_queued_events_event);
  809. }
  810. }
  811. #define queued_event_free(ev) \
  812. FREE_AND_NULL(queued_event_t, queued_event_free_, (ev))
  813. /** Release all storage held by <b>ev</b>. */
  814. static void
  815. queued_event_free_(queued_event_t *ev)
  816. {
  817. if (ev == NULL)
  818. return;
  819. tor_free(ev->msg);
  820. tor_free(ev);
  821. }
  822. /** Send every queued event to every controller that's interested in it,
  823. * and remove the events from the queue. If <b>force</b> is true,
  824. * then make all controllers send their data out immediately, since we
  825. * may be about to shut down. */
  826. static void
  827. queued_events_flush_all(int force)
  828. {
  829. /* Make sure that we get all the pending log events, if there are any. */
  830. flush_pending_log_callbacks();
  831. if (PREDICT_UNLIKELY(queued_control_events == NULL)) {
  832. return;
  833. }
  834. smartlist_t *all_conns = get_connection_array();
  835. smartlist_t *controllers = smartlist_new();
  836. smartlist_t *queued_events;
  837. int *block_event_queue = get_block_event_queue();
  838. ++*block_event_queue;
  839. tor_mutex_acquire(queued_control_events_lock);
  840. /* No queueing an event while flushing events. */
  841. flush_queued_event_pending = 0;
  842. queued_events = queued_control_events;
  843. queued_control_events = smartlist_new();
  844. tor_mutex_release(queued_control_events_lock);
  845. /* Gather all the controllers that will care... */
  846. SMARTLIST_FOREACH_BEGIN(all_conns, connection_t *, conn) {
  847. if (conn->type == CONN_TYPE_CONTROL &&
  848. !conn->marked_for_close &&
  849. conn->state == CONTROL_CONN_STATE_OPEN) {
  850. control_connection_t *control_conn = TO_CONTROL_CONN(conn);
  851. smartlist_add(controllers, control_conn);
  852. }
  853. } SMARTLIST_FOREACH_END(conn);
  854. SMARTLIST_FOREACH_BEGIN(queued_events, queued_event_t *, ev) {
  855. const event_mask_t bit = ((event_mask_t)1) << ev->event;
  856. const size_t msg_len = strlen(ev->msg);
  857. SMARTLIST_FOREACH_BEGIN(controllers, control_connection_t *,
  858. control_conn) {
  859. if (control_conn->event_mask & bit) {
  860. connection_buf_add(ev->msg, msg_len, TO_CONN(control_conn));
  861. }
  862. } SMARTLIST_FOREACH_END(control_conn);
  863. queued_event_free(ev);
  864. } SMARTLIST_FOREACH_END(ev);
  865. if (force) {
  866. SMARTLIST_FOREACH_BEGIN(controllers, control_connection_t *,
  867. control_conn) {
  868. connection_flush(TO_CONN(control_conn));
  869. } SMARTLIST_FOREACH_END(control_conn);
  870. }
  871. smartlist_free(queued_events);
  872. smartlist_free(controllers);
  873. --*block_event_queue;
  874. }
  875. /** Libevent callback: Flushes pending events to controllers that are
  876. * interested in them. */
  877. static void
  878. flush_queued_events_cb(mainloop_event_t *event, void *arg)
  879. {
  880. (void) event;
  881. (void) arg;
  882. queued_events_flush_all(0);
  883. }
  884. /** Send an event to all v1 controllers that are listening for code
  885. * <b>event</b>. The event's body is given by <b>msg</b>.
  886. *
  887. * The EXTENDED_FORMAT and NONEXTENDED_FORMAT flags behave similarly with
  888. * respect to the EXTENDED_EVENTS feature. */
  889. MOCK_IMPL(STATIC void,
  890. send_control_event_string,(uint16_t event,
  891. const char *msg))
  892. {
  893. tor_assert(event >= EVENT_MIN_ && event <= EVENT_MAX_);
  894. queue_control_event_string(event, tor_strdup(msg));
  895. }
  896. /** Helper for send_control_event and control_event_status:
  897. * Send an event to all v1 controllers that are listening for code
  898. * <b>event</b>. The event's body is created by the printf-style format in
  899. * <b>format</b>, and other arguments as provided. */
  900. static void
  901. send_control_event_impl(uint16_t event,
  902. const char *format, va_list ap)
  903. {
  904. char *buf = NULL;
  905. int len;
  906. len = tor_vasprintf(&buf, format, ap);
  907. if (len < 0) {
  908. log_warn(LD_BUG, "Unable to format event for controller.");
  909. return;
  910. }
  911. queue_control_event_string(event, buf);
  912. }
  913. /** Send an event to all v1 controllers that are listening for code
  914. * <b>event</b>. The event's body is created by the printf-style format in
  915. * <b>format</b>, and other arguments as provided. */
  916. static void
  917. send_control_event(uint16_t event,
  918. const char *format, ...)
  919. {
  920. va_list ap;
  921. va_start(ap, format);
  922. send_control_event_impl(event, format, ap);
  923. va_end(ap);
  924. }
  925. /** Given a text circuit <b>id</b>, return the corresponding circuit. */
  926. static origin_circuit_t *
  927. get_circ(const char *id)
  928. {
  929. uint32_t n_id;
  930. int ok;
  931. n_id = (uint32_t) tor_parse_ulong(id, 10, 0, UINT32_MAX, &ok, NULL);
  932. if (!ok)
  933. return NULL;
  934. return circuit_get_by_global_id(n_id);
  935. }
  936. /** Given a text stream <b>id</b>, return the corresponding AP connection. */
  937. static entry_connection_t *
  938. get_stream(const char *id)
  939. {
  940. uint64_t n_id;
  941. int ok;
  942. connection_t *conn;
  943. n_id = tor_parse_uint64(id, 10, 0, UINT64_MAX, &ok, NULL);
  944. if (!ok)
  945. return NULL;
  946. conn = connection_get_by_global_id(n_id);
  947. if (!conn || conn->type != CONN_TYPE_AP || conn->marked_for_close)
  948. return NULL;
  949. return TO_ENTRY_CONN(conn);
  950. }
  951. /** Helper for setconf and resetconf. Acts like setconf, except
  952. * it passes <b>use_defaults</b> on to options_trial_assign(). Modifies the
  953. * contents of body.
  954. */
  955. static int
  956. control_setconf_helper(control_connection_t *conn, uint32_t len, char *body,
  957. int use_defaults)
  958. {
  959. setopt_err_t opt_err;
  960. config_line_t *lines=NULL;
  961. char *start = body;
  962. char *errstring = NULL;
  963. const unsigned flags =
  964. CAL_CLEAR_FIRST | (use_defaults ? CAL_USE_DEFAULTS : 0);
  965. char *config;
  966. smartlist_t *entries = smartlist_new();
  967. /* We have a string, "body", of the format '(key(=val|="val")?)' entries
  968. * separated by space. break it into a list of configuration entries. */
  969. while (*body) {
  970. char *eq = body;
  971. char *key;
  972. char *entry;
  973. while (!TOR_ISSPACE(*eq) && *eq != '=')
  974. ++eq;
  975. key = tor_strndup(body, eq-body);
  976. body = eq+1;
  977. if (*eq == '=') {
  978. char *val=NULL;
  979. size_t val_len=0;
  980. if (*body != '\"') {
  981. char *val_start = body;
  982. while (!TOR_ISSPACE(*body))
  983. body++;
  984. val = tor_strndup(val_start, body-val_start);
  985. val_len = strlen(val);
  986. } else {
  987. body = (char*)extract_escaped_string(body, (len - (body-start)),
  988. &val, &val_len);
  989. if (!body) {
  990. connection_write_str_to_buf("551 Couldn't parse string\r\n", conn);
  991. SMARTLIST_FOREACH(entries, char *, cp, tor_free(cp));
  992. smartlist_free(entries);
  993. tor_free(key);
  994. return 0;
  995. }
  996. }
  997. tor_asprintf(&entry, "%s %s", key, val);
  998. tor_free(key);
  999. tor_free(val);
  1000. } else {
  1001. entry = key;
  1002. }
  1003. smartlist_add(entries, entry);
  1004. while (TOR_ISSPACE(*body))
  1005. ++body;
  1006. }
  1007. smartlist_add_strdup(entries, "");
  1008. config = smartlist_join_strings(entries, "\n", 0, NULL);
  1009. SMARTLIST_FOREACH(entries, char *, cp, tor_free(cp));
  1010. smartlist_free(entries);
  1011. if (config_get_lines(config, &lines, 0) < 0) {
  1012. log_warn(LD_CONTROL,"Controller gave us config lines we can't parse.");
  1013. connection_write_str_to_buf("551 Couldn't parse configuration\r\n",
  1014. conn);
  1015. tor_free(config);
  1016. return 0;
  1017. }
  1018. tor_free(config);
  1019. opt_err = options_trial_assign(lines, flags, &errstring);
  1020. {
  1021. const char *msg;
  1022. switch (opt_err) {
  1023. case SETOPT_ERR_MISC:
  1024. msg = "552 Unrecognized option";
  1025. break;
  1026. case SETOPT_ERR_PARSE:
  1027. msg = "513 Unacceptable option value";
  1028. break;
  1029. case SETOPT_ERR_TRANSITION:
  1030. msg = "553 Transition not allowed";
  1031. break;
  1032. case SETOPT_ERR_SETTING:
  1033. default:
  1034. msg = "553 Unable to set option";
  1035. break;
  1036. case SETOPT_OK:
  1037. config_free_lines(lines);
  1038. send_control_done(conn);
  1039. return 0;
  1040. }
  1041. log_warn(LD_CONTROL,
  1042. "Controller gave us config lines that didn't validate: %s",
  1043. errstring);
  1044. connection_printf_to_buf(conn, "%s: %s\r\n", msg, errstring);
  1045. config_free_lines(lines);
  1046. tor_free(errstring);
  1047. return 0;
  1048. }
  1049. }
  1050. /** Called when we receive a SETCONF message: parse the body and try
  1051. * to update our configuration. Reply with a DONE or ERROR message.
  1052. * Modifies the contents of body.*/
  1053. static int
  1054. handle_control_setconf(control_connection_t *conn, uint32_t len, char *body)
  1055. {
  1056. return control_setconf_helper(conn, len, body, 0);
  1057. }
  1058. /** Called when we receive a RESETCONF message: parse the body and try
  1059. * to update our configuration. Reply with a DONE or ERROR message.
  1060. * Modifies the contents of body. */
  1061. static int
  1062. handle_control_resetconf(control_connection_t *conn, uint32_t len, char *body)
  1063. {
  1064. return control_setconf_helper(conn, len, body, 1);
  1065. }
  1066. /** Called when we receive a GETCONF message. Parse the request, and
  1067. * reply with a CONFVALUE or an ERROR message */
  1068. static int
  1069. handle_control_getconf(control_connection_t *conn, uint32_t body_len,
  1070. const char *body)
  1071. {
  1072. smartlist_t *questions = smartlist_new();
  1073. smartlist_t *answers = smartlist_new();
  1074. smartlist_t *unrecognized = smartlist_new();
  1075. char *msg = NULL;
  1076. size_t msg_len;
  1077. const or_options_t *options = get_options();
  1078. int i, len;
  1079. (void) body_len; /* body is NUL-terminated; so we can ignore len. */
  1080. smartlist_split_string(questions, body, " ",
  1081. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1082. SMARTLIST_FOREACH_BEGIN(questions, const char *, q) {
  1083. if (!option_is_recognized(q)) {
  1084. smartlist_add(unrecognized, (char*) q);
  1085. } else {
  1086. config_line_t *answer = option_get_assignment(options,q);
  1087. if (!answer) {
  1088. const char *name = option_get_canonical_name(q);
  1089. smartlist_add_asprintf(answers, "250-%s\r\n", name);
  1090. }
  1091. while (answer) {
  1092. config_line_t *next;
  1093. smartlist_add_asprintf(answers, "250-%s=%s\r\n",
  1094. answer->key, answer->value);
  1095. next = answer->next;
  1096. tor_free(answer->key);
  1097. tor_free(answer->value);
  1098. tor_free(answer);
  1099. answer = next;
  1100. }
  1101. }
  1102. } SMARTLIST_FOREACH_END(q);
  1103. if ((len = smartlist_len(unrecognized))) {
  1104. for (i=0; i < len-1; ++i)
  1105. connection_printf_to_buf(conn,
  1106. "552-Unrecognized configuration key \"%s\"\r\n",
  1107. (char*)smartlist_get(unrecognized, i));
  1108. connection_printf_to_buf(conn,
  1109. "552 Unrecognized configuration key \"%s\"\r\n",
  1110. (char*)smartlist_get(unrecognized, len-1));
  1111. } else if ((len = smartlist_len(answers))) {
  1112. char *tmp = smartlist_get(answers, len-1);
  1113. tor_assert(strlen(tmp)>4);
  1114. tmp[3] = ' ';
  1115. msg = smartlist_join_strings(answers, "", 0, &msg_len);
  1116. connection_buf_add(msg, msg_len, TO_CONN(conn));
  1117. } else {
  1118. connection_write_str_to_buf("250 OK\r\n", conn);
  1119. }
  1120. SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
  1121. smartlist_free(answers);
  1122. SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
  1123. smartlist_free(questions);
  1124. smartlist_free(unrecognized);
  1125. tor_free(msg);
  1126. return 0;
  1127. }
  1128. /** Called when we get a +LOADCONF message. */
  1129. static int
  1130. handle_control_loadconf(control_connection_t *conn, uint32_t len,
  1131. const char *body)
  1132. {
  1133. setopt_err_t retval;
  1134. char *errstring = NULL;
  1135. const char *msg = NULL;
  1136. (void) len;
  1137. retval = options_init_from_string(NULL, body, CMD_RUN_TOR, NULL, &errstring);
  1138. if (retval != SETOPT_OK)
  1139. log_warn(LD_CONTROL,
  1140. "Controller gave us config file that didn't validate: %s",
  1141. errstring);
  1142. switch (retval) {
  1143. case SETOPT_ERR_PARSE:
  1144. msg = "552 Invalid config file";
  1145. break;
  1146. case SETOPT_ERR_TRANSITION:
  1147. msg = "553 Transition not allowed";
  1148. break;
  1149. case SETOPT_ERR_SETTING:
  1150. msg = "553 Unable to set option";
  1151. break;
  1152. case SETOPT_ERR_MISC:
  1153. default:
  1154. msg = "550 Unable to load config";
  1155. break;
  1156. case SETOPT_OK:
  1157. break;
  1158. }
  1159. if (msg) {
  1160. if (errstring)
  1161. connection_printf_to_buf(conn, "%s: %s\r\n", msg, errstring);
  1162. else
  1163. connection_printf_to_buf(conn, "%s\r\n", msg);
  1164. } else {
  1165. send_control_done(conn);
  1166. }
  1167. tor_free(errstring);
  1168. return 0;
  1169. }
  1170. /** Helper structure: maps event values to their names. */
  1171. struct control_event_t {
  1172. uint16_t event_code;
  1173. const char *event_name;
  1174. };
  1175. /** Table mapping event values to their names. Used to implement SETEVENTS
  1176. * and GETINFO events/names, and to keep they in sync. */
  1177. static const struct control_event_t control_event_table[] = {
  1178. { EVENT_CIRCUIT_STATUS, "CIRC" },
  1179. { EVENT_CIRCUIT_STATUS_MINOR, "CIRC_MINOR" },
  1180. { EVENT_STREAM_STATUS, "STREAM" },
  1181. { EVENT_OR_CONN_STATUS, "ORCONN" },
  1182. { EVENT_BANDWIDTH_USED, "BW" },
  1183. { EVENT_DEBUG_MSG, "DEBUG" },
  1184. { EVENT_INFO_MSG, "INFO" },
  1185. { EVENT_NOTICE_MSG, "NOTICE" },
  1186. { EVENT_WARN_MSG, "WARN" },
  1187. { EVENT_ERR_MSG, "ERR" },
  1188. { EVENT_NEW_DESC, "NEWDESC" },
  1189. { EVENT_ADDRMAP, "ADDRMAP" },
  1190. { EVENT_DESCCHANGED, "DESCCHANGED" },
  1191. { EVENT_NS, "NS" },
  1192. { EVENT_STATUS_GENERAL, "STATUS_GENERAL" },
  1193. { EVENT_STATUS_CLIENT, "STATUS_CLIENT" },
  1194. { EVENT_STATUS_SERVER, "STATUS_SERVER" },
  1195. { EVENT_GUARD, "GUARD" },
  1196. { EVENT_STREAM_BANDWIDTH_USED, "STREAM_BW" },
  1197. { EVENT_CLIENTS_SEEN, "CLIENTS_SEEN" },
  1198. { EVENT_NEWCONSENSUS, "NEWCONSENSUS" },
  1199. { EVENT_BUILDTIMEOUT_SET, "BUILDTIMEOUT_SET" },
  1200. { EVENT_GOT_SIGNAL, "SIGNAL" },
  1201. { EVENT_CONF_CHANGED, "CONF_CHANGED"},
  1202. { EVENT_CONN_BW, "CONN_BW" },
  1203. { EVENT_CELL_STATS, "CELL_STATS" },
  1204. { EVENT_CIRC_BANDWIDTH_USED, "CIRC_BW" },
  1205. { EVENT_TRANSPORT_LAUNCHED, "TRANSPORT_LAUNCHED" },
  1206. { EVENT_HS_DESC, "HS_DESC" },
  1207. { EVENT_HS_DESC_CONTENT, "HS_DESC_CONTENT" },
  1208. { EVENT_NETWORK_LIVENESS, "NETWORK_LIVENESS" },
  1209. { 0, NULL },
  1210. };
  1211. /** Called when we get a SETEVENTS message: update conn->event_mask,
  1212. * and reply with DONE or ERROR. */
  1213. static int
  1214. handle_control_setevents(control_connection_t *conn, uint32_t len,
  1215. const char *body)
  1216. {
  1217. int event_code;
  1218. event_mask_t event_mask = 0;
  1219. smartlist_t *events = smartlist_new();
  1220. (void) len;
  1221. smartlist_split_string(events, body, " ",
  1222. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1223. SMARTLIST_FOREACH_BEGIN(events, const char *, ev)
  1224. {
  1225. if (!strcasecmp(ev, "EXTENDED") ||
  1226. !strcasecmp(ev, "AUTHDIR_NEWDESCS")) {
  1227. log_warn(LD_CONTROL, "The \"%s\" SETEVENTS argument is no longer "
  1228. "supported.", ev);
  1229. continue;
  1230. } else {
  1231. int i;
  1232. event_code = -1;
  1233. for (i = 0; control_event_table[i].event_name != NULL; ++i) {
  1234. if (!strcasecmp(ev, control_event_table[i].event_name)) {
  1235. event_code = control_event_table[i].event_code;
  1236. break;
  1237. }
  1238. }
  1239. if (event_code == -1) {
  1240. connection_printf_to_buf(conn, "552 Unrecognized event \"%s\"\r\n",
  1241. ev);
  1242. SMARTLIST_FOREACH(events, char *, e, tor_free(e));
  1243. smartlist_free(events);
  1244. return 0;
  1245. }
  1246. }
  1247. event_mask |= (((event_mask_t)1) << event_code);
  1248. }
  1249. SMARTLIST_FOREACH_END(ev);
  1250. SMARTLIST_FOREACH(events, char *, e, tor_free(e));
  1251. smartlist_free(events);
  1252. conn->event_mask = event_mask;
  1253. control_update_global_event_mask();
  1254. send_control_done(conn);
  1255. return 0;
  1256. }
  1257. /** Decode the hashed, base64'd passwords stored in <b>passwords</b>.
  1258. * Return a smartlist of acceptable passwords (unterminated strings of
  1259. * length S2K_RFC2440_SPECIFIER_LEN+DIGEST_LEN) on success, or NULL on
  1260. * failure.
  1261. */
  1262. smartlist_t *
  1263. decode_hashed_passwords(config_line_t *passwords)
  1264. {
  1265. char decoded[64];
  1266. config_line_t *cl;
  1267. smartlist_t *sl = smartlist_new();
  1268. tor_assert(passwords);
  1269. for (cl = passwords; cl; cl = cl->next) {
  1270. const char *hashed = cl->value;
  1271. if (!strcmpstart(hashed, "16:")) {
  1272. if (base16_decode(decoded, sizeof(decoded), hashed+3, strlen(hashed+3))
  1273. != S2K_RFC2440_SPECIFIER_LEN + DIGEST_LEN
  1274. || strlen(hashed+3) != (S2K_RFC2440_SPECIFIER_LEN+DIGEST_LEN)*2) {
  1275. goto err;
  1276. }
  1277. } else {
  1278. if (base64_decode(decoded, sizeof(decoded), hashed, strlen(hashed))
  1279. != S2K_RFC2440_SPECIFIER_LEN+DIGEST_LEN) {
  1280. goto err;
  1281. }
  1282. }
  1283. smartlist_add(sl,
  1284. tor_memdup(decoded, S2K_RFC2440_SPECIFIER_LEN+DIGEST_LEN));
  1285. }
  1286. return sl;
  1287. err:
  1288. SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
  1289. smartlist_free(sl);
  1290. return NULL;
  1291. }
  1292. /** Called when we get an AUTHENTICATE message. Check whether the
  1293. * authentication is valid, and if so, update the connection's state to
  1294. * OPEN. Reply with DONE or ERROR.
  1295. */
  1296. static int
  1297. handle_control_authenticate(control_connection_t *conn, uint32_t len,
  1298. const char *body)
  1299. {
  1300. int used_quoted_string = 0;
  1301. const or_options_t *options = get_options();
  1302. const char *errstr = "Unknown error";
  1303. char *password;
  1304. size_t password_len;
  1305. const char *cp;
  1306. int i;
  1307. int bad_cookie=0, bad_password=0;
  1308. smartlist_t *sl = NULL;
  1309. if (!len) {
  1310. password = tor_strdup("");
  1311. password_len = 0;
  1312. } else if (TOR_ISXDIGIT(body[0])) {
  1313. cp = body;
  1314. while (TOR_ISXDIGIT(*cp))
  1315. ++cp;
  1316. i = (int)(cp - body);
  1317. tor_assert(i>0);
  1318. password_len = i/2;
  1319. password = tor_malloc(password_len + 1);
  1320. if (base16_decode(password, password_len+1, body, i)
  1321. != (int) password_len) {
  1322. connection_write_str_to_buf(
  1323. "551 Invalid hexadecimal encoding. Maybe you tried a plain text "
  1324. "password? If so, the standard requires that you put it in "
  1325. "double quotes.\r\n", conn);
  1326. connection_mark_for_close(TO_CONN(conn));
  1327. tor_free(password);
  1328. return 0;
  1329. }
  1330. } else {
  1331. if (!decode_escaped_string(body, len, &password, &password_len)) {
  1332. connection_write_str_to_buf("551 Invalid quoted string. You need "
  1333. "to put the password in double quotes.\r\n", conn);
  1334. connection_mark_for_close(TO_CONN(conn));
  1335. return 0;
  1336. }
  1337. used_quoted_string = 1;
  1338. }
  1339. if (conn->safecookie_client_hash != NULL) {
  1340. /* The controller has chosen safe cookie authentication; the only
  1341. * acceptable authentication value is the controller-to-server
  1342. * response. */
  1343. tor_assert(authentication_cookie_is_set);
  1344. if (password_len != DIGEST256_LEN) {
  1345. log_warn(LD_CONTROL,
  1346. "Got safe cookie authentication response with wrong length "
  1347. "(%d)", (int)password_len);
  1348. errstr = "Wrong length for safe cookie response.";
  1349. goto err;
  1350. }
  1351. if (tor_memneq(conn->safecookie_client_hash, password, DIGEST256_LEN)) {
  1352. log_warn(LD_CONTROL,
  1353. "Got incorrect safe cookie authentication response");
  1354. errstr = "Safe cookie response did not match expected value.";
  1355. goto err;
  1356. }
  1357. tor_free(conn->safecookie_client_hash);
  1358. goto ok;
  1359. }
  1360. if (!options->CookieAuthentication && !options->HashedControlPassword &&
  1361. !options->HashedControlSessionPassword) {
  1362. /* if Tor doesn't demand any stronger authentication, then
  1363. * the controller can get in with anything. */
  1364. goto ok;
  1365. }
  1366. if (options->CookieAuthentication) {
  1367. int also_password = options->HashedControlPassword != NULL ||
  1368. options->HashedControlSessionPassword != NULL;
  1369. if (password_len != AUTHENTICATION_COOKIE_LEN) {
  1370. if (!also_password) {
  1371. log_warn(LD_CONTROL, "Got authentication cookie with wrong length "
  1372. "(%d)", (int)password_len);
  1373. errstr = "Wrong length on authentication cookie.";
  1374. goto err;
  1375. }
  1376. bad_cookie = 1;
  1377. } else if (tor_memneq(authentication_cookie, password, password_len)) {
  1378. if (!also_password) {
  1379. log_warn(LD_CONTROL, "Got mismatched authentication cookie");
  1380. errstr = "Authentication cookie did not match expected value.";
  1381. goto err;
  1382. }
  1383. bad_cookie = 1;
  1384. } else {
  1385. goto ok;
  1386. }
  1387. }
  1388. if (options->HashedControlPassword ||
  1389. options->HashedControlSessionPassword) {
  1390. int bad = 0;
  1391. smartlist_t *sl_tmp;
  1392. char received[DIGEST_LEN];
  1393. int also_cookie = options->CookieAuthentication;
  1394. sl = smartlist_new();
  1395. if (options->HashedControlPassword) {
  1396. sl_tmp = decode_hashed_passwords(options->HashedControlPassword);
  1397. if (!sl_tmp)
  1398. bad = 1;
  1399. else {
  1400. smartlist_add_all(sl, sl_tmp);
  1401. smartlist_free(sl_tmp);
  1402. }
  1403. }
  1404. if (options->HashedControlSessionPassword) {
  1405. sl_tmp = decode_hashed_passwords(options->HashedControlSessionPassword);
  1406. if (!sl_tmp)
  1407. bad = 1;
  1408. else {
  1409. smartlist_add_all(sl, sl_tmp);
  1410. smartlist_free(sl_tmp);
  1411. }
  1412. }
  1413. if (bad) {
  1414. if (!also_cookie) {
  1415. log_warn(LD_BUG,
  1416. "Couldn't decode HashedControlPassword: invalid base16");
  1417. errstr="Couldn't decode HashedControlPassword value in configuration.";
  1418. goto err;
  1419. }
  1420. bad_password = 1;
  1421. SMARTLIST_FOREACH(sl, char *, str, tor_free(str));
  1422. smartlist_free(sl);
  1423. sl = NULL;
  1424. } else {
  1425. SMARTLIST_FOREACH(sl, char *, expected,
  1426. {
  1427. secret_to_key_rfc2440(received,DIGEST_LEN,
  1428. password,password_len,expected);
  1429. if (tor_memeq(expected + S2K_RFC2440_SPECIFIER_LEN,
  1430. received, DIGEST_LEN))
  1431. goto ok;
  1432. });
  1433. SMARTLIST_FOREACH(sl, char *, str, tor_free(str));
  1434. smartlist_free(sl);
  1435. sl = NULL;
  1436. if (used_quoted_string)
  1437. errstr = "Password did not match HashedControlPassword value from "
  1438. "configuration";
  1439. else
  1440. errstr = "Password did not match HashedControlPassword value from "
  1441. "configuration. Maybe you tried a plain text password? "
  1442. "If so, the standard requires that you put it in double quotes.";
  1443. bad_password = 1;
  1444. if (!also_cookie)
  1445. goto err;
  1446. }
  1447. }
  1448. /** We only get here if both kinds of authentication failed. */
  1449. tor_assert(bad_password && bad_cookie);
  1450. log_warn(LD_CONTROL, "Bad password or authentication cookie on controller.");
  1451. errstr = "Password did not match HashedControlPassword *or* authentication "
  1452. "cookie.";
  1453. err:
  1454. tor_free(password);
  1455. connection_printf_to_buf(conn, "515 Authentication failed: %s\r\n", errstr);
  1456. connection_mark_for_close(TO_CONN(conn));
  1457. if (sl) { /* clean up */
  1458. SMARTLIST_FOREACH(sl, char *, str, tor_free(str));
  1459. smartlist_free(sl);
  1460. }
  1461. return 0;
  1462. ok:
  1463. log_info(LD_CONTROL, "Authenticated control connection ("TOR_SOCKET_T_FORMAT
  1464. ")", conn->base_.s);
  1465. send_control_done(conn);
  1466. conn->base_.state = CONTROL_CONN_STATE_OPEN;
  1467. tor_free(password);
  1468. if (sl) { /* clean up */
  1469. SMARTLIST_FOREACH(sl, char *, str, tor_free(str));
  1470. smartlist_free(sl);
  1471. }
  1472. return 0;
  1473. }
  1474. /** Called when we get a SAVECONF command. Try to flush the current options to
  1475. * disk, and report success or failure. */
  1476. static int
  1477. handle_control_saveconf(control_connection_t *conn, uint32_t len,
  1478. const char *body)
  1479. {
  1480. (void) len;
  1481. int force = !strcmpstart(body, "FORCE");
  1482. const or_options_t *options = get_options();
  1483. if ((!force && options->IncludeUsed) || options_save_current() < 0) {
  1484. connection_write_str_to_buf(
  1485. "551 Unable to write configuration to disk.\r\n", conn);
  1486. } else {
  1487. send_control_done(conn);
  1488. }
  1489. return 0;
  1490. }
  1491. struct signal_t {
  1492. int sig;
  1493. const char *signal_name;
  1494. };
  1495. static const struct signal_t signal_table[] = {
  1496. { SIGHUP, "RELOAD" },
  1497. { SIGHUP, "HUP" },
  1498. { SIGINT, "SHUTDOWN" },
  1499. { SIGUSR1, "DUMP" },
  1500. { SIGUSR1, "USR1" },
  1501. { SIGUSR2, "DEBUG" },
  1502. { SIGUSR2, "USR2" },
  1503. { SIGTERM, "HALT" },
  1504. { SIGTERM, "TERM" },
  1505. { SIGTERM, "INT" },
  1506. { SIGNEWNYM, "NEWNYM" },
  1507. { SIGCLEARDNSCACHE, "CLEARDNSCACHE"},
  1508. { SIGHEARTBEAT, "HEARTBEAT"},
  1509. { 0, NULL },
  1510. };
  1511. /** Called when we get a SIGNAL command. React to the provided signal, and
  1512. * report success or failure. (If the signal results in a shutdown, success
  1513. * may not be reported.) */
  1514. static int
  1515. handle_control_signal(control_connection_t *conn, uint32_t len,
  1516. const char *body)
  1517. {
  1518. int sig = -1;
  1519. int i;
  1520. int n = 0;
  1521. char *s;
  1522. (void) len;
  1523. while (body[n] && ! TOR_ISSPACE(body[n]))
  1524. ++n;
  1525. s = tor_strndup(body, n);
  1526. for (i = 0; signal_table[i].signal_name != NULL; ++i) {
  1527. if (!strcasecmp(s, signal_table[i].signal_name)) {
  1528. sig = signal_table[i].sig;
  1529. break;
  1530. }
  1531. }
  1532. if (sig < 0)
  1533. connection_printf_to_buf(conn, "552 Unrecognized signal code \"%s\"\r\n",
  1534. s);
  1535. tor_free(s);
  1536. if (sig < 0)
  1537. return 0;
  1538. send_control_done(conn);
  1539. /* Flush the "done" first if the signal might make us shut down. */
  1540. if (sig == SIGTERM || sig == SIGINT)
  1541. connection_flush(TO_CONN(conn));
  1542. activate_signal(sig);
  1543. return 0;
  1544. }
  1545. /** Called when we get a TAKEOWNERSHIP command. Mark this connection
  1546. * as an owning connection, so that we will exit if the connection
  1547. * closes. */
  1548. static int
  1549. handle_control_takeownership(control_connection_t *conn, uint32_t len,
  1550. const char *body)
  1551. {
  1552. (void)len;
  1553. (void)body;
  1554. conn->is_owning_control_connection = 1;
  1555. log_info(LD_CONTROL, "Control connection %d has taken ownership of this "
  1556. "Tor instance.",
  1557. (int)(conn->base_.s));
  1558. send_control_done(conn);
  1559. return 0;
  1560. }
  1561. /** Return true iff <b>addr</b> is unusable as a mapaddress target because of
  1562. * containing funny characters. */
  1563. static int
  1564. address_is_invalid_mapaddress_target(const char *addr)
  1565. {
  1566. if (!strcmpstart(addr, "*."))
  1567. return address_is_invalid_destination(addr+2, 1);
  1568. else
  1569. return address_is_invalid_destination(addr, 1);
  1570. }
  1571. /** Called when we get a MAPADDRESS command; try to bind all listed addresses,
  1572. * and report success or failure. */
  1573. static int
  1574. handle_control_mapaddress(control_connection_t *conn, uint32_t len,
  1575. const char *body)
  1576. {
  1577. smartlist_t *elts;
  1578. smartlist_t *lines;
  1579. smartlist_t *reply;
  1580. char *r;
  1581. size_t sz;
  1582. (void) len; /* body is NUL-terminated, so it's safe to ignore the length. */
  1583. lines = smartlist_new();
  1584. elts = smartlist_new();
  1585. reply = smartlist_new();
  1586. smartlist_split_string(lines, body, " ",
  1587. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1588. SMARTLIST_FOREACH_BEGIN(lines, char *, line) {
  1589. tor_strlower(line);
  1590. smartlist_split_string(elts, line, "=", 0, 2);
  1591. if (smartlist_len(elts) == 2) {
  1592. const char *from = smartlist_get(elts,0);
  1593. const char *to = smartlist_get(elts,1);
  1594. if (address_is_invalid_mapaddress_target(to)) {
  1595. smartlist_add_asprintf(reply,
  1596. "512-syntax error: invalid address '%s'", to);
  1597. log_warn(LD_CONTROL,
  1598. "Skipping invalid argument '%s' in MapAddress msg", to);
  1599. } else if (!strcmp(from, ".") || !strcmp(from, "0.0.0.0") ||
  1600. !strcmp(from, "::")) {
  1601. const char type =
  1602. !strcmp(from,".") ? RESOLVED_TYPE_HOSTNAME :
  1603. (!strcmp(from, "0.0.0.0") ? RESOLVED_TYPE_IPV4 : RESOLVED_TYPE_IPV6);
  1604. const char *address = addressmap_register_virtual_address(
  1605. type, tor_strdup(to));
  1606. if (!address) {
  1607. smartlist_add_asprintf(reply,
  1608. "451-resource exhausted: skipping '%s'", line);
  1609. log_warn(LD_CONTROL,
  1610. "Unable to allocate address for '%s' in MapAddress msg",
  1611. safe_str_client(line));
  1612. } else {
  1613. smartlist_add_asprintf(reply, "250-%s=%s", address, to);
  1614. }
  1615. } else {
  1616. const char *msg;
  1617. if (addressmap_register_auto(from, to, 1,
  1618. ADDRMAPSRC_CONTROLLER, &msg) < 0) {
  1619. smartlist_add_asprintf(reply,
  1620. "512-syntax error: invalid address mapping "
  1621. " '%s': %s", line, msg);
  1622. log_warn(LD_CONTROL,
  1623. "Skipping invalid argument '%s' in MapAddress msg: %s",
  1624. line, msg);
  1625. } else {
  1626. smartlist_add_asprintf(reply, "250-%s", line);
  1627. }
  1628. }
  1629. } else {
  1630. smartlist_add_asprintf(reply, "512-syntax error: mapping '%s' is "
  1631. "not of expected form 'foo=bar'.", line);
  1632. log_info(LD_CONTROL, "Skipping MapAddress '%s': wrong "
  1633. "number of items.",
  1634. safe_str_client(line));
  1635. }
  1636. SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
  1637. smartlist_clear(elts);
  1638. } SMARTLIST_FOREACH_END(line);
  1639. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  1640. smartlist_free(lines);
  1641. smartlist_free(elts);
  1642. if (smartlist_len(reply)) {
  1643. ((char*)smartlist_get(reply,smartlist_len(reply)-1))[3] = ' ';
  1644. r = smartlist_join_strings(reply, "\r\n", 1, &sz);
  1645. connection_buf_add(r, sz, TO_CONN(conn));
  1646. tor_free(r);
  1647. } else {
  1648. const char *response =
  1649. "512 syntax error: not enough arguments to mapaddress.\r\n";
  1650. connection_buf_add(response, strlen(response), TO_CONN(conn));
  1651. }
  1652. SMARTLIST_FOREACH(reply, char *, cp, tor_free(cp));
  1653. smartlist_free(reply);
  1654. return 0;
  1655. }
  1656. /** Implementation helper for GETINFO: knows the answers for various
  1657. * trivial-to-implement questions. */
  1658. static int
  1659. getinfo_helper_misc(control_connection_t *conn, const char *question,
  1660. char **answer, const char **errmsg)
  1661. {
  1662. (void) conn;
  1663. if (!strcmp(question, "version")) {
  1664. *answer = tor_strdup(get_version());
  1665. } else if (!strcmp(question, "bw-event-cache")) {
  1666. *answer = get_bw_samples();
  1667. } else if (!strcmp(question, "config-file")) {
  1668. const char *a = get_torrc_fname(0);
  1669. if (a)
  1670. *answer = tor_strdup(a);
  1671. } else if (!strcmp(question, "config-defaults-file")) {
  1672. const char *a = get_torrc_fname(1);
  1673. if (a)
  1674. *answer = tor_strdup(a);
  1675. } else if (!strcmp(question, "config-text")) {
  1676. *answer = options_dump(get_options(), OPTIONS_DUMP_MINIMAL);
  1677. } else if (!strcmp(question, "config-can-saveconf")) {
  1678. *answer = tor_strdup(get_options()->IncludeUsed ? "0" : "1");
  1679. } else if (!strcmp(question, "info/names")) {
  1680. *answer = list_getinfo_options();
  1681. } else if (!strcmp(question, "dormant")) {
  1682. int dormant = rep_hist_circbuilding_dormant(time(NULL));
  1683. *answer = tor_strdup(dormant ? "1" : "0");
  1684. } else if (!strcmp(question, "events/names")) {
  1685. int i;
  1686. smartlist_t *event_names = smartlist_new();
  1687. for (i = 0; control_event_table[i].event_name != NULL; ++i) {
  1688. smartlist_add(event_names, (char *)control_event_table[i].event_name);
  1689. }
  1690. *answer = smartlist_join_strings(event_names, " ", 0, NULL);
  1691. smartlist_free(event_names);
  1692. } else if (!strcmp(question, "signal/names")) {
  1693. smartlist_t *signal_names = smartlist_new();
  1694. int j;
  1695. for (j = 0; signal_table[j].signal_name != NULL; ++j) {
  1696. smartlist_add(signal_names, (char*)signal_table[j].signal_name);
  1697. }
  1698. *answer = smartlist_join_strings(signal_names, " ", 0, NULL);
  1699. smartlist_free(signal_names);
  1700. } else if (!strcmp(question, "features/names")) {
  1701. *answer = tor_strdup("VERBOSE_NAMES EXTENDED_EVENTS");
  1702. } else if (!strcmp(question, "address")) {
  1703. uint32_t addr;
  1704. if (router_pick_published_address(get_options(), &addr, 0) < 0) {
  1705. *errmsg = "Address unknown";
  1706. return -1;
  1707. }
  1708. *answer = tor_dup_ip(addr);
  1709. } else if (!strcmp(question, "traffic/read")) {
  1710. tor_asprintf(answer, "%"PRIu64, (get_bytes_read()));
  1711. } else if (!strcmp(question, "traffic/written")) {
  1712. tor_asprintf(answer, "%"PRIu64, (get_bytes_written()));
  1713. } else if (!strcmp(question, "uptime")) {
  1714. long uptime_secs = get_uptime();
  1715. tor_asprintf(answer, "%ld", uptime_secs);
  1716. } else if (!strcmp(question, "process/pid")) {
  1717. int myPid = -1;
  1718. #ifdef _WIN32
  1719. myPid = _getpid();
  1720. #else
  1721. myPid = getpid();
  1722. #endif
  1723. tor_asprintf(answer, "%d", myPid);
  1724. } else if (!strcmp(question, "process/uid")) {
  1725. #ifdef _WIN32
  1726. *answer = tor_strdup("-1");
  1727. #else
  1728. int myUid = geteuid();
  1729. tor_asprintf(answer, "%d", myUid);
  1730. #endif /* defined(_WIN32) */
  1731. } else if (!strcmp(question, "process/user")) {
  1732. #ifdef _WIN32
  1733. *answer = tor_strdup("");
  1734. #else
  1735. int myUid = geteuid();
  1736. const struct passwd *myPwEntry = tor_getpwuid(myUid);
  1737. if (myPwEntry) {
  1738. *answer = tor_strdup(myPwEntry->pw_name);
  1739. } else {
  1740. *answer = tor_strdup("");
  1741. }
  1742. #endif /* defined(_WIN32) */
  1743. } else if (!strcmp(question, "process/descriptor-limit")) {
  1744. int max_fds = get_max_sockets();
  1745. tor_asprintf(answer, "%d", max_fds);
  1746. } else if (!strcmp(question, "limits/max-mem-in-queues")) {
  1747. tor_asprintf(answer, "%"PRIu64,
  1748. (get_options()->MaxMemInQueues));
  1749. } else if (!strcmp(question, "fingerprint")) {
  1750. crypto_pk_t *server_key;
  1751. if (!server_mode(get_options())) {
  1752. *errmsg = "Not running in server mode";
  1753. return -1;
  1754. }
  1755. server_key = get_server_identity_key();
  1756. *answer = tor_malloc(HEX_DIGEST_LEN+1);
  1757. crypto_pk_get_fingerprint(server_key, *answer, 0);
  1758. }
  1759. return 0;
  1760. }
  1761. /** Awful hack: return a newly allocated string based on a routerinfo and
  1762. * (possibly) an extrainfo, sticking the read-history and write-history from
  1763. * <b>ei</b> into the resulting string. The thing you get back won't
  1764. * necessarily have a valid signature.
  1765. *
  1766. * New code should never use this; it's for backward compatibility.
  1767. *
  1768. * NOTE: <b>ri_body</b> is as returned by signed_descriptor_get_body: it might
  1769. * not be NUL-terminated. */
  1770. static char *
  1771. munge_extrainfo_into_routerinfo(const char *ri_body,
  1772. const signed_descriptor_t *ri,
  1773. const signed_descriptor_t *ei)
  1774. {
  1775. char *out = NULL, *outp;
  1776. int i;
  1777. const char *router_sig;
  1778. const char *ei_body = signed_descriptor_get_body(ei);
  1779. size_t ri_len = ri->signed_descriptor_len;
  1780. size_t ei_len = ei->signed_descriptor_len;
  1781. if (!ei_body)
  1782. goto bail;
  1783. outp = out = tor_malloc(ri_len+ei_len+1);
  1784. if (!(router_sig = tor_memstr(ri_body, ri_len, "\nrouter-signature")))
  1785. goto bail;
  1786. ++router_sig;
  1787. memcpy(out, ri_body, router_sig-ri_body);
  1788. outp += router_sig-ri_body;
  1789. for (i=0; i < 2; ++i) {
  1790. const char *kwd = i ? "\nwrite-history " : "\nread-history ";
  1791. const char *cp, *eol;
  1792. if (!(cp = tor_memstr(ei_body, ei_len, kwd)))
  1793. continue;
  1794. ++cp;
  1795. if (!(eol = memchr(cp, '\n', ei_len - (cp-ei_body))))
  1796. continue;
  1797. memcpy(outp, cp, eol-cp+1);
  1798. outp += eol-cp+1;
  1799. }
  1800. memcpy(outp, router_sig, ri_len - (router_sig-ri_body));
  1801. *outp++ = '\0';
  1802. tor_assert(outp-out < (int)(ri_len+ei_len+1));
  1803. return out;
  1804. bail:
  1805. tor_free(out);
  1806. return tor_strndup(ri_body, ri->signed_descriptor_len);
  1807. }
  1808. /** Implementation helper for GETINFO: answers requests for information about
  1809. * which ports are bound. */
  1810. static int
  1811. getinfo_helper_listeners(control_connection_t *control_conn,
  1812. const char *question,
  1813. char **answer, const char **errmsg)
  1814. {
  1815. int type;
  1816. smartlist_t *res;
  1817. (void)control_conn;
  1818. (void)errmsg;
  1819. if (!strcmp(question, "net/listeners/or"))
  1820. type = CONN_TYPE_OR_LISTENER;
  1821. else if (!strcmp(question, "net/listeners/extor"))
  1822. type = CONN_TYPE_EXT_OR_LISTENER;
  1823. else if (!strcmp(question, "net/listeners/dir"))
  1824. type = CONN_TYPE_DIR_LISTENER;
  1825. else if (!strcmp(question, "net/listeners/socks"))
  1826. type = CONN_TYPE_AP_LISTENER;
  1827. else if (!strcmp(question, "net/listeners/trans"))
  1828. type = CONN_TYPE_AP_TRANS_LISTENER;
  1829. else if (!strcmp(question, "net/listeners/natd"))
  1830. type = CONN_TYPE_AP_NATD_LISTENER;
  1831. else if (!strcmp(question, "net/listeners/httptunnel"))
  1832. type = CONN_TYPE_AP_HTTP_CONNECT_LISTENER;
  1833. else if (!strcmp(question, "net/listeners/dns"))
  1834. type = CONN_TYPE_AP_DNS_LISTENER;
  1835. else if (!strcmp(question, "net/listeners/control"))
  1836. type = CONN_TYPE_CONTROL_LISTENER;
  1837. else
  1838. return 0; /* unknown key */
  1839. res = smartlist_new();
  1840. SMARTLIST_FOREACH_BEGIN(get_connection_array(), connection_t *, conn) {
  1841. struct sockaddr_storage ss;
  1842. socklen_t ss_len = sizeof(ss);
  1843. if (conn->type != type || conn->marked_for_close || !SOCKET_OK(conn->s))
  1844. continue;
  1845. if (getsockname(conn->s, (struct sockaddr *)&ss, &ss_len) < 0) {
  1846. smartlist_add_asprintf(res, "%s:%d", conn->address, (int)conn->port);
  1847. } else {
  1848. char *tmp = tor_sockaddr_to_str((struct sockaddr *)&ss);
  1849. smartlist_add(res, esc_for_log(tmp));
  1850. tor_free(tmp);
  1851. }
  1852. } SMARTLIST_FOREACH_END(conn);
  1853. *answer = smartlist_join_strings(res, " ", 0, NULL);
  1854. SMARTLIST_FOREACH(res, char *, cp, tor_free(cp));
  1855. smartlist_free(res);
  1856. return 0;
  1857. }
  1858. /** Implementation helper for GETINFO: answers requests for information about
  1859. * the current time in both local and UTC forms. */
  1860. STATIC int
  1861. getinfo_helper_current_time(control_connection_t *control_conn,
  1862. const char *question,
  1863. char **answer, const char **errmsg)
  1864. {
  1865. (void)control_conn;
  1866. (void)errmsg;
  1867. struct timeval now;
  1868. tor_gettimeofday(&now);
  1869. char timebuf[ISO_TIME_LEN+1];
  1870. if (!strcmp(question, "current-time/local"))
  1871. format_local_iso_time_nospace(timebuf, (time_t)now.tv_sec);
  1872. else if (!strcmp(question, "current-time/utc"))
  1873. format_iso_time_nospace(timebuf, (time_t)now.tv_sec);
  1874. else
  1875. return 0;
  1876. *answer = tor_strdup(timebuf);
  1877. return 0;
  1878. }
  1879. /** Implementation helper for GETINFO: knows the answers for questions about
  1880. * directory information. */
  1881. STATIC int
  1882. getinfo_helper_dir(control_connection_t *control_conn,
  1883. const char *question, char **answer,
  1884. const char **errmsg)
  1885. {
  1886. (void) control_conn;
  1887. if (!strcmpstart(question, "desc/id/")) {
  1888. const routerinfo_t *ri = NULL;
  1889. const node_t *node = node_get_by_hex_id(question+strlen("desc/id/"), 0);
  1890. if (node)
  1891. ri = node->ri;
  1892. if (ri) {
  1893. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1894. if (body)
  1895. *answer = tor_strndup(body, ri->cache_info.signed_descriptor_len);
  1896. } else if (! we_fetch_router_descriptors(get_options())) {
  1897. /* Descriptors won't be available, provide proper error */
  1898. *errmsg = "We fetch microdescriptors, not router "
  1899. "descriptors. You'll need to use md/id/* "
  1900. "instead of desc/id/*.";
  1901. return 0;
  1902. }
  1903. } else if (!strcmpstart(question, "desc/name/")) {
  1904. const routerinfo_t *ri = NULL;
  1905. /* XXX Setting 'warn_if_unnamed' here is a bit silly -- the
  1906. * warning goes to the user, not to the controller. */
  1907. const node_t *node =
  1908. node_get_by_nickname(question+strlen("desc/name/"), 0);
  1909. if (node)
  1910. ri = node->ri;
  1911. if (ri) {
  1912. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1913. if (body)
  1914. *answer = tor_strndup(body, ri->cache_info.signed_descriptor_len);
  1915. } else if (! we_fetch_router_descriptors(get_options())) {
  1916. /* Descriptors won't be available, provide proper error */
  1917. *errmsg = "We fetch microdescriptors, not router "
  1918. "descriptors. You'll need to use md/name/* "
  1919. "instead of desc/name/*.";
  1920. return 0;
  1921. }
  1922. } else if (!strcmp(question, "desc/download-enabled")) {
  1923. int r = we_fetch_router_descriptors(get_options());
  1924. tor_asprintf(answer, "%d", !!r);
  1925. } else if (!strcmp(question, "desc/all-recent")) {
  1926. routerlist_t *routerlist = router_get_routerlist();
  1927. smartlist_t *sl = smartlist_new();
  1928. if (routerlist && routerlist->routers) {
  1929. SMARTLIST_FOREACH(routerlist->routers, const routerinfo_t *, ri,
  1930. {
  1931. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1932. if (body)
  1933. smartlist_add(sl,
  1934. tor_strndup(body, ri->cache_info.signed_descriptor_len));
  1935. });
  1936. }
  1937. *answer = smartlist_join_strings(sl, "", 0, NULL);
  1938. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  1939. smartlist_free(sl);
  1940. } else if (!strcmp(question, "desc/all-recent-extrainfo-hack")) {
  1941. /* XXXX Remove this once Torstat asks for extrainfos. */
  1942. routerlist_t *routerlist = router_get_routerlist();
  1943. smartlist_t *sl = smartlist_new();
  1944. if (routerlist && routerlist->routers) {
  1945. SMARTLIST_FOREACH_BEGIN(routerlist->routers, const routerinfo_t *, ri) {
  1946. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1947. signed_descriptor_t *ei = extrainfo_get_by_descriptor_digest(
  1948. ri->cache_info.extra_info_digest);
  1949. if (ei && body) {
  1950. smartlist_add(sl, munge_extrainfo_into_routerinfo(body,
  1951. &ri->cache_info, ei));
  1952. } else if (body) {
  1953. smartlist_add(sl,
  1954. tor_strndup(body, ri->cache_info.signed_descriptor_len));
  1955. }
  1956. } SMARTLIST_FOREACH_END(ri);
  1957. }
  1958. *answer = smartlist_join_strings(sl, "", 0, NULL);
  1959. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  1960. smartlist_free(sl);
  1961. } else if (!strcmpstart(question, "hs/client/desc/id/")) {
  1962. hostname_type_t addr_type;
  1963. question += strlen("hs/client/desc/id/");
  1964. if (rend_valid_v2_service_id(question)) {
  1965. addr_type = ONION_V2_HOSTNAME;
  1966. } else if (hs_address_is_valid(question)) {
  1967. addr_type = ONION_V3_HOSTNAME;
  1968. } else {
  1969. *errmsg = "Invalid address";
  1970. return -1;
  1971. }
  1972. if (addr_type == ONION_V2_HOSTNAME) {
  1973. rend_cache_entry_t *e = NULL;
  1974. if (!rend_cache_lookup_entry(question, -1, &e)) {
  1975. /* Descriptor found in cache */
  1976. *answer = tor_strdup(e->desc);
  1977. } else {
  1978. *errmsg = "Not found in cache";
  1979. return -1;
  1980. }
  1981. } else {
  1982. ed25519_public_key_t service_pk;
  1983. const char *desc;
  1984. /* The check before this if/else makes sure of this. */
  1985. tor_assert(addr_type == ONION_V3_HOSTNAME);
  1986. if (hs_parse_address(question, &service_pk, NULL, NULL) < 0) {
  1987. *errmsg = "Invalid v3 address";
  1988. return -1;
  1989. }
  1990. desc = hs_cache_lookup_encoded_as_client(&service_pk);
  1991. if (desc) {
  1992. *answer = tor_strdup(desc);
  1993. } else {
  1994. *errmsg = "Not found in cache";
  1995. return -1;
  1996. }
  1997. }
  1998. } else if (!strcmpstart(question, "hs/service/desc/id/")) {
  1999. hostname_type_t addr_type;
  2000. question += strlen("hs/service/desc/id/");
  2001. if (rend_valid_v2_service_id(question)) {
  2002. addr_type = ONION_V2_HOSTNAME;
  2003. } else if (hs_address_is_valid(question)) {
  2004. addr_type = ONION_V3_HOSTNAME;
  2005. } else {
  2006. *errmsg = "Invalid address";
  2007. return -1;
  2008. }
  2009. rend_cache_entry_t *e = NULL;
  2010. if (addr_type == ONION_V2_HOSTNAME) {
  2011. if (!rend_cache_lookup_v2_desc_as_service(question, &e)) {
  2012. /* Descriptor found in cache */
  2013. *answer = tor_strdup(e->desc);
  2014. } else {
  2015. *errmsg = "Not found in cache";
  2016. return -1;
  2017. }
  2018. } else {
  2019. ed25519_public_key_t service_pk;
  2020. char *desc;
  2021. /* The check before this if/else makes sure of this. */
  2022. tor_assert(addr_type == ONION_V3_HOSTNAME);
  2023. if (hs_parse_address(question, &service_pk, NULL, NULL) < 0) {
  2024. *errmsg = "Invalid v3 address";
  2025. return -1;
  2026. }
  2027. desc = hs_service_lookup_current_desc(&service_pk);
  2028. if (desc) {
  2029. /* Newly allocated string, we have ownership. */
  2030. *answer = desc;
  2031. } else {
  2032. *errmsg = "Not found in cache";
  2033. return -1;
  2034. }
  2035. }
  2036. } else if (!strcmp(question, "md/all")) {
  2037. const smartlist_t *nodes = nodelist_get_list();
  2038. tor_assert(nodes);
  2039. if (smartlist_len(nodes) == 0) {
  2040. *answer = tor_strdup("");
  2041. return 0;
  2042. }
  2043. smartlist_t *microdescs = smartlist_new();
  2044. SMARTLIST_FOREACH_BEGIN(nodes, node_t *, n) {
  2045. if (n->md && n->md->body) {
  2046. char *copy = tor_strndup(n->md->body, n->md->bodylen);
  2047. smartlist_add(microdescs, copy);
  2048. }
  2049. } SMARTLIST_FOREACH_END(n);
  2050. *answer = smartlist_join_strings(microdescs, "", 0, NULL);
  2051. SMARTLIST_FOREACH(microdescs, char *, md, tor_free(md));
  2052. smartlist_free(microdescs);
  2053. } else if (!strcmpstart(question, "md/id/")) {
  2054. const node_t *node = node_get_by_hex_id(question+strlen("md/id/"), 0);
  2055. const microdesc_t *md = NULL;
  2056. if (node) md = node->md;
  2057. if (md && md->body) {
  2058. *answer = tor_strndup(md->body, md->bodylen);
  2059. }
  2060. } else if (!strcmpstart(question, "md/name/")) {
  2061. /* XXX Setting 'warn_if_unnamed' here is a bit silly -- the
  2062. * warning goes to the user, not to the controller. */
  2063. const node_t *node = node_get_by_nickname(question+strlen("md/name/"), 0);
  2064. /* XXXX duplicated code */
  2065. const microdesc_t *md = NULL;
  2066. if (node) md = node->md;
  2067. if (md && md->body) {
  2068. *answer = tor_strndup(md->body, md->bodylen);
  2069. }
  2070. } else if (!strcmp(question, "md/download-enabled")) {
  2071. int r = we_fetch_microdescriptors(get_options());
  2072. tor_asprintf(answer, "%d", !!r);
  2073. } else if (!strcmpstart(question, "desc-annotations/id/")) {
  2074. const routerinfo_t *ri = NULL;
  2075. const node_t *node =
  2076. node_get_by_hex_id(question+strlen("desc-annotations/id/"), 0);
  2077. if (node)
  2078. ri = node->ri;
  2079. if (ri) {
  2080. const char *annotations =
  2081. signed_descriptor_get_annotations(&ri->cache_info);
  2082. if (annotations)
  2083. *answer = tor_strndup(annotations,
  2084. ri->cache_info.annotations_len);
  2085. }
  2086. } else if (!strcmpstart(question, "dir/server/")) {
  2087. size_t answer_len = 0;
  2088. char *url = NULL;
  2089. smartlist_t *descs = smartlist_new();
  2090. const char *msg;
  2091. int res;
  2092. char *cp;
  2093. tor_asprintf(&url, "/tor/%s", question+4);
  2094. res = dirserv_get_routerdescs(descs, url, &msg);
  2095. if (res) {
  2096. log_warn(LD_CONTROL, "getinfo '%s': %s", question, msg);
  2097. smartlist_free(descs);
  2098. tor_free(url);
  2099. *errmsg = msg;
  2100. return -1;
  2101. }
  2102. SMARTLIST_FOREACH(descs, signed_descriptor_t *, sd,
  2103. answer_len += sd->signed_descriptor_len);
  2104. cp = *answer = tor_malloc(answer_len+1);
  2105. SMARTLIST_FOREACH(descs, signed_descriptor_t *, sd,
  2106. {
  2107. memcpy(cp, signed_descriptor_get_body(sd),
  2108. sd->signed_descriptor_len);
  2109. cp += sd->signed_descriptor_len;
  2110. });
  2111. *cp = '\0';
  2112. tor_free(url);
  2113. smartlist_free(descs);
  2114. } else if (!strcmpstart(question, "dir/status/")) {
  2115. *answer = tor_strdup("");
  2116. } else if (!strcmp(question, "dir/status-vote/current/consensus")) { /* v3 */
  2117. if (we_want_to_fetch_flavor(get_options(), FLAV_NS)) {
  2118. const cached_dir_t *consensus = dirserv_get_consensus("ns");
  2119. if (consensus)
  2120. *answer = tor_strdup(consensus->dir);
  2121. }
  2122. if (!*answer) { /* try loading it from disk */
  2123. *answer = networkstatus_read_cached_consensus("ns");
  2124. if (!*answer) { /* generate an error */
  2125. *errmsg = "Could not open cached consensus. "
  2126. "Make sure FetchUselessDescriptors is set to 1.";
  2127. return -1;
  2128. }
  2129. }
  2130. } else if (!strcmp(question, "network-status")) { /* v1 */
  2131. static int network_status_warned = 0;
  2132. if (!network_status_warned) {
  2133. log_warn(LD_CONTROL, "GETINFO network-status is deprecated; it will "
  2134. "go away in a future version of Tor.");
  2135. network_status_warned = 1;
  2136. }
  2137. routerlist_t *routerlist = router_get_routerlist();
  2138. if (!routerlist || !routerlist->routers ||
  2139. list_server_status_v1(routerlist->routers, answer, 1) < 0) {
  2140. return -1;
  2141. }
  2142. } else if (!strcmpstart(question, "extra-info/digest/")) {
  2143. question += strlen("extra-info/digest/");
  2144. if (strlen(question) == HEX_DIGEST_LEN) {
  2145. char d[DIGEST_LEN];
  2146. signed_descriptor_t *sd = NULL;
  2147. if (base16_decode(d, sizeof(d), question, strlen(question))
  2148. == sizeof(d)) {
  2149. /* XXXX this test should move into extrainfo_get_by_descriptor_digest,
  2150. * but I don't want to risk affecting other parts of the code,
  2151. * especially since the rules for using our own extrainfo (including
  2152. * when it might be freed) are different from those for using one
  2153. * we have downloaded. */
  2154. if (router_extrainfo_digest_is_me(d))
  2155. sd = &(router_get_my_extrainfo()->cache_info);
  2156. else
  2157. sd = extrainfo_get_by_descriptor_digest(d);
  2158. }
  2159. if (sd) {
  2160. const char *body = signed_descriptor_get_body(sd);
  2161. if (body)
  2162. *answer = tor_strndup(body, sd->signed_descriptor_len);
  2163. }
  2164. }
  2165. }
  2166. return 0;
  2167. }
  2168. /** Given a smartlist of 20-byte digests, return a newly allocated string
  2169. * containing each of those digests in order, formatted in HEX, and terminated
  2170. * with a newline. */
  2171. static char *
  2172. digest_list_to_string(const smartlist_t *sl)
  2173. {
  2174. int len;
  2175. char *result, *s;
  2176. /* Allow for newlines, and a \0 at the end */
  2177. len = smartlist_len(sl) * (HEX_DIGEST_LEN + 1) + 1;
  2178. result = tor_malloc_zero(len);
  2179. s = result;
  2180. SMARTLIST_FOREACH_BEGIN(sl, const char *, digest) {
  2181. base16_encode(s, HEX_DIGEST_LEN + 1, digest, DIGEST_LEN);
  2182. s[HEX_DIGEST_LEN] = '\n';
  2183. s += HEX_DIGEST_LEN + 1;
  2184. } SMARTLIST_FOREACH_END(digest);
  2185. *s = '\0';
  2186. return result;
  2187. }
  2188. /** Turn a download_status_t into a human-readable description in a newly
  2189. * allocated string. The format is specified in control-spec.txt, under
  2190. * the documentation for "GETINFO download/..." . */
  2191. static char *
  2192. download_status_to_string(const download_status_t *dl)
  2193. {
  2194. char *rv = NULL;
  2195. char tbuf[ISO_TIME_LEN+1];
  2196. const char *schedule_str, *want_authority_str;
  2197. const char *increment_on_str, *backoff_str;
  2198. if (dl) {
  2199. /* Get some substrings of the eventual output ready */
  2200. format_iso_time(tbuf, download_status_get_next_attempt_at(dl));
  2201. switch (dl->schedule) {
  2202. case DL_SCHED_GENERIC:
  2203. schedule_str = "DL_SCHED_GENERIC";
  2204. break;
  2205. case DL_SCHED_CONSENSUS:
  2206. schedule_str = "DL_SCHED_CONSENSUS";
  2207. break;
  2208. case DL_SCHED_BRIDGE:
  2209. schedule_str = "DL_SCHED_BRIDGE";
  2210. break;
  2211. default:
  2212. schedule_str = "unknown";
  2213. break;
  2214. }
  2215. switch (dl->want_authority) {
  2216. case DL_WANT_ANY_DIRSERVER:
  2217. want_authority_str = "DL_WANT_ANY_DIRSERVER";
  2218. break;
  2219. case DL_WANT_AUTHORITY:
  2220. want_authority_str = "DL_WANT_AUTHORITY";
  2221. break;
  2222. default:
  2223. want_authority_str = "unknown";
  2224. break;
  2225. }
  2226. switch (dl->increment_on) {
  2227. case DL_SCHED_INCREMENT_FAILURE:
  2228. increment_on_str = "DL_SCHED_INCREMENT_FAILURE";
  2229. break;
  2230. case DL_SCHED_INCREMENT_ATTEMPT:
  2231. increment_on_str = "DL_SCHED_INCREMENT_ATTEMPT";
  2232. break;
  2233. default:
  2234. increment_on_str = "unknown";
  2235. break;
  2236. }
  2237. backoff_str = "DL_SCHED_RANDOM_EXPONENTIAL";
  2238. /* Now assemble them */
  2239. tor_asprintf(&rv,
  2240. "next-attempt-at %s\n"
  2241. "n-download-failures %u\n"
  2242. "n-download-attempts %u\n"
  2243. "schedule %s\n"
  2244. "want-authority %s\n"
  2245. "increment-on %s\n"
  2246. "backoff %s\n"
  2247. "last-backoff-position %u\n"
  2248. "last-delay-used %d\n",
  2249. tbuf,
  2250. dl->n_download_failures,
  2251. dl->n_download_attempts,
  2252. schedule_str,
  2253. want_authority_str,
  2254. increment_on_str,
  2255. backoff_str,
  2256. dl->last_backoff_position,
  2257. dl->last_delay_used);
  2258. }
  2259. return rv;
  2260. }
  2261. /** Handle the consensus download cases for getinfo_helper_downloads() */
  2262. STATIC void
  2263. getinfo_helper_downloads_networkstatus(const char *flavor,
  2264. download_status_t **dl_to_emit,
  2265. const char **errmsg)
  2266. {
  2267. /*
  2268. * We get the one for the current bootstrapped status by default, or
  2269. * take an extra /bootstrap or /running suffix
  2270. */
  2271. if (strcmp(flavor, "ns") == 0) {
  2272. *dl_to_emit = networkstatus_get_dl_status_by_flavor(FLAV_NS);
  2273. } else if (strcmp(flavor, "ns/bootstrap") == 0) {
  2274. *dl_to_emit = networkstatus_get_dl_status_by_flavor_bootstrap(FLAV_NS);
  2275. } else if (strcmp(flavor, "ns/running") == 0 ) {
  2276. *dl_to_emit = networkstatus_get_dl_status_by_flavor_running(FLAV_NS);
  2277. } else if (strcmp(flavor, "microdesc") == 0) {
  2278. *dl_to_emit = networkstatus_get_dl_status_by_flavor(FLAV_MICRODESC);
  2279. } else if (strcmp(flavor, "microdesc/bootstrap") == 0) {
  2280. *dl_to_emit =
  2281. networkstatus_get_dl_status_by_flavor_bootstrap(FLAV_MICRODESC);
  2282. } else if (strcmp(flavor, "microdesc/running") == 0) {
  2283. *dl_to_emit =
  2284. networkstatus_get_dl_status_by_flavor_running(FLAV_MICRODESC);
  2285. } else {
  2286. *errmsg = "Unknown flavor";
  2287. }
  2288. }
  2289. /** Handle the cert download cases for getinfo_helper_downloads() */
  2290. STATIC void
  2291. getinfo_helper_downloads_cert(const char *fp_sk_req,
  2292. download_status_t **dl_to_emit,
  2293. smartlist_t **digest_list,
  2294. const char **errmsg)
  2295. {
  2296. const char *sk_req;
  2297. char id_digest[DIGEST_LEN];
  2298. char sk_digest[DIGEST_LEN];
  2299. /*
  2300. * We have to handle four cases; fp_sk_req is the request with
  2301. * a prefix of "downloads/cert/" snipped off.
  2302. *
  2303. * Case 1: fp_sk_req = "fps"
  2304. * - We should emit a digest_list with a list of all the identity
  2305. * fingerprints that can be queried for certificate download status;
  2306. * get it by calling list_authority_ids_with_downloads().
  2307. *
  2308. * Case 2: fp_sk_req = "fp/<fp>" for some fingerprint fp
  2309. * - We want the default certificate for this identity fingerprint's
  2310. * download status; this is the download we get from URLs starting
  2311. * in /fp/ on the directory server. We can get it with
  2312. * id_only_download_status_for_authority_id().
  2313. *
  2314. * Case 3: fp_sk_req = "fp/<fp>/sks" for some fingerprint fp
  2315. * - We want a list of all signing key digests for this identity
  2316. * fingerprint which can be queried for certificate download status.
  2317. * Get it with list_sk_digests_for_authority_id().
  2318. *
  2319. * Case 4: fp_sk_req = "fp/<fp>/<sk>" for some fingerprint fp and
  2320. * signing key digest sk
  2321. * - We want the download status for the certificate for this specific
  2322. * signing key and fingerprint. These correspond to the ones we get
  2323. * from URLs starting in /fp-sk/ on the directory server. Get it with
  2324. * list_sk_digests_for_authority_id().
  2325. */
  2326. if (strcmp(fp_sk_req, "fps") == 0) {
  2327. *digest_list = list_authority_ids_with_downloads();
  2328. if (!(*digest_list)) {
  2329. *errmsg = "Failed to get list of authority identity digests (!)";
  2330. }
  2331. } else if (!strcmpstart(fp_sk_req, "fp/")) {
  2332. fp_sk_req += strlen("fp/");
  2333. /* Okay, look for another / to tell the fp from fp-sk cases */
  2334. sk_req = strchr(fp_sk_req, '/');
  2335. if (sk_req) {
  2336. /* okay, split it here and try to parse <fp> */
  2337. if (base16_decode(id_digest, DIGEST_LEN,
  2338. fp_sk_req, sk_req - fp_sk_req) == DIGEST_LEN) {
  2339. /* Skip past the '/' */
  2340. ++sk_req;
  2341. if (strcmp(sk_req, "sks") == 0) {
  2342. /* We're asking for the list of signing key fingerprints */
  2343. *digest_list = list_sk_digests_for_authority_id(id_digest);
  2344. if (!(*digest_list)) {
  2345. *errmsg = "Failed to get list of signing key digests for this "
  2346. "authority identity digest";
  2347. }
  2348. } else {
  2349. /* We've got a signing key digest */
  2350. if (base16_decode(sk_digest, DIGEST_LEN,
  2351. sk_req, strlen(sk_req)) == DIGEST_LEN) {
  2352. *dl_to_emit =
  2353. download_status_for_authority_id_and_sk(id_digest, sk_digest);
  2354. if (!(*dl_to_emit)) {
  2355. *errmsg = "Failed to get download status for this identity/"
  2356. "signing key digest pair";
  2357. }
  2358. } else {
  2359. *errmsg = "That didn't look like a signing key digest";
  2360. }
  2361. }
  2362. } else {
  2363. *errmsg = "That didn't look like an identity digest";
  2364. }
  2365. } else {
  2366. /* We're either in downloads/certs/fp/<fp>, or we can't parse <fp> */
  2367. if (strlen(fp_sk_req) == HEX_DIGEST_LEN) {
  2368. if (base16_decode(id_digest, DIGEST_LEN,
  2369. fp_sk_req, strlen(fp_sk_req)) == DIGEST_LEN) {
  2370. *dl_to_emit = id_only_download_status_for_authority_id(id_digest);
  2371. if (!(*dl_to_emit)) {
  2372. *errmsg = "Failed to get download status for this authority "
  2373. "identity digest";
  2374. }
  2375. } else {
  2376. *errmsg = "That didn't look like a digest";
  2377. }
  2378. } else {
  2379. *errmsg = "That didn't look like a digest";
  2380. }
  2381. }
  2382. } else {
  2383. *errmsg = "Unknown certificate download status query";
  2384. }
  2385. }
  2386. /** Handle the routerdesc download cases for getinfo_helper_downloads() */
  2387. STATIC void
  2388. getinfo_helper_downloads_desc(const char *desc_req,
  2389. download_status_t **dl_to_emit,
  2390. smartlist_t **digest_list,
  2391. const char **errmsg)
  2392. {
  2393. char desc_digest[DIGEST_LEN];
  2394. /*
  2395. * Two cases to handle here:
  2396. *
  2397. * Case 1: desc_req = "descs"
  2398. * - Emit a list of all router descriptor digests, which we get by
  2399. * calling router_get_descriptor_digests(); this can return NULL
  2400. * if we have no current ns-flavor consensus.
  2401. *
  2402. * Case 2: desc_req = <fp>
  2403. * - Check on the specified fingerprint and emit its download_status_t
  2404. * using router_get_dl_status_by_descriptor_digest().
  2405. */
  2406. if (strcmp(desc_req, "descs") == 0) {
  2407. *digest_list = router_get_descriptor_digests();
  2408. if (!(*digest_list)) {
  2409. *errmsg = "We don't seem to have a networkstatus-flavored consensus";
  2410. }
  2411. /*
  2412. * Microdescs don't use the download_status_t mechanism, so we don't
  2413. * answer queries about their downloads here; see microdesc.c.
  2414. */
  2415. } else if (strlen(desc_req) == HEX_DIGEST_LEN) {
  2416. if (base16_decode(desc_digest, DIGEST_LEN,
  2417. desc_req, strlen(desc_req)) == DIGEST_LEN) {
  2418. /* Okay we got a digest-shaped thing; try asking for it */
  2419. *dl_to_emit = router_get_dl_status_by_descriptor_digest(desc_digest);
  2420. if (!(*dl_to_emit)) {
  2421. *errmsg = "No such descriptor digest found";
  2422. }
  2423. } else {
  2424. *errmsg = "That didn't look like a digest";
  2425. }
  2426. } else {
  2427. *errmsg = "Unknown router descriptor download status query";
  2428. }
  2429. }
  2430. /** Handle the bridge download cases for getinfo_helper_downloads() */
  2431. STATIC void
  2432. getinfo_helper_downloads_bridge(const char *bridge_req,
  2433. download_status_t **dl_to_emit,
  2434. smartlist_t **digest_list,
  2435. const char **errmsg)
  2436. {
  2437. char bridge_digest[DIGEST_LEN];
  2438. /*
  2439. * Two cases to handle here:
  2440. *
  2441. * Case 1: bridge_req = "bridges"
  2442. * - Emit a list of all bridge identity digests, which we get by
  2443. * calling list_bridge_identities(); this can return NULL if we are
  2444. * not using bridges.
  2445. *
  2446. * Case 2: bridge_req = <fp>
  2447. * - Check on the specified fingerprint and emit its download_status_t
  2448. * using get_bridge_dl_status_by_id().
  2449. */
  2450. if (strcmp(bridge_req, "bridges") == 0) {
  2451. *digest_list = list_bridge_identities();
  2452. if (!(*digest_list)) {
  2453. *errmsg = "We don't seem to be using bridges";
  2454. }
  2455. } else if (strlen(bridge_req) == HEX_DIGEST_LEN) {
  2456. if (base16_decode(bridge_digest, DIGEST_LEN,
  2457. bridge_req, strlen(bridge_req)) == DIGEST_LEN) {
  2458. /* Okay we got a digest-shaped thing; try asking for it */
  2459. *dl_to_emit = get_bridge_dl_status_by_id(bridge_digest);
  2460. if (!(*dl_to_emit)) {
  2461. *errmsg = "No such bridge identity digest found";
  2462. }
  2463. } else {
  2464. *errmsg = "That didn't look like a digest";
  2465. }
  2466. } else {
  2467. *errmsg = "Unknown bridge descriptor download status query";
  2468. }
  2469. }
  2470. /** Implementation helper for GETINFO: knows the answers for questions about
  2471. * download status information. */
  2472. STATIC int
  2473. getinfo_helper_downloads(control_connection_t *control_conn,
  2474. const char *question, char **answer,
  2475. const char **errmsg)
  2476. {
  2477. download_status_t *dl_to_emit = NULL;
  2478. smartlist_t *digest_list = NULL;
  2479. /* Assert args are sane */
  2480. tor_assert(control_conn != NULL);
  2481. tor_assert(question != NULL);
  2482. tor_assert(answer != NULL);
  2483. tor_assert(errmsg != NULL);
  2484. /* We check for this later to see if we should supply a default */
  2485. *errmsg = NULL;
  2486. /* Are we after networkstatus downloads? */
  2487. if (!strcmpstart(question, "downloads/networkstatus/")) {
  2488. getinfo_helper_downloads_networkstatus(
  2489. question + strlen("downloads/networkstatus/"),
  2490. &dl_to_emit, errmsg);
  2491. /* Certificates? */
  2492. } else if (!strcmpstart(question, "downloads/cert/")) {
  2493. getinfo_helper_downloads_cert(
  2494. question + strlen("downloads/cert/"),
  2495. &dl_to_emit, &digest_list, errmsg);
  2496. /* Router descriptors? */
  2497. } else if (!strcmpstart(question, "downloads/desc/")) {
  2498. getinfo_helper_downloads_desc(
  2499. question + strlen("downloads/desc/"),
  2500. &dl_to_emit, &digest_list, errmsg);
  2501. /* Bridge descriptors? */
  2502. } else if (!strcmpstart(question, "downloads/bridge/")) {
  2503. getinfo_helper_downloads_bridge(
  2504. question + strlen("downloads/bridge/"),
  2505. &dl_to_emit, &digest_list, errmsg);
  2506. } else {
  2507. *errmsg = "Unknown download status query";
  2508. }
  2509. if (dl_to_emit) {
  2510. *answer = download_status_to_string(dl_to_emit);
  2511. return 0;
  2512. } else if (digest_list) {
  2513. *answer = digest_list_to_string(digest_list);
  2514. SMARTLIST_FOREACH(digest_list, void *, s, tor_free(s));
  2515. smartlist_free(digest_list);
  2516. return 0;
  2517. } else {
  2518. if (!(*errmsg)) {
  2519. *errmsg = "Unknown error";
  2520. }
  2521. return -1;
  2522. }
  2523. }
  2524. /** Allocate and return a description of <b>circ</b>'s current status,
  2525. * including its path (if any). */
  2526. static char *
  2527. circuit_describe_status_for_controller(origin_circuit_t *circ)
  2528. {
  2529. char *rv;
  2530. smartlist_t *descparts = smartlist_new();
  2531. {
  2532. char *vpath = circuit_list_path_for_controller(circ);
  2533. if (*vpath) {
  2534. smartlist_add(descparts, vpath);
  2535. } else {
  2536. tor_free(vpath); /* empty path; don't put an extra space in the result */
  2537. }
  2538. }
  2539. {
  2540. cpath_build_state_t *build_state = circ->build_state;
  2541. smartlist_t *flaglist = smartlist_new();
  2542. char *flaglist_joined;
  2543. if (build_state->onehop_tunnel)
  2544. smartlist_add(flaglist, (void *)"ONEHOP_TUNNEL");
  2545. if (build_state->is_internal)
  2546. smartlist_add(flaglist, (void *)"IS_INTERNAL");
  2547. if (build_state->need_capacity)
  2548. smartlist_add(flaglist, (void *)"NEED_CAPACITY");
  2549. if (build_state->need_uptime)
  2550. smartlist_add(flaglist, (void *)"NEED_UPTIME");
  2551. /* Only emit a BUILD_FLAGS argument if it will have a non-empty value. */
  2552. if (smartlist_len(flaglist)) {
  2553. flaglist_joined = smartlist_join_strings(flaglist, ",", 0, NULL);
  2554. smartlist_add_asprintf(descparts, "BUILD_FLAGS=%s", flaglist_joined);
  2555. tor_free(flaglist_joined);
  2556. }
  2557. smartlist_free(flaglist);
  2558. }
  2559. smartlist_add_asprintf(descparts, "PURPOSE=%s",
  2560. circuit_purpose_to_controller_string(circ->base_.purpose));
  2561. {
  2562. const char *hs_state =
  2563. circuit_purpose_to_controller_hs_state_string(circ->base_.purpose);
  2564. if (hs_state != NULL) {
  2565. smartlist_add_asprintf(descparts, "HS_STATE=%s", hs_state);
  2566. }
  2567. }
  2568. if (circ->rend_data != NULL || circ->hs_ident != NULL) {
  2569. char addr[HS_SERVICE_ADDR_LEN_BASE32 + 1];
  2570. const char *onion_address;
  2571. if (circ->rend_data) {
  2572. onion_address = rend_data_get_address(circ->rend_data);
  2573. } else {
  2574. hs_build_address(&circ->hs_ident->identity_pk, HS_VERSION_THREE, addr);
  2575. onion_address = addr;
  2576. }
  2577. smartlist_add_asprintf(descparts, "REND_QUERY=%s", onion_address);
  2578. }
  2579. {
  2580. char tbuf[ISO_TIME_USEC_LEN+1];
  2581. format_iso_time_nospace_usec(tbuf, &circ->base_.timestamp_created);
  2582. smartlist_add_asprintf(descparts, "TIME_CREATED=%s", tbuf);
  2583. }
  2584. // Show username and/or password if available.
  2585. if (circ->socks_username_len > 0) {
  2586. char* socks_username_escaped = esc_for_log_len(circ->socks_username,
  2587. (size_t) circ->socks_username_len);
  2588. smartlist_add_asprintf(descparts, "SOCKS_USERNAME=%s",
  2589. socks_username_escaped);
  2590. tor_free(socks_username_escaped);
  2591. }
  2592. if (circ->socks_password_len > 0) {
  2593. char* socks_password_escaped = esc_for_log_len(circ->socks_password,
  2594. (size_t) circ->socks_password_len);
  2595. smartlist_add_asprintf(descparts, "SOCKS_PASSWORD=%s",
  2596. socks_password_escaped);
  2597. tor_free(socks_password_escaped);
  2598. }
  2599. rv = smartlist_join_strings(descparts, " ", 0, NULL);
  2600. SMARTLIST_FOREACH(descparts, char *, cp, tor_free(cp));
  2601. smartlist_free(descparts);
  2602. return rv;
  2603. }
  2604. /** Implementation helper for GETINFO: knows how to generate summaries of the
  2605. * current states of things we send events about. */
  2606. static int
  2607. getinfo_helper_events(control_connection_t *control_conn,
  2608. const char *question, char **answer,
  2609. const char **errmsg)
  2610. {
  2611. const or_options_t *options = get_options();
  2612. (void) control_conn;
  2613. if (!strcmp(question, "circuit-status")) {
  2614. smartlist_t *status = smartlist_new();
  2615. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ_) {
  2616. origin_circuit_t *circ;
  2617. char *circdesc;
  2618. const char *state;
  2619. if (! CIRCUIT_IS_ORIGIN(circ_) || circ_->marked_for_close)
  2620. continue;
  2621. circ = TO_ORIGIN_CIRCUIT(circ_);
  2622. if (circ->base_.state == CIRCUIT_STATE_OPEN)
  2623. state = "BUILT";
  2624. else if (circ->base_.state == CIRCUIT_STATE_GUARD_WAIT)
  2625. state = "GUARD_WAIT";
  2626. else if (circ->cpath)
  2627. state = "EXTENDED";
  2628. else
  2629. state = "LAUNCHED";
  2630. circdesc = circuit_describe_status_for_controller(circ);
  2631. smartlist_add_asprintf(status, "%lu %s%s%s",
  2632. (unsigned long)circ->global_identifier,
  2633. state, *circdesc ? " " : "", circdesc);
  2634. tor_free(circdesc);
  2635. }
  2636. SMARTLIST_FOREACH_END(circ_);
  2637. *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
  2638. SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
  2639. smartlist_free(status);
  2640. } else if (!strcmp(question, "stream-status")) {
  2641. smartlist_t *conns = get_connection_array();
  2642. smartlist_t *status = smartlist_new();
  2643. char buf[256];
  2644. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
  2645. const char *state;
  2646. entry_connection_t *conn;
  2647. circuit_t *circ;
  2648. origin_circuit_t *origin_circ = NULL;
  2649. if (base_conn->type != CONN_TYPE_AP ||
  2650. base_conn->marked_for_close ||
  2651. base_conn->state == AP_CONN_STATE_SOCKS_WAIT ||
  2652. base_conn->state == AP_CONN_STATE_NATD_WAIT)
  2653. continue;
  2654. conn = TO_ENTRY_CONN(base_conn);
  2655. switch (base_conn->state)
  2656. {
  2657. case AP_CONN_STATE_CONTROLLER_WAIT:
  2658. case AP_CONN_STATE_CIRCUIT_WAIT:
  2659. if (conn->socks_request &&
  2660. SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command))
  2661. state = "NEWRESOLVE";
  2662. else
  2663. state = "NEW";
  2664. break;
  2665. case AP_CONN_STATE_RENDDESC_WAIT:
  2666. case AP_CONN_STATE_CONNECT_WAIT:
  2667. state = "SENTCONNECT"; break;
  2668. case AP_CONN_STATE_RESOLVE_WAIT:
  2669. state = "SENTRESOLVE"; break;
  2670. case AP_CONN_STATE_OPEN:
  2671. state = "SUCCEEDED"; break;
  2672. default:
  2673. log_warn(LD_BUG, "Asked for stream in unknown state %d",
  2674. base_conn->state);
  2675. continue;
  2676. }
  2677. circ = circuit_get_by_edge_conn(ENTRY_TO_EDGE_CONN(conn));
  2678. if (circ && CIRCUIT_IS_ORIGIN(circ))
  2679. origin_circ = TO_ORIGIN_CIRCUIT(circ);
  2680. write_stream_target_to_buf(conn, buf, sizeof(buf));
  2681. smartlist_add_asprintf(status, "%lu %s %lu %s",
  2682. (unsigned long) base_conn->global_identifier,state,
  2683. origin_circ?
  2684. (unsigned long)origin_circ->global_identifier : 0ul,
  2685. buf);
  2686. } SMARTLIST_FOREACH_END(base_conn);
  2687. *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
  2688. SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
  2689. smartlist_free(status);
  2690. } else if (!strcmp(question, "orconn-status")) {
  2691. smartlist_t *conns = get_connection_array();
  2692. smartlist_t *status = smartlist_new();
  2693. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
  2694. const char *state;
  2695. char name[128];
  2696. or_connection_t *conn;
  2697. if (base_conn->type != CONN_TYPE_OR || base_conn->marked_for_close)
  2698. continue;
  2699. conn = TO_OR_CONN(base_conn);
  2700. if (conn->base_.state == OR_CONN_STATE_OPEN)
  2701. state = "CONNECTED";
  2702. else if (conn->nickname)
  2703. state = "LAUNCHED";
  2704. else
  2705. state = "NEW";
  2706. orconn_target_get_name(name, sizeof(name), conn);
  2707. smartlist_add_asprintf(status, "%s %s", name, state);
  2708. } SMARTLIST_FOREACH_END(base_conn);
  2709. *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
  2710. SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
  2711. smartlist_free(status);
  2712. } else if (!strcmpstart(question, "address-mappings/")) {
  2713. time_t min_e, max_e;
  2714. smartlist_t *mappings;
  2715. question += strlen("address-mappings/");
  2716. if (!strcmp(question, "all")) {
  2717. min_e = 0; max_e = TIME_MAX;
  2718. } else if (!strcmp(question, "cache")) {
  2719. min_e = 2; max_e = TIME_MAX;
  2720. } else if (!strcmp(question, "config")) {
  2721. min_e = 0; max_e = 0;
  2722. } else if (!strcmp(question, "control")) {
  2723. min_e = 1; max_e = 1;
  2724. } else {
  2725. return 0;
  2726. }
  2727. mappings = smartlist_new();
  2728. addressmap_get_mappings(mappings, min_e, max_e, 1);
  2729. *answer = smartlist_join_strings(mappings, "\r\n", 0, NULL);
  2730. SMARTLIST_FOREACH(mappings, char *, cp, tor_free(cp));
  2731. smartlist_free(mappings);
  2732. } else if (!strcmpstart(question, "status/")) {
  2733. /* Note that status/ is not a catch-all for events; there's only supposed
  2734. * to be a status GETINFO if there's a corresponding STATUS event. */
  2735. if (!strcmp(question, "status/circuit-established")) {
  2736. *answer = tor_strdup(have_completed_a_circuit() ? "1" : "0");
  2737. } else if (!strcmp(question, "status/enough-dir-info")) {
  2738. *answer = tor_strdup(router_have_minimum_dir_info() ? "1" : "0");
  2739. } else if (!strcmp(question, "status/good-server-descriptor") ||
  2740. !strcmp(question, "status/accepted-server-descriptor")) {
  2741. /* They're equivalent for now, until we can figure out how to make
  2742. * good-server-descriptor be what we want. See comment in
  2743. * control-spec.txt. */
  2744. *answer = tor_strdup(directories_have_accepted_server_descriptor()
  2745. ? "1" : "0");
  2746. } else if (!strcmp(question, "status/reachability-succeeded/or")) {
  2747. *answer = tor_strdup(check_whether_orport_reachable(options) ?
  2748. "1" : "0");
  2749. } else if (!strcmp(question, "status/reachability-succeeded/dir")) {
  2750. *answer = tor_strdup(check_whether_dirport_reachable(options) ?
  2751. "1" : "0");
  2752. } else if (!strcmp(question, "status/reachability-succeeded")) {
  2753. tor_asprintf(answer, "OR=%d DIR=%d",
  2754. check_whether_orport_reachable(options) ? 1 : 0,
  2755. check_whether_dirport_reachable(options) ? 1 : 0);
  2756. } else if (!strcmp(question, "status/bootstrap-phase")) {
  2757. *answer = tor_strdup(last_sent_bootstrap_message);
  2758. } else if (!strcmpstart(question, "status/version/")) {
  2759. int is_server = server_mode(options);
  2760. networkstatus_t *c = networkstatus_get_latest_consensus();
  2761. version_status_t status;
  2762. const char *recommended;
  2763. if (c) {
  2764. recommended = is_server ? c->server_versions : c->client_versions;
  2765. status = tor_version_is_obsolete(VERSION, recommended);
  2766. } else {
  2767. recommended = "?";
  2768. status = VS_UNKNOWN;
  2769. }
  2770. if (!strcmp(question, "status/version/recommended")) {
  2771. *answer = tor_strdup(recommended);
  2772. return 0;
  2773. }
  2774. if (!strcmp(question, "status/version/current")) {
  2775. switch (status)
  2776. {
  2777. case VS_RECOMMENDED: *answer = tor_strdup("recommended"); break;
  2778. case VS_OLD: *answer = tor_strdup("obsolete"); break;
  2779. case VS_NEW: *answer = tor_strdup("new"); break;
  2780. case VS_NEW_IN_SERIES: *answer = tor_strdup("new in series"); break;
  2781. case VS_UNRECOMMENDED: *answer = tor_strdup("unrecommended"); break;
  2782. case VS_EMPTY: *answer = tor_strdup("none recommended"); break;
  2783. case VS_UNKNOWN: *answer = tor_strdup("unknown"); break;
  2784. default: tor_fragile_assert();
  2785. }
  2786. } else if (!strcmp(question, "status/version/num-versioning") ||
  2787. !strcmp(question, "status/version/num-concurring")) {
  2788. tor_asprintf(answer, "%d", get_n_authorities(V3_DIRINFO));
  2789. log_warn(LD_GENERAL, "%s is deprecated; it no longer gives useful "
  2790. "information", question);
  2791. }
  2792. } else if (!strcmp(question, "status/clients-seen")) {
  2793. char *bridge_stats = geoip_get_bridge_stats_controller(time(NULL));
  2794. if (!bridge_stats) {
  2795. *errmsg = "No bridge-client stats available";
  2796. return -1;
  2797. }
  2798. *answer = bridge_stats;
  2799. } else if (!strcmp(question, "status/fresh-relay-descs")) {
  2800. if (!server_mode(options)) {
  2801. *errmsg = "Only relays have descriptors";
  2802. return -1;
  2803. }
  2804. routerinfo_t *r;
  2805. extrainfo_t *e;
  2806. if (router_build_fresh_descriptor(&r, &e) < 0) {
  2807. *errmsg = "Error generating descriptor";
  2808. return -1;
  2809. }
  2810. size_t size = r->cache_info.signed_descriptor_len + 1;
  2811. if (e) {
  2812. size += e->cache_info.signed_descriptor_len + 1;
  2813. }
  2814. tor_assert(r->cache_info.signed_descriptor_len);
  2815. char *descs = tor_malloc(size);
  2816. char *cp = descs;
  2817. memcpy(cp, signed_descriptor_get_body(&r->cache_info),
  2818. r->cache_info.signed_descriptor_len);
  2819. cp += r->cache_info.signed_descriptor_len - 1;
  2820. if (e) {
  2821. if (cp[0] == '\0') {
  2822. cp[0] = '\n';
  2823. } else if (cp[0] != '\n') {
  2824. cp[1] = '\n';
  2825. cp++;
  2826. }
  2827. memcpy(cp, signed_descriptor_get_body(&e->cache_info),
  2828. e->cache_info.signed_descriptor_len);
  2829. cp += e->cache_info.signed_descriptor_len - 1;
  2830. }
  2831. if (cp[0] == '\n') {
  2832. cp[0] = '\0';
  2833. } else if (cp[0] != '\0') {
  2834. cp[1] = '\0';
  2835. }
  2836. *answer = descs;
  2837. routerinfo_free(r);
  2838. extrainfo_free(e);
  2839. } else {
  2840. return 0;
  2841. }
  2842. }
  2843. return 0;
  2844. }
  2845. /** Implementation helper for GETINFO: knows how to enumerate hidden services
  2846. * created via the control port. */
  2847. STATIC int
  2848. getinfo_helper_onions(control_connection_t *control_conn,
  2849. const char *question, char **answer,
  2850. const char **errmsg)
  2851. {
  2852. smartlist_t *onion_list = NULL;
  2853. (void) errmsg; /* no errors from this method */
  2854. if (control_conn && !strcmp(question, "onions/current")) {
  2855. onion_list = control_conn->ephemeral_onion_services;
  2856. } else if (!strcmp(question, "onions/detached")) {
  2857. onion_list = detached_onion_services;
  2858. } else {
  2859. return 0;
  2860. }
  2861. if (!onion_list || smartlist_len(onion_list) == 0) {
  2862. if (answer) {
  2863. *answer = tor_strdup("");
  2864. }
  2865. } else {
  2866. if (answer) {
  2867. *answer = smartlist_join_strings(onion_list, "\r\n", 0, NULL);
  2868. }
  2869. }
  2870. return 0;
  2871. }
  2872. /** Implementation helper for GETINFO: answers queries about network
  2873. * liveness. */
  2874. static int
  2875. getinfo_helper_liveness(control_connection_t *control_conn,
  2876. const char *question, char **answer,
  2877. const char **errmsg)
  2878. {
  2879. (void)control_conn;
  2880. (void)errmsg;
  2881. if (strcmp(question, "network-liveness") == 0) {
  2882. if (get_cached_network_liveness()) {
  2883. *answer = tor_strdup("up");
  2884. } else {
  2885. *answer = tor_strdup("down");
  2886. }
  2887. }
  2888. return 0;
  2889. }
  2890. /** Implementation helper for GETINFO: answers queries about shared random
  2891. * value. */
  2892. static int
  2893. getinfo_helper_sr(control_connection_t *control_conn,
  2894. const char *question, char **answer,
  2895. const char **errmsg)
  2896. {
  2897. (void) control_conn;
  2898. (void) errmsg;
  2899. if (!strcmp(question, "sr/current")) {
  2900. *answer = sr_get_current_for_control();
  2901. } else if (!strcmp(question, "sr/previous")) {
  2902. *answer = sr_get_previous_for_control();
  2903. }
  2904. /* Else statement here is unrecognized key so do nothing. */
  2905. return 0;
  2906. }
  2907. /** Callback function for GETINFO: on a given control connection, try to
  2908. * answer the question <b>q</b> and store the newly-allocated answer in
  2909. * *<b>a</b>. If an internal error occurs, return -1 and optionally set
  2910. * *<b>error_out</b> to point to an error message to be delivered to the
  2911. * controller. On success, _or if the key is not recognized_, return 0. Do not
  2912. * set <b>a</b> if the key is not recognized but you may set <b>error_out</b>
  2913. * to improve the error message.
  2914. */
  2915. typedef int (*getinfo_helper_t)(control_connection_t *,
  2916. const char *q, char **a,
  2917. const char **error_out);
  2918. /** A single item for the GETINFO question-to-answer-function table. */
  2919. typedef struct getinfo_item_t {
  2920. const char *varname; /**< The value (or prefix) of the question. */
  2921. getinfo_helper_t fn; /**< The function that knows the answer: NULL if
  2922. * this entry is documentation-only. */
  2923. const char *desc; /**< Description of the variable. */
  2924. int is_prefix; /** Must varname match exactly, or must it be a prefix? */
  2925. } getinfo_item_t;
  2926. #define ITEM(name, fn, desc) { name, getinfo_helper_##fn, desc, 0 }
  2927. #define PREFIX(name, fn, desc) { name, getinfo_helper_##fn, desc, 1 }
  2928. #define DOC(name, desc) { name, NULL, desc, 0 }
  2929. /** Table mapping questions accepted by GETINFO to the functions that know how
  2930. * to answer them. */
  2931. static const getinfo_item_t getinfo_items[] = {
  2932. ITEM("version", misc, "The current version of Tor."),
  2933. ITEM("bw-event-cache", misc, "Cached BW events for a short interval."),
  2934. ITEM("config-file", misc, "Current location of the \"torrc\" file."),
  2935. ITEM("config-defaults-file", misc, "Current location of the defaults file."),
  2936. ITEM("config-text", misc,
  2937. "Return the string that would be written by a saveconf command."),
  2938. ITEM("config-can-saveconf", misc,
  2939. "Is it possible to save the configuration to the \"torrc\" file?"),
  2940. ITEM("accounting/bytes", accounting,
  2941. "Number of bytes read/written so far in the accounting interval."),
  2942. ITEM("accounting/bytes-left", accounting,
  2943. "Number of bytes left to write/read so far in the accounting interval."),
  2944. ITEM("accounting/enabled", accounting, "Is accounting currently enabled?"),
  2945. ITEM("accounting/hibernating", accounting, "Are we hibernating or awake?"),
  2946. ITEM("accounting/interval-start", accounting,
  2947. "Time when the accounting period starts."),
  2948. ITEM("accounting/interval-end", accounting,
  2949. "Time when the accounting period ends."),
  2950. ITEM("accounting/interval-wake", accounting,
  2951. "Time to wake up in this accounting period."),
  2952. ITEM("helper-nodes", entry_guards, NULL), /* deprecated */
  2953. ITEM("entry-guards", entry_guards,
  2954. "Which nodes are we using as entry guards?"),
  2955. ITEM("fingerprint", misc, NULL),
  2956. PREFIX("config/", config, "Current configuration values."),
  2957. DOC("config/names",
  2958. "List of configuration options, types, and documentation."),
  2959. DOC("config/defaults",
  2960. "List of default values for configuration options. "
  2961. "See also config/names"),
  2962. PREFIX("current-time/", current_time, "Current time."),
  2963. DOC("current-time/local", "Current time on the local system."),
  2964. DOC("current-time/utc", "Current UTC time."),
  2965. PREFIX("downloads/networkstatus/", downloads,
  2966. "Download statuses for networkstatus objects"),
  2967. DOC("downloads/networkstatus/ns",
  2968. "Download status for current-mode networkstatus download"),
  2969. DOC("downloads/networkstatus/ns/bootstrap",
  2970. "Download status for bootstrap-time networkstatus download"),
  2971. DOC("downloads/networkstatus/ns/running",
  2972. "Download status for run-time networkstatus download"),
  2973. DOC("downloads/networkstatus/microdesc",
  2974. "Download status for current-mode microdesc download"),
  2975. DOC("downloads/networkstatus/microdesc/bootstrap",
  2976. "Download status for bootstrap-time microdesc download"),
  2977. DOC("downloads/networkstatus/microdesc/running",
  2978. "Download status for run-time microdesc download"),
  2979. PREFIX("downloads/cert/", downloads,
  2980. "Download statuses for certificates, by id fingerprint and "
  2981. "signing key"),
  2982. DOC("downloads/cert/fps",
  2983. "List of authority fingerprints for which any download statuses "
  2984. "exist"),
  2985. DOC("downloads/cert/fp/<fp>",
  2986. "Download status for <fp> with the default signing key; corresponds "
  2987. "to /fp/ URLs on directory server."),
  2988. DOC("downloads/cert/fp/<fp>/sks",
  2989. "List of signing keys for which specific download statuses are "
  2990. "available for this id fingerprint"),
  2991. DOC("downloads/cert/fp/<fp>/<sk>",
  2992. "Download status for <fp> with signing key <sk>; corresponds "
  2993. "to /fp-sk/ URLs on directory server."),
  2994. PREFIX("downloads/desc/", downloads,
  2995. "Download statuses for router descriptors, by descriptor digest"),
  2996. DOC("downloads/desc/descs",
  2997. "Return a list of known router descriptor digests"),
  2998. DOC("downloads/desc/<desc>",
  2999. "Return a download status for a given descriptor digest"),
  3000. PREFIX("downloads/bridge/", downloads,
  3001. "Download statuses for bridge descriptors, by bridge identity "
  3002. "digest"),
  3003. DOC("downloads/bridge/bridges",
  3004. "Return a list of configured bridge identity digests with download "
  3005. "statuses"),
  3006. DOC("downloads/bridge/<desc>",
  3007. "Return a download status for a given bridge identity digest"),
  3008. ITEM("info/names", misc,
  3009. "List of GETINFO options, types, and documentation."),
  3010. ITEM("events/names", misc,
  3011. "Events that the controller can ask for with SETEVENTS."),
  3012. ITEM("signal/names", misc, "Signal names recognized by the SIGNAL command"),
  3013. ITEM("features/names", misc, "What arguments can USEFEATURE take?"),
  3014. PREFIX("desc/id/", dir, "Router descriptors by ID."),
  3015. PREFIX("desc/name/", dir, "Router descriptors by nickname."),
  3016. ITEM("desc/all-recent", dir,
  3017. "All non-expired, non-superseded router descriptors."),
  3018. ITEM("desc/download-enabled", dir,
  3019. "Do we try to download router descriptors?"),
  3020. ITEM("desc/all-recent-extrainfo-hack", dir, NULL), /* Hack. */
  3021. ITEM("md/all", dir, "All known microdescriptors."),
  3022. PREFIX("md/id/", dir, "Microdescriptors by ID"),
  3023. PREFIX("md/name/", dir, "Microdescriptors by name"),
  3024. ITEM("md/download-enabled", dir,
  3025. "Do we try to download microdescriptors?"),
  3026. PREFIX("extra-info/digest/", dir, "Extra-info documents by digest."),
  3027. PREFIX("hs/client/desc/id", dir,
  3028. "Hidden Service descriptor in client's cache by onion."),
  3029. PREFIX("hs/service/desc/id/", dir,
  3030. "Hidden Service descriptor in services's cache by onion."),
  3031. PREFIX("net/listeners/", listeners, "Bound addresses by type"),
  3032. ITEM("ns/all", networkstatus,
  3033. "Brief summary of router status (v2 directory format)"),
  3034. PREFIX("ns/id/", networkstatus,
  3035. "Brief summary of router status by ID (v2 directory format)."),
  3036. PREFIX("ns/name/", networkstatus,
  3037. "Brief summary of router status by nickname (v2 directory format)."),
  3038. PREFIX("ns/purpose/", networkstatus,
  3039. "Brief summary of router status by purpose (v2 directory format)."),
  3040. PREFIX("consensus/", networkstatus,
  3041. "Information about and from the ns consensus."),
  3042. ITEM("network-status", dir,
  3043. "Brief summary of router status (v1 directory format)"),
  3044. ITEM("network-liveness", liveness,
  3045. "Current opinion on whether the network is live"),
  3046. ITEM("circuit-status", events, "List of current circuits originating here."),
  3047. ITEM("stream-status", events,"List of current streams."),
  3048. ITEM("orconn-status", events, "A list of current OR connections."),
  3049. ITEM("dormant", misc,
  3050. "Is Tor dormant (not building circuits because it's idle)?"),
  3051. PREFIX("address-mappings/", events, NULL),
  3052. DOC("address-mappings/all", "Current address mappings."),
  3053. DOC("address-mappings/cache", "Current cached DNS replies."),
  3054. DOC("address-mappings/config",
  3055. "Current address mappings from configuration."),
  3056. DOC("address-mappings/control", "Current address mappings from controller."),
  3057. PREFIX("status/", events, NULL),
  3058. DOC("status/circuit-established",
  3059. "Whether we think client functionality is working."),
  3060. DOC("status/enough-dir-info",
  3061. "Whether we have enough up-to-date directory information to build "
  3062. "circuits."),
  3063. DOC("status/bootstrap-phase",
  3064. "The last bootstrap phase status event that Tor sent."),
  3065. DOC("status/clients-seen",
  3066. "Breakdown of client countries seen by a bridge."),
  3067. DOC("status/fresh-relay-descs",
  3068. "A fresh relay/ei descriptor pair for Tor's current state. Not stored."),
  3069. DOC("status/version/recommended", "List of currently recommended versions."),
  3070. DOC("status/version/current", "Status of the current version."),
  3071. DOC("status/version/num-versioning", "Number of versioning authorities."),
  3072. DOC("status/version/num-concurring",
  3073. "Number of versioning authorities agreeing on the status of the "
  3074. "current version"),
  3075. ITEM("address", misc, "IP address of this Tor host, if we can guess it."),
  3076. ITEM("traffic/read", misc,"Bytes read since the process was started."),
  3077. ITEM("traffic/written", misc,
  3078. "Bytes written since the process was started."),
  3079. ITEM("uptime", misc, "Uptime of the Tor daemon in seconds."),
  3080. ITEM("process/pid", misc, "Process id belonging to the main tor process."),
  3081. ITEM("process/uid", misc, "User id running the tor process."),
  3082. ITEM("process/user", misc,
  3083. "Username under which the tor process is running."),
  3084. ITEM("process/descriptor-limit", misc, "File descriptor limit."),
  3085. ITEM("limits/max-mem-in-queues", misc, "Actual limit on memory in queues"),
  3086. PREFIX("desc-annotations/id/", dir, "Router annotations by hexdigest."),
  3087. PREFIX("dir/server/", dir,"Router descriptors as retrieved from a DirPort."),
  3088. PREFIX("dir/status/", dir,
  3089. "v2 networkstatus docs as retrieved from a DirPort."),
  3090. ITEM("dir/status-vote/current/consensus", dir,
  3091. "v3 Networkstatus consensus as retrieved from a DirPort."),
  3092. ITEM("exit-policy/default", policies,
  3093. "The default value appended to the configured exit policy."),
  3094. ITEM("exit-policy/reject-private/default", policies,
  3095. "The default rules appended to the configured exit policy by"
  3096. " ExitPolicyRejectPrivate."),
  3097. ITEM("exit-policy/reject-private/relay", policies,
  3098. "The relay-specific rules appended to the configured exit policy by"
  3099. " ExitPolicyRejectPrivate and/or ExitPolicyRejectLocalInterfaces."),
  3100. ITEM("exit-policy/full", policies, "The entire exit policy of onion router"),
  3101. ITEM("exit-policy/ipv4", policies, "IPv4 parts of exit policy"),
  3102. ITEM("exit-policy/ipv6", policies, "IPv6 parts of exit policy"),
  3103. PREFIX("ip-to-country/", geoip, "Perform a GEOIP lookup"),
  3104. ITEM("onions/current", onions,
  3105. "Onion services owned by the current control connection."),
  3106. ITEM("onions/detached", onions,
  3107. "Onion services detached from the control connection."),
  3108. ITEM("sr/current", sr, "Get current shared random value."),
  3109. ITEM("sr/previous", sr, "Get previous shared random value."),
  3110. { NULL, NULL, NULL, 0 }
  3111. };
  3112. /** Allocate and return a list of recognized GETINFO options. */
  3113. static char *
  3114. list_getinfo_options(void)
  3115. {
  3116. int i;
  3117. smartlist_t *lines = smartlist_new();
  3118. char *ans;
  3119. for (i = 0; getinfo_items[i].varname; ++i) {
  3120. if (!getinfo_items[i].desc)
  3121. continue;
  3122. smartlist_add_asprintf(lines, "%s%s -- %s\n",
  3123. getinfo_items[i].varname,
  3124. getinfo_items[i].is_prefix ? "*" : "",
  3125. getinfo_items[i].desc);
  3126. }
  3127. smartlist_sort_strings(lines);
  3128. ans = smartlist_join_strings(lines, "", 0, NULL);
  3129. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  3130. smartlist_free(lines);
  3131. return ans;
  3132. }
  3133. /** Lookup the 'getinfo' entry <b>question</b>, and return
  3134. * the answer in <b>*answer</b> (or NULL if key not recognized).
  3135. * Return 0 if success or unrecognized, or -1 if recognized but
  3136. * internal error. */
  3137. static int
  3138. handle_getinfo_helper(control_connection_t *control_conn,
  3139. const char *question, char **answer,
  3140. const char **err_out)
  3141. {
  3142. int i;
  3143. *answer = NULL; /* unrecognized key by default */
  3144. for (i = 0; getinfo_items[i].varname; ++i) {
  3145. int match;
  3146. if (getinfo_items[i].is_prefix)
  3147. match = !strcmpstart(question, getinfo_items[i].varname);
  3148. else
  3149. match = !strcmp(question, getinfo_items[i].varname);
  3150. if (match) {
  3151. tor_assert(getinfo_items[i].fn);
  3152. return getinfo_items[i].fn(control_conn, question, answer, err_out);
  3153. }
  3154. }
  3155. return 0; /* unrecognized */
  3156. }
  3157. /** Called when we receive a GETINFO command. Try to fetch all requested
  3158. * information, and reply with information or error message. */
  3159. static int
  3160. handle_control_getinfo(control_connection_t *conn, uint32_t len,
  3161. const char *body)
  3162. {
  3163. smartlist_t *questions = smartlist_new();
  3164. smartlist_t *answers = smartlist_new();
  3165. smartlist_t *unrecognized = smartlist_new();
  3166. char *ans = NULL;
  3167. int i;
  3168. (void) len; /* body is NUL-terminated, so it's safe to ignore the length. */
  3169. smartlist_split_string(questions, body, " ",
  3170. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  3171. SMARTLIST_FOREACH_BEGIN(questions, const char *, q) {
  3172. const char *errmsg = NULL;
  3173. if (handle_getinfo_helper(conn, q, &ans, &errmsg) < 0) {
  3174. if (!errmsg)
  3175. errmsg = "Internal error";
  3176. connection_printf_to_buf(conn, "551 %s\r\n", errmsg);
  3177. goto done;
  3178. }
  3179. if (!ans) {
  3180. if (errmsg) /* use provided error message */
  3181. smartlist_add_strdup(unrecognized, errmsg);
  3182. else /* use default error message */
  3183. smartlist_add_asprintf(unrecognized, "Unrecognized key \"%s\"", q);
  3184. } else {
  3185. smartlist_add_strdup(answers, q);
  3186. smartlist_add(answers, ans);
  3187. }
  3188. } SMARTLIST_FOREACH_END(q);
  3189. if (smartlist_len(unrecognized)) {
  3190. /* control-spec section 2.3, mid-reply '-' or end of reply ' ' */
  3191. for (i=0; i < smartlist_len(unrecognized)-1; ++i)
  3192. connection_printf_to_buf(conn,
  3193. "552-%s\r\n",
  3194. (char *)smartlist_get(unrecognized, i));
  3195. connection_printf_to_buf(conn,
  3196. "552 %s\r\n",
  3197. (char *)smartlist_get(unrecognized, i));
  3198. goto done;
  3199. }
  3200. for (i = 0; i < smartlist_len(answers); i += 2) {
  3201. char *k = smartlist_get(answers, i);
  3202. char *v = smartlist_get(answers, i+1);
  3203. if (!strchr(v, '\n') && !strchr(v, '\r')) {
  3204. connection_printf_to_buf(conn, "250-%s=", k);
  3205. connection_write_str_to_buf(v, conn);
  3206. connection_write_str_to_buf("\r\n", conn);
  3207. } else {
  3208. char *esc = NULL;
  3209. size_t esc_len;
  3210. esc_len = write_escaped_data(v, strlen(v), &esc);
  3211. connection_printf_to_buf(conn, "250+%s=\r\n", k);
  3212. connection_buf_add(esc, esc_len, TO_CONN(conn));
  3213. tor_free(esc);
  3214. }
  3215. }
  3216. connection_write_str_to_buf("250 OK\r\n", conn);
  3217. done:
  3218. SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
  3219. smartlist_free(answers);
  3220. SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
  3221. smartlist_free(questions);
  3222. SMARTLIST_FOREACH(unrecognized, char *, cp, tor_free(cp));
  3223. smartlist_free(unrecognized);
  3224. return 0;
  3225. }
  3226. /** Given a string, convert it to a circuit purpose. */
  3227. static uint8_t
  3228. circuit_purpose_from_string(const char *string)
  3229. {
  3230. if (!strcasecmpstart(string, "purpose="))
  3231. string += strlen("purpose=");
  3232. if (!strcasecmp(string, "general"))
  3233. return CIRCUIT_PURPOSE_C_GENERAL;
  3234. else if (!strcasecmp(string, "controller"))
  3235. return CIRCUIT_PURPOSE_CONTROLLER;
  3236. else
  3237. return CIRCUIT_PURPOSE_UNKNOWN;
  3238. }
  3239. /** Return a newly allocated smartlist containing the arguments to the command
  3240. * waiting in <b>body</b>. If there are fewer than <b>min_args</b> arguments,
  3241. * or if <b>max_args</b> is nonnegative and there are more than
  3242. * <b>max_args</b> arguments, send a 512 error to the controller, using
  3243. * <b>command</b> as the command name in the error message. */
  3244. static smartlist_t *
  3245. getargs_helper(const char *command, control_connection_t *conn,
  3246. const char *body, int min_args, int max_args)
  3247. {
  3248. smartlist_t *args = smartlist_new();
  3249. smartlist_split_string(args, body, " ",
  3250. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  3251. if (smartlist_len(args) < min_args) {
  3252. connection_printf_to_buf(conn, "512 Missing argument to %s\r\n",command);
  3253. goto err;
  3254. } else if (max_args >= 0 && smartlist_len(args) > max_args) {
  3255. connection_printf_to_buf(conn, "512 Too many arguments to %s\r\n",command);
  3256. goto err;
  3257. }
  3258. return args;
  3259. err:
  3260. SMARTLIST_FOREACH(args, char *, s, tor_free(s));
  3261. smartlist_free(args);
  3262. return NULL;
  3263. }
  3264. /** Helper. Return the first element of <b>sl</b> at index <b>start_at</b> or
  3265. * higher that starts with <b>prefix</b>, case-insensitive. Return NULL if no
  3266. * such element exists. */
  3267. static const char *
  3268. find_element_starting_with(smartlist_t *sl, int start_at, const char *prefix)
  3269. {
  3270. int i;
  3271. for (i = start_at; i < smartlist_len(sl); ++i) {
  3272. const char *elt = smartlist_get(sl, i);
  3273. if (!strcasecmpstart(elt, prefix))
  3274. return elt;
  3275. }
  3276. return NULL;
  3277. }
  3278. /** Helper. Return true iff s is an argument that we should treat as a
  3279. * key-value pair. */
  3280. static int
  3281. is_keyval_pair(const char *s)
  3282. {
  3283. /* An argument is a key-value pair if it has an =, and it isn't of the form
  3284. * $fingeprint=name */
  3285. return strchr(s, '=') && s[0] != '$';
  3286. }
  3287. /** Called when we get an EXTENDCIRCUIT message. Try to extend the listed
  3288. * circuit, and report success or failure. */
  3289. static int
  3290. handle_control_extendcircuit(control_connection_t *conn, uint32_t len,
  3291. const char *body)
  3292. {
  3293. smartlist_t *router_nicknames=NULL, *nodes=NULL;
  3294. origin_circuit_t *circ = NULL;
  3295. int zero_circ;
  3296. uint8_t intended_purpose = CIRCUIT_PURPOSE_C_GENERAL;
  3297. smartlist_t *args;
  3298. (void) len;
  3299. router_nicknames = smartlist_new();
  3300. args = getargs_helper("EXTENDCIRCUIT", conn, body, 1, -1);
  3301. if (!args)
  3302. goto done;
  3303. zero_circ = !strcmp("0", (char*)smartlist_get(args,0));
  3304. if (zero_circ) {
  3305. const char *purp = find_element_starting_with(args, 1, "PURPOSE=");
  3306. if (purp) {
  3307. intended_purpose = circuit_purpose_from_string(purp);
  3308. if (intended_purpose == CIRCUIT_PURPOSE_UNKNOWN) {
  3309. connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n", purp);
  3310. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  3311. smartlist_free(args);
  3312. goto done;
  3313. }
  3314. }
  3315. if ((smartlist_len(args) == 1) ||
  3316. (smartlist_len(args) >= 2 && is_keyval_pair(smartlist_get(args, 1)))) {
  3317. // "EXTENDCIRCUIT 0" || EXTENDCIRCUIT 0 foo=bar"
  3318. circ = circuit_launch(intended_purpose, CIRCLAUNCH_NEED_CAPACITY);
  3319. if (!circ) {
  3320. connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
  3321. } else {
  3322. connection_printf_to_buf(conn, "250 EXTENDED %lu\r\n",
  3323. (unsigned long)circ->global_identifier);
  3324. }
  3325. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  3326. smartlist_free(args);
  3327. goto done;
  3328. }
  3329. // "EXTENDCIRCUIT 0 router1,router2" ||
  3330. // "EXTENDCIRCUIT 0 router1,router2 PURPOSE=foo"
  3331. }
  3332. if (!zero_circ && !(circ = get_circ(smartlist_get(args,0)))) {
  3333. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  3334. (char*)smartlist_get(args, 0));
  3335. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  3336. smartlist_free(args);
  3337. goto done;
  3338. }
  3339. if (smartlist_len(args) < 2) {
  3340. connection_printf_to_buf(conn,
  3341. "512 syntax error: not enough arguments.\r\n");
  3342. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  3343. smartlist_free(args);
  3344. goto done;
  3345. }
  3346. smartlist_split_string(router_nicknames, smartlist_get(args,1), ",", 0, 0);
  3347. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  3348. smartlist_free(args);
  3349. nodes = smartlist_new();
  3350. int first_node = zero_circ;
  3351. SMARTLIST_FOREACH_BEGIN(router_nicknames, const char *, n) {
  3352. const node_t *node = node_get_by_nickname(n, 0);
  3353. if (!node) {
  3354. connection_printf_to_buf(conn, "552 No such router \"%s\"\r\n", n);
  3355. goto done;
  3356. }
  3357. if (!node_has_preferred_descriptor(node, first_node)) {
  3358. connection_printf_to_buf(conn, "552 No descriptor for \"%s\"\r\n", n);
  3359. goto done;
  3360. }
  3361. smartlist_add(nodes, (void*)node);
  3362. first_node = 0;
  3363. } SMARTLIST_FOREACH_END(n);
  3364. if (!smartlist_len(nodes)) {
  3365. connection_write_str_to_buf("512 No router names provided\r\n", conn);
  3366. goto done;
  3367. }
  3368. if (zero_circ) {
  3369. /* start a new circuit */
  3370. circ = origin_circuit_init(intended_purpose, 0);
  3371. }
  3372. /* now circ refers to something that is ready to be extended */
  3373. first_node = zero_circ;
  3374. SMARTLIST_FOREACH(nodes, const node_t *, node,
  3375. {
  3376. extend_info_t *info = extend_info_from_node(node, first_node);
  3377. if (!info) {
  3378. tor_assert_nonfatal(first_node);
  3379. log_warn(LD_CONTROL,
  3380. "controller tried to connect to a node that lacks a suitable "
  3381. "descriptor, or which doesn't have any "
  3382. "addresses that are allowed by the firewall configuration; "
  3383. "circuit marked for closing.");
  3384. circuit_mark_for_close(TO_CIRCUIT(circ), -END_CIRC_REASON_CONNECTFAILED);
  3385. connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
  3386. goto done;
  3387. }
  3388. circuit_append_new_exit(circ, info);
  3389. if (circ->build_state->desired_path_len > 1) {
  3390. circ->build_state->onehop_tunnel = 0;
  3391. }
  3392. extend_info_free(info);
  3393. first_node = 0;
  3394. });
  3395. /* now that we've populated the cpath, start extending */
  3396. if (zero_circ) {
  3397. int err_reason = 0;
  3398. if ((err_reason = circuit_handle_first_hop(circ)) < 0) {
  3399. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  3400. connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
  3401. goto done;
  3402. }
  3403. } else {
  3404. if (circ->base_.state == CIRCUIT_STATE_OPEN ||
  3405. circ->base_.state == CIRCUIT_STATE_GUARD_WAIT) {
  3406. int err_reason = 0;
  3407. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
  3408. if ((err_reason = circuit_send_next_onion_skin(circ)) < 0) {
  3409. log_info(LD_CONTROL,
  3410. "send_next_onion_skin failed; circuit marked for closing.");
  3411. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  3412. connection_write_str_to_buf("551 Couldn't send onion skin\r\n", conn);
  3413. goto done;
  3414. }
  3415. }
  3416. }
  3417. connection_printf_to_buf(conn, "250 EXTENDED %lu\r\n",
  3418. (unsigned long)circ->global_identifier);
  3419. if (zero_circ) /* send a 'launched' event, for completeness */
  3420. control_event_circuit_status(circ, CIRC_EVENT_LAUNCHED, 0);
  3421. done:
  3422. SMARTLIST_FOREACH(router_nicknames, char *, n, tor_free(n));
  3423. smartlist_free(router_nicknames);
  3424. smartlist_free(nodes);
  3425. return 0;
  3426. }
  3427. /** Called when we get a SETCIRCUITPURPOSE message. If we can find the
  3428. * circuit and it's a valid purpose, change it. */
  3429. static int
  3430. handle_control_setcircuitpurpose(control_connection_t *conn,
  3431. uint32_t len, const char *body)
  3432. {
  3433. origin_circuit_t *circ = NULL;
  3434. uint8_t new_purpose;
  3435. smartlist_t *args;
  3436. (void) len; /* body is NUL-terminated, so it's safe to ignore the length. */
  3437. args = getargs_helper("SETCIRCUITPURPOSE", conn, body, 2, -1);
  3438. if (!args)
  3439. goto done;
  3440. if (!(circ = get_circ(smartlist_get(args,0)))) {
  3441. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  3442. (char*)smartlist_get(args, 0));
  3443. goto done;
  3444. }
  3445. {
  3446. const char *purp = find_element_starting_with(args,1,"PURPOSE=");
  3447. if (!purp) {
  3448. connection_write_str_to_buf("552 No purpose given\r\n", conn);
  3449. goto done;
  3450. }
  3451. new_purpose = circuit_purpose_from_string(purp);
  3452. if (new_purpose == CIRCUIT_PURPOSE_UNKNOWN) {
  3453. connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n", purp);
  3454. goto done;
  3455. }
  3456. }
  3457. circuit_change_purpose(TO_CIRCUIT(circ), new_purpose);
  3458. connection_write_str_to_buf("250 OK\r\n", conn);
  3459. done:
  3460. if (args) {
  3461. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  3462. smartlist_free(args);
  3463. }
  3464. return 0;
  3465. }
  3466. /** Called when we get an ATTACHSTREAM message. Try to attach the requested
  3467. * stream, and report success or failure. */
  3468. static int
  3469. handle_control_attachstream(control_connection_t *conn, uint32_t len,
  3470. const char *body)
  3471. {
  3472. entry_connection_t *ap_conn = NULL;
  3473. origin_circuit_t *circ = NULL;
  3474. int zero_circ;
  3475. smartlist_t *args;
  3476. crypt_path_t *cpath=NULL;
  3477. int hop=0, hop_line_ok=1;
  3478. (void) len;
  3479. args = getargs_helper("ATTACHSTREAM", conn, body, 2, -1);
  3480. if (!args)
  3481. return 0;
  3482. zero_circ = !strcmp("0", (char*)smartlist_get(args,1));
  3483. if (!(ap_conn = get_stream(smartlist_get(args, 0)))) {
  3484. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  3485. (char*)smartlist_get(args, 0));
  3486. } else if (!zero_circ && !(circ = get_circ(smartlist_get(args, 1)))) {
  3487. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  3488. (char*)smartlist_get(args, 1));
  3489. } else if (circ) {
  3490. const char *hopstring = find_element_starting_with(args,2,"HOP=");
  3491. if (hopstring) {
  3492. hopstring += strlen("HOP=");
  3493. hop = (int) tor_parse_ulong(hopstring, 10, 0, INT_MAX,
  3494. &hop_line_ok, NULL);
  3495. if (!hop_line_ok) { /* broken hop line */
  3496. connection_printf_to_buf(conn, "552 Bad value hop=%s\r\n", hopstring);
  3497. }
  3498. }
  3499. }
  3500. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  3501. smartlist_free(args);
  3502. if (!ap_conn || (!zero_circ && !circ) || !hop_line_ok)
  3503. return 0;
  3504. if (ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONTROLLER_WAIT &&
  3505. ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONNECT_WAIT &&
  3506. ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_RESOLVE_WAIT) {
  3507. connection_write_str_to_buf(
  3508. "555 Connection is not managed by controller.\r\n",
  3509. conn);
  3510. return 0;
  3511. }
  3512. /* Do we need to detach it first? */
  3513. if (ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONTROLLER_WAIT) {
  3514. edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
  3515. circuit_t *tmpcirc = circuit_get_by_edge_conn(edge_conn);
  3516. connection_edge_end(edge_conn, END_STREAM_REASON_TIMEOUT);
  3517. /* Un-mark it as ending, since we're going to reuse it. */
  3518. edge_conn->edge_has_sent_end = 0;
  3519. edge_conn->end_reason = 0;
  3520. if (tmpcirc)
  3521. circuit_detach_stream(tmpcirc, edge_conn);
  3522. CONNECTION_AP_EXPECT_NONPENDING(ap_conn);
  3523. TO_CONN(edge_conn)->state = AP_CONN_STATE_CONTROLLER_WAIT;
  3524. }
  3525. if (circ && (circ->base_.state != CIRCUIT_STATE_OPEN)) {
  3526. connection_write_str_to_buf(
  3527. "551 Can't attach stream to non-open origin circuit\r\n",
  3528. conn);
  3529. return 0;
  3530. }
  3531. /* Is this a single hop circuit? */
  3532. if (circ && (circuit_get_cpath_len(circ)<2 || hop==1)) {
  3533. connection_write_str_to_buf(
  3534. "551 Can't attach stream to this one-hop circuit.\r\n", conn);
  3535. return 0;
  3536. }
  3537. if (circ && hop>0) {
  3538. /* find this hop in the circuit, and set cpath */
  3539. cpath = circuit_get_cpath_hop(circ, hop);
  3540. if (!cpath) {
  3541. connection_printf_to_buf(conn,
  3542. "551 Circuit doesn't have %d hops.\r\n", hop);
  3543. return 0;
  3544. }
  3545. }
  3546. if (connection_ap_handshake_rewrite_and_attach(ap_conn, circ, cpath) < 0) {
  3547. connection_write_str_to_buf("551 Unable to attach stream\r\n", conn);
  3548. return 0;
  3549. }
  3550. send_control_done(conn);
  3551. return 0;
  3552. }
  3553. /** Called when we get a POSTDESCRIPTOR message. Try to learn the provided
  3554. * descriptor, and report success or failure. */
  3555. static int
  3556. handle_control_postdescriptor(control_connection_t *conn, uint32_t len,
  3557. const char *body)
  3558. {
  3559. char *desc;
  3560. const char *msg=NULL;
  3561. uint8_t purpose = ROUTER_PURPOSE_GENERAL;
  3562. int cache = 0; /* eventually, we may switch this to 1 */
  3563. const char *cp = memchr(body, '\n', len);
  3564. if (cp == NULL) {
  3565. connection_printf_to_buf(conn, "251 Empty body\r\n");
  3566. return 0;
  3567. }
  3568. ++cp;
  3569. char *cmdline = tor_memdup_nulterm(body, cp-body);
  3570. smartlist_t *args = smartlist_new();
  3571. smartlist_split_string(args, cmdline, " ",
  3572. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  3573. SMARTLIST_FOREACH_BEGIN(args, char *, option) {
  3574. if (!strcasecmpstart(option, "purpose=")) {
  3575. option += strlen("purpose=");
  3576. purpose = router_purpose_from_string(option);
  3577. if (purpose == ROUTER_PURPOSE_UNKNOWN) {
  3578. connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n",
  3579. option);
  3580. goto done;
  3581. }
  3582. } else if (!strcasecmpstart(option, "cache=")) {
  3583. option += strlen("cache=");
  3584. if (!strcasecmp(option, "no"))
  3585. cache = 0;
  3586. else if (!strcasecmp(option, "yes"))
  3587. cache = 1;
  3588. else {
  3589. connection_printf_to_buf(conn, "552 Unknown cache request \"%s\"\r\n",
  3590. option);
  3591. goto done;
  3592. }
  3593. } else { /* unrecognized argument? */
  3594. connection_printf_to_buf(conn,
  3595. "512 Unexpected argument \"%s\" to postdescriptor\r\n", option);
  3596. goto done;
  3597. }
  3598. } SMARTLIST_FOREACH_END(option);
  3599. read_escaped_data(cp, len-(cp-body), &desc);
  3600. switch (router_load_single_router(desc, purpose, cache, &msg)) {
  3601. case -1:
  3602. if (!msg) msg = "Could not parse descriptor";
  3603. connection_printf_to_buf(conn, "554 %s\r\n", msg);
  3604. break;
  3605. case 0:
  3606. if (!msg) msg = "Descriptor not added";
  3607. connection_printf_to_buf(conn, "251 %s\r\n",msg);
  3608. break;
  3609. case 1:
  3610. send_control_done(conn);
  3611. break;
  3612. }
  3613. tor_free(desc);
  3614. done:
  3615. SMARTLIST_FOREACH(args, char *, arg, tor_free(arg));
  3616. smartlist_free(args);
  3617. tor_free(cmdline);
  3618. return 0;
  3619. }
  3620. /** Called when we receive a REDIRECTSTERAM command. Try to change the target
  3621. * address of the named AP stream, and report success or failure. */
  3622. static int
  3623. handle_control_redirectstream(control_connection_t *conn, uint32_t len,
  3624. const char *body)
  3625. {
  3626. entry_connection_t *ap_conn = NULL;
  3627. char *new_addr = NULL;
  3628. uint16_t new_port = 0;
  3629. smartlist_t *args;
  3630. (void) len;
  3631. args = getargs_helper("REDIRECTSTREAM", conn, body, 2, -1);
  3632. if (!args)
  3633. return 0;
  3634. if (!(ap_conn = get_stream(smartlist_get(args, 0)))
  3635. || !ap_conn->socks_request) {
  3636. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  3637. (char*)smartlist_get(args, 0));
  3638. } else {
  3639. int ok = 1;
  3640. if (smartlist_len(args) > 2) { /* they included a port too */
  3641. new_port = (uint16_t) tor_parse_ulong(smartlist_get(args, 2),
  3642. 10, 1, 65535, &ok, NULL);
  3643. }
  3644. if (!ok) {
  3645. connection_printf_to_buf(conn, "512 Cannot parse port \"%s\"\r\n",
  3646. (char*)smartlist_get(args, 2));
  3647. } else {
  3648. new_addr = tor_strdup(smartlist_get(args, 1));
  3649. }
  3650. }
  3651. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  3652. smartlist_free(args);
  3653. if (!new_addr)
  3654. return 0;
  3655. strlcpy(ap_conn->socks_request->address, new_addr,
  3656. sizeof(ap_conn->socks_request->address));
  3657. if (new_port)
  3658. ap_conn->socks_request->port = new_port;
  3659. tor_free(new_addr);
  3660. send_control_done(conn);
  3661. return 0;
  3662. }
  3663. /** Called when we get a CLOSESTREAM command; try to close the named stream
  3664. * and report success or failure. */
  3665. static int
  3666. handle_control_closestream(control_connection_t *conn, uint32_t len,
  3667. const char *body)
  3668. {
  3669. entry_connection_t *ap_conn=NULL;
  3670. uint8_t reason=0;
  3671. smartlist_t *args;
  3672. int ok;
  3673. (void) len;
  3674. args = getargs_helper("CLOSESTREAM", conn, body, 2, -1);
  3675. if (!args)
  3676. return 0;
  3677. else if (!(ap_conn = get_stream(smartlist_get(args, 0))))
  3678. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  3679. (char*)smartlist_get(args, 0));
  3680. else {
  3681. reason = (uint8_t) tor_parse_ulong(smartlist_get(args,1), 10, 0, 255,
  3682. &ok, NULL);
  3683. if (!ok) {
  3684. connection_printf_to_buf(conn, "552 Unrecognized reason \"%s\"\r\n",
  3685. (char*)smartlist_get(args, 1));
  3686. ap_conn = NULL;
  3687. }
  3688. }
  3689. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  3690. smartlist_free(args);
  3691. if (!ap_conn)
  3692. return 0;
  3693. connection_mark_unattached_ap(ap_conn, reason);
  3694. send_control_done(conn);
  3695. return 0;
  3696. }
  3697. /** Called when we get a CLOSECIRCUIT command; try to close the named circuit
  3698. * and report success or failure. */
  3699. static int
  3700. handle_control_closecircuit(control_connection_t *conn, uint32_t len,
  3701. const char *body)
  3702. {
  3703. origin_circuit_t *circ = NULL;
  3704. int safe = 0;
  3705. smartlist_t *args;
  3706. (void) len;
  3707. args = getargs_helper("CLOSECIRCUIT", conn, body, 1, -1);
  3708. if (!args)
  3709. return 0;
  3710. if (!(circ=get_circ(smartlist_get(args, 0))))
  3711. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  3712. (char*)smartlist_get(args, 0));
  3713. else {
  3714. int i;
  3715. for (i=1; i < smartlist_len(args); ++i) {
  3716. if (!strcasecmp(smartlist_get(args, i), "IfUnused"))
  3717. safe = 1;
  3718. else
  3719. log_info(LD_CONTROL, "Skipping unknown option %s",
  3720. (char*)smartlist_get(args,i));
  3721. }
  3722. }
  3723. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  3724. smartlist_free(args);
  3725. if (!circ)
  3726. return 0;
  3727. if (!safe || !circ->p_streams) {
  3728. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_REQUESTED);
  3729. }
  3730. send_control_done(conn);
  3731. return 0;
  3732. }
  3733. /** Called when we get a RESOLVE command: start trying to resolve
  3734. * the listed addresses. */
  3735. static int
  3736. handle_control_resolve(control_connection_t *conn, uint32_t len,
  3737. const char *body)
  3738. {
  3739. smartlist_t *args, *failed;
  3740. int is_reverse = 0;
  3741. (void) len; /* body is nul-terminated; it's safe to ignore the length */
  3742. if (!(conn->event_mask & (((event_mask_t)1)<<EVENT_ADDRMAP))) {
  3743. log_warn(LD_CONTROL, "Controller asked us to resolve an address, but "
  3744. "isn't listening for ADDRMAP events. It probably won't see "
  3745. "the answer.");
  3746. }
  3747. args = smartlist_new();
  3748. smartlist_split_string(args, body, " ",
  3749. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  3750. {
  3751. const char *modearg = find_element_starting_with(args, 0, "mode=");
  3752. if (modearg && !strcasecmp(modearg, "mode=reverse"))
  3753. is_reverse = 1;
  3754. }
  3755. failed = smartlist_new();
  3756. SMARTLIST_FOREACH(args, const char *, arg, {
  3757. if (!is_keyval_pair(arg)) {
  3758. if (dnsserv_launch_request(arg, is_reverse, conn)<0)
  3759. smartlist_add(failed, (char*)arg);
  3760. }
  3761. });
  3762. send_control_done(conn);
  3763. SMARTLIST_FOREACH(failed, const char *, arg, {
  3764. control_event_address_mapped(arg, arg, time(NULL),
  3765. "internal", 0);
  3766. });
  3767. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  3768. smartlist_free(args);
  3769. smartlist_free(failed);
  3770. return 0;
  3771. }
  3772. /** Called when we get a PROTOCOLINFO command: send back a reply. */
  3773. static int
  3774. handle_control_protocolinfo(control_connection_t *conn, uint32_t len,
  3775. const char *body)
  3776. {
  3777. const char *bad_arg = NULL;
  3778. smartlist_t *args;
  3779. (void)len;
  3780. conn->have_sent_protocolinfo = 1;
  3781. args = smartlist_new();
  3782. smartlist_split_string(args, body, " ",
  3783. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  3784. SMARTLIST_FOREACH(args, const char *, arg, {
  3785. int ok;
  3786. tor_parse_long(arg, 10, 0, LONG_MAX, &ok, NULL);
  3787. if (!ok) {
  3788. bad_arg = arg;
  3789. break;
  3790. }
  3791. });
  3792. if (bad_arg) {
  3793. connection_printf_to_buf(conn, "513 No such version %s\r\n",
  3794. escaped(bad_arg));
  3795. /* Don't tolerate bad arguments when not authenticated. */
  3796. if (!STATE_IS_OPEN(TO_CONN(conn)->state))
  3797. connection_mark_for_close(TO_CONN(conn));
  3798. goto done;
  3799. } else {
  3800. const or_options_t *options = get_options();
  3801. int cookies = options->CookieAuthentication;
  3802. char *cfile = get_controller_cookie_file_name();
  3803. char *abs_cfile;
  3804. char *esc_cfile;
  3805. char *methods;
  3806. abs_cfile = make_path_absolute(cfile);
  3807. esc_cfile = esc_for_log(abs_cfile);
  3808. {
  3809. int passwd = (options->HashedControlPassword != NULL ||
  3810. options->HashedControlSessionPassword != NULL);
  3811. smartlist_t *mlist = smartlist_new();
  3812. if (cookies) {
  3813. smartlist_add(mlist, (char*)"COOKIE");
  3814. smartlist_add(mlist, (char*)"SAFECOOKIE");
  3815. }
  3816. if (passwd)
  3817. smartlist_add(mlist, (char*)"HASHEDPASSWORD");
  3818. if (!cookies && !passwd)
  3819. smartlist_add(mlist, (char*)"NULL");
  3820. methods = smartlist_join_strings(mlist, ",", 0, NULL);
  3821. smartlist_free(mlist);
  3822. }
  3823. connection_printf_to_buf(conn,
  3824. "250-PROTOCOLINFO 1\r\n"
  3825. "250-AUTH METHODS=%s%s%s\r\n"
  3826. "250-VERSION Tor=%s\r\n"
  3827. "250 OK\r\n",
  3828. methods,
  3829. cookies?" COOKIEFILE=":"",
  3830. cookies?esc_cfile:"",
  3831. escaped(VERSION));
  3832. tor_free(methods);
  3833. tor_free(cfile);
  3834. tor_free(abs_cfile);
  3835. tor_free(esc_cfile);
  3836. }
  3837. done:
  3838. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  3839. smartlist_free(args);
  3840. return 0;
  3841. }
  3842. /** Called when we get an AUTHCHALLENGE command. */
  3843. static int
  3844. handle_control_authchallenge(control_connection_t *conn, uint32_t len,
  3845. const char *body)
  3846. {
  3847. const char *cp = body;
  3848. char *client_nonce;
  3849. size_t client_nonce_len;
  3850. char server_hash[DIGEST256_LEN];
  3851. char server_hash_encoded[HEX_DIGEST256_LEN+1];
  3852. char server_nonce[SAFECOOKIE_SERVER_NONCE_LEN];
  3853. char server_nonce_encoded[(2*SAFECOOKIE_SERVER_NONCE_LEN) + 1];
  3854. cp += strspn(cp, " \t\n\r");
  3855. if (!strcasecmpstart(cp, "SAFECOOKIE")) {
  3856. cp += strlen("SAFECOOKIE");
  3857. } else {
  3858. connection_write_str_to_buf("513 AUTHCHALLENGE only supports SAFECOOKIE "
  3859. "authentication\r\n", conn);
  3860. connection_mark_for_close(TO_CONN(conn));
  3861. return -1;
  3862. }
  3863. if (!authentication_cookie_is_set) {
  3864. connection_write_str_to_buf("515 Cookie authentication is disabled\r\n",
  3865. conn);
  3866. connection_mark_for_close(TO_CONN(conn));
  3867. return -1;
  3868. }
  3869. cp += strspn(cp, " \t\n\r");
  3870. if (*cp == '"') {
  3871. const char *newcp =
  3872. decode_escaped_string(cp, len - (cp - body),
  3873. &client_nonce, &client_nonce_len);
  3874. if (newcp == NULL) {
  3875. connection_write_str_to_buf("513 Invalid quoted client nonce\r\n",
  3876. conn);
  3877. connection_mark_for_close(TO_CONN(conn));
  3878. return -1;
  3879. }
  3880. cp = newcp;
  3881. } else {
  3882. size_t client_nonce_encoded_len = strspn(cp, "0123456789ABCDEFabcdef");
  3883. client_nonce_len = client_nonce_encoded_len / 2;
  3884. client_nonce = tor_malloc_zero(client_nonce_len);
  3885. if (base16_decode(client_nonce, client_nonce_len,
  3886. cp, client_nonce_encoded_len)
  3887. != (int) client_nonce_len) {
  3888. connection_write_str_to_buf("513 Invalid base16 client nonce\r\n",
  3889. conn);
  3890. connection_mark_for_close(TO_CONN(conn));
  3891. tor_free(client_nonce);
  3892. return -1;
  3893. }
  3894. cp += client_nonce_encoded_len;
  3895. }
  3896. cp += strspn(cp, " \t\n\r");
  3897. if (*cp != '\0' ||
  3898. cp != body + len) {
  3899. connection_write_str_to_buf("513 Junk at end of AUTHCHALLENGE command\r\n",
  3900. conn);
  3901. connection_mark_for_close(TO_CONN(conn));
  3902. tor_free(client_nonce);
  3903. return -1;
  3904. }
  3905. crypto_rand(server_nonce, SAFECOOKIE_SERVER_NONCE_LEN);
  3906. /* Now compute and send the server-to-controller response, and the
  3907. * server's nonce. */
  3908. tor_assert(authentication_cookie != NULL);
  3909. {
  3910. size_t tmp_len = (AUTHENTICATION_COOKIE_LEN +
  3911. client_nonce_len +
  3912. SAFECOOKIE_SERVER_NONCE_LEN);
  3913. char *tmp = tor_malloc_zero(tmp_len);
  3914. char *client_hash = tor_malloc_zero(DIGEST256_LEN);
  3915. memcpy(tmp, authentication_cookie, AUTHENTICATION_COOKIE_LEN);
  3916. memcpy(tmp + AUTHENTICATION_COOKIE_LEN, client_nonce, client_nonce_len);
  3917. memcpy(tmp + AUTHENTICATION_COOKIE_LEN + client_nonce_len,
  3918. server_nonce, SAFECOOKIE_SERVER_NONCE_LEN);
  3919. crypto_hmac_sha256(server_hash,
  3920. SAFECOOKIE_SERVER_TO_CONTROLLER_CONSTANT,
  3921. strlen(SAFECOOKIE_SERVER_TO_CONTROLLER_CONSTANT),
  3922. tmp,
  3923. tmp_len);
  3924. crypto_hmac_sha256(client_hash,
  3925. SAFECOOKIE_CONTROLLER_TO_SERVER_CONSTANT,
  3926. strlen(SAFECOOKIE_CONTROLLER_TO_SERVER_CONSTANT),
  3927. tmp,
  3928. tmp_len);
  3929. conn->safecookie_client_hash = client_hash;
  3930. tor_free(tmp);
  3931. }
  3932. base16_encode(server_hash_encoded, sizeof(server_hash_encoded),
  3933. server_hash, sizeof(server_hash));
  3934. base16_encode(server_nonce_encoded, sizeof(server_nonce_encoded),
  3935. server_nonce, sizeof(server_nonce));
  3936. connection_printf_to_buf(conn,
  3937. "250 AUTHCHALLENGE SERVERHASH=%s "
  3938. "SERVERNONCE=%s\r\n",
  3939. server_hash_encoded,
  3940. server_nonce_encoded);
  3941. tor_free(client_nonce);
  3942. return 0;
  3943. }
  3944. /** Called when we get a USEFEATURE command: parse the feature list, and
  3945. * set up the control_connection's options properly. */
  3946. static int
  3947. handle_control_usefeature(control_connection_t *conn,
  3948. uint32_t len,
  3949. const char *body)
  3950. {
  3951. smartlist_t *args;
  3952. int bad = 0;
  3953. (void) len; /* body is nul-terminated; it's safe to ignore the length */
  3954. args = smartlist_new();
  3955. smartlist_split_string(args, body, " ",
  3956. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  3957. SMARTLIST_FOREACH_BEGIN(args, const char *, arg) {
  3958. if (!strcasecmp(arg, "VERBOSE_NAMES"))
  3959. ;
  3960. else if (!strcasecmp(arg, "EXTENDED_EVENTS"))
  3961. ;
  3962. else {
  3963. connection_printf_to_buf(conn, "552 Unrecognized feature \"%s\"\r\n",
  3964. arg);
  3965. bad = 1;
  3966. break;
  3967. }
  3968. } SMARTLIST_FOREACH_END(arg);
  3969. if (!bad) {
  3970. send_control_done(conn);
  3971. }
  3972. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  3973. smartlist_free(args);
  3974. return 0;
  3975. }
  3976. /** Implementation for the DROPGUARDS command. */
  3977. static int
  3978. handle_control_dropguards(control_connection_t *conn,
  3979. uint32_t len,
  3980. const char *body)
  3981. {
  3982. smartlist_t *args;
  3983. (void) len; /* body is nul-terminated; it's safe to ignore the length */
  3984. args = smartlist_new();
  3985. smartlist_split_string(args, body, " ",
  3986. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  3987. static int have_warned = 0;
  3988. if (! have_warned) {
  3989. log_warn(LD_CONTROL, "DROPGUARDS is dangerous; make sure you understand "
  3990. "the risks before using it. It may be removed in a future "
  3991. "version of Tor.");
  3992. have_warned = 1;
  3993. }
  3994. if (smartlist_len(args)) {
  3995. connection_printf_to_buf(conn, "512 Too many arguments to DROPGUARDS\r\n");
  3996. } else {
  3997. remove_all_entry_guards();
  3998. send_control_done(conn);
  3999. }
  4000. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  4001. smartlist_free(args);
  4002. return 0;
  4003. }
  4004. /** Implementation for the HSFETCH command. */
  4005. static int
  4006. handle_control_hsfetch(control_connection_t *conn, uint32_t len,
  4007. const char *body)
  4008. {
  4009. int i;
  4010. char digest[DIGEST_LEN], *hsaddress = NULL, *arg1 = NULL, *desc_id = NULL;
  4011. smartlist_t *args = NULL, *hsdirs = NULL;
  4012. (void) len; /* body is nul-terminated; it's safe to ignore the length */
  4013. static const char *hsfetch_command = "HSFETCH";
  4014. static const char *v2_str = "v2-";
  4015. const size_t v2_str_len = strlen(v2_str);
  4016. rend_data_t *rend_query = NULL;
  4017. /* Make sure we have at least one argument, the HSAddress. */
  4018. args = getargs_helper(hsfetch_command, conn, body, 1, -1);
  4019. if (!args) {
  4020. goto exit;
  4021. }
  4022. /* Extract the first argument (either HSAddress or DescID). */
  4023. arg1 = smartlist_get(args, 0);
  4024. /* Test if it's an HS address without the .onion part. */
  4025. if (rend_valid_v2_service_id(arg1)) {
  4026. hsaddress = arg1;
  4027. } else if (strcmpstart(arg1, v2_str) == 0 &&
  4028. rend_valid_descriptor_id(arg1 + v2_str_len) &&
  4029. base32_decode(digest, sizeof(digest), arg1 + v2_str_len,
  4030. REND_DESC_ID_V2_LEN_BASE32) == 0) {
  4031. /* We have a well formed version 2 descriptor ID. Keep the decoded value
  4032. * of the id. */
  4033. desc_id = digest;
  4034. } else {
  4035. connection_printf_to_buf(conn, "513 Invalid argument \"%s\"\r\n",
  4036. arg1);
  4037. goto done;
  4038. }
  4039. static const char *opt_server = "SERVER=";
  4040. /* Skip first argument because it's the HSAddress or DescID. */
  4041. for (i = 1; i < smartlist_len(args); ++i) {
  4042. const char *arg = smartlist_get(args, i);
  4043. const node_t *node;
  4044. if (!strcasecmpstart(arg, opt_server)) {
  4045. const char *server;
  4046. server = arg + strlen(opt_server);
  4047. node = node_get_by_hex_id(server, 0);
  4048. if (!node) {
  4049. connection_printf_to_buf(conn, "552 Server \"%s\" not found\r\n",
  4050. server);
  4051. goto done;
  4052. }
  4053. if (!hsdirs) {
  4054. /* Stores routerstatus_t object for each specified server. */
  4055. hsdirs = smartlist_new();
  4056. }
  4057. /* Valid server, add it to our local list. */
  4058. smartlist_add(hsdirs, node->rs);
  4059. } else {
  4060. connection_printf_to_buf(conn, "513 Unexpected argument \"%s\"\r\n",
  4061. arg);
  4062. goto done;
  4063. }
  4064. }
  4065. rend_query = rend_data_client_create(hsaddress, desc_id, NULL,
  4066. REND_NO_AUTH);
  4067. if (rend_query == NULL) {
  4068. connection_printf_to_buf(conn, "551 Error creating the HS query\r\n");
  4069. goto done;
  4070. }
  4071. /* Using a descriptor ID, we force the user to provide at least one
  4072. * hsdir server using the SERVER= option. */
  4073. if (desc_id && (!hsdirs || !smartlist_len(hsdirs))) {
  4074. connection_printf_to_buf(conn, "512 %s option is required\r\n",
  4075. opt_server);
  4076. goto done;
  4077. }
  4078. /* We are about to trigger HSDir fetch so send the OK now because after
  4079. * that 650 event(s) are possible so better to have the 250 OK before them
  4080. * to avoid out of order replies. */
  4081. send_control_done(conn);
  4082. /* Trigger the fetch using the built rend query and possibly a list of HS
  4083. * directory to use. This function ignores the client cache thus this will
  4084. * always send a fetch command. */
  4085. rend_client_fetch_v2_desc(rend_query, hsdirs);
  4086. done:
  4087. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  4088. smartlist_free(args);
  4089. /* Contains data pointer that we don't own thus no cleanup. */
  4090. smartlist_free(hsdirs);
  4091. rend_data_free(rend_query);
  4092. exit:
  4093. return 0;
  4094. }
  4095. /** Implementation for the HSPOST command. */
  4096. static int
  4097. handle_control_hspost(control_connection_t *conn,
  4098. uint32_t len,
  4099. const char *body)
  4100. {
  4101. static const char *opt_server = "SERVER=";
  4102. static const char *opt_hsaddress = "HSADDRESS=";
  4103. smartlist_t *hs_dirs = NULL;
  4104. const char *encoded_desc = body;
  4105. size_t encoded_desc_len = len;
  4106. const char *onion_address = NULL;
  4107. char *cp = memchr(body, '\n', len);
  4108. if (cp == NULL) {
  4109. connection_printf_to_buf(conn, "251 Empty body\r\n");
  4110. return 0;
  4111. }
  4112. char *argline = tor_strndup(body, cp-body);
  4113. smartlist_t *args = smartlist_new();
  4114. /* If any SERVER= or HSADDRESS= options were specified, try to parse
  4115. * the options line. */
  4116. if (!strcasecmpstart(argline, opt_server) ||
  4117. !strcasecmpstart(argline, opt_hsaddress)) {
  4118. /* encoded_desc begins after a newline character */
  4119. cp = cp + 1;
  4120. encoded_desc = cp;
  4121. encoded_desc_len = len-(cp-body);
  4122. smartlist_split_string(args, argline, " ",
  4123. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  4124. SMARTLIST_FOREACH_BEGIN(args, const char *, arg) {
  4125. if (!strcasecmpstart(arg, opt_server)) {
  4126. const char *server = arg + strlen(opt_server);
  4127. const node_t *node = node_get_by_hex_id(server, 0);
  4128. if (!node || !node->rs) {
  4129. connection_printf_to_buf(conn, "552 Server \"%s\" not found\r\n",
  4130. server);
  4131. goto done;
  4132. }
  4133. /* Valid server, add it to our local list. */
  4134. if (!hs_dirs)
  4135. hs_dirs = smartlist_new();
  4136. smartlist_add(hs_dirs, node->rs);
  4137. } else if (!strcasecmpstart(arg, opt_hsaddress)) {
  4138. const char *address = arg + strlen(opt_hsaddress);
  4139. if (!hs_address_is_valid(address)) {
  4140. connection_printf_to_buf(conn, "512 Malformed onion address\r\n");
  4141. goto done;
  4142. }
  4143. onion_address = address;
  4144. } else {
  4145. connection_printf_to_buf(conn, "512 Unexpected argument \"%s\"\r\n",
  4146. arg);
  4147. goto done;
  4148. }
  4149. } SMARTLIST_FOREACH_END(arg);
  4150. }
  4151. /* Handle the v3 case. */
  4152. if (onion_address) {
  4153. char *desc_str = NULL;
  4154. read_escaped_data(encoded_desc, encoded_desc_len, &desc_str);
  4155. if (hs_control_hspost_command(desc_str, onion_address, hs_dirs) < 0) {
  4156. connection_printf_to_buf(conn, "554 Invalid descriptor\r\n");
  4157. } else {
  4158. send_control_done(conn);
  4159. }
  4160. tor_free(desc_str);
  4161. goto done;
  4162. }
  4163. /* From this point on, it is only v2. */
  4164. /* Read the dot encoded descriptor, and parse it. */
  4165. rend_encoded_v2_service_descriptor_t *desc =
  4166. tor_malloc_zero(sizeof(rend_encoded_v2_service_descriptor_t));
  4167. read_escaped_data(encoded_desc, encoded_desc_len, &desc->desc_str);
  4168. rend_service_descriptor_t *parsed = NULL;
  4169. char *intro_content = NULL;
  4170. size_t intro_size;
  4171. size_t encoded_size;
  4172. const char *next_desc;
  4173. if (!rend_parse_v2_service_descriptor(&parsed, desc->desc_id, &intro_content,
  4174. &intro_size, &encoded_size,
  4175. &next_desc, desc->desc_str, 1)) {
  4176. /* Post the descriptor. */
  4177. char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  4178. if (!rend_get_service_id(parsed->pk, serviceid)) {
  4179. smartlist_t *descs = smartlist_new();
  4180. smartlist_add(descs, desc);
  4181. /* We are about to trigger HS descriptor upload so send the OK now
  4182. * because after that 650 event(s) are possible so better to have the
  4183. * 250 OK before them to avoid out of order replies. */
  4184. send_control_done(conn);
  4185. /* Trigger the descriptor upload */
  4186. directory_post_to_hs_dir(parsed, descs, hs_dirs, serviceid, 0);
  4187. smartlist_free(descs);
  4188. }
  4189. rend_service_descriptor_free(parsed);
  4190. } else {
  4191. connection_printf_to_buf(conn, "554 Invalid descriptor\r\n");
  4192. }
  4193. tor_free(intro_content);
  4194. rend_encoded_v2_service_descriptor_free(desc);
  4195. done:
  4196. tor_free(argline);
  4197. smartlist_free(hs_dirs); /* Contents belong to the rend service code. */
  4198. SMARTLIST_FOREACH(args, char *, arg, tor_free(arg));
  4199. smartlist_free(args);
  4200. return 0;
  4201. }
  4202. /* Helper function for ADD_ONION that adds an ephemeral service depending on
  4203. * the given hs_version.
  4204. *
  4205. * The secret key in pk depends on the hs_version. The ownership of the key
  4206. * used in pk is given to the HS subsystem so the caller must stop accessing
  4207. * it after.
  4208. *
  4209. * The port_cfgs is a list of service port. Ownership transferred to service.
  4210. * The max_streams refers to the MaxStreams= key.
  4211. * The max_streams_close_circuit refers to the MaxStreamsCloseCircuit key.
  4212. * The auth_type is the authentication type of the clients in auth_clients.
  4213. * The ownership of that list is transferred to the service.
  4214. *
  4215. * On success (RSAE_OKAY), the address_out points to a newly allocated string
  4216. * containing the onion address without the .onion part. On error, address_out
  4217. * is untouched. */
  4218. static hs_service_add_ephemeral_status_t
  4219. add_onion_helper_add_service(int hs_version,
  4220. add_onion_secret_key_t *pk,
  4221. smartlist_t *port_cfgs, int max_streams,
  4222. int max_streams_close_circuit, int auth_type,
  4223. smartlist_t *auth_clients, char **address_out)
  4224. {
  4225. hs_service_add_ephemeral_status_t ret;
  4226. tor_assert(pk);
  4227. tor_assert(port_cfgs);
  4228. tor_assert(address_out);
  4229. switch (hs_version) {
  4230. case HS_VERSION_TWO:
  4231. ret = rend_service_add_ephemeral(pk->v2, port_cfgs, max_streams,
  4232. max_streams_close_circuit, auth_type,
  4233. auth_clients, address_out);
  4234. break;
  4235. case HS_VERSION_THREE:
  4236. ret = hs_service_add_ephemeral(pk->v3, port_cfgs, max_streams,
  4237. max_streams_close_circuit, address_out);
  4238. break;
  4239. default:
  4240. tor_assert_unreached();
  4241. }
  4242. return ret;
  4243. }
  4244. /** Called when we get a ADD_ONION command; parse the body, and set up
  4245. * the new ephemeral Onion Service. */
  4246. static int
  4247. handle_control_add_onion(control_connection_t *conn,
  4248. uint32_t len,
  4249. const char *body)
  4250. {
  4251. smartlist_t *args;
  4252. int arg_len;
  4253. (void) len; /* body is nul-terminated; it's safe to ignore the length */
  4254. args = getargs_helper("ADD_ONION", conn, body, 2, -1);
  4255. if (!args)
  4256. return 0;
  4257. arg_len = smartlist_len(args);
  4258. /* Parse all of the arguments that do not involve handling cryptographic
  4259. * material first, since there's no reason to touch that at all if any of
  4260. * the other arguments are malformed.
  4261. */
  4262. smartlist_t *port_cfgs = smartlist_new();
  4263. smartlist_t *auth_clients = NULL;
  4264. smartlist_t *auth_created_clients = NULL;
  4265. int discard_pk = 0;
  4266. int detach = 0;
  4267. int max_streams = 0;
  4268. int max_streams_close_circuit = 0;
  4269. rend_auth_type_t auth_type = REND_NO_AUTH;
  4270. /* Default to adding an anonymous hidden service if no flag is given */
  4271. int non_anonymous = 0;
  4272. for (int i = 1; i < arg_len; i++) {
  4273. static const char *port_prefix = "Port=";
  4274. static const char *flags_prefix = "Flags=";
  4275. static const char *max_s_prefix = "MaxStreams=";
  4276. static const char *auth_prefix = "ClientAuth=";
  4277. const char *arg = smartlist_get(args, (int)i);
  4278. if (!strcasecmpstart(arg, port_prefix)) {
  4279. /* "Port=VIRTPORT[,TARGET]". */
  4280. const char *port_str = arg + strlen(port_prefix);
  4281. rend_service_port_config_t *cfg =
  4282. rend_service_parse_port_config(port_str, ",", NULL);
  4283. if (!cfg) {
  4284. connection_printf_to_buf(conn, "512 Invalid VIRTPORT/TARGET\r\n");
  4285. goto out;
  4286. }
  4287. smartlist_add(port_cfgs, cfg);
  4288. } else if (!strcasecmpstart(arg, max_s_prefix)) {
  4289. /* "MaxStreams=[0..65535]". */
  4290. const char *max_s_str = arg + strlen(max_s_prefix);
  4291. int ok = 0;
  4292. max_streams = (int)tor_parse_long(max_s_str, 10, 0, 65535, &ok, NULL);
  4293. if (!ok) {
  4294. connection_printf_to_buf(conn, "512 Invalid MaxStreams\r\n");
  4295. goto out;
  4296. }
  4297. } else if (!strcasecmpstart(arg, flags_prefix)) {
  4298. /* "Flags=Flag[,Flag]", where Flag can be:
  4299. * * 'DiscardPK' - If tor generates the keypair, do not include it in
  4300. * the response.
  4301. * * 'Detach' - Do not tie this onion service to any particular control
  4302. * connection.
  4303. * * 'MaxStreamsCloseCircuit' - Close the circuit if MaxStreams is
  4304. * exceeded.
  4305. * * 'BasicAuth' - Client authorization using the 'basic' method.
  4306. * * 'NonAnonymous' - Add a non-anonymous Single Onion Service. If this
  4307. * flag is present, tor must be in non-anonymous
  4308. * hidden service mode. If this flag is absent,
  4309. * tor must be in anonymous hidden service mode.
  4310. */
  4311. static const char *discard_flag = "DiscardPK";
  4312. static const char *detach_flag = "Detach";
  4313. static const char *max_s_close_flag = "MaxStreamsCloseCircuit";
  4314. static const char *basicauth_flag = "BasicAuth";
  4315. static const char *non_anonymous_flag = "NonAnonymous";
  4316. smartlist_t *flags = smartlist_new();
  4317. int bad = 0;
  4318. smartlist_split_string(flags, arg + strlen(flags_prefix), ",",
  4319. SPLIT_IGNORE_BLANK, 0);
  4320. if (smartlist_len(flags) < 1) {
  4321. connection_printf_to_buf(conn, "512 Invalid 'Flags' argument\r\n");
  4322. bad = 1;
  4323. }
  4324. SMARTLIST_FOREACH_BEGIN(flags, const char *, flag)
  4325. {
  4326. if (!strcasecmp(flag, discard_flag)) {
  4327. discard_pk = 1;
  4328. } else if (!strcasecmp(flag, detach_flag)) {
  4329. detach = 1;
  4330. } else if (!strcasecmp(flag, max_s_close_flag)) {
  4331. max_streams_close_circuit = 1;
  4332. } else if (!strcasecmp(flag, basicauth_flag)) {
  4333. auth_type = REND_BASIC_AUTH;
  4334. } else if (!strcasecmp(flag, non_anonymous_flag)) {
  4335. non_anonymous = 1;
  4336. } else {
  4337. connection_printf_to_buf(conn,
  4338. "512 Invalid 'Flags' argument: %s\r\n",
  4339. escaped(flag));
  4340. bad = 1;
  4341. break;
  4342. }
  4343. } SMARTLIST_FOREACH_END(flag);
  4344. SMARTLIST_FOREACH(flags, char *, cp, tor_free(cp));
  4345. smartlist_free(flags);
  4346. if (bad)
  4347. goto out;
  4348. } else if (!strcasecmpstart(arg, auth_prefix)) {
  4349. char *err_msg = NULL;
  4350. int created = 0;
  4351. rend_authorized_client_t *client =
  4352. add_onion_helper_clientauth(arg + strlen(auth_prefix),
  4353. &created, &err_msg);
  4354. if (!client) {
  4355. if (err_msg) {
  4356. connection_write_str_to_buf(err_msg, conn);
  4357. tor_free(err_msg);
  4358. }
  4359. goto out;
  4360. }
  4361. if (auth_clients != NULL) {
  4362. int bad = 0;
  4363. SMARTLIST_FOREACH_BEGIN(auth_clients, rend_authorized_client_t *, ac) {
  4364. if (strcmp(ac->client_name, client->client_name) == 0) {
  4365. bad = 1;
  4366. break;
  4367. }
  4368. } SMARTLIST_FOREACH_END(ac);
  4369. if (bad) {
  4370. connection_printf_to_buf(conn,
  4371. "512 Duplicate name in ClientAuth\r\n");
  4372. rend_authorized_client_free(client);
  4373. goto out;
  4374. }
  4375. } else {
  4376. auth_clients = smartlist_new();
  4377. auth_created_clients = smartlist_new();
  4378. }
  4379. smartlist_add(auth_clients, client);
  4380. if (created) {
  4381. smartlist_add(auth_created_clients, client);
  4382. }
  4383. } else {
  4384. connection_printf_to_buf(conn, "513 Invalid argument\r\n");
  4385. goto out;
  4386. }
  4387. }
  4388. if (smartlist_len(port_cfgs) == 0) {
  4389. connection_printf_to_buf(conn, "512 Missing 'Port' argument\r\n");
  4390. goto out;
  4391. } else if (auth_type == REND_NO_AUTH && auth_clients != NULL) {
  4392. connection_printf_to_buf(conn, "512 No auth type specified\r\n");
  4393. goto out;
  4394. } else if (auth_type != REND_NO_AUTH && auth_clients == NULL) {
  4395. connection_printf_to_buf(conn, "512 No auth clients specified\r\n");
  4396. goto out;
  4397. } else if ((auth_type == REND_BASIC_AUTH &&
  4398. smartlist_len(auth_clients) > 512) ||
  4399. (auth_type == REND_STEALTH_AUTH &&
  4400. smartlist_len(auth_clients) > 16)) {
  4401. connection_printf_to_buf(conn, "512 Too many auth clients\r\n");
  4402. goto out;
  4403. } else if (non_anonymous != rend_service_non_anonymous_mode_enabled(
  4404. get_options())) {
  4405. /* If we failed, and the non-anonymous flag is set, Tor must be in
  4406. * anonymous hidden service mode.
  4407. * The error message changes based on the current Tor config:
  4408. * 512 Tor is in anonymous hidden service mode
  4409. * 512 Tor is in non-anonymous hidden service mode
  4410. * (I've deliberately written them out in full here to aid searchability.)
  4411. */
  4412. connection_printf_to_buf(conn, "512 Tor is in %sanonymous hidden service "
  4413. "mode\r\n",
  4414. non_anonymous ? "" : "non-");
  4415. goto out;
  4416. }
  4417. /* Parse the "keytype:keyblob" argument. */
  4418. int hs_version = 0;
  4419. add_onion_secret_key_t pk = { NULL };
  4420. const char *key_new_alg = NULL;
  4421. char *key_new_blob = NULL;
  4422. char *err_msg = NULL;
  4423. if (add_onion_helper_keyarg(smartlist_get(args, 0), discard_pk,
  4424. &key_new_alg, &key_new_blob, &pk, &hs_version,
  4425. &err_msg) < 0) {
  4426. if (err_msg) {
  4427. connection_write_str_to_buf(err_msg, conn);
  4428. tor_free(err_msg);
  4429. }
  4430. goto out;
  4431. }
  4432. tor_assert(!err_msg);
  4433. /* Hidden service version 3 don't have client authentication support so if
  4434. * ClientAuth was given, send back an error. */
  4435. if (hs_version == HS_VERSION_THREE && auth_clients) {
  4436. connection_printf_to_buf(conn, "513 ClientAuth not supported\r\n");
  4437. goto out;
  4438. }
  4439. /* Create the HS, using private key pk, client authentication auth_type,
  4440. * the list of auth_clients, and port config port_cfg.
  4441. * rend_service_add_ephemeral() will take ownership of pk and port_cfg,
  4442. * regardless of success/failure.
  4443. */
  4444. char *service_id = NULL;
  4445. int ret = add_onion_helper_add_service(hs_version, &pk, port_cfgs,
  4446. max_streams,
  4447. max_streams_close_circuit, auth_type,
  4448. auth_clients, &service_id);
  4449. port_cfgs = NULL; /* port_cfgs is now owned by the rendservice code. */
  4450. auth_clients = NULL; /* so is auth_clients */
  4451. switch (ret) {
  4452. case RSAE_OKAY:
  4453. {
  4454. if (detach) {
  4455. if (!detached_onion_services)
  4456. detached_onion_services = smartlist_new();
  4457. smartlist_add(detached_onion_services, service_id);
  4458. } else {
  4459. if (!conn->ephemeral_onion_services)
  4460. conn->ephemeral_onion_services = smartlist_new();
  4461. smartlist_add(conn->ephemeral_onion_services, service_id);
  4462. }
  4463. tor_assert(service_id);
  4464. connection_printf_to_buf(conn, "250-ServiceID=%s\r\n", service_id);
  4465. if (key_new_alg) {
  4466. tor_assert(key_new_blob);
  4467. connection_printf_to_buf(conn, "250-PrivateKey=%s:%s\r\n",
  4468. key_new_alg, key_new_blob);
  4469. }
  4470. if (auth_created_clients) {
  4471. SMARTLIST_FOREACH(auth_created_clients, rend_authorized_client_t *, ac, {
  4472. char *encoded = rend_auth_encode_cookie(ac->descriptor_cookie,
  4473. auth_type);
  4474. tor_assert(encoded);
  4475. connection_printf_to_buf(conn, "250-ClientAuth=%s:%s\r\n",
  4476. ac->client_name, encoded);
  4477. memwipe(encoded, 0, strlen(encoded));
  4478. tor_free(encoded);
  4479. });
  4480. }
  4481. connection_printf_to_buf(conn, "250 OK\r\n");
  4482. break;
  4483. }
  4484. case RSAE_BADPRIVKEY:
  4485. connection_printf_to_buf(conn, "551 Failed to generate onion address\r\n");
  4486. break;
  4487. case RSAE_ADDREXISTS:
  4488. connection_printf_to_buf(conn, "550 Onion address collision\r\n");
  4489. break;
  4490. case RSAE_BADVIRTPORT:
  4491. connection_printf_to_buf(conn, "512 Invalid VIRTPORT/TARGET\r\n");
  4492. break;
  4493. case RSAE_BADAUTH:
  4494. connection_printf_to_buf(conn, "512 Invalid client authorization\r\n");
  4495. break;
  4496. case RSAE_INTERNAL: /* FALLSTHROUGH */
  4497. default:
  4498. connection_printf_to_buf(conn, "551 Failed to add Onion Service\r\n");
  4499. }
  4500. if (key_new_blob) {
  4501. memwipe(key_new_blob, 0, strlen(key_new_blob));
  4502. tor_free(key_new_blob);
  4503. }
  4504. out:
  4505. if (port_cfgs) {
  4506. SMARTLIST_FOREACH(port_cfgs, rend_service_port_config_t*, p,
  4507. rend_service_port_config_free(p));
  4508. smartlist_free(port_cfgs);
  4509. }
  4510. if (auth_clients) {
  4511. SMARTLIST_FOREACH(auth_clients, rend_authorized_client_t *, ac,
  4512. rend_authorized_client_free(ac));
  4513. smartlist_free(auth_clients);
  4514. }
  4515. if (auth_created_clients) {
  4516. // Do not free entries; they are the same as auth_clients
  4517. smartlist_free(auth_created_clients);
  4518. }
  4519. SMARTLIST_FOREACH(args, char *, cp, {
  4520. memwipe(cp, 0, strlen(cp));
  4521. tor_free(cp);
  4522. });
  4523. smartlist_free(args);
  4524. return 0;
  4525. }
  4526. /** Helper function to handle parsing the KeyType:KeyBlob argument to the
  4527. * ADD_ONION command. Return a new crypto_pk_t and if a new key was generated
  4528. * and the private key not discarded, the algorithm and serialized private key,
  4529. * or NULL and an optional control protocol error message on failure. The
  4530. * caller is responsible for freeing the returned key_new_blob and err_msg.
  4531. *
  4532. * Note: The error messages returned are deliberately vague to avoid echoing
  4533. * key material.
  4534. */
  4535. STATIC int
  4536. add_onion_helper_keyarg(const char *arg, int discard_pk,
  4537. const char **key_new_alg_out, char **key_new_blob_out,
  4538. add_onion_secret_key_t *decoded_key, int *hs_version,
  4539. char **err_msg_out)
  4540. {
  4541. smartlist_t *key_args = smartlist_new();
  4542. crypto_pk_t *pk = NULL;
  4543. const char *key_new_alg = NULL;
  4544. char *key_new_blob = NULL;
  4545. char *err_msg = NULL;
  4546. int ret = -1;
  4547. smartlist_split_string(key_args, arg, ":", SPLIT_IGNORE_BLANK, 0);
  4548. if (smartlist_len(key_args) != 2) {
  4549. err_msg = tor_strdup("512 Invalid key type/blob\r\n");
  4550. goto err;
  4551. }
  4552. /* The format is "KeyType:KeyBlob". */
  4553. static const char *key_type_new = "NEW";
  4554. static const char *key_type_best = "BEST";
  4555. static const char *key_type_rsa1024 = "RSA1024";
  4556. static const char *key_type_ed25519_v3 = "ED25519-V3";
  4557. const char *key_type = smartlist_get(key_args, 0);
  4558. const char *key_blob = smartlist_get(key_args, 1);
  4559. if (!strcasecmp(key_type_rsa1024, key_type)) {
  4560. /* "RSA:<Base64 Blob>" - Loading a pre-existing RSA1024 key. */
  4561. pk = crypto_pk_base64_decode_private(key_blob, strlen(key_blob));
  4562. if (!pk) {
  4563. err_msg = tor_strdup("512 Failed to decode RSA key\r\n");
  4564. goto err;
  4565. }
  4566. if (crypto_pk_num_bits(pk) != PK_BYTES*8) {
  4567. crypto_pk_free(pk);
  4568. err_msg = tor_strdup("512 Invalid RSA key size\r\n");
  4569. goto err;
  4570. }
  4571. decoded_key->v2 = pk;
  4572. *hs_version = HS_VERSION_TWO;
  4573. } else if (!strcasecmp(key_type_ed25519_v3, key_type)) {
  4574. /* "ED25519-V3:<Base64 Blob>" - Loading a pre-existing ed25519 key. */
  4575. ed25519_secret_key_t *sk = tor_malloc_zero(sizeof(*sk));
  4576. if (base64_decode((char *) sk->seckey, sizeof(sk->seckey), key_blob,
  4577. strlen(key_blob)) != sizeof(sk->seckey)) {
  4578. tor_free(sk);
  4579. err_msg = tor_strdup("512 Failed to decode ED25519-V3 key\r\n");
  4580. goto err;
  4581. }
  4582. decoded_key->v3 = sk;
  4583. *hs_version = HS_VERSION_THREE;
  4584. } else if (!strcasecmp(key_type_new, key_type)) {
  4585. /* "NEW:<Algorithm>" - Generating a new key, blob as algorithm. */
  4586. if (!strcasecmp(key_type_rsa1024, key_blob) ||
  4587. !strcasecmp(key_type_best, key_blob)) {
  4588. /* "RSA1024", RSA 1024 bit, also currently "BEST" by default. */
  4589. pk = crypto_pk_new();
  4590. if (crypto_pk_generate_key(pk)) {
  4591. tor_asprintf(&err_msg, "551 Failed to generate %s key\r\n",
  4592. key_type_rsa1024);
  4593. goto err;
  4594. }
  4595. if (!discard_pk) {
  4596. if (crypto_pk_base64_encode_private(pk, &key_new_blob)) {
  4597. crypto_pk_free(pk);
  4598. tor_asprintf(&err_msg, "551 Failed to encode %s key\r\n",
  4599. key_type_rsa1024);
  4600. goto err;
  4601. }
  4602. key_new_alg = key_type_rsa1024;
  4603. }
  4604. decoded_key->v2 = pk;
  4605. *hs_version = HS_VERSION_TWO;
  4606. } else if (!strcasecmp(key_type_ed25519_v3, key_blob)) {
  4607. ed25519_secret_key_t *sk = tor_malloc_zero(sizeof(*sk));
  4608. if (ed25519_secret_key_generate(sk, 1) < 0) {
  4609. tor_free(sk);
  4610. tor_asprintf(&err_msg, "551 Failed to generate %s key\r\n",
  4611. key_type_ed25519_v3);
  4612. goto err;
  4613. }
  4614. if (!discard_pk) {
  4615. ssize_t len = base64_encode_size(sizeof(sk->seckey), 0) + 1;
  4616. key_new_blob = tor_malloc_zero(len);
  4617. if (base64_encode(key_new_blob, len, (const char *) sk->seckey,
  4618. sizeof(sk->seckey), 0) != (len - 1)) {
  4619. tor_free(sk);
  4620. tor_free(key_new_blob);
  4621. tor_asprintf(&err_msg, "551 Failed to encode %s key\r\n",
  4622. key_type_ed25519_v3);
  4623. goto err;
  4624. }
  4625. key_new_alg = key_type_ed25519_v3;
  4626. }
  4627. decoded_key->v3 = sk;
  4628. *hs_version = HS_VERSION_THREE;
  4629. } else {
  4630. err_msg = tor_strdup("513 Invalid key type\r\n");
  4631. goto err;
  4632. }
  4633. } else {
  4634. err_msg = tor_strdup("513 Invalid key type\r\n");
  4635. goto err;
  4636. }
  4637. /* Succeeded in loading or generating a private key. */
  4638. ret = 0;
  4639. err:
  4640. SMARTLIST_FOREACH(key_args, char *, cp, {
  4641. memwipe(cp, 0, strlen(cp));
  4642. tor_free(cp);
  4643. });
  4644. smartlist_free(key_args);
  4645. if (err_msg_out) {
  4646. *err_msg_out = err_msg;
  4647. } else {
  4648. tor_free(err_msg);
  4649. }
  4650. *key_new_alg_out = key_new_alg;
  4651. *key_new_blob_out = key_new_blob;
  4652. return ret;
  4653. }
  4654. /** Helper function to handle parsing a ClientAuth argument to the
  4655. * ADD_ONION command. Return a new rend_authorized_client_t, or NULL
  4656. * and an optional control protocol error message on failure. The
  4657. * caller is responsible for freeing the returned auth_client and err_msg.
  4658. *
  4659. * If 'created' is specified, it will be set to 1 when a new cookie has
  4660. * been generated.
  4661. */
  4662. STATIC rend_authorized_client_t *
  4663. add_onion_helper_clientauth(const char *arg, int *created, char **err_msg)
  4664. {
  4665. int ok = 0;
  4666. tor_assert(arg);
  4667. tor_assert(created);
  4668. tor_assert(err_msg);
  4669. *err_msg = NULL;
  4670. smartlist_t *auth_args = smartlist_new();
  4671. rend_authorized_client_t *client =
  4672. tor_malloc_zero(sizeof(rend_authorized_client_t));
  4673. smartlist_split_string(auth_args, arg, ":", 0, 0);
  4674. if (smartlist_len(auth_args) < 1 || smartlist_len(auth_args) > 2) {
  4675. *err_msg = tor_strdup("512 Invalid ClientAuth syntax\r\n");
  4676. goto err;
  4677. }
  4678. client->client_name = tor_strdup(smartlist_get(auth_args, 0));
  4679. if (smartlist_len(auth_args) == 2) {
  4680. char *decode_err_msg = NULL;
  4681. if (rend_auth_decode_cookie(smartlist_get(auth_args, 1),
  4682. client->descriptor_cookie,
  4683. NULL, &decode_err_msg) < 0) {
  4684. tor_assert(decode_err_msg);
  4685. tor_asprintf(err_msg, "512 %s\r\n", decode_err_msg);
  4686. tor_free(decode_err_msg);
  4687. goto err;
  4688. }
  4689. *created = 0;
  4690. } else {
  4691. crypto_rand((char *) client->descriptor_cookie, REND_DESC_COOKIE_LEN);
  4692. *created = 1;
  4693. }
  4694. if (!rend_valid_client_name(client->client_name)) {
  4695. *err_msg = tor_strdup("512 Invalid name in ClientAuth\r\n");
  4696. goto err;
  4697. }
  4698. ok = 1;
  4699. err:
  4700. SMARTLIST_FOREACH(auth_args, char *, item, tor_free(item));
  4701. smartlist_free(auth_args);
  4702. if (!ok) {
  4703. rend_authorized_client_free(client);
  4704. client = NULL;
  4705. }
  4706. return client;
  4707. }
  4708. /** Called when we get a DEL_ONION command; parse the body, and remove
  4709. * the existing ephemeral Onion Service. */
  4710. static int
  4711. handle_control_del_onion(control_connection_t *conn,
  4712. uint32_t len,
  4713. const char *body)
  4714. {
  4715. int hs_version = 0;
  4716. smartlist_t *args;
  4717. (void) len; /* body is nul-terminated; it's safe to ignore the length */
  4718. args = getargs_helper("DEL_ONION", conn, body, 1, 1);
  4719. if (!args)
  4720. return 0;
  4721. const char *service_id = smartlist_get(args, 0);
  4722. if (rend_valid_v2_service_id(service_id)) {
  4723. hs_version = HS_VERSION_TWO;
  4724. } else if (hs_address_is_valid(service_id)) {
  4725. hs_version = HS_VERSION_THREE;
  4726. } else {
  4727. connection_printf_to_buf(conn, "512 Malformed Onion Service id\r\n");
  4728. goto out;
  4729. }
  4730. /* Determine if the onion service belongs to this particular control
  4731. * connection, or if it is in the global list of detached services. If it
  4732. * is in neither, either the service ID is invalid in some way, or it
  4733. * explicitly belongs to a different control connection, and an error
  4734. * should be returned.
  4735. */
  4736. smartlist_t *services[2] = {
  4737. conn->ephemeral_onion_services,
  4738. detached_onion_services
  4739. };
  4740. smartlist_t *onion_services = NULL;
  4741. int idx = -1;
  4742. for (size_t i = 0; i < ARRAY_LENGTH(services); i++) {
  4743. idx = smartlist_string_pos(services[i], service_id);
  4744. if (idx != -1) {
  4745. onion_services = services[i];
  4746. break;
  4747. }
  4748. }
  4749. if (onion_services == NULL) {
  4750. connection_printf_to_buf(conn, "552 Unknown Onion Service id\r\n");
  4751. } else {
  4752. int ret = -1;
  4753. switch (hs_version) {
  4754. case HS_VERSION_TWO:
  4755. ret = rend_service_del_ephemeral(service_id);
  4756. break;
  4757. case HS_VERSION_THREE:
  4758. ret = hs_service_del_ephemeral(service_id);
  4759. break;
  4760. default:
  4761. /* The ret value will be -1 thus hitting the warning below. This should
  4762. * never happen because of the check at the start of the function. */
  4763. break;
  4764. }
  4765. if (ret < 0) {
  4766. /* This should *NEVER* fail, since the service is on either the
  4767. * per-control connection list, or the global one.
  4768. */
  4769. log_warn(LD_BUG, "Failed to remove Onion Service %s.",
  4770. escaped(service_id));
  4771. tor_fragile_assert();
  4772. }
  4773. /* Remove/scrub the service_id from the appropriate list. */
  4774. char *cp = smartlist_get(onion_services, idx);
  4775. smartlist_del(onion_services, idx);
  4776. memwipe(cp, 0, strlen(cp));
  4777. tor_free(cp);
  4778. send_control_done(conn);
  4779. }
  4780. out:
  4781. SMARTLIST_FOREACH(args, char *, cp, {
  4782. memwipe(cp, 0, strlen(cp));
  4783. tor_free(cp);
  4784. });
  4785. smartlist_free(args);
  4786. return 0;
  4787. }
  4788. /** Called when <b>conn</b> has no more bytes left on its outbuf. */
  4789. int
  4790. connection_control_finished_flushing(control_connection_t *conn)
  4791. {
  4792. tor_assert(conn);
  4793. return 0;
  4794. }
  4795. /** Called when <b>conn</b> has gotten its socket closed. */
  4796. int
  4797. connection_control_reached_eof(control_connection_t *conn)
  4798. {
  4799. tor_assert(conn);
  4800. log_info(LD_CONTROL,"Control connection reached EOF. Closing.");
  4801. connection_mark_for_close(TO_CONN(conn));
  4802. return 0;
  4803. }
  4804. /** Shut down this Tor instance in the same way that SIGINT would, but
  4805. * with a log message appropriate for the loss of an owning controller. */
  4806. static void
  4807. lost_owning_controller(const char *owner_type, const char *loss_manner)
  4808. {
  4809. log_notice(LD_CONTROL, "Owning controller %s has %s -- exiting now.",
  4810. owner_type, loss_manner);
  4811. activate_signal(SIGTERM);
  4812. }
  4813. /** Called when <b>conn</b> is being freed. */
  4814. void
  4815. connection_control_closed(control_connection_t *conn)
  4816. {
  4817. tor_assert(conn);
  4818. conn->event_mask = 0;
  4819. control_update_global_event_mask();
  4820. /* Close all ephemeral Onion Services if any.
  4821. * The list and it's contents are scrubbed/freed in connection_free_.
  4822. */
  4823. if (conn->ephemeral_onion_services) {
  4824. SMARTLIST_FOREACH_BEGIN(conn->ephemeral_onion_services, char *, cp) {
  4825. if (rend_valid_v2_service_id(cp)) {
  4826. rend_service_del_ephemeral(cp);
  4827. } else if (hs_address_is_valid(cp)) {
  4828. hs_service_del_ephemeral(cp);
  4829. } else {
  4830. /* An invalid .onion in our list should NEVER happen */
  4831. tor_fragile_assert();
  4832. }
  4833. } SMARTLIST_FOREACH_END(cp);
  4834. }
  4835. if (conn->is_owning_control_connection) {
  4836. lost_owning_controller("connection", "closed");
  4837. }
  4838. }
  4839. /** Return true iff <b>cmd</b> is allowable (or at least forgivable) at this
  4840. * stage of the protocol. */
  4841. static int
  4842. is_valid_initial_command(control_connection_t *conn, const char *cmd)
  4843. {
  4844. if (conn->base_.state == CONTROL_CONN_STATE_OPEN)
  4845. return 1;
  4846. if (!strcasecmp(cmd, "PROTOCOLINFO"))
  4847. return (!conn->have_sent_protocolinfo &&
  4848. conn->safecookie_client_hash == NULL);
  4849. if (!strcasecmp(cmd, "AUTHCHALLENGE"))
  4850. return (conn->safecookie_client_hash == NULL);
  4851. if (!strcasecmp(cmd, "AUTHENTICATE") ||
  4852. !strcasecmp(cmd, "QUIT"))
  4853. return 1;
  4854. return 0;
  4855. }
  4856. /** Do not accept any control command of more than 1MB in length. Anything
  4857. * that needs to be anywhere near this long probably means that one of our
  4858. * interfaces is broken. */
  4859. #define MAX_COMMAND_LINE_LENGTH (1024*1024)
  4860. /** Wrapper around peek_buf_has_control0 command: presents the same
  4861. * interface as that underlying functions, but takes a connection_t intead of
  4862. * a buf_t.
  4863. */
  4864. static int
  4865. peek_connection_has_control0_command(connection_t *conn)
  4866. {
  4867. return peek_buf_has_control0_command(conn->inbuf);
  4868. }
  4869. static int
  4870. peek_connection_has_http_command(connection_t *conn)
  4871. {
  4872. return peek_buf_has_http_command(conn->inbuf);
  4873. }
  4874. static const char CONTROLPORT_IS_NOT_AN_HTTP_PROXY_MSG[] =
  4875. "HTTP/1.0 501 Tor ControlPort is not an HTTP proxy"
  4876. "\r\nContent-Type: text/html; charset=iso-8859-1\r\n\r\n"
  4877. "<html>\n"
  4878. "<head>\n"
  4879. "<title>Tor's ControlPort is not an HTTP proxy</title>\n"
  4880. "</head>\n"
  4881. "<body>\n"
  4882. "<h1>Tor's ControlPort is not an HTTP proxy</h1>\n"
  4883. "<p>\n"
  4884. "It appears you have configured your web browser to use Tor's control port"
  4885. " as an HTTP proxy.\n"
  4886. "This is not correct: Tor's default SOCKS proxy port is 9050.\n"
  4887. "Please configure your client accordingly.\n"
  4888. "</p>\n"
  4889. "<p>\n"
  4890. "See <a href=\"https://www.torproject.org/documentation.html\">"
  4891. "https://www.torproject.org/documentation.html</a> for more "
  4892. "information.\n"
  4893. "<!-- Plus this comment, to make the body response more than 512 bytes, so "
  4894. " IE will be willing to display it. Comment comment comment comment "
  4895. " comment comment comment comment comment comment comment comment.-->\n"
  4896. "</p>\n"
  4897. "</body>\n"
  4898. "</html>\n";
  4899. /** Called when data has arrived on a v1 control connection: Try to fetch
  4900. * commands from conn->inbuf, and execute them.
  4901. */
  4902. int
  4903. connection_control_process_inbuf(control_connection_t *conn)
  4904. {
  4905. size_t data_len;
  4906. uint32_t cmd_data_len;
  4907. int cmd_len;
  4908. char *args;
  4909. tor_assert(conn);
  4910. tor_assert(conn->base_.state == CONTROL_CONN_STATE_OPEN ||
  4911. conn->base_.state == CONTROL_CONN_STATE_NEEDAUTH);
  4912. if (!conn->incoming_cmd) {
  4913. conn->incoming_cmd = tor_malloc(1024);
  4914. conn->incoming_cmd_len = 1024;
  4915. conn->incoming_cmd_cur_len = 0;
  4916. }
  4917. if (conn->base_.state == CONTROL_CONN_STATE_NEEDAUTH &&
  4918. peek_connection_has_control0_command(TO_CONN(conn))) {
  4919. /* Detect v0 commands and send a "no more v0" message. */
  4920. size_t body_len;
  4921. char buf[128];
  4922. set_uint16(buf+2, htons(0x0000)); /* type == error */
  4923. set_uint16(buf+4, htons(0x0001)); /* code == internal error */
  4924. strlcpy(buf+6, "The v0 control protocol is not supported by Tor 0.1.2.17 "
  4925. "and later; upgrade your controller.",
  4926. sizeof(buf)-6);
  4927. body_len = 2+strlen(buf+6)+2; /* code, msg, nul. */
  4928. set_uint16(buf+0, htons(body_len));
  4929. connection_buf_add(buf, 4+body_len, TO_CONN(conn));
  4930. connection_mark_and_flush(TO_CONN(conn));
  4931. return 0;
  4932. }
  4933. /* If the user has the HTTP proxy port and the control port confused. */
  4934. if (conn->base_.state == CONTROL_CONN_STATE_NEEDAUTH &&
  4935. peek_connection_has_http_command(TO_CONN(conn))) {
  4936. connection_write_str_to_buf(CONTROLPORT_IS_NOT_AN_HTTP_PROXY_MSG, conn);
  4937. log_notice(LD_CONTROL, "Received HTTP request on ControlPort");
  4938. connection_mark_and_flush(TO_CONN(conn));
  4939. return 0;
  4940. }
  4941. again:
  4942. while (1) {
  4943. size_t last_idx;
  4944. int r;
  4945. /* First, fetch a line. */
  4946. do {
  4947. data_len = conn->incoming_cmd_len - conn->incoming_cmd_cur_len;
  4948. r = connection_buf_get_line(TO_CONN(conn),
  4949. conn->incoming_cmd+conn->incoming_cmd_cur_len,
  4950. &data_len);
  4951. if (r == 0)
  4952. /* Line not all here yet. Wait. */
  4953. return 0;
  4954. else if (r == -1) {
  4955. if (data_len + conn->incoming_cmd_cur_len > MAX_COMMAND_LINE_LENGTH) {
  4956. connection_write_str_to_buf("500 Line too long.\r\n", conn);
  4957. connection_stop_reading(TO_CONN(conn));
  4958. connection_mark_and_flush(TO_CONN(conn));
  4959. }
  4960. while (conn->incoming_cmd_len < data_len+conn->incoming_cmd_cur_len)
  4961. conn->incoming_cmd_len *= 2;
  4962. conn->incoming_cmd = tor_realloc(conn->incoming_cmd,
  4963. conn->incoming_cmd_len);
  4964. }
  4965. } while (r != 1);
  4966. tor_assert(data_len);
  4967. last_idx = conn->incoming_cmd_cur_len;
  4968. conn->incoming_cmd_cur_len += (int)data_len;
  4969. /* We have appended a line to incoming_cmd. Is the command done? */
  4970. if (last_idx == 0 && *conn->incoming_cmd != '+')
  4971. /* One line command, didn't start with '+'. */
  4972. break;
  4973. /* XXXX this code duplication is kind of dumb. */
  4974. if (last_idx+3 == conn->incoming_cmd_cur_len &&
  4975. tor_memeq(conn->incoming_cmd + last_idx, ".\r\n", 3)) {
  4976. /* Just appended ".\r\n"; we're done. Remove it. */
  4977. conn->incoming_cmd[last_idx] = '\0';
  4978. conn->incoming_cmd_cur_len -= 3;
  4979. break;
  4980. } else if (last_idx+2 == conn->incoming_cmd_cur_len &&
  4981. tor_memeq(conn->incoming_cmd + last_idx, ".\n", 2)) {
  4982. /* Just appended ".\n"; we're done. Remove it. */
  4983. conn->incoming_cmd[last_idx] = '\0';
  4984. conn->incoming_cmd_cur_len -= 2;
  4985. break;
  4986. }
  4987. /* Otherwise, read another line. */
  4988. }
  4989. data_len = conn->incoming_cmd_cur_len;
  4990. /* Okay, we now have a command sitting on conn->incoming_cmd. See if we
  4991. * recognize it.
  4992. */
  4993. cmd_len = 0;
  4994. while ((size_t)cmd_len < data_len
  4995. && !TOR_ISSPACE(conn->incoming_cmd[cmd_len]))
  4996. ++cmd_len;
  4997. conn->incoming_cmd[cmd_len]='\0';
  4998. args = conn->incoming_cmd+cmd_len+1;
  4999. tor_assert(data_len>(size_t)cmd_len);
  5000. data_len -= (cmd_len+1); /* skip the command and NUL we added after it */
  5001. while (TOR_ISSPACE(*args)) {
  5002. ++args;
  5003. --data_len;
  5004. }
  5005. /* If the connection is already closing, ignore further commands */
  5006. if (TO_CONN(conn)->marked_for_close) {
  5007. return 0;
  5008. }
  5009. /* Otherwise, Quit is always valid. */
  5010. if (!strcasecmp(conn->incoming_cmd, "QUIT")) {
  5011. connection_write_str_to_buf("250 closing connection\r\n", conn);
  5012. connection_mark_and_flush(TO_CONN(conn));
  5013. return 0;
  5014. }
  5015. if (conn->base_.state == CONTROL_CONN_STATE_NEEDAUTH &&
  5016. !is_valid_initial_command(conn, conn->incoming_cmd)) {
  5017. connection_write_str_to_buf("514 Authentication required.\r\n", conn);
  5018. connection_mark_for_close(TO_CONN(conn));
  5019. return 0;
  5020. }
  5021. if (data_len >= UINT32_MAX) {
  5022. connection_write_str_to_buf("500 A 4GB command? Nice try.\r\n", conn);
  5023. connection_mark_for_close(TO_CONN(conn));
  5024. return 0;
  5025. }
  5026. /* XXXX Why is this not implemented as a table like the GETINFO
  5027. * items are? Even handling the plus signs at the beginnings of
  5028. * commands wouldn't be very hard with proper macros. */
  5029. cmd_data_len = (uint32_t)data_len;
  5030. if (!strcasecmp(conn->incoming_cmd, "SETCONF")) {
  5031. if (handle_control_setconf(conn, cmd_data_len, args))
  5032. return -1;
  5033. } else if (!strcasecmp(conn->incoming_cmd, "RESETCONF")) {
  5034. if (handle_control_resetconf(conn, cmd_data_len, args))
  5035. return -1;
  5036. } else if (!strcasecmp(conn->incoming_cmd, "GETCONF")) {
  5037. if (handle_control_getconf(conn, cmd_data_len, args))
  5038. return -1;
  5039. } else if (!strcasecmp(conn->incoming_cmd, "+LOADCONF")) {
  5040. if (handle_control_loadconf(conn, cmd_data_len, args))
  5041. return -1;
  5042. } else if (!strcasecmp(conn->incoming_cmd, "SETEVENTS")) {
  5043. if (handle_control_setevents(conn, cmd_data_len, args))
  5044. return -1;
  5045. } else if (!strcasecmp(conn->incoming_cmd, "AUTHENTICATE")) {
  5046. if (handle_control_authenticate(conn, cmd_data_len, args))
  5047. return -1;
  5048. } else if (!strcasecmp(conn->incoming_cmd, "SAVECONF")) {
  5049. if (handle_control_saveconf(conn, cmd_data_len, args))
  5050. return -1;
  5051. } else if (!strcasecmp(conn->incoming_cmd, "SIGNAL")) {
  5052. if (handle_control_signal(conn, cmd_data_len, args))
  5053. return -1;
  5054. } else if (!strcasecmp(conn->incoming_cmd, "TAKEOWNERSHIP")) {
  5055. if (handle_control_takeownership(conn, cmd_data_len, args))
  5056. return -1;
  5057. } else if (!strcasecmp(conn->incoming_cmd, "MAPADDRESS")) {
  5058. if (handle_control_mapaddress(conn, cmd_data_len, args))
  5059. return -1;
  5060. } else if (!strcasecmp(conn->incoming_cmd, "GETINFO")) {
  5061. if (handle_control_getinfo(conn, cmd_data_len, args))
  5062. return -1;
  5063. } else if (!strcasecmp(conn->incoming_cmd, "EXTENDCIRCUIT")) {
  5064. if (handle_control_extendcircuit(conn, cmd_data_len, args))
  5065. return -1;
  5066. } else if (!strcasecmp(conn->incoming_cmd, "SETCIRCUITPURPOSE")) {
  5067. if (handle_control_setcircuitpurpose(conn, cmd_data_len, args))
  5068. return -1;
  5069. } else if (!strcasecmp(conn->incoming_cmd, "SETROUTERPURPOSE")) {
  5070. connection_write_str_to_buf("511 SETROUTERPURPOSE is obsolete.\r\n", conn);
  5071. } else if (!strcasecmp(conn->incoming_cmd, "ATTACHSTREAM")) {
  5072. if (handle_control_attachstream(conn, cmd_data_len, args))
  5073. return -1;
  5074. } else if (!strcasecmp(conn->incoming_cmd, "+POSTDESCRIPTOR")) {
  5075. if (handle_control_postdescriptor(conn, cmd_data_len, args))
  5076. return -1;
  5077. } else if (!strcasecmp(conn->incoming_cmd, "REDIRECTSTREAM")) {
  5078. if (handle_control_redirectstream(conn, cmd_data_len, args))
  5079. return -1;
  5080. } else if (!strcasecmp(conn->incoming_cmd, "CLOSESTREAM")) {
  5081. if (handle_control_closestream(conn, cmd_data_len, args))
  5082. return -1;
  5083. } else if (!strcasecmp(conn->incoming_cmd, "CLOSECIRCUIT")) {
  5084. if (handle_control_closecircuit(conn, cmd_data_len, args))
  5085. return -1;
  5086. } else if (!strcasecmp(conn->incoming_cmd, "USEFEATURE")) {
  5087. if (handle_control_usefeature(conn, cmd_data_len, args))
  5088. return -1;
  5089. } else if (!strcasecmp(conn->incoming_cmd, "RESOLVE")) {
  5090. if (handle_control_resolve(conn, cmd_data_len, args))
  5091. return -1;
  5092. } else if (!strcasecmp(conn->incoming_cmd, "PROTOCOLINFO")) {
  5093. if (handle_control_protocolinfo(conn, cmd_data_len, args))
  5094. return -1;
  5095. } else if (!strcasecmp(conn->incoming_cmd, "AUTHCHALLENGE")) {
  5096. if (handle_control_authchallenge(conn, cmd_data_len, args))
  5097. return -1;
  5098. } else if (!strcasecmp(conn->incoming_cmd, "DROPGUARDS")) {
  5099. if (handle_control_dropguards(conn, cmd_data_len, args))
  5100. return -1;
  5101. } else if (!strcasecmp(conn->incoming_cmd, "HSFETCH")) {
  5102. if (handle_control_hsfetch(conn, cmd_data_len, args))
  5103. return -1;
  5104. } else if (!strcasecmp(conn->incoming_cmd, "+HSPOST")) {
  5105. if (handle_control_hspost(conn, cmd_data_len, args))
  5106. return -1;
  5107. } else if (!strcasecmp(conn->incoming_cmd, "ADD_ONION")) {
  5108. int ret = handle_control_add_onion(conn, cmd_data_len, args);
  5109. memwipe(args, 0, cmd_data_len); /* Scrub the private key. */
  5110. if (ret)
  5111. return -1;
  5112. } else if (!strcasecmp(conn->incoming_cmd, "DEL_ONION")) {
  5113. int ret = handle_control_del_onion(conn, cmd_data_len, args);
  5114. memwipe(args, 0, cmd_data_len); /* Scrub the service id/pk. */
  5115. if (ret)
  5116. return -1;
  5117. } else {
  5118. connection_printf_to_buf(conn, "510 Unrecognized command \"%s\"\r\n",
  5119. conn->incoming_cmd);
  5120. }
  5121. conn->incoming_cmd_cur_len = 0;
  5122. goto again;
  5123. }
  5124. /** Something major has happened to circuit <b>circ</b>: tell any
  5125. * interested control connections. */
  5126. int
  5127. control_event_circuit_status(origin_circuit_t *circ, circuit_status_event_t tp,
  5128. int reason_code)
  5129. {
  5130. const char *status;
  5131. char reasons[64] = "";
  5132. if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS))
  5133. return 0;
  5134. tor_assert(circ);
  5135. switch (tp)
  5136. {
  5137. case CIRC_EVENT_LAUNCHED: status = "LAUNCHED"; break;
  5138. case CIRC_EVENT_BUILT: status = "BUILT"; break;
  5139. case CIRC_EVENT_EXTENDED: status = "EXTENDED"; break;
  5140. case CIRC_EVENT_FAILED: status = "FAILED"; break;
  5141. case CIRC_EVENT_CLOSED: status = "CLOSED"; break;
  5142. default:
  5143. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  5144. tor_fragile_assert();
  5145. return 0;
  5146. }
  5147. if (tp == CIRC_EVENT_FAILED || tp == CIRC_EVENT_CLOSED) {
  5148. const char *reason_str = circuit_end_reason_to_control_string(reason_code);
  5149. char unk_reason_buf[16];
  5150. if (!reason_str) {
  5151. tor_snprintf(unk_reason_buf, 16, "UNKNOWN_%d", reason_code);
  5152. reason_str = unk_reason_buf;
  5153. }
  5154. if (reason_code > 0 && reason_code & END_CIRC_REASON_FLAG_REMOTE) {
  5155. tor_snprintf(reasons, sizeof(reasons),
  5156. " REASON=DESTROYED REMOTE_REASON=%s", reason_str);
  5157. } else {
  5158. tor_snprintf(reasons, sizeof(reasons),
  5159. " REASON=%s", reason_str);
  5160. }
  5161. }
  5162. {
  5163. char *circdesc = circuit_describe_status_for_controller(circ);
  5164. const char *sp = strlen(circdesc) ? " " : "";
  5165. send_control_event(EVENT_CIRCUIT_STATUS,
  5166. "650 CIRC %lu %s%s%s%s\r\n",
  5167. (unsigned long)circ->global_identifier,
  5168. status, sp,
  5169. circdesc,
  5170. reasons);
  5171. tor_free(circdesc);
  5172. }
  5173. return 0;
  5174. }
  5175. /** Something minor has happened to circuit <b>circ</b>: tell any
  5176. * interested control connections. */
  5177. static int
  5178. control_event_circuit_status_minor(origin_circuit_t *circ,
  5179. circuit_status_minor_event_t e,
  5180. int purpose, const struct timeval *tv)
  5181. {
  5182. const char *event_desc;
  5183. char event_tail[160] = "";
  5184. if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS_MINOR))
  5185. return 0;
  5186. tor_assert(circ);
  5187. switch (e)
  5188. {
  5189. case CIRC_MINOR_EVENT_PURPOSE_CHANGED:
  5190. event_desc = "PURPOSE_CHANGED";
  5191. {
  5192. /* event_tail can currently be up to 68 chars long */
  5193. const char *hs_state_str =
  5194. circuit_purpose_to_controller_hs_state_string(purpose);
  5195. tor_snprintf(event_tail, sizeof(event_tail),
  5196. " OLD_PURPOSE=%s%s%s",
  5197. circuit_purpose_to_controller_string(purpose),
  5198. (hs_state_str != NULL) ? " OLD_HS_STATE=" : "",
  5199. (hs_state_str != NULL) ? hs_state_str : "");
  5200. }
  5201. break;
  5202. case CIRC_MINOR_EVENT_CANNIBALIZED:
  5203. event_desc = "CANNIBALIZED";
  5204. {
  5205. /* event_tail can currently be up to 130 chars long */
  5206. const char *hs_state_str =
  5207. circuit_purpose_to_controller_hs_state_string(purpose);
  5208. const struct timeval *old_timestamp_began = tv;
  5209. char tbuf[ISO_TIME_USEC_LEN+1];
  5210. format_iso_time_nospace_usec(tbuf, old_timestamp_began);
  5211. tor_snprintf(event_tail, sizeof(event_tail),
  5212. " OLD_PURPOSE=%s%s%s OLD_TIME_CREATED=%s",
  5213. circuit_purpose_to_controller_string(purpose),
  5214. (hs_state_str != NULL) ? " OLD_HS_STATE=" : "",
  5215. (hs_state_str != NULL) ? hs_state_str : "",
  5216. tbuf);
  5217. }
  5218. break;
  5219. default:
  5220. log_warn(LD_BUG, "Unrecognized status code %d", (int)e);
  5221. tor_fragile_assert();
  5222. return 0;
  5223. }
  5224. {
  5225. char *circdesc = circuit_describe_status_for_controller(circ);
  5226. const char *sp = strlen(circdesc) ? " " : "";
  5227. send_control_event(EVENT_CIRCUIT_STATUS_MINOR,
  5228. "650 CIRC_MINOR %lu %s%s%s%s\r\n",
  5229. (unsigned long)circ->global_identifier,
  5230. event_desc, sp,
  5231. circdesc,
  5232. event_tail);
  5233. tor_free(circdesc);
  5234. }
  5235. return 0;
  5236. }
  5237. /**
  5238. * <b>circ</b> has changed its purpose from <b>old_purpose</b>: tell any
  5239. * interested controllers.
  5240. */
  5241. int
  5242. control_event_circuit_purpose_changed(origin_circuit_t *circ,
  5243. int old_purpose)
  5244. {
  5245. return control_event_circuit_status_minor(circ,
  5246. CIRC_MINOR_EVENT_PURPOSE_CHANGED,
  5247. old_purpose,
  5248. NULL);
  5249. }
  5250. /**
  5251. * <b>circ</b> has changed its purpose from <b>old_purpose</b>, and its
  5252. * created-time from <b>old_tv_created</b>: tell any interested controllers.
  5253. */
  5254. int
  5255. control_event_circuit_cannibalized(origin_circuit_t *circ,
  5256. int old_purpose,
  5257. const struct timeval *old_tv_created)
  5258. {
  5259. return control_event_circuit_status_minor(circ,
  5260. CIRC_MINOR_EVENT_CANNIBALIZED,
  5261. old_purpose,
  5262. old_tv_created);
  5263. }
  5264. /** Given an AP connection <b>conn</b> and a <b>len</b>-character buffer
  5265. * <b>buf</b>, determine the address:port combination requested on
  5266. * <b>conn</b>, and write it to <b>buf</b>. Return 0 on success, -1 on
  5267. * failure. */
  5268. static int
  5269. write_stream_target_to_buf(entry_connection_t *conn, char *buf, size_t len)
  5270. {
  5271. char buf2[256];
  5272. if (conn->chosen_exit_name)
  5273. if (tor_snprintf(buf2, sizeof(buf2), ".%s.exit", conn->chosen_exit_name)<0)
  5274. return -1;
  5275. if (!conn->socks_request)
  5276. return -1;
  5277. if (tor_snprintf(buf, len, "%s%s%s:%d",
  5278. conn->socks_request->address,
  5279. conn->chosen_exit_name ? buf2 : "",
  5280. !conn->chosen_exit_name && connection_edge_is_rendezvous_stream(
  5281. ENTRY_TO_EDGE_CONN(conn)) ? ".onion" : "",
  5282. conn->socks_request->port)<0)
  5283. return -1;
  5284. return 0;
  5285. }
  5286. /** Something has happened to the stream associated with AP connection
  5287. * <b>conn</b>: tell any interested control connections. */
  5288. int
  5289. control_event_stream_status(entry_connection_t *conn, stream_status_event_t tp,
  5290. int reason_code)
  5291. {
  5292. char reason_buf[64];
  5293. char addrport_buf[64];
  5294. const char *status;
  5295. circuit_t *circ;
  5296. origin_circuit_t *origin_circ = NULL;
  5297. char buf[256];
  5298. const char *purpose = "";
  5299. tor_assert(conn->socks_request);
  5300. if (!EVENT_IS_INTERESTING(EVENT_STREAM_STATUS))
  5301. return 0;
  5302. if (tp == STREAM_EVENT_CLOSED &&
  5303. (reason_code & END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED))
  5304. return 0;
  5305. write_stream_target_to_buf(conn, buf, sizeof(buf));
  5306. reason_buf[0] = '\0';
  5307. switch (tp)
  5308. {
  5309. case STREAM_EVENT_SENT_CONNECT: status = "SENTCONNECT"; break;
  5310. case STREAM_EVENT_SENT_RESOLVE: status = "SENTRESOLVE"; break;
  5311. case STREAM_EVENT_SUCCEEDED: status = "SUCCEEDED"; break;
  5312. case STREAM_EVENT_FAILED: status = "FAILED"; break;
  5313. case STREAM_EVENT_CLOSED: status = "CLOSED"; break;
  5314. case STREAM_EVENT_NEW: status = "NEW"; break;
  5315. case STREAM_EVENT_NEW_RESOLVE: status = "NEWRESOLVE"; break;
  5316. case STREAM_EVENT_FAILED_RETRIABLE: status = "DETACHED"; break;
  5317. case STREAM_EVENT_REMAP: status = "REMAP"; break;
  5318. default:
  5319. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  5320. return 0;
  5321. }
  5322. if (reason_code && (tp == STREAM_EVENT_FAILED ||
  5323. tp == STREAM_EVENT_CLOSED ||
  5324. tp == STREAM_EVENT_FAILED_RETRIABLE)) {
  5325. const char *reason_str = stream_end_reason_to_control_string(reason_code);
  5326. char *r = NULL;
  5327. if (!reason_str) {
  5328. tor_asprintf(&r, " UNKNOWN_%d", reason_code);
  5329. reason_str = r;
  5330. }
  5331. if (reason_code & END_STREAM_REASON_FLAG_REMOTE)
  5332. tor_snprintf(reason_buf, sizeof(reason_buf),
  5333. " REASON=END REMOTE_REASON=%s", reason_str);
  5334. else
  5335. tor_snprintf(reason_buf, sizeof(reason_buf),
  5336. " REASON=%s", reason_str);
  5337. tor_free(r);
  5338. } else if (reason_code && tp == STREAM_EVENT_REMAP) {
  5339. switch (reason_code) {
  5340. case REMAP_STREAM_SOURCE_CACHE:
  5341. strlcpy(reason_buf, " SOURCE=CACHE", sizeof(reason_buf));
  5342. break;
  5343. case REMAP_STREAM_SOURCE_EXIT:
  5344. strlcpy(reason_buf, " SOURCE=EXIT", sizeof(reason_buf));
  5345. break;
  5346. default:
  5347. tor_snprintf(reason_buf, sizeof(reason_buf), " REASON=UNKNOWN_%d",
  5348. reason_code);
  5349. /* XXX do we want SOURCE=UNKNOWN_%d above instead? -RD */
  5350. break;
  5351. }
  5352. }
  5353. if (tp == STREAM_EVENT_NEW || tp == STREAM_EVENT_NEW_RESOLVE) {
  5354. /*
  5355. * When the control conn is an AF_UNIX socket and we have no address,
  5356. * it gets set to "(Tor_internal)"; see dnsserv_launch_request() in
  5357. * dnsserv.c.
  5358. */
  5359. if (strcmp(ENTRY_TO_CONN(conn)->address, "(Tor_internal)") != 0) {
  5360. tor_snprintf(addrport_buf,sizeof(addrport_buf), " SOURCE_ADDR=%s:%d",
  5361. ENTRY_TO_CONN(conn)->address, ENTRY_TO_CONN(conn)->port);
  5362. } else {
  5363. /*
  5364. * else leave it blank so control on AF_UNIX doesn't need to make
  5365. * something up.
  5366. */
  5367. addrport_buf[0] = '\0';
  5368. }
  5369. } else {
  5370. addrport_buf[0] = '\0';
  5371. }
  5372. if (tp == STREAM_EVENT_NEW_RESOLVE) {
  5373. purpose = " PURPOSE=DNS_REQUEST";
  5374. } else if (tp == STREAM_EVENT_NEW) {
  5375. if (conn->use_begindir) {
  5376. connection_t *linked = ENTRY_TO_CONN(conn)->linked_conn;
  5377. int linked_dir_purpose = -1;
  5378. if (linked && linked->type == CONN_TYPE_DIR)
  5379. linked_dir_purpose = linked->purpose;
  5380. if (DIR_PURPOSE_IS_UPLOAD(linked_dir_purpose))
  5381. purpose = " PURPOSE=DIR_UPLOAD";
  5382. else
  5383. purpose = " PURPOSE=DIR_FETCH";
  5384. } else
  5385. purpose = " PURPOSE=USER";
  5386. }
  5387. circ = circuit_get_by_edge_conn(ENTRY_TO_EDGE_CONN(conn));
  5388. if (circ && CIRCUIT_IS_ORIGIN(circ))
  5389. origin_circ = TO_ORIGIN_CIRCUIT(circ);
  5390. send_control_event(EVENT_STREAM_STATUS,
  5391. "650 STREAM %"PRIu64" %s %lu %s%s%s%s\r\n",
  5392. (ENTRY_TO_CONN(conn)->global_identifier),
  5393. status,
  5394. origin_circ?
  5395. (unsigned long)origin_circ->global_identifier : 0ul,
  5396. buf, reason_buf, addrport_buf, purpose);
  5397. /* XXX need to specify its intended exit, etc? */
  5398. return 0;
  5399. }
  5400. /** Figure out the best name for the target router of an OR connection
  5401. * <b>conn</b>, and write it into the <b>len</b>-character buffer
  5402. * <b>name</b>. */
  5403. static void
  5404. orconn_target_get_name(char *name, size_t len, or_connection_t *conn)
  5405. {
  5406. const node_t *node = node_get_by_id(conn->identity_digest);
  5407. if (node) {
  5408. tor_assert(len > MAX_VERBOSE_NICKNAME_LEN);
  5409. node_get_verbose_nickname(node, name);
  5410. } else if (! tor_digest_is_zero(conn->identity_digest)) {
  5411. name[0] = '$';
  5412. base16_encode(name+1, len-1, conn->identity_digest,
  5413. DIGEST_LEN);
  5414. } else {
  5415. tor_snprintf(name, len, "%s:%d",
  5416. conn->base_.address, conn->base_.port);
  5417. }
  5418. }
  5419. /** Called when the status of an OR connection <b>conn</b> changes: tell any
  5420. * interested control connections. <b>tp</b> is the new status for the
  5421. * connection. If <b>conn</b> has just closed or failed, then <b>reason</b>
  5422. * may be the reason why.
  5423. */
  5424. int
  5425. control_event_or_conn_status(or_connection_t *conn, or_conn_status_event_t tp,
  5426. int reason)
  5427. {
  5428. int ncircs = 0;
  5429. const char *status;
  5430. char name[128];
  5431. char ncircs_buf[32] = {0}; /* > 8 + log10(2^32)=10 + 2 */
  5432. if (!EVENT_IS_INTERESTING(EVENT_OR_CONN_STATUS))
  5433. return 0;
  5434. switch (tp)
  5435. {
  5436. case OR_CONN_EVENT_LAUNCHED: status = "LAUNCHED"; break;
  5437. case OR_CONN_EVENT_CONNECTED: status = "CONNECTED"; break;
  5438. case OR_CONN_EVENT_FAILED: status = "FAILED"; break;
  5439. case OR_CONN_EVENT_CLOSED: status = "CLOSED"; break;
  5440. case OR_CONN_EVENT_NEW: status = "NEW"; break;
  5441. default:
  5442. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  5443. return 0;
  5444. }
  5445. if (conn->chan) {
  5446. ncircs = circuit_count_pending_on_channel(TLS_CHAN_TO_BASE(conn->chan));
  5447. } else {
  5448. ncircs = 0;
  5449. }
  5450. ncircs += connection_or_get_num_circuits(conn);
  5451. if (ncircs && (tp == OR_CONN_EVENT_FAILED || tp == OR_CONN_EVENT_CLOSED)) {
  5452. tor_snprintf(ncircs_buf, sizeof(ncircs_buf), " NCIRCS=%d", ncircs);
  5453. }
  5454. orconn_target_get_name(name, sizeof(name), conn);
  5455. send_control_event(EVENT_OR_CONN_STATUS,
  5456. "650 ORCONN %s %s%s%s%s ID=%"PRIu64"\r\n",
  5457. name, status,
  5458. reason ? " REASON=" : "",
  5459. orconn_end_reason_to_control_string(reason),
  5460. ncircs_buf,
  5461. (conn->base_.global_identifier));
  5462. return 0;
  5463. }
  5464. /**
  5465. * Print out STREAM_BW event for a single conn
  5466. */
  5467. int
  5468. control_event_stream_bandwidth(edge_connection_t *edge_conn)
  5469. {
  5470. struct timeval now;
  5471. char tbuf[ISO_TIME_USEC_LEN+1];
  5472. if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED)) {
  5473. if (!edge_conn->n_read && !edge_conn->n_written)
  5474. return 0;
  5475. tor_gettimeofday(&now);
  5476. format_iso_time_nospace_usec(tbuf, &now);
  5477. send_control_event(EVENT_STREAM_BANDWIDTH_USED,
  5478. "650 STREAM_BW %"PRIu64" %lu %lu %s\r\n",
  5479. (edge_conn->base_.global_identifier),
  5480. (unsigned long)edge_conn->n_read,
  5481. (unsigned long)edge_conn->n_written,
  5482. tbuf);
  5483. edge_conn->n_written = edge_conn->n_read = 0;
  5484. }
  5485. return 0;
  5486. }
  5487. /** A second or more has elapsed: tell any interested control
  5488. * connections how much bandwidth streams have used. */
  5489. int
  5490. control_event_stream_bandwidth_used(void)
  5491. {
  5492. if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED)) {
  5493. smartlist_t *conns = get_connection_array();
  5494. edge_connection_t *edge_conn;
  5495. struct timeval now;
  5496. char tbuf[ISO_TIME_USEC_LEN+1];
  5497. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn)
  5498. {
  5499. if (conn->type != CONN_TYPE_AP)
  5500. continue;
  5501. edge_conn = TO_EDGE_CONN(conn);
  5502. if (!edge_conn->n_read && !edge_conn->n_written)
  5503. continue;
  5504. tor_gettimeofday(&now);
  5505. format_iso_time_nospace_usec(tbuf, &now);
  5506. send_control_event(EVENT_STREAM_BANDWIDTH_USED,
  5507. "650 STREAM_BW %"PRIu64" %lu %lu %s\r\n",
  5508. (edge_conn->base_.global_identifier),
  5509. (unsigned long)edge_conn->n_read,
  5510. (unsigned long)edge_conn->n_written,
  5511. tbuf);
  5512. edge_conn->n_written = edge_conn->n_read = 0;
  5513. }
  5514. SMARTLIST_FOREACH_END(conn);
  5515. }
  5516. return 0;
  5517. }
  5518. /** A second or more has elapsed: tell any interested control connections
  5519. * how much bandwidth origin circuits have used. */
  5520. int
  5521. control_event_circ_bandwidth_used(void)
  5522. {
  5523. if (!EVENT_IS_INTERESTING(EVENT_CIRC_BANDWIDTH_USED))
  5524. return 0;
  5525. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  5526. if (!CIRCUIT_IS_ORIGIN(circ))
  5527. continue;
  5528. control_event_circ_bandwidth_used_for_circ(TO_ORIGIN_CIRCUIT(circ));
  5529. }
  5530. SMARTLIST_FOREACH_END(circ);
  5531. return 0;
  5532. }
  5533. /**
  5534. * Emit a CIRC_BW event line for a specific circuit.
  5535. *
  5536. * This function sets the values it emits to 0, and does not emit
  5537. * an event if there is no new data to report since the last call.
  5538. *
  5539. * Therefore, it may be called at any frequency.
  5540. */
  5541. int
  5542. control_event_circ_bandwidth_used_for_circ(origin_circuit_t *ocirc)
  5543. {
  5544. struct timeval now;
  5545. char tbuf[ISO_TIME_USEC_LEN+1];
  5546. tor_assert(ocirc);
  5547. if (!EVENT_IS_INTERESTING(EVENT_CIRC_BANDWIDTH_USED))
  5548. return 0;
  5549. /* n_read_circ_bw and n_written_circ_bw are always updated
  5550. * when there is any new cell on a circuit, and set to 0 after
  5551. * the event, below.
  5552. *
  5553. * Therefore, checking them is sufficient to determine if there
  5554. * is new data to report. */
  5555. if (!ocirc->n_read_circ_bw && !ocirc->n_written_circ_bw)
  5556. return 0;
  5557. tor_gettimeofday(&now);
  5558. format_iso_time_nospace_usec(tbuf, &now);
  5559. send_control_event(EVENT_CIRC_BANDWIDTH_USED,
  5560. "650 CIRC_BW ID=%d READ=%lu WRITTEN=%lu TIME=%s "
  5561. "DELIVERED_READ=%lu OVERHEAD_READ=%lu "
  5562. "DELIVERED_WRITTEN=%lu OVERHEAD_WRITTEN=%lu\r\n",
  5563. ocirc->global_identifier,
  5564. (unsigned long)ocirc->n_read_circ_bw,
  5565. (unsigned long)ocirc->n_written_circ_bw,
  5566. tbuf,
  5567. (unsigned long)ocirc->n_delivered_read_circ_bw,
  5568. (unsigned long)ocirc->n_overhead_read_circ_bw,
  5569. (unsigned long)ocirc->n_delivered_written_circ_bw,
  5570. (unsigned long)ocirc->n_overhead_written_circ_bw);
  5571. ocirc->n_written_circ_bw = ocirc->n_read_circ_bw = 0;
  5572. ocirc->n_overhead_written_circ_bw = ocirc->n_overhead_read_circ_bw = 0;
  5573. ocirc->n_delivered_written_circ_bw = ocirc->n_delivered_read_circ_bw = 0;
  5574. return 0;
  5575. }
  5576. /** Print out CONN_BW event for a single OR/DIR/EXIT <b>conn</b> and reset
  5577. * bandwidth counters. */
  5578. int
  5579. control_event_conn_bandwidth(connection_t *conn)
  5580. {
  5581. const char *conn_type_str;
  5582. if (!get_options()->TestingEnableConnBwEvent ||
  5583. !EVENT_IS_INTERESTING(EVENT_CONN_BW))
  5584. return 0;
  5585. if (!conn->n_read_conn_bw && !conn->n_written_conn_bw)
  5586. return 0;
  5587. switch (conn->type) {
  5588. case CONN_TYPE_OR:
  5589. conn_type_str = "OR";
  5590. break;
  5591. case CONN_TYPE_DIR:
  5592. conn_type_str = "DIR";
  5593. break;
  5594. case CONN_TYPE_EXIT:
  5595. conn_type_str = "EXIT";
  5596. break;
  5597. default:
  5598. return 0;
  5599. }
  5600. send_control_event(EVENT_CONN_BW,
  5601. "650 CONN_BW ID=%"PRIu64" TYPE=%s "
  5602. "READ=%lu WRITTEN=%lu\r\n",
  5603. (conn->global_identifier),
  5604. conn_type_str,
  5605. (unsigned long)conn->n_read_conn_bw,
  5606. (unsigned long)conn->n_written_conn_bw);
  5607. conn->n_written_conn_bw = conn->n_read_conn_bw = 0;
  5608. return 0;
  5609. }
  5610. /** A second or more has elapsed: tell any interested control
  5611. * connections how much bandwidth connections have used. */
  5612. int
  5613. control_event_conn_bandwidth_used(void)
  5614. {
  5615. if (get_options()->TestingEnableConnBwEvent &&
  5616. EVENT_IS_INTERESTING(EVENT_CONN_BW)) {
  5617. SMARTLIST_FOREACH(get_connection_array(), connection_t *, conn,
  5618. control_event_conn_bandwidth(conn));
  5619. }
  5620. return 0;
  5621. }
  5622. /** Helper: iterate over cell statistics of <b>circ</b> and sum up added
  5623. * cells, removed cells, and waiting times by cell command and direction.
  5624. * Store results in <b>cell_stats</b>. Free cell statistics of the
  5625. * circuit afterwards. */
  5626. void
  5627. sum_up_cell_stats_by_command(circuit_t *circ, cell_stats_t *cell_stats)
  5628. {
  5629. memset(cell_stats, 0, sizeof(cell_stats_t));
  5630. SMARTLIST_FOREACH_BEGIN(circ->testing_cell_stats,
  5631. const testing_cell_stats_entry_t *, ent) {
  5632. tor_assert(ent->command <= CELL_COMMAND_MAX_);
  5633. if (!ent->removed && !ent->exitward) {
  5634. cell_stats->added_cells_appward[ent->command] += 1;
  5635. } else if (!ent->removed && ent->exitward) {
  5636. cell_stats->added_cells_exitward[ent->command] += 1;
  5637. } else if (!ent->exitward) {
  5638. cell_stats->removed_cells_appward[ent->command] += 1;
  5639. cell_stats->total_time_appward[ent->command] += ent->waiting_time * 10;
  5640. } else {
  5641. cell_stats->removed_cells_exitward[ent->command] += 1;
  5642. cell_stats->total_time_exitward[ent->command] += ent->waiting_time * 10;
  5643. }
  5644. } SMARTLIST_FOREACH_END(ent);
  5645. circuit_clear_testing_cell_stats(circ);
  5646. }
  5647. /** Helper: append a cell statistics string to <code>event_parts</code>,
  5648. * prefixed with <code>key</code>=. Statistics consist of comma-separated
  5649. * key:value pairs with lower-case command strings as keys and cell
  5650. * numbers or total waiting times as values. A key:value pair is included
  5651. * if the entry in <code>include_if_non_zero</code> is not zero, but with
  5652. * the (possibly zero) entry from <code>number_to_include</code>. Both
  5653. * arrays are expected to have a length of CELL_COMMAND_MAX_ + 1. If no
  5654. * entry in <code>include_if_non_zero</code> is positive, no string will
  5655. * be added to <code>event_parts</code>. */
  5656. void
  5657. append_cell_stats_by_command(smartlist_t *event_parts, const char *key,
  5658. const uint64_t *include_if_non_zero,
  5659. const uint64_t *number_to_include)
  5660. {
  5661. smartlist_t *key_value_strings = smartlist_new();
  5662. int i;
  5663. for (i = 0; i <= CELL_COMMAND_MAX_; i++) {
  5664. if (include_if_non_zero[i] > 0) {
  5665. smartlist_add_asprintf(key_value_strings, "%s:%"PRIu64,
  5666. cell_command_to_string(i),
  5667. (number_to_include[i]));
  5668. }
  5669. }
  5670. if (smartlist_len(key_value_strings) > 0) {
  5671. char *joined = smartlist_join_strings(key_value_strings, ",", 0, NULL);
  5672. smartlist_add_asprintf(event_parts, "%s=%s", key, joined);
  5673. SMARTLIST_FOREACH(key_value_strings, char *, cp, tor_free(cp));
  5674. tor_free(joined);
  5675. }
  5676. smartlist_free(key_value_strings);
  5677. }
  5678. /** Helper: format <b>cell_stats</b> for <b>circ</b> for inclusion in a
  5679. * CELL_STATS event and write result string to <b>event_string</b>. */
  5680. void
  5681. format_cell_stats(char **event_string, circuit_t *circ,
  5682. cell_stats_t *cell_stats)
  5683. {
  5684. smartlist_t *event_parts = smartlist_new();
  5685. if (CIRCUIT_IS_ORIGIN(circ)) {
  5686. origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
  5687. smartlist_add_asprintf(event_parts, "ID=%lu",
  5688. (unsigned long)ocirc->global_identifier);
  5689. } else if (TO_OR_CIRCUIT(circ)->p_chan) {
  5690. or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
  5691. smartlist_add_asprintf(event_parts, "InboundQueue=%lu",
  5692. (unsigned long)or_circ->p_circ_id);
  5693. smartlist_add_asprintf(event_parts, "InboundConn=%"PRIu64,
  5694. (or_circ->p_chan->global_identifier));
  5695. append_cell_stats_by_command(event_parts, "InboundAdded",
  5696. cell_stats->added_cells_appward,
  5697. cell_stats->added_cells_appward);
  5698. append_cell_stats_by_command(event_parts, "InboundRemoved",
  5699. cell_stats->removed_cells_appward,
  5700. cell_stats->removed_cells_appward);
  5701. append_cell_stats_by_command(event_parts, "InboundTime",
  5702. cell_stats->removed_cells_appward,
  5703. cell_stats->total_time_appward);
  5704. }
  5705. if (circ->n_chan) {
  5706. smartlist_add_asprintf(event_parts, "OutboundQueue=%lu",
  5707. (unsigned long)circ->n_circ_id);
  5708. smartlist_add_asprintf(event_parts, "OutboundConn=%"PRIu64,
  5709. (circ->n_chan->global_identifier));
  5710. append_cell_stats_by_command(event_parts, "OutboundAdded",
  5711. cell_stats->added_cells_exitward,
  5712. cell_stats->added_cells_exitward);
  5713. append_cell_stats_by_command(event_parts, "OutboundRemoved",
  5714. cell_stats->removed_cells_exitward,
  5715. cell_stats->removed_cells_exitward);
  5716. append_cell_stats_by_command(event_parts, "OutboundTime",
  5717. cell_stats->removed_cells_exitward,
  5718. cell_stats->total_time_exitward);
  5719. }
  5720. *event_string = smartlist_join_strings(event_parts, " ", 0, NULL);
  5721. SMARTLIST_FOREACH(event_parts, char *, cp, tor_free(cp));
  5722. smartlist_free(event_parts);
  5723. }
  5724. /** A second or more has elapsed: tell any interested control connection
  5725. * how many cells have been processed for a given circuit. */
  5726. int
  5727. control_event_circuit_cell_stats(void)
  5728. {
  5729. cell_stats_t *cell_stats;
  5730. char *event_string;
  5731. if (!get_options()->TestingEnableCellStatsEvent ||
  5732. !EVENT_IS_INTERESTING(EVENT_CELL_STATS))
  5733. return 0;
  5734. cell_stats = tor_malloc(sizeof(cell_stats_t));
  5735. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  5736. if (!circ->testing_cell_stats)
  5737. continue;
  5738. sum_up_cell_stats_by_command(circ, cell_stats);
  5739. format_cell_stats(&event_string, circ, cell_stats);
  5740. send_control_event(EVENT_CELL_STATS,
  5741. "650 CELL_STATS %s\r\n", event_string);
  5742. tor_free(event_string);
  5743. }
  5744. SMARTLIST_FOREACH_END(circ);
  5745. tor_free(cell_stats);
  5746. return 0;
  5747. }
  5748. /* about 5 minutes worth. */
  5749. #define N_BW_EVENTS_TO_CACHE 300
  5750. /* Index into cached_bw_events to next write. */
  5751. static int next_measurement_idx = 0;
  5752. /* number of entries set in n_measurements */
  5753. static int n_measurements = 0;
  5754. static struct cached_bw_event_s {
  5755. uint32_t n_read;
  5756. uint32_t n_written;
  5757. } cached_bw_events[N_BW_EVENTS_TO_CACHE];
  5758. /** A second or more has elapsed: tell any interested control
  5759. * connections how much bandwidth we used. */
  5760. int
  5761. control_event_bandwidth_used(uint32_t n_read, uint32_t n_written)
  5762. {
  5763. cached_bw_events[next_measurement_idx].n_read = n_read;
  5764. cached_bw_events[next_measurement_idx].n_written = n_written;
  5765. if (++next_measurement_idx == N_BW_EVENTS_TO_CACHE)
  5766. next_measurement_idx = 0;
  5767. if (n_measurements < N_BW_EVENTS_TO_CACHE)
  5768. ++n_measurements;
  5769. if (EVENT_IS_INTERESTING(EVENT_BANDWIDTH_USED)) {
  5770. send_control_event(EVENT_BANDWIDTH_USED,
  5771. "650 BW %lu %lu\r\n",
  5772. (unsigned long)n_read,
  5773. (unsigned long)n_written);
  5774. }
  5775. return 0;
  5776. }
  5777. STATIC char *
  5778. get_bw_samples(void)
  5779. {
  5780. int i;
  5781. int idx = (next_measurement_idx + N_BW_EVENTS_TO_CACHE - n_measurements)
  5782. % N_BW_EVENTS_TO_CACHE;
  5783. tor_assert(0 <= idx && idx < N_BW_EVENTS_TO_CACHE);
  5784. smartlist_t *elements = smartlist_new();
  5785. for (i = 0; i < n_measurements; ++i) {
  5786. tor_assert(0 <= idx && idx < N_BW_EVENTS_TO_CACHE);
  5787. const struct cached_bw_event_s *bwe = &cached_bw_events[idx];
  5788. smartlist_add_asprintf(elements, "%u,%u",
  5789. (unsigned)bwe->n_read,
  5790. (unsigned)bwe->n_written);
  5791. idx = (idx + 1) % N_BW_EVENTS_TO_CACHE;
  5792. }
  5793. char *result = smartlist_join_strings(elements, " ", 0, NULL);
  5794. SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
  5795. smartlist_free(elements);
  5796. return result;
  5797. }
  5798. /** Called when we are sending a log message to the controllers: suspend
  5799. * sending further log messages to the controllers until we're done. Used by
  5800. * CONN_LOG_PROTECT. */
  5801. void
  5802. disable_control_logging(void)
  5803. {
  5804. ++disable_log_messages;
  5805. }
  5806. /** We're done sending a log message to the controllers: re-enable controller
  5807. * logging. Used by CONN_LOG_PROTECT. */
  5808. void
  5809. enable_control_logging(void)
  5810. {
  5811. if (--disable_log_messages < 0)
  5812. tor_assert(0);
  5813. }
  5814. /** We got a log message: tell any interested control connections. */
  5815. void
  5816. control_event_logmsg(int severity, uint32_t domain, const char *msg)
  5817. {
  5818. int event;
  5819. /* Don't even think of trying to add stuff to a buffer from a cpuworker
  5820. * thread. (See #25987 for plan to fix.) */
  5821. if (! in_main_thread())
  5822. return;
  5823. if (disable_log_messages)
  5824. return;
  5825. if (domain == LD_BUG && EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL) &&
  5826. severity <= LOG_NOTICE) {
  5827. char *esc = esc_for_log(msg);
  5828. ++disable_log_messages;
  5829. control_event_general_status(severity, "BUG REASON=%s", esc);
  5830. --disable_log_messages;
  5831. tor_free(esc);
  5832. }
  5833. event = log_severity_to_event(severity);
  5834. if (event >= 0 && EVENT_IS_INTERESTING(event)) {
  5835. char *b = NULL;
  5836. const char *s;
  5837. if (strchr(msg, '\n')) {
  5838. char *cp;
  5839. b = tor_strdup(msg);
  5840. for (cp = b; *cp; ++cp)
  5841. if (*cp == '\r' || *cp == '\n')
  5842. *cp = ' ';
  5843. }
  5844. switch (severity) {
  5845. case LOG_DEBUG: s = "DEBUG"; break;
  5846. case LOG_INFO: s = "INFO"; break;
  5847. case LOG_NOTICE: s = "NOTICE"; break;
  5848. case LOG_WARN: s = "WARN"; break;
  5849. case LOG_ERR: s = "ERR"; break;
  5850. default: s = "UnknownLogSeverity"; break;
  5851. }
  5852. ++disable_log_messages;
  5853. send_control_event(event, "650 %s %s\r\n", s, b?b:msg);
  5854. if (severity == LOG_ERR) {
  5855. /* Force a flush, since we may be about to die horribly */
  5856. queued_events_flush_all(1);
  5857. }
  5858. --disable_log_messages;
  5859. tor_free(b);
  5860. }
  5861. }
  5862. /**
  5863. * Logging callback: called when there is a queued pending log callback.
  5864. */
  5865. void
  5866. control_event_logmsg_pending(void)
  5867. {
  5868. if (! in_main_thread()) {
  5869. /* We can't handle this case yet, since we're using a
  5870. * mainloop_event_t to invoke queued_events_flush_all. We ought to
  5871. * use a different mechanism instead: see #25987.
  5872. **/
  5873. return;
  5874. }
  5875. tor_assert(flush_queued_events_event);
  5876. mainloop_event_activate(flush_queued_events_event);
  5877. }
  5878. /** Called whenever we receive new router descriptors: tell any
  5879. * interested control connections. <b>routers</b> is a list of
  5880. * routerinfo_t's.
  5881. */
  5882. int
  5883. control_event_descriptors_changed(smartlist_t *routers)
  5884. {
  5885. char *msg;
  5886. if (!EVENT_IS_INTERESTING(EVENT_NEW_DESC))
  5887. return 0;
  5888. {
  5889. smartlist_t *names = smartlist_new();
  5890. char *ids;
  5891. SMARTLIST_FOREACH(routers, routerinfo_t *, ri, {
  5892. char *b = tor_malloc(MAX_VERBOSE_NICKNAME_LEN+1);
  5893. router_get_verbose_nickname(b, ri);
  5894. smartlist_add(names, b);
  5895. });
  5896. ids = smartlist_join_strings(names, " ", 0, NULL);
  5897. tor_asprintf(&msg, "650 NEWDESC %s\r\n", ids);
  5898. send_control_event_string(EVENT_NEW_DESC, msg);
  5899. tor_free(ids);
  5900. tor_free(msg);
  5901. SMARTLIST_FOREACH(names, char *, cp, tor_free(cp));
  5902. smartlist_free(names);
  5903. }
  5904. return 0;
  5905. }
  5906. /** Called when an address mapping on <b>from</b> from changes to <b>to</b>.
  5907. * <b>expires</b> values less than 3 are special; see connection_edge.c. If
  5908. * <b>error</b> is non-NULL, it is an error code describing the failure
  5909. * mode of the mapping.
  5910. */
  5911. int
  5912. control_event_address_mapped(const char *from, const char *to, time_t expires,
  5913. const char *error, const int cached)
  5914. {
  5915. if (!EVENT_IS_INTERESTING(EVENT_ADDRMAP))
  5916. return 0;
  5917. if (expires < 3 || expires == TIME_MAX)
  5918. send_control_event(EVENT_ADDRMAP,
  5919. "650 ADDRMAP %s %s NEVER %s%s"
  5920. "CACHED=\"%s\"\r\n",
  5921. from, to, error?error:"", error?" ":"",
  5922. cached?"YES":"NO");
  5923. else {
  5924. char buf[ISO_TIME_LEN+1];
  5925. char buf2[ISO_TIME_LEN+1];
  5926. format_local_iso_time(buf,expires);
  5927. format_iso_time(buf2,expires);
  5928. send_control_event(EVENT_ADDRMAP,
  5929. "650 ADDRMAP %s %s \"%s\""
  5930. " %s%sEXPIRES=\"%s\" CACHED=\"%s\"\r\n",
  5931. from, to, buf,
  5932. error?error:"", error?" ":"",
  5933. buf2, cached?"YES":"NO");
  5934. }
  5935. return 0;
  5936. }
  5937. /** Cached liveness for network liveness events and GETINFO
  5938. */
  5939. static int network_is_live = 0;
  5940. static int
  5941. get_cached_network_liveness(void)
  5942. {
  5943. return network_is_live;
  5944. }
  5945. static void
  5946. set_cached_network_liveness(int liveness)
  5947. {
  5948. network_is_live = liveness;
  5949. }
  5950. /** The network liveness has changed; this is called from circuitstats.c
  5951. * whenever we receive a cell, or when timeout expires and we assume the
  5952. * network is down. */
  5953. int
  5954. control_event_network_liveness_update(int liveness)
  5955. {
  5956. if (liveness > 0) {
  5957. if (get_cached_network_liveness() <= 0) {
  5958. /* Update cached liveness */
  5959. set_cached_network_liveness(1);
  5960. log_debug(LD_CONTROL, "Sending NETWORK_LIVENESS UP");
  5961. send_control_event_string(EVENT_NETWORK_LIVENESS,
  5962. "650 NETWORK_LIVENESS UP\r\n");
  5963. }
  5964. /* else was already live, no-op */
  5965. } else {
  5966. if (get_cached_network_liveness() > 0) {
  5967. /* Update cached liveness */
  5968. set_cached_network_liveness(0);
  5969. log_debug(LD_CONTROL, "Sending NETWORK_LIVENESS DOWN");
  5970. send_control_event_string(EVENT_NETWORK_LIVENESS,
  5971. "650 NETWORK_LIVENESS DOWN\r\n");
  5972. }
  5973. /* else was already dead, no-op */
  5974. }
  5975. return 0;
  5976. }
  5977. /** Helper function for NS-style events. Constructs and sends an event
  5978. * of type <b>event</b> with string <b>event_string</b> out of the set of
  5979. * networkstatuses <b>statuses</b>. Currently it is used for NS events
  5980. * and NEWCONSENSUS events. */
  5981. static int
  5982. control_event_networkstatus_changed_helper(smartlist_t *statuses,
  5983. uint16_t event,
  5984. const char *event_string)
  5985. {
  5986. smartlist_t *strs;
  5987. char *s, *esc = NULL;
  5988. if (!EVENT_IS_INTERESTING(event) || !smartlist_len(statuses))
  5989. return 0;
  5990. strs = smartlist_new();
  5991. smartlist_add_strdup(strs, "650+");
  5992. smartlist_add_strdup(strs, event_string);
  5993. smartlist_add_strdup(strs, "\r\n");
  5994. SMARTLIST_FOREACH(statuses, const routerstatus_t *, rs,
  5995. {
  5996. s = networkstatus_getinfo_helper_single(rs);
  5997. if (!s) continue;
  5998. smartlist_add(strs, s);
  5999. });
  6000. s = smartlist_join_strings(strs, "", 0, NULL);
  6001. write_escaped_data(s, strlen(s), &esc);
  6002. SMARTLIST_FOREACH(strs, char *, cp, tor_free(cp));
  6003. smartlist_free(strs);
  6004. tor_free(s);
  6005. send_control_event_string(event, esc);
  6006. send_control_event_string(event,
  6007. "650 OK\r\n");
  6008. tor_free(esc);
  6009. return 0;
  6010. }
  6011. /** Called when the routerstatus_ts <b>statuses</b> have changed: sends
  6012. * an NS event to any controller that cares. */
  6013. int
  6014. control_event_networkstatus_changed(smartlist_t *statuses)
  6015. {
  6016. return control_event_networkstatus_changed_helper(statuses, EVENT_NS, "NS");
  6017. }
  6018. /** Called when we get a new consensus networkstatus. Sends a NEWCONSENSUS
  6019. * event consisting of an NS-style line for each relay in the consensus. */
  6020. int
  6021. control_event_newconsensus(const networkstatus_t *consensus)
  6022. {
  6023. if (!control_event_is_interesting(EVENT_NEWCONSENSUS))
  6024. return 0;
  6025. return control_event_networkstatus_changed_helper(
  6026. consensus->routerstatus_list, EVENT_NEWCONSENSUS, "NEWCONSENSUS");
  6027. }
  6028. /** Called when we compute a new circuitbuildtimeout */
  6029. int
  6030. control_event_buildtimeout_set(buildtimeout_set_event_t type,
  6031. const char *args)
  6032. {
  6033. const char *type_string = NULL;
  6034. if (!control_event_is_interesting(EVENT_BUILDTIMEOUT_SET))
  6035. return 0;
  6036. switch (type) {
  6037. case BUILDTIMEOUT_SET_EVENT_COMPUTED:
  6038. type_string = "COMPUTED";
  6039. break;
  6040. case BUILDTIMEOUT_SET_EVENT_RESET:
  6041. type_string = "RESET";
  6042. break;
  6043. case BUILDTIMEOUT_SET_EVENT_SUSPENDED:
  6044. type_string = "SUSPENDED";
  6045. break;
  6046. case BUILDTIMEOUT_SET_EVENT_DISCARD:
  6047. type_string = "DISCARD";
  6048. break;
  6049. case BUILDTIMEOUT_SET_EVENT_RESUME:
  6050. type_string = "RESUME";
  6051. break;
  6052. default:
  6053. type_string = "UNKNOWN";
  6054. break;
  6055. }
  6056. send_control_event(EVENT_BUILDTIMEOUT_SET,
  6057. "650 BUILDTIMEOUT_SET %s %s\r\n",
  6058. type_string, args);
  6059. return 0;
  6060. }
  6061. /** Called when a signal has been processed from signal_callback */
  6062. int
  6063. control_event_signal(uintptr_t signal_num)
  6064. {
  6065. const char *signal_string = NULL;
  6066. if (!control_event_is_interesting(EVENT_GOT_SIGNAL))
  6067. return 0;
  6068. switch (signal_num) {
  6069. case SIGHUP:
  6070. signal_string = "RELOAD";
  6071. break;
  6072. case SIGUSR1:
  6073. signal_string = "DUMP";
  6074. break;
  6075. case SIGUSR2:
  6076. signal_string = "DEBUG";
  6077. break;
  6078. case SIGNEWNYM:
  6079. signal_string = "NEWNYM";
  6080. break;
  6081. case SIGCLEARDNSCACHE:
  6082. signal_string = "CLEARDNSCACHE";
  6083. break;
  6084. case SIGHEARTBEAT:
  6085. signal_string = "HEARTBEAT";
  6086. break;
  6087. default:
  6088. log_warn(LD_BUG, "Unrecognized signal %lu in control_event_signal",
  6089. (unsigned long)signal_num);
  6090. return -1;
  6091. }
  6092. send_control_event(EVENT_GOT_SIGNAL, "650 SIGNAL %s\r\n",
  6093. signal_string);
  6094. return 0;
  6095. }
  6096. /** Called when a single local_routerstatus_t has changed: Sends an NS event
  6097. * to any controller that cares. */
  6098. int
  6099. control_event_networkstatus_changed_single(const routerstatus_t *rs)
  6100. {
  6101. smartlist_t *statuses;
  6102. int r;
  6103. if (!EVENT_IS_INTERESTING(EVENT_NS))
  6104. return 0;
  6105. statuses = smartlist_new();
  6106. smartlist_add(statuses, (void*)rs);
  6107. r = control_event_networkstatus_changed(statuses);
  6108. smartlist_free(statuses);
  6109. return r;
  6110. }
  6111. /** Our own router descriptor has changed; tell any controllers that care.
  6112. */
  6113. int
  6114. control_event_my_descriptor_changed(void)
  6115. {
  6116. send_control_event(EVENT_DESCCHANGED, "650 DESCCHANGED\r\n");
  6117. return 0;
  6118. }
  6119. /** Helper: sends a status event where <b>type</b> is one of
  6120. * EVENT_STATUS_{GENERAL,CLIENT,SERVER}, where <b>severity</b> is one of
  6121. * LOG_{NOTICE,WARN,ERR}, and where <b>format</b> is a printf-style format
  6122. * string corresponding to <b>args</b>. */
  6123. static int
  6124. control_event_status(int type, int severity, const char *format, va_list args)
  6125. {
  6126. char *user_buf = NULL;
  6127. char format_buf[160];
  6128. const char *status, *sev;
  6129. switch (type) {
  6130. case EVENT_STATUS_GENERAL:
  6131. status = "STATUS_GENERAL";
  6132. break;
  6133. case EVENT_STATUS_CLIENT:
  6134. status = "STATUS_CLIENT";
  6135. break;
  6136. case EVENT_STATUS_SERVER:
  6137. status = "STATUS_SERVER";
  6138. break;
  6139. default:
  6140. log_warn(LD_BUG, "Unrecognized status type %d", type);
  6141. return -1;
  6142. }
  6143. switch (severity) {
  6144. case LOG_NOTICE:
  6145. sev = "NOTICE";
  6146. break;
  6147. case LOG_WARN:
  6148. sev = "WARN";
  6149. break;
  6150. case LOG_ERR:
  6151. sev = "ERR";
  6152. break;
  6153. default:
  6154. log_warn(LD_BUG, "Unrecognized status severity %d", severity);
  6155. return -1;
  6156. }
  6157. if (tor_snprintf(format_buf, sizeof(format_buf), "650 %s %s",
  6158. status, sev)<0) {
  6159. log_warn(LD_BUG, "Format string too long.");
  6160. return -1;
  6161. }
  6162. tor_vasprintf(&user_buf, format, args);
  6163. send_control_event(type, "%s %s\r\n", format_buf, user_buf);
  6164. tor_free(user_buf);
  6165. return 0;
  6166. }
  6167. #define CONTROL_EVENT_STATUS_BODY(event, sev) \
  6168. int r; \
  6169. do { \
  6170. va_list ap; \
  6171. if (!EVENT_IS_INTERESTING(event)) \
  6172. return 0; \
  6173. \
  6174. va_start(ap, format); \
  6175. r = control_event_status((event), (sev), format, ap); \
  6176. va_end(ap); \
  6177. } while (0)
  6178. /** Format and send an EVENT_STATUS_GENERAL event whose main text is obtained
  6179. * by formatting the arguments using the printf-style <b>format</b>. */
  6180. int
  6181. control_event_general_status(int severity, const char *format, ...)
  6182. {
  6183. CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_GENERAL, severity);
  6184. return r;
  6185. }
  6186. /** Format and send an EVENT_STATUS_GENERAL LOG_ERR event, and flush it to the
  6187. * controller(s) immediately. */
  6188. int
  6189. control_event_general_error(const char *format, ...)
  6190. {
  6191. CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_GENERAL, LOG_ERR);
  6192. /* Force a flush, since we may be about to die horribly */
  6193. queued_events_flush_all(1);
  6194. return r;
  6195. }
  6196. /** Format and send an EVENT_STATUS_CLIENT event whose main text is obtained
  6197. * by formatting the arguments using the printf-style <b>format</b>. */
  6198. int
  6199. control_event_client_status(int severity, const char *format, ...)
  6200. {
  6201. CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_CLIENT, severity);
  6202. return r;
  6203. }
  6204. /** Format and send an EVENT_STATUS_CLIENT LOG_ERR event, and flush it to the
  6205. * controller(s) immediately. */
  6206. int
  6207. control_event_client_error(const char *format, ...)
  6208. {
  6209. CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_CLIENT, LOG_ERR);
  6210. /* Force a flush, since we may be about to die horribly */
  6211. queued_events_flush_all(1);
  6212. return r;
  6213. }
  6214. /** Format and send an EVENT_STATUS_SERVER event whose main text is obtained
  6215. * by formatting the arguments using the printf-style <b>format</b>. */
  6216. int
  6217. control_event_server_status(int severity, const char *format, ...)
  6218. {
  6219. CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_SERVER, severity);
  6220. return r;
  6221. }
  6222. /** Format and send an EVENT_STATUS_SERVER LOG_ERR event, and flush it to the
  6223. * controller(s) immediately. */
  6224. int
  6225. control_event_server_error(const char *format, ...)
  6226. {
  6227. CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_SERVER, LOG_ERR);
  6228. /* Force a flush, since we may be about to die horribly */
  6229. queued_events_flush_all(1);
  6230. return r;
  6231. }
  6232. /** Called when the status of an entry guard with the given <b>nickname</b>
  6233. * and identity <b>digest</b> has changed to <b>status</b>: tells any
  6234. * controllers that care. */
  6235. int
  6236. control_event_guard(const char *nickname, const char *digest,
  6237. const char *status)
  6238. {
  6239. char hbuf[HEX_DIGEST_LEN+1];
  6240. base16_encode(hbuf, sizeof(hbuf), digest, DIGEST_LEN);
  6241. if (!EVENT_IS_INTERESTING(EVENT_GUARD))
  6242. return 0;
  6243. {
  6244. char buf[MAX_VERBOSE_NICKNAME_LEN+1];
  6245. const node_t *node = node_get_by_id(digest);
  6246. if (node) {
  6247. node_get_verbose_nickname(node, buf);
  6248. } else {
  6249. tor_snprintf(buf, sizeof(buf), "$%s~%s", hbuf, nickname);
  6250. }
  6251. send_control_event(EVENT_GUARD,
  6252. "650 GUARD ENTRY %s %s\r\n", buf, status);
  6253. }
  6254. return 0;
  6255. }
  6256. /** Called when a configuration option changes. This is generally triggered
  6257. * by SETCONF requests and RELOAD/SIGHUP signals. The <b>elements</b> is
  6258. * a smartlist_t containing (key, value, ...) pairs in sequence.
  6259. * <b>value</b> can be NULL. */
  6260. int
  6261. control_event_conf_changed(const smartlist_t *elements)
  6262. {
  6263. int i;
  6264. char *result;
  6265. smartlist_t *lines;
  6266. if (!EVENT_IS_INTERESTING(EVENT_CONF_CHANGED) ||
  6267. smartlist_len(elements) == 0) {
  6268. return 0;
  6269. }
  6270. lines = smartlist_new();
  6271. for (i = 0; i < smartlist_len(elements); i += 2) {
  6272. char *k = smartlist_get(elements, i);
  6273. char *v = smartlist_get(elements, i+1);
  6274. if (v == NULL) {
  6275. smartlist_add_asprintf(lines, "650-%s", k);
  6276. } else {
  6277. smartlist_add_asprintf(lines, "650-%s=%s", k, v);
  6278. }
  6279. }
  6280. result = smartlist_join_strings(lines, "\r\n", 0, NULL);
  6281. send_control_event(EVENT_CONF_CHANGED,
  6282. "650-CONF_CHANGED\r\n%s\r\n650 OK\r\n", result);
  6283. tor_free(result);
  6284. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  6285. smartlist_free(lines);
  6286. return 0;
  6287. }
  6288. /** Helper: Return a newly allocated string containing a path to the
  6289. * file where we store our authentication cookie. */
  6290. char *
  6291. get_controller_cookie_file_name(void)
  6292. {
  6293. const or_options_t *options = get_options();
  6294. if (options->CookieAuthFile && strlen(options->CookieAuthFile)) {
  6295. return tor_strdup(options->CookieAuthFile);
  6296. } else {
  6297. return get_datadir_fname("control_auth_cookie");
  6298. }
  6299. }
  6300. /* Initialize the cookie-based authentication system of the
  6301. * ControlPort. If <b>enabled</b> is 0, then disable the cookie
  6302. * authentication system. */
  6303. int
  6304. init_control_cookie_authentication(int enabled)
  6305. {
  6306. char *fname = NULL;
  6307. int retval;
  6308. if (!enabled) {
  6309. authentication_cookie_is_set = 0;
  6310. return 0;
  6311. }
  6312. fname = get_controller_cookie_file_name();
  6313. retval = init_cookie_authentication(fname, "", /* no header */
  6314. AUTHENTICATION_COOKIE_LEN,
  6315. get_options()->CookieAuthFileGroupReadable,
  6316. &authentication_cookie,
  6317. &authentication_cookie_is_set);
  6318. tor_free(fname);
  6319. return retval;
  6320. }
  6321. /** A copy of the process specifier of Tor's owning controller, or
  6322. * NULL if this Tor instance is not currently owned by a process. */
  6323. static char *owning_controller_process_spec = NULL;
  6324. /** A process-termination monitor for Tor's owning controller, or NULL
  6325. * if this Tor instance is not currently owned by a process. */
  6326. static tor_process_monitor_t *owning_controller_process_monitor = NULL;
  6327. /** Process-termination monitor callback for Tor's owning controller
  6328. * process. */
  6329. static void
  6330. owning_controller_procmon_cb(void *unused)
  6331. {
  6332. (void)unused;
  6333. lost_owning_controller("process", "vanished");
  6334. }
  6335. /** Set <b>process_spec</b> as Tor's owning controller process.
  6336. * Exit on failure. */
  6337. void
  6338. monitor_owning_controller_process(const char *process_spec)
  6339. {
  6340. const char *msg;
  6341. tor_assert((owning_controller_process_spec == NULL) ==
  6342. (owning_controller_process_monitor == NULL));
  6343. if (owning_controller_process_spec != NULL) {
  6344. if ((process_spec != NULL) && !strcmp(process_spec,
  6345. owning_controller_process_spec)) {
  6346. /* Same process -- return now, instead of disposing of and
  6347. * recreating the process-termination monitor. */
  6348. return;
  6349. }
  6350. /* We are currently owned by a process, and we should no longer be
  6351. * owned by it. Free the process-termination monitor. */
  6352. tor_process_monitor_free(owning_controller_process_monitor);
  6353. owning_controller_process_monitor = NULL;
  6354. tor_free(owning_controller_process_spec);
  6355. owning_controller_process_spec = NULL;
  6356. }
  6357. tor_assert((owning_controller_process_spec == NULL) &&
  6358. (owning_controller_process_monitor == NULL));
  6359. if (process_spec == NULL)
  6360. return;
  6361. owning_controller_process_spec = tor_strdup(process_spec);
  6362. owning_controller_process_monitor =
  6363. tor_process_monitor_new(tor_libevent_get_base(),
  6364. owning_controller_process_spec,
  6365. LD_CONTROL,
  6366. owning_controller_procmon_cb, NULL,
  6367. &msg);
  6368. if (owning_controller_process_monitor == NULL) {
  6369. log_err(LD_BUG, "Couldn't create process-termination monitor for "
  6370. "owning controller: %s. Exiting.",
  6371. msg);
  6372. owning_controller_process_spec = NULL;
  6373. tor_shutdown_event_loop_and_exit(1);
  6374. }
  6375. }
  6376. /** Convert the name of a bootstrapping phase <b>s</b> into strings
  6377. * <b>tag</b> and <b>summary</b> suitable for display by the controller. */
  6378. static int
  6379. bootstrap_status_to_string(bootstrap_status_t s, const char **tag,
  6380. const char **summary)
  6381. {
  6382. switch (s) {
  6383. case BOOTSTRAP_STATUS_UNDEF:
  6384. *tag = "undef";
  6385. *summary = "Undefined";
  6386. break;
  6387. case BOOTSTRAP_STATUS_STARTING:
  6388. *tag = "starting";
  6389. *summary = "Starting";
  6390. break;
  6391. case BOOTSTRAP_STATUS_CONN_DIR:
  6392. *tag = "conn_dir";
  6393. *summary = "Connecting to directory server";
  6394. break;
  6395. case BOOTSTRAP_STATUS_HANDSHAKE:
  6396. *tag = "status_handshake";
  6397. *summary = "Finishing handshake";
  6398. break;
  6399. case BOOTSTRAP_STATUS_HANDSHAKE_DIR:
  6400. *tag = "handshake_dir";
  6401. *summary = "Finishing handshake with directory server";
  6402. break;
  6403. case BOOTSTRAP_STATUS_ONEHOP_CREATE:
  6404. *tag = "onehop_create";
  6405. *summary = "Establishing an encrypted directory connection";
  6406. break;
  6407. case BOOTSTRAP_STATUS_REQUESTING_STATUS:
  6408. *tag = "requesting_status";
  6409. *summary = "Asking for networkstatus consensus";
  6410. break;
  6411. case BOOTSTRAP_STATUS_LOADING_STATUS:
  6412. *tag = "loading_status";
  6413. *summary = "Loading networkstatus consensus";
  6414. break;
  6415. case BOOTSTRAP_STATUS_LOADING_KEYS:
  6416. *tag = "loading_keys";
  6417. *summary = "Loading authority key certs";
  6418. break;
  6419. case BOOTSTRAP_STATUS_REQUESTING_DESCRIPTORS:
  6420. *tag = "requesting_descriptors";
  6421. /* XXXX this appears to incorrectly report internal on most loads */
  6422. *summary = router_have_consensus_path() == CONSENSUS_PATH_INTERNAL ?
  6423. "Asking for relay descriptors for internal paths" :
  6424. "Asking for relay descriptors";
  6425. break;
  6426. /* If we're sure there are no exits in the consensus,
  6427. * inform the controller by adding "internal"
  6428. * to the status summaries.
  6429. * (We only check this while loading descriptors,
  6430. * so we may not know in the earlier stages.)
  6431. * But if there are exits, we can't be sure whether
  6432. * we're creating internal or exit paths/circuits.
  6433. * XXXX Or should be use different tags or statuses
  6434. * for internal and exit/all? */
  6435. case BOOTSTRAP_STATUS_LOADING_DESCRIPTORS:
  6436. *tag = "loading_descriptors";
  6437. *summary = router_have_consensus_path() == CONSENSUS_PATH_INTERNAL ?
  6438. "Loading relay descriptors for internal paths" :
  6439. "Loading relay descriptors";
  6440. break;
  6441. case BOOTSTRAP_STATUS_CONN_OR:
  6442. *tag = "conn_or";
  6443. *summary = router_have_consensus_path() == CONSENSUS_PATH_INTERNAL ?
  6444. "Connecting to the Tor network internally" :
  6445. "Connecting to the Tor network";
  6446. break;
  6447. case BOOTSTRAP_STATUS_HANDSHAKE_OR:
  6448. *tag = "handshake_or";
  6449. *summary = router_have_consensus_path() == CONSENSUS_PATH_INTERNAL ?
  6450. "Finishing handshake with first hop of internal circuit" :
  6451. "Finishing handshake with first hop";
  6452. break;
  6453. case BOOTSTRAP_STATUS_CIRCUIT_CREATE:
  6454. *tag = "circuit_create";
  6455. *summary = router_have_consensus_path() == CONSENSUS_PATH_INTERNAL ?
  6456. "Establishing an internal Tor circuit" :
  6457. "Establishing a Tor circuit";
  6458. break;
  6459. case BOOTSTRAP_STATUS_DONE:
  6460. *tag = "done";
  6461. *summary = "Done";
  6462. break;
  6463. default:
  6464. // log_warn(LD_BUG, "Unrecognized bootstrap status code %d", s);
  6465. *tag = *summary = "unknown";
  6466. return -1;
  6467. }
  6468. return 0;
  6469. }
  6470. /** What percentage through the bootstrap process are we? We remember
  6471. * this so we can avoid sending redundant bootstrap status events, and
  6472. * so we can guess context for the bootstrap messages which are
  6473. * ambiguous. It starts at 'undef', but gets set to 'starting' while
  6474. * Tor initializes. */
  6475. static int bootstrap_percent = BOOTSTRAP_STATUS_UNDEF;
  6476. /** Like bootstrap_percent, but only takes on the enumerated values in
  6477. * bootstrap_status_t.
  6478. */
  6479. static int bootstrap_phase = BOOTSTRAP_STATUS_UNDEF;
  6480. /** As bootstrap_percent, but holds the bootstrapping level at which we last
  6481. * logged a NOTICE-level message. We use this, plus BOOTSTRAP_PCT_INCREMENT,
  6482. * to avoid flooding the log with a new message every time we get a few more
  6483. * microdescriptors */
  6484. static int notice_bootstrap_percent = 0;
  6485. /** How many problems have we had getting to the next bootstrapping phase?
  6486. * These include failure to establish a connection to a Tor relay,
  6487. * failures to finish the TLS handshake, failures to validate the
  6488. * consensus document, etc. */
  6489. static int bootstrap_problems = 0;
  6490. /** We only tell the controller once we've hit a threshold of problems
  6491. * for the current phase. */
  6492. #define BOOTSTRAP_PROBLEM_THRESHOLD 10
  6493. /** When our bootstrapping progress level changes, but our bootstrapping
  6494. * status has not advanced, we only log at NOTICE when we have made at least
  6495. * this much progress.
  6496. */
  6497. #define BOOTSTRAP_PCT_INCREMENT 5
  6498. /** Do the actual logging and notifications for
  6499. * control_event_bootstrap(). Doesn't change any state beyond that.
  6500. */
  6501. static void
  6502. control_event_bootstrap_core(int loglevel, bootstrap_status_t status,
  6503. int progress)
  6504. {
  6505. char buf[BOOTSTRAP_MSG_LEN];
  6506. const char *tag, *summary;
  6507. bootstrap_status_to_string(status, &tag, &summary);
  6508. /* Locally reset status if there's incremental progress */
  6509. if (progress)
  6510. status = progress;
  6511. tor_log(loglevel, LD_CONTROL,
  6512. "Bootstrapped %d%%: %s", status, summary);
  6513. tor_snprintf(buf, sizeof(buf),
  6514. "BOOTSTRAP PROGRESS=%d TAG=%s SUMMARY=\"%s\"",
  6515. status, tag, summary);
  6516. tor_snprintf(last_sent_bootstrap_message,
  6517. sizeof(last_sent_bootstrap_message),
  6518. "NOTICE %s", buf);
  6519. control_event_client_status(LOG_NOTICE, "%s", buf);
  6520. }
  6521. /** Called when Tor has made progress at bootstrapping its directory
  6522. * information and initial circuits.
  6523. *
  6524. * <b>status</b> is the new status, that is, what task we will be doing
  6525. * next. <b>progress</b> is zero if we just started this task, else it
  6526. * represents progress on the task.
  6527. */
  6528. void
  6529. control_event_bootstrap(bootstrap_status_t status, int progress)
  6530. {
  6531. int loglevel = LOG_NOTICE;
  6532. if (bootstrap_percent == BOOTSTRAP_STATUS_DONE)
  6533. return; /* already bootstrapped; nothing to be done here. */
  6534. /* special case for handshaking status, since our TLS handshaking code
  6535. * can't distinguish what the connection is going to be for. */
  6536. if (status == BOOTSTRAP_STATUS_HANDSHAKE) {
  6537. if (bootstrap_percent < BOOTSTRAP_STATUS_CONN_OR) {
  6538. status = BOOTSTRAP_STATUS_HANDSHAKE_DIR;
  6539. } else {
  6540. status = BOOTSTRAP_STATUS_HANDSHAKE_OR;
  6541. }
  6542. }
  6543. if (status <= bootstrap_percent) {
  6544. /* If there's no new progress, return early. */
  6545. if (!progress || progress <= bootstrap_percent)
  6546. return;
  6547. /* Log at INFO if not enough progress happened. */
  6548. if (progress < notice_bootstrap_percent + BOOTSTRAP_PCT_INCREMENT)
  6549. loglevel = LOG_INFO;
  6550. }
  6551. control_event_bootstrap_core(loglevel, status, progress);
  6552. if (status > bootstrap_percent) {
  6553. bootstrap_phase = status; /* new milestone reached */
  6554. bootstrap_percent = status;
  6555. }
  6556. if (progress > bootstrap_percent) {
  6557. /* incremental progress within a milestone */
  6558. bootstrap_percent = progress;
  6559. bootstrap_problems = 0; /* Progress! Reset our problem counter. */
  6560. }
  6561. if (loglevel == LOG_NOTICE &&
  6562. bootstrap_percent > notice_bootstrap_percent) {
  6563. /* Remember that we gave a notice at this level. */
  6564. notice_bootstrap_percent = bootstrap_percent;
  6565. }
  6566. }
  6567. /** Flag whether we've opened an OR_CONN yet */
  6568. static int bootstrap_first_orconn = 0;
  6569. /** Like bootstrap_phase, but for (possibly deferred) directory progress */
  6570. static int bootstrap_dir_phase = BOOTSTRAP_STATUS_UNDEF;
  6571. /** Like bootstrap_problems, but for (possibly deferred) directory progress */
  6572. static int bootstrap_dir_progress = BOOTSTRAP_STATUS_UNDEF;
  6573. /** Defer directory info bootstrap events until we have successfully
  6574. * completed our first connection to a router. */
  6575. void
  6576. control_event_boot_dir(bootstrap_status_t status, int progress)
  6577. {
  6578. if (status > bootstrap_dir_progress) {
  6579. bootstrap_dir_progress = status;
  6580. bootstrap_dir_phase = status;
  6581. }
  6582. if (progress && progress >= bootstrap_dir_progress) {
  6583. bootstrap_dir_progress = progress;
  6584. }
  6585. /* Don't report unless we have successfully opened at least one OR_CONN */
  6586. if (!bootstrap_first_orconn)
  6587. return;
  6588. control_event_bootstrap(status, progress);
  6589. }
  6590. /** Set a flag to allow reporting of directory bootstrap progress.
  6591. * (Code that reports completion of an OR_CONN calls this.) Also,
  6592. * report directory progress so far. */
  6593. void
  6594. control_event_boot_first_orconn(void)
  6595. {
  6596. bootstrap_first_orconn = 1;
  6597. control_event_bootstrap(bootstrap_dir_phase, bootstrap_dir_progress);
  6598. }
  6599. /** Called when Tor has failed to make bootstrapping progress in a way
  6600. * that indicates a problem. <b>warn</b> gives a human-readable hint
  6601. * as to why, and <b>reason</b> provides a controller-facing short
  6602. * tag. <b>conn</b> is the connection that caused this problem and
  6603. * can be NULL if a connection cannot be easily identified.
  6604. */
  6605. void
  6606. control_event_bootstrap_problem(const char *warn, const char *reason,
  6607. const connection_t *conn, int dowarn)
  6608. {
  6609. int status = bootstrap_percent;
  6610. const char *tag = "", *summary = "";
  6611. char buf[BOOTSTRAP_MSG_LEN];
  6612. const char *recommendation = "ignore";
  6613. int severity;
  6614. char *or_id = NULL, *hostaddr = NULL;
  6615. or_connection_t *or_conn = NULL;
  6616. /* bootstrap_percent must not be in "undefined" state here. */
  6617. tor_assert(status >= 0);
  6618. if (bootstrap_percent == 100)
  6619. return; /* already bootstrapped; nothing to be done here. */
  6620. bootstrap_problems++;
  6621. if (bootstrap_problems >= BOOTSTRAP_PROBLEM_THRESHOLD)
  6622. dowarn = 1;
  6623. /* Don't warn about our bootstrapping status if we are hibernating or
  6624. * shutting down. */
  6625. if (we_are_hibernating())
  6626. dowarn = 0;
  6627. tor_assert(bootstrap_status_to_string(bootstrap_phase, &tag, &summary) == 0);
  6628. severity = dowarn ? LOG_WARN : LOG_INFO;
  6629. if (dowarn)
  6630. recommendation = "warn";
  6631. if (conn && conn->type == CONN_TYPE_OR) {
  6632. /* XXX TO_OR_CONN can't deal with const */
  6633. or_conn = TO_OR_CONN((connection_t *)conn);
  6634. or_id = tor_strdup(hex_str(or_conn->identity_digest, DIGEST_LEN));
  6635. } else {
  6636. or_id = tor_strdup("?");
  6637. }
  6638. if (conn)
  6639. tor_asprintf(&hostaddr, "%s:%d", conn->address, (int)conn->port);
  6640. else
  6641. hostaddr = tor_strdup("?");
  6642. log_fn(severity,
  6643. LD_CONTROL, "Problem bootstrapping. Stuck at %d%%: %s. (%s; %s; "
  6644. "count %d; recommendation %s; host %s at %s)",
  6645. status, summary, warn, reason,
  6646. bootstrap_problems, recommendation,
  6647. or_id, hostaddr);
  6648. connection_or_report_broken_states(severity, LD_HANDSHAKE);
  6649. tor_snprintf(buf, sizeof(buf),
  6650. "BOOTSTRAP PROGRESS=%d TAG=%s SUMMARY=\"%s\" WARNING=\"%s\" REASON=%s "
  6651. "COUNT=%d RECOMMENDATION=%s HOSTID=\"%s\" HOSTADDR=\"%s\"",
  6652. bootstrap_percent, tag, summary, warn, reason, bootstrap_problems,
  6653. recommendation,
  6654. or_id, hostaddr);
  6655. tor_snprintf(last_sent_bootstrap_message,
  6656. sizeof(last_sent_bootstrap_message),
  6657. "WARN %s", buf);
  6658. control_event_client_status(LOG_WARN, "%s", buf);
  6659. tor_free(hostaddr);
  6660. tor_free(or_id);
  6661. }
  6662. /** Called when Tor has failed to make bootstrapping progress in a way
  6663. * that indicates a problem. <b>warn</b> gives a hint as to why, and
  6664. * <b>reason</b> provides an "or_conn_end_reason" tag. <b>or_conn</b>
  6665. * is the connection that caused this problem.
  6666. */
  6667. MOCK_IMPL(void,
  6668. control_event_bootstrap_prob_or, (const char *warn, int reason,
  6669. or_connection_t *or_conn))
  6670. {
  6671. int dowarn = 0;
  6672. if (or_conn->have_noted_bootstrap_problem)
  6673. return;
  6674. or_conn->have_noted_bootstrap_problem = 1;
  6675. if (reason == END_OR_CONN_REASON_NO_ROUTE)
  6676. dowarn = 1;
  6677. /* If we are using bridges and all our OR connections are now
  6678. closed, it means that we totally failed to connect to our
  6679. bridges. Throw a warning. */
  6680. if (get_options()->UseBridges && !any_other_active_or_conns(or_conn))
  6681. dowarn = 1;
  6682. control_event_bootstrap_problem(warn,
  6683. orconn_end_reason_to_control_string(reason),
  6684. TO_CONN(or_conn), dowarn);
  6685. }
  6686. /** We just generated a new summary of which countries we've seen clients
  6687. * from recently. Send a copy to the controller in case it wants to
  6688. * display it for the user. */
  6689. void
  6690. control_event_clients_seen(const char *controller_str)
  6691. {
  6692. send_control_event(EVENT_CLIENTS_SEEN,
  6693. "650 CLIENTS_SEEN %s\r\n", controller_str);
  6694. }
  6695. /** A new pluggable transport called <b>transport_name</b> was
  6696. * launched on <b>addr</b>:<b>port</b>. <b>mode</b> is either
  6697. * "server" or "client" depending on the mode of the pluggable
  6698. * transport.
  6699. * "650" SP "TRANSPORT_LAUNCHED" SP Mode SP Name SP Address SP Port
  6700. */
  6701. void
  6702. control_event_transport_launched(const char *mode, const char *transport_name,
  6703. tor_addr_t *addr, uint16_t port)
  6704. {
  6705. send_control_event(EVENT_TRANSPORT_LAUNCHED,
  6706. "650 TRANSPORT_LAUNCHED %s %s %s %u\r\n",
  6707. mode, transport_name, fmt_addr(addr), port);
  6708. }
  6709. /** Convert rendezvous auth type to string for HS_DESC control events
  6710. */
  6711. const char *
  6712. rend_auth_type_to_string(rend_auth_type_t auth_type)
  6713. {
  6714. const char *str;
  6715. switch (auth_type) {
  6716. case REND_NO_AUTH:
  6717. str = "NO_AUTH";
  6718. break;
  6719. case REND_BASIC_AUTH:
  6720. str = "BASIC_AUTH";
  6721. break;
  6722. case REND_STEALTH_AUTH:
  6723. str = "STEALTH_AUTH";
  6724. break;
  6725. default:
  6726. str = "UNKNOWN";
  6727. }
  6728. return str;
  6729. }
  6730. /** Return a longname the node whose identity is <b>id_digest</b>. If
  6731. * node_get_by_id() returns NULL, base 16 encoding of <b>id_digest</b> is
  6732. * returned instead.
  6733. *
  6734. * This function is not thread-safe. Each call to this function invalidates
  6735. * previous values returned by this function.
  6736. */
  6737. MOCK_IMPL(const char *,
  6738. node_describe_longname_by_id,(const char *id_digest))
  6739. {
  6740. static char longname[MAX_VERBOSE_NICKNAME_LEN+1];
  6741. node_get_verbose_nickname_by_id(id_digest, longname);
  6742. return longname;
  6743. }
  6744. /** Return either the onion address if the given pointer is a non empty
  6745. * string else the unknown string. */
  6746. static const char *
  6747. rend_hsaddress_str_or_unknown(const char *onion_address)
  6748. {
  6749. static const char *str_unknown = "UNKNOWN";
  6750. const char *str_ret = str_unknown;
  6751. /* No valid pointer, unknown it is. */
  6752. if (!onion_address) {
  6753. goto end;
  6754. }
  6755. /* Empty onion address thus we don't know, unknown it is. */
  6756. if (onion_address[0] == '\0') {
  6757. goto end;
  6758. }
  6759. /* All checks are good so return the given onion address. */
  6760. str_ret = onion_address;
  6761. end:
  6762. return str_ret;
  6763. }
  6764. /** send HS_DESC requested event.
  6765. *
  6766. * <b>rend_query</b> is used to fetch requested onion address and auth type.
  6767. * <b>hs_dir</b> is the description of contacting hs directory.
  6768. * <b>desc_id_base32</b> is the ID of requested hs descriptor.
  6769. * <b>hsdir_index</b> is the HSDir fetch index value for v3, an hex string.
  6770. */
  6771. void
  6772. control_event_hs_descriptor_requested(const char *onion_address,
  6773. rend_auth_type_t auth_type,
  6774. const char *id_digest,
  6775. const char *desc_id,
  6776. const char *hsdir_index)
  6777. {
  6778. char *hsdir_index_field = NULL;
  6779. if (BUG(!id_digest || !desc_id)) {
  6780. return;
  6781. }
  6782. if (hsdir_index) {
  6783. tor_asprintf(&hsdir_index_field, " HSDIR_INDEX=%s", hsdir_index);
  6784. }
  6785. send_control_event(EVENT_HS_DESC,
  6786. "650 HS_DESC REQUESTED %s %s %s %s%s\r\n",
  6787. rend_hsaddress_str_or_unknown(onion_address),
  6788. rend_auth_type_to_string(auth_type),
  6789. node_describe_longname_by_id(id_digest),
  6790. desc_id,
  6791. hsdir_index_field ? hsdir_index_field : "");
  6792. tor_free(hsdir_index_field);
  6793. }
  6794. /** For an HS descriptor query <b>rend_data</b>, using the
  6795. * <b>onion_address</b> and HSDir fingerprint <b>hsdir_fp</b>, find out
  6796. * which descriptor ID in the query is the right one.
  6797. *
  6798. * Return a pointer of the binary descriptor ID found in the query's object
  6799. * or NULL if not found. */
  6800. static const char *
  6801. get_desc_id_from_query(const rend_data_t *rend_data, const char *hsdir_fp)
  6802. {
  6803. int replica;
  6804. const char *desc_id = NULL;
  6805. const rend_data_v2_t *rend_data_v2 = TO_REND_DATA_V2(rend_data);
  6806. /* Possible if the fetch was done using a descriptor ID. This means that
  6807. * the HSFETCH command was used. */
  6808. if (!tor_digest_is_zero(rend_data_v2->desc_id_fetch)) {
  6809. desc_id = rend_data_v2->desc_id_fetch;
  6810. goto end;
  6811. }
  6812. /* Without a directory fingerprint at this stage, we can't do much. */
  6813. if (hsdir_fp == NULL) {
  6814. goto end;
  6815. }
  6816. /* OK, we have an onion address so now let's find which descriptor ID
  6817. * is the one associated with the HSDir fingerprint. */
  6818. for (replica = 0; replica < REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS;
  6819. replica++) {
  6820. const char *digest = rend_data_get_desc_id(rend_data, replica, NULL);
  6821. SMARTLIST_FOREACH_BEGIN(rend_data->hsdirs_fp, char *, fingerprint) {
  6822. if (tor_memcmp(fingerprint, hsdir_fp, DIGEST_LEN) == 0) {
  6823. /* Found it! This descriptor ID is the right one. */
  6824. desc_id = digest;
  6825. goto end;
  6826. }
  6827. } SMARTLIST_FOREACH_END(fingerprint);
  6828. }
  6829. end:
  6830. return desc_id;
  6831. }
  6832. /** send HS_DESC CREATED event when a local service generates a descriptor.
  6833. *
  6834. * <b>onion_address</b> is service address.
  6835. * <b>desc_id</b> is the descriptor ID.
  6836. * <b>replica</b> is the the descriptor replica number. If it is negative, it
  6837. * is ignored.
  6838. */
  6839. void
  6840. control_event_hs_descriptor_created(const char *onion_address,
  6841. const char *desc_id,
  6842. int replica)
  6843. {
  6844. char *replica_field = NULL;
  6845. if (BUG(!onion_address || !desc_id)) {
  6846. return;
  6847. }
  6848. if (replica >= 0) {
  6849. tor_asprintf(&replica_field, " REPLICA=%d", replica);
  6850. }
  6851. send_control_event(EVENT_HS_DESC,
  6852. "650 HS_DESC CREATED %s UNKNOWN UNKNOWN %s%s\r\n",
  6853. onion_address, desc_id,
  6854. replica_field ? replica_field : "");
  6855. tor_free(replica_field);
  6856. }
  6857. /** send HS_DESC upload event.
  6858. *
  6859. * <b>onion_address</b> is service address.
  6860. * <b>hs_dir</b> is the description of contacting hs directory.
  6861. * <b>desc_id</b> is the ID of requested hs descriptor.
  6862. */
  6863. void
  6864. control_event_hs_descriptor_upload(const char *onion_address,
  6865. const char *id_digest,
  6866. const char *desc_id,
  6867. const char *hsdir_index)
  6868. {
  6869. char *hsdir_index_field = NULL;
  6870. if (BUG(!onion_address || !id_digest || !desc_id)) {
  6871. return;
  6872. }
  6873. if (hsdir_index) {
  6874. tor_asprintf(&hsdir_index_field, " HSDIR_INDEX=%s", hsdir_index);
  6875. }
  6876. send_control_event(EVENT_HS_DESC,
  6877. "650 HS_DESC UPLOAD %s UNKNOWN %s %s%s\r\n",
  6878. onion_address,
  6879. node_describe_longname_by_id(id_digest),
  6880. desc_id,
  6881. hsdir_index_field ? hsdir_index_field : "");
  6882. tor_free(hsdir_index_field);
  6883. }
  6884. /** send HS_DESC event after got response from hs directory.
  6885. *
  6886. * NOTE: this is an internal function used by following functions:
  6887. * control_event_hsv2_descriptor_received
  6888. * control_event_hsv2_descriptor_failed
  6889. * control_event_hsv3_descriptor_failed
  6890. *
  6891. * So do not call this function directly.
  6892. */
  6893. static void
  6894. event_hs_descriptor_receive_end(const char *action,
  6895. const char *onion_address,
  6896. const char *desc_id,
  6897. rend_auth_type_t auth_type,
  6898. const char *hsdir_id_digest,
  6899. const char *reason)
  6900. {
  6901. char *reason_field = NULL;
  6902. if (BUG(!action || !onion_address)) {
  6903. return;
  6904. }
  6905. if (reason) {
  6906. tor_asprintf(&reason_field, " REASON=%s", reason);
  6907. }
  6908. send_control_event(EVENT_HS_DESC,
  6909. "650 HS_DESC %s %s %s %s%s%s\r\n",
  6910. action,
  6911. rend_hsaddress_str_or_unknown(onion_address),
  6912. rend_auth_type_to_string(auth_type),
  6913. hsdir_id_digest ?
  6914. node_describe_longname_by_id(hsdir_id_digest) :
  6915. "UNKNOWN",
  6916. desc_id ? desc_id : "",
  6917. reason_field ? reason_field : "");
  6918. tor_free(reason_field);
  6919. }
  6920. /** send HS_DESC event after got response from hs directory.
  6921. *
  6922. * NOTE: this is an internal function used by following functions:
  6923. * control_event_hs_descriptor_uploaded
  6924. * control_event_hs_descriptor_upload_failed
  6925. *
  6926. * So do not call this function directly.
  6927. */
  6928. void
  6929. control_event_hs_descriptor_upload_end(const char *action,
  6930. const char *onion_address,
  6931. const char *id_digest,
  6932. const char *reason)
  6933. {
  6934. char *reason_field = NULL;
  6935. if (BUG(!action || !id_digest)) {
  6936. return;
  6937. }
  6938. if (reason) {
  6939. tor_asprintf(&reason_field, " REASON=%s", reason);
  6940. }
  6941. send_control_event(EVENT_HS_DESC,
  6942. "650 HS_DESC %s %s UNKNOWN %s%s\r\n",
  6943. action,
  6944. rend_hsaddress_str_or_unknown(onion_address),
  6945. node_describe_longname_by_id(id_digest),
  6946. reason_field ? reason_field : "");
  6947. tor_free(reason_field);
  6948. }
  6949. /** send HS_DESC RECEIVED event
  6950. *
  6951. * called when we successfully received a hidden service descriptor.
  6952. */
  6953. void
  6954. control_event_hsv2_descriptor_received(const char *onion_address,
  6955. const rend_data_t *rend_data,
  6956. const char *hsdir_id_digest)
  6957. {
  6958. char *desc_id_field = NULL;
  6959. const char *desc_id;
  6960. if (BUG(!rend_data || !hsdir_id_digest || !onion_address)) {
  6961. return;
  6962. }
  6963. desc_id = get_desc_id_from_query(rend_data, hsdir_id_digest);
  6964. if (desc_id != NULL) {
  6965. char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
  6966. /* Set the descriptor ID digest to base32 so we can send it. */
  6967. base32_encode(desc_id_base32, sizeof(desc_id_base32), desc_id,
  6968. DIGEST_LEN);
  6969. /* Extra whitespace is needed before the value. */
  6970. tor_asprintf(&desc_id_field, " %s", desc_id_base32);
  6971. }
  6972. event_hs_descriptor_receive_end("RECEIVED", onion_address, desc_id_field,
  6973. TO_REND_DATA_V2(rend_data)->auth_type,
  6974. hsdir_id_digest, NULL);
  6975. tor_free(desc_id_field);
  6976. }
  6977. /* Send HS_DESC RECEIVED event
  6978. *
  6979. * Called when we successfully received a hidden service descriptor. */
  6980. void
  6981. control_event_hsv3_descriptor_received(const char *onion_address,
  6982. const char *desc_id,
  6983. const char *hsdir_id_digest)
  6984. {
  6985. char *desc_id_field = NULL;
  6986. if (BUG(!onion_address || !desc_id || !hsdir_id_digest)) {
  6987. return;
  6988. }
  6989. /* Because DescriptorID is an optional positional value, we need to add a
  6990. * whitespace before in order to not be next to the HsDir value. */
  6991. tor_asprintf(&desc_id_field, " %s", desc_id);
  6992. event_hs_descriptor_receive_end("RECEIVED", onion_address, desc_id_field,
  6993. REND_NO_AUTH, hsdir_id_digest, NULL);
  6994. tor_free(desc_id_field);
  6995. }
  6996. /** send HS_DESC UPLOADED event
  6997. *
  6998. * called when we successfully uploaded a hidden service descriptor.
  6999. */
  7000. void
  7001. control_event_hs_descriptor_uploaded(const char *id_digest,
  7002. const char *onion_address)
  7003. {
  7004. if (BUG(!id_digest)) {
  7005. return;
  7006. }
  7007. control_event_hs_descriptor_upload_end("UPLOADED", onion_address,
  7008. id_digest, NULL);
  7009. }
  7010. /** Send HS_DESC event to inform controller that query <b>rend_data</b>
  7011. * failed to retrieve hidden service descriptor from directory identified by
  7012. * <b>id_digest</b>. If NULL, "UNKNOWN" is used. If <b>reason</b> is not NULL,
  7013. * add it to REASON= field.
  7014. */
  7015. void
  7016. control_event_hsv2_descriptor_failed(const rend_data_t *rend_data,
  7017. const char *hsdir_id_digest,
  7018. const char *reason)
  7019. {
  7020. char *desc_id_field = NULL;
  7021. const char *desc_id;
  7022. if (BUG(!rend_data)) {
  7023. return;
  7024. }
  7025. desc_id = get_desc_id_from_query(rend_data, hsdir_id_digest);
  7026. if (desc_id != NULL) {
  7027. char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
  7028. /* Set the descriptor ID digest to base32 so we can send it. */
  7029. base32_encode(desc_id_base32, sizeof(desc_id_base32), desc_id,
  7030. DIGEST_LEN);
  7031. /* Extra whitespace is needed before the value. */
  7032. tor_asprintf(&desc_id_field, " %s", desc_id_base32);
  7033. }
  7034. event_hs_descriptor_receive_end("FAILED", rend_data_get_address(rend_data),
  7035. desc_id_field,
  7036. TO_REND_DATA_V2(rend_data)->auth_type,
  7037. hsdir_id_digest, reason);
  7038. tor_free(desc_id_field);
  7039. }
  7040. /** Send HS_DESC event to inform controller that the query to
  7041. * <b>onion_address</b> failed to retrieve hidden service descriptor
  7042. * <b>desc_id</b> from directory identified by <b>hsdir_id_digest</b>. If
  7043. * NULL, "UNKNOWN" is used. If <b>reason</b> is not NULL, add it to REASON=
  7044. * field. */
  7045. void
  7046. control_event_hsv3_descriptor_failed(const char *onion_address,
  7047. const char *desc_id,
  7048. const char *hsdir_id_digest,
  7049. const char *reason)
  7050. {
  7051. char *desc_id_field = NULL;
  7052. if (BUG(!onion_address || !desc_id || !reason)) {
  7053. return;
  7054. }
  7055. /* Because DescriptorID is an optional positional value, we need to add a
  7056. * whitespace before in order to not be next to the HsDir value. */
  7057. tor_asprintf(&desc_id_field, " %s", desc_id);
  7058. event_hs_descriptor_receive_end("FAILED", onion_address, desc_id_field,
  7059. REND_NO_AUTH, hsdir_id_digest, reason);
  7060. tor_free(desc_id_field);
  7061. }
  7062. /** Send HS_DESC_CONTENT event after completion of a successful fetch
  7063. * from hs directory. If <b>hsdir_id_digest</b> is NULL, it is replaced
  7064. * by "UNKNOWN". If <b>content</b> is NULL, it is replaced by an empty
  7065. * string. The <b>onion_address</b> or <b>desc_id</b> set to NULL will
  7066. * not trigger the control event. */
  7067. void
  7068. control_event_hs_descriptor_content(const char *onion_address,
  7069. const char *desc_id,
  7070. const char *hsdir_id_digest,
  7071. const char *content)
  7072. {
  7073. static const char *event_name = "HS_DESC_CONTENT";
  7074. char *esc_content = NULL;
  7075. if (!onion_address || !desc_id) {
  7076. log_warn(LD_BUG, "Called with onion_address==%p, desc_id==%p, ",
  7077. onion_address, desc_id);
  7078. return;
  7079. }
  7080. if (content == NULL) {
  7081. /* Point it to empty content so it can still be escaped. */
  7082. content = "";
  7083. }
  7084. write_escaped_data(content, strlen(content), &esc_content);
  7085. send_control_event(EVENT_HS_DESC_CONTENT,
  7086. "650+%s %s %s %s\r\n%s650 OK\r\n",
  7087. event_name,
  7088. rend_hsaddress_str_or_unknown(onion_address),
  7089. desc_id,
  7090. hsdir_id_digest ?
  7091. node_describe_longname_by_id(hsdir_id_digest) :
  7092. "UNKNOWN",
  7093. esc_content);
  7094. tor_free(esc_content);
  7095. }
  7096. /** Send HS_DESC event to inform controller upload of hidden service
  7097. * descriptor identified by <b>id_digest</b> failed. If <b>reason</b>
  7098. * is not NULL, add it to REASON= field.
  7099. */
  7100. void
  7101. control_event_hs_descriptor_upload_failed(const char *id_digest,
  7102. const char *onion_address,
  7103. const char *reason)
  7104. {
  7105. if (BUG(!id_digest)) {
  7106. return;
  7107. }
  7108. control_event_hs_descriptor_upload_end("FAILED", onion_address,
  7109. id_digest, reason);
  7110. }
  7111. /** Free any leftover allocated memory of the control.c subsystem. */
  7112. void
  7113. control_free_all(void)
  7114. {
  7115. smartlist_t *queued_events = NULL;
  7116. stats_prev_n_read = stats_prev_n_written = 0;
  7117. if (authentication_cookie) /* Free the auth cookie */
  7118. tor_free(authentication_cookie);
  7119. if (detached_onion_services) { /* Free the detached onion services */
  7120. SMARTLIST_FOREACH(detached_onion_services, char *, cp, tor_free(cp));
  7121. smartlist_free(detached_onion_services);
  7122. }
  7123. if (queued_control_events_lock) {
  7124. tor_mutex_acquire(queued_control_events_lock);
  7125. flush_queued_event_pending = 0;
  7126. queued_events = queued_control_events;
  7127. queued_control_events = NULL;
  7128. tor_mutex_release(queued_control_events_lock);
  7129. }
  7130. if (queued_events) {
  7131. SMARTLIST_FOREACH(queued_events, queued_event_t *, ev,
  7132. queued_event_free(ev));
  7133. smartlist_free(queued_events);
  7134. }
  7135. if (flush_queued_events_event) {
  7136. mainloop_event_free(flush_queued_events_event);
  7137. flush_queued_events_event = NULL;
  7138. }
  7139. bootstrap_percent = BOOTSTRAP_STATUS_UNDEF;
  7140. notice_bootstrap_percent = 0;
  7141. bootstrap_problems = 0;
  7142. authentication_cookie_is_set = 0;
  7143. global_event_mask = 0;
  7144. disable_log_messages = 0;
  7145. memset(last_sent_bootstrap_message, 0, sizeof(last_sent_bootstrap_message));
  7146. }
  7147. #ifdef TOR_UNIT_TESTS
  7148. /* For testing: change the value of global_event_mask */
  7149. void
  7150. control_testing_set_global_event_mask(uint64_t mask)
  7151. {
  7152. global_event_mask = mask;
  7153. }
  7154. #endif /* defined(TOR_UNIT_TESTS) */