control.c 263 KB

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