control.c 85 KB

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