control.c 87 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740
  1. /* Copyright 2004-2006 Roger Dingledine, Nick Mathewson. */
  2. /* See LICENSE for licensing information */
  3. /* $Id$ */
  4. const char control_c_id[] =
  5. "$Id$";
  6. /**
  7. * \file control.c
  8. * \brief Implementation for Tor's control-socket interface.
  9. **/
  10. #include "or.h"
  11. #define STATE_IS_OPEN(s) ((s) == CONTROL_CONN_STATE_OPEN_V0 || \
  12. (s) == CONTROL_CONN_STATE_OPEN_V1)
  13. #define STATE_IS_V0(s) ((s) == CONTROL_CONN_STATE_NEEDAUTH_V0 || \
  14. (s) == CONTROL_CONN_STATE_OPEN_V0)
  15. /*
  16. * See control-spec.txt and control-spec-v0.txt for full details on
  17. * protocol(s).
  18. *
  19. */
  20. /* Recognized 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. s);
  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. "desc/all-recent Latest server descriptor for every router\n"
  1171. "entry-guards Which nodes will we use as entry guards?\n"
  1172. "info/names List of GETINFO options, types, and documentation.\n"
  1173. "network-status List of hex IDs, nicknames, server statuses.\n"
  1174. "orconn-status Status of each current OR connection.\n"
  1175. "stream-status Status of each current application stream.\n"
  1176. "version The current version of Tor.\n");
  1177. }
  1178. /** Lookup the 'getinfo' entry <b>question</b>, and return
  1179. * the answer in <b>*answer</b> (or NULL if key not recognized).
  1180. * Return 0 if success, or -1 if internal error. */
  1181. static int
  1182. handle_getinfo_helper(const char *question, char **answer)
  1183. {
  1184. *answer = NULL; /* unrecognized key by default */
  1185. if (!strcmp(question, "version")) {
  1186. *answer = tor_strdup(VERSION);
  1187. } else if (!strcmp(question, "config-file")) {
  1188. *answer = tor_strdup(get_torrc_fname());
  1189. } else if (!strcmpstart(question, "accounting/")) {
  1190. return accounting_getinfo_helper(question, answer);
  1191. } else if (!strcmpstart(question, "helper-nodes")) { /* deprecated */
  1192. return entry_guards_getinfo(question, answer);
  1193. } else if (!strcmpstart(question, "entry-guards")) {
  1194. return entry_guards_getinfo(question, answer);
  1195. } else if (!strcmpstart(question, "config/")) {
  1196. return config_getinfo_helper(question, answer);
  1197. } else if (!strcmp(question, "info/names")) {
  1198. *answer = list_getinfo_options();
  1199. } else if (!strcmpstart(question, "desc/id/")) {
  1200. routerinfo_t *ri = router_get_by_hexdigest(question+strlen("desc/id/"));
  1201. if (ri) {
  1202. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1203. if (body)
  1204. *answer = tor_strdup(body);
  1205. }
  1206. } else if (!strcmpstart(question, "desc/name/")) {
  1207. routerinfo_t *ri = router_get_by_nickname(question+strlen("desc/name/"),1);
  1208. if (ri) {
  1209. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1210. if (body)
  1211. *answer = tor_strdup(body);
  1212. }
  1213. } else if (!strcmp(question, "desc/all-recent")) {
  1214. routerlist_t *routerlist = router_get_routerlist();
  1215. smartlist_t *sl = smartlist_create();
  1216. if (routerlist && routerlist->routers) {
  1217. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
  1218. {
  1219. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1220. if (body)
  1221. smartlist_add(sl, tor_strdup(body));
  1222. });
  1223. }
  1224. *answer = smartlist_join_strings(sl, "", 0, NULL);
  1225. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  1226. smartlist_free(sl);
  1227. } else if (!strcmpstart(question, "unregistered-servers-")) {
  1228. *answer = dirserver_getinfo_unregistered(question +
  1229. strlen("unregistered-servers-"));
  1230. } else if (!strcmp(question, "network-status")) {
  1231. routerlist_t *routerlist = router_get_routerlist();
  1232. if (!routerlist || !routerlist->routers ||
  1233. list_server_status(routerlist->routers, answer) < 0) {
  1234. return -1;
  1235. }
  1236. } else if (!strcmp(question, "circuit-status")) {
  1237. circuit_t *circ;
  1238. smartlist_t *status = smartlist_create();
  1239. for (circ = _circuit_get_global_list(); circ; circ = circ->next) {
  1240. char *s, *path;
  1241. size_t slen;
  1242. const char *state;
  1243. if (! CIRCUIT_IS_ORIGIN(circ) || circ->marked_for_close)
  1244. continue;
  1245. path = circuit_list_path(circ,0);
  1246. if (circ->state == CIRCUIT_STATE_OPEN)
  1247. state = "BUILT";
  1248. else if (strlen(path))
  1249. state = "EXTENDED";
  1250. else
  1251. state = "LAUNCHED";
  1252. slen = strlen(path)+strlen(state)+20;
  1253. s = tor_malloc(slen+1);
  1254. tor_snprintf(s, slen, "%lu %s %s",
  1255. (unsigned long)circ->global_identifier,
  1256. state, path);
  1257. smartlist_add(status, s);
  1258. tor_free(path);
  1259. }
  1260. *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
  1261. SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
  1262. smartlist_free(status);
  1263. } else if (!strcmp(question, "stream-status")) {
  1264. connection_t **conns;
  1265. int n_conns, i;
  1266. char buf[256];
  1267. smartlist_t *status = smartlist_create();
  1268. get_connection_array(&conns, &n_conns);
  1269. for (i=0; i < n_conns; ++i) {
  1270. const char *state;
  1271. char *s;
  1272. size_t slen;
  1273. circuit_t *circ;
  1274. if (conns[i]->type != CONN_TYPE_AP ||
  1275. conns[i]->marked_for_close ||
  1276. conns[i]->state == AP_CONN_STATE_SOCKS_WAIT)
  1277. continue;
  1278. switch (conns[i]->state)
  1279. {
  1280. case AP_CONN_STATE_CONTROLLER_WAIT:
  1281. case AP_CONN_STATE_CIRCUIT_WAIT:
  1282. if (conns[i]->socks_request &&
  1283. conns[i]->socks_request->command == SOCKS_COMMAND_RESOLVE)
  1284. state = "NEWRESOLVE";
  1285. else
  1286. state = "NEW";
  1287. break;
  1288. case AP_CONN_STATE_RENDDESC_WAIT:
  1289. case AP_CONN_STATE_CONNECT_WAIT:
  1290. state = "SENTCONNECT"; break;
  1291. case AP_CONN_STATE_RESOLVE_WAIT:
  1292. state = "SENTRESOLVE"; break;
  1293. case AP_CONN_STATE_OPEN:
  1294. state = "SUCCEEDED"; break;
  1295. default:
  1296. warn(LD_BUG, "Asked for stream in unknown state %d",
  1297. conns[i]->state);
  1298. continue;
  1299. }
  1300. circ = circuit_get_by_edge_conn(conns[i]);
  1301. write_stream_target_to_buf(conns[i], buf, sizeof(buf));
  1302. slen = strlen(buf)+strlen(state)+32;
  1303. s = tor_malloc(slen+1);
  1304. tor_snprintf(s, slen, "%lu %s %lu %s",
  1305. (unsigned long) conns[i]->global_identifier,state,
  1306. circ?(unsigned long)circ->global_identifier : 0ul,
  1307. buf);
  1308. smartlist_add(status, s);
  1309. }
  1310. *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
  1311. SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
  1312. smartlist_free(status);
  1313. } else if (!strcmp(question, "orconn-status")) {
  1314. connection_t **conns;
  1315. int n_conns, i;
  1316. smartlist_t *status = smartlist_create();
  1317. get_connection_array(&conns, &n_conns);
  1318. for (i=0; i < n_conns; ++i) {
  1319. const char *state;
  1320. char *s;
  1321. size_t slen;
  1322. if (conns[i]->type != CONN_TYPE_OR || conns[i]->marked_for_close)
  1323. continue;
  1324. if (conns[i]->state == OR_CONN_STATE_OPEN)
  1325. state = "CONNECTED";
  1326. else
  1327. state = "LAUNCHED";
  1328. slen = strlen(conns[i]->nickname)+strlen(state)+2;
  1329. s = tor_malloc(slen+1);
  1330. tor_snprintf(s, slen, "%s %s",conns[i]->nickname,state);
  1331. smartlist_add(status, s);
  1332. }
  1333. *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
  1334. SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
  1335. smartlist_free(status);
  1336. } else if (!strcmpstart(question, "addr-mappings/")) {
  1337. time_t min_e, max_e;
  1338. smartlist_t *mappings;
  1339. if (!strcmp(question, "addr-mappings/all")) {
  1340. min_e = 0; max_e = TIME_MAX;
  1341. } else if (!strcmp(question, "addr-mappings/cache")) {
  1342. min_e = 2; max_e = TIME_MAX;
  1343. } else if (!strcmp(question, "addr-mappings/config")) {
  1344. min_e = 0; max_e = 0;
  1345. } else if (!strcmp(question, "addr-mappings/control")) {
  1346. min_e = 1; max_e = 1;
  1347. } else {
  1348. return 0;
  1349. }
  1350. mappings = smartlist_create();
  1351. addressmap_get_mappings(mappings, min_e, max_e);
  1352. *answer = smartlist_join_strings(mappings, "\n", 0, NULL);
  1353. SMARTLIST_FOREACH(mappings, char *, cp, tor_free(cp));
  1354. smartlist_free(mappings);
  1355. } else if (!strcmp(question, "dir-usage")) {
  1356. *answer = directory_dump_request_log();
  1357. }
  1358. return 0;
  1359. }
  1360. /** Called when we receive a GETINFO command. Try to fetch all requested
  1361. * information, and reply with information or error message. */
  1362. static int
  1363. handle_control_getinfo(connection_t *conn, uint32_t len, const char *body)
  1364. {
  1365. smartlist_t *questions = NULL;
  1366. smartlist_t *answers = NULL;
  1367. smartlist_t *unrecognized = NULL;
  1368. char *msg = NULL, *ans = NULL;
  1369. size_t msg_len;
  1370. int v0 = STATE_IS_V0(conn->state);
  1371. questions = smartlist_create();
  1372. if (v0)
  1373. smartlist_split_string(questions, body, "\n",
  1374. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1375. else
  1376. smartlist_split_string(questions, body, " ",
  1377. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1378. answers = smartlist_create();
  1379. unrecognized = smartlist_create();
  1380. SMARTLIST_FOREACH(questions, const char *, q,
  1381. {
  1382. if (handle_getinfo_helper(q, &ans) < 0) {
  1383. if (v0)
  1384. send_control0_error(conn, ERR_INTERNAL, body);
  1385. else
  1386. connection_write_str_to_buf("551 Internal error\r\n", conn);
  1387. goto done;
  1388. }
  1389. if (!ans) {
  1390. if (v0) {
  1391. send_control0_error(conn, ERR_UNRECOGNIZED_CONFIG_KEY, body);
  1392. goto done;
  1393. } else
  1394. smartlist_add(unrecognized, (char*)q);
  1395. } else {
  1396. smartlist_add(answers, tor_strdup(q));
  1397. smartlist_add(answers, ans);
  1398. }
  1399. });
  1400. if (smartlist_len(unrecognized)) {
  1401. int i;
  1402. tor_assert(!v0);
  1403. for (i=0; i < smartlist_len(unrecognized)-1; ++i)
  1404. connection_printf_to_buf(conn,
  1405. "552-Unrecognized key \"%s\"\r\n",
  1406. (char*)smartlist_get(unrecognized, i));
  1407. connection_printf_to_buf(conn,
  1408. "552 Unrecognized key \"%s\"\r\n",
  1409. (char*)smartlist_get(unrecognized, i));
  1410. goto done;
  1411. }
  1412. if (v0) {
  1413. msg = smartlist_join_strings2(answers, "\0", 1, 1, &msg_len);
  1414. tor_assert(msg_len > 0); /* it will at least be terminated */
  1415. send_control0_message(conn, CONTROL0_CMD_INFOVALUE,
  1416. msg_len, msg);
  1417. } else {
  1418. int i;
  1419. for (i = 0; i < smartlist_len(answers); i += 2) {
  1420. char *k = smartlist_get(answers, i);
  1421. char *v = smartlist_get(answers, i+1);
  1422. /*XXXX Not an adequate test! XXXX011 */
  1423. if (!strchr(v, '\n') && !strchr(v, '\r')) {
  1424. connection_printf_to_buf(conn, "250-%s=", k);
  1425. connection_write_str_to_buf(v, conn);
  1426. connection_write_str_to_buf("\r\n", conn);
  1427. } else {
  1428. char *esc = NULL;
  1429. size_t len;
  1430. len = write_escaped_data(v, strlen(v), 1, &esc);
  1431. connection_printf_to_buf(conn, "250+%s=\r\n", k);
  1432. connection_write_to_buf(esc, len, conn);
  1433. tor_free(esc);
  1434. }
  1435. }
  1436. connection_write_str_to_buf("250 OK\r\n", conn);
  1437. }
  1438. done:
  1439. if (answers) {
  1440. SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
  1441. smartlist_free(answers);
  1442. }
  1443. if (questions) {
  1444. SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
  1445. smartlist_free(questions);
  1446. }
  1447. smartlist_free(unrecognized);
  1448. tor_free(msg);
  1449. return 0;
  1450. }
  1451. /** Called when we get an EXTENDCIRCUIT message. Try to extend the listed
  1452. * circuit, and report success or failure. */
  1453. static int
  1454. handle_control_extendcircuit(connection_t *conn, uint32_t len,
  1455. const char *body)
  1456. {
  1457. smartlist_t *router_nicknames=NULL, *routers=NULL;
  1458. uint32_t circ_id;
  1459. circuit_t *circ = NULL;
  1460. int zero_circ, v0;
  1461. char reply[4];
  1462. v0 = STATE_IS_V0(conn->state);
  1463. router_nicknames = smartlist_create();
  1464. if (v0) {
  1465. if (len<5) {
  1466. send_control0_error(conn, ERR_SYNTAX, "extendcircuit message too short");
  1467. goto done;
  1468. }
  1469. smartlist_split_string(router_nicknames, body+4, ",", 0, 0);
  1470. circ_id = ntohl(get_uint32(body));
  1471. if (!circ_id) {
  1472. /* start a new circuit */
  1473. zero_circ = 1;
  1474. } else {
  1475. circ = circuit_get_by_global_id(circ_id);
  1476. zero_circ = 0;
  1477. if (!circ) {
  1478. send_control0_error(conn, ERR_NO_CIRC,
  1479. "No circuit found with given ID");
  1480. goto done;
  1481. }
  1482. }
  1483. } else { /* v1 */
  1484. smartlist_t *args;
  1485. args = smartlist_create();
  1486. smartlist_split_string(args, body, " ",
  1487. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1488. if (smartlist_len(args)<2) {
  1489. connection_printf_to_buf(conn,
  1490. "512 Missing argument to EXTENDCIRCUIT\r\n");
  1491. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1492. smartlist_free(args);
  1493. goto done;
  1494. }
  1495. zero_circ = !strcmp("0", (char*)smartlist_get(args,0));
  1496. if (!zero_circ && !(circ = get_circ(smartlist_get(args,0)))) {
  1497. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  1498. (char*)smartlist_get(args, 0));
  1499. }
  1500. smartlist_split_string(router_nicknames, smartlist_get(args,1), ",", 0, 0);
  1501. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1502. smartlist_free(args);
  1503. if (!zero_circ && !circ) {
  1504. goto done;
  1505. }
  1506. }
  1507. routers = smartlist_create();
  1508. SMARTLIST_FOREACH(router_nicknames, const char *, n,
  1509. {
  1510. routerinfo_t *r = router_get_by_nickname(n, 1);
  1511. if (!r) {
  1512. if (v0)
  1513. send_control0_error(conn, ERR_NO_ROUTER, n);
  1514. else
  1515. connection_printf_to_buf(conn, "552 No such router \"%s\"\r\n", n);
  1516. goto done;
  1517. }
  1518. smartlist_add(routers, r);
  1519. });
  1520. if (!smartlist_len(routers)) {
  1521. if (v0)
  1522. send_control0_error(conn, ERR_SYNTAX, "No router names provided");
  1523. else
  1524. connection_write_str_to_buf("512 No router names provided\r\n", conn);
  1525. goto done;
  1526. }
  1527. if (zero_circ) {
  1528. /* start a new circuit */
  1529. circ = circuit_init(CIRCUIT_PURPOSE_C_GENERAL, 0, 0, 0);
  1530. }
  1531. /* now circ refers to something that is ready to be extended */
  1532. SMARTLIST_FOREACH(routers, routerinfo_t *, r,
  1533. {
  1534. extend_info_t *info = extend_info_from_router(r);
  1535. circuit_append_new_exit(circ, info);
  1536. extend_info_free(info);
  1537. });
  1538. /* now that we've populated the cpath, start extending */
  1539. if (zero_circ) {
  1540. if (circuit_handle_first_hop(circ) < 0) {
  1541. circuit_mark_for_close(circ, END_CIRC_AT_ORIGIN);
  1542. if (v0)
  1543. send_control0_error(conn, ERR_INTERNAL, "couldn't start circuit");
  1544. else
  1545. connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
  1546. goto done;
  1547. }
  1548. } else {
  1549. if (circ->state == CIRCUIT_STATE_OPEN) {
  1550. circuit_set_state(circ, CIRCUIT_STATE_BUILDING);
  1551. if (circuit_send_next_onion_skin(circ) < 0) {
  1552. info(LD_CONTROL,
  1553. "send_next_onion_skin failed; circuit marked for closing.");
  1554. circuit_mark_for_close(circ, END_CIRC_AT_ORIGIN);
  1555. if (v0)
  1556. send_control0_error(conn, ERR_INTERNAL, "couldn't send onion skin");
  1557. else
  1558. connection_write_str_to_buf("551 Couldn't send onion skinr\n", conn);
  1559. goto done;
  1560. }
  1561. }
  1562. }
  1563. if (v0) {
  1564. set_uint32(reply, htonl(circ->global_identifier));
  1565. send_control_done2(conn, reply, sizeof(reply));
  1566. } else {
  1567. connection_printf_to_buf(conn, "250 EXTENDED %lu\r\n",
  1568. (unsigned long)circ->global_identifier);
  1569. }
  1570. done:
  1571. SMARTLIST_FOREACH(router_nicknames, char *, n, tor_free(n));
  1572. smartlist_free(router_nicknames);
  1573. if (routers)
  1574. smartlist_free(routers);
  1575. return 0;
  1576. }
  1577. /** Called when we get an ATTACHSTREAM message. Try to attach the requested
  1578. * stream, and report success or failure. */
  1579. static int
  1580. handle_control_attachstream(connection_t *conn, uint32_t len,
  1581. const char *body)
  1582. {
  1583. connection_t *ap_conn = NULL;
  1584. circuit_t *circ = NULL;
  1585. int zero_circ;
  1586. if (STATE_IS_V0(conn->state)) {
  1587. uint32_t conn_id;
  1588. uint32_t circ_id;
  1589. if (len < 8) {
  1590. send_control0_error(conn, ERR_SYNTAX, "attachstream message too short");
  1591. return 0;
  1592. }
  1593. conn_id = ntohl(get_uint32(body));
  1594. circ_id = ntohl(get_uint32(body+4));
  1595. zero_circ = circ_id == 0;
  1596. if (!(ap_conn = connection_get_by_global_id(conn_id))) {
  1597. send_control0_error(conn, ERR_NO_STREAM,
  1598. "No connection found with given ID");
  1599. return 0;
  1600. }
  1601. if (circ_id && !(circ = circuit_get_by_global_id(circ_id))) {
  1602. send_control0_error(conn, ERR_NO_CIRC, "No circuit found with given ID");
  1603. return 0;
  1604. }
  1605. } else {
  1606. smartlist_t *args;
  1607. args = smartlist_create();
  1608. smartlist_split_string(args, body, " ",
  1609. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1610. if (smartlist_len(args)<2) {
  1611. connection_printf_to_buf(conn,
  1612. "512 Missing argument to ATTACHSTREAM\r\n");
  1613. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1614. smartlist_free(args);
  1615. return 0;
  1616. }
  1617. zero_circ = !strcmp("0", (char*)smartlist_get(args,1));
  1618. if (!(ap_conn = get_stream(smartlist_get(args, 0)))) {
  1619. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  1620. (char*)smartlist_get(args, 0));
  1621. } else if (!zero_circ && !(circ = get_circ(smartlist_get(args, 1)))) {
  1622. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  1623. (char*)smartlist_get(args, 1));
  1624. }
  1625. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1626. smartlist_free(args);
  1627. if (!ap_conn || (!zero_circ && !circ))
  1628. return 0;
  1629. }
  1630. if (ap_conn->state != AP_CONN_STATE_CONTROLLER_WAIT) {
  1631. if (STATE_IS_V0(conn->state)) {
  1632. send_control0_error(conn, ERR_NO_STREAM,
  1633. "Connection is not managed by controller.");
  1634. } else {
  1635. connection_write_str_to_buf(
  1636. "555 Connection is not managed by controller.\r\n",
  1637. conn);
  1638. }
  1639. return 0;
  1640. }
  1641. if (zero_circ) {
  1642. connection_ap_handshake_rewrite_and_attach(ap_conn);
  1643. send_control_done(conn);
  1644. return 0;
  1645. }
  1646. if (circ->state != CIRCUIT_STATE_OPEN) {
  1647. if (STATE_IS_V0(conn->state))
  1648. send_control0_error(conn, ERR_INTERNAL,
  1649. "Refuse to attach stream to non-open circ.");
  1650. else
  1651. connection_write_str_to_buf(
  1652. "551 Can't attach stream to non-open circuit\r\n",
  1653. conn);
  1654. return 0;
  1655. }
  1656. if (connection_ap_handshake_attach_chosen_circuit(ap_conn, circ) != 1) {
  1657. if (STATE_IS_V0(conn->state))
  1658. send_control0_error(conn, ERR_INTERNAL, "Unable to attach stream.");
  1659. else
  1660. connection_write_str_to_buf("551 Unable to attach stream\r\n", conn);
  1661. return 0;
  1662. }
  1663. send_control_done(conn);
  1664. return 0;
  1665. }
  1666. /** Called when we get a POSTDESCRIPTOR message. Try to learn the provided
  1667. * descriptor, and report success or failure. */
  1668. static int
  1669. handle_control_postdescriptor(connection_t *conn, uint32_t len,
  1670. const char *body)
  1671. {
  1672. char *desc;
  1673. int v0 = STATE_IS_V0(conn->state);
  1674. const char *msg=NULL;
  1675. if (v0)
  1676. desc = (char*)body;
  1677. else {
  1678. const char *cp = memchr(body, '\n', len);
  1679. tor_assert(cp);
  1680. read_escaped_data(cp, len-(cp-body), 1, &desc);
  1681. }
  1682. switch (router_load_single_router(desc, &msg)) {
  1683. case -1:
  1684. if (!msg) msg = "Could not parse descriptor";
  1685. if (v0)
  1686. send_control0_error(conn,ERR_SYNTAX,msg);
  1687. else
  1688. connection_printf_to_buf(conn, "554 %s\r\n", msg);
  1689. break;
  1690. case 0:
  1691. if (!msg) msg = "Descriptor not added";
  1692. if (v0)
  1693. send_control_done2(conn,msg,0);
  1694. else
  1695. connection_printf_to_buf(conn, "251 %s\r\n",msg);
  1696. break;
  1697. case 1:
  1698. send_control_done(conn);
  1699. break;
  1700. }
  1701. if (!v0)
  1702. tor_free(desc);
  1703. return 0;
  1704. }
  1705. /** Called when we receive a REDIRECTSTERAM command. Try to change the target
  1706. * address of the named AP stream, and report success or failure. */
  1707. static int
  1708. handle_control_redirectstream(connection_t *conn, uint32_t len,
  1709. const char *body)
  1710. {
  1711. connection_t *ap_conn = NULL;
  1712. uint32_t conn_id;
  1713. char *new_addr = NULL;
  1714. uint16_t new_port = 0;
  1715. if (STATE_IS_V0(conn->state)) {
  1716. if (len < 6) {
  1717. send_control0_error(conn, ERR_SYNTAX,
  1718. "redirectstream message too short");
  1719. return 0;
  1720. }
  1721. conn_id = ntohl(get_uint32(body));
  1722. if (!(ap_conn = connection_get_by_global_id(conn_id))
  1723. || ap_conn->state != CONN_TYPE_AP
  1724. || !ap_conn->socks_request) {
  1725. send_control0_error(conn, ERR_NO_STREAM,
  1726. "No AP connection found with given ID");
  1727. return 0;
  1728. }
  1729. new_addr = tor_strdup(body+4);
  1730. } else {
  1731. smartlist_t *args;
  1732. args = smartlist_create();
  1733. smartlist_split_string(args, body, " ",
  1734. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1735. if (smartlist_len(args) < 2)
  1736. connection_printf_to_buf(conn,
  1737. "512 Missing argument to REDIRECTSTREAM\r\n");
  1738. else if (!(ap_conn = get_stream(smartlist_get(args, 0)))
  1739. || !ap_conn->socks_request) {
  1740. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  1741. (char*)smartlist_get(args, 0));
  1742. } else {
  1743. int ok;
  1744. if (smartlist_len(args) > 2) { /* they included a port too */
  1745. new_port = (uint16_t) tor_parse_ulong(smartlist_get(args, 2),
  1746. 10, 1, 65535, &ok, NULL);
  1747. }
  1748. if (!ok) {
  1749. connection_printf_to_buf(conn, "512 Cannot parse port \"%s\"\r\n",
  1750. (char*)smartlist_get(args, 2));
  1751. } else {
  1752. new_addr = tor_strdup(smartlist_get(args, 1));
  1753. }
  1754. }
  1755. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1756. smartlist_free(args);
  1757. if (!new_addr)
  1758. return 0;
  1759. }
  1760. strlcpy(ap_conn->socks_request->address, new_addr,
  1761. sizeof(ap_conn->socks_request->address));
  1762. if (new_port)
  1763. ap_conn->socks_request->port = new_port;
  1764. tor_free(new_addr);
  1765. send_control_done(conn);
  1766. return 0;
  1767. }
  1768. /** Called when we get a CLOSESTREAM command; try to close the named stream
  1769. * and report success or failure. */
  1770. static int
  1771. handle_control_closestream(connection_t *conn, uint32_t len,
  1772. const char *body)
  1773. {
  1774. connection_t *ap_conn=NULL;
  1775. uint8_t reason=0;
  1776. if (STATE_IS_V0(conn->state)) {
  1777. uint32_t conn_id;
  1778. if (len < 6) {
  1779. send_control0_error(conn, ERR_SYNTAX, "closestream message too short");
  1780. return 0;
  1781. }
  1782. conn_id = ntohl(get_uint32(body));
  1783. reason = *(uint8_t*)(body+4);
  1784. if (!(ap_conn = connection_get_by_global_id(conn_id))
  1785. || ap_conn->state != CONN_TYPE_AP
  1786. || !ap_conn->socks_request) {
  1787. send_control0_error(conn, ERR_NO_STREAM,
  1788. "No AP connection found with given ID");
  1789. return 0;
  1790. }
  1791. } else {
  1792. smartlist_t *args;
  1793. int ok;
  1794. args = smartlist_create();
  1795. smartlist_split_string(args, body, " ",
  1796. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1797. if (smartlist_len(args)<2)
  1798. connection_printf_to_buf(conn,
  1799. "512 Missing argument to CLOSESTREAM\r\n");
  1800. else if (!(ap_conn = get_stream(smartlist_get(args, 0))))
  1801. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  1802. (char*)smartlist_get(args, 0));
  1803. else {
  1804. reason = (uint8_t) tor_parse_ulong(smartlist_get(args,1), 10, 0, 255,
  1805. &ok, NULL);
  1806. if (!ok) {
  1807. connection_printf_to_buf(conn, "552 Unrecognized reason \"%s\"\r\n",
  1808. (char*)smartlist_get(args, 1));
  1809. ap_conn = NULL;
  1810. }
  1811. }
  1812. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1813. smartlist_free(args);
  1814. if (!ap_conn)
  1815. return 0;
  1816. }
  1817. connection_mark_unattached_ap(ap_conn, reason);
  1818. send_control_done(conn);
  1819. return 0;
  1820. }
  1821. /** Called when we get a CLOSECIRCUIT command; try to close the named circuit
  1822. * and report success or failure. */
  1823. static int
  1824. handle_control_closecircuit(connection_t *conn, uint32_t len,
  1825. const char *body)
  1826. {
  1827. circuit_t *circ = NULL;
  1828. int safe = 0;
  1829. if (STATE_IS_V0(conn->state)) {
  1830. uint32_t circ_id;
  1831. if (len < 5) {
  1832. send_control0_error(conn, ERR_SYNTAX, "closecircuit message too short");
  1833. return 0;
  1834. }
  1835. circ_id = ntohl(get_uint32(body));
  1836. safe = (*(uint8_t*)(body+4)) & 1;
  1837. if (!(circ = circuit_get_by_global_id(circ_id))) {
  1838. send_control0_error(conn, ERR_NO_CIRC,
  1839. "No circuit found with given ID");
  1840. return 0;
  1841. }
  1842. } else {
  1843. smartlist_t *args;
  1844. args = smartlist_create();
  1845. smartlist_split_string(args, body, " ",
  1846. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1847. if (smartlist_len(args)<1)
  1848. connection_printf_to_buf(conn,
  1849. "512 Missing argument to CLOSECIRCUIT\r\n");
  1850. else if (!(circ=get_circ(smartlist_get(args, 0))))
  1851. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  1852. (char*)smartlist_get(args, 0));
  1853. else {
  1854. int i;
  1855. for (i=1; i < smartlist_len(args); ++i) {
  1856. if (!strcasecmp(smartlist_get(args, i), "IfUnused"))
  1857. safe = 1;
  1858. else
  1859. info(LD_CONTROL, "Skipping unknown option %s",
  1860. (char*)smartlist_get(args,i));
  1861. }
  1862. }
  1863. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1864. smartlist_free(args);
  1865. if (!circ)
  1866. return 0;
  1867. }
  1868. if (!safe || !circ->p_streams) {
  1869. circuit_mark_for_close(circ, END_CIRC_REASON_NONE);
  1870. }
  1871. send_control_done(conn);
  1872. return 0;
  1873. }
  1874. /** Called when we get a v0 FRAGMENTHEADER or FRAGMENT command; try to append
  1875. * the data to conn->incoming_cmd, setting conn->incoming_(type|len|cur_len)
  1876. * as appropriate. If the command is malformed, drop it and all pending
  1877. * fragments and report failure.
  1878. */
  1879. static int
  1880. handle_control_fragments(connection_t *conn, uint16_t command_type,
  1881. uint32_t body_len, char *body)
  1882. {
  1883. if (command_type == CONTROL0_CMD_FRAGMENTHEADER) {
  1884. if (conn->incoming_cmd) {
  1885. warn(LD_CONTROL, "Dropping incomplete fragmented command");
  1886. tor_free(conn->incoming_cmd);
  1887. }
  1888. if (body_len < 6) {
  1889. send_control0_error(conn, ERR_SYNTAX, "FRAGMENTHEADER too short.");
  1890. return 0;
  1891. }
  1892. conn->incoming_cmd_type = ntohs(get_uint16(body));
  1893. conn->incoming_cmd_len = ntohl(get_uint32(body+2));
  1894. conn->incoming_cmd_cur_len = 0;
  1895. conn->incoming_cmd = tor_malloc(conn->incoming_cmd_len);
  1896. body += 6;
  1897. body_len -= 6;
  1898. } else if (command_type == CONTROL0_CMD_FRAGMENT) {
  1899. if (!conn->incoming_cmd) {
  1900. send_control0_error(conn, ERR_SYNTAX, "Out-of-place FRAGMENT");
  1901. return 0;
  1902. }
  1903. } else {
  1904. tor_assert(0);
  1905. }
  1906. if (conn->incoming_cmd_cur_len + body_len > conn->incoming_cmd_len) {
  1907. tor_free(conn->incoming_cmd);
  1908. send_control0_error(conn, ERR_SYNTAX,
  1909. "Fragmented data exceeds declared length");
  1910. return 0;
  1911. }
  1912. memcpy(conn->incoming_cmd + conn->incoming_cmd_cur_len,
  1913. body, body_len);
  1914. conn->incoming_cmd_cur_len += body_len;
  1915. return 0;
  1916. }
  1917. /** Called when <b>conn</b> has no more bytes left on its outbuf. */
  1918. int
  1919. connection_control_finished_flushing(connection_t *conn)
  1920. {
  1921. tor_assert(conn);
  1922. tor_assert(conn->type == CONN_TYPE_CONTROL);
  1923. connection_stop_writing(conn);
  1924. return 0;
  1925. }
  1926. /** Called when <b>conn</b> has gotten its socket closed. */
  1927. int
  1928. connection_control_reached_eof(connection_t *conn)
  1929. {
  1930. tor_assert(conn);
  1931. tor_assert(conn->type == CONN_TYPE_CONTROL);
  1932. info(LD_CONTROL,"Control connection reached EOF. Closing.");
  1933. connection_mark_for_close(conn);
  1934. return 0;
  1935. }
  1936. /** Called when data has arrived on a v1 control connection: Try to fetch
  1937. * commands from conn->inbuf, and execute them.
  1938. */
  1939. static int
  1940. connection_control_process_inbuf_v1(connection_t *conn)
  1941. {
  1942. size_t data_len;
  1943. int cmd_len;
  1944. char *args;
  1945. tor_assert(conn);
  1946. tor_assert(conn->type == CONN_TYPE_CONTROL);
  1947. tor_assert(conn->state == CONTROL_CONN_STATE_OPEN_V1 ||
  1948. conn->state == CONTROL_CONN_STATE_NEEDAUTH_V1);
  1949. if (!conn->incoming_cmd) {
  1950. conn->incoming_cmd = tor_malloc(1024);
  1951. conn->incoming_cmd_len = 1024;
  1952. conn->incoming_cmd_cur_len = 0;
  1953. }
  1954. again:
  1955. while (1) {
  1956. size_t last_idx;
  1957. int r;
  1958. /* First, fetch a line. */
  1959. do {
  1960. data_len = conn->incoming_cmd_len - conn->incoming_cmd_cur_len;
  1961. r = fetch_from_buf_line(conn->inbuf,
  1962. conn->incoming_cmd+conn->incoming_cmd_cur_len,
  1963. &data_len);
  1964. if (r == 0)
  1965. /* Line not all here yet. Wait. */
  1966. return 0;
  1967. else if (r == -1) {
  1968. while (conn->incoming_cmd_len < data_len+conn->incoming_cmd_cur_len)
  1969. conn->incoming_cmd_len *= 2;
  1970. conn->incoming_cmd = tor_realloc(conn->incoming_cmd,
  1971. conn->incoming_cmd_len);
  1972. }
  1973. } while (r != 1);
  1974. tor_assert(data_len);
  1975. last_idx = conn->incoming_cmd_cur_len;
  1976. conn->incoming_cmd_cur_len += data_len;
  1977. /* We have appended a line to incoming_cmd. Is the command done? */
  1978. if (last_idx == 0 && *conn->incoming_cmd != '+')
  1979. /* One line command, didn't start with '+'. */
  1980. break;
  1981. if (last_idx+3 == conn->incoming_cmd_cur_len &&
  1982. !memcmp(conn->incoming_cmd + last_idx, ".\r\n", 3)) {
  1983. /* Just appended ".\r\n"; we're done. Remove it. */
  1984. conn->incoming_cmd_cur_len -= 3;
  1985. break;
  1986. }
  1987. /* Otherwise, read another line. */
  1988. }
  1989. data_len = conn->incoming_cmd_cur_len;
  1990. /* Okay, we now have a command sitting on conn->incoming_cmd. See if we
  1991. * recognize it.
  1992. */
  1993. cmd_len = 0;
  1994. while ((size_t)cmd_len < data_len
  1995. && !TOR_ISSPACE(conn->incoming_cmd[cmd_len]))
  1996. ++cmd_len;
  1997. data_len -= cmd_len;
  1998. conn->incoming_cmd[cmd_len]='\0';
  1999. args = conn->incoming_cmd+cmd_len+1;
  2000. while (*args == ' ' || *args == '\t') {
  2001. ++args;
  2002. --data_len;
  2003. }
  2004. if (!strcasecmp(conn->incoming_cmd, "QUIT")) {
  2005. connection_write_str_to_buf("250 closing connection\r\n", conn);
  2006. connection_mark_for_close(conn);
  2007. return 0;
  2008. }
  2009. if (conn->state == CONTROL_CONN_STATE_NEEDAUTH_V1 &&
  2010. strcasecmp(conn->incoming_cmd, "AUTHENTICATE")) {
  2011. connection_write_str_to_buf("514 Authentication required.\r\n", conn);
  2012. conn->incoming_cmd_cur_len = 0;
  2013. goto again;
  2014. }
  2015. if (!strcasecmp(conn->incoming_cmd, "SETCONF")) {
  2016. if (handle_control_setconf(conn, data_len, args))
  2017. return -1;
  2018. } else if (!strcasecmp(conn->incoming_cmd, "RESETCONF")) {
  2019. if (handle_control_resetconf(conn, data_len, args))
  2020. return -1;
  2021. } else if (!strcasecmp(conn->incoming_cmd, "GETCONF")) {
  2022. if (handle_control_getconf(conn, data_len, args))
  2023. return -1;
  2024. } else if (!strcasecmp(conn->incoming_cmd, "SETEVENTS")) {
  2025. if (handle_control_setevents(conn, data_len, args))
  2026. return -1;
  2027. } else if (!strcasecmp(conn->incoming_cmd, "AUTHENTICATE")) {
  2028. if (handle_control_authenticate(conn, data_len, args))
  2029. return -1;
  2030. } else if (!strcasecmp(conn->incoming_cmd, "SAVECONF")) {
  2031. if (handle_control_saveconf(conn, data_len, args))
  2032. return -1;
  2033. } else if (!strcasecmp(conn->incoming_cmd, "SIGNAL")) {
  2034. if (handle_control_signal(conn, data_len, args))
  2035. return -1;
  2036. } else if (!strcasecmp(conn->incoming_cmd, "MAPADDRESS")) {
  2037. if (handle_control_mapaddress(conn, data_len, args))
  2038. return -1;
  2039. } else if (!strcasecmp(conn->incoming_cmd, "GETINFO")) {
  2040. if (handle_control_getinfo(conn, data_len, args))
  2041. return -1;
  2042. } else if (!strcasecmp(conn->incoming_cmd, "EXTENDCIRCUIT")) {
  2043. if (handle_control_extendcircuit(conn, data_len, args))
  2044. return -1;
  2045. } else if (!strcasecmp(conn->incoming_cmd, "ATTACHSTREAM")) {
  2046. if (handle_control_attachstream(conn, data_len, args))
  2047. return -1;
  2048. } else if (!strcasecmp(conn->incoming_cmd, "+POSTDESCRIPTOR")) {
  2049. if (handle_control_postdescriptor(conn, data_len, args))
  2050. return -1;
  2051. } else if (!strcasecmp(conn->incoming_cmd, "REDIRECTSTREAM")) {
  2052. if (handle_control_redirectstream(conn, data_len, args))
  2053. return -1;
  2054. } else if (!strcasecmp(conn->incoming_cmd, "CLOSESTREAM")) {
  2055. if (handle_control_closestream(conn, data_len, args))
  2056. return -1;
  2057. } else if (!strcasecmp(conn->incoming_cmd, "CLOSECIRCUIT")) {
  2058. if (handle_control_closecircuit(conn, data_len, args))
  2059. return -1;
  2060. } else {
  2061. connection_printf_to_buf(conn, "510 Unrecognized command \"%s\"\r\n",
  2062. conn->incoming_cmd);
  2063. }
  2064. conn->incoming_cmd_cur_len = 0;
  2065. goto again;
  2066. }
  2067. /** Called when data has arrived on a v0 control connection: Try to fetch
  2068. * commands from conn->inbuf, and execute them.
  2069. */
  2070. static int
  2071. connection_control_process_inbuf_v0(connection_t *conn)
  2072. {
  2073. uint32_t body_len;
  2074. uint16_t command_type;
  2075. char *body=NULL;
  2076. again:
  2077. /* Try to suck a control message from the buffer. */
  2078. switch (fetch_from_buf_control0(conn->inbuf, &body_len, &command_type, &body,
  2079. conn->state == CONTROL_CONN_STATE_NEEDAUTH_V0))
  2080. {
  2081. case -2:
  2082. tor_free(body);
  2083. info(LD_CONTROL, "Detected v1 control protocol on connection (fd %d)",
  2084. conn->s);
  2085. conn->state = CONTROL_CONN_STATE_NEEDAUTH_V1;
  2086. return connection_control_process_inbuf_v1(conn);
  2087. case -1:
  2088. tor_free(body);
  2089. warn(LD_CONTROL, "Error in control command. Failing.");
  2090. return -1;
  2091. case 0:
  2092. /* Control command not all here yet. Wait. */
  2093. return 0;
  2094. case 1:
  2095. /* We got a command. Process it. */
  2096. break;
  2097. default:
  2098. tor_assert(0);
  2099. }
  2100. /* We got a command. If we need authentication, only authentication
  2101. * commands will be considered. */
  2102. if (conn->state == CONTROL_CONN_STATE_NEEDAUTH_V0 &&
  2103. command_type != CONTROL0_CMD_AUTHENTICATE) {
  2104. info(LD_CONTROL, "Rejecting '%s' command; authentication needed.",
  2105. control_cmd_to_string(command_type));
  2106. send_control0_error(conn, ERR_UNAUTHORIZED, "Authentication required");
  2107. tor_free(body);
  2108. goto again;
  2109. }
  2110. if (command_type == CONTROL0_CMD_FRAGMENTHEADER ||
  2111. command_type == CONTROL0_CMD_FRAGMENT) {
  2112. if (handle_control_fragments(conn, command_type, body_len, body))
  2113. return -1;
  2114. tor_free(body);
  2115. if (conn->incoming_cmd_cur_len != conn->incoming_cmd_len)
  2116. goto again;
  2117. command_type = conn->incoming_cmd_type;
  2118. body_len = conn->incoming_cmd_len;
  2119. body = conn->incoming_cmd;
  2120. conn->incoming_cmd = NULL;
  2121. } else if (conn->incoming_cmd) {
  2122. warn(LD_CONTROL, "Dropping incomplete fragmented command");
  2123. tor_free(conn->incoming_cmd);
  2124. }
  2125. /* Okay, we're willing to process the command. */
  2126. switch (command_type)
  2127. {
  2128. case CONTROL0_CMD_SETCONF:
  2129. if (handle_control_setconf(conn, body_len, body))
  2130. return -1;
  2131. break;
  2132. case CONTROL0_CMD_GETCONF:
  2133. if (handle_control_getconf(conn, body_len, body))
  2134. return -1;
  2135. break;
  2136. case CONTROL0_CMD_SETEVENTS:
  2137. if (handle_control_setevents(conn, body_len, body))
  2138. return -1;
  2139. break;
  2140. case CONTROL0_CMD_AUTHENTICATE:
  2141. if (handle_control_authenticate(conn, body_len, body))
  2142. return -1;
  2143. break;
  2144. case CONTROL0_CMD_SAVECONF:
  2145. if (handle_control_saveconf(conn, body_len, body))
  2146. return -1;
  2147. break;
  2148. case CONTROL0_CMD_SIGNAL:
  2149. if (handle_control_signal(conn, body_len, body))
  2150. return -1;
  2151. break;
  2152. case CONTROL0_CMD_MAPADDRESS:
  2153. if (handle_control_mapaddress(conn, body_len, body))
  2154. return -1;
  2155. break;
  2156. case CONTROL0_CMD_GETINFO:
  2157. if (handle_control_getinfo(conn, body_len, body))
  2158. return -1;
  2159. break;
  2160. case CONTROL0_CMD_EXTENDCIRCUIT:
  2161. if (handle_control_extendcircuit(conn, body_len, body))
  2162. return -1;
  2163. break;
  2164. case CONTROL0_CMD_ATTACHSTREAM:
  2165. if (handle_control_attachstream(conn, body_len, body))
  2166. return -1;
  2167. break;
  2168. case CONTROL0_CMD_POSTDESCRIPTOR:
  2169. if (handle_control_postdescriptor(conn, body_len, body))
  2170. return -1;
  2171. break;
  2172. case CONTROL0_CMD_REDIRECTSTREAM:
  2173. if (handle_control_redirectstream(conn, body_len, body))
  2174. return -1;
  2175. break;
  2176. case CONTROL0_CMD_CLOSESTREAM:
  2177. if (handle_control_closestream(conn, body_len, body))
  2178. return -1;
  2179. break;
  2180. case CONTROL0_CMD_CLOSECIRCUIT:
  2181. if (handle_control_closecircuit(conn, body_len, body))
  2182. return -1;
  2183. break;
  2184. case CONTROL0_CMD_ERROR:
  2185. case CONTROL0_CMD_DONE:
  2186. case CONTROL0_CMD_CONFVALUE:
  2187. case CONTROL0_CMD_EVENT:
  2188. case CONTROL0_CMD_INFOVALUE:
  2189. warn(LD_CONTROL, "Received client-only '%s' command; ignoring.",
  2190. control_cmd_to_string(command_type));
  2191. send_control0_error(conn, ERR_UNRECOGNIZED_TYPE,
  2192. "Command type only valid from server to tor client");
  2193. break;
  2194. case CONTROL0_CMD_FRAGMENTHEADER:
  2195. case CONTROL0_CMD_FRAGMENT:
  2196. warn(LD_CONTROL, "Recieved command fragment out of order; ignoring.");
  2197. send_control0_error(conn, ERR_SYNTAX, "Bad fragmentation on command.");
  2198. default:
  2199. warn(LD_CONTROL, "Received unrecognized command type %d; ignoring.",
  2200. (int)command_type);
  2201. send_control0_error(conn, ERR_UNRECOGNIZED_TYPE,
  2202. "Unrecognized command type");
  2203. break;
  2204. }
  2205. tor_free(body);
  2206. goto again; /* There might be more data. */
  2207. }
  2208. /** Called when <b>conn</b> has received more bytes on its inbuf.
  2209. */
  2210. int
  2211. connection_control_process_inbuf(connection_t *conn)
  2212. {
  2213. tor_assert(conn);
  2214. tor_assert(conn->type == CONN_TYPE_CONTROL);
  2215. if (STATE_IS_V0(conn->state))
  2216. return connection_control_process_inbuf_v0(conn);
  2217. else
  2218. return connection_control_process_inbuf_v1(conn);
  2219. }
  2220. /** Something has happened to circuit <b>circ</b>: tell any interested
  2221. * control connections. */
  2222. int
  2223. control_event_circuit_status(circuit_t *circ, circuit_status_event_t tp)
  2224. {
  2225. char *path, *msg;
  2226. if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS))
  2227. return 0;
  2228. tor_assert(circ);
  2229. tor_assert(CIRCUIT_IS_ORIGIN(circ));
  2230. path = circuit_list_path(circ,0);
  2231. if (EVENT_IS_INTERESTING0(EVENT_CIRCUIT_STATUS)) {
  2232. size_t path_len = strlen(path);
  2233. msg = tor_malloc(1+4+path_len+1); /* event, circid, path, NUL. */
  2234. msg[0] = (uint8_t) tp;
  2235. set_uint32(msg+1, htonl(circ->global_identifier));
  2236. strlcpy(msg+5,path,path_len+1);
  2237. send_control0_event(EVENT_CIRCUIT_STATUS, (uint32_t)(path_len+6), msg);
  2238. tor_free(msg);
  2239. }
  2240. if (EVENT_IS_INTERESTING1(EVENT_CIRCUIT_STATUS)) {
  2241. const char *status;
  2242. switch (tp)
  2243. {
  2244. case CIRC_EVENT_LAUNCHED: status = "LAUNCHED"; break;
  2245. case CIRC_EVENT_BUILT: status = "BUILT"; break;
  2246. case CIRC_EVENT_EXTENDED: status = "EXTENDED"; break;
  2247. case CIRC_EVENT_FAILED: status = "FAILED"; break;
  2248. case CIRC_EVENT_CLOSED: status = "CLOSED"; break;
  2249. default:
  2250. warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  2251. return 0;
  2252. }
  2253. send_control1_event(EVENT_CIRCUIT_STATUS,
  2254. "650 CIRC %lu %s %s\r\n",
  2255. (unsigned long)circ->global_identifier,
  2256. status, path);
  2257. }
  2258. tor_free(path);
  2259. return 0;
  2260. }
  2261. /** Given an AP connection <b>conn</b> and a <b>len</b>-character buffer
  2262. * <b>buf</b>, determine the address:port combination requested on
  2263. * <b>conn</b>, and write it to <b>buf</b>. Return 0 on success, -1 on
  2264. * failure. */
  2265. static int
  2266. write_stream_target_to_buf(connection_t *conn, char *buf, size_t len)
  2267. {
  2268. char buf2[256];
  2269. if (conn->chosen_exit_name)
  2270. if (tor_snprintf(buf2, sizeof(buf2), ".%s.exit", conn->chosen_exit_name)<0)
  2271. return -1;
  2272. if (tor_snprintf(buf, len, "%s%s%s:%d",
  2273. conn->socks_request->address,
  2274. conn->chosen_exit_name ? buf2 : "",
  2275. !conn->chosen_exit_name &&
  2276. connection_edge_is_rendezvous_stream(conn) ? ".onion" : "",
  2277. conn->socks_request->port)<0)
  2278. return -1;
  2279. return 0;
  2280. }
  2281. /** Something has happened to the stream associated with AP connection
  2282. * <b>conn</b>: tell any interested control connections. */
  2283. int
  2284. control_event_stream_status(connection_t *conn, stream_status_event_t tp)
  2285. {
  2286. char *msg;
  2287. size_t len;
  2288. char buf[256];
  2289. tor_assert(conn->type == CONN_TYPE_AP);
  2290. tor_assert(conn->socks_request);
  2291. if (!EVENT_IS_INTERESTING(EVENT_STREAM_STATUS))
  2292. return 0;
  2293. write_stream_target_to_buf(conn, buf, sizeof(buf));
  2294. if (EVENT_IS_INTERESTING0(EVENT_STREAM_STATUS)) {
  2295. len = strlen(buf);
  2296. msg = tor_malloc(5+len+1);
  2297. msg[0] = (uint8_t) tp;
  2298. set_uint32(msg+1, htonl(conn->global_identifier));
  2299. strlcpy(msg+5, buf, len+1);
  2300. send_control0_event(EVENT_STREAM_STATUS, (uint32_t)(5+len+1), msg);
  2301. tor_free(msg);
  2302. }
  2303. if (EVENT_IS_INTERESTING1(EVENT_STREAM_STATUS)) {
  2304. const char *status;
  2305. circuit_t *circ;
  2306. switch (tp)
  2307. {
  2308. case STREAM_EVENT_SENT_CONNECT: status = "SENTCONNECT"; break;
  2309. case STREAM_EVENT_SENT_RESOLVE: status = "SENTRESOLVE"; break;
  2310. case STREAM_EVENT_SUCCEEDED: status = "SUCCEEDED"; break;
  2311. case STREAM_EVENT_FAILED: status = "FAILED"; break;
  2312. case STREAM_EVENT_CLOSED: status = "CLOSED"; break;
  2313. case STREAM_EVENT_NEW: status = "NEW"; break;
  2314. case STREAM_EVENT_NEW_RESOLVE: status = "NEWRESOLVE"; break;
  2315. case STREAM_EVENT_FAILED_RETRIABLE: status = "DETACHED"; break;
  2316. default:
  2317. warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  2318. return 0;
  2319. }
  2320. circ = circuit_get_by_edge_conn(conn);
  2321. send_control1_event(EVENT_STREAM_STATUS,
  2322. "650 STREAM %lu %s %lu %s\r\n",
  2323. (unsigned long)conn->global_identifier, status,
  2324. circ?(unsigned long)circ->global_identifier : 0ul,
  2325. buf);
  2326. /* XXX need to specify its intended exit, etc? */
  2327. }
  2328. return 0;
  2329. }
  2330. /** Something has happened to the OR connection <b>conn</b>: tell any
  2331. * interested control connections. */
  2332. int
  2333. control_event_or_conn_status(connection_t *conn,or_conn_status_event_t tp)
  2334. {
  2335. char buf[HEX_DIGEST_LEN+3]; /* status, dollar, identity, NUL */
  2336. size_t len;
  2337. tor_assert(conn->type == CONN_TYPE_OR);
  2338. if (!EVENT_IS_INTERESTING(EVENT_OR_CONN_STATUS))
  2339. return 0;
  2340. if (EVENT_IS_INTERESTING0(EVENT_OR_CONN_STATUS)) {
  2341. buf[0] = (uint8_t)tp;
  2342. strlcpy(buf+1,conn->nickname,sizeof(buf)-1);
  2343. len = strlen(buf+1);
  2344. send_control0_event(EVENT_OR_CONN_STATUS, (uint32_t)(len+1), buf);
  2345. }
  2346. if (EVENT_IS_INTERESTING1(EVENT_OR_CONN_STATUS)) {
  2347. const char *status;
  2348. switch (tp)
  2349. {
  2350. case OR_CONN_EVENT_LAUNCHED: status = "LAUNCHED"; break;
  2351. case OR_CONN_EVENT_CONNECTED: status = "CONNECTED"; break;
  2352. case OR_CONN_EVENT_FAILED: status = "FAILED"; break;
  2353. case OR_CONN_EVENT_CLOSED: status = "CLOSED"; break;
  2354. default:
  2355. warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  2356. return 0;
  2357. }
  2358. send_control1_event(EVENT_OR_CONN_STATUS,
  2359. "650 ORCONN %s %s\r\n",
  2360. conn->nickname, status);
  2361. }
  2362. return 0;
  2363. }
  2364. /** A second or more has elapsed: tell any interested control
  2365. * connections how much bandwidth we used. */
  2366. int
  2367. control_event_bandwidth_used(uint32_t n_read, uint32_t n_written)
  2368. {
  2369. char buf[8];
  2370. if (EVENT_IS_INTERESTING0(EVENT_BANDWIDTH_USED)) {
  2371. set_uint32(buf, htonl(n_read));
  2372. set_uint32(buf+4, htonl(n_written));
  2373. send_control0_event(EVENT_BANDWIDTH_USED, 8, buf);
  2374. }
  2375. if (EVENT_IS_INTERESTING1(EVENT_BANDWIDTH_USED)) {
  2376. send_control1_event(EVENT_BANDWIDTH_USED,
  2377. "650 BW %lu %lu\r\n",
  2378. (unsigned long)n_read,
  2379. (unsigned long)n_written);
  2380. }
  2381. return 0;
  2382. }
  2383. /** Called when we are sending a log message to the controllers: suspend
  2384. * sending further log messages to the controllers until we're done. Used by
  2385. * CONN_LOG_PROTECT. */
  2386. void
  2387. disable_control_logging(void)
  2388. {
  2389. ++disable_log_messages;
  2390. }
  2391. /** We're done sending a log message to the controllers: re-enable controller
  2392. * logging. Used by CONN_LOG_PROTECT. */
  2393. void
  2394. enable_control_logging(void)
  2395. {
  2396. if (--disable_log_messages < 0)
  2397. tor_assert(0);
  2398. }
  2399. /** We got a log message: tell any interested control connections. */
  2400. void
  2401. control_event_logmsg(int severity, unsigned int domain, const char *msg)
  2402. {
  2403. int oldlog, event;
  2404. if (disable_log_messages)
  2405. return;
  2406. oldlog = EVENT_IS_INTERESTING0(EVENT_LOG_OBSOLETE) &&
  2407. (severity == LOG_NOTICE || severity == LOG_WARN || severity == LOG_ERR);
  2408. event = log_severity_to_event(severity);
  2409. if (event<0 || !EVENT_IS_INTERESTING0(event))
  2410. event = 0;
  2411. if (oldlog || event) {
  2412. size_t len = strlen(msg);
  2413. ++disable_log_messages;
  2414. if (event)
  2415. send_control0_event(event, (uint32_t)(len+1), msg);
  2416. if (oldlog)
  2417. send_control0_event(EVENT_LOG_OBSOLETE, (uint32_t)(len+1), msg);
  2418. --disable_log_messages;
  2419. }
  2420. event = log_severity_to_event(severity);
  2421. if (event >= 0 && EVENT_IS_INTERESTING1(event)) {
  2422. char *b = NULL;
  2423. const char *s;
  2424. if (strchr(msg, '\n')) {
  2425. char *cp;
  2426. b = tor_strdup(msg);
  2427. for (cp = b; *cp; ++cp)
  2428. if (*cp == '\r' || *cp == '\n')
  2429. *cp = ' ';
  2430. }
  2431. switch (severity) {
  2432. case LOG_DEBUG: s = "DEBUG"; break;
  2433. case LOG_INFO: s = "INFO"; break;
  2434. case LOG_NOTICE: s = "NOTICE"; break;
  2435. case LOG_WARN: s = "WARN"; break;
  2436. case LOG_ERR: s = "ERR"; break;
  2437. default: s = "UnknownLogSeverity"; break;
  2438. }
  2439. ++disable_log_messages;
  2440. send_control1_event(event, "650 %s %s\r\n", s, b?b:msg);
  2441. --disable_log_messages;
  2442. tor_free(b);
  2443. }
  2444. }
  2445. /** Called whenever we receive new router descriptors: tell any
  2446. * interested control connections. <b>routers</b> is a list of
  2447. * DIGEST_LEN-byte identity digests.
  2448. */
  2449. int
  2450. control_event_descriptors_changed(smartlist_t *routers)
  2451. {
  2452. size_t len;
  2453. char *msg;
  2454. smartlist_t *identities;
  2455. char buf[HEX_DIGEST_LEN+1];
  2456. if (!EVENT_IS_INTERESTING(EVENT_NEW_DESC))
  2457. return 0;
  2458. identities = smartlist_create();
  2459. SMARTLIST_FOREACH(routers, routerinfo_t *, r,
  2460. {
  2461. base16_encode(buf,sizeof(buf),r->cache_info.identity_digest,DIGEST_LEN);
  2462. smartlist_add(identities, tor_strdup(buf));
  2463. });
  2464. if (EVENT_IS_INTERESTING0(EVENT_NEW_DESC)) {
  2465. msg = smartlist_join_strings(identities, ",", 0, &len);
  2466. send_control0_event(EVENT_NEW_DESC, len+1, msg);
  2467. tor_free(msg);
  2468. }
  2469. if (EVENT_IS_INTERESTING1(EVENT_NEW_DESC)) {
  2470. msg = smartlist_join_strings(identities, " ", 0, &len);
  2471. send_control1_event(EVENT_NEW_DESC, "650 NEWDESC %s\r\n", msg);
  2472. tor_free(msg);
  2473. }
  2474. SMARTLIST_FOREACH(identities, char *, cp, tor_free(cp));
  2475. smartlist_free(identities);
  2476. return 0;
  2477. }
  2478. /** Called whenever an address mapping on <b>from<b> from changes to <b>to</b>.
  2479. * <b>expires</b> values less than 3 are special; see connection_edge.c. */
  2480. int
  2481. control_event_address_mapped(const char *from, const char *to, time_t expires)
  2482. {
  2483. if (!EVENT_IS_INTERESTING1(EVENT_ADDRMAP))
  2484. return 0;
  2485. if (expires < 3)
  2486. send_control1_event(EVENT_ADDRMAP,
  2487. "650 ADDRMAP %s %s NEVER\r\n", from, to);
  2488. else {
  2489. char buf[ISO_TIME_LEN+1];
  2490. format_local_iso_time(buf,expires);
  2491. send_control1_event(EVENT_ADDRMAP, "650 ADDRMAP %s %s \"%s\"\r\n",
  2492. from, to, buf);
  2493. }
  2494. return 0;
  2495. }
  2496. /** The authoritative dirserver has received a new descriptor that
  2497. * has passed basic syntax checks and is properly self-signed.
  2498. *
  2499. * Notify any interested party of the new descriptor and what has
  2500. * been done with it, and also optionally give an explanation/reason. */
  2501. int
  2502. control_event_or_authdir_new_descriptor(const char *action,
  2503. const char *descriptor,
  2504. const char *msg)
  2505. {
  2506. char firstline[1024];
  2507. char *buf;
  2508. int totallen;
  2509. char *esc = NULL;
  2510. size_t esclen;
  2511. if (!EVENT_IS_INTERESTING(EVENT_AUTHDIR_NEWDESCS))
  2512. return 0;
  2513. tor_snprintf(firstline, sizeof(firstline),
  2514. "650+AUTHDIR_NEWDESC=\r\n%s\r\n%s\r\n",
  2515. action,
  2516. msg ? msg : "");
  2517. /* Escape the server descriptor properly */
  2518. esclen = write_escaped_data(descriptor, strlen(descriptor), 1, &esc);
  2519. totallen = strlen(firstline) + esclen + 1;
  2520. buf = tor_malloc(totallen);
  2521. strlcpy(buf, firstline, totallen);
  2522. strlcpy(buf+strlen(firstline), esc, totallen);
  2523. send_control1_event_string(EVENT_AUTHDIR_NEWDESCS, buf);
  2524. tor_free(esc);
  2525. tor_free(buf);
  2526. return 0;
  2527. }
  2528. /** Choose a random authentication cookie and write it to disk.
  2529. * Anybody who can read the cookie from disk will be considered
  2530. * authorized to use the control connection. */
  2531. int
  2532. init_cookie_authentication(int enabled)
  2533. {
  2534. char fname[512];
  2535. if (!enabled) {
  2536. authentication_cookie_is_set = 0;
  2537. return 0;
  2538. }
  2539. tor_snprintf(fname, sizeof(fname), "%s/control_auth_cookie",
  2540. get_options()->DataDirectory);
  2541. crypto_rand(authentication_cookie, AUTHENTICATION_COOKIE_LEN);
  2542. authentication_cookie_is_set = 1;
  2543. if (write_bytes_to_file(fname, authentication_cookie,
  2544. AUTHENTICATION_COOKIE_LEN, 1)) {
  2545. warn(LD_FS,"Error writing authentication cookie.");
  2546. return -1;
  2547. }
  2548. return 0;
  2549. }