control.c 86 KB

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