control.c 233 KB

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