control.c 135 KB

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