control.c 121 KB

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