control.c 255 KB

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