control.c 105 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193
  1. /* Copyright 2004-2006 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. **/
  10. #include "or.h"
  11. #define STATE_IS_OPEN(s) ((s) == CONTROL_CONN_STATE_OPEN_V0 || \
  12. (s) == CONTROL_CONN_STATE_OPEN_V1)
  13. #define STATE_IS_V0(s) ((s) == CONTROL_CONN_STATE_NEEDAUTH_V0 || \
  14. (s) == CONTROL_CONN_STATE_OPEN_V0)
  15. /*
  16. * See control-spec.txt and control-spec-v0.txt for full details on
  17. * protocol(s).
  18. *
  19. */
  20. /* Recognized version 0 message type codes; do not add new codes to this list.
  21. * Version 0 is dead; version 1 doesn't use codes. */
  22. #define CONTROL0_CMD_ERROR 0x0000
  23. #define CONTROL0_CMD_DONE 0x0001
  24. #define CONTROL0_CMD_SETCONF 0x0002
  25. #define CONTROL0_CMD_GETCONF 0x0003
  26. #define CONTROL0_CMD_CONFVALUE 0x0004
  27. #define CONTROL0_CMD_SETEVENTS 0x0005
  28. #define CONTROL0_CMD_EVENT 0x0006
  29. #define CONTROL0_CMD_AUTHENTICATE 0x0007
  30. #define CONTROL0_CMD_SAVECONF 0x0008
  31. #define CONTROL0_CMD_SIGNAL 0x0009
  32. #define CONTROL0_CMD_MAPADDRESS 0x000A
  33. #define CONTROL0_CMD_GETINFO 0x000B
  34. #define CONTROL0_CMD_INFOVALUE 0x000C
  35. #define CONTROL0_CMD_EXTENDCIRCUIT 0x000D
  36. #define CONTROL0_CMD_ATTACHSTREAM 0x000E
  37. #define CONTROL0_CMD_POSTDESCRIPTOR 0x000F
  38. #define CONTROL0_CMD_FRAGMENTHEADER 0x0010
  39. #define CONTROL0_CMD_FRAGMENT 0x0011
  40. #define CONTROL0_CMD_REDIRECTSTREAM 0x0012
  41. #define CONTROL0_CMD_CLOSESTREAM 0x0013
  42. #define CONTROL0_CMD_CLOSECIRCUIT 0x0014
  43. #define _CONTROL0_CMD_MAX_RECOGNIZED 0x0014
  44. /* Recognized version 0 error codes. Do not expand. */
  45. #define ERR_UNSPECIFIED 0x0000
  46. #define ERR_INTERNAL 0x0001
  47. #define ERR_UNRECOGNIZED_TYPE 0x0002
  48. #define ERR_SYNTAX 0x0003
  49. #define ERR_UNRECOGNIZED_CONFIG_KEY 0x0004
  50. #define ERR_INVALID_CONFIG_VALUE 0x0005
  51. #define ERR_UNRECOGNIZED_EVENT_CODE 0x0006
  52. #define ERR_UNAUTHORIZED 0x0007
  53. #define ERR_REJECTED_AUTHENTICATION 0x0008
  54. #define ERR_RESOURCE_EXHAUSETED 0x0009
  55. #define ERR_NO_STREAM 0x000A
  56. #define ERR_NO_CIRC 0x000B
  57. #define ERR_NO_ROUTER 0x000C
  58. /* Recognized asynchronous event types. It's okay to expand this list
  59. * because it use used both as a list of v0 event types, and as indices
  60. * into the bitfield to determine which controllers want which events.
  61. */
  62. #define _EVENT_MIN 0x0001
  63. #define EVENT_CIRCUIT_STATUS 0x0001
  64. #define EVENT_STREAM_STATUS 0x0002
  65. #define EVENT_OR_CONN_STATUS 0x0003
  66. #define EVENT_BANDWIDTH_USED 0x0004
  67. #define EVENT_LOG_OBSOLETE 0x0005
  68. #define EVENT_NEW_DESC 0x0006
  69. #define EVENT_DEBUG_MSG 0x0007
  70. #define EVENT_INFO_MSG 0x0008
  71. #define EVENT_NOTICE_MSG 0x0009
  72. #define EVENT_WARN_MSG 0x000A
  73. #define EVENT_ERR_MSG 0x000B
  74. #define LAST_V0_EVENT 0x000B
  75. #define EVENT_ADDRMAP 0x000C
  76. #define EVENT_AUTHDIR_NEWDESCS 0x000D
  77. #define EVENT_DESCCHANGED 0x000E
  78. #define _EVENT_MAX 0x000E
  79. /** Array mapping from message type codes to human-readable message
  80. * type names. Used for compatibility with version 0 of the control
  81. * protocol. Do not add new items to this list. */
  82. static const char * CONTROL0_COMMANDS[_CONTROL0_CMD_MAX_RECOGNIZED+1] = {
  83. "error",
  84. "done",
  85. "setconf",
  86. "getconf",
  87. "confvalue",
  88. "setevents",
  89. "events",
  90. "authenticate",
  91. "saveconf",
  92. "signal",
  93. "mapaddress",
  94. "getinfo",
  95. "infovalue",
  96. "extendcircuit",
  97. "attachstream",
  98. "postdescriptor",
  99. "fragmentheader",
  100. "fragment",
  101. "redirectstream",
  102. "closestream",
  103. "closecircuit",
  104. };
  105. /** Bitfield: The bit 1&lt;&lt;e is set if <b>any</b> open control
  106. * connection is interested in events of type <b>e</b>. We use this
  107. * so that we can decide to skip generating event messages that nobody
  108. * has interest in without having to walk over the global connection
  109. * list to find out.
  110. **/
  111. static uint32_t global_event_mask0 = 0;
  112. static uint32_t global_event_mask1long = 0;
  113. static uint32_t global_event_mask1short = 0;
  114. /** True iff we have disabled log messages from being sent to the controller */
  115. static int disable_log_messages = 0;
  116. /** Macro: true if any control connection is interested in events of type
  117. * <b>e</b>. */
  118. #define EVENT_IS_INTERESTING0(e) (global_event_mask0 & (1<<(e)))
  119. #define EVENT_IS_INTERESTING1(e) \
  120. ((global_event_mask1long|global_event_mask1short) & (1<<(e)))
  121. #define EVENT_IS_INTERESTING1L(e) (global_event_mask1long & (1<<(e)))
  122. #define EVENT_IS_INTERESTING1S(e) (global_event_mask1short & (1<<(e)))
  123. #define EVENT_IS_INTERESTING(e) \
  124. ((global_event_mask0|global_event_mask1short|global_event_mask1long) \
  125. & (1<<(e)))
  126. /** If we're using cookie-type authentication, how long should our cookies be?
  127. */
  128. #define AUTHENTICATION_COOKIE_LEN 32
  129. /** If true, we've set authentication_cookie to a secret code and
  130. * stored it to disk. */
  131. static int authentication_cookie_is_set = 0;
  132. static char authentication_cookie[AUTHENTICATION_COOKIE_LEN];
  133. typedef enum {
  134. SHORT_NAMES,LONG_NAMES,ALL_NAMES
  135. } name_type_t;
  136. static void connection_printf_to_buf(control_connection_t *conn,
  137. const char *format, ...)
  138. CHECK_PRINTF(2,3);
  139. /*static*/ size_t write_escaped_data(const char *data, size_t len,
  140. int translate_newlines, char **out);
  141. /*static*/ size_t read_escaped_data(const char *data, size_t len,
  142. int translate_newlines, char **out);
  143. static void send_control0_message(control_connection_t *conn, uint16_t type,
  144. uint32_t len, const char *body);
  145. static void send_control_done(control_connection_t *conn);
  146. static void send_control_done2(control_connection_t *conn, const char *msg,
  147. size_t len);
  148. static void send_control0_error(control_connection_t *conn, uint16_t error,
  149. const char *message);
  150. static void send_control0_event(uint16_t event, uint32_t len,
  151. const char *body);
  152. static void send_control1_event(uint16_t event, name_type_t which,
  153. const char *format, ...)
  154. CHECK_PRINTF(3,4);
  155. static int handle_control_setconf(control_connection_t *conn, uint32_t len,
  156. char *body);
  157. static int handle_control_resetconf(control_connection_t *conn, uint32_t len,
  158. char *body);
  159. static int handle_control_getconf(control_connection_t *conn, uint32_t len,
  160. const char *body);
  161. static int handle_control_setevents(control_connection_t *conn, uint32_t len,
  162. const char *body);
  163. static int handle_control_authenticate(control_connection_t *conn,
  164. uint32_t len,
  165. const char *body);
  166. static int handle_control_saveconf(control_connection_t *conn, uint32_t len,
  167. const char *body);
  168. static int handle_control_signal(control_connection_t *conn, uint32_t len,
  169. const char *body);
  170. static int handle_control_mapaddress(control_connection_t *conn, uint32_t len,
  171. const char *body);
  172. static int handle_control_getinfo(control_connection_t *conn, uint32_t len,
  173. const char *body);
  174. static int handle_control_extendcircuit(control_connection_t *conn,
  175. uint32_t len,
  176. const char *body);
  177. static int handle_control_setpurpose(control_connection_t *conn,
  178. int for_circuits,
  179. uint32_t len, const char *body);
  180. static int handle_control_attachstream(control_connection_t *conn,
  181. uint32_t len,
  182. const char *body);
  183. static int handle_control_postdescriptor(control_connection_t *conn,
  184. uint32_t len,
  185. const char *body);
  186. static int handle_control_redirectstream(control_connection_t *conn,
  187. uint32_t len,
  188. const char *body);
  189. static int handle_control_closestream(control_connection_t *conn, uint32_t len,
  190. const char *body);
  191. static int handle_control_closecircuit(control_connection_t *conn,
  192. uint32_t len,
  193. const char *body);
  194. static int handle_control_usefeature(control_connection_t *conn,
  195. uint32_t len,
  196. const char *body);
  197. static int write_stream_target_to_buf(edge_connection_t *conn, char *buf,
  198. size_t len);
  199. static void orconn_target_get_name(int long_names, char *buf, size_t len,
  200. or_connection_t *conn);
  201. /** Given a possibly invalid message type code <b>cmd</b>, return a
  202. * human-readable string equivalent. */
  203. static INLINE const char *
  204. control_cmd_to_string(uint16_t cmd)
  205. {
  206. return (cmd<=_CONTROL0_CMD_MAX_RECOGNIZED) ?
  207. CONTROL0_COMMANDS[cmd] : "Unknown";
  208. }
  209. /** Given a control event code for a message event, return the corresponding
  210. * log severity. */
  211. static INLINE int
  212. event_to_log_severity(int event)
  213. {
  214. switch (event) {
  215. case EVENT_DEBUG_MSG: return LOG_DEBUG;
  216. case EVENT_INFO_MSG: return LOG_INFO;
  217. case EVENT_NOTICE_MSG: return LOG_NOTICE;
  218. case EVENT_WARN_MSG: return LOG_WARN;
  219. case EVENT_ERR_MSG: return LOG_ERR;
  220. default: return -1;
  221. }
  222. }
  223. /** Given a log severity, return the corresponding control event code. */
  224. static INLINE int
  225. log_severity_to_event(int severity)
  226. {
  227. switch (severity) {
  228. case LOG_DEBUG: return EVENT_DEBUG_MSG;
  229. case LOG_INFO: return EVENT_INFO_MSG;
  230. case LOG_NOTICE: return EVENT_NOTICE_MSG;
  231. case LOG_WARN: return EVENT_WARN_MSG;
  232. case LOG_ERR: return EVENT_ERR_MSG;
  233. default: return -1;
  234. }
  235. }
  236. /** Set <b>global_event_mask*</b> to the bitwise OR of each live control
  237. * connection's event_mask field. */
  238. void
  239. control_update_global_event_mask(void)
  240. {
  241. connection_t **conns;
  242. int n_conns, i;
  243. global_event_mask0 = 0;
  244. global_event_mask1short = 0;
  245. global_event_mask1long = 0;
  246. get_connection_array(&conns, &n_conns);
  247. for (i = 0; i < n_conns; ++i) {
  248. if (conns[i]->type == CONN_TYPE_CONTROL &&
  249. STATE_IS_OPEN(conns[i]->state)) {
  250. control_connection_t *conn = TO_CONTROL_CONN(conns[i]);
  251. if (STATE_IS_V0(conn->_base.state))
  252. global_event_mask0 |= conn->event_mask;
  253. else if (conn->use_long_names)
  254. global_event_mask1long |= conn->event_mask;
  255. else
  256. global_event_mask1short |= conn->event_mask;
  257. }
  258. }
  259. control_adjust_event_log_severity();
  260. }
  261. /** Adjust the log severities that result in control_event_logmsg being called
  262. * to match the severity of log messages that any controllers are interested
  263. * in. */
  264. void
  265. control_adjust_event_log_severity(void)
  266. {
  267. int i;
  268. int min_log_event=EVENT_ERR_MSG, max_log_event=EVENT_DEBUG_MSG;
  269. for (i = EVENT_DEBUG_MSG; i <= EVENT_ERR_MSG; ++i) {
  270. if (EVENT_IS_INTERESTING(i)) {
  271. min_log_event = i;
  272. break;
  273. }
  274. }
  275. for (i = EVENT_ERR_MSG; i >= EVENT_DEBUG_MSG; --i) {
  276. if (EVENT_IS_INTERESTING(i)) {
  277. max_log_event = i;
  278. break;
  279. }
  280. }
  281. if (EVENT_IS_INTERESTING(EVENT_LOG_OBSOLETE)) {
  282. if (min_log_event > EVENT_NOTICE_MSG)
  283. min_log_event = EVENT_NOTICE_MSG;
  284. if (max_log_event < EVENT_ERR_MSG)
  285. max_log_event = EVENT_ERR_MSG;
  286. }
  287. change_callback_log_severity(event_to_log_severity(min_log_event),
  288. event_to_log_severity(max_log_event),
  289. control_event_logmsg);
  290. }
  291. /** Append a NUL-terminated string <b>s</b> to the end of
  292. * <b>conn</b>-\>outbuf
  293. */
  294. static INLINE void
  295. connection_write_str_to_buf(const char *s, control_connection_t *conn)
  296. {
  297. size_t len = strlen(s);
  298. connection_write_to_buf(s, len, TO_CONN(conn));
  299. }
  300. /** Given a <b>len</b>-character string in <b>data</b>, made of lines
  301. * terminated by CRLF, allocate a new string in *<b>out</b>, and copy
  302. * the contents of <b>data</b> into *<b>out</b>, adding a period
  303. * before any period that that appears at the start of a line, and
  304. * adding a period-CRLF line at the end. If <b>translate_newlines</b>
  305. * is true, replace all LF characters sequences with CRLF. Return the
  306. * number of bytes in *<b>out</b>.
  307. */
  308. /* static */ size_t
  309. write_escaped_data(const char *data, size_t len, int translate_newlines,
  310. char **out)
  311. {
  312. size_t sz_out = len+8;
  313. char *outp;
  314. const char *end;
  315. int i;
  316. int start_of_line;
  317. for (i=0; i<(int)len; ++i) {
  318. if (data[i]== '\n')
  319. sz_out += 2; /* Maybe add a CR; maybe add a dot. */
  320. }
  321. *out = outp = tor_malloc(sz_out+1);
  322. end = data+len;
  323. start_of_line = 1;
  324. while (data < end) {
  325. if (*data == '\n') {
  326. if (translate_newlines)
  327. *outp++ = '\r';
  328. start_of_line = 1;
  329. } else if (*data == '.') {
  330. if (start_of_line) {
  331. start_of_line = 0;
  332. *outp++ = '.';
  333. }
  334. } else {
  335. start_of_line = 0;
  336. }
  337. *outp++ = *data++;
  338. }
  339. if (outp < *out+2 || memcmp(outp-2, "\r\n", 2)) {
  340. *outp++ = '\r';
  341. *outp++ = '\n';
  342. }
  343. *outp++ = '.';
  344. *outp++ = '\r';
  345. *outp++ = '\n';
  346. *outp = '\0'; /* NUL-terminate just in case. */
  347. tor_assert((outp - *out) <= (int)sz_out);
  348. return outp - *out;
  349. }
  350. /** Given a <b>len</b>-character string in <b>data</b>, made of lines
  351. * terminated by CRLF, allocate a new string in *<b>out</b>, and copy
  352. * the contents of <b>data</b> into *<b>out</b>, removing any period
  353. * that appears at the start of a line. If <b>translate_newlines</b>
  354. * is true, replace all CRLF sequences with LF. Return the number of
  355. * bytes in *<b>out</b>. */
  356. /*static*/ size_t
  357. read_escaped_data(const char *data, size_t len, int translate_newlines,
  358. char **out)
  359. {
  360. char *outp;
  361. const char *next;
  362. const char *end;
  363. *out = outp = tor_malloc(len+1);
  364. end = data+len;
  365. while (data < end) {
  366. if (*data == '.')
  367. ++data;
  368. if (translate_newlines)
  369. next = tor_memmem(data, end-data, "\r\n", 2);
  370. else
  371. next = tor_memmem(data, end-data, "\r\n.", 3);
  372. if (next) {
  373. memcpy(outp, data, next-data);
  374. outp += (next-data);
  375. data = next+2;
  376. } else {
  377. memcpy(outp, data, end-data);
  378. outp += (end-data);
  379. *outp = '\0';
  380. return outp - *out;
  381. }
  382. if (translate_newlines) {
  383. *outp++ = '\n';
  384. } else {
  385. *outp++ = '\r';
  386. *outp++ = '\n';
  387. }
  388. }
  389. *outp = '\0';
  390. return outp - *out;
  391. }
  392. /** Given a pointer to a string starting at <b>start</b> containing
  393. * <b>in_len_max</b> characters, decode a string beginning with a single
  394. * quote, containing any number of non-quote characters or characters escaped
  395. * with a backslash, and ending with a final quote. Place the resulting
  396. * string (unquoted, unescaped) into a newly allocated string in *<b>out</b>;
  397. * store its length in <b>out_len</b>. On success, return a pointer to the
  398. * character immediately following the escaped string. On failure, return
  399. * NULL. */
  400. static const char *
  401. get_escaped_string(const char *start, size_t in_len_max,
  402. char **out, size_t *out_len)
  403. {
  404. const char *cp, *end;
  405. char *outp;
  406. size_t len=0;
  407. if (*start != '\"')
  408. return NULL;
  409. cp = start+1;
  410. end = start+in_len_max;
  411. /* Calculate length. */
  412. while (1) {
  413. if (cp >= end)
  414. return NULL;
  415. else if (*cp == '\\') {
  416. if (++cp == end)
  417. return NULL; /* Can't escape EOS. */
  418. ++cp;
  419. ++len;
  420. } else if (*cp == '\"') {
  421. break;
  422. } else {
  423. ++cp;
  424. ++len;
  425. }
  426. }
  427. end = cp;
  428. outp = *out = tor_malloc(len+1);
  429. *out_len = len;
  430. cp = start+1;
  431. while (cp < end) {
  432. if (*cp == '\\')
  433. ++cp;
  434. *outp++ = *cp++;
  435. }
  436. *outp = '\0';
  437. tor_assert((outp - *out) == (int)*out_len);
  438. return end+1;
  439. }
  440. /** Acts like sprintf, but writes its formatted string to the end of
  441. * <b>conn</b>-\>outbuf. The message may be truncated if it is too long,
  442. * but it will always end with a CRLF sequence.
  443. *
  444. * Currently the length of the message is limited to 1024 (including the
  445. * ending \n\r\0. */
  446. static void
  447. connection_printf_to_buf(control_connection_t *conn, const char *format, ...)
  448. {
  449. #define CONNECTION_PRINTF_TO_BUF_BUFFERSIZE 1024
  450. va_list ap;
  451. char buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE];
  452. int r;
  453. size_t len;
  454. va_start(ap,format);
  455. r = tor_vsnprintf(buf, sizeof(buf), format, ap);
  456. va_end(ap);
  457. len = strlen(buf);
  458. if (memcmp("\r\n\0", buf+len-2, 3)) {
  459. buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE-1] = '\0';
  460. buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE-2] = '\n';
  461. buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE-3] = '\r';
  462. }
  463. connection_write_to_buf(buf, len, TO_CONN(conn));
  464. }
  465. /** Send a message of type <b>type</b> containing <b>len</b> bytes
  466. * from <b>body</b> along the control connection <b>conn</b> */
  467. static void
  468. send_control0_message(control_connection_t *conn, uint16_t type, uint32_t len,
  469. const char *body)
  470. {
  471. char buf[10];
  472. tor_assert(conn);
  473. tor_assert(STATE_IS_V0(conn->_base.state));
  474. tor_assert(len || !body);
  475. tor_assert(type <= _CONTROL0_CMD_MAX_RECOGNIZED);
  476. if (len < 65536) {
  477. set_uint16(buf, htons(len));
  478. set_uint16(buf+2, htons(type));
  479. connection_write_to_buf(buf, 4, TO_CONN(conn));
  480. if (len)
  481. connection_write_to_buf(body, len, TO_CONN(conn));
  482. } else {
  483. set_uint16(buf, htons(65535));
  484. set_uint16(buf+2, htons(CONTROL0_CMD_FRAGMENTHEADER));
  485. set_uint16(buf+4, htons(type));
  486. set_uint32(buf+6, htonl(len));
  487. connection_write_to_buf(buf, 10, TO_CONN(conn));
  488. connection_write_to_buf(body, 65535-6, TO_CONN(conn));
  489. len -= (65535-6);
  490. body += (65535-6);
  491. while (len) {
  492. size_t chunklen = (len<65535)?len:65535;
  493. set_uint16(buf, htons((uint16_t)chunklen));
  494. set_uint16(buf+2, htons(CONTROL0_CMD_FRAGMENT));
  495. connection_write_to_buf(buf, 4, TO_CONN(conn));
  496. connection_write_to_buf(body, chunklen, TO_CONN(conn));
  497. len -= chunklen;
  498. body += chunklen;
  499. }
  500. }
  501. }
  502. /** Send a "DONE" message down the control connection <b>conn</b> */
  503. static void
  504. send_control_done(control_connection_t *conn)
  505. {
  506. if (STATE_IS_V0(conn->_base.state)) {
  507. send_control0_message(conn, CONTROL0_CMD_DONE, 0, NULL);
  508. } else {
  509. connection_write_str_to_buf("250 OK\r\n", conn);
  510. }
  511. }
  512. /** Send a "DONE" message down the v0 control message <b>conn</b>, with body
  513. * as provided in the <b>len</b> bytes at <b>msg</b>.
  514. */
  515. static void
  516. send_control_done2(control_connection_t *conn, const char *msg, size_t len)
  517. {
  518. if (len==0)
  519. len = strlen(msg);
  520. send_control0_message(conn, CONTROL0_CMD_DONE, len, msg);
  521. }
  522. /** Send an error message with error code <b>error</b> and body
  523. * <b>message</b> down the connection <b>conn</b> */
  524. static void
  525. send_control0_error(control_connection_t *conn, uint16_t error,
  526. const char *message)
  527. {
  528. char buf[256];
  529. size_t len;
  530. set_uint16(buf, htons(error));
  531. len = strlen(message);
  532. tor_assert(len < (256-2));
  533. memcpy(buf+2, message, len);
  534. send_control0_message(conn, CONTROL0_CMD_ERROR, (uint16_t)(len+2), buf);
  535. }
  536. /** Send an 'event' message of event type <b>event</b>, containing
  537. * <b>len</b> bytes in <b>body</b> to every control connection that
  538. * is interested in it. */
  539. static void
  540. send_control0_event(uint16_t event, uint32_t len, const char *body)
  541. {
  542. connection_t **conns;
  543. int n_conns, i;
  544. size_t buflen;
  545. char *buf;
  546. tor_assert(event >= _EVENT_MIN && event <= LAST_V0_EVENT);
  547. buflen = len + 2;
  548. buf = tor_malloc_zero(buflen);
  549. set_uint16(buf, htons(event));
  550. memcpy(buf+2, body, len);
  551. get_connection_array(&conns, &n_conns);
  552. for (i = 0; i < n_conns; ++i) {
  553. if (conns[i]->type == CONN_TYPE_CONTROL &&
  554. !conns[i]->marked_for_close &&
  555. conns[i]->state == CONTROL_CONN_STATE_OPEN_V0) {
  556. control_connection_t *control_conn = TO_CONTROL_CONN(conns[i]);
  557. if (control_conn->event_mask & (1<<event)) {
  558. send_control0_message(control_conn, CONTROL0_CMD_EVENT, buflen, buf);
  559. if (event == EVENT_ERR_MSG)
  560. _connection_controller_force_write(control_conn);
  561. }
  562. }
  563. }
  564. tor_free(buf);
  565. }
  566. /* Send an event to all v1 controllers that are listening for code
  567. * <b>event</b>. The event's body is given by <b>msg</b>. */
  568. static void
  569. send_control1_event_string(uint16_t event, name_type_t which, const char *msg)
  570. {
  571. connection_t **conns;
  572. int n_conns, i;
  573. tor_assert(event >= _EVENT_MIN && event <= _EVENT_MAX);
  574. get_connection_array(&conns, &n_conns);
  575. for (i = 0; i < n_conns; ++i) {
  576. if (conns[i]->type == CONN_TYPE_CONTROL &&
  577. !conns[i]->marked_for_close &&
  578. conns[i]->state == CONTROL_CONN_STATE_OPEN_V1) {
  579. control_connection_t *control_conn = TO_CONTROL_CONN(conns[i]);
  580. if (which == SHORT_NAMES) {
  581. if (control_conn->use_long_names)
  582. continue;
  583. } else if (which == LONG_NAMES) {
  584. if (! control_conn->use_long_names)
  585. continue;
  586. }
  587. if (control_conn->event_mask & (1<<event)) {
  588. connection_write_to_buf(msg, strlen(msg), TO_CONN(control_conn));
  589. if (event == EVENT_ERR_MSG)
  590. _connection_controller_force_write(control_conn);
  591. }
  592. }
  593. }
  594. }
  595. /* Send an event to all v1 controllers that are listening for code
  596. * <b>event</b>. The event's body is created by the printf-style format in
  597. * <b>format</b>, and other arguments as provided.
  598. *
  599. * Currently the length of the message is limited to 1024 (including the
  600. * ending \n\r\0. */
  601. static void
  602. send_control1_event(uint16_t event, name_type_t which, const char *format, ...)
  603. {
  604. #define SEND_CONTROL1_EVENT_BUFFERSIZE 1024
  605. int r;
  606. char buf[SEND_CONTROL1_EVENT_BUFFERSIZE]; /* XXXX Length */
  607. va_list ap;
  608. size_t len;
  609. va_start(ap, format);
  610. r = tor_vsnprintf(buf, sizeof(buf), format, ap);
  611. va_end(ap);
  612. len = strlen(buf);
  613. if (memcmp("\r\n\0", buf+len-2, 3)) {
  614. /* if it is not properly terminated, do it now */
  615. buf[SEND_CONTROL1_EVENT_BUFFERSIZE-1] = '\0';
  616. buf[SEND_CONTROL1_EVENT_BUFFERSIZE-2] = '\n';
  617. buf[SEND_CONTROL1_EVENT_BUFFERSIZE-3] = '\r';
  618. }
  619. send_control1_event_string(event, which, buf);
  620. }
  621. /** Given a text circuit <b>id</b>, return the corresponding circuit. */
  622. static origin_circuit_t *
  623. get_circ(const char *id)
  624. {
  625. unsigned long n_id;
  626. int ok;
  627. n_id = tor_parse_ulong(id, 10, 0, ULONG_MAX, &ok, NULL);
  628. if (!ok)
  629. return NULL;
  630. return circuit_get_by_global_id(n_id);
  631. }
  632. /** Given a text stream <b>id</b>, return the corresponding AP connection. */
  633. static edge_connection_t *
  634. get_stream(const char *id)
  635. {
  636. unsigned long n_id;
  637. int ok;
  638. edge_connection_t *conn;
  639. n_id = tor_parse_ulong(id, 10, 0, ULONG_MAX, &ok, NULL);
  640. if (!ok)
  641. return NULL;
  642. conn = connection_get_by_global_id(n_id);
  643. if (!conn || conn->_base.type != CONN_TYPE_AP)
  644. return NULL;
  645. return conn;
  646. }
  647. /** Helper for setconf and resetconf. Acts like setconf, except
  648. * it passes <b>use_defaults</b> on to options_trial_assign().
  649. */
  650. static int
  651. control_setconf_helper(control_connection_t *conn, uint32_t len, char *body,
  652. int use_defaults, int clear_first)
  653. {
  654. int r;
  655. config_line_t *lines=NULL;
  656. char *start = body;
  657. char *errstring = NULL;
  658. int v0 = STATE_IS_V0(conn->_base.state);
  659. if (!v0) {
  660. char *config = tor_malloc(len+1);
  661. char *outp = config;
  662. while (*body) {
  663. char *eq = body;
  664. while (!TOR_ISSPACE(*eq) && *eq != '=')
  665. ++eq;
  666. memcpy(outp, body, eq-body);
  667. outp += (eq-body);
  668. *outp++ = ' ';
  669. body = eq+1;
  670. if (*eq == '=') {
  671. if (*body != '\"') {
  672. while (!TOR_ISSPACE(*body))
  673. *outp++ = *body++;
  674. } else {
  675. char *val;
  676. size_t val_len;
  677. body = (char*)get_escaped_string(body, (len - (body-start)),
  678. &val, &val_len);
  679. if (!body) {
  680. connection_write_str_to_buf("551 Couldn't parse string\r\n", conn);
  681. tor_free(config);
  682. return 0;
  683. }
  684. memcpy(outp, val, val_len);
  685. outp += val_len;
  686. tor_free(val);
  687. }
  688. }
  689. while (TOR_ISSPACE(*body))
  690. ++body;
  691. *outp++ = '\n';
  692. }
  693. *outp = '\0';
  694. if (config_get_lines(config, &lines) < 0) {
  695. log_warn(LD_CONTROL,"Controller gave us config lines we can't parse.");
  696. connection_write_str_to_buf("551 Couldn't parse configuration\r\n",
  697. conn);
  698. tor_free(config);
  699. return 0;
  700. }
  701. tor_free(config);
  702. } else {
  703. if (config_get_lines(body, &lines) < 0) {
  704. log_warn(LD_CONTROL,
  705. "V0 controller gave us config lines we can't parse.");
  706. send_control0_error(conn, ERR_SYNTAX, "Couldn't parse configuration");
  707. return 0;
  708. }
  709. }
  710. if ((r=options_trial_assign(lines, use_defaults,
  711. clear_first, &errstring)) < 0) {
  712. int v0_err;
  713. const char *msg;
  714. log_warn(LD_CONTROL,
  715. "Controller gave us config lines that didn't validate: %s.",
  716. errstring);
  717. switch (r) {
  718. case -1:
  719. v0_err = ERR_UNRECOGNIZED_CONFIG_KEY;
  720. msg = "552 Unrecognized option";
  721. break;
  722. case -2:
  723. v0_err = ERR_INVALID_CONFIG_VALUE;
  724. msg = "513 Unacceptable option value";
  725. break;
  726. case -3:
  727. v0_err = ERR_INVALID_CONFIG_VALUE;
  728. msg = "553 Transition not allowed";
  729. break;
  730. case -4:
  731. default:
  732. v0_err = ERR_INVALID_CONFIG_VALUE;
  733. msg = "553 Unable to set option";
  734. break;
  735. }
  736. if (v0) {
  737. send_control0_error(conn, v0_err, msg);
  738. } else {
  739. connection_printf_to_buf(conn, "%s: %s\r\n", msg, errstring);
  740. }
  741. config_free_lines(lines);
  742. tor_free(errstring);
  743. return 0;
  744. }
  745. config_free_lines(lines);
  746. send_control_done(conn);
  747. return 0;
  748. }
  749. /** Called when we receive a SETCONF message: parse the body and try
  750. * to update our configuration. Reply with a DONE or ERROR message. */
  751. static int
  752. handle_control_setconf(control_connection_t *conn, uint32_t len, char *body)
  753. {
  754. return control_setconf_helper(conn, len, body, 0, 1);
  755. }
  756. /** Called when we receive a RESETCONF message: parse the body and try
  757. * to update our configuration. Reply with a DONE or ERROR message. */
  758. static int
  759. handle_control_resetconf(control_connection_t *conn, uint32_t len, char *body)
  760. {
  761. int v0 = STATE_IS_V0(conn->_base.state);
  762. tor_assert(!v0);
  763. return control_setconf_helper(conn, len, body, 1, 1);
  764. }
  765. /** Called when we receive a GETCONF message. Parse the request, and
  766. * reply with a CONFVALUE or an ERROR message */
  767. static int
  768. handle_control_getconf(control_connection_t *conn, uint32_t body_len,
  769. const char *body)
  770. {
  771. smartlist_t *questions = NULL;
  772. smartlist_t *answers = NULL;
  773. smartlist_t *unrecognized = NULL;
  774. char *msg = NULL;
  775. size_t msg_len;
  776. or_options_t *options = get_options();
  777. int v0 = STATE_IS_V0(conn->_base.state);
  778. questions = smartlist_create();
  779. (void) body_len; /* body is nul-terminated; so we can ignore len. */
  780. if (v0) {
  781. smartlist_split_string(questions, body, "\n",
  782. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  783. } else {
  784. smartlist_split_string(questions, body, " ",
  785. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  786. }
  787. answers = smartlist_create();
  788. unrecognized = smartlist_create();
  789. SMARTLIST_FOREACH(questions, char *, q,
  790. {
  791. if (!option_is_recognized(q)) {
  792. if (v0) {
  793. send_control0_error(conn, ERR_UNRECOGNIZED_CONFIG_KEY, q);
  794. goto done;
  795. } else {
  796. smartlist_add(unrecognized, q);
  797. }
  798. } else {
  799. config_line_t *answer = option_get_assignment(options,q);
  800. if (!v0 && !answer) {
  801. const char *name = option_get_canonical_name(q);
  802. size_t alen = strlen(name)+8;
  803. char *astr = tor_malloc(alen);
  804. tor_snprintf(astr, alen, "250-%s\r\n", name);
  805. smartlist_add(answers, astr);
  806. }
  807. while (answer) {
  808. config_line_t *next;
  809. size_t alen = strlen(answer->key)+strlen(answer->value)+8;
  810. char *astr = tor_malloc(alen);
  811. if (v0)
  812. tor_snprintf(astr, alen, "%s %s\n", answer->key, answer->value);
  813. else
  814. tor_snprintf(astr, alen, "250-%s=%s\r\n",
  815. answer->key, answer->value);
  816. smartlist_add(answers, astr);
  817. next = answer->next;
  818. tor_free(answer->key);
  819. tor_free(answer->value);
  820. tor_free(answer);
  821. answer = next;
  822. }
  823. }
  824. });
  825. if (v0) {
  826. msg = smartlist_join_strings(answers, "", 0, &msg_len);
  827. send_control0_message(conn, CONTROL0_CMD_CONFVALUE,
  828. (uint16_t)msg_len, msg_len?msg:NULL);
  829. } else {
  830. int i,len;
  831. if ((len = smartlist_len(unrecognized))) {
  832. for (i=0; i < len-1; ++i)
  833. connection_printf_to_buf(conn,
  834. "552-Unrecognized configuration key \"%s\"\r\n",
  835. (char*)smartlist_get(unrecognized, i));
  836. connection_printf_to_buf(conn,
  837. "552 Unrecognized configuration key \"%s\"\r\n",
  838. (char*)smartlist_get(unrecognized, len-1));
  839. } else if ((len = smartlist_len(answers))) {
  840. char *tmp = smartlist_get(answers, len-1);
  841. tor_assert(strlen(tmp)>4);
  842. tmp[3] = ' ';
  843. msg = smartlist_join_strings(answers, "", 0, &msg_len);
  844. connection_write_to_buf(msg, msg_len, TO_CONN(conn));
  845. } else {
  846. connection_write_str_to_buf("250 OK\r\n", conn);
  847. }
  848. }
  849. done:
  850. if (answers) {
  851. SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
  852. smartlist_free(answers);
  853. }
  854. if (questions) {
  855. SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
  856. smartlist_free(questions);
  857. }
  858. smartlist_free(unrecognized);
  859. tor_free(msg);
  860. return 0;
  861. }
  862. /** Called when we get a SETEVENTS message: update conn->event_mask,
  863. * and reply with DONE or ERROR. */
  864. static int
  865. handle_control_setevents(control_connection_t *conn, uint32_t len,
  866. const char *body)
  867. {
  868. uint16_t event_code;
  869. uint32_t event_mask = 0;
  870. unsigned int extended = 0;
  871. if (STATE_IS_V0(conn->_base.state)) {
  872. if (len % 2) {
  873. send_control0_error(conn, ERR_SYNTAX,
  874. "Odd number of bytes in setevents message");
  875. return 0;
  876. }
  877. for (; len; len -= 2, body += 2) {
  878. event_code = ntohs(get_uint16(body));
  879. if (event_code < _EVENT_MIN || event_code > LAST_V0_EVENT) {
  880. send_control0_error(conn, ERR_UNRECOGNIZED_EVENT_CODE,
  881. "Unrecognized event code");
  882. return 0;
  883. }
  884. event_mask |= (1 << event_code);
  885. }
  886. } else {
  887. smartlist_t *events = smartlist_create();
  888. smartlist_split_string(events, body, " ",
  889. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  890. SMARTLIST_FOREACH(events, const char *, ev,
  891. {
  892. if (!strcasecmp(ev, "EXTENDED")) {
  893. extended = 1;
  894. continue;
  895. } else if (!strcasecmp(ev, "CIRC"))
  896. event_code = EVENT_CIRCUIT_STATUS;
  897. else if (!strcasecmp(ev, "STREAM"))
  898. event_code = EVENT_STREAM_STATUS;
  899. else if (!strcasecmp(ev, "ORCONN"))
  900. event_code = EVENT_OR_CONN_STATUS;
  901. else if (!strcasecmp(ev, "BW"))
  902. event_code = EVENT_BANDWIDTH_USED;
  903. else if (!strcasecmp(ev, "DEBUG"))
  904. event_code = EVENT_DEBUG_MSG;
  905. else if (!strcasecmp(ev, "INFO"))
  906. event_code = EVENT_INFO_MSG;
  907. else if (!strcasecmp(ev, "NOTICE"))
  908. event_code = EVENT_NOTICE_MSG;
  909. else if (!strcasecmp(ev, "WARN"))
  910. event_code = EVENT_WARN_MSG;
  911. else if (!strcasecmp(ev, "ERR"))
  912. event_code = EVENT_ERR_MSG;
  913. else if (!strcasecmp(ev, "NEWDESC"))
  914. event_code = EVENT_NEW_DESC;
  915. else if (!strcasecmp(ev, "ADDRMAP"))
  916. event_code = EVENT_ADDRMAP;
  917. else if (!strcasecmp(ev, "AUTHDIR_NEWDESCS"))
  918. event_code = EVENT_AUTHDIR_NEWDESCS;
  919. else if (!strcasecmp(ev, "DESCCHANGED"))
  920. event_code = EVENT_DESCCHANGED;
  921. else {
  922. connection_printf_to_buf(conn, "552 Unrecognized event \"%s\"\r\n",
  923. ev);
  924. SMARTLIST_FOREACH(events, char *, e, tor_free(e));
  925. smartlist_free(events);
  926. return 0;
  927. }
  928. event_mask |= (1 << event_code);
  929. });
  930. SMARTLIST_FOREACH(events, char *, e, tor_free(e));
  931. smartlist_free(events);
  932. }
  933. conn->event_mask = event_mask;
  934. conn->use_extended_events = extended;
  935. control_update_global_event_mask();
  936. send_control_done(conn);
  937. return 0;
  938. }
  939. /** Decode the hashed, base64'd password stored in <b>hashed</b>. If
  940. * <b>buf</b> is provided, store the hashed password in the first
  941. * S2K_SPECIFIER_LEN+DIGEST_LEN bytes of <b>buf</b>. Return 0 on
  942. * success, -1 on failure.
  943. */
  944. int
  945. decode_hashed_password(char *buf, const char *hashed)
  946. {
  947. char decoded[64];
  948. if (!strcmpstart(hashed, "16:")) {
  949. if (base16_decode(decoded, sizeof(decoded), hashed+3, strlen(hashed+3))<0
  950. || strlen(hashed+3) != (S2K_SPECIFIER_LEN+DIGEST_LEN)*2) {
  951. return -1;
  952. }
  953. } else {
  954. if (base64_decode(decoded, sizeof(decoded), hashed, strlen(hashed))
  955. != S2K_SPECIFIER_LEN+DIGEST_LEN) {
  956. return -1;
  957. }
  958. }
  959. if (buf)
  960. memcpy(buf, decoded, S2K_SPECIFIER_LEN+DIGEST_LEN);
  961. return 0;
  962. }
  963. /** Called when we get an AUTHENTICATE message. Check whether the
  964. * authentication is valid, and if so, update the connection's state to
  965. * OPEN. Reply with DONE or ERROR.
  966. */
  967. static int
  968. handle_control_authenticate(control_connection_t *conn, uint32_t len,
  969. const char *body)
  970. {
  971. int used_quoted_string = 0;
  972. or_options_t *options = get_options();
  973. const char *errstr = NULL;
  974. char *password;
  975. size_t password_len;
  976. if (STATE_IS_V0(conn->_base.state)) {
  977. password = (char*)body;
  978. password_len = len;
  979. } else {
  980. if (TOR_ISXDIGIT(body[0])) {
  981. int i = 0;
  982. while (TOR_ISXDIGIT(body[i]))
  983. ++i;
  984. password = tor_malloc(i/2 + 1);
  985. if (base16_decode(password, i/2+1, body, i)<0) {
  986. connection_write_str_to_buf(
  987. "551 Invalid hexadecimal encoding. Maybe you tried a plain text "
  988. "password? If so, the standard requires you put it in double "
  989. "quotes.\r\n", conn);
  990. tor_free(password);
  991. return 0;
  992. }
  993. password_len = i/2;
  994. } else if (TOR_ISSPACE(body[0])) {
  995. password = tor_strdup("");
  996. password_len = 0;
  997. } else {
  998. if (!get_escaped_string(body, len, &password, &password_len)) {
  999. connection_write_str_to_buf("551 Invalid quoted string. You need "
  1000. "to put the password in double quotes.\r\n", conn);
  1001. return 0;
  1002. }
  1003. used_quoted_string = 1;
  1004. }
  1005. }
  1006. if (options->CookieAuthentication) {
  1007. if (password_len != AUTHENTICATION_COOKIE_LEN) {
  1008. log_warn(LD_CONTROL, "Got authentication cookie with wrong length (%d)",
  1009. (int)password_len);
  1010. errstr = "Wrong length on authentication cookie.";
  1011. goto err;
  1012. } else if (memcmp(authentication_cookie, password, password_len)) {
  1013. log_warn(LD_CONTROL, "Got mismatched authentication cookie");
  1014. errstr = "Authentication cookie did not match expected value.";
  1015. goto err;
  1016. } else {
  1017. goto ok;
  1018. }
  1019. } else if (options->HashedControlPassword) {
  1020. char expected[S2K_SPECIFIER_LEN+DIGEST_LEN];
  1021. char received[DIGEST_LEN];
  1022. if (decode_hashed_password(expected, options->HashedControlPassword)<0) {
  1023. log_warn(LD_CONTROL,
  1024. "Couldn't decode HashedControlPassword: invalid base16");
  1025. errstr = "Couldn't decode HashedControlPassword value in configuration.";
  1026. goto err;
  1027. }
  1028. secret_to_key(received,DIGEST_LEN,password,password_len,expected);
  1029. if (!memcmp(expected+S2K_SPECIFIER_LEN, received, DIGEST_LEN))
  1030. goto ok;
  1031. if (used_quoted_string)
  1032. errstr = "Password did not match HashedControlPassword value from "
  1033. "configuration";
  1034. else
  1035. errstr = "Password did not match HashedControlPassword value from "
  1036. "configuration. Maybe you tried a plain text password? "
  1037. "If so, the standard requires you put it in double quotes.";
  1038. goto err;
  1039. } else {
  1040. /* if Tor doesn't demand any stronger authentication, then
  1041. * the controller can get in with anything. */
  1042. goto ok;
  1043. }
  1044. err:
  1045. if (STATE_IS_V0(conn->_base.state))
  1046. send_control0_error(conn,ERR_REJECTED_AUTHENTICATION,
  1047. "Authentication failed");
  1048. else {
  1049. tor_free(password);
  1050. if (!errstr)
  1051. errstr = "Unknown reason.";
  1052. connection_printf_to_buf(conn, "515 Authentication failed: %s\r\n",
  1053. errstr);
  1054. }
  1055. return 0;
  1056. ok:
  1057. log_info(LD_CONTROL, "Authenticated control connection (%d)", conn->_base.s);
  1058. send_control_done(conn);
  1059. if (STATE_IS_V0(conn->_base.state))
  1060. conn->_base.state = CONTROL_CONN_STATE_OPEN_V0;
  1061. else {
  1062. conn->_base.state = CONTROL_CONN_STATE_OPEN_V1;
  1063. tor_free(password);
  1064. }
  1065. return 0;
  1066. }
  1067. /** Called when we get a SAVECONF command. Try to flush the current options to
  1068. * disk, and report success or failure. */
  1069. static int
  1070. handle_control_saveconf(control_connection_t *conn, uint32_t len,
  1071. const char *body)
  1072. {
  1073. (void) len;
  1074. (void) body;
  1075. if (options_save_current()<0) {
  1076. if (STATE_IS_V0(conn->_base.state))
  1077. send_control0_error(conn, ERR_INTERNAL,
  1078. "Unable to write configuration to disk.");
  1079. else
  1080. connection_write_str_to_buf(
  1081. "551 Unable to write configuration to disk.\r\n", conn);
  1082. } else {
  1083. send_control_done(conn);
  1084. }
  1085. return 0;
  1086. }
  1087. /** Called when we get a SIGNAL command. React to the provided signal, and
  1088. * report success or failure. (If the signal results in a shutdown, success
  1089. * may not be reported.) */
  1090. static int
  1091. handle_control_signal(control_connection_t *conn, uint32_t len,
  1092. const char *body)
  1093. {
  1094. int sig;
  1095. if (STATE_IS_V0(conn->_base.state)) {
  1096. if (len != 1) {
  1097. send_control0_error(conn, ERR_SYNTAX,
  1098. "Body of SIGNAL command too long or too short.");
  1099. return 0;
  1100. } else {
  1101. sig = (uint8_t)body[0];
  1102. }
  1103. } else {
  1104. int n = 0;
  1105. char *s;
  1106. while (body[n] && ! TOR_ISSPACE(body[n]))
  1107. ++n;
  1108. s = tor_strndup(body, n);
  1109. if (!strcasecmp(s, "RELOAD") || !strcasecmp(s, "HUP"))
  1110. sig = SIGHUP;
  1111. else if (!strcasecmp(s, "SHUTDOWN") || !strcasecmp(s, "INT"))
  1112. sig = SIGINT;
  1113. else if (!strcasecmp(s, "DUMP") || !strcasecmp(s, "USR1"))
  1114. sig = SIGUSR1;
  1115. else if (!strcasecmp(s, "DEBUG") || !strcasecmp(s, "USR2"))
  1116. sig = SIGUSR2;
  1117. else if (!strcasecmp(s, "HALT") || !strcasecmp(s, "TERM"))
  1118. sig = SIGTERM;
  1119. else if (!strcasecmp(s, "NEWNYM"))
  1120. sig = SIGNEWNYM;
  1121. else {
  1122. connection_printf_to_buf(conn, "552 Unrecognized signal code \"%s\"\r\n",
  1123. s);
  1124. sig = -1;
  1125. }
  1126. tor_free(s);
  1127. if (sig<0)
  1128. return 0;
  1129. }
  1130. if (!control_signal_check(sig)) {
  1131. if (STATE_IS_V0(conn->_base.state))
  1132. send_control0_error(conn, ERR_SYNTAX, "Unrecognized signal number.");
  1133. else
  1134. connection_write_str_to_buf("551 Unable to act on signal\r\n",
  1135. conn);
  1136. } else {
  1137. /* Send DONE first, in case the signal makes us shut down. */
  1138. send_control_done(conn);
  1139. control_signal_act(sig);
  1140. }
  1141. return 0;
  1142. }
  1143. /** Called when we get a MAPADDRESS command; try to bind all listed addresses,
  1144. * and report success or failrue. */
  1145. static int
  1146. handle_control_mapaddress(control_connection_t *conn, uint32_t len,
  1147. const char *body)
  1148. {
  1149. smartlist_t *elts;
  1150. smartlist_t *lines;
  1151. smartlist_t *reply;
  1152. char *r;
  1153. size_t sz;
  1154. int v0 = STATE_IS_V0(conn->_base.state);
  1155. (void) len; /* body is nul-terminated, so it's safe to ignore the length. */
  1156. lines = smartlist_create();
  1157. elts = smartlist_create();
  1158. reply = smartlist_create();
  1159. if (v0)
  1160. smartlist_split_string(lines, body, "\n",
  1161. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1162. else
  1163. smartlist_split_string(lines, body, " ",
  1164. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1165. SMARTLIST_FOREACH(lines, char *, line,
  1166. {
  1167. tor_strlower(line);
  1168. if (v0)
  1169. smartlist_split_string(elts, line, " ", 0, 2);
  1170. else
  1171. smartlist_split_string(elts, line, "=", 0, 2);
  1172. if (smartlist_len(elts) == 2) {
  1173. const char *from = smartlist_get(elts,0);
  1174. const char *to = smartlist_get(elts,1);
  1175. size_t anslen = strlen(line)+512;
  1176. char *ans = tor_malloc(anslen);
  1177. if (!is_plausible_address(from)) {
  1178. if (!v0) {
  1179. tor_snprintf(ans, anslen,
  1180. "512-syntax error: invalid address '%s'", from);
  1181. smartlist_add(reply, ans);
  1182. } else
  1183. tor_free(ans); /* don't respond if v0 */
  1184. log_warn(LD_CONTROL,
  1185. "Skipping invalid argument '%s' in MapAddress msg",
  1186. from);
  1187. } else if (!is_plausible_address(to)) {
  1188. if (!v0) {
  1189. tor_snprintf(ans, anslen,
  1190. "512-syntax error: invalid address '%s'", to);
  1191. smartlist_add(reply, ans);
  1192. } else
  1193. tor_free(ans); /* don't respond if v0 */
  1194. log_warn(LD_CONTROL,
  1195. "Skipping invalid argument '%s' in MapAddress msg", to);
  1196. } else if (!strcmp(from, ".") || !strcmp(from, "0.0.0.0")) {
  1197. const char *address = addressmap_register_virtual_address(
  1198. !strcmp(from,".") ? RESOLVED_TYPE_HOSTNAME : RESOLVED_TYPE_IPV4,
  1199. tor_strdup(to));
  1200. if (!address) {
  1201. if (!v0) {
  1202. tor_snprintf(ans, anslen,
  1203. "451-resource exhausted: skipping '%s'", line);
  1204. smartlist_add(reply, ans);
  1205. } else
  1206. tor_free(ans); /* don't respond if v0 */
  1207. log_warn(LD_CONTROL,
  1208. "Unable to allocate address for '%s' in MapAddress msg",
  1209. safe_str(line));
  1210. } else {
  1211. if (v0)
  1212. tor_snprintf(ans, anslen, "%s %s", address, to);
  1213. else
  1214. tor_snprintf(ans, anslen, "250-%s=%s", address, to);
  1215. smartlist_add(reply, ans);
  1216. }
  1217. } else {
  1218. addressmap_register(from, tor_strdup(to), 1);
  1219. if (v0)
  1220. tor_snprintf(ans, anslen, "%s", line);
  1221. else
  1222. tor_snprintf(ans, anslen, "250-%s", line);
  1223. smartlist_add(reply, ans);
  1224. }
  1225. } else {
  1226. if (!v0) {
  1227. size_t anslen = strlen(line)+256;
  1228. char *ans = tor_malloc(anslen);
  1229. tor_snprintf(ans, anslen, "512-syntax error: mapping '%s' is "
  1230. "not of expected form 'foo=bar'.", line);
  1231. smartlist_add(reply, ans);
  1232. }
  1233. log_info(LD_CONTROL, "Skipping MapAddress '%s': wrong "
  1234. "number of items.", safe_str(line));
  1235. }
  1236. SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
  1237. smartlist_clear(elts);
  1238. });
  1239. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  1240. smartlist_free(lines);
  1241. smartlist_free(elts);
  1242. if (v0) {
  1243. r = smartlist_join_strings(reply, "\n", 1, &sz);
  1244. send_control_done2(conn,r,sz);
  1245. tor_free(r);
  1246. } else {
  1247. if (smartlist_len(reply)) {
  1248. ((char*)smartlist_get(reply,smartlist_len(reply)-1))[3] = ' ';
  1249. r = smartlist_join_strings(reply, "\r\n", 1, &sz);
  1250. connection_write_to_buf(r, sz, TO_CONN(conn));
  1251. tor_free(r);
  1252. } else {
  1253. const char *response =
  1254. "512 syntax error: not enough arguments to mapaddress.\r\n";
  1255. connection_write_to_buf(response, strlen(response), TO_CONN(conn));
  1256. }
  1257. }
  1258. SMARTLIST_FOREACH(reply, char *, cp, tor_free(cp));
  1259. smartlist_free(reply);
  1260. return 0;
  1261. }
  1262. /** Return a newly allocated string listing all valid GETINFO fields as
  1263. * required by GETINFO info/names. */
  1264. static char *
  1265. list_getinfo_options(void)
  1266. {
  1267. return tor_strdup(
  1268. "accounting/bytes Number of bytes read/written so far in interval.\n"
  1269. "accounting/bytes-left Number of bytes left to read/write in interval.\n"
  1270. "accounting/enabled Is accounting currently enabled?\n"
  1271. "accounting/hibernating Are we hibernating or awake?\n"
  1272. "accounting/interval-end Time when interval ends.\n"
  1273. "accounting/interval-start Time when interval starts.\n"
  1274. "accounting/interval-wake Time to wake up in this interval.\n"
  1275. "addr-mappings/all All current remapped addresses.\n"
  1276. "addr-mappings/cache Addresses remapped by DNS cache.\n"
  1277. "addr-mappings/configl Addresses remapped from configuration options.\n"
  1278. "addr-mappings/control Addresses remapped by a controller.\n"
  1279. "address The best guess at our external IP address.\n"
  1280. "circuit-status Status of each current circuit.\n"
  1281. "config-file Current location of the \"torrc\" file.\n"
  1282. "config/names List of configuration options, types, and documentation.\n"
  1283. "desc/id/* Server descriptor by hex ID\n"
  1284. "desc/name/* Server descriptor by nickname.\n"
  1285. "desc/all-recent Latest server descriptor for every router\n"
  1286. "dir/server/* Fetch server descriptors -- see dir-spec.txt\n"
  1287. "entry-guards Which nodes will we use as entry guards?\n"
  1288. "exit-policy/default Default lines appended to config->ExitPolicy\n"
  1289. "info/names List of GETINFO options, types, and documentation.\n"
  1290. "network-status List of hex IDs, nicknames, server statuses.\n"
  1291. "orconn-status Status of each current OR connection.\n"
  1292. "stream-status Status of each current application stream.\n"
  1293. "version The current version of Tor.\n");
  1294. }
  1295. /** Lookup the 'getinfo' entry <b>question</b>, and return
  1296. * the answer in <b>*answer</b> (or NULL if key not recognized).
  1297. * Return 0 if success or unrecognized, or -1 if recognized but
  1298. * internal error. */
  1299. static int
  1300. handle_getinfo_helper(control_connection_t *control_conn,
  1301. const char *question, char **answer)
  1302. {
  1303. *answer = NULL; /* unrecognized key by default */
  1304. if (!strcmp(question, "version")) {
  1305. *answer = tor_strdup(VERSION);
  1306. } else if (!strcmp(question, "config-file")) {
  1307. *answer = tor_strdup(get_torrc_fname());
  1308. } else if (!strcmpstart(question, "accounting/")) {
  1309. return accounting_getinfo_helper(question, answer);
  1310. } else if (!strcmpstart(question, "helper-nodes")) { /* deprecated */
  1311. return entry_guards_getinfo(control_conn->use_long_names,
  1312. question, answer);
  1313. } else if (!strcmpstart(question, "entry-guards")) {
  1314. return entry_guards_getinfo(control_conn->use_long_names,
  1315. question, answer);
  1316. } else if (!strcmpstart(question, "config/")) {
  1317. return config_getinfo_helper(question, answer);
  1318. } else if (!strcmp(question, "info/names")) {
  1319. *answer = list_getinfo_options();
  1320. } else if (!strcmpstart(question, "desc/id/")) {
  1321. routerinfo_t *ri = router_get_by_hexdigest(question+strlen("desc/id/"));
  1322. if (ri) {
  1323. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1324. if (body)
  1325. *answer = tor_strndup(body, ri->cache_info.signed_descriptor_len);
  1326. }
  1327. } else if (!strcmpstart(question, "desc/name/")) {
  1328. routerinfo_t *ri = router_get_by_nickname(question+strlen("desc/name/"),1);
  1329. if (ri) {
  1330. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1331. if (body)
  1332. *answer = tor_strndup(body, ri->cache_info.signed_descriptor_len);
  1333. }
  1334. } else if (!strcmp(question, "desc/all-recent")) {
  1335. routerlist_t *routerlist = router_get_routerlist();
  1336. smartlist_t *sl = smartlist_create();
  1337. if (routerlist && routerlist->routers) {
  1338. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
  1339. {
  1340. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1341. if (body)
  1342. smartlist_add(sl,
  1343. tor_strndup(body, ri->cache_info.signed_descriptor_len));
  1344. });
  1345. }
  1346. *answer = smartlist_join_strings(sl, "", 0, NULL);
  1347. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  1348. smartlist_free(sl);
  1349. } else if (!strcmpstart(question, "unregistered-servers-")) {
  1350. *answer = dirserver_getinfo_unregistered(question +
  1351. strlen("unregistered-servers-"));
  1352. } else if (!strcmp(question, "network-status")) {
  1353. routerlist_t *routerlist = router_get_routerlist();
  1354. if (!routerlist || !routerlist->routers ||
  1355. list_server_status(routerlist->routers, answer) < 0) {
  1356. return -1;
  1357. }
  1358. } else if (!strcmp(question, "circuit-status")) {
  1359. circuit_t *circ;
  1360. smartlist_t *status = smartlist_create();
  1361. for (circ = _circuit_get_global_list(); circ; circ = circ->next) {
  1362. char *s, *path;
  1363. size_t slen;
  1364. const char *state;
  1365. if (! CIRCUIT_IS_ORIGIN(circ) || circ->marked_for_close)
  1366. continue;
  1367. if (control_conn->use_long_names)
  1368. path = circuit_list_path_for_controller(TO_ORIGIN_CIRCUIT(circ));
  1369. else
  1370. path = circuit_list_path(TO_ORIGIN_CIRCUIT(circ),0);
  1371. if (circ->state == CIRCUIT_STATE_OPEN)
  1372. state = "BUILT";
  1373. else if (strlen(path))
  1374. state = "EXTENDED";
  1375. else
  1376. state = "LAUNCHED";
  1377. slen = strlen(path)+strlen(state)+20;
  1378. s = tor_malloc(slen+1);
  1379. tor_snprintf(s, slen, "%lu %s %s",
  1380. (unsigned long)TO_ORIGIN_CIRCUIT(circ)->global_identifier,
  1381. state, path);
  1382. smartlist_add(status, s);
  1383. tor_free(path);
  1384. }
  1385. *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
  1386. SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
  1387. smartlist_free(status);
  1388. } else if (!strcmp(question, "stream-status")) {
  1389. connection_t **conns;
  1390. int n_conns, i;
  1391. char buf[256];
  1392. smartlist_t *status = smartlist_create();
  1393. get_connection_array(&conns, &n_conns);
  1394. for (i=0; i < n_conns; ++i) {
  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 (conns[i]->type != CONN_TYPE_AP ||
  1402. conns[i]->marked_for_close ||
  1403. conns[i]->state == AP_CONN_STATE_SOCKS_WAIT ||
  1404. conns[i]->state == AP_CONN_STATE_ORIGDST_WAIT)
  1405. continue;
  1406. conn = TO_EDGE_CONN(conns[i]);
  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. (conn->socks_request->command == SOCKS_COMMAND_RESOLVE ||
  1413. conn->socks_request->command == SOCKS_COMMAND_RESOLVE_PTR))
  1414. state = "NEWRESOLVE";
  1415. else
  1416. state = "NEW";
  1417. break;
  1418. case AP_CONN_STATE_RENDDESC_WAIT:
  1419. case AP_CONN_STATE_CONNECT_WAIT:
  1420. state = "SENTCONNECT"; break;
  1421. case AP_CONN_STATE_RESOLVE_WAIT:
  1422. state = "SENTRESOLVE"; break;
  1423. case AP_CONN_STATE_OPEN:
  1424. state = "SUCCEEDED"; break;
  1425. default:
  1426. log_warn(LD_BUG, "Asked for stream in unknown state %d",
  1427. conn->_base.state);
  1428. continue;
  1429. }
  1430. circ = circuit_get_by_edge_conn(conn);
  1431. if (circ && CIRCUIT_IS_ORIGIN(circ))
  1432. origin_circ = TO_ORIGIN_CIRCUIT(circ);
  1433. write_stream_target_to_buf(conn, buf, sizeof(buf));
  1434. slen = strlen(buf)+strlen(state)+32;
  1435. s = tor_malloc(slen+1);
  1436. tor_snprintf(s, slen, "%lu %s %lu %s",
  1437. (unsigned long) conn->global_identifier,state,
  1438. origin_circ?
  1439. (unsigned long)origin_circ->global_identifier : 0ul,
  1440. buf);
  1441. smartlist_add(status, s);
  1442. }
  1443. *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
  1444. SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
  1445. smartlist_free(status);
  1446. } else if (!strcmp(question, "orconn-status")) {
  1447. connection_t **conns;
  1448. int n_conns, i;
  1449. smartlist_t *status = smartlist_create();
  1450. get_connection_array(&conns, &n_conns);
  1451. for (i=0; i < n_conns; ++i) {
  1452. const char *state;
  1453. char *s;
  1454. char name[128];
  1455. size_t slen;
  1456. or_connection_t *conn;
  1457. if (conns[i]->type != CONN_TYPE_OR || conns[i]->marked_for_close)
  1458. continue;
  1459. conn = TO_OR_CONN(conns[i]);
  1460. if (conn->_base.state == OR_CONN_STATE_OPEN)
  1461. state = "CONNECTED";
  1462. else if (conn->nickname)
  1463. state = "LAUNCHED";
  1464. else
  1465. state = "NEW";
  1466. orconn_target_get_name(control_conn->use_long_names, name, sizeof(name),
  1467. conn);
  1468. slen = strlen(name)+strlen(state)+2;
  1469. s = tor_malloc(slen+1);
  1470. tor_snprintf(s, slen, "%s %s", name, state);
  1471. smartlist_add(status, s);
  1472. }
  1473. *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
  1474. SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
  1475. smartlist_free(status);
  1476. } else if (!strcmpstart(question, "addr-mappings/")) {
  1477. time_t min_e, max_e;
  1478. smartlist_t *mappings;
  1479. if (!strcmp(question, "addr-mappings/all")) {
  1480. min_e = 0; max_e = TIME_MAX;
  1481. } else if (!strcmp(question, "addr-mappings/cache")) {
  1482. min_e = 2; max_e = TIME_MAX;
  1483. } else if (!strcmp(question, "addr-mappings/config")) {
  1484. min_e = 0; max_e = 0;
  1485. } else if (!strcmp(question, "addr-mappings/control")) {
  1486. min_e = 1; max_e = 1;
  1487. } else {
  1488. return 0;
  1489. }
  1490. mappings = smartlist_create();
  1491. addressmap_get_mappings(mappings, min_e, max_e);
  1492. *answer = smartlist_join_strings(mappings, "\r\n", 0, NULL);
  1493. SMARTLIST_FOREACH(mappings, char *, cp, tor_free(cp));
  1494. smartlist_free(mappings);
  1495. } else if (!strcmp(question, "address")) {
  1496. uint32_t addr;
  1497. if (router_pick_published_address(get_options(), &addr) < 0)
  1498. return -1;
  1499. *answer = tor_dup_addr(addr);
  1500. } else if (!strcmp(question, "dir-usage")) {
  1501. *answer = directory_dump_request_log();
  1502. } else if (!strcmpstart(question, "dir/server/")) {
  1503. size_t answer_len = 0, url_len = strlen(question)+2;
  1504. char *url = tor_malloc(url_len);
  1505. int res;
  1506. smartlist_t *descs = smartlist_create();
  1507. const char *msg;
  1508. char *cp;
  1509. tor_snprintf(url, url_len, "/tor/%s", question+4);
  1510. res = dirserv_get_routerdescs(descs, url, &msg);
  1511. SMARTLIST_FOREACH(descs, signed_descriptor_t *, sd,
  1512. answer_len += sd->signed_descriptor_len);
  1513. cp = *answer = tor_malloc(answer_len+1);
  1514. SMARTLIST_FOREACH(descs, signed_descriptor_t *, sd,
  1515. {
  1516. memcpy(cp, signed_descriptor_get_body(sd),
  1517. sd->signed_descriptor_len);
  1518. cp += sd->signed_descriptor_len;
  1519. });
  1520. *cp = '\0';
  1521. tor_free(url);
  1522. smartlist_free(descs);
  1523. } else if (!strcmpstart(question, "dir/status/")) {
  1524. smartlist_t *status_list;
  1525. size_t len;
  1526. char *cp;
  1527. if (!get_options()->DirPort) {
  1528. log_warn(LD_CONTROL, "getinfo dir/status/ requires an open dirport.");
  1529. return -1;
  1530. }
  1531. status_list = smartlist_create();
  1532. dirserv_get_networkstatus_v2(status_list,
  1533. question+strlen("dir/status/"));
  1534. len = 0;
  1535. SMARTLIST_FOREACH(status_list, cached_dir_t *, d, len += d->dir_len);
  1536. cp = *answer = tor_malloc(len+1);
  1537. SMARTLIST_FOREACH(status_list, cached_dir_t *, d, {
  1538. memcpy(cp, d->dir, d->dir_len);
  1539. cp += d->dir_len;
  1540. });
  1541. *cp = '\0';
  1542. } else if (!strcmpstart(question, "exit-policy/")) {
  1543. return policies_getinfo_helper(question, answer);
  1544. }
  1545. return 0; /* unrecognized */
  1546. }
  1547. /** Called when we receive a GETINFO command. Try to fetch all requested
  1548. * information, and reply with information or error message. */
  1549. static int
  1550. handle_control_getinfo(control_connection_t *conn, uint32_t len,
  1551. const char *body)
  1552. {
  1553. smartlist_t *questions = NULL;
  1554. smartlist_t *answers = NULL;
  1555. smartlist_t *unrecognized = NULL;
  1556. char *msg = NULL, *ans = NULL;
  1557. size_t msg_len;
  1558. int v0 = STATE_IS_V0(conn->_base.state);
  1559. (void) len; /* body is nul-terminated, so it's safe to ignore the length. */
  1560. questions = smartlist_create();
  1561. if (v0)
  1562. smartlist_split_string(questions, body, "\n",
  1563. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1564. else
  1565. smartlist_split_string(questions, body, " ",
  1566. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1567. answers = smartlist_create();
  1568. unrecognized = smartlist_create();
  1569. SMARTLIST_FOREACH(questions, const char *, q,
  1570. {
  1571. if (handle_getinfo_helper(conn, q, &ans) < 0) {
  1572. if (v0)
  1573. send_control0_error(conn, ERR_INTERNAL, body);
  1574. else
  1575. connection_write_str_to_buf("551 Internal error\r\n", conn);
  1576. goto done;
  1577. }
  1578. if (!ans) {
  1579. if (v0) {
  1580. send_control0_error(conn, ERR_UNRECOGNIZED_CONFIG_KEY, body);
  1581. goto done;
  1582. } else
  1583. smartlist_add(unrecognized, (char*)q);
  1584. } else {
  1585. smartlist_add(answers, tor_strdup(q));
  1586. smartlist_add(answers, ans);
  1587. }
  1588. });
  1589. if (smartlist_len(unrecognized)) {
  1590. int i;
  1591. tor_assert(!v0);
  1592. for (i=0; i < smartlist_len(unrecognized)-1; ++i)
  1593. connection_printf_to_buf(conn,
  1594. "552-Unrecognized key \"%s\"\r\n",
  1595. (char*)smartlist_get(unrecognized, i));
  1596. connection_printf_to_buf(conn,
  1597. "552 Unrecognized key \"%s\"\r\n",
  1598. (char*)smartlist_get(unrecognized, i));
  1599. goto done;
  1600. }
  1601. if (v0) {
  1602. msg = smartlist_join_strings2(answers, "\0", 1, 1, &msg_len);
  1603. tor_assert(msg_len > 0); /* it will at least be terminated */
  1604. send_control0_message(conn, CONTROL0_CMD_INFOVALUE,
  1605. msg_len, msg);
  1606. } else {
  1607. int i;
  1608. for (i = 0; i < smartlist_len(answers); i += 2) {
  1609. char *k = smartlist_get(answers, i);
  1610. char *v = smartlist_get(answers, i+1);
  1611. if (!strchr(v, '\n') && !strchr(v, '\r')) {
  1612. connection_printf_to_buf(conn, "250-%s=", k);
  1613. connection_write_str_to_buf(v, conn);
  1614. connection_write_str_to_buf("\r\n", conn);
  1615. } else {
  1616. char *esc = NULL;
  1617. size_t len;
  1618. len = write_escaped_data(v, strlen(v), 1, &esc);
  1619. connection_printf_to_buf(conn, "250+%s=\r\n", k);
  1620. connection_write_to_buf(esc, len, TO_CONN(conn));
  1621. tor_free(esc);
  1622. }
  1623. }
  1624. connection_write_str_to_buf("250 OK\r\n", conn);
  1625. }
  1626. done:
  1627. if (answers) {
  1628. SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
  1629. smartlist_free(answers);
  1630. }
  1631. if (questions) {
  1632. SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
  1633. smartlist_free(questions);
  1634. }
  1635. smartlist_free(unrecognized);
  1636. tor_free(msg);
  1637. return 0;
  1638. }
  1639. /** If *<b>string</b> contains a recognized purpose (for
  1640. * circuits if <b>for_circuits</b> is 1, else for routers),
  1641. * possibly prefaced with the string "purpose=", then assign it
  1642. * and return 0. Otherwise return -1.
  1643. *
  1644. * If it's prefaced with "purpose=", then set *<b>string</b> to
  1645. * the remainder of the string. */
  1646. static int
  1647. get_purpose(char **string, int for_circuits, uint8_t *purpose)
  1648. {
  1649. if (!strcmpstart(*string, "purpose="))
  1650. *string += strlen("purpose=");
  1651. if (!strcmp(*string, "general"))
  1652. *purpose = for_circuits ? CIRCUIT_PURPOSE_C_GENERAL :
  1653. ROUTER_PURPOSE_GENERAL;
  1654. else if (!strcmp(*string, "controller"))
  1655. *purpose = for_circuits ? CIRCUIT_PURPOSE_CONTROLLER :
  1656. ROUTER_PURPOSE_GENERAL;
  1657. else { /* not a recognized purpose */
  1658. return -1;
  1659. }
  1660. return 0;
  1661. }
  1662. /** Called when we get an EXTENDCIRCUIT message. Try to extend the listed
  1663. * circuit, and report success or failure. */
  1664. static int
  1665. handle_control_extendcircuit(control_connection_t *conn, uint32_t len,
  1666. const char *body)
  1667. {
  1668. smartlist_t *router_nicknames=NULL, *routers=NULL;
  1669. uint32_t circ_id;
  1670. origin_circuit_t *circ = NULL;
  1671. int zero_circ, v0;
  1672. char reply[4];
  1673. uint8_t intended_purpose = CIRCUIT_PURPOSE_C_GENERAL;
  1674. v0 = STATE_IS_V0(conn->_base.state);
  1675. router_nicknames = smartlist_create();
  1676. if (v0) {
  1677. if (len<5) {
  1678. send_control0_error(conn, ERR_SYNTAX, "extendcircuit message too short");
  1679. goto done;
  1680. }
  1681. smartlist_split_string(router_nicknames, body+4, ",", 0, 0);
  1682. circ_id = ntohl(get_uint32(body));
  1683. if (!circ_id) {
  1684. /* start a new circuit */
  1685. zero_circ = 1;
  1686. } else {
  1687. circ = circuit_get_by_global_id(circ_id);
  1688. zero_circ = 0;
  1689. if (!circ) {
  1690. send_control0_error(conn, ERR_NO_CIRC,
  1691. "No circuit found with given ID");
  1692. goto done;
  1693. }
  1694. }
  1695. } else { /* v1 */
  1696. smartlist_t *args;
  1697. args = smartlist_create();
  1698. smartlist_split_string(args, body, " ",
  1699. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1700. if (smartlist_len(args)<2) {
  1701. connection_printf_to_buf(conn,
  1702. "512 Missing argument to EXTENDCIRCUIT\r\n");
  1703. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1704. smartlist_free(args);
  1705. goto done;
  1706. }
  1707. zero_circ = !strcmp("0", (char*)smartlist_get(args,0));
  1708. if (!zero_circ && !(circ = get_circ(smartlist_get(args,0)))) {
  1709. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  1710. (char*)smartlist_get(args, 0));
  1711. }
  1712. smartlist_split_string(router_nicknames, smartlist_get(args,1), ",", 0, 0);
  1713. if (zero_circ && smartlist_len(args)>2) {
  1714. char *purp = smartlist_get(args,2);
  1715. if (get_purpose(&purp, 1, &intended_purpose) < 0) {
  1716. connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n", purp);
  1717. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1718. smartlist_free(args);
  1719. goto done;
  1720. }
  1721. }
  1722. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1723. smartlist_free(args);
  1724. if (!zero_circ && !circ) {
  1725. goto done;
  1726. }
  1727. }
  1728. routers = smartlist_create();
  1729. SMARTLIST_FOREACH(router_nicknames, const char *, n,
  1730. {
  1731. routerinfo_t *r = router_get_by_nickname(n, 1);
  1732. if (!r) {
  1733. if (v0)
  1734. send_control0_error(conn, ERR_NO_ROUTER, n);
  1735. else
  1736. connection_printf_to_buf(conn, "552 No such router \"%s\"\r\n", n);
  1737. goto done;
  1738. }
  1739. smartlist_add(routers, r);
  1740. });
  1741. if (!smartlist_len(routers)) {
  1742. if (v0)
  1743. send_control0_error(conn, ERR_SYNTAX, "No router names provided");
  1744. else
  1745. connection_write_str_to_buf("512 No router names provided\r\n", conn);
  1746. goto done;
  1747. }
  1748. if (zero_circ) {
  1749. /* start a new circuit */
  1750. circ = origin_circuit_init(intended_purpose, 0, 0, 0);
  1751. }
  1752. /* now circ refers to something that is ready to be extended */
  1753. SMARTLIST_FOREACH(routers, routerinfo_t *, r,
  1754. {
  1755. extend_info_t *info = extend_info_from_router(r);
  1756. circuit_append_new_exit(circ, info);
  1757. extend_info_free(info);
  1758. });
  1759. /* now that we've populated the cpath, start extending */
  1760. if (zero_circ) {
  1761. if (circuit_handle_first_hop(circ) < 0) {
  1762. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_AT_ORIGIN);
  1763. if (v0)
  1764. send_control0_error(conn, ERR_INTERNAL, "couldn't start circuit");
  1765. else
  1766. connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
  1767. goto done;
  1768. }
  1769. } else {
  1770. if (circ->_base.state == CIRCUIT_STATE_OPEN) {
  1771. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
  1772. if (circuit_send_next_onion_skin(circ) < 0) {
  1773. log_info(LD_CONTROL,
  1774. "send_next_onion_skin failed; circuit marked for closing.");
  1775. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_AT_ORIGIN);
  1776. if (v0)
  1777. send_control0_error(conn, ERR_INTERNAL, "couldn't send onion skin");
  1778. else
  1779. connection_write_str_to_buf("551 Couldn't send onion skinr\n", conn);
  1780. goto done;
  1781. }
  1782. }
  1783. }
  1784. if (v0) {
  1785. set_uint32(reply, htonl(circ->global_identifier));
  1786. send_control_done2(conn, reply, sizeof(reply));
  1787. } else {
  1788. connection_printf_to_buf(conn, "250 EXTENDED %lu\r\n",
  1789. (unsigned long)circ->global_identifier);
  1790. }
  1791. done:
  1792. SMARTLIST_FOREACH(router_nicknames, char *, n, tor_free(n));
  1793. smartlist_free(router_nicknames);
  1794. if (routers)
  1795. smartlist_free(routers);
  1796. return 0;
  1797. }
  1798. /** Called when we get a SETCIRCUITPURPOSE (if <b>for_circuits</b>
  1799. * is 1) or SETROUTERPURPOSE message. If we can find
  1800. * the circuit/router and it's a valid purpose, change it. */
  1801. static int
  1802. handle_control_setpurpose(control_connection_t *conn, int for_circuits,
  1803. uint32_t len, const char *body)
  1804. {
  1805. origin_circuit_t *circ = NULL;
  1806. routerinfo_t *ri = NULL;
  1807. uint8_t new_purpose;
  1808. smartlist_t *args = smartlist_create();
  1809. (void) len; /* body is nul-terminated, so it's safe to ignore the length. */
  1810. smartlist_split_string(args, body, " ",
  1811. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1812. if (smartlist_len(args)<2) {
  1813. connection_printf_to_buf(conn,
  1814. "512 Missing argument to SET%sPURPOSE\r\n",
  1815. for_circuits ? "CIRCUIT" : "ROUTER");
  1816. goto done;
  1817. }
  1818. if (for_circuits) {
  1819. if (!(circ = get_circ(smartlist_get(args,0)))) {
  1820. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  1821. (char*)smartlist_get(args, 0));
  1822. goto done;
  1823. }
  1824. } else {
  1825. if (!(ri = router_get_by_nickname(smartlist_get(args,0), 0))) {
  1826. connection_printf_to_buf(conn, "552 Unknown router \"%s\"\r\n",
  1827. (char*)smartlist_get(args, 0));
  1828. goto done;
  1829. }
  1830. }
  1831. {
  1832. char *purp = smartlist_get(args,1);
  1833. if (get_purpose(&purp, for_circuits, &new_purpose) < 0) {
  1834. connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n", purp);
  1835. goto done;
  1836. }
  1837. }
  1838. if (for_circuits)
  1839. circ->_base.purpose = new_purpose;
  1840. else
  1841. ri->purpose = new_purpose;
  1842. connection_write_str_to_buf("250 OK\r\n", conn);
  1843. done:
  1844. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1845. smartlist_free(args);
  1846. return 0;
  1847. }
  1848. /** Called when we get an ATTACHSTREAM message. Try to attach the requested
  1849. * stream, and report success or failure. */
  1850. static int
  1851. handle_control_attachstream(control_connection_t *conn, uint32_t len,
  1852. const char *body)
  1853. {
  1854. edge_connection_t *ap_conn = NULL;
  1855. origin_circuit_t *circ = NULL;
  1856. int zero_circ;
  1857. if (STATE_IS_V0(conn->_base.state)) {
  1858. uint32_t conn_id;
  1859. uint32_t circ_id;
  1860. if (len < 8) {
  1861. send_control0_error(conn, ERR_SYNTAX, "attachstream message too short");
  1862. return 0;
  1863. }
  1864. conn_id = ntohl(get_uint32(body));
  1865. circ_id = ntohl(get_uint32(body+4));
  1866. zero_circ = circ_id == 0;
  1867. if (!(ap_conn = connection_get_by_global_id(conn_id))) {
  1868. send_control0_error(conn, ERR_NO_STREAM,
  1869. "No connection found with given ID");
  1870. return 0;
  1871. }
  1872. if (circ_id && !(circ = circuit_get_by_global_id(circ_id))) {
  1873. send_control0_error(conn, ERR_NO_CIRC, "No circuit found with given ID");
  1874. return 0;
  1875. }
  1876. } else {
  1877. smartlist_t *args;
  1878. args = smartlist_create();
  1879. smartlist_split_string(args, body, " ",
  1880. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1881. if (smartlist_len(args)<2) {
  1882. connection_printf_to_buf(conn,
  1883. "512 Missing argument to ATTACHSTREAM\r\n");
  1884. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1885. smartlist_free(args);
  1886. return 0;
  1887. }
  1888. zero_circ = !strcmp("0", (char*)smartlist_get(args,1));
  1889. if (!(ap_conn = get_stream(smartlist_get(args, 0)))) {
  1890. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  1891. (char*)smartlist_get(args, 0));
  1892. } else if (!zero_circ && !(circ = get_circ(smartlist_get(args, 1)))) {
  1893. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  1894. (char*)smartlist_get(args, 1));
  1895. }
  1896. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1897. smartlist_free(args);
  1898. if (!ap_conn || (!zero_circ && !circ))
  1899. return 0;
  1900. }
  1901. if (ap_conn->_base.state != AP_CONN_STATE_CONTROLLER_WAIT &&
  1902. ap_conn->_base.state != AP_CONN_STATE_CONNECT_WAIT &&
  1903. ap_conn->_base.state != AP_CONN_STATE_RESOLVE_WAIT) {
  1904. if (STATE_IS_V0(conn->_base.state)) {
  1905. send_control0_error(conn, ERR_NO_STREAM,
  1906. "Connection is not managed by controller.");
  1907. } else {
  1908. connection_write_str_to_buf(
  1909. "555 Connection is not managed by controller.\r\n",
  1910. conn);
  1911. }
  1912. return 0;
  1913. }
  1914. /* Do we need to detach it first? */
  1915. if (ap_conn->_base.state != AP_CONN_STATE_CONTROLLER_WAIT) {
  1916. circuit_t *tmpcirc = circuit_get_by_edge_conn(ap_conn);
  1917. connection_edge_end(ap_conn, END_STREAM_REASON_TIMEOUT,
  1918. ap_conn->cpath_layer);
  1919. /* Un-mark it as ending, since we're going to reuse it. */
  1920. ap_conn->_base.edge_has_sent_end = 0;
  1921. if (tmpcirc)
  1922. circuit_detach_stream(tmpcirc,ap_conn);
  1923. ap_conn->_base.state = AP_CONN_STATE_CONTROLLER_WAIT;
  1924. }
  1925. if (circ && (circ->_base.state != CIRCUIT_STATE_OPEN)) {
  1926. if (STATE_IS_V0(conn->_base.state))
  1927. send_control0_error(conn, ERR_INTERNAL,
  1928. "Refuse to attach stream to non-open, origin circ.");
  1929. else
  1930. connection_write_str_to_buf(
  1931. "551 Can't attach stream to non-open, origin circuit\r\n",
  1932. conn);
  1933. return 0;
  1934. }
  1935. if (circ && circuit_get_cpath_len(circ) < 2) {
  1936. if (STATE_IS_V0(conn->_base.state))
  1937. send_control0_error(conn, ERR_INTERNAL,
  1938. "Refuse to attach stream to one-hop circuit.");
  1939. else
  1940. connection_write_str_to_buf(
  1941. "551 Can't attach stream to one-hop circuit.\r\n",
  1942. conn);
  1943. return 0;
  1944. }
  1945. if (connection_ap_handshake_rewrite_and_attach(ap_conn, circ) < 0) {
  1946. if (STATE_IS_V0(conn->_base.state))
  1947. send_control0_error(conn, ERR_INTERNAL, "Unable to attach stream.");
  1948. else
  1949. connection_write_str_to_buf("551 Unable to attach stream\r\n", conn);
  1950. return 0;
  1951. }
  1952. send_control_done(conn);
  1953. return 0;
  1954. }
  1955. /** Called when we get a POSTDESCRIPTOR message. Try to learn the provided
  1956. * descriptor, and report success or failure. */
  1957. static int
  1958. handle_control_postdescriptor(control_connection_t *conn, uint32_t len,
  1959. const char *body)
  1960. {
  1961. char *desc;
  1962. int v0 = STATE_IS_V0(conn->_base.state);
  1963. const char *msg=NULL;
  1964. uint8_t purpose = ROUTER_PURPOSE_GENERAL;
  1965. if (v0)
  1966. desc = (char*)body;
  1967. else {
  1968. char *cp = memchr(body, '\n', len);
  1969. smartlist_t *args = smartlist_create();
  1970. tor_assert(cp);
  1971. *cp++ = '\0';
  1972. smartlist_split_string(args, body, " ",
  1973. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1974. if (smartlist_len(args)) {
  1975. char *purp = smartlist_get(args,0);
  1976. if (get_purpose(&purp, 0, &purpose) < 0) {
  1977. connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n",
  1978. purp);
  1979. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1980. smartlist_free(args);
  1981. return 0;
  1982. }
  1983. }
  1984. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1985. smartlist_free(args);
  1986. read_escaped_data(cp, len-(cp-body), 1, &desc);
  1987. }
  1988. switch (router_load_single_router(desc, purpose, &msg)) {
  1989. case -1:
  1990. if (!msg) msg = "Could not parse descriptor";
  1991. if (v0)
  1992. send_control0_error(conn,ERR_SYNTAX,msg);
  1993. else
  1994. connection_printf_to_buf(conn, "554 %s\r\n", msg);
  1995. break;
  1996. case 0:
  1997. if (!msg) msg = "Descriptor not added";
  1998. if (v0)
  1999. send_control_done2(conn,msg,0);
  2000. else
  2001. connection_printf_to_buf(conn, "251 %s\r\n",msg);
  2002. break;
  2003. case 1:
  2004. send_control_done(conn);
  2005. break;
  2006. }
  2007. if (!v0)
  2008. tor_free(desc);
  2009. return 0;
  2010. }
  2011. /** Called when we receive a REDIRECTSTERAM command. Try to change the target
  2012. * address of the named AP stream, and report success or failure. */
  2013. static int
  2014. handle_control_redirectstream(control_connection_t *conn, uint32_t len,
  2015. const char *body)
  2016. {
  2017. edge_connection_t *ap_conn = NULL;
  2018. uint32_t conn_id;
  2019. char *new_addr = NULL;
  2020. uint16_t new_port = 0;
  2021. if (STATE_IS_V0(conn->_base.state)) {
  2022. if (len < 6) {
  2023. send_control0_error(conn, ERR_SYNTAX,
  2024. "redirectstream message too short");
  2025. return 0;
  2026. }
  2027. conn_id = ntohl(get_uint32(body));
  2028. if (!(ap_conn = connection_get_by_global_id(conn_id))
  2029. || ap_conn->_base.state != CONN_TYPE_AP
  2030. || ap_conn->socks_request) {
  2031. send_control0_error(conn, ERR_NO_STREAM,
  2032. "No AP connection found with given ID");
  2033. return 0;
  2034. }
  2035. new_addr = tor_strdup(body+4);
  2036. } else {
  2037. smartlist_t *args;
  2038. args = smartlist_create();
  2039. smartlist_split_string(args, body, " ",
  2040. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2041. if (smartlist_len(args) < 2)
  2042. connection_printf_to_buf(conn,
  2043. "512 Missing argument to REDIRECTSTREAM\r\n");
  2044. else if (!(ap_conn = get_stream(smartlist_get(args, 0)))
  2045. || !ap_conn->socks_request) {
  2046. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  2047. (char*)smartlist_get(args, 0));
  2048. } else {
  2049. int ok;
  2050. if (smartlist_len(args) > 2) { /* they included a port too */
  2051. new_port = (uint16_t) tor_parse_ulong(smartlist_get(args, 2),
  2052. 10, 1, 65535, &ok, NULL);
  2053. }
  2054. if (!ok) {
  2055. connection_printf_to_buf(conn, "512 Cannot parse port \"%s\"\r\n",
  2056. (char*)smartlist_get(args, 2));
  2057. } else {
  2058. new_addr = tor_strdup(smartlist_get(args, 1));
  2059. }
  2060. }
  2061. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2062. smartlist_free(args);
  2063. if (!new_addr)
  2064. return 0;
  2065. }
  2066. strlcpy(ap_conn->socks_request->address, new_addr,
  2067. sizeof(ap_conn->socks_request->address));
  2068. if (new_port)
  2069. ap_conn->socks_request->port = new_port;
  2070. tor_free(new_addr);
  2071. send_control_done(conn);
  2072. return 0;
  2073. }
  2074. /** Called when we get a CLOSESTREAM command; try to close the named stream
  2075. * and report success or failure. */
  2076. static int
  2077. handle_control_closestream(control_connection_t *conn, uint32_t len,
  2078. const char *body)
  2079. {
  2080. edge_connection_t *ap_conn=NULL;
  2081. uint8_t reason=0;
  2082. if (STATE_IS_V0(conn->_base.state)) {
  2083. uint32_t conn_id;
  2084. if (len < 6) {
  2085. send_control0_error(conn, ERR_SYNTAX, "closestream message too short");
  2086. return 0;
  2087. }
  2088. conn_id = ntohl(get_uint32(body));
  2089. reason = *(uint8_t*)(body+4);
  2090. if (!(ap_conn = connection_get_by_global_id(conn_id))
  2091. || ap_conn->_base.state != CONN_TYPE_AP
  2092. || ap_conn->socks_request) {
  2093. send_control0_error(conn, ERR_NO_STREAM,
  2094. "No AP connection found with given ID");
  2095. return 0;
  2096. }
  2097. } else {
  2098. smartlist_t *args;
  2099. int ok;
  2100. args = smartlist_create();
  2101. smartlist_split_string(args, body, " ",
  2102. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2103. if (smartlist_len(args)<2)
  2104. connection_printf_to_buf(conn,
  2105. "512 Missing argument to CLOSESTREAM\r\n");
  2106. else if (!(ap_conn = get_stream(smartlist_get(args, 0))))
  2107. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  2108. (char*)smartlist_get(args, 0));
  2109. else {
  2110. reason = (uint8_t) tor_parse_ulong(smartlist_get(args,1), 10, 0, 255,
  2111. &ok, NULL);
  2112. if (!ok) {
  2113. connection_printf_to_buf(conn, "552 Unrecognized reason \"%s\"\r\n",
  2114. (char*)smartlist_get(args, 1));
  2115. ap_conn = NULL;
  2116. }
  2117. }
  2118. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2119. smartlist_free(args);
  2120. if (!ap_conn)
  2121. return 0;
  2122. }
  2123. connection_mark_unattached_ap(ap_conn, reason);
  2124. send_control_done(conn);
  2125. return 0;
  2126. }
  2127. /** Called when we get a CLOSECIRCUIT command; try to close the named circuit
  2128. * and report success or failure. */
  2129. static int
  2130. handle_control_closecircuit(control_connection_t *conn, uint32_t len,
  2131. const char *body)
  2132. {
  2133. origin_circuit_t *circ = NULL;
  2134. int safe = 0;
  2135. if (STATE_IS_V0(conn->_base.state)) {
  2136. uint32_t circ_id;
  2137. if (len < 5) {
  2138. send_control0_error(conn, ERR_SYNTAX, "closecircuit message too short");
  2139. return 0;
  2140. }
  2141. circ_id = ntohl(get_uint32(body));
  2142. safe = (*(uint8_t*)(body+4)) & 1;
  2143. if (!(circ = circuit_get_by_global_id(circ_id))) {
  2144. send_control0_error(conn, ERR_NO_CIRC,
  2145. "No circuit found with given ID");
  2146. return 0;
  2147. }
  2148. } else {
  2149. smartlist_t *args;
  2150. args = smartlist_create();
  2151. smartlist_split_string(args, body, " ",
  2152. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2153. if (smartlist_len(args)<1)
  2154. connection_printf_to_buf(conn,
  2155. "512 Missing argument to CLOSECIRCUIT\r\n");
  2156. else if (!(circ=get_circ(smartlist_get(args, 0))))
  2157. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  2158. (char*)smartlist_get(args, 0));
  2159. else {
  2160. int i;
  2161. for (i=1; i < smartlist_len(args); ++i) {
  2162. if (!strcasecmp(smartlist_get(args, i), "IfUnused"))
  2163. safe = 1;
  2164. else
  2165. log_info(LD_CONTROL, "Skipping unknown option %s",
  2166. (char*)smartlist_get(args,i));
  2167. }
  2168. }
  2169. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2170. smartlist_free(args);
  2171. if (!circ)
  2172. return 0;
  2173. }
  2174. if (!safe || !circ->p_streams) {
  2175. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_NONE);
  2176. }
  2177. send_control_done(conn);
  2178. return 0;
  2179. }
  2180. static int
  2181. handle_control_usefeature(control_connection_t *conn,
  2182. uint32_t len,
  2183. const char *body)
  2184. {
  2185. smartlist_t *args;
  2186. int verbose_names = 0, extended_events = 0;
  2187. int bad = 0;
  2188. (void) len; /* body is nul-terminated; it's safe to ignore the length */
  2189. tor_assert(! STATE_IS_V0(conn->_base.state));
  2190. args = smartlist_create();
  2191. smartlist_split_string(args, body, " ",
  2192. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2193. SMARTLIST_FOREACH(args, const char *, arg, {
  2194. if (!strcasecmp(arg, "VERBOSE_NAMES"))
  2195. verbose_names = 1;
  2196. else if (!strcasecmp(arg, "EXTENDED_EVENTS"))
  2197. extended_events = 1;
  2198. else {
  2199. connection_printf_to_buf(conn, "552 Unrecognized feature \"%s\"\r\n",
  2200. arg);
  2201. bad = 1;
  2202. break;
  2203. }
  2204. });
  2205. if (!bad) {
  2206. if (verbose_names) {
  2207. conn->use_long_names = 1;
  2208. control_update_global_event_mask();
  2209. }
  2210. if (extended_events)
  2211. conn->use_extended_events = 1;
  2212. send_control_done(conn);
  2213. }
  2214. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2215. smartlist_free(args);
  2216. return 0;
  2217. }
  2218. /** Called when we get a v0 FRAGMENTHEADER or FRAGMENT command; try to append
  2219. * the data to conn->incoming_cmd, setting conn->incoming_(type|len|cur_len)
  2220. * as appropriate. If the command is malformed, drop it and all pending
  2221. * fragments and report failure.
  2222. */
  2223. static int
  2224. handle_control_fragments(control_connection_t *conn, uint16_t command_type,
  2225. uint32_t body_len, char *body)
  2226. {
  2227. if (command_type == CONTROL0_CMD_FRAGMENTHEADER) {
  2228. if (conn->incoming_cmd) {
  2229. log_warn(LD_CONTROL, "Dropping incomplete fragmented command; new "
  2230. "fragmented command was begun.");
  2231. tor_free(conn->incoming_cmd);
  2232. }
  2233. if (body_len < 6) {
  2234. send_control0_error(conn, ERR_SYNTAX, "FRAGMENTHEADER too short.");
  2235. return 0;
  2236. }
  2237. conn->incoming_cmd_type = ntohs(get_uint16(body));
  2238. conn->incoming_cmd_len = ntohl(get_uint32(body+2));
  2239. conn->incoming_cmd_cur_len = 0;
  2240. conn->incoming_cmd = tor_malloc(conn->incoming_cmd_len);
  2241. body += 6;
  2242. body_len -= 6;
  2243. } else if (command_type == CONTROL0_CMD_FRAGMENT) {
  2244. if (!conn->incoming_cmd) {
  2245. send_control0_error(conn, ERR_SYNTAX, "Out-of-place FRAGMENT");
  2246. return 0;
  2247. }
  2248. } else {
  2249. tor_assert(0);
  2250. }
  2251. if (conn->incoming_cmd_cur_len + body_len > conn->incoming_cmd_len) {
  2252. tor_free(conn->incoming_cmd);
  2253. send_control0_error(conn, ERR_SYNTAX,
  2254. "Fragmented data exceeds declared length");
  2255. return 0;
  2256. }
  2257. memcpy(conn->incoming_cmd + conn->incoming_cmd_cur_len,
  2258. body, body_len);
  2259. conn->incoming_cmd_cur_len += body_len;
  2260. return 0;
  2261. }
  2262. /** Called when <b>conn</b> has no more bytes left on its outbuf. */
  2263. int
  2264. connection_control_finished_flushing(control_connection_t *conn)
  2265. {
  2266. tor_assert(conn);
  2267. connection_stop_writing(TO_CONN(conn));
  2268. return 0;
  2269. }
  2270. /** Called when <b>conn</b> has gotten its socket closed. */
  2271. int
  2272. connection_control_reached_eof(control_connection_t *conn)
  2273. {
  2274. tor_assert(conn);
  2275. log_info(LD_CONTROL,"Control connection reached EOF. Closing.");
  2276. connection_mark_for_close(TO_CONN(conn));
  2277. return 0;
  2278. }
  2279. /** Called when data has arrived on a v1 control connection: Try to fetch
  2280. * commands from conn->inbuf, and execute them.
  2281. */
  2282. static int
  2283. connection_control_process_inbuf_v1(control_connection_t *conn)
  2284. {
  2285. size_t data_len;
  2286. int cmd_len;
  2287. char *args;
  2288. tor_assert(conn);
  2289. tor_assert(conn->_base.state == CONTROL_CONN_STATE_OPEN_V1 ||
  2290. conn->_base.state == CONTROL_CONN_STATE_NEEDAUTH_V1);
  2291. if (!conn->incoming_cmd) {
  2292. conn->incoming_cmd = tor_malloc(1024);
  2293. conn->incoming_cmd_len = 1024;
  2294. conn->incoming_cmd_cur_len = 0;
  2295. }
  2296. again:
  2297. while (1) {
  2298. size_t last_idx;
  2299. int r;
  2300. /* First, fetch a line. */
  2301. do {
  2302. data_len = conn->incoming_cmd_len - conn->incoming_cmd_cur_len;
  2303. r = fetch_from_buf_line(conn->_base.inbuf,
  2304. conn->incoming_cmd+conn->incoming_cmd_cur_len,
  2305. &data_len);
  2306. if (r == 0)
  2307. /* Line not all here yet. Wait. */
  2308. return 0;
  2309. else if (r == -1) {
  2310. while (conn->incoming_cmd_len < data_len+conn->incoming_cmd_cur_len)
  2311. conn->incoming_cmd_len *= 2;
  2312. conn->incoming_cmd = tor_realloc(conn->incoming_cmd,
  2313. conn->incoming_cmd_len);
  2314. }
  2315. } while (r != 1);
  2316. tor_assert(data_len);
  2317. last_idx = conn->incoming_cmd_cur_len;
  2318. conn->incoming_cmd_cur_len += data_len;
  2319. /* We have appended a line to incoming_cmd. Is the command done? */
  2320. if (last_idx == 0 && *conn->incoming_cmd != '+')
  2321. /* One line command, didn't start with '+'. */
  2322. break;
  2323. if (last_idx+3 == conn->incoming_cmd_cur_len &&
  2324. !memcmp(conn->incoming_cmd + last_idx, ".\r\n", 3)) {
  2325. /* Just appended ".\r\n"; we're done. Remove it. */
  2326. conn->incoming_cmd_cur_len -= 3;
  2327. break;
  2328. }
  2329. /* Otherwise, read another line. */
  2330. }
  2331. data_len = conn->incoming_cmd_cur_len;
  2332. /* Okay, we now have a command sitting on conn->incoming_cmd. See if we
  2333. * recognize it.
  2334. */
  2335. cmd_len = 0;
  2336. while ((size_t)cmd_len < data_len
  2337. && !TOR_ISSPACE(conn->incoming_cmd[cmd_len]))
  2338. ++cmd_len;
  2339. data_len -= cmd_len;
  2340. conn->incoming_cmd[cmd_len]='\0';
  2341. args = conn->incoming_cmd+cmd_len+1;
  2342. while (*args == ' ' || *args == '\t') {
  2343. ++args;
  2344. --data_len;
  2345. }
  2346. if (!strcasecmp(conn->incoming_cmd, "QUIT")) {
  2347. connection_write_str_to_buf("250 closing connection\r\n", conn);
  2348. connection_mark_for_close(TO_CONN(conn));
  2349. return 0;
  2350. }
  2351. if (conn->_base.state == CONTROL_CONN_STATE_NEEDAUTH_V1 &&
  2352. strcasecmp(conn->incoming_cmd, "AUTHENTICATE")) {
  2353. connection_write_str_to_buf("514 Authentication required.\r\n", conn);
  2354. conn->incoming_cmd_cur_len = 0;
  2355. goto again;
  2356. }
  2357. if (!strcasecmp(conn->incoming_cmd, "SETCONF")) {
  2358. if (handle_control_setconf(conn, data_len, args))
  2359. return -1;
  2360. } else if (!strcasecmp(conn->incoming_cmd, "RESETCONF")) {
  2361. if (handle_control_resetconf(conn, data_len, args))
  2362. return -1;
  2363. } else if (!strcasecmp(conn->incoming_cmd, "GETCONF")) {
  2364. if (handle_control_getconf(conn, data_len, args))
  2365. return -1;
  2366. } else if (!strcasecmp(conn->incoming_cmd, "SETEVENTS")) {
  2367. if (handle_control_setevents(conn, data_len, args))
  2368. return -1;
  2369. } else if (!strcasecmp(conn->incoming_cmd, "AUTHENTICATE")) {
  2370. if (handle_control_authenticate(conn, data_len, args))
  2371. return -1;
  2372. } else if (!strcasecmp(conn->incoming_cmd, "SAVECONF")) {
  2373. if (handle_control_saveconf(conn, data_len, args))
  2374. return -1;
  2375. } else if (!strcasecmp(conn->incoming_cmd, "SIGNAL")) {
  2376. if (handle_control_signal(conn, data_len, args))
  2377. return -1;
  2378. } else if (!strcasecmp(conn->incoming_cmd, "MAPADDRESS")) {
  2379. if (handle_control_mapaddress(conn, data_len, args))
  2380. return -1;
  2381. } else if (!strcasecmp(conn->incoming_cmd, "GETINFO")) {
  2382. if (handle_control_getinfo(conn, data_len, args))
  2383. return -1;
  2384. } else if (!strcasecmp(conn->incoming_cmd, "EXTENDCIRCUIT")) {
  2385. if (handle_control_extendcircuit(conn, data_len, args))
  2386. return -1;
  2387. } else if (!strcasecmp(conn->incoming_cmd, "SETCIRCUITPURPOSE")) {
  2388. if (handle_control_setpurpose(conn, 1, data_len, args))
  2389. return -1;
  2390. } else if (!strcasecmp(conn->incoming_cmd, "SETROUTERPURPOSE")) {
  2391. if (handle_control_setpurpose(conn, 0, data_len, args))
  2392. return -1;
  2393. } else if (!strcasecmp(conn->incoming_cmd, "ATTACHSTREAM")) {
  2394. if (handle_control_attachstream(conn, data_len, args))
  2395. return -1;
  2396. } else if (!strcasecmp(conn->incoming_cmd, "+POSTDESCRIPTOR")) {
  2397. if (handle_control_postdescriptor(conn, data_len, args))
  2398. return -1;
  2399. } else if (!strcasecmp(conn->incoming_cmd, "REDIRECTSTREAM")) {
  2400. if (handle_control_redirectstream(conn, data_len, args))
  2401. return -1;
  2402. } else if (!strcasecmp(conn->incoming_cmd, "CLOSESTREAM")) {
  2403. if (handle_control_closestream(conn, data_len, args))
  2404. return -1;
  2405. } else if (!strcasecmp(conn->incoming_cmd, "CLOSECIRCUIT")) {
  2406. if (handle_control_closecircuit(conn, data_len, args))
  2407. return -1;
  2408. } else if (!strcasecmp(conn->incoming_cmd, "USEFEATURE")) {
  2409. if (handle_control_usefeature(conn, data_len, args))
  2410. return -1;
  2411. } else {
  2412. connection_printf_to_buf(conn, "510 Unrecognized command \"%s\"\r\n",
  2413. conn->incoming_cmd);
  2414. }
  2415. conn->incoming_cmd_cur_len = 0;
  2416. goto again;
  2417. }
  2418. /** Called when data has arrived on a v0 control connection: Try to fetch
  2419. * commands from conn->inbuf, and execute them.
  2420. */
  2421. static int
  2422. connection_control_process_inbuf_v0(control_connection_t *conn)
  2423. {
  2424. uint32_t body_len;
  2425. uint16_t command_type;
  2426. char *body=NULL;
  2427. again:
  2428. /* Try to suck a control message from the buffer. */
  2429. switch (fetch_from_buf_control0(conn->_base.inbuf, &body_len, &command_type,
  2430. &body,
  2431. conn->_base.state == CONTROL_CONN_STATE_NEEDAUTH_V0))
  2432. {
  2433. case -2:
  2434. tor_free(body);
  2435. log_info(LD_CONTROL,
  2436. "Detected v1 control protocol on connection (fd %d)",
  2437. conn->_base.s);
  2438. conn->_base.state = CONTROL_CONN_STATE_NEEDAUTH_V1;
  2439. return connection_control_process_inbuf_v1(conn);
  2440. case -1:
  2441. tor_free(body);
  2442. log_warn(LD_CONTROL, "Error in control command. Failing.");
  2443. return -1;
  2444. case 0:
  2445. /* Control command not all here yet. Wait. */
  2446. return 0;
  2447. case 1:
  2448. /* We got a command. Process it. */
  2449. break;
  2450. default:
  2451. tor_assert(0);
  2452. }
  2453. /* We got a command. If we need authentication, only authentication
  2454. * commands will be considered. */
  2455. if (conn->_base.state == CONTROL_CONN_STATE_NEEDAUTH_V0 &&
  2456. command_type != CONTROL0_CMD_AUTHENTICATE) {
  2457. log_info(LD_CONTROL, "Rejecting '%s' command; authentication needed.",
  2458. control_cmd_to_string(command_type));
  2459. send_control0_error(conn, ERR_UNAUTHORIZED, "Authentication required");
  2460. tor_free(body);
  2461. goto again;
  2462. }
  2463. if (command_type == CONTROL0_CMD_FRAGMENTHEADER ||
  2464. command_type == CONTROL0_CMD_FRAGMENT) {
  2465. if (handle_control_fragments(conn, command_type, body_len, body))
  2466. return -1;
  2467. tor_free(body);
  2468. if (conn->incoming_cmd_cur_len != conn->incoming_cmd_len)
  2469. goto again;
  2470. command_type = conn->incoming_cmd_type;
  2471. body_len = conn->incoming_cmd_len;
  2472. body = conn->incoming_cmd;
  2473. conn->incoming_cmd = NULL;
  2474. } else if (conn->incoming_cmd) {
  2475. log_warn(LD_CONTROL, "Dropping incomplete fragmented command");
  2476. tor_free(conn->incoming_cmd);
  2477. }
  2478. /* Okay, we're willing to process the command. */
  2479. switch (command_type)
  2480. {
  2481. case CONTROL0_CMD_SETCONF:
  2482. if (handle_control_setconf(conn, body_len, body))
  2483. return -1;
  2484. break;
  2485. case CONTROL0_CMD_GETCONF:
  2486. if (handle_control_getconf(conn, body_len, body))
  2487. return -1;
  2488. break;
  2489. case CONTROL0_CMD_SETEVENTS:
  2490. if (handle_control_setevents(conn, body_len, body))
  2491. return -1;
  2492. break;
  2493. case CONTROL0_CMD_AUTHENTICATE:
  2494. if (handle_control_authenticate(conn, body_len, body))
  2495. return -1;
  2496. break;
  2497. case CONTROL0_CMD_SAVECONF:
  2498. if (handle_control_saveconf(conn, body_len, body))
  2499. return -1;
  2500. break;
  2501. case CONTROL0_CMD_SIGNAL:
  2502. if (handle_control_signal(conn, body_len, body))
  2503. return -1;
  2504. break;
  2505. case CONTROL0_CMD_MAPADDRESS:
  2506. if (handle_control_mapaddress(conn, body_len, body))
  2507. return -1;
  2508. break;
  2509. case CONTROL0_CMD_GETINFO:
  2510. if (handle_control_getinfo(conn, body_len, body))
  2511. return -1;
  2512. break;
  2513. case CONTROL0_CMD_EXTENDCIRCUIT:
  2514. if (handle_control_extendcircuit(conn, body_len, body))
  2515. return -1;
  2516. break;
  2517. case CONTROL0_CMD_ATTACHSTREAM:
  2518. if (handle_control_attachstream(conn, body_len, body))
  2519. return -1;
  2520. break;
  2521. case CONTROL0_CMD_POSTDESCRIPTOR:
  2522. if (handle_control_postdescriptor(conn, body_len, body))
  2523. return -1;
  2524. break;
  2525. case CONTROL0_CMD_REDIRECTSTREAM:
  2526. if (handle_control_redirectstream(conn, body_len, body))
  2527. return -1;
  2528. break;
  2529. case CONTROL0_CMD_CLOSESTREAM:
  2530. if (handle_control_closestream(conn, body_len, body))
  2531. return -1;
  2532. break;
  2533. case CONTROL0_CMD_CLOSECIRCUIT:
  2534. if (handle_control_closecircuit(conn, body_len, body))
  2535. return -1;
  2536. break;
  2537. case CONTROL0_CMD_ERROR:
  2538. case CONTROL0_CMD_DONE:
  2539. case CONTROL0_CMD_CONFVALUE:
  2540. case CONTROL0_CMD_EVENT:
  2541. case CONTROL0_CMD_INFOVALUE:
  2542. log_warn(LD_CONTROL, "Received client-only '%s' command; ignoring.",
  2543. control_cmd_to_string(command_type));
  2544. send_control0_error(conn, ERR_UNRECOGNIZED_TYPE,
  2545. "Command type only valid from server to tor client");
  2546. break;
  2547. case CONTROL0_CMD_FRAGMENTHEADER:
  2548. case CONTROL0_CMD_FRAGMENT:
  2549. log_warn(LD_CONTROL,
  2550. "Recieved command fragment out of order; ignoring.");
  2551. send_control0_error(conn, ERR_SYNTAX, "Bad fragmentation on command.");
  2552. default:
  2553. log_warn(LD_CONTROL, "Received unrecognized command type %d; ignoring.",
  2554. (int)command_type);
  2555. send_control0_error(conn, ERR_UNRECOGNIZED_TYPE,
  2556. "Unrecognized command type");
  2557. break;
  2558. }
  2559. tor_free(body);
  2560. goto again; /* There might be more data. */
  2561. }
  2562. /** Called when <b>conn</b> has received more bytes on its inbuf.
  2563. */
  2564. int
  2565. connection_control_process_inbuf(control_connection_t *conn)
  2566. {
  2567. tor_assert(conn);
  2568. if (STATE_IS_V0(conn->_base.state))
  2569. return connection_control_process_inbuf_v0(conn);
  2570. else
  2571. return connection_control_process_inbuf_v1(conn);
  2572. }
  2573. /** Something has happened to circuit <b>circ</b>: tell any interested
  2574. * control connections. */
  2575. int
  2576. control_event_circuit_status(origin_circuit_t *circ, circuit_status_event_t tp)
  2577. {
  2578. char *path=NULL, *msg;
  2579. if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS))
  2580. return 0;
  2581. tor_assert(circ);
  2582. if (EVENT_IS_INTERESTING0(EVENT_CIRCUIT_STATUS) ||
  2583. EVENT_IS_INTERESTING1S(EVENT_CIRCUIT_STATUS))
  2584. path = circuit_list_path(circ,0);
  2585. if (EVENT_IS_INTERESTING0(EVENT_CIRCUIT_STATUS)) {
  2586. size_t path_len = strlen(path);
  2587. msg = tor_malloc(1+4+path_len+1); /* event, circid, path, NUL. */
  2588. msg[0] = (uint8_t) tp;
  2589. set_uint32(msg+1, htonl(circ->global_identifier));
  2590. strlcpy(msg+5,path,path_len+1);
  2591. send_control0_event(EVENT_CIRCUIT_STATUS, (uint32_t)(path_len+6), msg);
  2592. tor_free(msg);
  2593. }
  2594. if (EVENT_IS_INTERESTING1(EVENT_CIRCUIT_STATUS)) {
  2595. const char *status;
  2596. switch (tp)
  2597. {
  2598. case CIRC_EVENT_LAUNCHED: status = "LAUNCHED"; break;
  2599. case CIRC_EVENT_BUILT: status = "BUILT"; break;
  2600. case CIRC_EVENT_EXTENDED: status = "EXTENDED"; break;
  2601. case CIRC_EVENT_FAILED: status = "FAILED"; break;
  2602. case CIRC_EVENT_CLOSED: status = "CLOSED"; break;
  2603. default:
  2604. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  2605. return 0;
  2606. }
  2607. if (EVENT_IS_INTERESTING1S(EVENT_CIRCUIT_STATUS)) {
  2608. send_control1_event(EVENT_CIRCUIT_STATUS, SHORT_NAMES,
  2609. "650 CIRC %lu %s %s\r\n",
  2610. (unsigned long)circ->global_identifier,
  2611. status, path);
  2612. }
  2613. if (EVENT_IS_INTERESTING1L(EVENT_CIRCUIT_STATUS)) {
  2614. char *vpath = circuit_list_path_for_controller(circ);
  2615. send_control1_event(EVENT_CIRCUIT_STATUS, LONG_NAMES,
  2616. "650 CIRC %lu %s %s\r\n",
  2617. (unsigned long)circ->global_identifier,
  2618. status, vpath);
  2619. tor_free(vpath);
  2620. }
  2621. }
  2622. tor_free(path);
  2623. return 0;
  2624. }
  2625. /** Given an AP connection <b>conn</b> and a <b>len</b>-character buffer
  2626. * <b>buf</b>, determine the address:port combination requested on
  2627. * <b>conn</b>, and write it to <b>buf</b>. Return 0 on success, -1 on
  2628. * failure. */
  2629. static int
  2630. write_stream_target_to_buf(edge_connection_t *conn, char *buf, size_t len)
  2631. {
  2632. char buf2[256];
  2633. if (conn->chosen_exit_name)
  2634. if (tor_snprintf(buf2, sizeof(buf2), ".%s.exit", conn->chosen_exit_name)<0)
  2635. return -1;
  2636. if (tor_snprintf(buf, len, "%s%s%s:%d",
  2637. conn->socks_request->address,
  2638. conn->chosen_exit_name ? buf2 : "",
  2639. !conn->chosen_exit_name &&
  2640. connection_edge_is_rendezvous_stream(conn) ? ".onion" : "",
  2641. conn->socks_request->port)<0)
  2642. return -1;
  2643. return 0;
  2644. }
  2645. /** Something has happened to the stream associated with AP connection
  2646. * <b>conn</b>: tell any interested control connections. */
  2647. int
  2648. control_event_stream_status(edge_connection_t *conn, stream_status_event_t tp)
  2649. {
  2650. char *msg;
  2651. size_t len;
  2652. char buf[256];
  2653. tor_assert(conn->socks_request);
  2654. if (!EVENT_IS_INTERESTING(EVENT_STREAM_STATUS))
  2655. return 0;
  2656. write_stream_target_to_buf(conn, buf, sizeof(buf));
  2657. if (EVENT_IS_INTERESTING0(EVENT_STREAM_STATUS)) {
  2658. len = strlen(buf);
  2659. msg = tor_malloc(5+len+1);
  2660. msg[0] = (uint8_t) tp;
  2661. set_uint32(msg+1, htonl(conn->global_identifier));
  2662. strlcpy(msg+5, buf, len+1);
  2663. send_control0_event(EVENT_STREAM_STATUS, (uint32_t)(5+len+1), msg);
  2664. tor_free(msg);
  2665. }
  2666. if (EVENT_IS_INTERESTING1(EVENT_STREAM_STATUS)) {
  2667. const char *status;
  2668. circuit_t *circ;
  2669. origin_circuit_t *origin_circ = NULL;
  2670. switch (tp)
  2671. {
  2672. case STREAM_EVENT_SENT_CONNECT: status = "SENTCONNECT"; break;
  2673. case STREAM_EVENT_SENT_RESOLVE: status = "SENTRESOLVE"; break;
  2674. case STREAM_EVENT_SUCCEEDED: status = "SUCCEEDED"; break;
  2675. case STREAM_EVENT_FAILED: status = "FAILED"; break;
  2676. case STREAM_EVENT_CLOSED: status = "CLOSED"; break;
  2677. case STREAM_EVENT_NEW: status = "NEW"; break;
  2678. case STREAM_EVENT_NEW_RESOLVE: status = "NEWRESOLVE"; break;
  2679. case STREAM_EVENT_FAILED_RETRIABLE: status = "DETACHED"; break;
  2680. default:
  2681. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  2682. return 0;
  2683. }
  2684. circ = circuit_get_by_edge_conn(conn);
  2685. if (circ && CIRCUIT_IS_ORIGIN(circ))
  2686. origin_circ = TO_ORIGIN_CIRCUIT(circ);
  2687. send_control1_event(EVENT_STREAM_STATUS, ALL_NAMES,
  2688. "650 STREAM %lu %s %lu %s\r\n",
  2689. (unsigned long)conn->global_identifier, status,
  2690. origin_circ?
  2691. (unsigned long)origin_circ->global_identifier : 0ul,
  2692. buf);
  2693. /* XXX need to specify its intended exit, etc? */
  2694. }
  2695. return 0;
  2696. }
  2697. static void
  2698. orconn_target_get_name(int long_names,
  2699. char *name, size_t len, or_connection_t *conn)
  2700. {
  2701. if (long_names) {
  2702. if (conn->nickname)
  2703. strlcpy(name, conn->nickname, len);
  2704. else
  2705. tor_snprintf(name, len, "%s:%d",
  2706. conn->_base.address, conn->_base.port);
  2707. } else {
  2708. routerinfo_t *ri = router_get_by_digest(conn->identity_digest);
  2709. if (ri) {
  2710. tor_assert(len > MAX_VERBOSE_NICKNAME_LEN);
  2711. router_get_verbose_nickname(name, ri);
  2712. } else if (! tor_digest_is_zero(conn->identity_digest)) {
  2713. name[0] = '$';
  2714. base16_encode(name+1, len-1, conn->identity_digest,
  2715. DIGEST_LEN);
  2716. } else {
  2717. tor_snprintf(name, len, "%s:%d",
  2718. conn->_base.address, conn->_base.port);
  2719. }
  2720. }
  2721. }
  2722. /** Something has happened to the OR connection <b>conn</b>: tell any
  2723. * interested control connections. */
  2724. int
  2725. control_event_or_conn_status(or_connection_t *conn,or_conn_status_event_t tp)
  2726. {
  2727. char buf[HEX_DIGEST_LEN+3]; /* status, dollar, identity, NUL */
  2728. size_t len;
  2729. if (!EVENT_IS_INTERESTING(EVENT_OR_CONN_STATUS))
  2730. return 0;
  2731. if (EVENT_IS_INTERESTING0(EVENT_OR_CONN_STATUS)) {
  2732. buf[0] = (uint8_t)tp;
  2733. strlcpy(buf+1,conn->nickname ? conn->nickname : "",sizeof(buf)-1);
  2734. len = strlen(buf+1);
  2735. send_control0_event(EVENT_OR_CONN_STATUS, (uint32_t)(len+1), buf);
  2736. }
  2737. if (EVENT_IS_INTERESTING1(EVENT_OR_CONN_STATUS)) {
  2738. const char *status;
  2739. char name[128];
  2740. switch (tp)
  2741. {
  2742. case OR_CONN_EVENT_LAUNCHED: status = "LAUNCHED"; break;
  2743. case OR_CONN_EVENT_CONNECTED: status = "CONNECTED"; break;
  2744. case OR_CONN_EVENT_FAILED: status = "FAILED"; break;
  2745. case OR_CONN_EVENT_CLOSED: status = "CLOSED"; break;
  2746. case OR_CONN_EVENT_NEW: status = "NEW"; break;
  2747. default:
  2748. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  2749. return 0;
  2750. }
  2751. if (EVENT_IS_INTERESTING1S(EVENT_OR_CONN_STATUS)) {
  2752. orconn_target_get_name(0, name, sizeof(name), conn);
  2753. send_control1_event(EVENT_OR_CONN_STATUS, SHORT_NAMES,
  2754. "650 ORCONN %s %s\r\n",
  2755. name, status);
  2756. }
  2757. if (EVENT_IS_INTERESTING1L(EVENT_OR_CONN_STATUS)) {
  2758. orconn_target_get_name(1, name, sizeof(name), conn);
  2759. send_control1_event(EVENT_OR_CONN_STATUS, LONG_NAMES,
  2760. "650 ORCONN %s %s\r\n",
  2761. name, status);
  2762. }
  2763. }
  2764. return 0;
  2765. }
  2766. /** A second or more has elapsed: tell any interested control
  2767. * connections how much bandwidth we used. */
  2768. int
  2769. control_event_bandwidth_used(uint32_t n_read, uint32_t n_written)
  2770. {
  2771. char buf[8];
  2772. if (EVENT_IS_INTERESTING0(EVENT_BANDWIDTH_USED)) {
  2773. set_uint32(buf, htonl(n_read));
  2774. set_uint32(buf+4, htonl(n_written));
  2775. send_control0_event(EVENT_BANDWIDTH_USED, 8, buf);
  2776. }
  2777. if (EVENT_IS_INTERESTING1(EVENT_BANDWIDTH_USED)) {
  2778. send_control1_event(EVENT_BANDWIDTH_USED, ALL_NAMES,
  2779. "650 BW %lu %lu\r\n",
  2780. (unsigned long)n_read,
  2781. (unsigned long)n_written);
  2782. }
  2783. return 0;
  2784. }
  2785. /** Called when we are sending a log message to the controllers: suspend
  2786. * sending further log messages to the controllers until we're done. Used by
  2787. * CONN_LOG_PROTECT. */
  2788. void
  2789. disable_control_logging(void)
  2790. {
  2791. ++disable_log_messages;
  2792. }
  2793. /** We're done sending a log message to the controllers: re-enable controller
  2794. * logging. Used by CONN_LOG_PROTECT. */
  2795. void
  2796. enable_control_logging(void)
  2797. {
  2798. if (--disable_log_messages < 0)
  2799. tor_assert(0);
  2800. }
  2801. /** We got a log message: tell any interested control connections. */
  2802. void
  2803. control_event_logmsg(int severity, unsigned int domain, const char *msg)
  2804. {
  2805. int oldlog, event;
  2806. (void) domain;
  2807. if (disable_log_messages)
  2808. return;
  2809. oldlog = EVENT_IS_INTERESTING0(EVENT_LOG_OBSOLETE) &&
  2810. (severity == LOG_NOTICE || severity == LOG_WARN || severity == LOG_ERR);
  2811. event = log_severity_to_event(severity);
  2812. if (event<0 || !EVENT_IS_INTERESTING0(event))
  2813. event = 0;
  2814. if (oldlog || event) {
  2815. size_t len = strlen(msg);
  2816. ++disable_log_messages;
  2817. if (event)
  2818. send_control0_event(event, (uint32_t)(len+1), msg);
  2819. if (oldlog)
  2820. send_control0_event(EVENT_LOG_OBSOLETE, (uint32_t)(len+1), msg);
  2821. --disable_log_messages;
  2822. }
  2823. event = log_severity_to_event(severity);
  2824. if (event >= 0 && EVENT_IS_INTERESTING1(event)) {
  2825. char *b = NULL;
  2826. const char *s;
  2827. if (strchr(msg, '\n')) {
  2828. char *cp;
  2829. b = tor_strdup(msg);
  2830. for (cp = b; *cp; ++cp)
  2831. if (*cp == '\r' || *cp == '\n')
  2832. *cp = ' ';
  2833. }
  2834. switch (severity) {
  2835. case LOG_DEBUG: s = "DEBUG"; break;
  2836. case LOG_INFO: s = "INFO"; break;
  2837. case LOG_NOTICE: s = "NOTICE"; break;
  2838. case LOG_WARN: s = "WARN"; break;
  2839. case LOG_ERR: s = "ERR"; break;
  2840. default: s = "UnknownLogSeverity"; break;
  2841. }
  2842. ++disable_log_messages;
  2843. send_control1_event(event, ALL_NAMES, "650 %s %s\r\n", s, b?b:msg);
  2844. --disable_log_messages;
  2845. tor_free(b);
  2846. }
  2847. }
  2848. /** Called whenever we receive new router descriptors: tell any
  2849. * interested control connections. <b>routers</b> is a list of
  2850. * DIGEST_LEN-byte identity digests.
  2851. */
  2852. int
  2853. control_event_descriptors_changed(smartlist_t *routers)
  2854. {
  2855. size_t len;
  2856. char *msg;
  2857. smartlist_t *identities = NULL;
  2858. char buf[HEX_DIGEST_LEN+1];
  2859. if (!EVENT_IS_INTERESTING(EVENT_NEW_DESC))
  2860. return 0;
  2861. if (EVENT_IS_INTERESTING0(EVENT_NEW_DESC) ||
  2862. EVENT_IS_INTERESTING1S(EVENT_NEW_DESC)) {
  2863. identities = smartlist_create();
  2864. SMARTLIST_FOREACH(routers, routerinfo_t *, r,
  2865. {
  2866. base16_encode(buf,sizeof(buf),r->cache_info.identity_digest,DIGEST_LEN);
  2867. smartlist_add(identities, tor_strdup(buf));
  2868. });
  2869. }
  2870. if (EVENT_IS_INTERESTING0(EVENT_NEW_DESC)) {
  2871. msg = smartlist_join_strings(identities, ",", 0, &len);
  2872. send_control0_event(EVENT_NEW_DESC, len+1, msg);
  2873. tor_free(msg);
  2874. }
  2875. if (EVENT_IS_INTERESTING1S(EVENT_NEW_DESC)) {
  2876. char *ids = smartlist_join_strings(identities, " ", 0, &len);
  2877. size_t len = strlen(ids)+32;
  2878. msg = tor_malloc(len);
  2879. tor_snprintf(msg, len, "650 NEWDESC %s\r\n", ids);
  2880. send_control1_event_string(EVENT_NEW_DESC, SHORT_NAMES, msg);
  2881. tor_free(ids);
  2882. tor_free(msg);
  2883. }
  2884. if (EVENT_IS_INTERESTING1L(EVENT_NEW_DESC)) {
  2885. smartlist_t *names = smartlist_create();
  2886. char *ids;
  2887. size_t len;
  2888. SMARTLIST_FOREACH(routers, routerinfo_t *, ri, {
  2889. char *b = tor_malloc(MAX_VERBOSE_NICKNAME_LEN+1);
  2890. smartlist_add(names, b);
  2891. });
  2892. ids = smartlist_join_strings(names, " ", 0, &len);
  2893. len = strlen(ids)+32;
  2894. msg = tor_malloc(len);
  2895. tor_snprintf(msg, len, "650 NEWDESC %s\r\n", ids);
  2896. send_control1_event_string(EVENT_NEW_DESC, LONG_NAMES, msg);
  2897. tor_free(ids);
  2898. tor_free(msg);
  2899. SMARTLIST_FOREACH(names, char *, cp, tor_free(cp));
  2900. smartlist_free(names);
  2901. }
  2902. if (identities) {
  2903. SMARTLIST_FOREACH(identities, char *, cp, tor_free(cp));
  2904. smartlist_free(identities);
  2905. }
  2906. return 0;
  2907. }
  2908. /** Called whenever an address mapping on <b>from<b> from changes to <b>to</b>.
  2909. * <b>expires</b> values less than 3 are special; see connection_edge.c. */
  2910. int
  2911. control_event_address_mapped(const char *from, const char *to, time_t expires)
  2912. {
  2913. if (!EVENT_IS_INTERESTING1(EVENT_ADDRMAP))
  2914. return 0;
  2915. if (expires < 3)
  2916. send_control1_event(EVENT_ADDRMAP, ALL_NAMES,
  2917. "650 ADDRMAP %s %s NEVER\r\n", from, to);
  2918. else {
  2919. char buf[ISO_TIME_LEN+1];
  2920. format_local_iso_time(buf,expires);
  2921. send_control1_event(EVENT_ADDRMAP, ALL_NAMES,
  2922. "650 ADDRMAP %s %s \"%s\"\r\n",
  2923. from, to, buf);
  2924. }
  2925. return 0;
  2926. }
  2927. /** The authoritative dirserver has received a new descriptor that
  2928. * has passed basic syntax checks and is properly self-signed.
  2929. *
  2930. * Notify any interested party of the new descriptor and what has
  2931. * been done with it, and also optionally give an explanation/reason. */
  2932. int
  2933. control_event_or_authdir_new_descriptor(const char *action,
  2934. const char *descriptor,
  2935. const char *msg)
  2936. {
  2937. char firstline[1024];
  2938. char *buf;
  2939. int totallen;
  2940. char *esc = NULL;
  2941. size_t esclen;
  2942. if (!EVENT_IS_INTERESTING(EVENT_AUTHDIR_NEWDESCS))
  2943. return 0;
  2944. tor_snprintf(firstline, sizeof(firstline),
  2945. "650+AUTHDIR_NEWDESC=\r\n%s\r\n%s\r\n",
  2946. action,
  2947. msg ? msg : "");
  2948. /* Escape the server descriptor properly */
  2949. esclen = write_escaped_data(descriptor, strlen(descriptor), 1, &esc);
  2950. totallen = strlen(firstline) + esclen + 1;
  2951. buf = tor_malloc(totallen);
  2952. strlcpy(buf, firstline, totallen);
  2953. strlcpy(buf+strlen(firstline), esc, totallen);
  2954. send_control1_event_string(EVENT_AUTHDIR_NEWDESCS, ALL_NAMES, buf);
  2955. tor_free(esc);
  2956. tor_free(buf);
  2957. return 0;
  2958. }
  2959. /** Our own router descriptor has changed; tell any controllers that care.
  2960. */
  2961. int
  2962. control_event_my_descriptor_changed(void)
  2963. {
  2964. send_control1_event(EVENT_DESCCHANGED, ALL_NAMES, "650 DESCCHANGED\r\n");
  2965. return 0;
  2966. }
  2967. /** Choose a random authentication cookie and write it to disk.
  2968. * Anybody who can read the cookie from disk will be considered
  2969. * authorized to use the control connection. */
  2970. int
  2971. init_cookie_authentication(int enabled)
  2972. {
  2973. char fname[512];
  2974. if (!enabled) {
  2975. authentication_cookie_is_set = 0;
  2976. return 0;
  2977. }
  2978. tor_snprintf(fname, sizeof(fname), "%s/control_auth_cookie",
  2979. get_options()->DataDirectory);
  2980. crypto_rand(authentication_cookie, AUTHENTICATION_COOKIE_LEN);
  2981. authentication_cookie_is_set = 1;
  2982. if (write_bytes_to_file(fname, authentication_cookie,
  2983. AUTHENTICATION_COOKIE_LEN, 1)) {
  2984. log_warn(LD_FS,"Error writing authentication cookie.");
  2985. return -1;
  2986. }
  2987. return 0;
  2988. }