control.c 121 KB

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