Appease verbose GCC warnings.
[tor.git] / src / or / control.c
blob582f6e001e28390830c74d8c5c0e85fba8522b8b
1 /* Copyright 2004-2005 Roger Dingledine, Nick Mathewson. */
2 /* See LICENSE for licensing information */
3 /* $Id$ */
4 const char control_c_id[] = "$Id$";
6 /**
7 * \file control.c
8 * \brief Implementation for Tor's control-socket interface.
9 **/
11 #include "or.h"
13 #define STATE_IS_OPEN(s) ((s) == CONTROL_CONN_STATE_OPEN_V0 || \
14 (s) == CONTROL_CONN_STATE_OPEN_V1)
15 #define STATE_IS_V0(s) ((s) == CONTROL_CONN_STATE_NEEDAUTH_V0 || \
16 (s) == CONTROL_CONN_STATE_OPEN_V0)
19 * See control-spec.txt and control-spec-v0.txt for full details on protocol(s).
22 /* Recognized message type codes. */
23 #define CONTROL0_CMD_ERROR 0x0000
24 #define CONTROL0_CMD_DONE 0x0001
25 #define CONTROL0_CMD_SETCONF 0x0002
26 #define CONTROL0_CMD_GETCONF 0x0003
27 #define CONTROL0_CMD_CONFVALUE 0x0004
28 #define CONTROL0_CMD_SETEVENTS 0x0005
29 #define CONTROL0_CMD_EVENT 0x0006
30 #define CONTROL0_CMD_AUTHENTICATE 0x0007
31 #define CONTROL0_CMD_SAVECONF 0x0008
32 #define CONTROL0_CMD_SIGNAL 0x0009
33 #define CONTROL0_CMD_MAPADDRESS 0x000A
34 #define CONTROL0_CMD_GETINFO 0x000B
35 #define CONTROL0_CMD_INFOVALUE 0x000C
36 #define CONTROL0_CMD_EXTENDCIRCUIT 0x000D
37 #define CONTROL0_CMD_ATTACHSTREAM 0x000E
38 #define CONTROL0_CMD_POSTDESCRIPTOR 0x000F
39 #define CONTROL0_CMD_FRAGMENTHEADER 0x0010
40 #define CONTROL0_CMD_FRAGMENT 0x0011
41 #define CONTROL0_CMD_REDIRECTSTREAM 0x0012
42 #define CONTROL0_CMD_CLOSESTREAM 0x0013
43 #define CONTROL0_CMD_CLOSECIRCUIT 0x0014
44 #define _CONTROL0_CMD_MAX_RECOGNIZED 0x0014
46 /* Recognized error codes. */
47 #define ERR_UNSPECIFIED 0x0000
48 #define ERR_INTERNAL 0x0001
49 #define ERR_UNRECOGNIZED_TYPE 0x0002
50 #define ERR_SYNTAX 0x0003
51 #define ERR_UNRECOGNIZED_CONFIG_KEY 0x0004
52 #define ERR_INVALID_CONFIG_VALUE 0x0005
53 #define ERR_UNRECOGNIZED_EVENT_CODE 0x0006
54 #define ERR_UNAUTHORIZED 0x0007
55 #define ERR_REJECTED_AUTHENTICATION 0x0008
56 #define ERR_RESOURCE_EXHAUSETED 0x0009
57 #define ERR_NO_STREAM 0x000A
58 #define ERR_NO_CIRC 0x000B
59 #define ERR_NO_ROUTER 0x000C
61 /* Recognized asynchronous event types. */
62 #define _EVENT_MIN 0x0001
63 #define EVENT_CIRCUIT_STATUS 0x0001
64 #define EVENT_STREAM_STATUS 0x0002
65 #define EVENT_OR_CONN_STATUS 0x0003
66 #define EVENT_BANDWIDTH_USED 0x0004
67 #define EVENT_LOG_OBSOLETE 0x0005
68 #define EVENT_NEW_DESC 0x0006
69 #define EVENT_DEBUG_MSG 0x0007
70 #define EVENT_INFO_MSG 0x0008
71 #define EVENT_NOTICE_MSG 0x0009
72 #define EVENT_WARN_MSG 0x000A
73 #define EVENT_ERR_MSG 0x000B
74 #define EVENT_ADDRMAP 0x000C
75 #define _EVENT_MAX 0x000C
77 /** Array mapping from message type codes to human-readable message
78 * type names. */
79 static const char * CONTROL0_COMMANDS[_CONTROL0_CMD_MAX_RECOGNIZED+1] = {
80 "error",
81 "done",
82 "setconf",
83 "getconf",
84 "confvalue",
85 "setevents",
86 "events",
87 "authenticate",
88 "saveconf",
89 "signal",
90 "mapaddress",
91 "getinfo",
92 "infovalue",
93 "extendcircuit",
94 "attachstream",
95 "postdescriptor",
96 "fragmentheader",
97 "fragment",
100 /** Bitfield: The bit 1&lt;&lt;e is set if <b>any</b> open control
101 * connection is interested in events of type <b>e</b>. We use this
102 * so that we can decide to skip generating event messages that nobody
103 * has interest in without having to walk over the global connection
104 * list to find out.
106 static uint32_t global_event_mask0 = 0;
107 static uint32_t global_event_mask1 = 0;
109 /** Macro: true if any control connection is interested in events of type
110 * <b>e</b>. */
111 #define EVENT_IS_INTERESTING0(e) (global_event_mask0 & (1<<(e)))
112 #define EVENT_IS_INTERESTING1(e) (global_event_mask1 & (1<<(e)))
113 #define EVENT_IS_INTERESTING(e) \
114 ((global_event_mask0|global_event_mask1) & (1<<(e)))
116 /** If we're using cookie-type authentication, how long should our cookies be?
118 #define AUTHENTICATION_COOKIE_LEN 32
120 /** If true, we've set authentication_cookie to a secret code and
121 * stored it to disk. */
122 static int authentication_cookie_is_set = 0;
123 static char authentication_cookie[AUTHENTICATION_COOKIE_LEN];
125 static void connection_printf_to_buf(connection_t *conn, const char *format, ...)
126 CHECK_PRINTF(2,3);
127 static void update_global_event_mask(void);
128 static void send_control0_message(connection_t *conn, uint16_t type,
129 uint32_t len, const char *body);
130 static void send_control_done(connection_t *conn);
131 static void send_control_done2(connection_t *conn, const char *msg, 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, const char *body);
135 static void send_control1_event(uint16_t event, const char *format, ...)
136 CHECK_PRINTF(2,3);
137 static int handle_control_setconf(connection_t *conn, uint32_t len,
138 char *body);
139 static int handle_control_getconf(connection_t *conn, uint32_t len,
140 const char *body);
141 static int handle_control_setevents(connection_t *conn, uint32_t len,
142 const char *body);
143 static int handle_control_authenticate(connection_t *conn, uint32_t len,
144 const char *body);
145 static int handle_control_saveconf(connection_t *conn, uint32_t len,
146 const char *body);
147 static int handle_control_signal(connection_t *conn, uint32_t len,
148 const char *body);
149 static int handle_control_mapaddress(connection_t *conn, uint32_t len,
150 const char *body);
151 static int handle_control_getinfo(connection_t *conn, uint32_t len,
152 const char *body);
153 static int handle_control_extendcircuit(connection_t *conn, uint32_t len,
154 const char *body);
155 static int handle_control_attachstream(connection_t *conn, uint32_t len,
156 const char *body);
157 static int handle_control_postdescriptor(connection_t *conn, uint32_t len,
158 const char *body);
159 static int handle_control_redirectstream(connection_t *conn, uint32_t len,
160 const char *body);
161 static int handle_control_closestream(connection_t *conn, uint32_t len,
162 const char *body);
163 static int handle_control_closecircuit(connection_t *conn, uint32_t len,
164 const char *body);
165 static int write_stream_target_to_buf(connection_t *conn, char *buf, size_t len);
167 /** Given a possibly invalid message type code <b>cmd</b>, return a
168 * human-readable string equivalent. */
169 static INLINE const char *
170 control_cmd_to_string(uint16_t cmd)
172 return (cmd<=_CONTROL0_CMD_MAX_RECOGNIZED) ? CONTROL0_COMMANDS[cmd] : "Unknown";
175 static INLINE int
176 event_to_log_severity(int event)
178 switch (event) {
179 case EVENT_DEBUG_MSG: return LOG_DEBUG;
180 case EVENT_INFO_MSG: return LOG_INFO;
181 case EVENT_NOTICE_MSG: return LOG_NOTICE;
182 case EVENT_WARN_MSG: return LOG_WARN;
183 case EVENT_ERR_MSG: return LOG_ERR;
184 default: return -1;
188 /** DOCDOC */
189 static INLINE int
190 log_severity_to_event(int severity)
192 switch (severity) {
193 case LOG_DEBUG: return EVENT_DEBUG_MSG;
194 case LOG_INFO: return EVENT_INFO_MSG;
195 case LOG_NOTICE: return EVENT_NOTICE_MSG;
196 case LOG_WARN: return EVENT_WARN_MSG;
197 case LOG_ERR: return EVENT_ERR_MSG;
198 default: return -1;
202 /** Set <b>global_event_mask</b> to the bitwise OR of each live control
203 * connection's event_mask field. */
204 static void
205 update_global_event_mask(void)
207 connection_t **conns;
208 int n_conns, i;
209 global_event_mask0 = 0;
210 global_event_mask1 = 0;
211 get_connection_array(&conns, &n_conns);
212 for (i = 0; i < n_conns; ++i) {
213 if (conns[i]->type == CONN_TYPE_CONTROL &&
214 STATE_IS_OPEN(conns[i]->state)) {
215 if (STATE_IS_V0(conns[i]->state))
216 global_event_mask0 |= conns[i]->event_mask;
217 else
218 global_event_mask1 |= conns[i]->event_mask;
222 adjust_event_log_severity();
225 /** DOCDOC */
226 void
227 adjust_event_log_severity(void)
229 int i;
230 int min_log_event=EVENT_ERR_MSG, max_log_event=EVENT_DEBUG_MSG;
232 for (i = EVENT_DEBUG_MSG; i <= EVENT_ERR_MSG; ++i) {
233 if (EVENT_IS_INTERESTING(i)) {
234 min_log_event = i;
235 break;
238 for (i = EVENT_ERR_MSG; i >= EVENT_DEBUG_MSG; --i) {
239 if (EVENT_IS_INTERESTING(i)) {
240 max_log_event = i;
241 break;
244 if (EVENT_IS_INTERESTING(EVENT_LOG_OBSOLETE)) {
245 if (min_log_event > EVENT_NOTICE_MSG)
246 min_log_event = EVENT_NOTICE_MSG;
247 if (max_log_event < EVENT_ERR_MSG)
248 max_log_event = EVENT_ERR_MSG;
250 change_callback_log_severity(event_to_log_severity(min_log_event),
251 event_to_log_severity(max_log_event),
252 control_event_logmsg);
255 /* DOCDOC */
256 static INLINE void
257 connection_write_str_to_buf(const char *s, connection_t *conn)
259 size_t len = strlen(s);
260 connection_write_to_buf(s, len, conn);
263 /* DOCDOC ; test */
264 static size_t
265 write_escaped_data(const char *data, size_t len, int translate_newlines,
266 char **out)
268 size_t sz_out = len+8;
269 char *outp;
270 const char *end;
271 int i;
272 int start_of_line;
273 for (i=0; i<len; ++i) {
274 if (data[i]== '\n')
275 ++sz_out;
277 *out = outp = tor_malloc(sz_out+1);
278 end = data+len;
279 start_of_line = 1;
280 while (data < end) {
281 if (*data == '\n') {
282 if (translate_newlines)
283 *outp++ = '\r';
284 start_of_line = 1;
285 } else if (*data == '.') {
286 if (start_of_line) {
287 start_of_line = 0;
288 *outp++ = '.';
290 } else {
291 start_of_line = 0;
293 *outp++ = *data++;
295 if (outp < *out+2 || memcmp(outp-2, "\r\n", 2)) {
296 *outp++ = '\r';
297 *outp++ = '\n';
299 *outp++ = '.';
300 *outp++ = '\r';
301 *outp++ = '\n';
302 return outp - *out;
305 /* DOCDOC ; test */
306 static size_t
307 read_escaped_data(const char *data, size_t len, int translate_newlines,
308 char **out)
310 char *outp;
311 const char *next;
313 *out = outp = tor_malloc(len);
315 while (len) {
316 if (*data == '.')
317 ++data;
318 if (translate_newlines)
319 next = tor_memmem(data, len, "\r\n", 2);
320 else
321 next = tor_memmem(data, len, "\r\n.", 3);
322 if (next) {
323 memcpy(outp, data, next-data);
324 outp += (next-data);
325 data = next+2;
326 } else {
327 memcpy(outp, data, len);
328 outp += len;
329 return outp - *out;
331 if (translate_newlines) {
332 *outp++ = '\n';
333 } else {
334 *outp++ = '\r';
335 *outp++ = '\n';
339 return outp - *out;
342 /** DOCDOC; test **/
343 static const char *
344 get_escaped_string(const char *start, size_t in_len_max,
345 char **out, size_t *out_len)
347 const char *cp, *end;
348 char *outp;
349 size_t len=0;
351 if (*start != '\"')
352 return NULL;
354 cp = start+1;
355 end = start+in_len_max;
357 /* Calculate length. */
358 while (1) {
359 if (cp >= end)
360 return NULL;
361 else if (*cp == '\\') {
362 if (++cp == end)
363 return NULL; /* Can't escape EOS. */
364 ++cp;
365 ++len;
366 } else if (*cp == '\"') {
367 break;
368 } else {
369 ++cp;
370 ++len;
373 end = cp;
374 outp = *out = tor_malloc(len+1);
375 *out_len = len;
377 cp = start+1;
378 while (cp < end) {
379 if (*cp == '\\')
380 ++cp;
381 *outp++ = *cp++;
383 *outp = '\0';
384 tor_assert((outp - *out) == *out_len);
386 return end+1;
389 /* DOCDOC */
390 static void
391 connection_printf_to_buf(connection_t *conn, const char *format, ...)
393 va_list ap;
394 char buf[1024];
395 int r;
396 size_t len;
397 va_start(ap,format);
398 r = tor_vsnprintf(buf, sizeof(buf), format, ap);
399 va_end(ap);
400 len = strlen(buf);
401 if (memcmp("\r\n\0", buf+len-2, 3)) {
402 buf[1023] = '\0';
403 buf[1022] = '\n';
404 buf[1021] = '\r';
406 connection_write_to_buf(buf, len, conn);
409 /** Send a message of type <b>type</b> containing <b>len</b> bytes
410 * from <b>body</b> along the control connection <b>conn</b> */
411 static void
412 send_control0_message(connection_t *conn, uint16_t type, uint32_t len,
413 const char *body)
415 char buf[10];
416 tor_assert(conn);
417 tor_assert(STATE_IS_V0(conn->state));
418 tor_assert(len || !body);
419 tor_assert(type <= _CONTROL0_CMD_MAX_RECOGNIZED);
420 if (len < 65536) {
421 set_uint16(buf, htons(len));
422 set_uint16(buf+2, htons(type));
423 connection_write_to_buf(buf, 4, conn);
424 if (len)
425 connection_write_to_buf(body, len, conn);
426 } else {
427 set_uint16(buf, htons(65535));
428 set_uint16(buf+2, htons(CONTROL0_CMD_FRAGMENTHEADER));
429 set_uint16(buf+4, htons(type));
430 set_uint32(buf+6, htonl(len));
431 connection_write_to_buf(buf, 10, conn);
432 connection_write_to_buf(body, 65535-6, conn);
433 len -= (65535-6);
434 body += (65535-6);
435 while (len) {
436 size_t chunklen = (len<65535)?len:65535;
437 set_uint16(buf, htons((uint16_t)chunklen));
438 set_uint16(buf+2, htons(CONTROL0_CMD_FRAGMENT));
439 connection_write_to_buf(buf, 4, conn);
440 connection_write_to_buf(body, chunklen, conn);
441 len -= chunklen;
442 body += chunklen;
447 /** Send a "DONE" message down the control connection <b>conn</b> */
448 static void
449 send_control_done(connection_t *conn)
451 if (STATE_IS_V0(conn->state)) {
452 send_control0_message(conn, CONTROL0_CMD_DONE, 0, NULL);
453 } else {
454 connection_write_str_to_buf("250 OK\r\n", conn);
458 /** DOCDOC */
459 static void
460 send_control_done2(connection_t *conn, const char *msg, size_t len)
462 if (len==0)
463 len = strlen(msg);
464 send_control0_message(conn, CONTROL0_CMD_DONE, len, msg);
467 /** Send an error message with error code <b>error</b> and body
468 * <b>message</b> down the connection <b>conn</b> */
469 static void
470 send_control0_error(connection_t *conn, uint16_t error, const char *message)
472 char buf[256];
473 size_t len;
474 set_uint16(buf, htons(error));
475 len = strlen(message);
476 tor_assert(len < (256-2));
477 memcpy(buf+2, message, len);
478 send_control0_message(conn, CONTROL0_CMD_ERROR, (uint16_t)(len+2), buf);
481 /** Send an 'event' message of event type <b>event</b>, containing
482 * <b>len</b> bytes in <b>body</b> to every control connection that
483 * is interested in it. */
484 static void
485 send_control0_event(uint16_t event, uint32_t len, const char *body)
487 connection_t **conns;
488 int n_conns, i;
489 size_t buflen;
490 char *buf;
492 tor_assert(event >= _EVENT_MIN && event <= _EVENT_MAX);
494 buflen = len + 2;
495 buf = tor_malloc_zero(buflen);
496 set_uint16(buf, htons(event));
497 memcpy(buf+2, body, len);
499 get_connection_array(&conns, &n_conns);
500 for (i = 0; i < n_conns; ++i) {
501 if (conns[i]->type == CONN_TYPE_CONTROL &&
502 conns[i]->state == CONTROL_CONN_STATE_OPEN_V0 &&
503 conns[i]->event_mask & (1<<event)) {
504 send_control0_message(conns[i], CONTROL0_CMD_EVENT, buflen, buf);
505 if (event == EVENT_ERR_MSG)
506 _connection_controller_force_write(conns[i]);
510 tor_free(buf);
513 /* DOCDOC */
514 static void
515 send_control1_event(uint16_t event, const char *format, ...)
517 connection_t **conns;
518 int n_conns, i, r;
519 char buf[1024]; /* XXXX Length */
520 va_list ap;
521 size_t len;
523 va_start(ap, format);
524 r = tor_vsnprintf(buf, sizeof(buf), format, ap);
525 va_end(ap);
527 len = strlen(buf);
528 if (memcmp("\r\n\0", buf+len-2, 3)) {
529 buf[1023] = '\0';
530 buf[1022] = '\n';
531 buf[1021] = '\r';
534 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]->state == CONTROL_CONN_STATE_OPEN_V1 &&
540 conns[i]->event_mask & (1<<event)) {
541 connection_write_to_buf(buf, len, conns[i]);
542 if (event == EVENT_ERR_MSG)
543 _connection_controller_force_write(conns[i]);
548 static circuit_t *
549 get_circ(const char *id)
551 unsigned long n_id;
552 int ok;
553 n_id = tor_parse_ulong(id, 10, 0, ULONG_MAX, &ok, NULL);
554 if (!ok)
555 return NULL;
556 return circuit_get_by_global_id(n_id);
559 static connection_t *
560 get_stream(const char *id)
562 unsigned long n_id;
563 int ok;
564 connection_t *conn;
565 n_id = tor_parse_ulong(id, 10, 0, ULONG_MAX, &ok, NULL);
566 if (!ok)
567 return NULL;
568 conn = connection_get_by_global_id(n_id);
569 if (conn->type != CONN_TYPE_AP)
570 return NULL;
571 return conn;
574 /** Called when we receive a SETCONF message: parse the body and try
575 * to update our configuration. Reply with a DONE or ERROR message. */
576 static int
577 handle_control_setconf(connection_t *conn, uint32_t len, char *body)
579 int r;
580 struct config_line_t *lines=NULL;
581 char *start = body;
582 int v0 = STATE_IS_V0(conn->state);
584 if (!v0) {
585 char *config = tor_malloc(len+1);
586 char *outp = config;
587 while (*body) {
588 char *eq = body;
589 while (!TOR_ISSPACE(*eq) && *eq != '=')
590 ++eq;
591 memcpy(outp, body, eq-body);
592 outp += (eq-body);
593 *outp++ = ' ';
594 body = eq+1;
595 if (*eq == '=') {
596 if (*body != '\"') {
597 while (!TOR_ISSPACE(*body))
598 *outp++ = *body++;
599 } else {
600 char *val;
601 size_t val_len;
602 body = (char*)get_escaped_string(body, (len - (body-start)),
603 &val, &val_len);
604 if (!body) {
605 connection_write_str_to_buf("551 Couldn't parse string\r\n", conn);
606 tor_free(config);
607 return 0;
609 memcpy(outp, val, val_len);
610 outp += val_len;
611 tor_free(val);
614 while (TOR_ISSPACE(*body))
615 ++body;
616 *outp++ = '\n';
618 *outp = '\0';
620 if (config_get_lines(config, &lines) < 0) {
621 log_fn(LOG_WARN,"Controller gave us config lines we can't parse.");
622 connection_write_str_to_buf("551 Couldn't parse configuration\r\n", conn);
623 tor_free(config);
624 return 0;
626 tor_free(config);
627 } else {
628 if (config_get_lines(body, &lines) < 0) {
629 log_fn(LOG_WARN,"Controller gave us config lines we can't parse.");
630 send_control0_error(conn, ERR_SYNTAX, "Couldn't parse configuration");
631 return 0;
635 if ((r=config_trial_assign(lines, 1)) < 0) {
636 log_fn(LOG_WARN,"Controller gave us config lines that didn't validate.");
637 if (r==-1) {
638 if (v0)
639 send_control0_error(conn, ERR_UNRECOGNIZED_CONFIG_KEY,
640 "Unrecognized option");
641 else
642 connection_write_str_to_buf("552 Unrecognzied option\r\n", conn);
643 } else {
644 if (v0)
645 send_control0_error(conn,ERR_INVALID_CONFIG_VALUE,"Invalid option value");
646 else
647 connection_write_str_to_buf("552 Invalid option value\r\n", conn);
649 config_free_lines(lines);
650 return 0;
653 config_free_lines(lines);
654 if (options_act() < 0) { /* acting on them failed. die. */
655 log_fn(LOG_ERR,"Acting on config options left us in a broken state. Dying.");
656 exit(1);
658 send_control_done(conn);
659 return 0;
662 /** Called when we receive a GETCONF message. Parse the request, and
663 * reply with a CONFVALUE or an ERROR message */
664 static int
665 handle_control_getconf(connection_t *conn, uint32_t body_len, const char *body)
667 smartlist_t *questions = NULL;
668 smartlist_t *answers = NULL;
669 smartlist_t *unrecognized = NULL;
670 char *msg = NULL;
671 size_t msg_len;
672 or_options_t *options = get_options();
673 int v0 = STATE_IS_V0(conn->state);
675 questions = smartlist_create();
676 if (v0) {
677 smartlist_split_string(questions, body, "\n",
678 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
679 } else {
680 smartlist_split_string(questions, body, " ",
681 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
683 answers = smartlist_create();
684 unrecognized = smartlist_create();
685 SMARTLIST_FOREACH(questions, char *, q,
687 if (!config_option_is_recognized(q)) {
688 if (v0) {
689 send_control0_error(conn, ERR_UNRECOGNIZED_CONFIG_KEY, q);
690 goto done;
691 } else {
692 smartlist_add(unrecognized, q);
694 } else {
695 struct config_line_t *answer = config_get_assigned_option(options,q);
696 if (!v0 && !answer) {
697 size_t alen = strlen(q)+8;
698 char *astr = tor_malloc(alen);
699 tor_snprintf(astr, alen, "250-%s\r\n", q);
700 smartlist_add(answers, astr);
703 while (answer) {
704 struct config_line_t *next;
705 size_t alen = strlen(answer->key)+strlen(answer->value)+8;
706 char *astr = tor_malloc(alen);
707 if (v0)
708 tor_snprintf(astr, alen, "%s %s\n", answer->key, answer->value);
709 else
710 tor_snprintf(astr, alen, "250-%s=%s\r\n", answer->key, answer->value);
711 smartlist_add(answers, astr);
713 next = answer->next;
714 tor_free(answer->key);
715 tor_free(answer->value);
716 tor_free(answer);
717 answer = next;
722 if (v0) {
723 msg = smartlist_join_strings(answers, "", 0, &msg_len);
724 send_control0_message(conn, CONTROL0_CMD_CONFVALUE,
725 (uint16_t)msg_len, msg_len?msg:NULL);
726 } else {
727 int i,len;
728 if ((len = smartlist_len(unrecognized))) {
729 for (i=0; i < len-1; ++i)
730 connection_printf_to_buf(conn,
731 "552-Unrecognized configuration key \"%s\"\r\n",
732 (char*)smartlist_get(unrecognized, i));
733 connection_printf_to_buf(conn,
734 "552 Unrecognized configuration key \"%s\"\r\n",
735 (char*)smartlist_get(unrecognized, len-1));
736 } else if ((len = smartlist_len(answers))) {
737 char *tmp = smartlist_get(answers, len-1);
738 tor_assert(strlen(tmp)>4);
739 tmp[3] = ' ';
740 msg = smartlist_join_strings(answers, "", 0, &msg_len);
741 connection_write_to_buf(msg, msg_len, conn);
742 } else {
743 connection_write_str_to_buf("250 OK\r\n", conn);
747 done:
748 if (answers) SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
749 if (questions) SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
750 smartlist_free(answers);
751 smartlist_free(questions);
752 smartlist_free(unrecognized);
753 tor_free(msg);
755 return 0;
758 /** Called when we get a SETEVENTS message: update conn->event_mask,
759 * and reply with DONE or ERROR. */
760 static int
761 handle_control_setevents(connection_t *conn, uint32_t len, const char *body)
763 uint16_t event_code;
764 uint32_t event_mask = 0;
766 if (STATE_IS_V0(conn->state)) {
767 if (len % 2) {
768 send_control0_error(conn, ERR_SYNTAX,
769 "Odd number of bytes in setevents message");
770 return 0;
773 for (; len; len -= 2, body += 2) {
774 event_code = ntohs(get_uint16(body));
775 if (event_code < _EVENT_MIN || event_code > _EVENT_MAX) {
776 send_control0_error(conn, ERR_UNRECOGNIZED_EVENT_CODE,
777 "Unrecognized event code");
778 return 0;
780 event_mask |= (1 << event_code);
782 } else {
783 smartlist_t *events = smartlist_create();
784 smartlist_split_string(events, body, " ",
785 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
786 SMARTLIST_FOREACH(events, const char *, ev,
788 if (!strcasecmp(ev, "CIRC"))
789 event_code = EVENT_CIRCUIT_STATUS;
790 else if (!strcasecmp(ev, "STREAM"))
791 event_code = EVENT_STREAM_STATUS;
792 else if (!strcasecmp(ev, "ORCONN"))
793 event_code = EVENT_OR_CONN_STATUS;
794 else if (!strcasecmp(ev, "BW"))
795 event_code = EVENT_BANDWIDTH_USED;
796 else if (!strcasecmp(ev, "DEBUG"))
797 continue; /* Don't do debug messages */
798 else if (!strcasecmp(ev, "INFO"))
799 event_code = EVENT_INFO_MSG;
800 else if (!strcasecmp(ev, "NOTICE"))
801 event_code = EVENT_NOTICE_MSG;
802 else if (!strcasecmp(ev, "WARN"))
803 event_code = EVENT_WARN_MSG;
804 else if (!strcasecmp(ev, "ERR"))
805 event_code = EVENT_ERR_MSG;
806 else if (!strcasecmp(ev, "NEWDESC"))
807 event_code = EVENT_NEW_DESC;
808 else if (!strcasecmp(ev, "ADDRMAP"))
809 event_code = EVENT_ADDRMAP;
810 else {
811 connection_printf_to_buf(conn, "552 Unrecognized event \"%s\"\r\n",
812 ev);
813 SMARTLIST_FOREACH(events, char *, e, tor_free(e));
814 smartlist_free(events);
815 return 0;
817 event_mask |= (1 << event_code);
819 SMARTLIST_FOREACH(events, char *, e, tor_free(e));
820 smartlist_free(events);
822 conn->event_mask = event_mask;
824 update_global_event_mask();
825 send_control_done(conn);
826 return 0;
829 /** Decode the hashed, base64'd password stored in <b>hashed</b>. If
830 * <b>buf</b> is provided, store the hashed password in the first
831 * S2K_SPECIFIER_LEN+DIGEST_LEN bytes of <b>buf</b>. Return 0 on
832 * success, -1 on failure.
835 decode_hashed_password(char *buf, const char *hashed)
837 char decoded[64];
838 if (!strcmpstart(hashed, "16:")) {
839 if (base16_decode(decoded, sizeof(decoded), hashed+3, strlen(hashed+3))<0
840 || strlen(hashed+3) != (S2K_SPECIFIER_LEN+DIGEST_LEN)*2) {
841 return -1;
843 } else {
844 if (base64_decode(decoded, sizeof(decoded), hashed, strlen(hashed))
845 != S2K_SPECIFIER_LEN+DIGEST_LEN) {
846 return -1;
849 if (buf)
850 memcpy(buf, decoded, S2K_SPECIFIER_LEN+DIGEST_LEN);
851 return 0;
854 /** Called when we get an AUTHENTICATE message. Check whether the
855 * authentication is valid, and if so, update the connection's state to
856 * OPEN. Reply with DONE or ERROR.
858 static int
859 handle_control_authenticate(connection_t *conn, uint32_t len, const char *body)
861 or_options_t *options = get_options();
862 char *password;
863 size_t password_len;
864 if (STATE_IS_V0(conn->state)) {
865 password = (char*)body;
866 password_len = len;
867 } else {
868 if (TOR_ISXDIGIT(body[0])) {
869 int i = 0;
870 while (TOR_ISXDIGIT(body[i]))
871 ++i;
872 password = tor_malloc(i/2 + 1);
873 if (base16_decode(password, i/2+1, body, i)<0) {
874 connection_write_str_to_buf("551 Invalid hexadecimal encoding\r\n", conn);
875 tor_free(password);
876 return 0;
878 password_len = i/2;
879 } else if (TOR_ISSPACE(body[0])) {
880 password = tor_strdup("");
881 password_len = 0;
882 } else {
883 if (!get_escaped_string(body, len, &password, &password_len)) {
884 connection_write_str_to_buf("551 Invalid quoted string\r\n", conn);
885 return 0;
889 if (options->CookieAuthentication) {
890 if (len == AUTHENTICATION_COOKIE_LEN &&
891 !memcmp(authentication_cookie, password, password_len)) {
892 goto ok;
894 } else if (options->HashedControlPassword) {
895 char expected[S2K_SPECIFIER_LEN+DIGEST_LEN];
896 char received[DIGEST_LEN];
897 if (decode_hashed_password(expected, options->HashedControlPassword)<0) {
898 log_fn(LOG_WARN,"Couldn't decode HashedControlPassword: invalid base64");
899 goto err;
901 secret_to_key(received,DIGEST_LEN,password,password_len,expected);
902 if (!memcmp(expected+S2K_SPECIFIER_LEN, received, DIGEST_LEN))
903 goto ok;
904 goto err;
905 } else {
906 /* if Tor doesn't demand any stronger authentication, then
907 * the controller can get in with anything. */
908 goto ok;
911 err:
912 if (STATE_IS_V0(conn->state))
913 send_control0_error(conn,ERR_REJECTED_AUTHENTICATION,"Authentication failed");
914 else {
915 tor_free(password);
916 connection_write_str_to_buf("515 Authentication failed\r\n", conn);
918 return 0;
920 log_fn(LOG_INFO, "Authenticated control connection (%d)", conn->s);
921 send_control_done(conn);
922 if (STATE_IS_V0(conn->state))
923 conn->state = CONTROL_CONN_STATE_OPEN_V0;
924 else {
925 conn->state = CONTROL_CONN_STATE_OPEN_V1;
926 tor_free(password);
928 return 0;
931 /** DOCDOC */
932 static int
933 handle_control_saveconf(connection_t *conn, uint32_t len,
934 const char *body)
936 if (save_current_config()<0) {
937 if (STATE_IS_V0(conn->state))
938 send_control0_error(conn, ERR_INTERNAL,
939 "Unable to write configuration to disk.");
940 else
941 connection_write_str_to_buf("551 Unable to write configuration to disk.",
942 conn);
943 } else {
944 send_control_done(conn);
946 return 0;
949 /** DOCDOC */
950 static int
951 handle_control_signal(connection_t *conn, uint32_t len,
952 const char *body)
954 int sig;
955 if (STATE_IS_V0(conn->state)) {
956 if (len != 1) {
957 send_control0_error(conn, ERR_SYNTAX,
958 "Body of SIGNAL command too long or too short.");
959 return 0;
960 } else {
961 sig = (uint8_t)body[0];
963 } else {
964 int n = 0;
965 char *s;
966 while (body[n] && ! TOR_ISSPACE(body[n]))
967 ++n;
968 s = tor_strndup(body, n);
969 if (!strcasecmp(s, "RELOAD") || !strcasecmp(s, "HUP"))
970 sig = SIGHUP;
971 else if (!strcasecmp(s, "SHUTDOWN") || !strcasecmp(s, "INT"))
972 sig = SIGINT;
973 else if (!strcasecmp(s, "DUMP") || !strcasecmp(s, "USR1"))
974 sig = SIGUSR1;
975 else if (!strcasecmp(s, "DEBUG") || !strcasecmp(s, "USR2"))
976 sig = SIGUSR2;
977 else if (!strcasecmp(s, "HALT") || !strcasecmp(s, "TERM"))
978 sig = SIGTERM;
979 else {
980 connection_printf_to_buf(conn, "552 Unrecognized signal code \"%s\"\r\n",
981 body);
982 sig = -1;
984 tor_free(s);
985 if (sig<0)
986 return 0;
989 if (control_signal_act(sig) < 0) {
990 if (STATE_IS_V0(conn->state))
991 send_control0_error(conn, ERR_SYNTAX, "Unrecognized signal number.");
992 else
993 connection_write_str_to_buf("551 Internal error acting on signal\r\n",
994 conn);
995 } else {
996 send_control_done(conn);
998 return 0;
1001 /** DOCDOC */
1002 static int
1003 handle_control_mapaddress(connection_t *conn, uint32_t len, const char *body)
1005 smartlist_t *elts;
1006 smartlist_t *lines;
1007 smartlist_t *reply;
1008 char *r;
1009 size_t sz;
1010 int v0 = STATE_IS_V0(conn->state);
1011 lines = smartlist_create();
1012 elts = smartlist_create();
1013 reply = smartlist_create();
1014 if (v0)
1015 smartlist_split_string(lines, body, "\n",
1016 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1017 else
1018 smartlist_split_string(lines, body, " ",
1019 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1020 /* XXXX Make errors conformant. */
1021 SMARTLIST_FOREACH(lines, char *, line,
1023 tor_strlower(line);
1024 if (v0)
1025 smartlist_split_string(elts, line, " ", 0, 2);
1026 else
1027 smartlist_split_string(elts, line, "=", 0, 2);
1028 if (smartlist_len(elts) == 2) {
1029 const char *from = smartlist_get(elts,0);
1030 const char *to = smartlist_get(elts,1);
1031 if (!is_plausible_address(from)) {
1032 log_fn(LOG_WARN,"Skipping invalid argument '%s' in MapAddress msg",from);
1033 } else if (!is_plausible_address(to)) {
1034 log_fn(LOG_WARN,"Skipping invalid argument '%s' in MapAddress msg",to);
1035 } else if (!strcmp(from, ".") || !strcmp(from, "0.0.0.0")) {
1036 const char *addr = addressmap_register_virtual_address(
1037 !strcmp(from,".") ? RESOLVED_TYPE_HOSTNAME : RESOLVED_TYPE_IPV4,
1038 tor_strdup(to));
1039 if (!addr) {
1040 log_fn(LOG_WARN,
1041 "Unable to allocate address for '%s' in MapAddress msg",
1042 safe_str(line));
1043 } else {
1044 size_t anslen = strlen(addr)+strlen(to)+8;
1045 char *ans = tor_malloc(anslen);
1046 if (v0)
1047 tor_snprintf(ans, anslen, "%s %s", addr, to);
1048 else
1049 tor_snprintf(ans, anslen, "250-%s=%s", addr, to);
1050 smartlist_add(reply, ans);
1052 } else {
1053 addressmap_register(from, tor_strdup(to), 1);
1054 if (v0)
1055 smartlist_add(reply, tor_strdup(line));
1056 else {
1057 size_t anslen = strlen(line)+8;
1058 char *ans = tor_malloc(anslen);
1059 tor_snprintf(ans, anslen, "250-%s", line);
1060 smartlist_add(reply, ans);
1063 } else {
1064 log_fn(LOG_WARN, "Skipping MapAddress line with wrong number of items.");
1066 SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
1067 smartlist_clear(elts);
1069 SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
1070 smartlist_free(lines);
1071 smartlist_free(elts);
1073 if (v0) {
1074 r = smartlist_join_strings(reply, "\n", 1, &sz);
1075 send_control_done2(conn,r,sz);
1076 } else {
1077 if (smartlist_len(reply))
1078 ((char*)smartlist_get(reply,smartlist_len(reply)-1))[3] = ' ';
1079 r = smartlist_join_strings(reply, "\r\n", 1, &sz);
1080 connection_write_to_buf(r, sz, conn);
1083 SMARTLIST_FOREACH(reply, char *, cp, tor_free(cp));
1084 smartlist_free(reply);
1085 tor_free(r);
1086 return 0;
1089 /** Lookup the 'getinfo' entry <b>question</b>, and return
1090 * the answer in <b>*answer</b> (or NULL if key not recognized).
1091 * Return 0 if success, or -1 if internal error. */
1092 static int
1093 handle_getinfo_helper(const char *question, char **answer)
1095 *answer = NULL; /* unrecognized key by default */
1096 if (!strcmp(question, "version")) {
1097 *answer = tor_strdup(VERSION);
1098 } else if (!strcmpstart(question, "desc/id/")) {
1099 routerinfo_t *ri = router_get_by_hexdigest(question+strlen("desc/id/"));
1100 if (ri && ri->signed_descriptor)
1101 *answer = tor_strdup(ri->signed_descriptor);
1102 } else if (!strcmpstart(question, "desc/name/")) {
1103 routerinfo_t *ri = router_get_by_nickname(question+strlen("desc/name/"));
1104 if (ri && ri->signed_descriptor)
1105 *answer = tor_strdup(ri->signed_descriptor);
1106 } else if (!strcmp(question, "network-status")) {
1107 routerlist_t *routerlist;
1108 router_get_routerlist(&routerlist);
1109 if (!routerlist || !routerlist->routers ||
1110 list_server_status(routerlist->routers, answer) < 0) {
1111 return -1;
1113 } else if (!strcmp(question, "circuit-status")) {
1114 circuit_t *circ;
1115 smartlist_t *status = smartlist_create();
1116 for (circ = _circuit_get_global_list(); circ; circ = circ->next) {
1117 char *s, *path;
1118 size_t slen;
1119 const char *state;
1120 if (! CIRCUIT_IS_ORIGIN(circ) || circ->marked_for_close)
1121 continue;
1122 path = circuit_list_path(circ,0);
1123 if (circ->state == CIRCUIT_STATE_OPEN)
1124 state = "BUILT";
1125 else if (strlen(path))
1126 state = "EXTENDED";
1127 else
1128 state = "LAUNCHED";
1130 slen = strlen(path)+strlen(state)+20;
1131 s = tor_malloc(slen+1);
1132 tor_snprintf(s, slen, "%lu %s %s", (unsigned long)circ->global_identifier,
1133 state, path);
1134 smartlist_add(status, s);
1135 tor_free(path);
1137 *answer = smartlist_join_strings(status, "\r\n", 1, NULL);
1138 SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
1139 smartlist_free(status);
1140 } else if (!strcmp(question, "stream-status")) {
1141 connection_t **conns;
1142 int n_conns, i;
1143 char buf[256];
1144 smartlist_t *status = smartlist_create();
1145 get_connection_array(&conns, &n_conns);
1146 for (i=0; i < n_conns; ++i) {
1147 const char *state;
1148 char *s;
1149 size_t slen;
1150 circuit_t *circ;
1151 if (conns[i]->type != CONN_TYPE_AP ||
1152 conns[i]->marked_for_close ||
1153 conns[i]->state == AP_CONN_STATE_SOCKS_WAIT)
1154 continue;
1155 switch (conns[i]->state)
1157 case AP_CONN_STATE_CONTROLLER_WAIT:
1158 case AP_CONN_STATE_CIRCUIT_WAIT:
1159 if (conns[i]->socks_request &&
1160 conns[i]->socks_request->command == SOCKS_COMMAND_RESOLVE)
1161 state = "NEWRESOLVE";
1162 else
1163 state = "NEW";
1164 break;
1165 case AP_CONN_STATE_RENDDESC_WAIT:
1166 case AP_CONN_STATE_CONNECT_WAIT:
1167 state = "SENTCONNECT"; break;
1168 case AP_CONN_STATE_RESOLVE_WAIT:
1169 state = "SENTRESOLVE"; break;
1170 case AP_CONN_STATE_OPEN:
1171 state = "SUCCEEDED"; break;
1172 default:
1173 log_fn(LOG_WARN, "Asked for stream in unknown state %d",
1174 conns[i]->state);
1175 continue;
1177 circ = circuit_get_by_edge_conn(conns[i]);
1178 write_stream_target_to_buf(conns[i], buf, sizeof(buf));
1179 slen = strlen(buf)+strlen(state)+32;
1180 s = tor_malloc(slen+1);
1181 tor_snprintf(s, slen, "%lu %s %lu %s",
1182 (unsigned long) conns[i]->global_identifier,state,
1183 circ?(unsigned long)circ->global_identifier : 0ul,
1184 buf);
1185 smartlist_add(status, s);
1187 *answer = smartlist_join_strings(status, "\r\n", 1, NULL);
1188 SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
1189 smartlist_free(status);
1190 } else if (!strcmp(question, "orconn-status")) {
1191 connection_t **conns;
1192 int n_conns, i;
1193 smartlist_t *status = smartlist_create();
1194 get_connection_array(&conns, &n_conns);
1195 for (i=0; i < n_conns; ++i) {
1196 const char *state;
1197 char *s;
1198 size_t slen;
1199 if (conns[i]->type != CONN_TYPE_OR || conns[i]->marked_for_close)
1200 continue;
1201 if (conns[i]->state == OR_CONN_STATE_OPEN)
1202 state = "CONNECTED";
1203 else
1204 state = "LAUNCHED";
1205 slen = strlen(conns[i]->nickname)+strlen(state)+2;
1206 s = tor_malloc(slen+1);
1207 tor_snprintf(s, slen, "%s %s",conns[i]->nickname,state);
1208 smartlist_add(status, s);
1210 *answer = smartlist_join_strings(status, "\r\n", 1, NULL);
1211 SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
1212 smartlist_free(status);
1213 } else if (!strcmpstart(question, "addr-mappings/")) {
1214 time_t min_e, max_e;
1215 smartlist_t *mappings;
1216 if (!strcmp(question, "addr-mappings/all")) {
1217 min_e = 0; max_e = TIME_MAX;
1218 } else if (!strcmp(question, "addr-mappings/cache")) {
1219 min_e = 2; max_e = TIME_MAX;
1220 } else if (!strcmp(question, "addr-mappings/config")) {
1221 min_e = 0; max_e = 0;
1222 } else if (!strcmp(question, "addr-mappings/control")) {
1223 min_e = 1; max_e = 1;
1224 } else {
1225 return 0;
1227 mappings = smartlist_create();
1228 addressmap_get_mappings(mappings, min_e, max_e);
1229 *answer = smartlist_join_strings(mappings, "\n", 1, NULL);
1230 SMARTLIST_FOREACH(mappings, char *, cp, tor_free(cp));
1231 smartlist_free(mappings);
1233 return 0;
1236 /** DOCDOC */
1237 static int
1238 handle_control_getinfo(connection_t *conn, uint32_t len, const char *body)
1240 smartlist_t *questions = NULL;
1241 smartlist_t *answers = NULL;
1242 smartlist_t *unrecognized = NULL;
1243 char *msg = NULL, *ans;
1244 size_t msg_len;
1245 int v0 = STATE_IS_V0(conn->state);
1247 questions = smartlist_create();
1248 if (v0)
1249 smartlist_split_string(questions, body, "\n",
1250 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1251 else
1252 smartlist_split_string(questions, body, " ",
1253 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1254 answers = smartlist_create();
1255 unrecognized = smartlist_create();
1256 SMARTLIST_FOREACH(questions, const char *, q,
1258 if (handle_getinfo_helper(q, &ans) < 0) {
1259 if (v0)
1260 send_control0_error(conn, ERR_INTERNAL, body);
1261 else
1262 connection_write_str_to_buf("551 Internal error\r\n", conn);
1263 goto done;
1265 if (!ans) {
1266 if (v0) {
1267 send_control0_error(conn, ERR_UNRECOGNIZED_CONFIG_KEY, body);
1268 goto done;
1269 } else
1270 smartlist_add(unrecognized, (char*)q);
1271 } else {
1272 smartlist_add(answers, tor_strdup(q));
1273 smartlist_add(answers, ans);
1276 if (smartlist_len(unrecognized)) {
1277 int i;
1278 tor_assert(!v0);
1279 for (i=0; i < smartlist_len(unrecognized)-1; ++i)
1280 connection_printf_to_buf(conn,
1281 "552-Unrecognized key \"%s\"\r\n",
1282 (char*)smartlist_get(unrecognized, i));
1283 connection_printf_to_buf(conn,
1284 "552 Unrecognized key \"%s\"\r\n",
1285 (char*)smartlist_get(unrecognized, i));
1286 goto done;
1289 if (v0) {
1290 msg = smartlist_join_strings2(answers, "\0", 1, 1, &msg_len);
1291 tor_assert(msg_len > 0); /* it will at least be terminated */
1292 send_control0_message(conn, CONTROL0_CMD_INFOVALUE,
1293 msg_len, msg);
1294 } else if (smartlist_len(answers)) {
1295 int i;
1296 for (i = 0; i < smartlist_len(answers); i += 2) {
1297 char *k = smartlist_get(answers, i);
1298 char *v = smartlist_get(answers, i+1);
1299 /*XXXX Not an adequate test! XXXX011 */
1300 if (!strchr(v, '\n') && !strchr(v, '\r')) {
1301 connection_printf_to_buf(conn, "250-%s=", k);
1302 connection_write_str_to_buf(v, conn);
1303 connection_write_str_to_buf("\r\n", conn);
1304 } else {
1305 char *esc = NULL;
1306 size_t len;
1307 len = write_escaped_data(v, strlen(v), 1, &esc);
1308 connection_printf_to_buf(conn, "250+%s=\r\n", k);
1309 connection_write_to_buf(esc, len, conn);
1310 tor_free(esc);
1313 connection_write_str_to_buf("250 OK\r\n", conn);
1316 done:
1317 if (answers) SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
1318 if (questions) SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
1319 smartlist_free(answers);
1320 smartlist_free(questions);
1321 smartlist_free(unrecognized);
1322 tor_free(msg);
1324 return 0;
1327 /** DOCDOC */
1328 static int
1329 handle_control_extendcircuit(connection_t *conn, uint32_t len,
1330 const char *body)
1332 smartlist_t *router_nicknames=NULL, *routers=NULL;
1333 uint32_t circ_id;
1334 circuit_t *circ = NULL;
1335 int zero_circ, v0;
1336 char reply[4];
1338 v0 = STATE_IS_V0(conn->state);
1339 router_nicknames = smartlist_create();
1341 if (v0) {
1342 if (len<5) {
1343 send_control0_error(conn, ERR_SYNTAX, "extendcircuit message too short");
1344 goto done;
1346 smartlist_split_string(router_nicknames, body+4, ",", 0, 0);
1347 circ_id = ntohl(get_uint32(body));
1348 if (!circ_id) {
1349 /* start a new circuit */
1350 zero_circ = 1;
1351 } else {
1352 circ = circuit_get_by_global_id(circ_id);
1353 zero_circ = 0;
1354 if (!circ) {
1355 send_control0_error(conn, ERR_NO_CIRC,
1356 "No circuit found with given ID");
1357 goto done;
1360 } else {
1361 smartlist_t *args;
1362 args = smartlist_create();
1363 smartlist_split_string(args, body, " ",
1364 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1365 if (smartlist_len(args)<2)
1366 connection_printf_to_buf(conn,"512 Missing argument to ATTACHSTREAM\r\n");
1368 smartlist_split_string(router_nicknames, smartlist_get(args,0), ",", 0, 0);
1369 zero_circ = !strcmp("0", (char*)smartlist_get(args,1));
1370 if (!zero_circ && !(circ = get_circ(smartlist_get(args,1)))) {
1371 connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
1372 (char*)smartlist_get(args, 1));
1375 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
1376 smartlist_free(args);
1377 if (!zero_circ && !circ)
1378 return 0;
1381 routers = smartlist_create();
1382 SMARTLIST_FOREACH(router_nicknames, const char *, n,
1384 routerinfo_t *r = router_get_by_nickname(n);
1385 if (!r) {
1386 if (v0)
1387 send_control0_error(conn, ERR_NO_ROUTER, n);
1388 else
1389 connection_printf_to_buf(conn, "552 No such router \"%s\"\r\n", n);
1390 goto done;
1392 smartlist_add(routers, r);
1394 if (!smartlist_len(routers)) {
1395 if (v0)
1396 send_control0_error(conn, ERR_SYNTAX, "No router names provided");
1397 else
1398 connection_write_str_to_buf("512 No router names provided\r\n", conn);
1399 goto done;
1402 /* now circ refers to something that is ready to be extended */
1403 SMARTLIST_FOREACH(routers, routerinfo_t *, r,
1405 circuit_append_new_exit(circ, r);
1408 /* now that we've populated the cpath, start extending */
1409 if (zero_circ) {
1410 if (circuit_handle_first_hop(circ) < 0) {
1411 circuit_mark_for_close(circ);
1412 if (v0)
1413 send_control0_error(conn, ERR_INTERNAL, "couldn't start circuit");
1414 else
1415 connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
1416 goto done;
1418 } else {
1419 if (circ->state == CIRCUIT_STATE_OPEN) {
1420 circ->state = CIRCUIT_STATE_BUILDING;
1421 if (circuit_send_next_onion_skin(circ) < 0) {
1422 log_fn(LOG_INFO,"send_next_onion_skin failed; circuit marked for closing.");
1423 circuit_mark_for_close(circ);
1424 if (v0)
1425 send_control0_error(conn, ERR_INTERNAL, "couldn't send onion skin");
1426 else
1427 connection_write_str_to_buf("551 Couldn't send onion skinr\n", conn);
1428 goto done;
1433 if (v0) {
1434 set_uint32(reply, htonl(circ->global_identifier));
1435 send_control_done2(conn, reply, sizeof(reply));
1436 } else {
1437 connection_printf_to_buf(conn, "250 EXTENDED %lu\r\n",
1438 (unsigned long)circ->global_identifier);
1440 done:
1441 SMARTLIST_FOREACH(router_nicknames, char *, n, tor_free(n));
1442 smartlist_free(router_nicknames);
1443 smartlist_free(routers);
1444 return 0;
1447 /** DOCDOC */
1448 static int
1449 handle_control_attachstream(connection_t *conn, uint32_t len,
1450 const char *body)
1452 connection_t *ap_conn = NULL;
1453 circuit_t *circ = NULL;
1454 int zero_circ;
1456 if (STATE_IS_V0(conn->state)) {
1457 uint32_t conn_id;
1458 uint32_t circ_id;
1459 if (len < 8) {
1460 send_control0_error(conn, ERR_SYNTAX, "attachstream message too short");
1461 return 0;
1464 conn_id = ntohl(get_uint32(body));
1465 circ_id = ntohl(get_uint32(body+4));
1466 zero_circ = circ_id == 0;
1468 if (!(ap_conn = connection_get_by_global_id(conn_id))) {
1469 send_control0_error(conn, ERR_NO_STREAM,
1470 "No connection found with given ID");
1471 return 0;
1473 if (circ_id && !(circ = circuit_get_by_global_id(circ_id))) {
1474 send_control0_error(conn, ERR_NO_CIRC, "No circuit found with given ID");
1475 return 0;
1477 } else {
1478 smartlist_t *args;
1479 args = smartlist_create();
1480 smartlist_split_string(args, body, " ",
1481 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1482 if (smartlist_len(args)<2)
1483 connection_printf_to_buf(conn,"512 Missing argument to ATTACHSTREAM\r\n");
1485 zero_circ = !strcmp("0", (char*)smartlist_get(args,1));
1487 if (!(ap_conn = get_stream(smartlist_get(args, 0)))) {
1488 connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
1489 (char*)smartlist_get(args, 0));
1490 } else if (!zero_circ && !(circ = get_circ(smartlist_get(args, 1)))) {
1491 connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
1492 (char*)smartlist_get(args, 1));
1494 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
1495 smartlist_free(args);
1496 if (!ap_conn || (!zero_circ && !circ))
1497 return 0;
1500 if (ap_conn->state != AP_CONN_STATE_CONTROLLER_WAIT) {
1501 if (STATE_IS_V0(conn->state)) {
1502 send_control0_error(conn, ERR_NO_STREAM,
1503 "Connection is not managed by controller.");
1504 } else {
1505 connection_write_str_to_buf(
1506 "555 Connection is not managed by controller.\r\n",
1507 conn);
1509 return 0;
1512 if (zero_circ) {
1513 ap_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
1514 if (connection_ap_handshake_attach_circuit(ap_conn)<0)
1515 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_CANT_ATTACH);
1516 send_control_done(conn);
1517 return 0;
1519 if (circ->state != CIRCUIT_STATE_OPEN) {
1520 if (STATE_IS_V0(conn->state))
1521 send_control0_error(conn, ERR_INTERNAL, "Refuse to attach stream to non-open circ.");
1522 else
1523 connection_write_str_to_buf(
1524 "551 Can't attach stream to non-open circuit\r\n",
1525 conn);
1526 return 0;
1528 if (connection_ap_handshake_attach_chosen_circuit(ap_conn, circ) != 1) {
1529 if (STATE_IS_V0(conn->state))
1530 send_control0_error(conn, ERR_INTERNAL, "Unable to attach stream.");
1531 else
1532 connection_write_str_to_buf("551 Unable to attach stream\r\n", conn);
1533 return 0;
1535 send_control_done(conn);
1536 return 0;
1539 /** DOCDOC */
1540 static int
1541 handle_control_postdescriptor(connection_t *conn, uint32_t len,
1542 const char *body)
1544 char *desc;
1545 int v0 = STATE_IS_V0(conn->state);
1546 const char *msg=NULL;
1548 if (v0)
1549 desc = (char*)body;
1550 else {
1551 const char *cp = memchr(body, '\n', len);
1552 tor_assert(cp);
1553 read_escaped_data(cp, len-(cp-body), 1, &desc);
1556 switch (router_load_single_router(desc, &msg)) {
1557 case -1:
1558 if (!msg) msg = "Could not parse descriptor";
1559 if (v0)
1560 send_control0_error(conn,ERR_SYNTAX,msg);
1561 else
1562 connection_printf_to_buf(conn, "554 %s\r\n", msg);
1563 break;
1564 case 0:
1565 if (!msg) msg = "Descriptor not added";
1566 if (v0)
1567 send_control_done2(conn,msg,0);
1568 else
1569 connection_printf_to_buf(conn, "251 %s\r\n",msg);
1570 break;
1571 case 1:
1572 send_control_done(conn);
1573 break;
1576 if (!v0)
1577 tor_free(desc);
1578 return 0;
1581 /** DOCDOC */
1582 static int
1583 handle_control_redirectstream(connection_t *conn, uint32_t len,
1584 const char *body)
1586 connection_t *ap_conn = NULL;
1587 uint32_t conn_id;
1588 char *new_addr = NULL;
1589 if (STATE_IS_V0(conn->state)) {
1590 if (len < 6) {
1591 send_control0_error(conn, ERR_SYNTAX, "redirectstream message too short");
1592 return 0;
1594 conn_id = ntohl(get_uint32(body));
1596 if (!(ap_conn = connection_get_by_global_id(conn_id))
1597 || ap_conn->state != CONN_TYPE_AP
1598 || !ap_conn->socks_request) {
1599 send_control0_error(conn, ERR_NO_STREAM,
1600 "No AP connection found with given ID");
1601 return 0;
1603 new_addr = tor_strdup(body+4);
1604 } else {
1605 smartlist_t *args;
1606 args = smartlist_create();
1607 smartlist_split_string(args, body, " ",
1608 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1609 if (smartlist_len(args)<2)
1610 connection_printf_to_buf(conn,"512 Missing argument to REDIRECTSTREAM\r\n");
1611 else if (!(ap_conn = get_stream(smartlist_get(args, 0)))
1612 || !ap_conn->socks_request) {
1613 connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
1614 (char*)smartlist_get(args, 0));
1615 } else {
1616 new_addr = tor_strdup(smartlist_get(args, 1));
1619 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
1620 smartlist_free(args);
1621 if (!new_addr)
1622 return 0;
1625 strlcpy(ap_conn->socks_request->address, new_addr,
1626 sizeof(ap_conn->socks_request->address));
1627 tor_free(new_addr);
1628 send_control_done(conn);
1629 return 0;
1632 /** DOCDOC */
1633 static int
1634 handle_control_closestream(connection_t *conn, uint32_t len,
1635 const char *body)
1637 connection_t *ap_conn=NULL;
1638 uint8_t reason=0;
1640 if (STATE_IS_V0(conn->state)) {
1641 uint32_t conn_id;
1642 if (len < 6) {
1643 send_control0_error(conn, ERR_SYNTAX, "closestream message too short");
1644 return 0;
1647 conn_id = ntohl(get_uint32(body));
1648 reason = *(uint8_t*)(body+4);
1650 if (!(ap_conn = connection_get_by_global_id(conn_id))
1651 || ap_conn->state != CONN_TYPE_AP
1652 || !ap_conn->socks_request) {
1653 send_control0_error(conn, ERR_NO_STREAM,
1654 "No AP connection found with given ID");
1655 return 0;
1657 } else {
1658 smartlist_t *args;
1659 int ok;
1660 args = smartlist_create();
1661 smartlist_split_string(args, body, " ",
1662 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1663 if (smartlist_len(args)<2)
1664 connection_printf_to_buf(conn, "512 Missing argument to CLOSECIRCUIT\r\n");
1665 else if (!(ap_conn = get_stream(smartlist_get(args, 0))))
1666 connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
1667 (char*)smartlist_get(args, 0));
1668 else {
1669 reason = (uint8_t) tor_parse_ulong(smartlist_get(args,1), 10, 0, 255,
1670 &ok, NULL);
1671 if (!ok) {
1672 connection_printf_to_buf(conn, "552 Unrecognized reason \"%s\"\r\n",
1673 (char*)smartlist_get(args, 1));
1674 ap_conn = NULL;
1677 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
1678 smartlist_free(args);
1679 if (!ap_conn)
1680 return 0;
1683 connection_mark_unattached_ap(ap_conn, reason);
1684 send_control_done(conn);
1685 return 0;
1688 /** DOCDOC */
1689 static int
1690 handle_control_closecircuit(connection_t *conn, uint32_t len,
1691 const char *body)
1693 circuit_t *circ = NULL;
1694 int safe = 0;
1696 if (STATE_IS_V0(conn->state)) {
1697 uint32_t circ_id;
1698 if (len < 5) {
1699 send_control0_error(conn, ERR_SYNTAX, "closecircuit message too short");
1700 return 0;
1702 circ_id = ntohl(get_uint32(body));
1703 safe = (*(uint8_t*)(body+4)) & 1;
1705 if (!(circ = circuit_get_by_global_id(circ_id))) {
1706 send_control0_error(conn, ERR_NO_CIRC,
1707 "No circuit found with given ID");
1708 return 0;
1710 } else {
1711 smartlist_t *args;
1712 args = smartlist_create();
1713 smartlist_split_string(args, body, " ",
1714 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1715 if (smartlist_len(args)<1)
1716 connection_printf_to_buf(conn, "512 Missing argument to CLOSECIRCUIT\r\n");
1717 else if (!(circ=get_circ(smartlist_get(args, 0))))
1718 connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
1719 (char*)smartlist_get(args, 0));
1720 else {
1721 int i;
1722 for (i=1; i < smartlist_len(args); ++i) {
1723 if (!strcasecmp(smartlist_get(args, i), "IfUnused"))
1724 safe = 1;
1725 else
1726 log_fn(LOG_INFO, "Skipping unknown option %s",
1727 (char*)smartlist_get(args,i));
1730 SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
1731 smartlist_free(args);
1732 if (!circ)
1733 return 0;
1736 if (!safe || !circ->p_streams) {
1737 circuit_mark_for_close(circ);
1740 send_control_done(conn);
1741 return 0;
1744 /** DOCDOC */
1745 static int
1746 handle_control_fragments(connection_t *conn, uint16_t command_type,
1747 uint32_t body_len, char *body)
1749 if (command_type == CONTROL0_CMD_FRAGMENTHEADER) {
1750 if (conn->incoming_cmd) {
1751 log_fn(LOG_WARN, "Dropping incomplete fragmented command");
1752 tor_free(conn->incoming_cmd);
1754 if (body_len < 6) {
1755 send_control0_error(conn, ERR_SYNTAX, "FRAGMENTHEADER too short.");
1756 return 0;
1758 conn->incoming_cmd_type = ntohs(get_uint16(body));
1759 conn->incoming_cmd_len = ntohl(get_uint32(body+2));
1760 conn->incoming_cmd_cur_len = 0;
1761 conn->incoming_cmd = tor_malloc(conn->incoming_cmd_len);
1762 body += 6;
1763 body_len -= 6;
1764 } else if (command_type == CONTROL0_CMD_FRAGMENT) {
1765 if (!conn->incoming_cmd) {
1766 send_control0_error(conn, ERR_SYNTAX, "Out-of-place FRAGMENT");
1767 return 0;
1769 } else {
1770 tor_assert(0);
1773 if (conn->incoming_cmd_cur_len + body_len > conn->incoming_cmd_len) {
1774 tor_free(conn->incoming_cmd);
1775 send_control0_error(conn, ERR_SYNTAX,
1776 "Fragmented data exceeds declared length");
1777 return 0;
1779 memcpy(conn->incoming_cmd + conn->incoming_cmd_cur_len,
1780 body, body_len);
1781 conn->incoming_cmd_cur_len += body_len;
1782 return 0;
1785 /** Called when <b>conn</b> has no more bytes left on its outbuf. */
1787 connection_control_finished_flushing(connection_t *conn)
1789 tor_assert(conn);
1790 tor_assert(conn->type == CONN_TYPE_CONTROL);
1792 connection_stop_writing(conn);
1793 return 0;
1796 /** Called when <b>conn</b> has gotten its socket closed. */
1798 connection_control_reached_eof(connection_t *conn)
1800 tor_assert(conn);
1801 tor_assert(conn->type == CONN_TYPE_CONTROL);
1803 log_fn(LOG_INFO,"Control connection reached EOF. Closing.");
1804 connection_mark_for_close(conn);
1805 return 0;
1808 /* DOCDOC */
1809 static int
1810 connection_control_process_inbuf_v1(connection_t *conn)
1812 size_t data_len, cmd_len;
1813 char *args;
1815 tor_assert(conn);
1816 tor_assert(conn->type == CONN_TYPE_CONTROL);
1817 tor_assert(conn->state == CONTROL_CONN_STATE_OPEN_V1 ||
1818 conn->state == CONTROL_CONN_STATE_NEEDAUTH_V1);
1820 if (!conn->incoming_cmd) {
1821 conn->incoming_cmd = tor_malloc(1024);
1822 conn->incoming_cmd_len = 1024;
1823 conn->incoming_cmd_cur_len = 0;
1826 again:
1827 while (1) {
1828 size_t last_idx;
1829 int r;
1830 do {
1831 data_len = conn->incoming_cmd_len - conn->incoming_cmd_cur_len;
1832 r = fetch_from_buf_line(conn->inbuf,
1833 conn->incoming_cmd+conn->incoming_cmd_cur_len,
1834 &data_len);
1835 if (r == 0)
1836 /* Line not all here yet. Wait. */
1837 return 0;
1838 else if (r == -1) {
1839 while (conn->incoming_cmd_len < data_len+conn->incoming_cmd_cur_len)
1840 conn->incoming_cmd_len *= 2;
1841 conn->incoming_cmd = tor_realloc(conn->incoming_cmd, conn->incoming_cmd_len);
1843 } while (r != 1);
1845 tor_assert(data_len);
1847 last_idx = conn->incoming_cmd_cur_len;
1848 conn->incoming_cmd_cur_len += data_len;
1850 /* We have appended a line to incoming_cmd. Is the command done? */
1851 if (last_idx == 0 && *conn->incoming_cmd != '+')
1852 /* One line command, didn't start with '+'. */
1853 break;
1854 if (last_idx+3 == conn->incoming_cmd_cur_len &&
1855 !memcmp(conn->incoming_cmd + last_idx, ".\r\n", 3))
1856 /* Just appended ".\r\n"; we're done. */
1857 break;
1858 /* Otherwise, read another line. */
1860 data_len = conn->incoming_cmd_cur_len;
1861 /* Okay, we now have a command sitting on conn->incoming_cmd. See if we
1862 * recognize it.
1864 cmd_len = 0;
1865 while (cmd_len < data_len && !isspace(conn->incoming_cmd[cmd_len]))
1866 ++cmd_len;
1869 log_fn(LOG_NOTICE, "READ A COMMAND FROM THE BUFFER: <%s> [%d]",
1870 conn->incoming_cmd, (int)cmd_len);
1872 data_len -= cmd_len;
1873 conn->incoming_cmd[cmd_len]='\0';
1874 args = conn->incoming_cmd+cmd_len+1;
1875 while (*args == ' ' || *args == '\t') {
1876 ++args;
1877 --data_len;
1880 log_fn(LOG_NOTICE, "COMMAND IS: <%s>", conn->incoming_cmd);
1881 log_fn(LOG_NOTICE, "ARGS ARE: <%s>", args);
1884 if (conn->state == CONTROL_CONN_STATE_NEEDAUTH_V1 &&
1885 strcasecmp(conn->incoming_cmd, "AUTHENTICATE")) {
1886 connection_write_str_to_buf("514 Authentication required.\r\n", conn);
1887 conn->incoming_cmd_cur_len = 0;
1888 goto again;
1891 if (!strcasecmp(conn->incoming_cmd, "SETCONF")) {
1892 if (handle_control_setconf(conn, data_len, args))
1893 return -1;
1894 } else if (!strcasecmp(conn->incoming_cmd, "GETCONF")) {
1895 if (handle_control_getconf(conn, data_len, args))
1896 return -1;
1897 } else if (!strcasecmp(conn->incoming_cmd, "SETEVENTS")) {
1898 if (handle_control_setevents(conn, data_len, args))
1899 return -1;
1900 } else if (!strcasecmp(conn->incoming_cmd, "AUTHENTICATE")) {
1901 if (handle_control_authenticate(conn, data_len, args))
1902 return -1;
1903 } else if (!strcasecmp(conn->incoming_cmd, "SAVECONF")) {
1904 if (handle_control_saveconf(conn, data_len, args))
1905 return -1;
1906 } else if (!strcasecmp(conn->incoming_cmd, "SIGNAL")) {
1907 if (handle_control_signal(conn, data_len, args))
1908 return -1;
1909 } else if (!strcasecmp(conn->incoming_cmd, "MAPADDRESS")) {
1910 if (handle_control_mapaddress(conn, data_len, args))
1911 return -1;
1912 } else if (!strcasecmp(conn->incoming_cmd, "GETINFO")) {
1913 if (handle_control_getinfo(conn, data_len, args))
1914 return -1;
1915 } else if (!strcasecmp(conn->incoming_cmd, "EXTENDCIRCUIT")) {
1916 if (handle_control_extendcircuit(conn, data_len, args))
1917 return -1;
1918 } else if (!strcasecmp(conn->incoming_cmd, "ATTACHSTREAM")) {
1919 if (handle_control_attachstream(conn, data_len, args))
1920 return -1;
1921 } else if (!strcasecmp(conn->incoming_cmd, "+POSTDESCRIPTOR")) {
1922 if (handle_control_postdescriptor(conn, data_len, args))
1923 return -1;
1924 } else if (!strcasecmp(conn->incoming_cmd, "REDIRECTSTREAM")) {
1925 if (handle_control_redirectstream(conn, data_len, args))
1926 return -1;
1927 } else if (!strcasecmp(conn->incoming_cmd, "CLOSESTREAM")) {
1928 if (handle_control_closestream(conn, data_len, args))
1929 return -1;
1930 } else if (!strcasecmp(conn->incoming_cmd, "CLOSECIRCUIT")) {
1931 if (handle_control_closecircuit(conn, data_len, args))
1932 return -1;
1933 } else {
1934 connection_printf_to_buf(conn, "510 Unrecognized command \"%s\"\r\n",
1935 conn->incoming_cmd);
1938 conn->incoming_cmd_cur_len = 0;
1939 goto again;
1942 /* DOCDOC */
1943 static int
1944 connection_control_process_inbuf_v0(connection_t *conn)
1946 uint32_t body_len;
1947 uint16_t command_type;
1948 char *body;
1950 again:
1951 /* Try to suck a control message from the buffer. */
1952 switch (fetch_from_buf_control0(conn->inbuf, &body_len, &command_type, &body,
1953 conn->state == CONTROL_CONN_STATE_NEEDAUTH_V0))
1955 case -2:
1956 tor_free(body);
1957 log_fn(LOG_INFO, "Detected v1 contol protocol on connection (fd %d)",
1958 conn->s);
1959 conn->state = CONTROL_CONN_STATE_NEEDAUTH_V1;
1960 return connection_control_process_inbuf_v1(conn);
1961 case -1:
1962 tor_free(body);
1963 log_fn(LOG_WARN, "Error in control command. Failing.");
1964 return -1;
1965 case 0:
1966 /* Control command not all here yet. Wait. */
1967 return 0;
1968 case 1:
1969 /* We got a command. Process it. */
1970 break;
1971 default:
1972 tor_assert(0);
1975 /* We got a command. If we need authentication, only authentication
1976 * commands will be considered. */
1977 if (conn->state == CONTROL_CONN_STATE_NEEDAUTH_V0 &&
1978 command_type != CONTROL0_CMD_AUTHENTICATE) {
1979 log_fn(LOG_WARN, "Rejecting '%s' command; authentication needed.",
1980 control_cmd_to_string(command_type));
1981 send_control0_error(conn, ERR_UNAUTHORIZED, "Authentication required");
1982 tor_free(body);
1983 goto again;
1986 if (command_type == CONTROL0_CMD_FRAGMENTHEADER ||
1987 command_type == CONTROL0_CMD_FRAGMENT) {
1988 if (handle_control_fragments(conn, command_type, body_len, body))
1989 return -1;
1990 tor_free(body);
1991 if (conn->incoming_cmd_cur_len != conn->incoming_cmd_len)
1992 goto again;
1994 command_type = conn->incoming_cmd_type;
1995 body_len = conn->incoming_cmd_len;
1996 body = conn->incoming_cmd;
1997 conn->incoming_cmd = NULL;
1998 } else if (conn->incoming_cmd) {
1999 log_fn(LOG_WARN, "Dropping incomplete fragmented command");
2000 tor_free(conn->incoming_cmd);
2003 /* Okay, we're willing to process the command. */
2004 switch (command_type)
2006 case CONTROL0_CMD_SETCONF:
2007 if (handle_control_setconf(conn, body_len, body))
2008 return -1;
2009 break;
2010 case CONTROL0_CMD_GETCONF:
2011 if (handle_control_getconf(conn, body_len, body))
2012 return -1;
2013 break;
2014 case CONTROL0_CMD_SETEVENTS:
2015 if (handle_control_setevents(conn, body_len, body))
2016 return -1;
2017 break;
2018 case CONTROL0_CMD_AUTHENTICATE:
2019 if (handle_control_authenticate(conn, body_len, body))
2020 return -1;
2021 break;
2022 case CONTROL0_CMD_SAVECONF:
2023 if (handle_control_saveconf(conn, body_len, body))
2024 return -1;
2025 break;
2026 case CONTROL0_CMD_SIGNAL:
2027 if (handle_control_signal(conn, body_len, body))
2028 return -1;
2029 break;
2030 case CONTROL0_CMD_MAPADDRESS:
2031 if (handle_control_mapaddress(conn, body_len, body))
2032 return -1;
2033 break;
2034 case CONTROL0_CMD_GETINFO:
2035 if (handle_control_getinfo(conn, body_len, body))
2036 return -1;
2037 break;
2038 case CONTROL0_CMD_EXTENDCIRCUIT:
2039 if (handle_control_extendcircuit(conn, body_len, body))
2040 return -1;
2041 break;
2042 case CONTROL0_CMD_ATTACHSTREAM:
2043 if (handle_control_attachstream(conn, body_len, body))
2044 return -1;
2045 break;
2046 case CONTROL0_CMD_POSTDESCRIPTOR:
2047 if (handle_control_postdescriptor(conn, body_len, body))
2048 return -1;
2049 break;
2050 case CONTROL0_CMD_REDIRECTSTREAM:
2051 if (handle_control_redirectstream(conn, body_len, body))
2052 return -1;
2053 break;
2054 case CONTROL0_CMD_CLOSESTREAM:
2055 if (handle_control_closestream(conn, body_len, body))
2056 return -1;
2057 break;
2058 case CONTROL0_CMD_CLOSECIRCUIT:
2059 if (handle_control_closecircuit(conn, body_len, body))
2060 return -1;
2061 break;
2062 case CONTROL0_CMD_ERROR:
2063 case CONTROL0_CMD_DONE:
2064 case CONTROL0_CMD_CONFVALUE:
2065 case CONTROL0_CMD_EVENT:
2066 case CONTROL0_CMD_INFOVALUE:
2067 log_fn(LOG_WARN, "Received client-only '%s' command; ignoring.",
2068 control_cmd_to_string(command_type));
2069 send_control0_error(conn, ERR_UNRECOGNIZED_TYPE,
2070 "Command type only valid from server to tor client");
2071 break;
2072 case CONTROL0_CMD_FRAGMENTHEADER:
2073 case CONTROL0_CMD_FRAGMENT:
2074 log_fn(LOG_WARN, "Recieved command fragment out of order; ignoring.");
2075 send_control0_error(conn, ERR_SYNTAX, "Bad fragmentation on command.");
2076 default:
2077 log_fn(LOG_WARN, "Received unrecognized command type %d; ignoring.",
2078 (int)command_type);
2079 send_control0_error(conn, ERR_UNRECOGNIZED_TYPE,
2080 "Unrecognized command type");
2081 break;
2083 tor_free(body);
2084 goto again; /* There might be more data. */
2087 /** Called when <b>conn</b> has received more bytes on its inbuf.
2090 connection_control_process_inbuf(connection_t *conn)
2092 tor_assert(conn);
2093 tor_assert(conn->type == CONN_TYPE_CONTROL);
2095 if (STATE_IS_V0(conn->state))
2096 return connection_control_process_inbuf_v0(conn);
2097 else
2098 return connection_control_process_inbuf_v1(conn);
2101 /** Something has happened to circuit <b>circ</b>: tell any interested
2102 * control connections. */
2104 control_event_circuit_status(circuit_t *circ, circuit_status_event_t tp)
2106 char *path, *msg;
2107 if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS))
2108 return 0;
2109 tor_assert(circ);
2110 tor_assert(CIRCUIT_IS_ORIGIN(circ));
2112 path = circuit_list_path(circ,0);
2113 if (EVENT_IS_INTERESTING0(EVENT_CIRCUIT_STATUS)) {
2114 size_t path_len = strlen(path);
2115 msg = tor_malloc(1+4+path_len+1); /* event, circid, path, NUL. */
2116 msg[0] = (uint8_t) tp;
2117 set_uint32(msg+1, htonl(circ->global_identifier));
2118 strlcpy(msg+5,path,path_len+1);
2120 send_control0_event(EVENT_CIRCUIT_STATUS, (uint32_t)(path_len+6), msg);
2121 tor_free(msg);
2123 if (EVENT_IS_INTERESTING1(EVENT_CIRCUIT_STATUS)) {
2124 const char *status;
2125 switch (tp)
2127 case CIRC_EVENT_LAUNCHED: status = "LAUNCHED"; break;
2128 case CIRC_EVENT_BUILT: status = "BUILT"; break;
2129 case CIRC_EVENT_EXTENDED: status = "EXTENDED"; break;
2130 case CIRC_EVENT_FAILED: status = "FAILED"; break;
2131 case CIRC_EVENT_CLOSED: status = "CLOSED"; break;
2132 default:
2133 log_fn(LOG_WARN, "Unrecognized status code %d", (int)tp);
2134 return 0;
2136 send_control1_event(EVENT_CIRCUIT_STATUS,
2137 "650 CIRC %lu %s %s\r\n",
2138 (unsigned long)circ->global_identifier,
2139 status, path);
2141 tor_free(path);
2143 return 0;
2146 /** DOCDOC */
2147 static int
2148 write_stream_target_to_buf(connection_t *conn, char *buf, size_t len)
2150 char buf2[256];
2151 if (conn->chosen_exit_name)
2152 if (tor_snprintf(buf2, sizeof(buf2), ".%s.exit", conn->chosen_exit_name)<0)
2153 return -1;
2154 if (tor_snprintf(buf, len, "%s%s:%d",
2155 conn->socks_request->address,
2156 conn->chosen_exit_name ? buf2 : "",
2157 conn->socks_request->port)<0)
2158 return -1;
2159 return 0;
2162 /** Something has happened to the stream associated with AP connection
2163 * <b>conn</b>: tell any interested control connections. */
2165 control_event_stream_status(connection_t *conn, stream_status_event_t tp)
2167 char *msg;
2168 size_t len;
2169 char buf[256];
2170 tor_assert(conn->type == CONN_TYPE_AP);
2171 tor_assert(conn->socks_request);
2173 if (!EVENT_IS_INTERESTING(EVENT_STREAM_STATUS))
2174 return 0;
2176 write_stream_target_to_buf(conn, buf, sizeof(buf));
2177 if (EVENT_IS_INTERESTING0(EVENT_STREAM_STATUS)) {
2178 len = strlen(buf);
2179 msg = tor_malloc(5+len+1);
2180 msg[0] = (uint8_t) tp;
2181 set_uint32(msg+1, htonl(conn->global_identifier));
2182 strlcpy(msg+5, buf, len+1);
2184 send_control0_event(EVENT_STREAM_STATUS, (uint32_t)(5+len+1), msg);
2185 tor_free(msg);
2187 if (EVENT_IS_INTERESTING0(EVENT_STREAM_STATUS)) {
2188 const char *status;
2189 circuit_t *circ;
2190 switch (tp)
2192 case STREAM_EVENT_SENT_CONNECT: status = "SENTCONNECT"; break;
2193 case STREAM_EVENT_SENT_RESOLVE: status = "SENTRESOLVE"; break;
2194 case STREAM_EVENT_SUCCEEDED: status = "SUCCEEDED"; break;
2195 case STREAM_EVENT_FAILED: status = "FAILED"; break;
2196 case STREAM_EVENT_CLOSED: status = "CLOSED"; break;
2197 case STREAM_EVENT_NEW: status = "NEW"; break;
2198 case STREAM_EVENT_NEW_RESOLVE: status = "NEWRESOLVE"; break;
2199 case STREAM_EVENT_FAILED_RETRIABLE: status = "DETACHED"; break;
2200 default:
2201 log_fn(LOG_WARN, "Unrecognized status code %d", (int)tp);
2202 return 0;
2204 circ = circuit_get_by_edge_conn(conn);
2205 send_control1_event(EVENT_STREAM_STATUS,
2206 "650 STREAM %lu %s %lu %s\r\n",
2207 (unsigned long)conn->global_identifier, status,
2208 circ?(unsigned long)circ->global_identifier : 0ul,
2209 buf);
2211 return 0;
2214 /** Something has happened to the OR connection <b>conn</b>: tell any
2215 * interested control connections. */
2217 control_event_or_conn_status(connection_t *conn,or_conn_status_event_t tp)
2219 char buf[HEX_DIGEST_LEN+3]; /* status, dollar, identity, NUL */
2220 size_t len;
2222 tor_assert(conn->type == CONN_TYPE_OR);
2224 if (!EVENT_IS_INTERESTING(EVENT_OR_CONN_STATUS))
2225 return 0;
2227 if (EVENT_IS_INTERESTING0(EVENT_OR_CONN_STATUS)) {
2228 buf[0] = (uint8_t)tp;
2229 strlcpy(buf+1,conn->nickname,sizeof(buf)-1);
2230 len = strlen(buf+1);
2231 send_control0_event(EVENT_OR_CONN_STATUS, (uint32_t)(len+1), buf);
2233 if (EVENT_IS_INTERESTING1(EVENT_OR_CONN_STATUS)) {
2234 const char *status;
2235 switch (tp)
2237 case OR_CONN_EVENT_LAUNCHED: status = "LAUNCHED"; break;
2238 case OR_CONN_EVENT_CONNECTED: status = "CONNECTED"; break;
2239 case OR_CONN_EVENT_FAILED: status = "FAILED"; break;
2240 case OR_CONN_EVENT_CLOSED: status = "CLOSED"; break;
2241 default:
2242 log_fn(LOG_WARN, "Unrecognized status code %d", (int)tp);
2243 return 0;
2245 send_control1_event(EVENT_OR_CONN_STATUS,
2246 "650 ORCONN %s %s\r\n",
2247 conn->nickname, status);
2249 return 0;
2252 /** A second or more has elapsed: tell any interested control
2253 * connections how much bandwidth we used. */
2255 control_event_bandwidth_used(uint32_t n_read, uint32_t n_written)
2257 char buf[8];
2259 if (EVENT_IS_INTERESTING0(EVENT_BANDWIDTH_USED)) {
2260 set_uint32(buf, htonl(n_read));
2261 set_uint32(buf+4, htonl(n_written));
2262 send_control0_event(EVENT_BANDWIDTH_USED, 8, buf);
2264 if (EVENT_IS_INTERESTING1(EVENT_BANDWIDTH_USED)) {
2265 send_control1_event(EVENT_BANDWIDTH_USED,
2266 "650 BW %lu %lu\r\n",
2267 (unsigned long)n_read,
2268 (unsigned long)n_written);
2271 return 0;
2274 /** We got a log message: tell any interested control connections. */
2275 void
2276 control_event_logmsg(int severity, const char *msg)
2278 static int sending_logmsg=0;
2279 int oldlog, event;
2281 if (sending_logmsg)
2282 return;
2284 oldlog = EVENT_IS_INTERESTING0(EVENT_LOG_OBSOLETE) &&
2285 (severity == LOG_NOTICE || severity == LOG_WARN || severity == LOG_ERR);
2286 event = log_severity_to_event(severity);
2288 if (event<0 || !EVENT_IS_INTERESTING0(event))
2289 event = 0;
2291 if (oldlog || event) {
2292 size_t len = strlen(msg);
2293 sending_logmsg = 1;
2294 if (event)
2295 send_control0_event(event, (uint32_t)(len+1), msg);
2296 if (oldlog)
2297 send_control0_event(EVENT_LOG_OBSOLETE, (uint32_t)(len+1), msg);
2298 sending_logmsg = 0;
2301 event = log_severity_to_event(severity);
2302 if (event >= 0 && EVENT_IS_INTERESTING1(event)) {
2303 char *b = NULL;
2304 const char *s;
2305 if (strchr(msg, '\n')) {
2306 char *cp;
2307 b = tor_strdup(msg);
2308 for (cp = b; *cp; ++cp)
2309 if (*cp == '\r' || *cp == '\n')
2310 *cp = ' ';
2312 switch (severity) {
2313 case LOG_INFO: s = "INFO"; break;
2314 case LOG_NOTICE: s = "NOTICE"; break;
2315 case LOG_WARN: s = "WARN"; break;
2316 case LOG_ERR: s = "ERR"; break;
2317 default: s = "UnknownLogSeverity"; break;
2319 send_control1_event(event, "650 %s %s\r\n", s, b?b:msg);
2320 tor_free(b);
2324 /** Called whenever we receive new router descriptors: tell any
2325 * interested control connections. <b>routers</b> is a list of
2326 * DIGEST_LEN-byte identity digests.
2329 control_event_descriptors_changed(smartlist_t *routers)
2331 size_t len;
2332 char *msg;
2333 smartlist_t *identities;
2334 char buf[HEX_DIGEST_LEN+1];
2336 if (!EVENT_IS_INTERESTING(EVENT_NEW_DESC))
2337 return 0;
2338 identities = smartlist_create();
2339 SMARTLIST_FOREACH(routers, routerinfo_t *, r,
2341 base16_encode(buf,sizeof(buf),r->identity_digest,DIGEST_LEN);
2342 smartlist_add(identities, tor_strdup(buf));
2344 if (EVENT_IS_INTERESTING0(EVENT_NEW_DESC)) {
2345 msg = smartlist_join_strings(identities, ",", 0, &len);
2346 send_control0_event(EVENT_NEW_DESC, len+1, msg);
2347 tor_free(msg);
2349 if (EVENT_IS_INTERESTING1(EVENT_NEW_DESC)) {
2350 msg = smartlist_join_strings(identities, " ", 0, &len);
2351 send_control1_event(EVENT_NEW_DESC, "650 NEWDESC %s\r\n", msg);
2352 tor_free(msg);
2354 SMARTLIST_FOREACH(identities, char *, cp, tor_free(cp));
2355 smartlist_free(identities);
2357 return 0;
2360 /** DOCDOC */
2362 control_event_address_mapped(const char *from, const char *to, time_t expires)
2364 if (!EVENT_IS_INTERESTING1(EVENT_ADDRMAP))
2365 return 0;
2367 if (expires < 3)
2368 send_control1_event(EVENT_ADDRMAP, "650 ADDRMAP %s %s NEVER\r\n", from, to);
2369 else {
2370 char buf[ISO_TIME_LEN+1];
2371 format_local_iso_time(buf,expires);
2372 send_control1_event(EVENT_ADDRMAP, "650 ADDRMAP %s %s \"%s\"\r\n",
2373 from, to, buf);
2376 return 0;
2379 /** Choose a random authentication cookie and write it to disk.
2380 * Anybody who can read the cookie from disk will be considered
2381 * authorized to use the control connection. */
2383 init_cookie_authentication(int enabled)
2385 char fname[512];
2387 if (!enabled) {
2388 authentication_cookie_is_set = 0;
2389 return 0;
2392 tor_snprintf(fname, sizeof(fname), "%s/control_auth_cookie",
2393 get_options()->DataDirectory);
2394 crypto_rand(authentication_cookie, AUTHENTICATION_COOKIE_LEN);
2395 authentication_cookie_is_set = 1;
2396 if (write_bytes_to_file(fname, authentication_cookie,
2397 AUTHENTICATION_COOKIE_LEN, 1)) {
2398 log_fn(LOG_WARN,"Error writing authentication cookie.");
2399 return -1;
2402 return 0;