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