control.c 264 KB

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