control.c 222 KB

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