control.c 171 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155
  1. /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  2. * Copyright (c) 2007-2013, 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 "config.h"
  21. #include "confparse.h"
  22. #include "connection.h"
  23. #include "connection_edge.h"
  24. #include "connection_or.h"
  25. #include "control.h"
  26. #include "directory.h"
  27. #include "dirserv.h"
  28. #include "dnsserv.h"
  29. #include "entrynodes.h"
  30. #include "geoip.h"
  31. #include "hibernate.h"
  32. #include "main.h"
  33. #include "networkstatus.h"
  34. #include "nodelist.h"
  35. #include "policies.h"
  36. #include "reasons.h"
  37. #include "rephist.h"
  38. #include "router.h"
  39. #include "routerlist.h"
  40. #include "routerparse.h"
  41. #ifndef _WIN32
  42. #include <pwd.h>
  43. #include <sys/resource.h>
  44. #endif
  45. #include "procmon.h"
  46. /** Yield true iff <b>s</b> is the state of a control_connection_t that has
  47. * finished authentication and is accepting commands. */
  48. #define STATE_IS_OPEN(s) ((s) == CONTROL_CONN_STATE_OPEN)
  49. /** Bitfield: The bit 1&lt;&lt;e is set if <b>any</b> open control
  50. * connection is interested in events of type <b>e</b>. We use this
  51. * so that we can decide to skip generating event messages that nobody
  52. * has interest in without having to walk over the global connection
  53. * list to find out.
  54. **/
  55. typedef uint64_t event_mask_t;
  56. /** An event mask of all the events that any controller is interested in
  57. * receiving. */
  58. static event_mask_t global_event_mask = 0;
  59. /** True iff we have disabled log messages from being sent to the controller */
  60. static int disable_log_messages = 0;
  61. /** Macro: true if any control connection is interested in events of type
  62. * <b>e</b>. */
  63. #define EVENT_IS_INTERESTING(e) \
  64. (!! (global_event_mask & (((uint64_t)1)<<(e))))
  65. /** If we're using cookie-type authentication, how long should our cookies be?
  66. */
  67. #define AUTHENTICATION_COOKIE_LEN 32
  68. /** If true, we've set authentication_cookie to a secret code and
  69. * stored it to disk. */
  70. static int authentication_cookie_is_set = 0;
  71. /** If authentication_cookie_is_set, a secret cookie that we've stored to disk
  72. * and which we're using to authenticate controllers. (If the controller can
  73. * read it off disk, it has permission to connect.) */
  74. static uint8_t *authentication_cookie = NULL;
  75. #define SAFECOOKIE_SERVER_TO_CONTROLLER_CONSTANT \
  76. "Tor safe cookie authentication server-to-controller hash"
  77. #define SAFECOOKIE_CONTROLLER_TO_SERVER_CONSTANT \
  78. "Tor safe cookie authentication controller-to-server hash"
  79. #define SAFECOOKIE_SERVER_NONCE_LEN DIGEST256_LEN
  80. /** A sufficiently large size to record the last bootstrap phase string. */
  81. #define BOOTSTRAP_MSG_LEN 1024
  82. /** What was the last bootstrap phase message we sent? We keep track
  83. * of this so we can respond to getinfo status/bootstrap-phase queries. */
  84. static char last_sent_bootstrap_message[BOOTSTRAP_MSG_LEN];
  85. static void connection_printf_to_buf(control_connection_t *conn,
  86. const char *format, ...)
  87. CHECK_PRINTF(2,3);
  88. static void send_control_event_impl(uint16_t event, event_format_t which,
  89. const char *format, va_list ap)
  90. CHECK_PRINTF(3,0);
  91. static int control_event_status(int type, int severity, const char *format,
  92. va_list args)
  93. CHECK_PRINTF(3,0);
  94. static void send_control_done(control_connection_t *conn);
  95. static void send_control_event(uint16_t event, event_format_t which,
  96. const char *format, ...)
  97. CHECK_PRINTF(3,4);
  98. static int handle_control_setconf(control_connection_t *conn, uint32_t len,
  99. char *body);
  100. static int handle_control_resetconf(control_connection_t *conn, uint32_t len,
  101. char *body);
  102. static int handle_control_getconf(control_connection_t *conn, uint32_t len,
  103. const char *body);
  104. static int handle_control_loadconf(control_connection_t *conn, uint32_t len,
  105. const char *body);
  106. static int handle_control_setevents(control_connection_t *conn, uint32_t len,
  107. const char *body);
  108. static int handle_control_authenticate(control_connection_t *conn,
  109. uint32_t len,
  110. const char *body);
  111. static int handle_control_signal(control_connection_t *conn, uint32_t len,
  112. const char *body);
  113. static int handle_control_mapaddress(control_connection_t *conn, uint32_t len,
  114. const char *body);
  115. static char *list_getinfo_options(void);
  116. static int handle_control_getinfo(control_connection_t *conn, uint32_t len,
  117. const char *body);
  118. static int handle_control_extendcircuit(control_connection_t *conn,
  119. uint32_t len,
  120. const char *body);
  121. static int handle_control_setcircuitpurpose(control_connection_t *conn,
  122. uint32_t len, const char *body);
  123. static int handle_control_attachstream(control_connection_t *conn,
  124. uint32_t len,
  125. const char *body);
  126. static int handle_control_postdescriptor(control_connection_t *conn,
  127. uint32_t len,
  128. const char *body);
  129. static int handle_control_redirectstream(control_connection_t *conn,
  130. uint32_t len,
  131. const char *body);
  132. static int handle_control_closestream(control_connection_t *conn, uint32_t len,
  133. const char *body);
  134. static int handle_control_closecircuit(control_connection_t *conn,
  135. uint32_t len,
  136. const char *body);
  137. static int handle_control_resolve(control_connection_t *conn, uint32_t len,
  138. const char *body);
  139. static int handle_control_usefeature(control_connection_t *conn,
  140. uint32_t len,
  141. const char *body);
  142. static int write_stream_target_to_buf(entry_connection_t *conn, char *buf,
  143. size_t len);
  144. static void orconn_target_get_name(char *buf, size_t len,
  145. or_connection_t *conn);
  146. /** Given a control event code for a message event, return the corresponding
  147. * log severity. */
  148. static INLINE int
  149. event_to_log_severity(int event)
  150. {
  151. switch (event) {
  152. case EVENT_DEBUG_MSG: return LOG_DEBUG;
  153. case EVENT_INFO_MSG: return LOG_INFO;
  154. case EVENT_NOTICE_MSG: return LOG_NOTICE;
  155. case EVENT_WARN_MSG: return LOG_WARN;
  156. case EVENT_ERR_MSG: return LOG_ERR;
  157. default: return -1;
  158. }
  159. }
  160. /** Given a log severity, return the corresponding control event code. */
  161. static INLINE int
  162. log_severity_to_event(int severity)
  163. {
  164. switch (severity) {
  165. case LOG_DEBUG: return EVENT_DEBUG_MSG;
  166. case LOG_INFO: return EVENT_INFO_MSG;
  167. case LOG_NOTICE: return EVENT_NOTICE_MSG;
  168. case LOG_WARN: return EVENT_WARN_MSG;
  169. case LOG_ERR: return EVENT_ERR_MSG;
  170. default: return -1;
  171. }
  172. }
  173. /** Helper: clear bandwidth counters of all origin circuits. */
  174. static void
  175. clear_circ_bw_fields(void)
  176. {
  177. origin_circuit_t *ocirc;
  178. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  179. if (!CIRCUIT_IS_ORIGIN(circ))
  180. continue;
  181. ocirc = TO_ORIGIN_CIRCUIT(circ);
  182. ocirc->n_written_circ_bw = ocirc->n_read_circ_bw = 0;
  183. }
  184. SMARTLIST_FOREACH_END(circ);
  185. }
  186. /** Set <b>global_event_mask*</b> to the bitwise OR of each live control
  187. * connection's event_mask field. */
  188. void
  189. control_update_global_event_mask(void)
  190. {
  191. smartlist_t *conns = get_connection_array();
  192. event_mask_t old_mask, new_mask;
  193. old_mask = global_event_mask;
  194. global_event_mask = 0;
  195. SMARTLIST_FOREACH(conns, connection_t *, _conn,
  196. {
  197. if (_conn->type == CONN_TYPE_CONTROL &&
  198. STATE_IS_OPEN(_conn->state)) {
  199. control_connection_t *conn = TO_CONTROL_CONN(_conn);
  200. global_event_mask |= conn->event_mask;
  201. }
  202. });
  203. new_mask = global_event_mask;
  204. /* Handle the aftermath. Set up the log callback to tell us only what
  205. * we want to hear...*/
  206. control_adjust_event_log_severity();
  207. /* ...then, if we've started logging stream or circ bw, clear the
  208. * appropriate fields. */
  209. if (! (old_mask & EVENT_STREAM_BANDWIDTH_USED) &&
  210. (new_mask & EVENT_STREAM_BANDWIDTH_USED)) {
  211. SMARTLIST_FOREACH(conns, connection_t *, conn,
  212. {
  213. if (conn->type == CONN_TYPE_AP) {
  214. edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
  215. edge_conn->n_written = edge_conn->n_read = 0;
  216. }
  217. });
  218. }
  219. if (! (old_mask & EVENT_CIRC_BANDWIDTH_USED) &&
  220. (new_mask & EVENT_CIRC_BANDWIDTH_USED)) {
  221. clear_circ_bw_fields();
  222. }
  223. }
  224. /** Adjust the log severities that result in control_event_logmsg being called
  225. * to match the severity of log messages that any controllers are interested
  226. * in. */
  227. void
  228. control_adjust_event_log_severity(void)
  229. {
  230. int i;
  231. int min_log_event=EVENT_ERR_MSG, max_log_event=EVENT_DEBUG_MSG;
  232. for (i = EVENT_DEBUG_MSG; i <= EVENT_ERR_MSG; ++i) {
  233. if (EVENT_IS_INTERESTING(i)) {
  234. min_log_event = i;
  235. break;
  236. }
  237. }
  238. for (i = EVENT_ERR_MSG; i >= EVENT_DEBUG_MSG; --i) {
  239. if (EVENT_IS_INTERESTING(i)) {
  240. max_log_event = i;
  241. break;
  242. }
  243. }
  244. if (EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL)) {
  245. if (min_log_event > EVENT_NOTICE_MSG)
  246. min_log_event = EVENT_NOTICE_MSG;
  247. if (max_log_event < EVENT_ERR_MSG)
  248. max_log_event = EVENT_ERR_MSG;
  249. }
  250. if (min_log_event <= max_log_event)
  251. change_callback_log_severity(event_to_log_severity(min_log_event),
  252. event_to_log_severity(max_log_event),
  253. control_event_logmsg);
  254. else
  255. change_callback_log_severity(LOG_ERR, LOG_ERR,
  256. control_event_logmsg);
  257. }
  258. /** Return true iff the event with code <b>c</b> is being sent to any current
  259. * control connection. This is useful if the amount of work needed to prepare
  260. * to call the appropriate control_event_...() function is high.
  261. */
  262. int
  263. control_event_is_interesting(int event)
  264. {
  265. return EVENT_IS_INTERESTING(event);
  266. }
  267. /** Append a NUL-terminated string <b>s</b> to the end of
  268. * <b>conn</b>-\>outbuf.
  269. */
  270. static INLINE void
  271. connection_write_str_to_buf(const char *s, control_connection_t *conn)
  272. {
  273. size_t len = strlen(s);
  274. connection_write_to_buf(s, len, TO_CONN(conn));
  275. }
  276. /** Given a <b>len</b>-character string in <b>data</b>, made of lines
  277. * terminated by CRLF, allocate a new string in *<b>out</b>, and copy the
  278. * contents of <b>data</b> into *<b>out</b>, adding a period before any period
  279. * that appears at the start of a line, and adding a period-CRLF line at
  280. * the end. Replace all LF characters sequences with CRLF. Return the number
  281. * of bytes in *<b>out</b>.
  282. */
  283. STATIC size_t
  284. write_escaped_data(const char *data, size_t len, char **out)
  285. {
  286. size_t sz_out = len+8;
  287. char *outp;
  288. const char *start = data, *end;
  289. int i;
  290. int start_of_line;
  291. for (i=0; i<(int)len; ++i) {
  292. if (data[i]== '\n')
  293. sz_out += 2; /* Maybe add a CR; maybe add a dot. */
  294. }
  295. *out = outp = tor_malloc(sz_out+1);
  296. end = data+len;
  297. start_of_line = 1;
  298. while (data < end) {
  299. if (*data == '\n') {
  300. if (data > start && data[-1] != '\r')
  301. *outp++ = '\r';
  302. start_of_line = 1;
  303. } else if (*data == '.') {
  304. if (start_of_line) {
  305. start_of_line = 0;
  306. *outp++ = '.';
  307. }
  308. } else {
  309. start_of_line = 0;
  310. }
  311. *outp++ = *data++;
  312. }
  313. if (outp < *out+2 || fast_memcmp(outp-2, "\r\n", 2)) {
  314. *outp++ = '\r';
  315. *outp++ = '\n';
  316. }
  317. *outp++ = '.';
  318. *outp++ = '\r';
  319. *outp++ = '\n';
  320. *outp = '\0'; /* NUL-terminate just in case. */
  321. tor_assert((outp - *out) <= (int)sz_out);
  322. return outp - *out;
  323. }
  324. /** Given a <b>len</b>-character string in <b>data</b>, made of lines
  325. * terminated by CRLF, allocate a new string in *<b>out</b>, and copy
  326. * the contents of <b>data</b> into *<b>out</b>, removing any period
  327. * that appears at the start of a line, and replacing all CRLF sequences
  328. * with LF. Return the number of
  329. * bytes in *<b>out</b>. */
  330. STATIC size_t
  331. read_escaped_data(const char *data, size_t len, char **out)
  332. {
  333. char *outp;
  334. const char *next;
  335. const char *end;
  336. *out = outp = tor_malloc(len+1);
  337. end = data+len;
  338. while (data < end) {
  339. /* we're at the start of a line. */
  340. if (*data == '.')
  341. ++data;
  342. next = memchr(data, '\n', end-data);
  343. if (next) {
  344. size_t n_to_copy = next-data;
  345. /* Don't copy a CR that precedes this LF. */
  346. if (n_to_copy && *(next-1) == '\r')
  347. --n_to_copy;
  348. memcpy(outp, data, n_to_copy);
  349. outp += n_to_copy;
  350. data = next+1; /* This will point at the start of the next line,
  351. * or the end of the string, or a period. */
  352. } else {
  353. memcpy(outp, data, end-data);
  354. outp += (end-data);
  355. *outp = '\0';
  356. return outp - *out;
  357. }
  358. *outp++ = '\n';
  359. }
  360. *outp = '\0';
  361. return outp - *out;
  362. }
  363. /** If the first <b>in_len_max</b> characters in <b>start</b> contain a
  364. * double-quoted string with escaped characters, return the length of that
  365. * string (as encoded, including quotes). Otherwise return -1. */
  366. static INLINE int
  367. get_escaped_string_length(const char *start, size_t in_len_max,
  368. int *chars_out)
  369. {
  370. const char *cp, *end;
  371. int chars = 0;
  372. if (*start != '\"')
  373. return -1;
  374. cp = start+1;
  375. end = start+in_len_max;
  376. /* Calculate length. */
  377. while (1) {
  378. if (cp >= end) {
  379. return -1; /* Too long. */
  380. } else if (*cp == '\\') {
  381. if (++cp == end)
  382. return -1; /* Can't escape EOS. */
  383. ++cp;
  384. ++chars;
  385. } else if (*cp == '\"') {
  386. break;
  387. } else {
  388. ++cp;
  389. ++chars;
  390. }
  391. }
  392. if (chars_out)
  393. *chars_out = chars;
  394. return (int)(cp - start+1);
  395. }
  396. /** As decode_escaped_string, but does not decode the string: copies the
  397. * entire thing, including quotation marks. */
  398. static const char *
  399. extract_escaped_string(const char *start, size_t in_len_max,
  400. char **out, size_t *out_len)
  401. {
  402. int length = get_escaped_string_length(start, in_len_max, NULL);
  403. if (length<0)
  404. return NULL;
  405. *out_len = length;
  406. *out = tor_strndup(start, *out_len);
  407. return start+length;
  408. }
  409. /** Given a pointer to a string starting at <b>start</b> containing
  410. * <b>in_len_max</b> characters, decode a string beginning with one double
  411. * quote, containing any number of non-quote characters or characters escaped
  412. * with a backslash, and ending with a final double quote. Place the resulting
  413. * string (unquoted, unescaped) into a newly allocated string in *<b>out</b>;
  414. * store its length in <b>out_len</b>. On success, return a pointer to the
  415. * character immediately following the escaped string. On failure, return
  416. * NULL. */
  417. static const char *
  418. decode_escaped_string(const char *start, size_t in_len_max,
  419. char **out, size_t *out_len)
  420. {
  421. const char *cp, *end;
  422. char *outp;
  423. int len, n_chars = 0;
  424. len = get_escaped_string_length(start, in_len_max, &n_chars);
  425. if (len<0)
  426. return NULL;
  427. end = start+len-1; /* Index of last quote. */
  428. tor_assert(*end == '\"');
  429. outp = *out = tor_malloc(len+1);
  430. *out_len = n_chars;
  431. cp = start+1;
  432. while (cp < end) {
  433. if (*cp == '\\')
  434. ++cp;
  435. *outp++ = *cp++;
  436. }
  437. *outp = '\0';
  438. tor_assert((outp - *out) == (int)*out_len);
  439. return end+1;
  440. }
  441. /** Acts like sprintf, but writes its formatted string to the end of
  442. * <b>conn</b>-\>outbuf. */
  443. static void
  444. connection_printf_to_buf(control_connection_t *conn, const char *format, ...)
  445. {
  446. va_list ap;
  447. char *buf = NULL;
  448. int len;
  449. va_start(ap,format);
  450. len = tor_vasprintf(&buf, format, ap);
  451. va_end(ap);
  452. if (len < 0) {
  453. log_err(LD_BUG, "Unable to format string for controller.");
  454. tor_assert(0);
  455. }
  456. connection_write_to_buf(buf, (size_t)len, TO_CONN(conn));
  457. tor_free(buf);
  458. }
  459. /** Write all of the open control ports to ControlPortWriteToFile */
  460. void
  461. control_ports_write_to_file(void)
  462. {
  463. smartlist_t *lines;
  464. char *joined = NULL;
  465. const or_options_t *options = get_options();
  466. if (!options->ControlPortWriteToFile)
  467. return;
  468. lines = smartlist_new();
  469. SMARTLIST_FOREACH_BEGIN(get_connection_array(), const connection_t *, conn) {
  470. if (conn->type != CONN_TYPE_CONTROL_LISTENER || conn->marked_for_close)
  471. continue;
  472. #ifdef AF_UNIX
  473. if (conn->socket_family == AF_UNIX) {
  474. smartlist_add_asprintf(lines, "UNIX_PORT=%s\n", conn->address);
  475. continue;
  476. }
  477. #endif
  478. smartlist_add_asprintf(lines, "PORT=%s:%d\n", conn->address, conn->port);
  479. } SMARTLIST_FOREACH_END(conn);
  480. joined = smartlist_join_strings(lines, "", 0, NULL);
  481. if (write_str_to_file(options->ControlPortWriteToFile, joined, 0) < 0) {
  482. log_warn(LD_CONTROL, "Writing %s failed: %s",
  483. options->ControlPortWriteToFile, strerror(errno));
  484. }
  485. #ifndef _WIN32
  486. if (options->ControlPortFileGroupReadable) {
  487. if (chmod(options->ControlPortWriteToFile, 0640)) {
  488. log_warn(LD_FS,"Unable to make %s group-readable.",
  489. options->ControlPortWriteToFile);
  490. }
  491. }
  492. #endif
  493. tor_free(joined);
  494. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  495. smartlist_free(lines);
  496. }
  497. /** Send a "DONE" message down the control connection <b>conn</b>. */
  498. static void
  499. send_control_done(control_connection_t *conn)
  500. {
  501. connection_write_str_to_buf("250 OK\r\n", conn);
  502. }
  503. /** Send an event to all v1 controllers that are listening for code
  504. * <b>event</b>. The event's body is given by <b>msg</b>.
  505. *
  506. * If <b>which</b> & SHORT_NAMES, the event contains short-format names: send
  507. * it to controllers that haven't enabled the VERBOSE_NAMES feature. If
  508. * <b>which</b> & LONG_NAMES, the event contains long-format names: send it
  509. * to controllers that <em>have</em> enabled VERBOSE_NAMES.
  510. *
  511. * The EXTENDED_FORMAT and NONEXTENDED_FORMAT flags behave similarly with
  512. * respect to the EXTENDED_EVENTS feature. */
  513. MOCK_IMPL(STATIC void,
  514. send_control_event_string,(uint16_t event, event_format_t which,
  515. const char *msg))
  516. {
  517. smartlist_t *conns = get_connection_array();
  518. (void)which;
  519. tor_assert(event >= EVENT_MIN_ && event <= EVENT_MAX_);
  520. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
  521. if (conn->type == CONN_TYPE_CONTROL &&
  522. !conn->marked_for_close &&
  523. conn->state == CONTROL_CONN_STATE_OPEN) {
  524. control_connection_t *control_conn = TO_CONTROL_CONN(conn);
  525. if (control_conn->event_mask & (((event_mask_t)1)<<event)) {
  526. int is_err = 0;
  527. connection_write_to_buf(msg, strlen(msg), TO_CONN(control_conn));
  528. if (event == EVENT_ERR_MSG)
  529. is_err = 1;
  530. else if (event == EVENT_STATUS_GENERAL)
  531. is_err = !strcmpstart(msg, "STATUS_GENERAL ERR ");
  532. else if (event == EVENT_STATUS_CLIENT)
  533. is_err = !strcmpstart(msg, "STATUS_CLIENT ERR ");
  534. else if (event == EVENT_STATUS_SERVER)
  535. is_err = !strcmpstart(msg, "STATUS_SERVER ERR ");
  536. if (is_err)
  537. connection_flush(TO_CONN(control_conn));
  538. }
  539. }
  540. } SMARTLIST_FOREACH_END(conn);
  541. }
  542. /** Helper for send_control_event and control_event_status:
  543. * Send an event to all v1 controllers that are listening for code
  544. * <b>event</b>. The event's body is created by the printf-style format in
  545. * <b>format</b>, and other arguments as provided. */
  546. static void
  547. send_control_event_impl(uint16_t event, event_format_t which,
  548. const char *format, va_list ap)
  549. {
  550. char *buf = NULL;
  551. int len;
  552. len = tor_vasprintf(&buf, format, ap);
  553. if (len < 0) {
  554. log_warn(LD_BUG, "Unable to format event for controller.");
  555. return;
  556. }
  557. send_control_event_string(event, which|ALL_FORMATS, buf);
  558. tor_free(buf);
  559. }
  560. /** Send an event to all v1 controllers that are listening for code
  561. * <b>event</b>. The event's body is created by the printf-style format in
  562. * <b>format</b>, and other arguments as provided. */
  563. static void
  564. send_control_event(uint16_t event, event_format_t which,
  565. const char *format, ...)
  566. {
  567. va_list ap;
  568. va_start(ap, format);
  569. send_control_event_impl(event, which, format, ap);
  570. va_end(ap);
  571. }
  572. /** Given a text circuit <b>id</b>, return the corresponding circuit. */
  573. static origin_circuit_t *
  574. get_circ(const char *id)
  575. {
  576. uint32_t n_id;
  577. int ok;
  578. n_id = (uint32_t) tor_parse_ulong(id, 10, 0, UINT32_MAX, &ok, NULL);
  579. if (!ok)
  580. return NULL;
  581. return circuit_get_by_global_id(n_id);
  582. }
  583. /** Given a text stream <b>id</b>, return the corresponding AP connection. */
  584. static entry_connection_t *
  585. get_stream(const char *id)
  586. {
  587. uint64_t n_id;
  588. int ok;
  589. connection_t *conn;
  590. n_id = tor_parse_uint64(id, 10, 0, UINT64_MAX, &ok, NULL);
  591. if (!ok)
  592. return NULL;
  593. conn = connection_get_by_global_id(n_id);
  594. if (!conn || conn->type != CONN_TYPE_AP || conn->marked_for_close)
  595. return NULL;
  596. return TO_ENTRY_CONN(conn);
  597. }
  598. /** Helper for setconf and resetconf. Acts like setconf, except
  599. * it passes <b>use_defaults</b> on to options_trial_assign(). Modifies the
  600. * contents of body.
  601. */
  602. static int
  603. control_setconf_helper(control_connection_t *conn, uint32_t len, char *body,
  604. int use_defaults)
  605. {
  606. setopt_err_t opt_err;
  607. config_line_t *lines=NULL;
  608. char *start = body;
  609. char *errstring = NULL;
  610. const int clear_first = 1;
  611. char *config;
  612. smartlist_t *entries = smartlist_new();
  613. /* We have a string, "body", of the format '(key(=val|="val")?)' entries
  614. * separated by space. break it into a list of configuration entries. */
  615. while (*body) {
  616. char *eq = body;
  617. char *key;
  618. char *entry;
  619. while (!TOR_ISSPACE(*eq) && *eq != '=')
  620. ++eq;
  621. key = tor_strndup(body, eq-body);
  622. body = eq+1;
  623. if (*eq == '=') {
  624. char *val=NULL;
  625. size_t val_len=0;
  626. if (*body != '\"') {
  627. char *val_start = body;
  628. while (!TOR_ISSPACE(*body))
  629. body++;
  630. val = tor_strndup(val_start, body-val_start);
  631. val_len = strlen(val);
  632. } else {
  633. body = (char*)extract_escaped_string(body, (len - (body-start)),
  634. &val, &val_len);
  635. if (!body) {
  636. connection_write_str_to_buf("551 Couldn't parse string\r\n", conn);
  637. SMARTLIST_FOREACH(entries, char *, cp, tor_free(cp));
  638. smartlist_free(entries);
  639. tor_free(key);
  640. return 0;
  641. }
  642. }
  643. tor_asprintf(&entry, "%s %s", key, val);
  644. tor_free(key);
  645. tor_free(val);
  646. } else {
  647. entry = key;
  648. }
  649. smartlist_add(entries, entry);
  650. while (TOR_ISSPACE(*body))
  651. ++body;
  652. }
  653. smartlist_add(entries, tor_strdup(""));
  654. config = smartlist_join_strings(entries, "\n", 0, NULL);
  655. SMARTLIST_FOREACH(entries, char *, cp, tor_free(cp));
  656. smartlist_free(entries);
  657. if (config_get_lines(config, &lines, 0) < 0) {
  658. log_warn(LD_CONTROL,"Controller gave us config lines we can't parse.");
  659. connection_write_str_to_buf("551 Couldn't parse configuration\r\n",
  660. conn);
  661. tor_free(config);
  662. return 0;
  663. }
  664. tor_free(config);
  665. opt_err = options_trial_assign(lines, use_defaults, clear_first, &errstring);
  666. {
  667. const char *msg;
  668. switch (opt_err) {
  669. case SETOPT_ERR_MISC:
  670. msg = "552 Unrecognized option";
  671. break;
  672. case SETOPT_ERR_PARSE:
  673. msg = "513 Unacceptable option value";
  674. break;
  675. case SETOPT_ERR_TRANSITION:
  676. msg = "553 Transition not allowed";
  677. break;
  678. case SETOPT_ERR_SETTING:
  679. default:
  680. msg = "553 Unable to set option";
  681. break;
  682. case SETOPT_OK:
  683. config_free_lines(lines);
  684. send_control_done(conn);
  685. return 0;
  686. }
  687. log_warn(LD_CONTROL,
  688. "Controller gave us config lines that didn't validate: %s",
  689. errstring);
  690. connection_printf_to_buf(conn, "%s: %s\r\n", msg, errstring);
  691. config_free_lines(lines);
  692. tor_free(errstring);
  693. return 0;
  694. }
  695. }
  696. /** Called when we receive a SETCONF message: parse the body and try
  697. * to update our configuration. Reply with a DONE or ERROR message.
  698. * Modifies the contents of body.*/
  699. static int
  700. handle_control_setconf(control_connection_t *conn, uint32_t len, char *body)
  701. {
  702. return control_setconf_helper(conn, len, body, 0);
  703. }
  704. /** Called when we receive a RESETCONF message: parse the body and try
  705. * to update our configuration. Reply with a DONE or ERROR message.
  706. * Modifies the contents of body. */
  707. static int
  708. handle_control_resetconf(control_connection_t *conn, uint32_t len, char *body)
  709. {
  710. return control_setconf_helper(conn, len, body, 1);
  711. }
  712. /** Called when we receive a GETCONF message. Parse the request, and
  713. * reply with a CONFVALUE or an ERROR message */
  714. static int
  715. handle_control_getconf(control_connection_t *conn, uint32_t body_len,
  716. const char *body)
  717. {
  718. smartlist_t *questions = smartlist_new();
  719. smartlist_t *answers = smartlist_new();
  720. smartlist_t *unrecognized = smartlist_new();
  721. char *msg = NULL;
  722. size_t msg_len;
  723. const or_options_t *options = get_options();
  724. int i, len;
  725. (void) body_len; /* body is NUL-terminated; so we can ignore len. */
  726. smartlist_split_string(questions, body, " ",
  727. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  728. SMARTLIST_FOREACH_BEGIN(questions, const char *, q) {
  729. if (!option_is_recognized(q)) {
  730. smartlist_add(unrecognized, (char*) q);
  731. } else {
  732. config_line_t *answer = option_get_assignment(options,q);
  733. if (!answer) {
  734. const char *name = option_get_canonical_name(q);
  735. smartlist_add_asprintf(answers, "250-%s\r\n", name);
  736. }
  737. while (answer) {
  738. config_line_t *next;
  739. smartlist_add_asprintf(answers, "250-%s=%s\r\n",
  740. answer->key, answer->value);
  741. next = answer->next;
  742. tor_free(answer->key);
  743. tor_free(answer->value);
  744. tor_free(answer);
  745. answer = next;
  746. }
  747. }
  748. } SMARTLIST_FOREACH_END(q);
  749. if ((len = smartlist_len(unrecognized))) {
  750. for (i=0; i < len-1; ++i)
  751. connection_printf_to_buf(conn,
  752. "552-Unrecognized configuration key \"%s\"\r\n",
  753. (char*)smartlist_get(unrecognized, i));
  754. connection_printf_to_buf(conn,
  755. "552 Unrecognized configuration key \"%s\"\r\n",
  756. (char*)smartlist_get(unrecognized, len-1));
  757. } else if ((len = smartlist_len(answers))) {
  758. char *tmp = smartlist_get(answers, len-1);
  759. tor_assert(strlen(tmp)>4);
  760. tmp[3] = ' ';
  761. msg = smartlist_join_strings(answers, "", 0, &msg_len);
  762. connection_write_to_buf(msg, msg_len, TO_CONN(conn));
  763. } else {
  764. connection_write_str_to_buf("250 OK\r\n", conn);
  765. }
  766. SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
  767. smartlist_free(answers);
  768. SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
  769. smartlist_free(questions);
  770. smartlist_free(unrecognized);
  771. tor_free(msg);
  772. return 0;
  773. }
  774. /** Called when we get a +LOADCONF message. */
  775. static int
  776. handle_control_loadconf(control_connection_t *conn, uint32_t len,
  777. const char *body)
  778. {
  779. setopt_err_t retval;
  780. char *errstring = NULL;
  781. const char *msg = NULL;
  782. (void) len;
  783. retval = options_init_from_string(NULL, body, CMD_RUN_TOR, NULL, &errstring);
  784. if (retval != SETOPT_OK)
  785. log_warn(LD_CONTROL,
  786. "Controller gave us config file that didn't validate: %s",
  787. errstring);
  788. switch (retval) {
  789. case SETOPT_ERR_PARSE:
  790. msg = "552 Invalid config file";
  791. break;
  792. case SETOPT_ERR_TRANSITION:
  793. msg = "553 Transition not allowed";
  794. break;
  795. case SETOPT_ERR_SETTING:
  796. msg = "553 Unable to set option";
  797. break;
  798. case SETOPT_ERR_MISC:
  799. default:
  800. msg = "550 Unable to load config";
  801. break;
  802. case SETOPT_OK:
  803. break;
  804. }
  805. if (msg) {
  806. if (errstring)
  807. connection_printf_to_buf(conn, "%s: %s\r\n", msg, errstring);
  808. else
  809. connection_printf_to_buf(conn, "%s\r\n", msg);
  810. } else {
  811. send_control_done(conn);
  812. }
  813. tor_free(errstring);
  814. return 0;
  815. }
  816. /** Helper structure: maps event values to their names. */
  817. struct control_event_t {
  818. uint16_t event_code;
  819. const char *event_name;
  820. };
  821. /** Table mapping event values to their names. Used to implement SETEVENTS
  822. * and GETINFO events/names, and to keep they in sync. */
  823. static const struct control_event_t control_event_table[] = {
  824. { EVENT_CIRCUIT_STATUS, "CIRC" },
  825. { EVENT_CIRCUIT_STATUS_MINOR, "CIRC_MINOR" },
  826. { EVENT_STREAM_STATUS, "STREAM" },
  827. { EVENT_OR_CONN_STATUS, "ORCONN" },
  828. { EVENT_BANDWIDTH_USED, "BW" },
  829. { EVENT_DEBUG_MSG, "DEBUG" },
  830. { EVENT_INFO_MSG, "INFO" },
  831. { EVENT_NOTICE_MSG, "NOTICE" },
  832. { EVENT_WARN_MSG, "WARN" },
  833. { EVENT_ERR_MSG, "ERR" },
  834. { EVENT_NEW_DESC, "NEWDESC" },
  835. { EVENT_ADDRMAP, "ADDRMAP" },
  836. { EVENT_AUTHDIR_NEWDESCS, "AUTHDIR_NEWDESCS" },
  837. { EVENT_DESCCHANGED, "DESCCHANGED" },
  838. { EVENT_NS, "NS" },
  839. { EVENT_STATUS_GENERAL, "STATUS_GENERAL" },
  840. { EVENT_STATUS_CLIENT, "STATUS_CLIENT" },
  841. { EVENT_STATUS_SERVER, "STATUS_SERVER" },
  842. { EVENT_GUARD, "GUARD" },
  843. { EVENT_STREAM_BANDWIDTH_USED, "STREAM_BW" },
  844. { EVENT_CLIENTS_SEEN, "CLIENTS_SEEN" },
  845. { EVENT_NEWCONSENSUS, "NEWCONSENSUS" },
  846. { EVENT_BUILDTIMEOUT_SET, "BUILDTIMEOUT_SET" },
  847. { EVENT_SIGNAL, "SIGNAL" },
  848. { EVENT_CONF_CHANGED, "CONF_CHANGED"},
  849. { EVENT_CONN_BW, "CONN_BW" },
  850. { EVENT_CELL_STATS, "CELL_STATS" },
  851. { EVENT_TB_EMPTY, "TB_EMPTY" },
  852. { EVENT_CIRC_BANDWIDTH_USED, "CIRC_BW" },
  853. { EVENT_TRANSPORT_LAUNCHED, "TRANSPORT_LAUNCHED" },
  854. { EVENT_HS_DESC, "HS_DESC" },
  855. { 0, NULL },
  856. };
  857. /** Called when we get a SETEVENTS message: update conn->event_mask,
  858. * and reply with DONE or ERROR. */
  859. static int
  860. handle_control_setevents(control_connection_t *conn, uint32_t len,
  861. const char *body)
  862. {
  863. int event_code = -1;
  864. event_mask_t event_mask = 0;
  865. smartlist_t *events = smartlist_new();
  866. (void) len;
  867. smartlist_split_string(events, body, " ",
  868. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  869. SMARTLIST_FOREACH_BEGIN(events, const char *, ev)
  870. {
  871. if (!strcasecmp(ev, "EXTENDED")) {
  872. continue;
  873. } else {
  874. int i;
  875. for (i = 0; control_event_table[i].event_name != NULL; ++i) {
  876. if (!strcasecmp(ev, control_event_table[i].event_name)) {
  877. event_code = control_event_table[i].event_code;
  878. break;
  879. }
  880. }
  881. if (event_code == -1) {
  882. connection_printf_to_buf(conn, "552 Unrecognized event \"%s\"\r\n",
  883. ev);
  884. SMARTLIST_FOREACH(events, char *, e, tor_free(e));
  885. smartlist_free(events);
  886. return 0;
  887. }
  888. }
  889. event_mask |= (((event_mask_t)1) << event_code);
  890. }
  891. SMARTLIST_FOREACH_END(ev);
  892. SMARTLIST_FOREACH(events, char *, e, tor_free(e));
  893. smartlist_free(events);
  894. conn->event_mask = event_mask;
  895. control_update_global_event_mask();
  896. send_control_done(conn);
  897. return 0;
  898. }
  899. /** Decode the hashed, base64'd passwords stored in <b>passwords</b>.
  900. * Return a smartlist of acceptable passwords (unterminated strings of
  901. * length S2K_SPECIFIER_LEN+DIGEST_LEN) on success, or NULL on failure.
  902. */
  903. smartlist_t *
  904. decode_hashed_passwords(config_line_t *passwords)
  905. {
  906. char decoded[64];
  907. config_line_t *cl;
  908. smartlist_t *sl = smartlist_new();
  909. tor_assert(passwords);
  910. for (cl = passwords; cl; cl = cl->next) {
  911. const char *hashed = cl->value;
  912. if (!strcmpstart(hashed, "16:")) {
  913. if (base16_decode(decoded, sizeof(decoded), hashed+3, strlen(hashed+3))<0
  914. || strlen(hashed+3) != (S2K_SPECIFIER_LEN+DIGEST_LEN)*2) {
  915. goto err;
  916. }
  917. } else {
  918. if (base64_decode(decoded, sizeof(decoded), hashed, strlen(hashed))
  919. != S2K_SPECIFIER_LEN+DIGEST_LEN) {
  920. goto err;
  921. }
  922. }
  923. smartlist_add(sl, tor_memdup(decoded, S2K_SPECIFIER_LEN+DIGEST_LEN));
  924. }
  925. return sl;
  926. err:
  927. SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
  928. smartlist_free(sl);
  929. return NULL;
  930. }
  931. /** Called when we get an AUTHENTICATE message. Check whether the
  932. * authentication is valid, and if so, update the connection's state to
  933. * OPEN. Reply with DONE or ERROR.
  934. */
  935. static int
  936. handle_control_authenticate(control_connection_t *conn, uint32_t len,
  937. const char *body)
  938. {
  939. int used_quoted_string = 0;
  940. const or_options_t *options = get_options();
  941. const char *errstr = "Unknown error";
  942. char *password;
  943. size_t password_len;
  944. const char *cp;
  945. int i;
  946. int bad_cookie=0, bad_password=0;
  947. smartlist_t *sl = NULL;
  948. if (!len) {
  949. password = tor_strdup("");
  950. password_len = 0;
  951. } else if (TOR_ISXDIGIT(body[0])) {
  952. cp = body;
  953. while (TOR_ISXDIGIT(*cp))
  954. ++cp;
  955. i = (int)(cp - body);
  956. tor_assert(i>0);
  957. password_len = i/2;
  958. password = tor_malloc(password_len + 1);
  959. if (base16_decode(password, password_len+1, body, i)<0) {
  960. connection_write_str_to_buf(
  961. "551 Invalid hexadecimal encoding. Maybe you tried a plain text "
  962. "password? If so, the standard requires that you put it in "
  963. "double quotes.\r\n", conn);
  964. connection_mark_for_close(TO_CONN(conn));
  965. tor_free(password);
  966. return 0;
  967. }
  968. } else {
  969. if (!decode_escaped_string(body, len, &password, &password_len)) {
  970. connection_write_str_to_buf("551 Invalid quoted string. You need "
  971. "to put the password in double quotes.\r\n", conn);
  972. connection_mark_for_close(TO_CONN(conn));
  973. return 0;
  974. }
  975. used_quoted_string = 1;
  976. }
  977. if (conn->safecookie_client_hash != NULL) {
  978. /* The controller has chosen safe cookie authentication; the only
  979. * acceptable authentication value is the controller-to-server
  980. * response. */
  981. tor_assert(authentication_cookie_is_set);
  982. if (password_len != DIGEST256_LEN) {
  983. log_warn(LD_CONTROL,
  984. "Got safe cookie authentication response with wrong length "
  985. "(%d)", (int)password_len);
  986. errstr = "Wrong length for safe cookie response.";
  987. goto err;
  988. }
  989. if (tor_memneq(conn->safecookie_client_hash, password, DIGEST256_LEN)) {
  990. log_warn(LD_CONTROL,
  991. "Got incorrect safe cookie authentication response");
  992. errstr = "Safe cookie response did not match expected value.";
  993. goto err;
  994. }
  995. tor_free(conn->safecookie_client_hash);
  996. goto ok;
  997. }
  998. if (!options->CookieAuthentication && !options->HashedControlPassword &&
  999. !options->HashedControlSessionPassword) {
  1000. /* if Tor doesn't demand any stronger authentication, then
  1001. * the controller can get in with anything. */
  1002. goto ok;
  1003. }
  1004. if (options->CookieAuthentication) {
  1005. int also_password = options->HashedControlPassword != NULL ||
  1006. options->HashedControlSessionPassword != NULL;
  1007. if (password_len != AUTHENTICATION_COOKIE_LEN) {
  1008. if (!also_password) {
  1009. log_warn(LD_CONTROL, "Got authentication cookie with wrong length "
  1010. "(%d)", (int)password_len);
  1011. errstr = "Wrong length on authentication cookie.";
  1012. goto err;
  1013. }
  1014. bad_cookie = 1;
  1015. } else if (tor_memneq(authentication_cookie, password, password_len)) {
  1016. if (!also_password) {
  1017. log_warn(LD_CONTROL, "Got mismatched authentication cookie");
  1018. errstr = "Authentication cookie did not match expected value.";
  1019. goto err;
  1020. }
  1021. bad_cookie = 1;
  1022. } else {
  1023. goto ok;
  1024. }
  1025. }
  1026. if (options->HashedControlPassword ||
  1027. options->HashedControlSessionPassword) {
  1028. int bad = 0;
  1029. smartlist_t *sl_tmp;
  1030. char received[DIGEST_LEN];
  1031. int also_cookie = options->CookieAuthentication;
  1032. sl = smartlist_new();
  1033. if (options->HashedControlPassword) {
  1034. sl_tmp = decode_hashed_passwords(options->HashedControlPassword);
  1035. if (!sl_tmp)
  1036. bad = 1;
  1037. else {
  1038. smartlist_add_all(sl, sl_tmp);
  1039. smartlist_free(sl_tmp);
  1040. }
  1041. }
  1042. if (options->HashedControlSessionPassword) {
  1043. sl_tmp = decode_hashed_passwords(options->HashedControlSessionPassword);
  1044. if (!sl_tmp)
  1045. bad = 1;
  1046. else {
  1047. smartlist_add_all(sl, sl_tmp);
  1048. smartlist_free(sl_tmp);
  1049. }
  1050. }
  1051. if (bad) {
  1052. if (!also_cookie) {
  1053. log_warn(LD_BUG,
  1054. "Couldn't decode HashedControlPassword: invalid base16");
  1055. errstr="Couldn't decode HashedControlPassword value in configuration.";
  1056. goto err;
  1057. }
  1058. bad_password = 1;
  1059. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1060. smartlist_free(sl);
  1061. } else {
  1062. SMARTLIST_FOREACH(sl, char *, expected,
  1063. {
  1064. secret_to_key(received,DIGEST_LEN,password,password_len,expected);
  1065. if (tor_memeq(expected+S2K_SPECIFIER_LEN, received, DIGEST_LEN))
  1066. goto ok;
  1067. });
  1068. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1069. smartlist_free(sl);
  1070. sl = NULL;
  1071. if (used_quoted_string)
  1072. errstr = "Password did not match HashedControlPassword value from "
  1073. "configuration";
  1074. else
  1075. errstr = "Password did not match HashedControlPassword value from "
  1076. "configuration. Maybe you tried a plain text password? "
  1077. "If so, the standard requires that you put it in double quotes.";
  1078. bad_password = 1;
  1079. if (!also_cookie)
  1080. goto err;
  1081. }
  1082. }
  1083. /** We only get here if both kinds of authentication failed. */
  1084. tor_assert(bad_password && bad_cookie);
  1085. log_warn(LD_CONTROL, "Bad password or authentication cookie on controller.");
  1086. errstr = "Password did not match HashedControlPassword *or* authentication "
  1087. "cookie.";
  1088. err:
  1089. tor_free(password);
  1090. connection_printf_to_buf(conn, "515 Authentication failed: %s\r\n", errstr);
  1091. connection_mark_for_close(TO_CONN(conn));
  1092. if (sl) { /* clean up */
  1093. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1094. smartlist_free(sl);
  1095. }
  1096. return 0;
  1097. ok:
  1098. log_info(LD_CONTROL, "Authenticated control connection ("TOR_SOCKET_T_FORMAT
  1099. ")", conn->base_.s);
  1100. send_control_done(conn);
  1101. conn->base_.state = CONTROL_CONN_STATE_OPEN;
  1102. tor_free(password);
  1103. if (sl) { /* clean up */
  1104. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1105. smartlist_free(sl);
  1106. }
  1107. return 0;
  1108. }
  1109. /** Called when we get a SAVECONF command. Try to flush the current options to
  1110. * disk, and report success or failure. */
  1111. static int
  1112. handle_control_saveconf(control_connection_t *conn, uint32_t len,
  1113. const char *body)
  1114. {
  1115. (void) len;
  1116. (void) body;
  1117. if (options_save_current()<0) {
  1118. connection_write_str_to_buf(
  1119. "551 Unable to write configuration to disk.\r\n", conn);
  1120. } else {
  1121. send_control_done(conn);
  1122. }
  1123. return 0;
  1124. }
  1125. struct signal_t {
  1126. int sig;
  1127. const char *signal_name;
  1128. };
  1129. static const struct signal_t signal_table[] = {
  1130. { SIGHUP, "RELOAD" },
  1131. { SIGHUP, "HUP" },
  1132. { SIGINT, "SHUTDOWN" },
  1133. { SIGUSR1, "DUMP" },
  1134. { SIGUSR1, "USR1" },
  1135. { SIGUSR2, "DEBUG" },
  1136. { SIGUSR2, "USR2" },
  1137. { SIGTERM, "HALT" },
  1138. { SIGTERM, "TERM" },
  1139. { SIGTERM, "INT" },
  1140. { SIGNEWNYM, "NEWNYM" },
  1141. { SIGCLEARDNSCACHE, "CLEARDNSCACHE"},
  1142. { 0, NULL },
  1143. };
  1144. /** Called when we get a SIGNAL command. React to the provided signal, and
  1145. * report success or failure. (If the signal results in a shutdown, success
  1146. * may not be reported.) */
  1147. static int
  1148. handle_control_signal(control_connection_t *conn, uint32_t len,
  1149. const char *body)
  1150. {
  1151. int sig = -1;
  1152. int i;
  1153. int n = 0;
  1154. char *s;
  1155. (void) len;
  1156. while (body[n] && ! TOR_ISSPACE(body[n]))
  1157. ++n;
  1158. s = tor_strndup(body, n);
  1159. for (i = 0; signal_table[i].signal_name != NULL; ++i) {
  1160. if (!strcasecmp(s, signal_table[i].signal_name)) {
  1161. sig = signal_table[i].sig;
  1162. break;
  1163. }
  1164. }
  1165. if (sig < 0)
  1166. connection_printf_to_buf(conn, "552 Unrecognized signal code \"%s\"\r\n",
  1167. s);
  1168. tor_free(s);
  1169. if (sig < 0)
  1170. return 0;
  1171. send_control_done(conn);
  1172. /* Flush the "done" first if the signal might make us shut down. */
  1173. if (sig == SIGTERM || sig == SIGINT)
  1174. connection_flush(TO_CONN(conn));
  1175. process_signal(sig);
  1176. return 0;
  1177. }
  1178. /** Called when we get a TAKEOWNERSHIP command. Mark this connection
  1179. * as an owning connection, so that we will exit if the connection
  1180. * closes. */
  1181. static int
  1182. handle_control_takeownership(control_connection_t *conn, uint32_t len,
  1183. const char *body)
  1184. {
  1185. (void)len;
  1186. (void)body;
  1187. conn->is_owning_control_connection = 1;
  1188. log_info(LD_CONTROL, "Control connection %d has taken ownership of this "
  1189. "Tor instance.",
  1190. (int)(conn->base_.s));
  1191. send_control_done(conn);
  1192. return 0;
  1193. }
  1194. /** Return true iff <b>addr</b> is unusable as a mapaddress target because of
  1195. * containing funny characters. */
  1196. static int
  1197. address_is_invalid_mapaddress_target(const char *addr)
  1198. {
  1199. if (!strcmpstart(addr, "*."))
  1200. return address_is_invalid_destination(addr+2, 1);
  1201. else
  1202. return address_is_invalid_destination(addr, 1);
  1203. }
  1204. /** Called when we get a MAPADDRESS command; try to bind all listed addresses,
  1205. * and report success or failure. */
  1206. static int
  1207. handle_control_mapaddress(control_connection_t *conn, uint32_t len,
  1208. const char *body)
  1209. {
  1210. smartlist_t *elts;
  1211. smartlist_t *lines;
  1212. smartlist_t *reply;
  1213. char *r;
  1214. size_t sz;
  1215. (void) len; /* body is NUL-terminated, so it's safe to ignore the length. */
  1216. lines = smartlist_new();
  1217. elts = smartlist_new();
  1218. reply = smartlist_new();
  1219. smartlist_split_string(lines, body, " ",
  1220. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1221. SMARTLIST_FOREACH_BEGIN(lines, char *, line) {
  1222. tor_strlower(line);
  1223. smartlist_split_string(elts, line, "=", 0, 2);
  1224. if (smartlist_len(elts) == 2) {
  1225. const char *from = smartlist_get(elts,0);
  1226. const char *to = smartlist_get(elts,1);
  1227. if (address_is_invalid_mapaddress_target(to)) {
  1228. smartlist_add_asprintf(reply,
  1229. "512-syntax error: invalid address '%s'", to);
  1230. log_warn(LD_CONTROL,
  1231. "Skipping invalid argument '%s' in MapAddress msg", to);
  1232. } else if (!strcmp(from, ".") || !strcmp(from, "0.0.0.0") ||
  1233. !strcmp(from, "::")) {
  1234. const char type =
  1235. !strcmp(from,".") ? RESOLVED_TYPE_HOSTNAME :
  1236. (!strcmp(from, "0.0.0.0") ? RESOLVED_TYPE_IPV4 : RESOLVED_TYPE_IPV6);
  1237. const char *address = addressmap_register_virtual_address(
  1238. type, tor_strdup(to));
  1239. if (!address) {
  1240. smartlist_add_asprintf(reply,
  1241. "451-resource exhausted: skipping '%s'", line);
  1242. log_warn(LD_CONTROL,
  1243. "Unable to allocate address for '%s' in MapAddress msg",
  1244. safe_str_client(line));
  1245. } else {
  1246. smartlist_add_asprintf(reply, "250-%s=%s", address, to);
  1247. }
  1248. } else {
  1249. const char *msg;
  1250. if (addressmap_register_auto(from, to, 1,
  1251. ADDRMAPSRC_CONTROLLER, &msg) < 0) {
  1252. smartlist_add_asprintf(reply,
  1253. "512-syntax error: invalid address mapping "
  1254. " '%s': %s", line, msg);
  1255. log_warn(LD_CONTROL,
  1256. "Skipping invalid argument '%s' in MapAddress msg: %s",
  1257. line, msg);
  1258. } else {
  1259. smartlist_add_asprintf(reply, "250-%s", line);
  1260. }
  1261. }
  1262. } else {
  1263. smartlist_add_asprintf(reply, "512-syntax error: mapping '%s' is "
  1264. "not of expected form 'foo=bar'.", line);
  1265. log_info(LD_CONTROL, "Skipping MapAddress '%s': wrong "
  1266. "number of items.",
  1267. safe_str_client(line));
  1268. }
  1269. SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
  1270. smartlist_clear(elts);
  1271. } SMARTLIST_FOREACH_END(line);
  1272. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  1273. smartlist_free(lines);
  1274. smartlist_free(elts);
  1275. if (smartlist_len(reply)) {
  1276. ((char*)smartlist_get(reply,smartlist_len(reply)-1))[3] = ' ';
  1277. r = smartlist_join_strings(reply, "\r\n", 1, &sz);
  1278. connection_write_to_buf(r, sz, TO_CONN(conn));
  1279. tor_free(r);
  1280. } else {
  1281. const char *response =
  1282. "512 syntax error: not enough arguments to mapaddress.\r\n";
  1283. connection_write_to_buf(response, strlen(response), TO_CONN(conn));
  1284. }
  1285. SMARTLIST_FOREACH(reply, char *, cp, tor_free(cp));
  1286. smartlist_free(reply);
  1287. return 0;
  1288. }
  1289. /** Implementation helper for GETINFO: knows the answers for various
  1290. * trivial-to-implement questions. */
  1291. static int
  1292. getinfo_helper_misc(control_connection_t *conn, const char *question,
  1293. char **answer, const char **errmsg)
  1294. {
  1295. (void) conn;
  1296. if (!strcmp(question, "version")) {
  1297. *answer = tor_strdup(get_version());
  1298. } else if (!strcmp(question, "config-file")) {
  1299. *answer = tor_strdup(get_torrc_fname(0));
  1300. } else if (!strcmp(question, "config-defaults-file")) {
  1301. *answer = tor_strdup(get_torrc_fname(1));
  1302. } else if (!strcmp(question, "config-text")) {
  1303. *answer = options_dump(get_options(), OPTIONS_DUMP_MINIMAL);
  1304. } else if (!strcmp(question, "info/names")) {
  1305. *answer = list_getinfo_options();
  1306. } else if (!strcmp(question, "dormant")) {
  1307. int dormant = rep_hist_circbuilding_dormant(time(NULL));
  1308. *answer = tor_strdup(dormant ? "1" : "0");
  1309. } else if (!strcmp(question, "events/names")) {
  1310. int i;
  1311. smartlist_t *event_names = smartlist_new();
  1312. for (i = 0; control_event_table[i].event_name != NULL; ++i) {
  1313. smartlist_add(event_names, (char *)control_event_table[i].event_name);
  1314. }
  1315. *answer = smartlist_join_strings(event_names, " ", 0, NULL);
  1316. smartlist_free(event_names);
  1317. } else if (!strcmp(question, "signal/names")) {
  1318. smartlist_t *signal_names = smartlist_new();
  1319. int j;
  1320. for (j = 0; signal_table[j].signal_name != NULL; ++j) {
  1321. smartlist_add(signal_names, (char*)signal_table[j].signal_name);
  1322. }
  1323. *answer = smartlist_join_strings(signal_names, " ", 0, NULL);
  1324. smartlist_free(signal_names);
  1325. } else if (!strcmp(question, "features/names")) {
  1326. *answer = tor_strdup("VERBOSE_NAMES EXTENDED_EVENTS");
  1327. } else if (!strcmp(question, "address")) {
  1328. uint32_t addr;
  1329. if (router_pick_published_address(get_options(), &addr) < 0) {
  1330. *errmsg = "Address unknown";
  1331. return -1;
  1332. }
  1333. *answer = tor_dup_ip(addr);
  1334. } else if (!strcmp(question, "traffic/read")) {
  1335. tor_asprintf(answer, U64_FORMAT, U64_PRINTF_ARG(get_bytes_read()));
  1336. } else if (!strcmp(question, "traffic/written")) {
  1337. tor_asprintf(answer, U64_FORMAT, U64_PRINTF_ARG(get_bytes_written()));
  1338. } else if (!strcmp(question, "process/pid")) {
  1339. int myPid = -1;
  1340. #ifdef _WIN32
  1341. myPid = _getpid();
  1342. #else
  1343. myPid = getpid();
  1344. #endif
  1345. tor_asprintf(answer, "%d", myPid);
  1346. } else if (!strcmp(question, "process/uid")) {
  1347. #ifdef _WIN32
  1348. *answer = tor_strdup("-1");
  1349. #else
  1350. int myUid = geteuid();
  1351. tor_asprintf(answer, "%d", myUid);
  1352. #endif
  1353. } else if (!strcmp(question, "process/user")) {
  1354. #ifdef _WIN32
  1355. *answer = tor_strdup("");
  1356. #else
  1357. int myUid = geteuid();
  1358. const struct passwd *myPwEntry = tor_getpwuid(myUid);
  1359. if (myPwEntry) {
  1360. *answer = tor_strdup(myPwEntry->pw_name);
  1361. } else {
  1362. *answer = tor_strdup("");
  1363. }
  1364. #endif
  1365. } else if (!strcmp(question, "process/descriptor-limit")) {
  1366. int max_fds=-1;
  1367. set_max_file_descriptors(0, &max_fds);
  1368. tor_asprintf(answer, "%d", max_fds);
  1369. } else if (!strcmp(question, "limits/max-mem-in-queues")) {
  1370. tor_asprintf(answer, U64_FORMAT,
  1371. U64_PRINTF_ARG(get_options()->MaxMemInQueues));
  1372. } else if (!strcmp(question, "dir-usage")) {
  1373. *answer = directory_dump_request_log();
  1374. } else if (!strcmp(question, "fingerprint")) {
  1375. crypto_pk_t *server_key;
  1376. if (!server_mode(get_options())) {
  1377. *errmsg = "Not running in server mode";
  1378. return -1;
  1379. }
  1380. server_key = get_server_identity_key();
  1381. *answer = tor_malloc(HEX_DIGEST_LEN+1);
  1382. crypto_pk_get_fingerprint(server_key, *answer, 0);
  1383. }
  1384. return 0;
  1385. }
  1386. /** Awful hack: return a newly allocated string based on a routerinfo and
  1387. * (possibly) an extrainfo, sticking the read-history and write-history from
  1388. * <b>ei</b> into the resulting string. The thing you get back won't
  1389. * necessarily have a valid signature.
  1390. *
  1391. * New code should never use this; it's for backward compatibility.
  1392. *
  1393. * NOTE: <b>ri_body</b> is as returned by signed_descriptor_get_body: it might
  1394. * not be NUL-terminated. */
  1395. static char *
  1396. munge_extrainfo_into_routerinfo(const char *ri_body,
  1397. const signed_descriptor_t *ri,
  1398. const signed_descriptor_t *ei)
  1399. {
  1400. char *out = NULL, *outp;
  1401. int i;
  1402. const char *router_sig;
  1403. const char *ei_body = signed_descriptor_get_body(ei);
  1404. size_t ri_len = ri->signed_descriptor_len;
  1405. size_t ei_len = ei->signed_descriptor_len;
  1406. if (!ei_body)
  1407. goto bail;
  1408. outp = out = tor_malloc(ri_len+ei_len+1);
  1409. if (!(router_sig = tor_memstr(ri_body, ri_len, "\nrouter-signature")))
  1410. goto bail;
  1411. ++router_sig;
  1412. memcpy(out, ri_body, router_sig-ri_body);
  1413. outp += router_sig-ri_body;
  1414. for (i=0; i < 2; ++i) {
  1415. const char *kwd = i ? "\nwrite-history " : "\nread-history ";
  1416. const char *cp, *eol;
  1417. if (!(cp = tor_memstr(ei_body, ei_len, kwd)))
  1418. continue;
  1419. ++cp;
  1420. if (!(eol = memchr(cp, '\n', ei_len - (cp-ei_body))))
  1421. continue;
  1422. memcpy(outp, cp, eol-cp+1);
  1423. outp += eol-cp+1;
  1424. }
  1425. memcpy(outp, router_sig, ri_len - (router_sig-ri_body));
  1426. *outp++ = '\0';
  1427. tor_assert(outp-out < (int)(ri_len+ei_len+1));
  1428. return out;
  1429. bail:
  1430. tor_free(out);
  1431. return tor_strndup(ri_body, ri->signed_descriptor_len);
  1432. }
  1433. /** Implementation helper for GETINFO: answers requests for information about
  1434. * which ports are bound. */
  1435. static int
  1436. getinfo_helper_listeners(control_connection_t *control_conn,
  1437. const char *question,
  1438. char **answer, const char **errmsg)
  1439. {
  1440. int type;
  1441. smartlist_t *res;
  1442. (void)control_conn;
  1443. (void)errmsg;
  1444. if (!strcmp(question, "net/listeners/or"))
  1445. type = CONN_TYPE_OR_LISTENER;
  1446. else if (!strcmp(question, "net/listeners/dir"))
  1447. type = CONN_TYPE_DIR_LISTENER;
  1448. else if (!strcmp(question, "net/listeners/socks"))
  1449. type = CONN_TYPE_AP_LISTENER;
  1450. else if (!strcmp(question, "net/listeners/trans"))
  1451. type = CONN_TYPE_AP_TRANS_LISTENER;
  1452. else if (!strcmp(question, "net/listeners/natd"))
  1453. type = CONN_TYPE_AP_NATD_LISTENER;
  1454. else if (!strcmp(question, "net/listeners/dns"))
  1455. type = CONN_TYPE_AP_DNS_LISTENER;
  1456. else if (!strcmp(question, "net/listeners/control"))
  1457. type = CONN_TYPE_CONTROL_LISTENER;
  1458. else
  1459. return 0; /* unknown key */
  1460. res = smartlist_new();
  1461. SMARTLIST_FOREACH_BEGIN(get_connection_array(), connection_t *, conn) {
  1462. struct sockaddr_storage ss;
  1463. socklen_t ss_len = sizeof(ss);
  1464. if (conn->type != type || conn->marked_for_close || !SOCKET_OK(conn->s))
  1465. continue;
  1466. if (getsockname(conn->s, (struct sockaddr *)&ss, &ss_len) < 0) {
  1467. smartlist_add_asprintf(res, "%s:%d", conn->address, (int)conn->port);
  1468. } else {
  1469. char *tmp = tor_sockaddr_to_str((struct sockaddr *)&ss);
  1470. smartlist_add(res, esc_for_log(tmp));
  1471. tor_free(tmp);
  1472. }
  1473. } SMARTLIST_FOREACH_END(conn);
  1474. *answer = smartlist_join_strings(res, " ", 0, NULL);
  1475. SMARTLIST_FOREACH(res, char *, cp, tor_free(cp));
  1476. smartlist_free(res);
  1477. return 0;
  1478. }
  1479. /** Implementation helper for GETINFO: knows the answers for questions about
  1480. * directory information. */
  1481. static int
  1482. getinfo_helper_dir(control_connection_t *control_conn,
  1483. const char *question, char **answer,
  1484. const char **errmsg)
  1485. {
  1486. const node_t *node;
  1487. const routerinfo_t *ri = NULL;
  1488. (void) control_conn;
  1489. if (!strcmpstart(question, "desc/id/")) {
  1490. node = node_get_by_hex_id(question+strlen("desc/id/"));
  1491. if (node)
  1492. ri = node->ri;
  1493. if (ri) {
  1494. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1495. if (body)
  1496. *answer = tor_strndup(body, ri->cache_info.signed_descriptor_len);
  1497. }
  1498. } else if (!strcmpstart(question, "desc/name/")) {
  1499. /* XXX023 Setting 'warn_if_unnamed' here is a bit silly -- the
  1500. * warning goes to the user, not to the controller. */
  1501. node = node_get_by_nickname(question+strlen("desc/name/"), 1);
  1502. if (node)
  1503. ri = node->ri;
  1504. if (ri) {
  1505. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1506. if (body)
  1507. *answer = tor_strndup(body, ri->cache_info.signed_descriptor_len);
  1508. }
  1509. } else if (!strcmp(question, "desc/all-recent")) {
  1510. routerlist_t *routerlist = router_get_routerlist();
  1511. smartlist_t *sl = smartlist_new();
  1512. if (routerlist && routerlist->routers) {
  1513. SMARTLIST_FOREACH(routerlist->routers, const routerinfo_t *, ri,
  1514. {
  1515. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1516. if (body)
  1517. smartlist_add(sl,
  1518. tor_strndup(body, ri->cache_info.signed_descriptor_len));
  1519. });
  1520. }
  1521. *answer = smartlist_join_strings(sl, "", 0, NULL);
  1522. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  1523. smartlist_free(sl);
  1524. } else if (!strcmp(question, "desc/all-recent-extrainfo-hack")) {
  1525. /* XXXX Remove this once Torstat asks for extrainfos. */
  1526. routerlist_t *routerlist = router_get_routerlist();
  1527. smartlist_t *sl = smartlist_new();
  1528. if (routerlist && routerlist->routers) {
  1529. SMARTLIST_FOREACH_BEGIN(routerlist->routers, const routerinfo_t *, ri) {
  1530. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1531. signed_descriptor_t *ei = extrainfo_get_by_descriptor_digest(
  1532. ri->cache_info.extra_info_digest);
  1533. if (ei && body) {
  1534. smartlist_add(sl, munge_extrainfo_into_routerinfo(body,
  1535. &ri->cache_info, ei));
  1536. } else if (body) {
  1537. smartlist_add(sl,
  1538. tor_strndup(body, ri->cache_info.signed_descriptor_len));
  1539. }
  1540. } SMARTLIST_FOREACH_END(ri);
  1541. }
  1542. *answer = smartlist_join_strings(sl, "", 0, NULL);
  1543. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  1544. smartlist_free(sl);
  1545. } else if (!strcmpstart(question, "md/id/")) {
  1546. const node_t *node = node_get_by_hex_id(question+strlen("md/id/"));
  1547. const microdesc_t *md = NULL;
  1548. if (node) md = node->md;
  1549. if (md && md->body) {
  1550. *answer = tor_strndup(md->body, md->bodylen);
  1551. }
  1552. } else if (!strcmpstart(question, "md/name/")) {
  1553. /* XXX023 Setting 'warn_if_unnamed' here is a bit silly -- the
  1554. * warning goes to the user, not to the controller. */
  1555. const node_t *node = node_get_by_nickname(question+strlen("md/name/"), 1);
  1556. /* XXXX duplicated code */
  1557. const microdesc_t *md = NULL;
  1558. if (node) md = node->md;
  1559. if (md && md->body) {
  1560. *answer = tor_strndup(md->body, md->bodylen);
  1561. }
  1562. } else if (!strcmpstart(question, "desc-annotations/id/")) {
  1563. node = node_get_by_hex_id(question+strlen("desc-annotations/id/"));
  1564. if (node)
  1565. ri = node->ri;
  1566. if (ri) {
  1567. const char *annotations =
  1568. signed_descriptor_get_annotations(&ri->cache_info);
  1569. if (annotations)
  1570. *answer = tor_strndup(annotations,
  1571. ri->cache_info.annotations_len);
  1572. }
  1573. } else if (!strcmpstart(question, "dir/server/")) {
  1574. size_t answer_len = 0;
  1575. char *url = NULL;
  1576. smartlist_t *descs = smartlist_new();
  1577. const char *msg;
  1578. int res;
  1579. char *cp;
  1580. tor_asprintf(&url, "/tor/%s", question+4);
  1581. res = dirserv_get_routerdescs(descs, url, &msg);
  1582. if (res) {
  1583. log_warn(LD_CONTROL, "getinfo '%s': %s", question, msg);
  1584. smartlist_free(descs);
  1585. tor_free(url);
  1586. *errmsg = msg;
  1587. return -1;
  1588. }
  1589. SMARTLIST_FOREACH(descs, signed_descriptor_t *, sd,
  1590. answer_len += sd->signed_descriptor_len);
  1591. cp = *answer = tor_malloc(answer_len+1);
  1592. SMARTLIST_FOREACH(descs, signed_descriptor_t *, sd,
  1593. {
  1594. memcpy(cp, signed_descriptor_get_body(sd),
  1595. sd->signed_descriptor_len);
  1596. cp += sd->signed_descriptor_len;
  1597. });
  1598. *cp = '\0';
  1599. tor_free(url);
  1600. smartlist_free(descs);
  1601. } else if (!strcmpstart(question, "dir/status/")) {
  1602. *answer = tor_strdup("");
  1603. } else if (!strcmp(question, "dir/status-vote/current/consensus")) { /* v3 */
  1604. if (directory_caches_dir_info(get_options())) {
  1605. const cached_dir_t *consensus = dirserv_get_consensus("ns");
  1606. if (consensus)
  1607. *answer = tor_strdup(consensus->dir);
  1608. }
  1609. if (!*answer) { /* try loading it from disk */
  1610. char *filename = get_datadir_fname("cached-consensus");
  1611. *answer = read_file_to_str(filename, RFTS_IGNORE_MISSING, NULL);
  1612. tor_free(filename);
  1613. }
  1614. } else if (!strcmp(question, "network-status")) { /* v1 */
  1615. routerlist_t *routerlist = router_get_routerlist();
  1616. if (!routerlist || !routerlist->routers ||
  1617. list_server_status_v1(routerlist->routers, answer, 1) < 0) {
  1618. return -1;
  1619. }
  1620. } else if (!strcmpstart(question, "extra-info/digest/")) {
  1621. question += strlen("extra-info/digest/");
  1622. if (strlen(question) == HEX_DIGEST_LEN) {
  1623. char d[DIGEST_LEN];
  1624. signed_descriptor_t *sd = NULL;
  1625. if (base16_decode(d, sizeof(d), question, strlen(question))==0) {
  1626. /* XXXX this test should move into extrainfo_get_by_descriptor_digest,
  1627. * but I don't want to risk affecting other parts of the code,
  1628. * especially since the rules for using our own extrainfo (including
  1629. * when it might be freed) are different from those for using one
  1630. * we have downloaded. */
  1631. if (router_extrainfo_digest_is_me(d))
  1632. sd = &(router_get_my_extrainfo()->cache_info);
  1633. else
  1634. sd = extrainfo_get_by_descriptor_digest(d);
  1635. }
  1636. if (sd) {
  1637. const char *body = signed_descriptor_get_body(sd);
  1638. if (body)
  1639. *answer = tor_strndup(body, sd->signed_descriptor_len);
  1640. }
  1641. }
  1642. }
  1643. return 0;
  1644. }
  1645. /** Allocate and return a description of <b>circ</b>'s current status,
  1646. * including its path (if any). */
  1647. static char *
  1648. circuit_describe_status_for_controller(origin_circuit_t *circ)
  1649. {
  1650. char *rv;
  1651. smartlist_t *descparts = smartlist_new();
  1652. {
  1653. char *vpath = circuit_list_path_for_controller(circ);
  1654. if (*vpath) {
  1655. smartlist_add(descparts, vpath);
  1656. } else {
  1657. tor_free(vpath); /* empty path; don't put an extra space in the result */
  1658. }
  1659. }
  1660. {
  1661. cpath_build_state_t *build_state = circ->build_state;
  1662. smartlist_t *flaglist = smartlist_new();
  1663. char *flaglist_joined;
  1664. if (build_state->onehop_tunnel)
  1665. smartlist_add(flaglist, (void *)"ONEHOP_TUNNEL");
  1666. if (build_state->is_internal)
  1667. smartlist_add(flaglist, (void *)"IS_INTERNAL");
  1668. if (build_state->need_capacity)
  1669. smartlist_add(flaglist, (void *)"NEED_CAPACITY");
  1670. if (build_state->need_uptime)
  1671. smartlist_add(flaglist, (void *)"NEED_UPTIME");
  1672. /* Only emit a BUILD_FLAGS argument if it will have a non-empty value. */
  1673. if (smartlist_len(flaglist)) {
  1674. flaglist_joined = smartlist_join_strings(flaglist, ",", 0, NULL);
  1675. smartlist_add_asprintf(descparts, "BUILD_FLAGS=%s", flaglist_joined);
  1676. tor_free(flaglist_joined);
  1677. }
  1678. smartlist_free(flaglist);
  1679. }
  1680. smartlist_add_asprintf(descparts, "PURPOSE=%s",
  1681. circuit_purpose_to_controller_string(circ->base_.purpose));
  1682. {
  1683. const char *hs_state =
  1684. circuit_purpose_to_controller_hs_state_string(circ->base_.purpose);
  1685. if (hs_state != NULL) {
  1686. smartlist_add_asprintf(descparts, "HS_STATE=%s", hs_state);
  1687. }
  1688. }
  1689. if (circ->rend_data != NULL) {
  1690. smartlist_add_asprintf(descparts, "REND_QUERY=%s",
  1691. circ->rend_data->onion_address);
  1692. }
  1693. {
  1694. char tbuf[ISO_TIME_USEC_LEN+1];
  1695. format_iso_time_nospace_usec(tbuf, &circ->base_.timestamp_created);
  1696. smartlist_add_asprintf(descparts, "TIME_CREATED=%s", tbuf);
  1697. }
  1698. rv = smartlist_join_strings(descparts, " ", 0, NULL);
  1699. SMARTLIST_FOREACH(descparts, char *, cp, tor_free(cp));
  1700. smartlist_free(descparts);
  1701. return rv;
  1702. }
  1703. /** Implementation helper for GETINFO: knows how to generate summaries of the
  1704. * current states of things we send events about. */
  1705. static int
  1706. getinfo_helper_events(control_connection_t *control_conn,
  1707. const char *question, char **answer,
  1708. const char **errmsg)
  1709. {
  1710. (void) control_conn;
  1711. if (!strcmp(question, "circuit-status")) {
  1712. smartlist_t *status = smartlist_new();
  1713. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ_) {
  1714. origin_circuit_t *circ;
  1715. char *circdesc;
  1716. const char *state;
  1717. if (! CIRCUIT_IS_ORIGIN(circ_) || circ_->marked_for_close)
  1718. continue;
  1719. circ = TO_ORIGIN_CIRCUIT(circ_);
  1720. if (circ->base_.state == CIRCUIT_STATE_OPEN)
  1721. state = "BUILT";
  1722. else if (circ->cpath)
  1723. state = "EXTENDED";
  1724. else
  1725. state = "LAUNCHED";
  1726. circdesc = circuit_describe_status_for_controller(circ);
  1727. smartlist_add_asprintf(status, "%lu %s%s%s",
  1728. (unsigned long)circ->global_identifier,
  1729. state, *circdesc ? " " : "", circdesc);
  1730. tor_free(circdesc);
  1731. }
  1732. SMARTLIST_FOREACH_END(circ_);
  1733. *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
  1734. SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
  1735. smartlist_free(status);
  1736. } else if (!strcmp(question, "stream-status")) {
  1737. smartlist_t *conns = get_connection_array();
  1738. smartlist_t *status = smartlist_new();
  1739. char buf[256];
  1740. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
  1741. const char *state;
  1742. entry_connection_t *conn;
  1743. circuit_t *circ;
  1744. origin_circuit_t *origin_circ = NULL;
  1745. if (base_conn->type != CONN_TYPE_AP ||
  1746. base_conn->marked_for_close ||
  1747. base_conn->state == AP_CONN_STATE_SOCKS_WAIT ||
  1748. base_conn->state == AP_CONN_STATE_NATD_WAIT)
  1749. continue;
  1750. conn = TO_ENTRY_CONN(base_conn);
  1751. switch (base_conn->state)
  1752. {
  1753. case AP_CONN_STATE_CONTROLLER_WAIT:
  1754. case AP_CONN_STATE_CIRCUIT_WAIT:
  1755. if (conn->socks_request &&
  1756. SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command))
  1757. state = "NEWRESOLVE";
  1758. else
  1759. state = "NEW";
  1760. break;
  1761. case AP_CONN_STATE_RENDDESC_WAIT:
  1762. case AP_CONN_STATE_CONNECT_WAIT:
  1763. state = "SENTCONNECT"; break;
  1764. case AP_CONN_STATE_RESOLVE_WAIT:
  1765. state = "SENTRESOLVE"; break;
  1766. case AP_CONN_STATE_OPEN:
  1767. state = "SUCCEEDED"; break;
  1768. default:
  1769. log_warn(LD_BUG, "Asked for stream in unknown state %d",
  1770. base_conn->state);
  1771. continue;
  1772. }
  1773. circ = circuit_get_by_edge_conn(ENTRY_TO_EDGE_CONN(conn));
  1774. if (circ && CIRCUIT_IS_ORIGIN(circ))
  1775. origin_circ = TO_ORIGIN_CIRCUIT(circ);
  1776. write_stream_target_to_buf(conn, buf, sizeof(buf));
  1777. smartlist_add_asprintf(status, "%lu %s %lu %s",
  1778. (unsigned long) base_conn->global_identifier,state,
  1779. origin_circ?
  1780. (unsigned long)origin_circ->global_identifier : 0ul,
  1781. buf);
  1782. } SMARTLIST_FOREACH_END(base_conn);
  1783. *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
  1784. SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
  1785. smartlist_free(status);
  1786. } else if (!strcmp(question, "orconn-status")) {
  1787. smartlist_t *conns = get_connection_array();
  1788. smartlist_t *status = smartlist_new();
  1789. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
  1790. const char *state;
  1791. char name[128];
  1792. or_connection_t *conn;
  1793. if (base_conn->type != CONN_TYPE_OR || base_conn->marked_for_close)
  1794. continue;
  1795. conn = TO_OR_CONN(base_conn);
  1796. if (conn->base_.state == OR_CONN_STATE_OPEN)
  1797. state = "CONNECTED";
  1798. else if (conn->nickname)
  1799. state = "LAUNCHED";
  1800. else
  1801. state = "NEW";
  1802. orconn_target_get_name(name, sizeof(name), conn);
  1803. smartlist_add_asprintf(status, "%s %s", name, state);
  1804. } SMARTLIST_FOREACH_END(base_conn);
  1805. *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
  1806. SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
  1807. smartlist_free(status);
  1808. } else if (!strcmpstart(question, "address-mappings/")) {
  1809. time_t min_e, max_e;
  1810. smartlist_t *mappings;
  1811. question += strlen("address-mappings/");
  1812. if (!strcmp(question, "all")) {
  1813. min_e = 0; max_e = TIME_MAX;
  1814. } else if (!strcmp(question, "cache")) {
  1815. min_e = 2; max_e = TIME_MAX;
  1816. } else if (!strcmp(question, "config")) {
  1817. min_e = 0; max_e = 0;
  1818. } else if (!strcmp(question, "control")) {
  1819. min_e = 1; max_e = 1;
  1820. } else {
  1821. return 0;
  1822. }
  1823. mappings = smartlist_new();
  1824. addressmap_get_mappings(mappings, min_e, max_e, 1);
  1825. *answer = smartlist_join_strings(mappings, "\r\n", 0, NULL);
  1826. SMARTLIST_FOREACH(mappings, char *, cp, tor_free(cp));
  1827. smartlist_free(mappings);
  1828. } else if (!strcmpstart(question, "status/")) {
  1829. /* Note that status/ is not a catch-all for events; there's only supposed
  1830. * to be a status GETINFO if there's a corresponding STATUS event. */
  1831. if (!strcmp(question, "status/circuit-established")) {
  1832. *answer = tor_strdup(can_complete_circuit ? "1" : "0");
  1833. } else if (!strcmp(question, "status/enough-dir-info")) {
  1834. *answer = tor_strdup(router_have_minimum_dir_info() ? "1" : "0");
  1835. } else if (!strcmp(question, "status/good-server-descriptor") ||
  1836. !strcmp(question, "status/accepted-server-descriptor")) {
  1837. /* They're equivalent for now, until we can figure out how to make
  1838. * good-server-descriptor be what we want. See comment in
  1839. * control-spec.txt. */
  1840. *answer = tor_strdup(directories_have_accepted_server_descriptor()
  1841. ? "1" : "0");
  1842. } else if (!strcmp(question, "status/reachability-succeeded/or")) {
  1843. *answer = tor_strdup(check_whether_orport_reachable() ? "1" : "0");
  1844. } else if (!strcmp(question, "status/reachability-succeeded/dir")) {
  1845. *answer = tor_strdup(check_whether_dirport_reachable() ? "1" : "0");
  1846. } else if (!strcmp(question, "status/reachability-succeeded")) {
  1847. tor_asprintf(answer, "OR=%d DIR=%d",
  1848. check_whether_orport_reachable() ? 1 : 0,
  1849. check_whether_dirport_reachable() ? 1 : 0);
  1850. } else if (!strcmp(question, "status/bootstrap-phase")) {
  1851. *answer = tor_strdup(last_sent_bootstrap_message);
  1852. } else if (!strcmpstart(question, "status/version/")) {
  1853. int is_server = server_mode(get_options());
  1854. networkstatus_t *c = networkstatus_get_latest_consensus();
  1855. version_status_t status;
  1856. const char *recommended;
  1857. if (c) {
  1858. recommended = is_server ? c->server_versions : c->client_versions;
  1859. status = tor_version_is_obsolete(VERSION, recommended);
  1860. } else {
  1861. recommended = "?";
  1862. status = VS_UNKNOWN;
  1863. }
  1864. if (!strcmp(question, "status/version/recommended")) {
  1865. *answer = tor_strdup(recommended);
  1866. return 0;
  1867. }
  1868. if (!strcmp(question, "status/version/current")) {
  1869. switch (status)
  1870. {
  1871. case VS_RECOMMENDED: *answer = tor_strdup("recommended"); break;
  1872. case VS_OLD: *answer = tor_strdup("obsolete"); break;
  1873. case VS_NEW: *answer = tor_strdup("new"); break;
  1874. case VS_NEW_IN_SERIES: *answer = tor_strdup("new in series"); break;
  1875. case VS_UNRECOMMENDED: *answer = tor_strdup("unrecommended"); break;
  1876. case VS_EMPTY: *answer = tor_strdup("none recommended"); break;
  1877. case VS_UNKNOWN: *answer = tor_strdup("unknown"); break;
  1878. default: tor_fragile_assert();
  1879. }
  1880. } else if (!strcmp(question, "status/version/num-versioning") ||
  1881. !strcmp(question, "status/version/num-concurring")) {
  1882. tor_asprintf(answer, "%d", get_n_authorities(V3_DIRINFO));
  1883. log_warn(LD_GENERAL, "%s is deprecated; it no longer gives useful "
  1884. "information", question);
  1885. }
  1886. } else if (!strcmp(question, "status/clients-seen")) {
  1887. char *bridge_stats = geoip_get_bridge_stats_controller(time(NULL));
  1888. if (!bridge_stats) {
  1889. *errmsg = "No bridge-client stats available";
  1890. return -1;
  1891. }
  1892. *answer = bridge_stats;
  1893. } else {
  1894. return 0;
  1895. }
  1896. }
  1897. return 0;
  1898. }
  1899. /** Callback function for GETINFO: on a given control connection, try to
  1900. * answer the question <b>q</b> and store the newly-allocated answer in
  1901. * *<b>a</b>. If an internal error occurs, return -1 and optionally set
  1902. * *<b>error_out</b> to point to an error message to be delivered to the
  1903. * controller. On success, _or if the key is not recognized_, return 0. Do not
  1904. * set <b>a</b> if the key is not recognized.
  1905. */
  1906. typedef int (*getinfo_helper_t)(control_connection_t *,
  1907. const char *q, char **a,
  1908. const char **error_out);
  1909. /** A single item for the GETINFO question-to-answer-function table. */
  1910. typedef struct getinfo_item_t {
  1911. const char *varname; /**< The value (or prefix) of the question. */
  1912. getinfo_helper_t fn; /**< The function that knows the answer: NULL if
  1913. * this entry is documentation-only. */
  1914. const char *desc; /**< Description of the variable. */
  1915. int is_prefix; /** Must varname match exactly, or must it be a prefix? */
  1916. } getinfo_item_t;
  1917. #define ITEM(name, fn, desc) { name, getinfo_helper_##fn, desc, 0 }
  1918. #define PREFIX(name, fn, desc) { name, getinfo_helper_##fn, desc, 1 }
  1919. #define DOC(name, desc) { name, NULL, desc, 0 }
  1920. /** Table mapping questions accepted by GETINFO to the functions that know how
  1921. * to answer them. */
  1922. static const getinfo_item_t getinfo_items[] = {
  1923. ITEM("version", misc, "The current version of Tor."),
  1924. ITEM("config-file", misc, "Current location of the \"torrc\" file."),
  1925. ITEM("config-defaults-file", misc, "Current location of the defaults file."),
  1926. ITEM("config-text", misc,
  1927. "Return the string that would be written by a saveconf command."),
  1928. ITEM("accounting/bytes", accounting,
  1929. "Number of bytes read/written so far in the accounting interval."),
  1930. ITEM("accounting/bytes-left", accounting,
  1931. "Number of bytes left to write/read so far in the accounting interval."),
  1932. ITEM("accounting/enabled", accounting, "Is accounting currently enabled?"),
  1933. ITEM("accounting/hibernating", accounting, "Are we hibernating or awake?"),
  1934. ITEM("accounting/interval-start", accounting,
  1935. "Time when the accounting period starts."),
  1936. ITEM("accounting/interval-end", accounting,
  1937. "Time when the accounting period ends."),
  1938. ITEM("accounting/interval-wake", accounting,
  1939. "Time to wake up in this accounting period."),
  1940. ITEM("helper-nodes", entry_guards, NULL), /* deprecated */
  1941. ITEM("entry-guards", entry_guards,
  1942. "Which nodes are we using as entry guards?"),
  1943. ITEM("fingerprint", misc, NULL),
  1944. PREFIX("config/", config, "Current configuration values."),
  1945. DOC("config/names",
  1946. "List of configuration options, types, and documentation."),
  1947. DOC("config/defaults",
  1948. "List of default values for configuration options. "
  1949. "See also config/names"),
  1950. ITEM("info/names", misc,
  1951. "List of GETINFO options, types, and documentation."),
  1952. ITEM("events/names", misc,
  1953. "Events that the controller can ask for with SETEVENTS."),
  1954. ITEM("signal/names", misc, "Signal names recognized by the SIGNAL command"),
  1955. ITEM("features/names", misc, "What arguments can USEFEATURE take?"),
  1956. PREFIX("desc/id/", dir, "Router descriptors by ID."),
  1957. PREFIX("desc/name/", dir, "Router descriptors by nickname."),
  1958. ITEM("desc/all-recent", dir,
  1959. "All non-expired, non-superseded router descriptors."),
  1960. ITEM("desc/all-recent-extrainfo-hack", dir, NULL), /* Hack. */
  1961. PREFIX("md/id/", dir, "Microdescriptors by ID"),
  1962. PREFIX("md/name/", dir, "Microdescriptors by name"),
  1963. PREFIX("extra-info/digest/", dir, "Extra-info documents by digest."),
  1964. PREFIX("net/listeners/", listeners, "Bound addresses by type"),
  1965. ITEM("ns/all", networkstatus,
  1966. "Brief summary of router status (v2 directory format)"),
  1967. PREFIX("ns/id/", networkstatus,
  1968. "Brief summary of router status by ID (v2 directory format)."),
  1969. PREFIX("ns/name/", networkstatus,
  1970. "Brief summary of router status by nickname (v2 directory format)."),
  1971. PREFIX("ns/purpose/", networkstatus,
  1972. "Brief summary of router status by purpose (v2 directory format)."),
  1973. ITEM("network-status", dir,
  1974. "Brief summary of router status (v1 directory format)"),
  1975. ITEM("circuit-status", events, "List of current circuits originating here."),
  1976. ITEM("stream-status", events,"List of current streams."),
  1977. ITEM("orconn-status", events, "A list of current OR connections."),
  1978. ITEM("dormant", misc,
  1979. "Is Tor dormant (not building circuits because it's idle)?"),
  1980. PREFIX("address-mappings/", events, NULL),
  1981. DOC("address-mappings/all", "Current address mappings."),
  1982. DOC("address-mappings/cache", "Current cached DNS replies."),
  1983. DOC("address-mappings/config",
  1984. "Current address mappings from configuration."),
  1985. DOC("address-mappings/control", "Current address mappings from controller."),
  1986. PREFIX("status/", events, NULL),
  1987. DOC("status/circuit-established",
  1988. "Whether we think client functionality is working."),
  1989. DOC("status/enough-dir-info",
  1990. "Whether we have enough up-to-date directory information to build "
  1991. "circuits."),
  1992. DOC("status/bootstrap-phase",
  1993. "The last bootstrap phase status event that Tor sent."),
  1994. DOC("status/clients-seen",
  1995. "Breakdown of client countries seen by a bridge."),
  1996. DOC("status/version/recommended", "List of currently recommended versions."),
  1997. DOC("status/version/current", "Status of the current version."),
  1998. DOC("status/version/num-versioning", "Number of versioning authorities."),
  1999. DOC("status/version/num-concurring",
  2000. "Number of versioning authorities agreeing on the status of the "
  2001. "current version"),
  2002. ITEM("address", misc, "IP address of this Tor host, if we can guess it."),
  2003. ITEM("traffic/read", misc,"Bytes read since the process was started."),
  2004. ITEM("traffic/written", misc,
  2005. "Bytes written since the process was started."),
  2006. ITEM("process/pid", misc, "Process id belonging to the main tor process."),
  2007. ITEM("process/uid", misc, "User id running the tor process."),
  2008. ITEM("process/user", misc,
  2009. "Username under which the tor process is running."),
  2010. ITEM("process/descriptor-limit", misc, "File descriptor limit."),
  2011. ITEM("limits/max-mem-in-queues", misc, "Actual limit on memory in queues"),
  2012. ITEM("dir-usage", misc, "Breakdown of bytes transferred over DirPort."),
  2013. PREFIX("desc-annotations/id/", dir, "Router annotations by hexdigest."),
  2014. PREFIX("dir/server/", dir,"Router descriptors as retrieved from a DirPort."),
  2015. PREFIX("dir/status/", dir,
  2016. "v2 networkstatus docs as retrieved from a DirPort."),
  2017. ITEM("dir/status-vote/current/consensus", dir,
  2018. "v3 Networkstatus consensus as retrieved from a DirPort."),
  2019. ITEM("exit-policy/default", policies,
  2020. "The default value appended to the configured exit policy."),
  2021. ITEM("exit-policy/full", policies, "The entire exit policy of onion router"),
  2022. ITEM("exit-policy/ipv4", policies, "IPv4 parts of exit policy"),
  2023. ITEM("exit-policy/ipv6", policies, "IPv6 parts of exit policy"),
  2024. PREFIX("ip-to-country/", geoip, "Perform a GEOIP lookup"),
  2025. { NULL, NULL, NULL, 0 }
  2026. };
  2027. /** Allocate and return a list of recognized GETINFO options. */
  2028. static char *
  2029. list_getinfo_options(void)
  2030. {
  2031. int i;
  2032. smartlist_t *lines = smartlist_new();
  2033. char *ans;
  2034. for (i = 0; getinfo_items[i].varname; ++i) {
  2035. if (!getinfo_items[i].desc)
  2036. continue;
  2037. smartlist_add_asprintf(lines, "%s%s -- %s\n",
  2038. getinfo_items[i].varname,
  2039. getinfo_items[i].is_prefix ? "*" : "",
  2040. getinfo_items[i].desc);
  2041. }
  2042. smartlist_sort_strings(lines);
  2043. ans = smartlist_join_strings(lines, "", 0, NULL);
  2044. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  2045. smartlist_free(lines);
  2046. return ans;
  2047. }
  2048. /** Lookup the 'getinfo' entry <b>question</b>, and return
  2049. * the answer in <b>*answer</b> (or NULL if key not recognized).
  2050. * Return 0 if success or unrecognized, or -1 if recognized but
  2051. * internal error. */
  2052. static int
  2053. handle_getinfo_helper(control_connection_t *control_conn,
  2054. const char *question, char **answer,
  2055. const char **err_out)
  2056. {
  2057. int i;
  2058. *answer = NULL; /* unrecognized key by default */
  2059. for (i = 0; getinfo_items[i].varname; ++i) {
  2060. int match;
  2061. if (getinfo_items[i].is_prefix)
  2062. match = !strcmpstart(question, getinfo_items[i].varname);
  2063. else
  2064. match = !strcmp(question, getinfo_items[i].varname);
  2065. if (match) {
  2066. tor_assert(getinfo_items[i].fn);
  2067. return getinfo_items[i].fn(control_conn, question, answer, err_out);
  2068. }
  2069. }
  2070. return 0; /* unrecognized */
  2071. }
  2072. /** Called when we receive a GETINFO command. Try to fetch all requested
  2073. * information, and reply with information or error message. */
  2074. static int
  2075. handle_control_getinfo(control_connection_t *conn, uint32_t len,
  2076. const char *body)
  2077. {
  2078. smartlist_t *questions = smartlist_new();
  2079. smartlist_t *answers = smartlist_new();
  2080. smartlist_t *unrecognized = smartlist_new();
  2081. char *msg = NULL, *ans = NULL;
  2082. int i;
  2083. (void) len; /* body is NUL-terminated, so it's safe to ignore the length. */
  2084. smartlist_split_string(questions, body, " ",
  2085. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2086. SMARTLIST_FOREACH_BEGIN(questions, const char *, q) {
  2087. const char *errmsg = NULL;
  2088. if (handle_getinfo_helper(conn, q, &ans, &errmsg) < 0) {
  2089. if (!errmsg)
  2090. errmsg = "Internal error";
  2091. connection_printf_to_buf(conn, "551 %s\r\n", errmsg);
  2092. goto done;
  2093. }
  2094. if (!ans) {
  2095. smartlist_add(unrecognized, (char*)q);
  2096. } else {
  2097. smartlist_add(answers, tor_strdup(q));
  2098. smartlist_add(answers, ans);
  2099. }
  2100. } SMARTLIST_FOREACH_END(q);
  2101. if (smartlist_len(unrecognized)) {
  2102. for (i=0; i < smartlist_len(unrecognized)-1; ++i)
  2103. connection_printf_to_buf(conn,
  2104. "552-Unrecognized key \"%s\"\r\n",
  2105. (char*)smartlist_get(unrecognized, i));
  2106. connection_printf_to_buf(conn,
  2107. "552 Unrecognized key \"%s\"\r\n",
  2108. (char*)smartlist_get(unrecognized, i));
  2109. goto done;
  2110. }
  2111. for (i = 0; i < smartlist_len(answers); i += 2) {
  2112. char *k = smartlist_get(answers, i);
  2113. char *v = smartlist_get(answers, i+1);
  2114. if (!strchr(v, '\n') && !strchr(v, '\r')) {
  2115. connection_printf_to_buf(conn, "250-%s=", k);
  2116. connection_write_str_to_buf(v, conn);
  2117. connection_write_str_to_buf("\r\n", conn);
  2118. } else {
  2119. char *esc = NULL;
  2120. size_t esc_len;
  2121. esc_len = write_escaped_data(v, strlen(v), &esc);
  2122. connection_printf_to_buf(conn, "250+%s=\r\n", k);
  2123. connection_write_to_buf(esc, esc_len, TO_CONN(conn));
  2124. tor_free(esc);
  2125. }
  2126. }
  2127. connection_write_str_to_buf("250 OK\r\n", conn);
  2128. done:
  2129. SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
  2130. smartlist_free(answers);
  2131. SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
  2132. smartlist_free(questions);
  2133. smartlist_free(unrecognized);
  2134. tor_free(msg);
  2135. return 0;
  2136. }
  2137. /** Given a string, convert it to a circuit purpose. */
  2138. static uint8_t
  2139. circuit_purpose_from_string(const char *string)
  2140. {
  2141. if (!strcasecmpstart(string, "purpose="))
  2142. string += strlen("purpose=");
  2143. if (!strcasecmp(string, "general"))
  2144. return CIRCUIT_PURPOSE_C_GENERAL;
  2145. else if (!strcasecmp(string, "controller"))
  2146. return CIRCUIT_PURPOSE_CONTROLLER;
  2147. else
  2148. return CIRCUIT_PURPOSE_UNKNOWN;
  2149. }
  2150. /** Return a newly allocated smartlist containing the arguments to the command
  2151. * waiting in <b>body</b>. If there are fewer than <b>min_args</b> arguments,
  2152. * or if <b>max_args</b> is nonnegative and there are more than
  2153. * <b>max_args</b> arguments, send a 512 error to the controller, using
  2154. * <b>command</b> as the command name in the error message. */
  2155. static smartlist_t *
  2156. getargs_helper(const char *command, control_connection_t *conn,
  2157. const char *body, int min_args, int max_args)
  2158. {
  2159. smartlist_t *args = smartlist_new();
  2160. smartlist_split_string(args, body, " ",
  2161. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2162. if (smartlist_len(args) < min_args) {
  2163. connection_printf_to_buf(conn, "512 Missing argument to %s\r\n",command);
  2164. goto err;
  2165. } else if (max_args >= 0 && smartlist_len(args) > max_args) {
  2166. connection_printf_to_buf(conn, "512 Too many arguments to %s\r\n",command);
  2167. goto err;
  2168. }
  2169. return args;
  2170. err:
  2171. SMARTLIST_FOREACH(args, char *, s, tor_free(s));
  2172. smartlist_free(args);
  2173. return NULL;
  2174. }
  2175. /** Helper. Return the first element of <b>sl</b> at index <b>start_at</b> or
  2176. * higher that starts with <b>prefix</b>, case-insensitive. Return NULL if no
  2177. * such element exists. */
  2178. static const char *
  2179. find_element_starting_with(smartlist_t *sl, int start_at, const char *prefix)
  2180. {
  2181. int i;
  2182. for (i = start_at; i < smartlist_len(sl); ++i) {
  2183. const char *elt = smartlist_get(sl, i);
  2184. if (!strcasecmpstart(elt, prefix))
  2185. return elt;
  2186. }
  2187. return NULL;
  2188. }
  2189. /** Helper. Return true iff s is an argument that we should treat as a
  2190. * key-value pair. */
  2191. static int
  2192. is_keyval_pair(const char *s)
  2193. {
  2194. /* An argument is a key-value pair if it has an =, and it isn't of the form
  2195. * $fingeprint=name */
  2196. return strchr(s, '=') && s[0] != '$';
  2197. }
  2198. /** Called when we get an EXTENDCIRCUIT message. Try to extend the listed
  2199. * circuit, and report success or failure. */
  2200. static int
  2201. handle_control_extendcircuit(control_connection_t *conn, uint32_t len,
  2202. const char *body)
  2203. {
  2204. smartlist_t *router_nicknames=NULL, *nodes=NULL;
  2205. origin_circuit_t *circ = NULL;
  2206. int zero_circ;
  2207. uint8_t intended_purpose = CIRCUIT_PURPOSE_C_GENERAL;
  2208. smartlist_t *args;
  2209. (void) len;
  2210. router_nicknames = smartlist_new();
  2211. args = getargs_helper("EXTENDCIRCUIT", conn, body, 1, -1);
  2212. if (!args)
  2213. goto done;
  2214. zero_circ = !strcmp("0", (char*)smartlist_get(args,0));
  2215. if (zero_circ) {
  2216. const char *purp = find_element_starting_with(args, 1, "PURPOSE=");
  2217. if (purp) {
  2218. intended_purpose = circuit_purpose_from_string(purp);
  2219. if (intended_purpose == CIRCUIT_PURPOSE_UNKNOWN) {
  2220. connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n", purp);
  2221. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2222. smartlist_free(args);
  2223. goto done;
  2224. }
  2225. }
  2226. if ((smartlist_len(args) == 1) ||
  2227. (smartlist_len(args) >= 2 && is_keyval_pair(smartlist_get(args, 1)))) {
  2228. // "EXTENDCIRCUIT 0" || EXTENDCIRCUIT 0 foo=bar"
  2229. circ = circuit_launch(intended_purpose, CIRCLAUNCH_NEED_CAPACITY);
  2230. if (!circ) {
  2231. connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
  2232. } else {
  2233. connection_printf_to_buf(conn, "250 EXTENDED %lu\r\n",
  2234. (unsigned long)circ->global_identifier);
  2235. }
  2236. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2237. smartlist_free(args);
  2238. goto done;
  2239. }
  2240. // "EXTENDCIRCUIT 0 router1,router2" ||
  2241. // "EXTENDCIRCUIT 0 router1,router2 PURPOSE=foo"
  2242. }
  2243. if (!zero_circ && !(circ = get_circ(smartlist_get(args,0)))) {
  2244. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  2245. (char*)smartlist_get(args, 0));
  2246. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2247. smartlist_free(args);
  2248. goto done;
  2249. }
  2250. smartlist_split_string(router_nicknames, smartlist_get(args,1), ",", 0, 0);
  2251. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2252. smartlist_free(args);
  2253. nodes = smartlist_new();
  2254. SMARTLIST_FOREACH_BEGIN(router_nicknames, const char *, n) {
  2255. const node_t *node = node_get_by_nickname(n, 1);
  2256. if (!node) {
  2257. connection_printf_to_buf(conn, "552 No such router \"%s\"\r\n", n);
  2258. goto done;
  2259. }
  2260. if (!node_has_descriptor(node)) {
  2261. connection_printf_to_buf(conn, "552 No descriptor for \"%s\"\r\n", n);
  2262. goto done;
  2263. }
  2264. smartlist_add(nodes, (void*)node);
  2265. } SMARTLIST_FOREACH_END(n);
  2266. if (!smartlist_len(nodes)) {
  2267. connection_write_str_to_buf("512 No router names provided\r\n", conn);
  2268. goto done;
  2269. }
  2270. if (zero_circ) {
  2271. /* start a new circuit */
  2272. circ = origin_circuit_init(intended_purpose, 0);
  2273. }
  2274. /* now circ refers to something that is ready to be extended */
  2275. SMARTLIST_FOREACH(nodes, const node_t *, node,
  2276. {
  2277. extend_info_t *info = extend_info_from_node(node, 0);
  2278. tor_assert(info); /* True, since node_has_descriptor(node) == true */
  2279. circuit_append_new_exit(circ, info);
  2280. extend_info_free(info);
  2281. });
  2282. /* now that we've populated the cpath, start extending */
  2283. if (zero_circ) {
  2284. int err_reason = 0;
  2285. if ((err_reason = circuit_handle_first_hop(circ)) < 0) {
  2286. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  2287. connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
  2288. goto done;
  2289. }
  2290. } else {
  2291. if (circ->base_.state == CIRCUIT_STATE_OPEN) {
  2292. int err_reason = 0;
  2293. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
  2294. if ((err_reason = circuit_send_next_onion_skin(circ)) < 0) {
  2295. log_info(LD_CONTROL,
  2296. "send_next_onion_skin failed; circuit marked for closing.");
  2297. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  2298. connection_write_str_to_buf("551 Couldn't send onion skin\r\n", conn);
  2299. goto done;
  2300. }
  2301. }
  2302. }
  2303. connection_printf_to_buf(conn, "250 EXTENDED %lu\r\n",
  2304. (unsigned long)circ->global_identifier);
  2305. if (zero_circ) /* send a 'launched' event, for completeness */
  2306. control_event_circuit_status(circ, CIRC_EVENT_LAUNCHED, 0);
  2307. done:
  2308. SMARTLIST_FOREACH(router_nicknames, char *, n, tor_free(n));
  2309. smartlist_free(router_nicknames);
  2310. smartlist_free(nodes);
  2311. return 0;
  2312. }
  2313. /** Called when we get a SETCIRCUITPURPOSE message. If we can find the
  2314. * circuit and it's a valid purpose, change it. */
  2315. static int
  2316. handle_control_setcircuitpurpose(control_connection_t *conn,
  2317. uint32_t len, const char *body)
  2318. {
  2319. origin_circuit_t *circ = NULL;
  2320. uint8_t new_purpose;
  2321. smartlist_t *args;
  2322. (void) len; /* body is NUL-terminated, so it's safe to ignore the length. */
  2323. args = getargs_helper("SETCIRCUITPURPOSE", conn, body, 2, -1);
  2324. if (!args)
  2325. goto done;
  2326. if (!(circ = get_circ(smartlist_get(args,0)))) {
  2327. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  2328. (char*)smartlist_get(args, 0));
  2329. goto done;
  2330. }
  2331. {
  2332. const char *purp = find_element_starting_with(args,1,"PURPOSE=");
  2333. if (!purp) {
  2334. connection_write_str_to_buf("552 No purpose given\r\n", conn);
  2335. goto done;
  2336. }
  2337. new_purpose = circuit_purpose_from_string(purp);
  2338. if (new_purpose == CIRCUIT_PURPOSE_UNKNOWN) {
  2339. connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n", purp);
  2340. goto done;
  2341. }
  2342. }
  2343. circuit_change_purpose(TO_CIRCUIT(circ), new_purpose);
  2344. connection_write_str_to_buf("250 OK\r\n", conn);
  2345. done:
  2346. if (args) {
  2347. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2348. smartlist_free(args);
  2349. }
  2350. return 0;
  2351. }
  2352. /** Called when we get an ATTACHSTREAM message. Try to attach the requested
  2353. * stream, and report success or failure. */
  2354. static int
  2355. handle_control_attachstream(control_connection_t *conn, uint32_t len,
  2356. const char *body)
  2357. {
  2358. entry_connection_t *ap_conn = NULL;
  2359. origin_circuit_t *circ = NULL;
  2360. int zero_circ;
  2361. smartlist_t *args;
  2362. crypt_path_t *cpath=NULL;
  2363. int hop=0, hop_line_ok=1;
  2364. (void) len;
  2365. args = getargs_helper("ATTACHSTREAM", conn, body, 2, -1);
  2366. if (!args)
  2367. return 0;
  2368. zero_circ = !strcmp("0", (char*)smartlist_get(args,1));
  2369. if (!(ap_conn = get_stream(smartlist_get(args, 0)))) {
  2370. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  2371. (char*)smartlist_get(args, 0));
  2372. } else if (!zero_circ && !(circ = get_circ(smartlist_get(args, 1)))) {
  2373. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  2374. (char*)smartlist_get(args, 1));
  2375. } else if (circ) {
  2376. const char *hopstring = find_element_starting_with(args,2,"HOP=");
  2377. if (hopstring) {
  2378. hopstring += strlen("HOP=");
  2379. hop = (int) tor_parse_ulong(hopstring, 10, 0, INT_MAX,
  2380. &hop_line_ok, NULL);
  2381. if (!hop_line_ok) { /* broken hop line */
  2382. connection_printf_to_buf(conn, "552 Bad value hop=%s\r\n", hopstring);
  2383. }
  2384. }
  2385. }
  2386. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2387. smartlist_free(args);
  2388. if (!ap_conn || (!zero_circ && !circ) || !hop_line_ok)
  2389. return 0;
  2390. if (ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONTROLLER_WAIT &&
  2391. ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONNECT_WAIT &&
  2392. ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_RESOLVE_WAIT) {
  2393. connection_write_str_to_buf(
  2394. "555 Connection is not managed by controller.\r\n",
  2395. conn);
  2396. return 0;
  2397. }
  2398. /* Do we need to detach it first? */
  2399. if (ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONTROLLER_WAIT) {
  2400. edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
  2401. circuit_t *tmpcirc = circuit_get_by_edge_conn(edge_conn);
  2402. connection_edge_end(edge_conn, END_STREAM_REASON_TIMEOUT);
  2403. /* Un-mark it as ending, since we're going to reuse it. */
  2404. edge_conn->edge_has_sent_end = 0;
  2405. edge_conn->end_reason = 0;
  2406. if (tmpcirc)
  2407. circuit_detach_stream(tmpcirc, edge_conn);
  2408. TO_CONN(edge_conn)->state = AP_CONN_STATE_CONTROLLER_WAIT;
  2409. }
  2410. if (circ && (circ->base_.state != CIRCUIT_STATE_OPEN)) {
  2411. connection_write_str_to_buf(
  2412. "551 Can't attach stream to non-open origin circuit\r\n",
  2413. conn);
  2414. return 0;
  2415. }
  2416. /* Is this a single hop circuit? */
  2417. if (circ && (circuit_get_cpath_len(circ)<2 || hop==1)) {
  2418. const node_t *node = NULL;
  2419. char *exit_digest = NULL;
  2420. if (circ->build_state &&
  2421. circ->build_state->chosen_exit &&
  2422. !tor_digest_is_zero(circ->build_state->chosen_exit->identity_digest)) {
  2423. exit_digest = circ->build_state->chosen_exit->identity_digest;
  2424. node = node_get_by_id(exit_digest);
  2425. }
  2426. /* Do both the client and relay allow one-hop exit circuits? */
  2427. if (!node ||
  2428. !node_allows_single_hop_exits(node) ||
  2429. !get_options()->AllowSingleHopCircuits) {
  2430. connection_write_str_to_buf(
  2431. "551 Can't attach stream to this one-hop circuit.\r\n", conn);
  2432. return 0;
  2433. }
  2434. tor_assert(exit_digest);
  2435. ap_conn->chosen_exit_name = tor_strdup(hex_str(exit_digest, DIGEST_LEN));
  2436. }
  2437. if (circ && hop>0) {
  2438. /* find this hop in the circuit, and set cpath */
  2439. cpath = circuit_get_cpath_hop(circ, hop);
  2440. if (!cpath) {
  2441. connection_printf_to_buf(conn,
  2442. "551 Circuit doesn't have %d hops.\r\n", hop);
  2443. return 0;
  2444. }
  2445. }
  2446. if (connection_ap_handshake_rewrite_and_attach(ap_conn, circ, cpath) < 0) {
  2447. connection_write_str_to_buf("551 Unable to attach stream\r\n", conn);
  2448. return 0;
  2449. }
  2450. send_control_done(conn);
  2451. return 0;
  2452. }
  2453. /** Called when we get a POSTDESCRIPTOR message. Try to learn the provided
  2454. * descriptor, and report success or failure. */
  2455. static int
  2456. handle_control_postdescriptor(control_connection_t *conn, uint32_t len,
  2457. const char *body)
  2458. {
  2459. char *desc;
  2460. const char *msg=NULL;
  2461. uint8_t purpose = ROUTER_PURPOSE_GENERAL;
  2462. int cache = 0; /* eventually, we may switch this to 1 */
  2463. char *cp = memchr(body, '\n', len);
  2464. smartlist_t *args = smartlist_new();
  2465. tor_assert(cp);
  2466. *cp++ = '\0';
  2467. smartlist_split_string(args, body, " ",
  2468. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2469. SMARTLIST_FOREACH_BEGIN(args, char *, option) {
  2470. if (!strcasecmpstart(option, "purpose=")) {
  2471. option += strlen("purpose=");
  2472. purpose = router_purpose_from_string(option);
  2473. if (purpose == ROUTER_PURPOSE_UNKNOWN) {
  2474. connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n",
  2475. option);
  2476. goto done;
  2477. }
  2478. } else if (!strcasecmpstart(option, "cache=")) {
  2479. option += strlen("cache=");
  2480. if (!strcasecmp(option, "no"))
  2481. cache = 0;
  2482. else if (!strcasecmp(option, "yes"))
  2483. cache = 1;
  2484. else {
  2485. connection_printf_to_buf(conn, "552 Unknown cache request \"%s\"\r\n",
  2486. option);
  2487. goto done;
  2488. }
  2489. } else { /* unrecognized argument? */
  2490. connection_printf_to_buf(conn,
  2491. "512 Unexpected argument \"%s\" to postdescriptor\r\n", option);
  2492. goto done;
  2493. }
  2494. } SMARTLIST_FOREACH_END(option);
  2495. read_escaped_data(cp, len-(cp-body), &desc);
  2496. switch (router_load_single_router(desc, purpose, cache, &msg)) {
  2497. case -1:
  2498. if (!msg) msg = "Could not parse descriptor";
  2499. connection_printf_to_buf(conn, "554 %s\r\n", msg);
  2500. break;
  2501. case 0:
  2502. if (!msg) msg = "Descriptor not added";
  2503. connection_printf_to_buf(conn, "251 %s\r\n",msg);
  2504. break;
  2505. case 1:
  2506. send_control_done(conn);
  2507. break;
  2508. }
  2509. tor_free(desc);
  2510. done:
  2511. SMARTLIST_FOREACH(args, char *, arg, tor_free(arg));
  2512. smartlist_free(args);
  2513. return 0;
  2514. }
  2515. /** Called when we receive a REDIRECTSTERAM command. Try to change the target
  2516. * address of the named AP stream, and report success or failure. */
  2517. static int
  2518. handle_control_redirectstream(control_connection_t *conn, uint32_t len,
  2519. const char *body)
  2520. {
  2521. entry_connection_t *ap_conn = NULL;
  2522. char *new_addr = NULL;
  2523. uint16_t new_port = 0;
  2524. smartlist_t *args;
  2525. (void) len;
  2526. args = getargs_helper("REDIRECTSTREAM", conn, body, 2, -1);
  2527. if (!args)
  2528. return 0;
  2529. if (!(ap_conn = get_stream(smartlist_get(args, 0)))
  2530. || !ap_conn->socks_request) {
  2531. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  2532. (char*)smartlist_get(args, 0));
  2533. } else {
  2534. int ok = 1;
  2535. if (smartlist_len(args) > 2) { /* they included a port too */
  2536. new_port = (uint16_t) tor_parse_ulong(smartlist_get(args, 2),
  2537. 10, 1, 65535, &ok, NULL);
  2538. }
  2539. if (!ok) {
  2540. connection_printf_to_buf(conn, "512 Cannot parse port \"%s\"\r\n",
  2541. (char*)smartlist_get(args, 2));
  2542. } else {
  2543. new_addr = tor_strdup(smartlist_get(args, 1));
  2544. }
  2545. }
  2546. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2547. smartlist_free(args);
  2548. if (!new_addr)
  2549. return 0;
  2550. strlcpy(ap_conn->socks_request->address, new_addr,
  2551. sizeof(ap_conn->socks_request->address));
  2552. if (new_port)
  2553. ap_conn->socks_request->port = new_port;
  2554. tor_free(new_addr);
  2555. send_control_done(conn);
  2556. return 0;
  2557. }
  2558. /** Called when we get a CLOSESTREAM command; try to close the named stream
  2559. * and report success or failure. */
  2560. static int
  2561. handle_control_closestream(control_connection_t *conn, uint32_t len,
  2562. const char *body)
  2563. {
  2564. entry_connection_t *ap_conn=NULL;
  2565. uint8_t reason=0;
  2566. smartlist_t *args;
  2567. int ok;
  2568. (void) len;
  2569. args = getargs_helper("CLOSESTREAM", conn, body, 2, -1);
  2570. if (!args)
  2571. return 0;
  2572. else if (!(ap_conn = get_stream(smartlist_get(args, 0))))
  2573. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  2574. (char*)smartlist_get(args, 0));
  2575. else {
  2576. reason = (uint8_t) tor_parse_ulong(smartlist_get(args,1), 10, 0, 255,
  2577. &ok, NULL);
  2578. if (!ok) {
  2579. connection_printf_to_buf(conn, "552 Unrecognized reason \"%s\"\r\n",
  2580. (char*)smartlist_get(args, 1));
  2581. ap_conn = NULL;
  2582. }
  2583. }
  2584. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2585. smartlist_free(args);
  2586. if (!ap_conn)
  2587. return 0;
  2588. connection_mark_unattached_ap(ap_conn, reason);
  2589. send_control_done(conn);
  2590. return 0;
  2591. }
  2592. /** Called when we get a CLOSECIRCUIT command; try to close the named circuit
  2593. * and report success or failure. */
  2594. static int
  2595. handle_control_closecircuit(control_connection_t *conn, uint32_t len,
  2596. const char *body)
  2597. {
  2598. origin_circuit_t *circ = NULL;
  2599. int safe = 0;
  2600. smartlist_t *args;
  2601. (void) len;
  2602. args = getargs_helper("CLOSECIRCUIT", conn, body, 1, -1);
  2603. if (!args)
  2604. return 0;
  2605. if (!(circ=get_circ(smartlist_get(args, 0))))
  2606. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  2607. (char*)smartlist_get(args, 0));
  2608. else {
  2609. int i;
  2610. for (i=1; i < smartlist_len(args); ++i) {
  2611. if (!strcasecmp(smartlist_get(args, i), "IfUnused"))
  2612. safe = 1;
  2613. else
  2614. log_info(LD_CONTROL, "Skipping unknown option %s",
  2615. (char*)smartlist_get(args,i));
  2616. }
  2617. }
  2618. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2619. smartlist_free(args);
  2620. if (!circ)
  2621. return 0;
  2622. if (!safe || !circ->p_streams) {
  2623. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_REQUESTED);
  2624. }
  2625. send_control_done(conn);
  2626. return 0;
  2627. }
  2628. /** Called when we get a RESOLVE command: start trying to resolve
  2629. * the listed addresses. */
  2630. static int
  2631. handle_control_resolve(control_connection_t *conn, uint32_t len,
  2632. const char *body)
  2633. {
  2634. smartlist_t *args, *failed;
  2635. int is_reverse = 0;
  2636. (void) len; /* body is nul-terminated; it's safe to ignore the length */
  2637. if (!(conn->event_mask & (((event_mask_t)1)<<EVENT_ADDRMAP))) {
  2638. log_warn(LD_CONTROL, "Controller asked us to resolve an address, but "
  2639. "isn't listening for ADDRMAP events. It probably won't see "
  2640. "the answer.");
  2641. }
  2642. args = smartlist_new();
  2643. smartlist_split_string(args, body, " ",
  2644. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2645. {
  2646. const char *modearg = find_element_starting_with(args, 0, "mode=");
  2647. if (modearg && !strcasecmp(modearg, "mode=reverse"))
  2648. is_reverse = 1;
  2649. }
  2650. failed = smartlist_new();
  2651. SMARTLIST_FOREACH(args, const char *, arg, {
  2652. if (!is_keyval_pair(arg)) {
  2653. if (dnsserv_launch_request(arg, is_reverse, conn)<0)
  2654. smartlist_add(failed, (char*)arg);
  2655. }
  2656. });
  2657. send_control_done(conn);
  2658. SMARTLIST_FOREACH(failed, const char *, arg, {
  2659. control_event_address_mapped(arg, arg, time(NULL),
  2660. "internal", 0);
  2661. });
  2662. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2663. smartlist_free(args);
  2664. smartlist_free(failed);
  2665. return 0;
  2666. }
  2667. /** Called when we get a PROTOCOLINFO command: send back a reply. */
  2668. static int
  2669. handle_control_protocolinfo(control_connection_t *conn, uint32_t len,
  2670. const char *body)
  2671. {
  2672. const char *bad_arg = NULL;
  2673. smartlist_t *args;
  2674. (void)len;
  2675. conn->have_sent_protocolinfo = 1;
  2676. args = smartlist_new();
  2677. smartlist_split_string(args, body, " ",
  2678. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2679. SMARTLIST_FOREACH(args, const char *, arg, {
  2680. int ok;
  2681. tor_parse_long(arg, 10, 0, LONG_MAX, &ok, NULL);
  2682. if (!ok) {
  2683. bad_arg = arg;
  2684. break;
  2685. }
  2686. });
  2687. if (bad_arg) {
  2688. connection_printf_to_buf(conn, "513 No such version %s\r\n",
  2689. escaped(bad_arg));
  2690. /* Don't tolerate bad arguments when not authenticated. */
  2691. if (!STATE_IS_OPEN(TO_CONN(conn)->state))
  2692. connection_mark_for_close(TO_CONN(conn));
  2693. goto done;
  2694. } else {
  2695. const or_options_t *options = get_options();
  2696. int cookies = options->CookieAuthentication;
  2697. char *cfile = get_controller_cookie_file_name();
  2698. char *abs_cfile;
  2699. char *esc_cfile;
  2700. char *methods;
  2701. abs_cfile = make_path_absolute(cfile);
  2702. esc_cfile = esc_for_log(abs_cfile);
  2703. {
  2704. int passwd = (options->HashedControlPassword != NULL ||
  2705. options->HashedControlSessionPassword != NULL);
  2706. smartlist_t *mlist = smartlist_new();
  2707. if (cookies) {
  2708. smartlist_add(mlist, (char*)"COOKIE");
  2709. smartlist_add(mlist, (char*)"SAFECOOKIE");
  2710. }
  2711. if (passwd)
  2712. smartlist_add(mlist, (char*)"HASHEDPASSWORD");
  2713. if (!cookies && !passwd)
  2714. smartlist_add(mlist, (char*)"NULL");
  2715. methods = smartlist_join_strings(mlist, ",", 0, NULL);
  2716. smartlist_free(mlist);
  2717. }
  2718. connection_printf_to_buf(conn,
  2719. "250-PROTOCOLINFO 1\r\n"
  2720. "250-AUTH METHODS=%s%s%s\r\n"
  2721. "250-VERSION Tor=%s\r\n"
  2722. "250 OK\r\n",
  2723. methods,
  2724. cookies?" COOKIEFILE=":"",
  2725. cookies?esc_cfile:"",
  2726. escaped(VERSION));
  2727. tor_free(methods);
  2728. tor_free(cfile);
  2729. tor_free(abs_cfile);
  2730. tor_free(esc_cfile);
  2731. }
  2732. done:
  2733. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2734. smartlist_free(args);
  2735. return 0;
  2736. }
  2737. /** Called when we get an AUTHCHALLENGE command. */
  2738. static int
  2739. handle_control_authchallenge(control_connection_t *conn, uint32_t len,
  2740. const char *body)
  2741. {
  2742. const char *cp = body;
  2743. char *client_nonce;
  2744. size_t client_nonce_len;
  2745. char server_hash[DIGEST256_LEN];
  2746. char server_hash_encoded[HEX_DIGEST256_LEN+1];
  2747. char server_nonce[SAFECOOKIE_SERVER_NONCE_LEN];
  2748. char server_nonce_encoded[(2*SAFECOOKIE_SERVER_NONCE_LEN) + 1];
  2749. cp += strspn(cp, " \t\n\r");
  2750. if (!strcasecmpstart(cp, "SAFECOOKIE")) {
  2751. cp += strlen("SAFECOOKIE");
  2752. } else {
  2753. connection_write_str_to_buf("513 AUTHCHALLENGE only supports SAFECOOKIE "
  2754. "authentication\r\n", conn);
  2755. connection_mark_for_close(TO_CONN(conn));
  2756. return -1;
  2757. }
  2758. if (!authentication_cookie_is_set) {
  2759. connection_write_str_to_buf("515 Cookie authentication is disabled\r\n",
  2760. conn);
  2761. connection_mark_for_close(TO_CONN(conn));
  2762. return -1;
  2763. }
  2764. cp += strspn(cp, " \t\n\r");
  2765. if (*cp == '"') {
  2766. const char *newcp =
  2767. decode_escaped_string(cp, len - (cp - body),
  2768. &client_nonce, &client_nonce_len);
  2769. if (newcp == NULL) {
  2770. connection_write_str_to_buf("513 Invalid quoted client nonce\r\n",
  2771. conn);
  2772. connection_mark_for_close(TO_CONN(conn));
  2773. return -1;
  2774. }
  2775. cp = newcp;
  2776. } else {
  2777. size_t client_nonce_encoded_len = strspn(cp, "0123456789ABCDEFabcdef");
  2778. client_nonce_len = client_nonce_encoded_len / 2;
  2779. client_nonce = tor_malloc_zero(client_nonce_len);
  2780. if (base16_decode(client_nonce, client_nonce_len,
  2781. cp, client_nonce_encoded_len) < 0) {
  2782. connection_write_str_to_buf("513 Invalid base16 client nonce\r\n",
  2783. conn);
  2784. connection_mark_for_close(TO_CONN(conn));
  2785. tor_free(client_nonce);
  2786. return -1;
  2787. }
  2788. cp += client_nonce_encoded_len;
  2789. }
  2790. cp += strspn(cp, " \t\n\r");
  2791. if (*cp != '\0' ||
  2792. cp != body + len) {
  2793. connection_write_str_to_buf("513 Junk at end of AUTHCHALLENGE command\r\n",
  2794. conn);
  2795. connection_mark_for_close(TO_CONN(conn));
  2796. tor_free(client_nonce);
  2797. return -1;
  2798. }
  2799. tor_assert(!crypto_rand(server_nonce, SAFECOOKIE_SERVER_NONCE_LEN));
  2800. /* Now compute and send the server-to-controller response, and the
  2801. * server's nonce. */
  2802. tor_assert(authentication_cookie != NULL);
  2803. {
  2804. size_t tmp_len = (AUTHENTICATION_COOKIE_LEN +
  2805. client_nonce_len +
  2806. SAFECOOKIE_SERVER_NONCE_LEN);
  2807. char *tmp = tor_malloc_zero(tmp_len);
  2808. char *client_hash = tor_malloc_zero(DIGEST256_LEN);
  2809. memcpy(tmp, authentication_cookie, AUTHENTICATION_COOKIE_LEN);
  2810. memcpy(tmp + AUTHENTICATION_COOKIE_LEN, client_nonce, client_nonce_len);
  2811. memcpy(tmp + AUTHENTICATION_COOKIE_LEN + client_nonce_len,
  2812. server_nonce, SAFECOOKIE_SERVER_NONCE_LEN);
  2813. crypto_hmac_sha256(server_hash,
  2814. SAFECOOKIE_SERVER_TO_CONTROLLER_CONSTANT,
  2815. strlen(SAFECOOKIE_SERVER_TO_CONTROLLER_CONSTANT),
  2816. tmp,
  2817. tmp_len);
  2818. crypto_hmac_sha256(client_hash,
  2819. SAFECOOKIE_CONTROLLER_TO_SERVER_CONSTANT,
  2820. strlen(SAFECOOKIE_CONTROLLER_TO_SERVER_CONSTANT),
  2821. tmp,
  2822. tmp_len);
  2823. conn->safecookie_client_hash = client_hash;
  2824. tor_free(tmp);
  2825. }
  2826. base16_encode(server_hash_encoded, sizeof(server_hash_encoded),
  2827. server_hash, sizeof(server_hash));
  2828. base16_encode(server_nonce_encoded, sizeof(server_nonce_encoded),
  2829. server_nonce, sizeof(server_nonce));
  2830. connection_printf_to_buf(conn,
  2831. "250 AUTHCHALLENGE SERVERHASH=%s "
  2832. "SERVERNONCE=%s\r\n",
  2833. server_hash_encoded,
  2834. server_nonce_encoded);
  2835. tor_free(client_nonce);
  2836. return 0;
  2837. }
  2838. /** Called when we get a USEFEATURE command: parse the feature list, and
  2839. * set up the control_connection's options properly. */
  2840. static int
  2841. handle_control_usefeature(control_connection_t *conn,
  2842. uint32_t len,
  2843. const char *body)
  2844. {
  2845. smartlist_t *args;
  2846. int bad = 0;
  2847. (void) len; /* body is nul-terminated; it's safe to ignore the length */
  2848. args = smartlist_new();
  2849. smartlist_split_string(args, body, " ",
  2850. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2851. SMARTLIST_FOREACH_BEGIN(args, const char *, arg) {
  2852. if (!strcasecmp(arg, "VERBOSE_NAMES"))
  2853. ;
  2854. else if (!strcasecmp(arg, "EXTENDED_EVENTS"))
  2855. ;
  2856. else {
  2857. connection_printf_to_buf(conn, "552 Unrecognized feature \"%s\"\r\n",
  2858. arg);
  2859. bad = 1;
  2860. break;
  2861. }
  2862. } SMARTLIST_FOREACH_END(arg);
  2863. if (!bad) {
  2864. send_control_done(conn);
  2865. }
  2866. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2867. smartlist_free(args);
  2868. return 0;
  2869. }
  2870. /** Implementation for the DROPGUARDS command. */
  2871. static int
  2872. handle_control_dropguards(control_connection_t *conn,
  2873. uint32_t len,
  2874. const char *body)
  2875. {
  2876. smartlist_t *args;
  2877. (void) len; /* body is nul-terminated; it's safe to ignore the length */
  2878. args = smartlist_new();
  2879. smartlist_split_string(args, body, " ",
  2880. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2881. if (smartlist_len(args)) {
  2882. connection_printf_to_buf(conn, "512 Too many arguments to DROPGUARDS\r\n");
  2883. } else {
  2884. remove_all_entry_guards();
  2885. send_control_done(conn);
  2886. }
  2887. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2888. smartlist_free(args);
  2889. return 0;
  2890. }
  2891. /** Called when <b>conn</b> has no more bytes left on its outbuf. */
  2892. int
  2893. connection_control_finished_flushing(control_connection_t *conn)
  2894. {
  2895. tor_assert(conn);
  2896. return 0;
  2897. }
  2898. /** Called when <b>conn</b> has gotten its socket closed. */
  2899. int
  2900. connection_control_reached_eof(control_connection_t *conn)
  2901. {
  2902. tor_assert(conn);
  2903. log_info(LD_CONTROL,"Control connection reached EOF. Closing.");
  2904. connection_mark_for_close(TO_CONN(conn));
  2905. return 0;
  2906. }
  2907. static void lost_owning_controller(const char *owner_type,
  2908. const char *loss_manner)
  2909. ATTR_NORETURN;
  2910. /** Shut down this Tor instance in the same way that SIGINT would, but
  2911. * with a log message appropriate for the loss of an owning controller. */
  2912. static void
  2913. lost_owning_controller(const char *owner_type, const char *loss_manner)
  2914. {
  2915. log_notice(LD_CONTROL, "Owning controller %s has %s -- exiting now.",
  2916. owner_type, loss_manner);
  2917. /* XXXX Perhaps this chunk of code should be a separate function,
  2918. * called here and by process_signal(SIGINT). */
  2919. tor_cleanup();
  2920. exit(0);
  2921. }
  2922. /** Called when <b>conn</b> is being freed. */
  2923. void
  2924. connection_control_closed(control_connection_t *conn)
  2925. {
  2926. tor_assert(conn);
  2927. conn->event_mask = 0;
  2928. control_update_global_event_mask();
  2929. if (conn->is_owning_control_connection) {
  2930. lost_owning_controller("connection", "closed");
  2931. }
  2932. }
  2933. /** Return true iff <b>cmd</b> is allowable (or at least forgivable) at this
  2934. * stage of the protocol. */
  2935. static int
  2936. is_valid_initial_command(control_connection_t *conn, const char *cmd)
  2937. {
  2938. if (conn->base_.state == CONTROL_CONN_STATE_OPEN)
  2939. return 1;
  2940. if (!strcasecmp(cmd, "PROTOCOLINFO"))
  2941. return (!conn->have_sent_protocolinfo &&
  2942. conn->safecookie_client_hash == NULL);
  2943. if (!strcasecmp(cmd, "AUTHCHALLENGE"))
  2944. return (conn->safecookie_client_hash == NULL);
  2945. if (!strcasecmp(cmd, "AUTHENTICATE") ||
  2946. !strcasecmp(cmd, "QUIT"))
  2947. return 1;
  2948. return 0;
  2949. }
  2950. /** Do not accept any control command of more than 1MB in length. Anything
  2951. * that needs to be anywhere near this long probably means that one of our
  2952. * interfaces is broken. */
  2953. #define MAX_COMMAND_LINE_LENGTH (1024*1024)
  2954. /** Wrapper around peek_(evbuffer|buf)_has_control0 command: presents the same
  2955. * interface as those underlying functions, but takes a connection_t intead of
  2956. * an evbuffer or a buf_t.
  2957. */
  2958. static int
  2959. peek_connection_has_control0_command(connection_t *conn)
  2960. {
  2961. IF_HAS_BUFFEREVENT(conn, {
  2962. struct evbuffer *input = bufferevent_get_input(conn->bufev);
  2963. return peek_evbuffer_has_control0_command(input);
  2964. }) ELSE_IF_NO_BUFFEREVENT {
  2965. return peek_buf_has_control0_command(conn->inbuf);
  2966. }
  2967. }
  2968. /** Called when data has arrived on a v1 control connection: Try to fetch
  2969. * commands from conn->inbuf, and execute them.
  2970. */
  2971. int
  2972. connection_control_process_inbuf(control_connection_t *conn)
  2973. {
  2974. size_t data_len;
  2975. uint32_t cmd_data_len;
  2976. int cmd_len;
  2977. char *args;
  2978. tor_assert(conn);
  2979. tor_assert(conn->base_.state == CONTROL_CONN_STATE_OPEN ||
  2980. conn->base_.state == CONTROL_CONN_STATE_NEEDAUTH);
  2981. if (!conn->incoming_cmd) {
  2982. conn->incoming_cmd = tor_malloc(1024);
  2983. conn->incoming_cmd_len = 1024;
  2984. conn->incoming_cmd_cur_len = 0;
  2985. }
  2986. if (conn->base_.state == CONTROL_CONN_STATE_NEEDAUTH &&
  2987. peek_connection_has_control0_command(TO_CONN(conn))) {
  2988. /* Detect v0 commands and send a "no more v0" message. */
  2989. size_t body_len;
  2990. char buf[128];
  2991. set_uint16(buf+2, htons(0x0000)); /* type == error */
  2992. set_uint16(buf+4, htons(0x0001)); /* code == internal error */
  2993. strlcpy(buf+6, "The v0 control protocol is not supported by Tor 0.1.2.17 "
  2994. "and later; upgrade your controller.",
  2995. sizeof(buf)-6);
  2996. body_len = 2+strlen(buf+6)+2; /* code, msg, nul. */
  2997. set_uint16(buf+0, htons(body_len));
  2998. connection_write_to_buf(buf, 4+body_len, TO_CONN(conn));
  2999. connection_mark_and_flush(TO_CONN(conn));
  3000. return 0;
  3001. }
  3002. again:
  3003. while (1) {
  3004. size_t last_idx;
  3005. int r;
  3006. /* First, fetch a line. */
  3007. do {
  3008. data_len = conn->incoming_cmd_len - conn->incoming_cmd_cur_len;
  3009. r = connection_fetch_from_buf_line(TO_CONN(conn),
  3010. conn->incoming_cmd+conn->incoming_cmd_cur_len,
  3011. &data_len);
  3012. if (r == 0)
  3013. /* Line not all here yet. Wait. */
  3014. return 0;
  3015. else if (r == -1) {
  3016. if (data_len + conn->incoming_cmd_cur_len > MAX_COMMAND_LINE_LENGTH) {
  3017. connection_write_str_to_buf("500 Line too long.\r\n", conn);
  3018. connection_stop_reading(TO_CONN(conn));
  3019. connection_mark_and_flush(TO_CONN(conn));
  3020. }
  3021. while (conn->incoming_cmd_len < data_len+conn->incoming_cmd_cur_len)
  3022. conn->incoming_cmd_len *= 2;
  3023. conn->incoming_cmd = tor_realloc(conn->incoming_cmd,
  3024. conn->incoming_cmd_len);
  3025. }
  3026. } while (r != 1);
  3027. tor_assert(data_len);
  3028. last_idx = conn->incoming_cmd_cur_len;
  3029. conn->incoming_cmd_cur_len += (int)data_len;
  3030. /* We have appended a line to incoming_cmd. Is the command done? */
  3031. if (last_idx == 0 && *conn->incoming_cmd != '+')
  3032. /* One line command, didn't start with '+'. */
  3033. break;
  3034. /* XXXX this code duplication is kind of dumb. */
  3035. if (last_idx+3 == conn->incoming_cmd_cur_len &&
  3036. tor_memeq(conn->incoming_cmd + last_idx, ".\r\n", 3)) {
  3037. /* Just appended ".\r\n"; we're done. Remove it. */
  3038. conn->incoming_cmd[last_idx] = '\0';
  3039. conn->incoming_cmd_cur_len -= 3;
  3040. break;
  3041. } else if (last_idx+2 == conn->incoming_cmd_cur_len &&
  3042. tor_memeq(conn->incoming_cmd + last_idx, ".\n", 2)) {
  3043. /* Just appended ".\n"; we're done. Remove it. */
  3044. conn->incoming_cmd[last_idx] = '\0';
  3045. conn->incoming_cmd_cur_len -= 2;
  3046. break;
  3047. }
  3048. /* Otherwise, read another line. */
  3049. }
  3050. data_len = conn->incoming_cmd_cur_len;
  3051. /* Okay, we now have a command sitting on conn->incoming_cmd. See if we
  3052. * recognize it.
  3053. */
  3054. cmd_len = 0;
  3055. while ((size_t)cmd_len < data_len
  3056. && !TOR_ISSPACE(conn->incoming_cmd[cmd_len]))
  3057. ++cmd_len;
  3058. conn->incoming_cmd[cmd_len]='\0';
  3059. args = conn->incoming_cmd+cmd_len+1;
  3060. tor_assert(data_len>(size_t)cmd_len);
  3061. data_len -= (cmd_len+1); /* skip the command and NUL we added after it */
  3062. while (TOR_ISSPACE(*args)) {
  3063. ++args;
  3064. --data_len;
  3065. }
  3066. /* If the connection is already closing, ignore further commands */
  3067. if (TO_CONN(conn)->marked_for_close) {
  3068. return 0;
  3069. }
  3070. /* Otherwise, Quit is always valid. */
  3071. if (!strcasecmp(conn->incoming_cmd, "QUIT")) {
  3072. connection_write_str_to_buf("250 closing connection\r\n", conn);
  3073. connection_mark_and_flush(TO_CONN(conn));
  3074. return 0;
  3075. }
  3076. if (conn->base_.state == CONTROL_CONN_STATE_NEEDAUTH &&
  3077. !is_valid_initial_command(conn, conn->incoming_cmd)) {
  3078. connection_write_str_to_buf("514 Authentication required.\r\n", conn);
  3079. connection_mark_for_close(TO_CONN(conn));
  3080. return 0;
  3081. }
  3082. if (data_len >= UINT32_MAX) {
  3083. connection_write_str_to_buf("500 A 4GB command? Nice try.\r\n", conn);
  3084. connection_mark_for_close(TO_CONN(conn));
  3085. return 0;
  3086. }
  3087. /* XXXX Why is this not implemented as a table like the GETINFO
  3088. * items are? Even handling the plus signs at the beginnings of
  3089. * commands wouldn't be very hard with proper macros. */
  3090. cmd_data_len = (uint32_t)data_len;
  3091. if (!strcasecmp(conn->incoming_cmd, "SETCONF")) {
  3092. if (handle_control_setconf(conn, cmd_data_len, args))
  3093. return -1;
  3094. } else if (!strcasecmp(conn->incoming_cmd, "RESETCONF")) {
  3095. if (handle_control_resetconf(conn, cmd_data_len, args))
  3096. return -1;
  3097. } else if (!strcasecmp(conn->incoming_cmd, "GETCONF")) {
  3098. if (handle_control_getconf(conn, cmd_data_len, args))
  3099. return -1;
  3100. } else if (!strcasecmp(conn->incoming_cmd, "+LOADCONF")) {
  3101. if (handle_control_loadconf(conn, cmd_data_len, args))
  3102. return -1;
  3103. } else if (!strcasecmp(conn->incoming_cmd, "SETEVENTS")) {
  3104. if (handle_control_setevents(conn, cmd_data_len, args))
  3105. return -1;
  3106. } else if (!strcasecmp(conn->incoming_cmd, "AUTHENTICATE")) {
  3107. if (handle_control_authenticate(conn, cmd_data_len, args))
  3108. return -1;
  3109. } else if (!strcasecmp(conn->incoming_cmd, "SAVECONF")) {
  3110. if (handle_control_saveconf(conn, cmd_data_len, args))
  3111. return -1;
  3112. } else if (!strcasecmp(conn->incoming_cmd, "SIGNAL")) {
  3113. if (handle_control_signal(conn, cmd_data_len, args))
  3114. return -1;
  3115. } else if (!strcasecmp(conn->incoming_cmd, "TAKEOWNERSHIP")) {
  3116. if (handle_control_takeownership(conn, cmd_data_len, args))
  3117. return -1;
  3118. } else if (!strcasecmp(conn->incoming_cmd, "MAPADDRESS")) {
  3119. if (handle_control_mapaddress(conn, cmd_data_len, args))
  3120. return -1;
  3121. } else if (!strcasecmp(conn->incoming_cmd, "GETINFO")) {
  3122. if (handle_control_getinfo(conn, cmd_data_len, args))
  3123. return -1;
  3124. } else if (!strcasecmp(conn->incoming_cmd, "EXTENDCIRCUIT")) {
  3125. if (handle_control_extendcircuit(conn, cmd_data_len, args))
  3126. return -1;
  3127. } else if (!strcasecmp(conn->incoming_cmd, "SETCIRCUITPURPOSE")) {
  3128. if (handle_control_setcircuitpurpose(conn, cmd_data_len, args))
  3129. return -1;
  3130. } else if (!strcasecmp(conn->incoming_cmd, "SETROUTERPURPOSE")) {
  3131. connection_write_str_to_buf("511 SETROUTERPURPOSE is obsolete.\r\n", conn);
  3132. } else if (!strcasecmp(conn->incoming_cmd, "ATTACHSTREAM")) {
  3133. if (handle_control_attachstream(conn, cmd_data_len, args))
  3134. return -1;
  3135. } else if (!strcasecmp(conn->incoming_cmd, "+POSTDESCRIPTOR")) {
  3136. if (handle_control_postdescriptor(conn, cmd_data_len, args))
  3137. return -1;
  3138. } else if (!strcasecmp(conn->incoming_cmd, "REDIRECTSTREAM")) {
  3139. if (handle_control_redirectstream(conn, cmd_data_len, args))
  3140. return -1;
  3141. } else if (!strcasecmp(conn->incoming_cmd, "CLOSESTREAM")) {
  3142. if (handle_control_closestream(conn, cmd_data_len, args))
  3143. return -1;
  3144. } else if (!strcasecmp(conn->incoming_cmd, "CLOSECIRCUIT")) {
  3145. if (handle_control_closecircuit(conn, cmd_data_len, args))
  3146. return -1;
  3147. } else if (!strcasecmp(conn->incoming_cmd, "USEFEATURE")) {
  3148. if (handle_control_usefeature(conn, cmd_data_len, args))
  3149. return -1;
  3150. } else if (!strcasecmp(conn->incoming_cmd, "RESOLVE")) {
  3151. if (handle_control_resolve(conn, cmd_data_len, args))
  3152. return -1;
  3153. } else if (!strcasecmp(conn->incoming_cmd, "PROTOCOLINFO")) {
  3154. if (handle_control_protocolinfo(conn, cmd_data_len, args))
  3155. return -1;
  3156. } else if (!strcasecmp(conn->incoming_cmd, "AUTHCHALLENGE")) {
  3157. if (handle_control_authchallenge(conn, cmd_data_len, args))
  3158. return -1;
  3159. } else if (!strcasecmp(conn->incoming_cmd, "DROPGUARDS")) {
  3160. if (handle_control_dropguards(conn, cmd_data_len, args))
  3161. return -1;
  3162. } else {
  3163. connection_printf_to_buf(conn, "510 Unrecognized command \"%s\"\r\n",
  3164. conn->incoming_cmd);
  3165. }
  3166. conn->incoming_cmd_cur_len = 0;
  3167. goto again;
  3168. }
  3169. /** Something major has happened to circuit <b>circ</b>: tell any
  3170. * interested control connections. */
  3171. int
  3172. control_event_circuit_status(origin_circuit_t *circ, circuit_status_event_t tp,
  3173. int reason_code)
  3174. {
  3175. const char *status;
  3176. char reasons[64] = "";
  3177. if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS))
  3178. return 0;
  3179. tor_assert(circ);
  3180. switch (tp)
  3181. {
  3182. case CIRC_EVENT_LAUNCHED: status = "LAUNCHED"; break;
  3183. case CIRC_EVENT_BUILT: status = "BUILT"; break;
  3184. case CIRC_EVENT_EXTENDED: status = "EXTENDED"; break;
  3185. case CIRC_EVENT_FAILED: status = "FAILED"; break;
  3186. case CIRC_EVENT_CLOSED: status = "CLOSED"; break;
  3187. default:
  3188. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  3189. tor_fragile_assert();
  3190. return 0;
  3191. }
  3192. if (tp == CIRC_EVENT_FAILED || tp == CIRC_EVENT_CLOSED) {
  3193. const char *reason_str = circuit_end_reason_to_control_string(reason_code);
  3194. char unk_reason_buf[16];
  3195. if (!reason_str) {
  3196. tor_snprintf(unk_reason_buf, 16, "UNKNOWN_%d", reason_code);
  3197. reason_str = unk_reason_buf;
  3198. }
  3199. if (reason_code > 0 && reason_code & END_CIRC_REASON_FLAG_REMOTE) {
  3200. tor_snprintf(reasons, sizeof(reasons),
  3201. " REASON=DESTROYED REMOTE_REASON=%s", reason_str);
  3202. } else {
  3203. tor_snprintf(reasons, sizeof(reasons),
  3204. " REASON=%s", reason_str);
  3205. }
  3206. }
  3207. {
  3208. char *circdesc = circuit_describe_status_for_controller(circ);
  3209. const char *sp = strlen(circdesc) ? " " : "";
  3210. send_control_event(EVENT_CIRCUIT_STATUS, ALL_FORMATS,
  3211. "650 CIRC %lu %s%s%s%s\r\n",
  3212. (unsigned long)circ->global_identifier,
  3213. status, sp,
  3214. circdesc,
  3215. reasons);
  3216. tor_free(circdesc);
  3217. }
  3218. return 0;
  3219. }
  3220. /** Something minor has happened to circuit <b>circ</b>: tell any
  3221. * interested control connections. */
  3222. static int
  3223. control_event_circuit_status_minor(origin_circuit_t *circ,
  3224. circuit_status_minor_event_t e,
  3225. int purpose, const struct timeval *tv)
  3226. {
  3227. const char *event_desc;
  3228. char event_tail[160] = "";
  3229. if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS_MINOR))
  3230. return 0;
  3231. tor_assert(circ);
  3232. switch (e)
  3233. {
  3234. case CIRC_MINOR_EVENT_PURPOSE_CHANGED:
  3235. event_desc = "PURPOSE_CHANGED";
  3236. {
  3237. /* event_tail can currently be up to 68 chars long */
  3238. const char *hs_state_str =
  3239. circuit_purpose_to_controller_hs_state_string(purpose);
  3240. tor_snprintf(event_tail, sizeof(event_tail),
  3241. " OLD_PURPOSE=%s%s%s",
  3242. circuit_purpose_to_controller_string(purpose),
  3243. (hs_state_str != NULL) ? " OLD_HS_STATE=" : "",
  3244. (hs_state_str != NULL) ? hs_state_str : "");
  3245. }
  3246. break;
  3247. case CIRC_MINOR_EVENT_CANNIBALIZED:
  3248. event_desc = "CANNIBALIZED";
  3249. {
  3250. /* event_tail can currently be up to 130 chars long */
  3251. const char *hs_state_str =
  3252. circuit_purpose_to_controller_hs_state_string(purpose);
  3253. const struct timeval *old_timestamp_began = tv;
  3254. char tbuf[ISO_TIME_USEC_LEN+1];
  3255. format_iso_time_nospace_usec(tbuf, old_timestamp_began);
  3256. tor_snprintf(event_tail, sizeof(event_tail),
  3257. " OLD_PURPOSE=%s%s%s OLD_TIME_CREATED=%s",
  3258. circuit_purpose_to_controller_string(purpose),
  3259. (hs_state_str != NULL) ? " OLD_HS_STATE=" : "",
  3260. (hs_state_str != NULL) ? hs_state_str : "",
  3261. tbuf);
  3262. }
  3263. break;
  3264. default:
  3265. log_warn(LD_BUG, "Unrecognized status code %d", (int)e);
  3266. tor_fragile_assert();
  3267. return 0;
  3268. }
  3269. {
  3270. char *circdesc = circuit_describe_status_for_controller(circ);
  3271. const char *sp = strlen(circdesc) ? " " : "";
  3272. send_control_event(EVENT_CIRCUIT_STATUS_MINOR, ALL_FORMATS,
  3273. "650 CIRC_MINOR %lu %s%s%s%s\r\n",
  3274. (unsigned long)circ->global_identifier,
  3275. event_desc, sp,
  3276. circdesc,
  3277. event_tail);
  3278. tor_free(circdesc);
  3279. }
  3280. return 0;
  3281. }
  3282. /**
  3283. * <b>circ</b> has changed its purpose from <b>old_purpose</b>: tell any
  3284. * interested controllers.
  3285. */
  3286. int
  3287. control_event_circuit_purpose_changed(origin_circuit_t *circ,
  3288. int old_purpose)
  3289. {
  3290. return control_event_circuit_status_minor(circ,
  3291. CIRC_MINOR_EVENT_PURPOSE_CHANGED,
  3292. old_purpose,
  3293. NULL);
  3294. }
  3295. /**
  3296. * <b>circ</b> has changed its purpose from <b>old_purpose</b>, and its
  3297. * created-time from <b>old_tv_created</b>: tell any interested controllers.
  3298. */
  3299. int
  3300. control_event_circuit_cannibalized(origin_circuit_t *circ,
  3301. int old_purpose,
  3302. const struct timeval *old_tv_created)
  3303. {
  3304. return control_event_circuit_status_minor(circ,
  3305. CIRC_MINOR_EVENT_CANNIBALIZED,
  3306. old_purpose,
  3307. old_tv_created);
  3308. }
  3309. /** Given an AP connection <b>conn</b> and a <b>len</b>-character buffer
  3310. * <b>buf</b>, determine the address:port combination requested on
  3311. * <b>conn</b>, and write it to <b>buf</b>. Return 0 on success, -1 on
  3312. * failure. */
  3313. static int
  3314. write_stream_target_to_buf(entry_connection_t *conn, char *buf, size_t len)
  3315. {
  3316. char buf2[256];
  3317. if (conn->chosen_exit_name)
  3318. if (tor_snprintf(buf2, sizeof(buf2), ".%s.exit", conn->chosen_exit_name)<0)
  3319. return -1;
  3320. if (!conn->socks_request)
  3321. return -1;
  3322. if (tor_snprintf(buf, len, "%s%s%s:%d",
  3323. conn->socks_request->address,
  3324. conn->chosen_exit_name ? buf2 : "",
  3325. !conn->chosen_exit_name && connection_edge_is_rendezvous_stream(
  3326. ENTRY_TO_EDGE_CONN(conn)) ? ".onion" : "",
  3327. conn->socks_request->port)<0)
  3328. return -1;
  3329. return 0;
  3330. }
  3331. /** Something has happened to the stream associated with AP connection
  3332. * <b>conn</b>: tell any interested control connections. */
  3333. int
  3334. control_event_stream_status(entry_connection_t *conn, stream_status_event_t tp,
  3335. int reason_code)
  3336. {
  3337. char reason_buf[64];
  3338. char addrport_buf[64];
  3339. const char *status;
  3340. circuit_t *circ;
  3341. origin_circuit_t *origin_circ = NULL;
  3342. char buf[256];
  3343. const char *purpose = "";
  3344. tor_assert(conn->socks_request);
  3345. if (!EVENT_IS_INTERESTING(EVENT_STREAM_STATUS))
  3346. return 0;
  3347. if (tp == STREAM_EVENT_CLOSED &&
  3348. (reason_code & END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED))
  3349. return 0;
  3350. write_stream_target_to_buf(conn, buf, sizeof(buf));
  3351. reason_buf[0] = '\0';
  3352. switch (tp)
  3353. {
  3354. case STREAM_EVENT_SENT_CONNECT: status = "SENTCONNECT"; break;
  3355. case STREAM_EVENT_SENT_RESOLVE: status = "SENTRESOLVE"; break;
  3356. case STREAM_EVENT_SUCCEEDED: status = "SUCCEEDED"; break;
  3357. case STREAM_EVENT_FAILED: status = "FAILED"; break;
  3358. case STREAM_EVENT_CLOSED: status = "CLOSED"; break;
  3359. case STREAM_EVENT_NEW: status = "NEW"; break;
  3360. case STREAM_EVENT_NEW_RESOLVE: status = "NEWRESOLVE"; break;
  3361. case STREAM_EVENT_FAILED_RETRIABLE: status = "DETACHED"; break;
  3362. case STREAM_EVENT_REMAP: status = "REMAP"; break;
  3363. default:
  3364. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  3365. return 0;
  3366. }
  3367. if (reason_code && (tp == STREAM_EVENT_FAILED ||
  3368. tp == STREAM_EVENT_CLOSED ||
  3369. tp == STREAM_EVENT_FAILED_RETRIABLE)) {
  3370. const char *reason_str = stream_end_reason_to_control_string(reason_code);
  3371. char *r = NULL;
  3372. if (!reason_str) {
  3373. tor_asprintf(&r, " UNKNOWN_%d", reason_code);
  3374. reason_str = r;
  3375. }
  3376. if (reason_code & END_STREAM_REASON_FLAG_REMOTE)
  3377. tor_snprintf(reason_buf, sizeof(reason_buf),
  3378. " REASON=END REMOTE_REASON=%s", reason_str);
  3379. else
  3380. tor_snprintf(reason_buf, sizeof(reason_buf),
  3381. " REASON=%s", reason_str);
  3382. tor_free(r);
  3383. } else if (reason_code && tp == STREAM_EVENT_REMAP) {
  3384. switch (reason_code) {
  3385. case REMAP_STREAM_SOURCE_CACHE:
  3386. strlcpy(reason_buf, " SOURCE=CACHE", sizeof(reason_buf));
  3387. break;
  3388. case REMAP_STREAM_SOURCE_EXIT:
  3389. strlcpy(reason_buf, " SOURCE=EXIT", sizeof(reason_buf));
  3390. break;
  3391. default:
  3392. tor_snprintf(reason_buf, sizeof(reason_buf), " REASON=UNKNOWN_%d",
  3393. reason_code);
  3394. /* XXX do we want SOURCE=UNKNOWN_%d above instead? -RD */
  3395. break;
  3396. }
  3397. }
  3398. if (tp == STREAM_EVENT_NEW || tp == STREAM_EVENT_NEW_RESOLVE) {
  3399. /*
  3400. * When the control conn is an AF_UNIX socket and we have no address,
  3401. * it gets set to "(Tor_internal)"; see dnsserv_launch_request() in
  3402. * dnsserv.c.
  3403. */
  3404. if (strcmp(ENTRY_TO_CONN(conn)->address, "(Tor_internal)") != 0) {
  3405. tor_snprintf(addrport_buf,sizeof(addrport_buf), " SOURCE_ADDR=%s:%d",
  3406. ENTRY_TO_CONN(conn)->address, ENTRY_TO_CONN(conn)->port);
  3407. } else {
  3408. /*
  3409. * else leave it blank so control on AF_UNIX doesn't need to make
  3410. * something up.
  3411. */
  3412. addrport_buf[0] = '\0';
  3413. }
  3414. } else {
  3415. addrport_buf[0] = '\0';
  3416. }
  3417. if (tp == STREAM_EVENT_NEW_RESOLVE) {
  3418. purpose = " PURPOSE=DNS_REQUEST";
  3419. } else if (tp == STREAM_EVENT_NEW) {
  3420. if (conn->use_begindir) {
  3421. connection_t *linked = ENTRY_TO_CONN(conn)->linked_conn;
  3422. int linked_dir_purpose = -1;
  3423. if (linked && linked->type == CONN_TYPE_DIR)
  3424. linked_dir_purpose = linked->purpose;
  3425. if (DIR_PURPOSE_IS_UPLOAD(linked_dir_purpose))
  3426. purpose = " PURPOSE=DIR_UPLOAD";
  3427. else
  3428. purpose = " PURPOSE=DIR_FETCH";
  3429. } else
  3430. purpose = " PURPOSE=USER";
  3431. }
  3432. circ = circuit_get_by_edge_conn(ENTRY_TO_EDGE_CONN(conn));
  3433. if (circ && CIRCUIT_IS_ORIGIN(circ))
  3434. origin_circ = TO_ORIGIN_CIRCUIT(circ);
  3435. send_control_event(EVENT_STREAM_STATUS, ALL_FORMATS,
  3436. "650 STREAM "U64_FORMAT" %s %lu %s%s%s%s\r\n",
  3437. U64_PRINTF_ARG(ENTRY_TO_CONN(conn)->global_identifier),
  3438. status,
  3439. origin_circ?
  3440. (unsigned long)origin_circ->global_identifier : 0ul,
  3441. buf, reason_buf, addrport_buf, purpose);
  3442. /* XXX need to specify its intended exit, etc? */
  3443. return 0;
  3444. }
  3445. /** Figure out the best name for the target router of an OR connection
  3446. * <b>conn</b>, and write it into the <b>len</b>-character buffer
  3447. * <b>name</b>. */
  3448. static void
  3449. orconn_target_get_name(char *name, size_t len, or_connection_t *conn)
  3450. {
  3451. const node_t *node = node_get_by_id(conn->identity_digest);
  3452. if (node) {
  3453. tor_assert(len > MAX_VERBOSE_NICKNAME_LEN);
  3454. node_get_verbose_nickname(node, name);
  3455. } else if (! tor_digest_is_zero(conn->identity_digest)) {
  3456. name[0] = '$';
  3457. base16_encode(name+1, len-1, conn->identity_digest,
  3458. DIGEST_LEN);
  3459. } else {
  3460. tor_snprintf(name, len, "%s:%d",
  3461. conn->base_.address, conn->base_.port);
  3462. }
  3463. }
  3464. /** Called when the status of an OR connection <b>conn</b> changes: tell any
  3465. * interested control connections. <b>tp</b> is the new status for the
  3466. * connection. If <b>conn</b> has just closed or failed, then <b>reason</b>
  3467. * may be the reason why.
  3468. */
  3469. int
  3470. control_event_or_conn_status(or_connection_t *conn, or_conn_status_event_t tp,
  3471. int reason)
  3472. {
  3473. int ncircs = 0;
  3474. const char *status;
  3475. char name[128];
  3476. char ncircs_buf[32] = {0}; /* > 8 + log10(2^32)=10 + 2 */
  3477. if (!EVENT_IS_INTERESTING(EVENT_OR_CONN_STATUS))
  3478. return 0;
  3479. switch (tp)
  3480. {
  3481. case OR_CONN_EVENT_LAUNCHED: status = "LAUNCHED"; break;
  3482. case OR_CONN_EVENT_CONNECTED: status = "CONNECTED"; break;
  3483. case OR_CONN_EVENT_FAILED: status = "FAILED"; break;
  3484. case OR_CONN_EVENT_CLOSED: status = "CLOSED"; break;
  3485. case OR_CONN_EVENT_NEW: status = "NEW"; break;
  3486. default:
  3487. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  3488. return 0;
  3489. }
  3490. if (conn->chan) {
  3491. ncircs = circuit_count_pending_on_channel(TLS_CHAN_TO_BASE(conn->chan));
  3492. } else {
  3493. ncircs = 0;
  3494. }
  3495. ncircs += connection_or_get_num_circuits(conn);
  3496. if (ncircs && (tp == OR_CONN_EVENT_FAILED || tp == OR_CONN_EVENT_CLOSED)) {
  3497. tor_snprintf(ncircs_buf, sizeof(ncircs_buf), " NCIRCS=%d", ncircs);
  3498. }
  3499. orconn_target_get_name(name, sizeof(name), conn);
  3500. send_control_event(EVENT_OR_CONN_STATUS, ALL_FORMATS,
  3501. "650 ORCONN %s %s%s%s%s ID="U64_FORMAT"\r\n",
  3502. name, status,
  3503. reason ? " REASON=" : "",
  3504. orconn_end_reason_to_control_string(reason),
  3505. ncircs_buf,
  3506. U64_PRINTF_ARG(conn->base_.global_identifier));
  3507. return 0;
  3508. }
  3509. /**
  3510. * Print out STREAM_BW event for a single conn
  3511. */
  3512. int
  3513. control_event_stream_bandwidth(edge_connection_t *edge_conn)
  3514. {
  3515. circuit_t *circ;
  3516. origin_circuit_t *ocirc;
  3517. if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED)) {
  3518. if (!edge_conn->n_read && !edge_conn->n_written)
  3519. return 0;
  3520. send_control_event(EVENT_STREAM_BANDWIDTH_USED, ALL_FORMATS,
  3521. "650 STREAM_BW "U64_FORMAT" %lu %lu\r\n",
  3522. U64_PRINTF_ARG(edge_conn->base_.global_identifier),
  3523. (unsigned long)edge_conn->n_read,
  3524. (unsigned long)edge_conn->n_written);
  3525. circ = circuit_get_by_edge_conn(edge_conn);
  3526. if (circ && CIRCUIT_IS_ORIGIN(circ)) {
  3527. ocirc = TO_ORIGIN_CIRCUIT(circ);
  3528. ocirc->n_read_circ_bw += edge_conn->n_read;
  3529. ocirc->n_written_circ_bw += edge_conn->n_written;
  3530. }
  3531. edge_conn->n_written = edge_conn->n_read = 0;
  3532. }
  3533. return 0;
  3534. }
  3535. /** A second or more has elapsed: tell any interested control
  3536. * connections how much bandwidth streams have used. */
  3537. int
  3538. control_event_stream_bandwidth_used(void)
  3539. {
  3540. if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED)) {
  3541. smartlist_t *conns = get_connection_array();
  3542. edge_connection_t *edge_conn;
  3543. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn)
  3544. {
  3545. if (conn->type != CONN_TYPE_AP)
  3546. continue;
  3547. edge_conn = TO_EDGE_CONN(conn);
  3548. if (!edge_conn->n_read && !edge_conn->n_written)
  3549. continue;
  3550. send_control_event(EVENT_STREAM_BANDWIDTH_USED, ALL_FORMATS,
  3551. "650 STREAM_BW "U64_FORMAT" %lu %lu\r\n",
  3552. U64_PRINTF_ARG(edge_conn->base_.global_identifier),
  3553. (unsigned long)edge_conn->n_read,
  3554. (unsigned long)edge_conn->n_written);
  3555. edge_conn->n_written = edge_conn->n_read = 0;
  3556. }
  3557. SMARTLIST_FOREACH_END(conn);
  3558. }
  3559. return 0;
  3560. }
  3561. /** A second or more has elapsed: tell any interested control connections
  3562. * how much bandwidth origin circuits have used. */
  3563. int
  3564. control_event_circ_bandwidth_used(void)
  3565. {
  3566. origin_circuit_t *ocirc;
  3567. if (!EVENT_IS_INTERESTING(EVENT_CIRC_BANDWIDTH_USED))
  3568. return 0;
  3569. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  3570. if (!CIRCUIT_IS_ORIGIN(circ))
  3571. continue;
  3572. ocirc = TO_ORIGIN_CIRCUIT(circ);
  3573. if (!ocirc->n_read_circ_bw && !ocirc->n_written_circ_bw)
  3574. continue;
  3575. send_control_event(EVENT_CIRC_BANDWIDTH_USED, ALL_FORMATS,
  3576. "650 CIRC_BW ID=%d READ=%lu WRITTEN=%lu\r\n",
  3577. ocirc->global_identifier,
  3578. (unsigned long)ocirc->n_read_circ_bw,
  3579. (unsigned long)ocirc->n_written_circ_bw);
  3580. ocirc->n_written_circ_bw = ocirc->n_read_circ_bw = 0;
  3581. }
  3582. SMARTLIST_FOREACH_END(circ);
  3583. return 0;
  3584. }
  3585. /** Print out CONN_BW event for a single OR/DIR/EXIT <b>conn</b> and reset
  3586. * bandwidth counters. */
  3587. int
  3588. control_event_conn_bandwidth(connection_t *conn)
  3589. {
  3590. const char *conn_type_str;
  3591. if (!get_options()->TestingEnableConnBwEvent ||
  3592. !EVENT_IS_INTERESTING(EVENT_CONN_BW))
  3593. return 0;
  3594. if (!conn->n_read_conn_bw && !conn->n_written_conn_bw)
  3595. return 0;
  3596. switch (conn->type) {
  3597. case CONN_TYPE_OR:
  3598. conn_type_str = "OR";
  3599. break;
  3600. case CONN_TYPE_DIR:
  3601. conn_type_str = "DIR";
  3602. break;
  3603. case CONN_TYPE_EXIT:
  3604. conn_type_str = "EXIT";
  3605. break;
  3606. default:
  3607. return 0;
  3608. }
  3609. send_control_event(EVENT_CONN_BW, ALL_FORMATS,
  3610. "650 CONN_BW ID="U64_FORMAT" TYPE=%s "
  3611. "READ=%lu WRITTEN=%lu\r\n",
  3612. U64_PRINTF_ARG(conn->global_identifier),
  3613. conn_type_str,
  3614. (unsigned long)conn->n_read_conn_bw,
  3615. (unsigned long)conn->n_written_conn_bw);
  3616. conn->n_written_conn_bw = conn->n_read_conn_bw = 0;
  3617. return 0;
  3618. }
  3619. /** A second or more has elapsed: tell any interested control
  3620. * connections how much bandwidth connections have used. */
  3621. int
  3622. control_event_conn_bandwidth_used(void)
  3623. {
  3624. if (get_options()->TestingEnableConnBwEvent &&
  3625. EVENT_IS_INTERESTING(EVENT_CONN_BW)) {
  3626. SMARTLIST_FOREACH(get_connection_array(), connection_t *, conn,
  3627. control_event_conn_bandwidth(conn));
  3628. }
  3629. return 0;
  3630. }
  3631. /** Helper: iterate over cell statistics of <b>circ</b> and sum up added
  3632. * cells, removed cells, and waiting times by cell command and direction.
  3633. * Store results in <b>cell_stats</b>. Free cell statistics of the
  3634. * circuit afterwards. */
  3635. void
  3636. sum_up_cell_stats_by_command(circuit_t *circ, cell_stats_t *cell_stats)
  3637. {
  3638. memset(cell_stats, 0, sizeof(cell_stats_t));
  3639. SMARTLIST_FOREACH_BEGIN(circ->testing_cell_stats,
  3640. testing_cell_stats_entry_t *, ent) {
  3641. tor_assert(ent->command <= CELL_COMMAND_MAX_);
  3642. if (!ent->removed && !ent->exitward) {
  3643. cell_stats->added_cells_appward[ent->command] += 1;
  3644. } else if (!ent->removed && ent->exitward) {
  3645. cell_stats->added_cells_exitward[ent->command] += 1;
  3646. } else if (!ent->exitward) {
  3647. cell_stats->removed_cells_appward[ent->command] += 1;
  3648. cell_stats->total_time_appward[ent->command] += ent->waiting_time * 10;
  3649. } else {
  3650. cell_stats->removed_cells_exitward[ent->command] += 1;
  3651. cell_stats->total_time_exitward[ent->command] += ent->waiting_time * 10;
  3652. }
  3653. tor_free(ent);
  3654. } SMARTLIST_FOREACH_END(ent);
  3655. smartlist_free(circ->testing_cell_stats);
  3656. circ->testing_cell_stats = NULL;
  3657. }
  3658. /** Helper: append a cell statistics string to <code>event_parts</code>,
  3659. * prefixed with <code>key</code>=. Statistics consist of comma-separated
  3660. * key:value pairs with lower-case command strings as keys and cell
  3661. * numbers or total waiting times as values. A key:value pair is included
  3662. * if the entry in <code>include_if_non_zero</code> is not zero, but with
  3663. * the (possibly zero) entry from <code>number_to_include</code>. Both
  3664. * arrays are expected to have a length of CELL_COMMAND_MAX_ + 1. If no
  3665. * entry in <code>include_if_non_zero</code> is positive, no string will
  3666. * be added to <code>event_parts</code>. */
  3667. void
  3668. append_cell_stats_by_command(smartlist_t *event_parts, const char *key,
  3669. const uint64_t *include_if_non_zero,
  3670. const uint64_t *number_to_include)
  3671. {
  3672. smartlist_t *key_value_strings = smartlist_new();
  3673. int i;
  3674. for (i = 0; i <= CELL_COMMAND_MAX_; i++) {
  3675. if (include_if_non_zero[i] > 0) {
  3676. smartlist_add_asprintf(key_value_strings, "%s:"U64_FORMAT,
  3677. cell_command_to_string(i),
  3678. U64_PRINTF_ARG(number_to_include[i]));
  3679. }
  3680. }
  3681. if (smartlist_len(key_value_strings) > 0) {
  3682. char *joined = smartlist_join_strings(key_value_strings, ",", 0, NULL);
  3683. smartlist_add_asprintf(event_parts, "%s=%s", key, joined);
  3684. SMARTLIST_FOREACH(key_value_strings, char *, cp, tor_free(cp));
  3685. tor_free(joined);
  3686. }
  3687. smartlist_free(key_value_strings);
  3688. }
  3689. /** Helper: format <b>cell_stats</b> for <b>circ</b> for inclusion in a
  3690. * CELL_STATS event and write result string to <b>event_string</b>. */
  3691. void
  3692. format_cell_stats(char **event_string, circuit_t *circ,
  3693. cell_stats_t *cell_stats)
  3694. {
  3695. smartlist_t *event_parts = smartlist_new();
  3696. if (CIRCUIT_IS_ORIGIN(circ)) {
  3697. origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
  3698. smartlist_add_asprintf(event_parts, "ID=%lu",
  3699. (unsigned long)ocirc->global_identifier);
  3700. } else if (TO_OR_CIRCUIT(circ)->p_chan) {
  3701. or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
  3702. smartlist_add_asprintf(event_parts, "InboundQueue=%lu",
  3703. (unsigned long)or_circ->p_circ_id);
  3704. smartlist_add_asprintf(event_parts, "InboundConn="U64_FORMAT,
  3705. U64_PRINTF_ARG(or_circ->p_chan->global_identifier));
  3706. append_cell_stats_by_command(event_parts, "InboundAdded",
  3707. cell_stats->added_cells_appward,
  3708. cell_stats->added_cells_appward);
  3709. append_cell_stats_by_command(event_parts, "InboundRemoved",
  3710. cell_stats->removed_cells_appward,
  3711. cell_stats->removed_cells_appward);
  3712. append_cell_stats_by_command(event_parts, "InboundTime",
  3713. cell_stats->removed_cells_appward,
  3714. cell_stats->total_time_appward);
  3715. }
  3716. if (circ->n_chan) {
  3717. smartlist_add_asprintf(event_parts, "OutboundQueue=%lu",
  3718. (unsigned long)circ->n_circ_id);
  3719. smartlist_add_asprintf(event_parts, "OutboundConn="U64_FORMAT,
  3720. U64_PRINTF_ARG(circ->n_chan->global_identifier));
  3721. append_cell_stats_by_command(event_parts, "OutboundAdded",
  3722. cell_stats->added_cells_exitward,
  3723. cell_stats->added_cells_exitward);
  3724. append_cell_stats_by_command(event_parts, "OutboundRemoved",
  3725. cell_stats->removed_cells_exitward,
  3726. cell_stats->removed_cells_exitward);
  3727. append_cell_stats_by_command(event_parts, "OutboundTime",
  3728. cell_stats->removed_cells_exitward,
  3729. cell_stats->total_time_exitward);
  3730. }
  3731. *event_string = smartlist_join_strings(event_parts, " ", 0, NULL);
  3732. SMARTLIST_FOREACH(event_parts, char *, cp, tor_free(cp));
  3733. smartlist_free(event_parts);
  3734. }
  3735. /** A second or more has elapsed: tell any interested control connection
  3736. * how many cells have been processed for a given circuit. */
  3737. int
  3738. control_event_circuit_cell_stats(void)
  3739. {
  3740. cell_stats_t *cell_stats;
  3741. char *event_string;
  3742. if (!get_options()->TestingEnableCellStatsEvent ||
  3743. !EVENT_IS_INTERESTING(EVENT_CELL_STATS))
  3744. return 0;
  3745. cell_stats = tor_malloc(sizeof(cell_stats_t));;
  3746. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  3747. if (!circ->testing_cell_stats)
  3748. continue;
  3749. sum_up_cell_stats_by_command(circ, cell_stats);
  3750. format_cell_stats(&event_string, circ, cell_stats);
  3751. send_control_event(EVENT_CELL_STATS, ALL_FORMATS,
  3752. "650 CELL_STATS %s\r\n", event_string);
  3753. tor_free(event_string);
  3754. }
  3755. SMARTLIST_FOREACH_END(circ);
  3756. tor_free(cell_stats);
  3757. return 0;
  3758. }
  3759. /** Tokens in <b>bucket</b> have been refilled: the read bucket was empty
  3760. * for <b>read_empty_time</b> millis, the write bucket was empty for
  3761. * <b>write_empty_time</b> millis, and buckets were last refilled
  3762. * <b>milliseconds_elapsed</b> millis ago. Only emit TB_EMPTY event if
  3763. * either read or write bucket have been empty before. */
  3764. int
  3765. control_event_tb_empty(const char *bucket, uint32_t read_empty_time,
  3766. uint32_t write_empty_time,
  3767. int milliseconds_elapsed)
  3768. {
  3769. if (get_options()->TestingEnableTbEmptyEvent &&
  3770. EVENT_IS_INTERESTING(EVENT_TB_EMPTY) &&
  3771. (read_empty_time > 0 || write_empty_time > 0)) {
  3772. send_control_event(EVENT_TB_EMPTY, ALL_FORMATS,
  3773. "650 TB_EMPTY %s READ=%d WRITTEN=%d "
  3774. "LAST=%d\r\n",
  3775. bucket, read_empty_time, write_empty_time,
  3776. milliseconds_elapsed);
  3777. }
  3778. return 0;
  3779. }
  3780. /** A second or more has elapsed: tell any interested control
  3781. * connections how much bandwidth we used. */
  3782. int
  3783. control_event_bandwidth_used(uint32_t n_read, uint32_t n_written)
  3784. {
  3785. if (EVENT_IS_INTERESTING(EVENT_BANDWIDTH_USED)) {
  3786. send_control_event(EVENT_BANDWIDTH_USED, ALL_FORMATS,
  3787. "650 BW %lu %lu\r\n",
  3788. (unsigned long)n_read,
  3789. (unsigned long)n_written);
  3790. }
  3791. return 0;
  3792. }
  3793. /** Called when we are sending a log message to the controllers: suspend
  3794. * sending further log messages to the controllers until we're done. Used by
  3795. * CONN_LOG_PROTECT. */
  3796. void
  3797. disable_control_logging(void)
  3798. {
  3799. ++disable_log_messages;
  3800. }
  3801. /** We're done sending a log message to the controllers: re-enable controller
  3802. * logging. Used by CONN_LOG_PROTECT. */
  3803. void
  3804. enable_control_logging(void)
  3805. {
  3806. if (--disable_log_messages < 0)
  3807. tor_assert(0);
  3808. }
  3809. /** We got a log message: tell any interested control connections. */
  3810. void
  3811. control_event_logmsg(int severity, uint32_t domain, const char *msg)
  3812. {
  3813. int event;
  3814. /* Don't even think of trying to add stuff to a buffer from a cpuworker
  3815. * thread. */
  3816. if (! in_main_thread())
  3817. return;
  3818. if (disable_log_messages)
  3819. return;
  3820. if (domain == LD_BUG && EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL) &&
  3821. severity <= LOG_NOTICE) {
  3822. char *esc = esc_for_log(msg);
  3823. ++disable_log_messages;
  3824. control_event_general_status(severity, "BUG REASON=%s", esc);
  3825. --disable_log_messages;
  3826. tor_free(esc);
  3827. }
  3828. event = log_severity_to_event(severity);
  3829. if (event >= 0 && EVENT_IS_INTERESTING(event)) {
  3830. char *b = NULL;
  3831. const char *s;
  3832. if (strchr(msg, '\n')) {
  3833. char *cp;
  3834. b = tor_strdup(msg);
  3835. for (cp = b; *cp; ++cp)
  3836. if (*cp == '\r' || *cp == '\n')
  3837. *cp = ' ';
  3838. }
  3839. switch (severity) {
  3840. case LOG_DEBUG: s = "DEBUG"; break;
  3841. case LOG_INFO: s = "INFO"; break;
  3842. case LOG_NOTICE: s = "NOTICE"; break;
  3843. case LOG_WARN: s = "WARN"; break;
  3844. case LOG_ERR: s = "ERR"; break;
  3845. default: s = "UnknownLogSeverity"; break;
  3846. }
  3847. ++disable_log_messages;
  3848. send_control_event(event, ALL_FORMATS, "650 %s %s\r\n", s, b?b:msg);
  3849. --disable_log_messages;
  3850. tor_free(b);
  3851. }
  3852. }
  3853. /** Called whenever we receive new router descriptors: tell any
  3854. * interested control connections. <b>routers</b> is a list of
  3855. * routerinfo_t's.
  3856. */
  3857. int
  3858. control_event_descriptors_changed(smartlist_t *routers)
  3859. {
  3860. char *msg;
  3861. if (!EVENT_IS_INTERESTING(EVENT_NEW_DESC))
  3862. return 0;
  3863. {
  3864. smartlist_t *names = smartlist_new();
  3865. char *ids;
  3866. SMARTLIST_FOREACH(routers, routerinfo_t *, ri, {
  3867. char *b = tor_malloc(MAX_VERBOSE_NICKNAME_LEN+1);
  3868. router_get_verbose_nickname(b, ri);
  3869. smartlist_add(names, b);
  3870. });
  3871. ids = smartlist_join_strings(names, " ", 0, NULL);
  3872. tor_asprintf(&msg, "650 NEWDESC %s\r\n", ids);
  3873. send_control_event_string(EVENT_NEW_DESC, ALL_FORMATS, msg);
  3874. tor_free(ids);
  3875. tor_free(msg);
  3876. SMARTLIST_FOREACH(names, char *, cp, tor_free(cp));
  3877. smartlist_free(names);
  3878. }
  3879. return 0;
  3880. }
  3881. /** Called when an address mapping on <b>from</b> from changes to <b>to</b>.
  3882. * <b>expires</b> values less than 3 are special; see connection_edge.c. If
  3883. * <b>error</b> is non-NULL, it is an error code describing the failure
  3884. * mode of the mapping.
  3885. */
  3886. int
  3887. control_event_address_mapped(const char *from, const char *to, time_t expires,
  3888. const char *error, const int cached)
  3889. {
  3890. if (!EVENT_IS_INTERESTING(EVENT_ADDRMAP))
  3891. return 0;
  3892. if (expires < 3 || expires == TIME_MAX)
  3893. send_control_event(EVENT_ADDRMAP, ALL_FORMATS,
  3894. "650 ADDRMAP %s %s NEVER %s%s"
  3895. "CACHED=\"%s\"\r\n",
  3896. from, to, error?error:"", error?" ":"",
  3897. cached?"YES":"NO");
  3898. else {
  3899. char buf[ISO_TIME_LEN+1];
  3900. char buf2[ISO_TIME_LEN+1];
  3901. format_local_iso_time(buf,expires);
  3902. format_iso_time(buf2,expires);
  3903. send_control_event(EVENT_ADDRMAP, ALL_FORMATS,
  3904. "650 ADDRMAP %s %s \"%s\""
  3905. " %s%sEXPIRES=\"%s\" CACHED=\"%s\"\r\n",
  3906. from, to, buf,
  3907. error?error:"", error?" ":"",
  3908. buf2, cached?"YES":"NO");
  3909. }
  3910. return 0;
  3911. }
  3912. /** The authoritative dirserver has received a new descriptor that
  3913. * has passed basic syntax checks and is properly self-signed.
  3914. *
  3915. * Notify any interested party of the new descriptor and what has
  3916. * been done with it, and also optionally give an explanation/reason. */
  3917. int
  3918. control_event_or_authdir_new_descriptor(const char *action,
  3919. const char *desc, size_t desclen,
  3920. const char *msg)
  3921. {
  3922. char firstline[1024];
  3923. char *buf;
  3924. size_t totallen;
  3925. char *esc = NULL;
  3926. size_t esclen;
  3927. if (!EVENT_IS_INTERESTING(EVENT_AUTHDIR_NEWDESCS))
  3928. return 0;
  3929. tor_snprintf(firstline, sizeof(firstline),
  3930. "650+AUTHDIR_NEWDESC=\r\n%s\r\n%s\r\n",
  3931. action,
  3932. msg ? msg : "");
  3933. /* Escape the server descriptor properly */
  3934. esclen = write_escaped_data(desc, desclen, &esc);
  3935. totallen = strlen(firstline) + esclen + 1;
  3936. buf = tor_malloc(totallen);
  3937. strlcpy(buf, firstline, totallen);
  3938. strlcpy(buf+strlen(firstline), esc, totallen);
  3939. send_control_event_string(EVENT_AUTHDIR_NEWDESCS, ALL_FORMATS,
  3940. buf);
  3941. send_control_event_string(EVENT_AUTHDIR_NEWDESCS, ALL_FORMATS,
  3942. "650 OK\r\n");
  3943. tor_free(esc);
  3944. tor_free(buf);
  3945. return 0;
  3946. }
  3947. /** Helper function for NS-style events. Constructs and sends an event
  3948. * of type <b>event</b> with string <b>event_string</b> out of the set of
  3949. * networkstatuses <b>statuses</b>. Currently it is used for NS events
  3950. * and NEWCONSENSUS events. */
  3951. static int
  3952. control_event_networkstatus_changed_helper(smartlist_t *statuses,
  3953. uint16_t event,
  3954. const char *event_string)
  3955. {
  3956. smartlist_t *strs;
  3957. char *s, *esc = NULL;
  3958. if (!EVENT_IS_INTERESTING(event) || !smartlist_len(statuses))
  3959. return 0;
  3960. strs = smartlist_new();
  3961. smartlist_add(strs, tor_strdup("650+"));
  3962. smartlist_add(strs, tor_strdup(event_string));
  3963. smartlist_add(strs, tor_strdup("\r\n"));
  3964. SMARTLIST_FOREACH(statuses, const routerstatus_t *, rs,
  3965. {
  3966. s = networkstatus_getinfo_helper_single(rs);
  3967. if (!s) continue;
  3968. smartlist_add(strs, s);
  3969. });
  3970. s = smartlist_join_strings(strs, "", 0, NULL);
  3971. write_escaped_data(s, strlen(s), &esc);
  3972. SMARTLIST_FOREACH(strs, char *, cp, tor_free(cp));
  3973. smartlist_free(strs);
  3974. tor_free(s);
  3975. send_control_event_string(event, ALL_FORMATS, esc);
  3976. send_control_event_string(event, ALL_FORMATS,
  3977. "650 OK\r\n");
  3978. tor_free(esc);
  3979. return 0;
  3980. }
  3981. /** Called when the routerstatus_ts <b>statuses</b> have changed: sends
  3982. * an NS event to any controller that cares. */
  3983. int
  3984. control_event_networkstatus_changed(smartlist_t *statuses)
  3985. {
  3986. return control_event_networkstatus_changed_helper(statuses, EVENT_NS, "NS");
  3987. }
  3988. /** Called when we get a new consensus networkstatus. Sends a NEWCONSENSUS
  3989. * event consisting of an NS-style line for each relay in the consensus. */
  3990. int
  3991. control_event_newconsensus(const networkstatus_t *consensus)
  3992. {
  3993. if (!control_event_is_interesting(EVENT_NEWCONSENSUS))
  3994. return 0;
  3995. return control_event_networkstatus_changed_helper(
  3996. consensus->routerstatus_list, EVENT_NEWCONSENSUS, "NEWCONSENSUS");
  3997. }
  3998. /** Called when we compute a new circuitbuildtimeout */
  3999. int
  4000. control_event_buildtimeout_set(buildtimeout_set_event_t type,
  4001. const char *args)
  4002. {
  4003. const char *type_string = NULL;
  4004. if (!control_event_is_interesting(EVENT_BUILDTIMEOUT_SET))
  4005. return 0;
  4006. switch (type) {
  4007. case BUILDTIMEOUT_SET_EVENT_COMPUTED:
  4008. type_string = "COMPUTED";
  4009. break;
  4010. case BUILDTIMEOUT_SET_EVENT_RESET:
  4011. type_string = "RESET";
  4012. break;
  4013. case BUILDTIMEOUT_SET_EVENT_SUSPENDED:
  4014. type_string = "SUSPENDED";
  4015. break;
  4016. case BUILDTIMEOUT_SET_EVENT_DISCARD:
  4017. type_string = "DISCARD";
  4018. break;
  4019. case BUILDTIMEOUT_SET_EVENT_RESUME:
  4020. type_string = "RESUME";
  4021. break;
  4022. default:
  4023. type_string = "UNKNOWN";
  4024. break;
  4025. }
  4026. send_control_event(EVENT_BUILDTIMEOUT_SET, ALL_FORMATS,
  4027. "650 BUILDTIMEOUT_SET %s %s\r\n",
  4028. type_string, args);
  4029. return 0;
  4030. }
  4031. /** Called when a signal has been processed from signal_callback */
  4032. int
  4033. control_event_signal(uintptr_t signal)
  4034. {
  4035. const char *signal_string = NULL;
  4036. if (!control_event_is_interesting(EVENT_SIGNAL))
  4037. return 0;
  4038. switch (signal) {
  4039. case SIGHUP:
  4040. signal_string = "RELOAD";
  4041. break;
  4042. case SIGUSR1:
  4043. signal_string = "DUMP";
  4044. break;
  4045. case SIGUSR2:
  4046. signal_string = "DEBUG";
  4047. break;
  4048. case SIGNEWNYM:
  4049. signal_string = "NEWNYM";
  4050. break;
  4051. case SIGCLEARDNSCACHE:
  4052. signal_string = "CLEARDNSCACHE";
  4053. break;
  4054. default:
  4055. log_warn(LD_BUG, "Unrecognized signal %lu in control_event_signal",
  4056. (unsigned long)signal);
  4057. return -1;
  4058. }
  4059. send_control_event(EVENT_SIGNAL, ALL_FORMATS, "650 SIGNAL %s\r\n",
  4060. signal_string);
  4061. return 0;
  4062. }
  4063. /** Called when a single local_routerstatus_t has changed: Sends an NS event
  4064. * to any controller that cares. */
  4065. int
  4066. control_event_networkstatus_changed_single(const routerstatus_t *rs)
  4067. {
  4068. smartlist_t *statuses;
  4069. int r;
  4070. if (!EVENT_IS_INTERESTING(EVENT_NS))
  4071. return 0;
  4072. statuses = smartlist_new();
  4073. smartlist_add(statuses, (void*)rs);
  4074. r = control_event_networkstatus_changed(statuses);
  4075. smartlist_free(statuses);
  4076. return r;
  4077. }
  4078. /** Our own router descriptor has changed; tell any controllers that care.
  4079. */
  4080. int
  4081. control_event_my_descriptor_changed(void)
  4082. {
  4083. send_control_event(EVENT_DESCCHANGED, ALL_FORMATS, "650 DESCCHANGED\r\n");
  4084. return 0;
  4085. }
  4086. /** Helper: sends a status event where <b>type</b> is one of
  4087. * EVENT_STATUS_{GENERAL,CLIENT,SERVER}, where <b>severity</b> is one of
  4088. * LOG_{NOTICE,WARN,ERR}, and where <b>format</b> is a printf-style format
  4089. * string corresponding to <b>args</b>. */
  4090. static int
  4091. control_event_status(int type, int severity, const char *format, va_list args)
  4092. {
  4093. char *user_buf = NULL;
  4094. char format_buf[160];
  4095. const char *status, *sev;
  4096. switch (type) {
  4097. case EVENT_STATUS_GENERAL:
  4098. status = "STATUS_GENERAL";
  4099. break;
  4100. case EVENT_STATUS_CLIENT:
  4101. status = "STATUS_CLIENT";
  4102. break;
  4103. case EVENT_STATUS_SERVER:
  4104. status = "STATUS_SERVER";
  4105. break;
  4106. default:
  4107. log_warn(LD_BUG, "Unrecognized status type %d", type);
  4108. return -1;
  4109. }
  4110. switch (severity) {
  4111. case LOG_NOTICE:
  4112. sev = "NOTICE";
  4113. break;
  4114. case LOG_WARN:
  4115. sev = "WARN";
  4116. break;
  4117. case LOG_ERR:
  4118. sev = "ERR";
  4119. break;
  4120. default:
  4121. log_warn(LD_BUG, "Unrecognized status severity %d", severity);
  4122. return -1;
  4123. }
  4124. if (tor_snprintf(format_buf, sizeof(format_buf), "650 %s %s",
  4125. status, sev)<0) {
  4126. log_warn(LD_BUG, "Format string too long.");
  4127. return -1;
  4128. }
  4129. tor_vasprintf(&user_buf, format, args);
  4130. send_control_event(type, ALL_FORMATS, "%s %s\r\n", format_buf, user_buf);
  4131. tor_free(user_buf);
  4132. return 0;
  4133. }
  4134. /** Format and send an EVENT_STATUS_GENERAL event whose main text is obtained
  4135. * by formatting the arguments using the printf-style <b>format</b>. */
  4136. int
  4137. control_event_general_status(int severity, const char *format, ...)
  4138. {
  4139. va_list ap;
  4140. int r;
  4141. if (!EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL))
  4142. return 0;
  4143. va_start(ap, format);
  4144. r = control_event_status(EVENT_STATUS_GENERAL, severity, format, ap);
  4145. va_end(ap);
  4146. return r;
  4147. }
  4148. /** Format and send an EVENT_STATUS_CLIENT event whose main text is obtained
  4149. * by formatting the arguments using the printf-style <b>format</b>. */
  4150. int
  4151. control_event_client_status(int severity, const char *format, ...)
  4152. {
  4153. va_list ap;
  4154. int r;
  4155. if (!EVENT_IS_INTERESTING(EVENT_STATUS_CLIENT))
  4156. return 0;
  4157. va_start(ap, format);
  4158. r = control_event_status(EVENT_STATUS_CLIENT, severity, format, ap);
  4159. va_end(ap);
  4160. return r;
  4161. }
  4162. /** Format and send an EVENT_STATUS_SERVER event whose main text is obtained
  4163. * by formatting the arguments using the printf-style <b>format</b>. */
  4164. int
  4165. control_event_server_status(int severity, const char *format, ...)
  4166. {
  4167. va_list ap;
  4168. int r;
  4169. if (!EVENT_IS_INTERESTING(EVENT_STATUS_SERVER))
  4170. return 0;
  4171. va_start(ap, format);
  4172. r = control_event_status(EVENT_STATUS_SERVER, severity, format, ap);
  4173. va_end(ap);
  4174. return r;
  4175. }
  4176. /** Called when the status of an entry guard with the given <b>nickname</b>
  4177. * and identity <b>digest</b> has changed to <b>status</b>: tells any
  4178. * controllers that care. */
  4179. int
  4180. control_event_guard(const char *nickname, const char *digest,
  4181. const char *status)
  4182. {
  4183. char hbuf[HEX_DIGEST_LEN+1];
  4184. base16_encode(hbuf, sizeof(hbuf), digest, DIGEST_LEN);
  4185. if (!EVENT_IS_INTERESTING(EVENT_GUARD))
  4186. return 0;
  4187. {
  4188. char buf[MAX_VERBOSE_NICKNAME_LEN+1];
  4189. const node_t *node = node_get_by_id(digest);
  4190. if (node) {
  4191. node_get_verbose_nickname(node, buf);
  4192. } else {
  4193. tor_snprintf(buf, sizeof(buf), "$%s~%s", hbuf, nickname);
  4194. }
  4195. send_control_event(EVENT_GUARD, ALL_FORMATS,
  4196. "650 GUARD ENTRY %s %s\r\n", buf, status);
  4197. }
  4198. return 0;
  4199. }
  4200. /** Called when a configuration option changes. This is generally triggered
  4201. * by SETCONF requests and RELOAD/SIGHUP signals. The <b>elements</b> is
  4202. * a smartlist_t containing (key, value, ...) pairs in sequence.
  4203. * <b>value</b> can be NULL. */
  4204. int
  4205. control_event_conf_changed(const smartlist_t *elements)
  4206. {
  4207. int i;
  4208. char *result;
  4209. smartlist_t *lines;
  4210. if (!EVENT_IS_INTERESTING(EVENT_CONF_CHANGED) ||
  4211. smartlist_len(elements) == 0) {
  4212. return 0;
  4213. }
  4214. lines = smartlist_new();
  4215. for (i = 0; i < smartlist_len(elements); i += 2) {
  4216. char *k = smartlist_get(elements, i);
  4217. char *v = smartlist_get(elements, i+1);
  4218. if (v == NULL) {
  4219. smartlist_add_asprintf(lines, "650-%s", k);
  4220. } else {
  4221. smartlist_add_asprintf(lines, "650-%s=%s", k, v);
  4222. }
  4223. }
  4224. result = smartlist_join_strings(lines, "\r\n", 0, NULL);
  4225. send_control_event(EVENT_CONF_CHANGED, 0,
  4226. "650-CONF_CHANGED\r\n%s\r\n650 OK\r\n", result);
  4227. tor_free(result);
  4228. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  4229. smartlist_free(lines);
  4230. return 0;
  4231. }
  4232. /** Helper: Return a newly allocated string containing a path to the
  4233. * file where we store our authentication cookie. */
  4234. char *
  4235. get_controller_cookie_file_name(void)
  4236. {
  4237. const or_options_t *options = get_options();
  4238. if (options->CookieAuthFile && strlen(options->CookieAuthFile)) {
  4239. return tor_strdup(options->CookieAuthFile);
  4240. } else {
  4241. return get_datadir_fname("control_auth_cookie");
  4242. }
  4243. }
  4244. /* Initialize the cookie-based authentication system of the
  4245. * ControlPort. If <b>enabled</b> is 0, then disable the cookie
  4246. * authentication system. */
  4247. int
  4248. init_control_cookie_authentication(int enabled)
  4249. {
  4250. char *fname = NULL;
  4251. int retval;
  4252. if (!enabled) {
  4253. authentication_cookie_is_set = 0;
  4254. return 0;
  4255. }
  4256. fname = get_controller_cookie_file_name();
  4257. retval = init_cookie_authentication(fname, "", /* no header */
  4258. AUTHENTICATION_COOKIE_LEN,
  4259. get_options()->CookieAuthFileGroupReadable,
  4260. &authentication_cookie,
  4261. &authentication_cookie_is_set);
  4262. tor_free(fname);
  4263. return retval;
  4264. }
  4265. /** A copy of the process specifier of Tor's owning controller, or
  4266. * NULL if this Tor instance is not currently owned by a process. */
  4267. static char *owning_controller_process_spec = NULL;
  4268. /** A process-termination monitor for Tor's owning controller, or NULL
  4269. * if this Tor instance is not currently owned by a process. */
  4270. static tor_process_monitor_t *owning_controller_process_monitor = NULL;
  4271. static void owning_controller_procmon_cb(void *unused) ATTR_NORETURN;
  4272. /** Process-termination monitor callback for Tor's owning controller
  4273. * process. */
  4274. static void
  4275. owning_controller_procmon_cb(void *unused)
  4276. {
  4277. (void)unused;
  4278. lost_owning_controller("process", "vanished");
  4279. }
  4280. /** Set <b>process_spec</b> as Tor's owning controller process.
  4281. * Exit on failure. */
  4282. void
  4283. monitor_owning_controller_process(const char *process_spec)
  4284. {
  4285. const char *msg;
  4286. tor_assert((owning_controller_process_spec == NULL) ==
  4287. (owning_controller_process_monitor == NULL));
  4288. if (owning_controller_process_spec != NULL) {
  4289. if ((process_spec != NULL) && !strcmp(process_spec,
  4290. owning_controller_process_spec)) {
  4291. /* Same process -- return now, instead of disposing of and
  4292. * recreating the process-termination monitor. */
  4293. return;
  4294. }
  4295. /* We are currently owned by a process, and we should no longer be
  4296. * owned by it. Free the process-termination monitor. */
  4297. tor_process_monitor_free(owning_controller_process_monitor);
  4298. owning_controller_process_monitor = NULL;
  4299. tor_free(owning_controller_process_spec);
  4300. owning_controller_process_spec = NULL;
  4301. }
  4302. tor_assert((owning_controller_process_spec == NULL) &&
  4303. (owning_controller_process_monitor == NULL));
  4304. if (process_spec == NULL)
  4305. return;
  4306. owning_controller_process_spec = tor_strdup(process_spec);
  4307. owning_controller_process_monitor =
  4308. tor_process_monitor_new(tor_libevent_get_base(),
  4309. owning_controller_process_spec,
  4310. LD_CONTROL,
  4311. owning_controller_procmon_cb, NULL,
  4312. &msg);
  4313. if (owning_controller_process_monitor == NULL) {
  4314. log_err(LD_BUG, "Couldn't create process-termination monitor for "
  4315. "owning controller: %s. Exiting.",
  4316. msg);
  4317. owning_controller_process_spec = NULL;
  4318. tor_cleanup();
  4319. exit(0);
  4320. }
  4321. }
  4322. /** Convert the name of a bootstrapping phase <b>s</b> into strings
  4323. * <b>tag</b> and <b>summary</b> suitable for display by the controller. */
  4324. static int
  4325. bootstrap_status_to_string(bootstrap_status_t s, const char **tag,
  4326. const char **summary)
  4327. {
  4328. switch (s) {
  4329. case BOOTSTRAP_STATUS_UNDEF:
  4330. *tag = "undef";
  4331. *summary = "Undefined";
  4332. break;
  4333. case BOOTSTRAP_STATUS_STARTING:
  4334. *tag = "starting";
  4335. *summary = "Starting";
  4336. break;
  4337. case BOOTSTRAP_STATUS_CONN_DIR:
  4338. *tag = "conn_dir";
  4339. *summary = "Connecting to directory server";
  4340. break;
  4341. case BOOTSTRAP_STATUS_HANDSHAKE:
  4342. *tag = "status_handshake";
  4343. *summary = "Finishing handshake";
  4344. break;
  4345. case BOOTSTRAP_STATUS_HANDSHAKE_DIR:
  4346. *tag = "handshake_dir";
  4347. *summary = "Finishing handshake with directory server";
  4348. break;
  4349. case BOOTSTRAP_STATUS_ONEHOP_CREATE:
  4350. *tag = "onehop_create";
  4351. *summary = "Establishing an encrypted directory connection";
  4352. break;
  4353. case BOOTSTRAP_STATUS_REQUESTING_STATUS:
  4354. *tag = "requesting_status";
  4355. *summary = "Asking for networkstatus consensus";
  4356. break;
  4357. case BOOTSTRAP_STATUS_LOADING_STATUS:
  4358. *tag = "loading_status";
  4359. *summary = "Loading networkstatus consensus";
  4360. break;
  4361. case BOOTSTRAP_STATUS_LOADING_KEYS:
  4362. *tag = "loading_keys";
  4363. *summary = "Loading authority key certs";
  4364. break;
  4365. case BOOTSTRAP_STATUS_REQUESTING_DESCRIPTORS:
  4366. *tag = "requesting_descriptors";
  4367. *summary = "Asking for relay descriptors";
  4368. break;
  4369. case BOOTSTRAP_STATUS_LOADING_DESCRIPTORS:
  4370. *tag = "loading_descriptors";
  4371. *summary = "Loading relay descriptors";
  4372. break;
  4373. case BOOTSTRAP_STATUS_CONN_OR:
  4374. *tag = "conn_or";
  4375. *summary = "Connecting to the Tor network";
  4376. break;
  4377. case BOOTSTRAP_STATUS_HANDSHAKE_OR:
  4378. *tag = "handshake_or";
  4379. *summary = "Finishing handshake with first hop";
  4380. break;
  4381. case BOOTSTRAP_STATUS_CIRCUIT_CREATE:
  4382. *tag = "circuit_create";
  4383. *summary = "Establishing a Tor circuit";
  4384. break;
  4385. case BOOTSTRAP_STATUS_DONE:
  4386. *tag = "done";
  4387. *summary = "Done";
  4388. break;
  4389. default:
  4390. // log_warn(LD_BUG, "Unrecognized bootstrap status code %d", s);
  4391. *tag = *summary = "unknown";
  4392. return -1;
  4393. }
  4394. return 0;
  4395. }
  4396. /** What percentage through the bootstrap process are we? We remember
  4397. * this so we can avoid sending redundant bootstrap status events, and
  4398. * so we can guess context for the bootstrap messages which are
  4399. * ambiguous. It starts at 'undef', but gets set to 'starting' while
  4400. * Tor initializes. */
  4401. static int bootstrap_percent = BOOTSTRAP_STATUS_UNDEF;
  4402. /** As bootstrap_percent, but holds the bootstrapping level at which we last
  4403. * logged a NOTICE-level message. We use this, plus BOOTSTRAP_PCT_INCREMENT,
  4404. * to avoid flooding the log with a new message every time we get a few more
  4405. * microdescriptors */
  4406. static int notice_bootstrap_percent = 0;
  4407. /** How many problems have we had getting to the next bootstrapping phase?
  4408. * These include failure to establish a connection to a Tor relay,
  4409. * failures to finish the TLS handshake, failures to validate the
  4410. * consensus document, etc. */
  4411. static int bootstrap_problems = 0;
  4412. /** We only tell the controller once we've hit a threshold of problems
  4413. * for the current phase. */
  4414. #define BOOTSTRAP_PROBLEM_THRESHOLD 10
  4415. /** When our bootstrapping progress level changes, but our bootstrapping
  4416. * status has not advanced, we only log at NOTICE when we have made at least
  4417. * this much progress.
  4418. */
  4419. #define BOOTSTRAP_PCT_INCREMENT 5
  4420. /** Called when Tor has made progress at bootstrapping its directory
  4421. * information and initial circuits.
  4422. *
  4423. * <b>status</b> is the new status, that is, what task we will be doing
  4424. * next. <b>progress</b> is zero if we just started this task, else it
  4425. * represents progress on the task. */
  4426. void
  4427. control_event_bootstrap(bootstrap_status_t status, int progress)
  4428. {
  4429. const char *tag, *summary;
  4430. char buf[BOOTSTRAP_MSG_LEN];
  4431. if (bootstrap_percent == BOOTSTRAP_STATUS_DONE)
  4432. return; /* already bootstrapped; nothing to be done here. */
  4433. /* special case for handshaking status, since our TLS handshaking code
  4434. * can't distinguish what the connection is going to be for. */
  4435. if (status == BOOTSTRAP_STATUS_HANDSHAKE) {
  4436. if (bootstrap_percent < BOOTSTRAP_STATUS_CONN_OR) {
  4437. status = BOOTSTRAP_STATUS_HANDSHAKE_DIR;
  4438. } else {
  4439. status = BOOTSTRAP_STATUS_HANDSHAKE_OR;
  4440. }
  4441. }
  4442. if (status > bootstrap_percent ||
  4443. (progress && progress > bootstrap_percent)) {
  4444. int loglevel = LOG_NOTICE;
  4445. bootstrap_status_to_string(status, &tag, &summary);
  4446. if (status <= bootstrap_percent &&
  4447. (progress < notice_bootstrap_percent + BOOTSTRAP_PCT_INCREMENT)) {
  4448. /* We log the message at info if the status hasn't advanced, and if less
  4449. * than BOOTSTRAP_PCT_INCREMENT progress has been made.
  4450. */
  4451. loglevel = LOG_INFO;
  4452. }
  4453. tor_log(loglevel, LD_CONTROL,
  4454. "Bootstrapped %d%%: %s", progress ? progress : status, summary);
  4455. tor_snprintf(buf, sizeof(buf),
  4456. "BOOTSTRAP PROGRESS=%d TAG=%s SUMMARY=\"%s\"",
  4457. progress ? progress : status, tag, summary);
  4458. tor_snprintf(last_sent_bootstrap_message,
  4459. sizeof(last_sent_bootstrap_message),
  4460. "NOTICE %s", buf);
  4461. control_event_client_status(LOG_NOTICE, "%s", buf);
  4462. if (status > bootstrap_percent) {
  4463. bootstrap_percent = status; /* new milestone reached */
  4464. }
  4465. if (progress > bootstrap_percent) {
  4466. /* incremental progress within a milestone */
  4467. bootstrap_percent = progress;
  4468. bootstrap_problems = 0; /* Progress! Reset our problem counter. */
  4469. }
  4470. if (loglevel == LOG_NOTICE &&
  4471. bootstrap_percent > notice_bootstrap_percent) {
  4472. /* Remember that we gave a notice at this level. */
  4473. notice_bootstrap_percent = bootstrap_percent;
  4474. }
  4475. }
  4476. }
  4477. /** Called when Tor has failed to make bootstrapping progress in a way
  4478. * that indicates a problem. <b>warn</b> gives a hint as to why, and
  4479. * <b>reason</b> provides an "or_conn_end_reason" tag. <b>or_conn</b>
  4480. * is the connection that caused this problem.
  4481. */
  4482. MOCK_IMPL(void,
  4483. control_event_bootstrap_problem, (const char *warn, int reason,
  4484. or_connection_t *or_conn))
  4485. {
  4486. int status = bootstrap_percent;
  4487. const char *tag = "", *summary = "";
  4488. char buf[BOOTSTRAP_MSG_LEN];
  4489. const char *recommendation = "ignore";
  4490. int severity;
  4491. /* bootstrap_percent must not be in "undefined" state here. */
  4492. tor_assert(status >= 0);
  4493. if (or_conn->have_noted_bootstrap_problem)
  4494. return;
  4495. or_conn->have_noted_bootstrap_problem = 1;
  4496. if (bootstrap_percent == 100)
  4497. return; /* already bootstrapped; nothing to be done here. */
  4498. bootstrap_problems++;
  4499. if (bootstrap_problems >= BOOTSTRAP_PROBLEM_THRESHOLD)
  4500. recommendation = "warn";
  4501. if (reason == END_OR_CONN_REASON_NO_ROUTE)
  4502. recommendation = "warn";
  4503. /* If we are using bridges and all our OR connections are now
  4504. closed, it means that we totally failed to connect to our
  4505. bridges. Throw a warning. */
  4506. if (get_options()->UseBridges && !any_other_active_or_conns(or_conn))
  4507. recommendation = "warn";
  4508. if (we_are_hibernating())
  4509. recommendation = "ignore";
  4510. while (status>=0 && bootstrap_status_to_string(status, &tag, &summary) < 0)
  4511. status--; /* find a recognized status string based on current progress */
  4512. status = bootstrap_percent; /* set status back to the actual number */
  4513. severity = !strcmp(recommendation, "warn") ? LOG_WARN : LOG_INFO;
  4514. log_fn(severity,
  4515. LD_CONTROL, "Problem bootstrapping. Stuck at %d%%: %s. (%s; %s; "
  4516. "count %d; recommendation %s)",
  4517. status, summary, warn,
  4518. orconn_end_reason_to_control_string(reason),
  4519. bootstrap_problems, recommendation);
  4520. connection_or_report_broken_states(severity, LD_HANDSHAKE);
  4521. tor_snprintf(buf, sizeof(buf),
  4522. "BOOTSTRAP PROGRESS=%d TAG=%s SUMMARY=\"%s\" WARNING=\"%s\" REASON=%s "
  4523. "COUNT=%d RECOMMENDATION=%s",
  4524. bootstrap_percent, tag, summary, warn,
  4525. orconn_end_reason_to_control_string(reason), bootstrap_problems,
  4526. recommendation);
  4527. tor_snprintf(last_sent_bootstrap_message,
  4528. sizeof(last_sent_bootstrap_message),
  4529. "WARN %s", buf);
  4530. control_event_client_status(LOG_WARN, "%s", buf);
  4531. }
  4532. /** We just generated a new summary of which countries we've seen clients
  4533. * from recently. Send a copy to the controller in case it wants to
  4534. * display it for the user. */
  4535. void
  4536. control_event_clients_seen(const char *controller_str)
  4537. {
  4538. send_control_event(EVENT_CLIENTS_SEEN, 0,
  4539. "650 CLIENTS_SEEN %s\r\n", controller_str);
  4540. }
  4541. /** A new pluggable transport called <b>transport_name</b> was
  4542. * launched on <b>addr</b>:<b>port</b>. <b>mode</b> is either
  4543. * "server" or "client" depending on the mode of the pluggable
  4544. * transport.
  4545. * "650" SP "TRANSPORT_LAUNCHED" SP Mode SP Name SP Address SP Port
  4546. */
  4547. void
  4548. control_event_transport_launched(const char *mode, const char *transport_name,
  4549. tor_addr_t *addr, uint16_t port)
  4550. {
  4551. send_control_event(EVENT_TRANSPORT_LAUNCHED, ALL_FORMATS,
  4552. "650 TRANSPORT_LAUNCHED %s %s %s %u\r\n",
  4553. mode, transport_name, fmt_addr(addr), port);
  4554. }
  4555. /** Convert rendezvous auth type to string for HS_DESC control events
  4556. */
  4557. const char *
  4558. rend_auth_type_to_string(rend_auth_type_t auth_type)
  4559. {
  4560. const char *str;
  4561. switch (auth_type) {
  4562. case REND_NO_AUTH:
  4563. str = "NO_AUTH";
  4564. break;
  4565. case REND_BASIC_AUTH:
  4566. str = "BASIC_AUTH";
  4567. break;
  4568. case REND_STEALTH_AUTH:
  4569. str = "STEALTH_AUTH";
  4570. break;
  4571. default:
  4572. str = "UNKNOWN";
  4573. }
  4574. return str;
  4575. }
  4576. /** Return a longname the node whose identity is <b>id_digest</b>. If
  4577. * node_get_by_id() returns NULL, base 16 encoding of <b>id_digest</b> is
  4578. * returned instead.
  4579. *
  4580. * This function is not thread-safe. Each call to this function invalidates
  4581. * previous values returned by this function.
  4582. */
  4583. MOCK_IMPL(const char *,
  4584. node_describe_longname_by_id,(const char *id_digest))
  4585. {
  4586. static char longname[MAX_VERBOSE_NICKNAME_LEN+1];
  4587. node_get_verbose_nickname_by_id(id_digest, longname);
  4588. return longname;
  4589. }
  4590. /** send HS_DESC requested event.
  4591. *
  4592. * <b>rend_query</b> is used to fetch requested onion address and auth type.
  4593. * <b>hs_dir</b> is the description of contacting hs directory.
  4594. * <b>desc_id_base32</b> is the ID of requested hs descriptor.
  4595. */
  4596. void
  4597. control_event_hs_descriptor_requested(const rend_data_t *rend_query,
  4598. const char *id_digest,
  4599. const char *desc_id_base32)
  4600. {
  4601. if (!id_digest || !rend_query || !desc_id_base32) {
  4602. log_warn(LD_BUG, "Called with rend_query==%p, "
  4603. "id_digest==%p, desc_id_base32==%p",
  4604. rend_query, id_digest, desc_id_base32);
  4605. return;
  4606. }
  4607. send_control_event(EVENT_HS_DESC, ALL_FORMATS,
  4608. "650 HS_DESC REQUESTED %s %s %s %s\r\n",
  4609. rend_query->onion_address,
  4610. rend_auth_type_to_string(rend_query->auth_type),
  4611. node_describe_longname_by_id(id_digest),
  4612. desc_id_base32);
  4613. }
  4614. /** send HS_DESC event after got response from hs directory.
  4615. *
  4616. * NOTE: this is an internal function used by following functions:
  4617. * control_event_hs_descriptor_received
  4618. * control_event_hs_descriptor_failed
  4619. *
  4620. * So do not call this function directly.
  4621. */
  4622. void
  4623. control_event_hs_descriptor_receive_end(const char *action,
  4624. const rend_data_t *rend_query,
  4625. const char *id_digest)
  4626. {
  4627. if (!action || !rend_query || !id_digest) {
  4628. log_warn(LD_BUG, "Called with action==%p, rend_query==%p, "
  4629. "id_digest==%p", action, rend_query, id_digest);
  4630. return;
  4631. }
  4632. send_control_event(EVENT_HS_DESC, ALL_FORMATS,
  4633. "650 HS_DESC %s %s %s %s\r\n",
  4634. action,
  4635. rend_query->onion_address,
  4636. rend_auth_type_to_string(rend_query->auth_type),
  4637. node_describe_longname_by_id(id_digest));
  4638. }
  4639. /** send HS_DESC RECEIVED event
  4640. *
  4641. * called when a we successfully received a hidden service descriptor.
  4642. */
  4643. void
  4644. control_event_hs_descriptor_received(const rend_data_t *rend_query,
  4645. const char *id_digest)
  4646. {
  4647. if (!rend_query || !id_digest) {
  4648. log_warn(LD_BUG, "Called with rend_query==%p, id_digest==%p",
  4649. rend_query, id_digest);
  4650. return;
  4651. }
  4652. control_event_hs_descriptor_receive_end("RECEIVED", rend_query, id_digest);
  4653. }
  4654. /** send HS_DESC FAILED event
  4655. *
  4656. * called when request for hidden service descriptor returned failure.
  4657. */
  4658. void
  4659. control_event_hs_descriptor_failed(const rend_data_t *rend_query,
  4660. const char *id_digest)
  4661. {
  4662. if (!rend_query || !id_digest) {
  4663. log_warn(LD_BUG, "Called with rend_query==%p, id_digest==%p",
  4664. rend_query, id_digest);
  4665. return;
  4666. }
  4667. control_event_hs_descriptor_receive_end("FAILED", rend_query, id_digest);
  4668. }
  4669. /** Free any leftover allocated memory of the control.c subsystem. */
  4670. void
  4671. control_free_all(void)
  4672. {
  4673. if (authentication_cookie) /* Free the auth cookie */
  4674. tor_free(authentication_cookie);
  4675. }
  4676. #ifdef TOR_UNIT_TESTS
  4677. /* For testing: change the value of global_event_mask */
  4678. void
  4679. control_testing_set_global_event_mask(uint64_t mask)
  4680. {
  4681. global_event_mask = mask;
  4682. }
  4683. #endif