control.c 144 KB

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