control.c 259 KB

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