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