control.c 263 KB

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