control.c 264 KB

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