Revise control spec and implementation to allow all log messages to be sent to contro...
[tor.git] / src / or / control.c
blob514ff0c6bd4e340c1d58a7e745e63b0981e50fed
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
9 * \brief Implementation for Tor's control-socket interface.
12 #include "or.h"
14 /* Protocol outline: a bidirectional stream, over which each side
15 * sends a series of messages. Each message has a two-byte length field,
16 * a two-byte typecode, and a variable-length body whose length is
17 * given in the length field.
19 * By default, the server only sends messages in response to client messages.
20 * Every client message gets a message in response. The client may, however,
21 * _request_ that other messages be delivered asynchronously.
24 * Every message type is either client-only or server-only, and every
25 * server message type is either synchronous-only (only occurs in
26 * response to a client request) or asynchronous-only (never is an
27 * answer to a client request.
29 * See control-spec.txt for full details.
32 /* Recognized message type codes. */
33 #define CONTROL_CMD_ERROR 0x0000
34 #define CONTROL_CMD_DONE 0x0001
35 #define CONTROL_CMD_SETCONF 0x0002
36 #define CONTROL_CMD_GETCONF 0x0003
37 #define CONTROL_CMD_CONFVALUE 0x0004
38 #define CONTROL_CMD_SETEVENTS 0x0005
39 #define CONTROL_CMD_EVENT 0x0006
40 #define CONTROL_CMD_AUTHENTICATE 0x0007
41 #define CONTROL_CMD_SAVECONF 0x0008
42 #define CONTROL_CMD_SIGNAL 0x0009
43 #define CONTROL_CMD_MAPADDRESS 0x000A
44 #define CONTROL_CMD_GETINFO 0x000B
45 #define CONTROL_CMD_INFOVALUE 0x000C
46 #define CONTROL_CMD_EXTENDCIRCUIT 0x000D
47 #define CONTROL_CMD_ATTACHSTREAM 0x000E
48 #define CONTROL_CMD_POSTDESCRIPTOR 0x000F
49 #define CONTROL_CMD_FRAGMENTHEADER 0x0010
50 #define CONTROL_CMD_FRAGMENT 0x0011
51 #define CONTROL_CMD_REDIRECTSTREAM 0x0012
52 #define CONTROL_CMD_CLOSESTREAM 0x0013
53 #define CONTROL_CMD_CLOSECIRCUIT 0x0014
54 #define _CONTROL_CMD_MAX_RECOGNIZED 0x0014
56 /* Recognized error codes. */
57 #define ERR_UNSPECIFIED 0x0000
58 #define ERR_INTERNAL 0x0001
59 #define ERR_UNRECOGNIZED_TYPE 0x0002
60 #define ERR_SYNTAX 0x0003
61 #define ERR_UNRECOGNIZED_CONFIG_KEY 0x0004
62 #define ERR_INVALID_CONFIG_VALUE 0x0005
63 #define ERR_UNRECOGNIZED_EVENT_CODE 0x0006
64 #define ERR_UNAUTHORIZED 0x0007
65 #define ERR_REJECTED_AUTHENTICATION 0x0008
66 #define ERR_RESOURCE_EXHAUSETED 0x0009
67 #define ERR_NO_STREAM 0x000A
68 #define ERR_NO_CIRC 0x000B
69 #define ERR_NO_ROUTER 0x000C
71 /* Recognized asynchronous event types. */
72 #define _EVENT_MIN 0x0001
73 #define EVENT_CIRCUIT_STATUS 0x0001
74 #define EVENT_STREAM_STATUS 0x0002
75 #define EVENT_OR_CONN_STATUS 0x0003
76 #define EVENT_BANDWIDTH_USED 0x0004
77 #define EVENT_LOG_OBSOLETE 0x0005
78 #define EVENT_NEW_DESC 0x0006
79 #define EVENT_DEBUG_MSG 0x0007
80 #define EVENT_INFO_MSG 0x0008
81 #define EVENT_NOTICE_MSG 0x0009
82 #define EVENT_WARN_MSG 0x000A
83 #define EVENT_ERR_MSG 0x000B
84 #define _EVENT_MAX 0x000B
86 /** Array mapping from message type codes to human-readable message
87 * type names. */
88 static const char * CONTROL_COMMANDS[_CONTROL_CMD_MAX_RECOGNIZED+1] = {
89 "error",
90 "done",
91 "setconf",
92 "getconf",
93 "confvalue",
94 "setevents",
95 "events",
96 "authenticate",
97 "saveconf",
98 "signal",
99 "mapaddress",
100 "getinfo",
101 "infovalue",
102 "extendcircuit",
103 "attachstream",
104 "postdescriptor",
105 "fragmentheader",
106 "fragment",
109 /** Bitfield: The bit 1&lt;&lt;e is set if <b>any</b> open control
110 * connection is interested in events of type <b>e</b>. We use this
111 * so that we can decide to skip generating event messages that nobody
112 * has interest in without having to walk over the global connection
113 * list to find out.
115 static uint32_t global_event_mask = 0;
117 /** Macro: true if any control connection is interested in events of type
118 * <b>e</b>. */
119 #define EVENT_IS_INTERESTING(e) (global_event_mask & (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 update_global_event_mask(void);
131 static void send_control_message(connection_t *conn, uint16_t type,
132 uint32_t len, const char *body);
133 static void send_control_done(connection_t *conn);
134 static void send_control_done2(connection_t *conn, const char *msg, size_t len);
135 static void send_control_error(connection_t *conn, uint16_t error,
136 const char *message);
137 static void send_control_event(uint16_t event, uint32_t len, const char *body);
138 static int handle_control_setconf(connection_t *conn, uint32_t len,
139 char *body);
140 static int handle_control_getconf(connection_t *conn, uint32_t len,
141 const char *body);
142 static int handle_control_setevents(connection_t *conn, uint32_t len,
143 const char *body);
144 static int handle_control_authenticate(connection_t *conn, uint32_t len,
145 const char *body);
146 static int handle_control_saveconf(connection_t *conn, uint32_t len,
147 const char *body);
148 static int handle_control_signal(connection_t *conn, uint32_t len,
149 const char *body);
150 static int handle_control_mapaddress(connection_t *conn, uint32_t len,
151 const char *body);
152 static int handle_control_getinfo(connection_t *conn, uint32_t len,
153 const char *body);
154 static int handle_control_extendcircuit(connection_t *conn, uint32_t len,
155 const char *body);
156 static int handle_control_attachstream(connection_t *conn, uint32_t len,
157 const char *body);
158 static int handle_control_postdescriptor(connection_t *conn, uint32_t len,
159 const char *body);
160 static int handle_control_redirectstream(connection_t *conn, uint32_t len,
161 const char *body);
162 static int handle_control_closestream(connection_t *conn, uint32_t len,
163 const char *body);
164 static int handle_control_closecircuit(connection_t *conn, uint32_t len,
165 const char *body);
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<=_CONTROL_CMD_MAX_RECOGNIZED) ? CONTROL_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 static INLINE int
189 log_severity_to_event(int severity)
191 switch (severity) {
192 case LOG_DEBUG: return EVENT_DEBUG_MSG;
193 case LOG_INFO: return EVENT_INFO_MSG;
194 case LOG_NOTICE: return EVENT_NOTICE_MSG;
195 case LOG_WARN: return EVENT_WARN_MSG;
196 case LOG_ERR: return EVENT_ERR_MSG;
197 default: return -1;
201 /** Set <b>global_event_mask</b> to the bitwise OR of each live control
202 * connection's event_mask field. */
203 static void update_global_event_mask(void)
205 connection_t **conns;
206 int n_conns, i;
207 global_event_mask = 0;
208 get_connection_array(&conns, &n_conns);
209 for (i = 0; i < n_conns; ++i) {
210 if (conns[i]->type == CONN_TYPE_CONTROL &&
211 conns[i]->state == CONTROL_CONN_STATE_OPEN) {
212 global_event_mask |= conns[i]->event_mask;
216 adjust_event_log_severity();
219 void adjust_event_log_severity(void) {
220 int i;
221 int min_log_event=EVENT_ERR_MSG, max_log_event=EVENT_DEBUG_MSG;
223 for (i = EVENT_DEBUG_MSG; i <= EVENT_ERR_MSG; ++i) {
224 if (EVENT_IS_INTERESTING(i)) {
225 min_log_event = i;
226 break;
229 for (i = EVENT_ERR_MSG; i >= EVENT_DEBUG_MSG; --i) {
230 if (EVENT_IS_INTERESTING(i)) {
231 max_log_event = i;
232 break;
235 if (EVENT_IS_INTERESTING(EVENT_LOG_OBSOLETE)) {
236 if (min_log_event > EVENT_NOTICE_MSG)
237 min_log_event = EVENT_NOTICE_MSG;
238 if (max_log_event < EVENT_ERR_MSG)
239 max_log_event = EVENT_ERR_MSG;
241 change_callback_log_severity(event_to_log_severity(min_log_event),
242 event_to_log_severity(max_log_event),
243 control_event_logmsg);
246 /** Send a message of type <b>type</b> containing <b>len</b> bytes
247 * from <b>body</b> along the control connection <b>conn</b> */
248 static void
249 send_control_message(connection_t *conn, uint16_t type, uint32_t len,
250 const char *body)
252 char buf[10];
253 tor_assert(conn);
254 tor_assert(len || !body);
255 tor_assert(type <= _CONTROL_CMD_MAX_RECOGNIZED);
256 if (len < 65536) {
257 set_uint16(buf, htons(len));
258 set_uint16(buf+2, htons(type));
259 connection_write_to_buf(buf, 4, conn);
260 if (len)
261 connection_write_to_buf(body, len, conn);
262 } else {
263 set_uint16(buf, htons(65535));
264 set_uint16(buf+2, htons(CONTROL_CMD_FRAGMENTHEADER));
265 set_uint16(buf+4, htons(type));
266 set_uint32(buf+6, htonl(len));
267 connection_write_to_buf(buf, 10, conn);
268 connection_write_to_buf(body, 65535-6, conn);
269 len -= (65535-6);
270 body += (65535-6);
271 while (len) {
272 size_t chunklen = (len<65535)?len:65535;
273 set_uint16(buf, htons((uint16_t)chunklen));
274 set_uint16(buf+2, htons(CONTROL_CMD_FRAGMENT));
275 connection_write_to_buf(buf, 4, conn);
276 connection_write_to_buf(body, chunklen, conn);
277 len -= chunklen;
278 body += chunklen;
283 /** Send a "DONE" message down the control connection <b>conn</b> */
284 static void
285 send_control_done(connection_t *conn)
287 send_control_message(conn, CONTROL_CMD_DONE, 0, NULL);
290 static void send_control_done2(connection_t *conn, const char *msg, size_t len)
292 if (len==0)
293 len = strlen(msg);
294 send_control_message(conn, CONTROL_CMD_DONE, len, msg);
297 /** Send an error message with error code <b>error</b> and body
298 * <b>message</b> down the connection <b>conn</b> */
299 static void
300 send_control_error(connection_t *conn, uint16_t error, const char *message)
302 char buf[256];
303 size_t len;
304 set_uint16(buf, htons(error));
305 len = strlen(message);
306 tor_assert(len < (256-2));
307 memcpy(buf+2, message, len);
308 send_control_message(conn, CONTROL_CMD_ERROR, (uint16_t)(len+2), buf);
311 /** Send an 'event' message of event type <b>event</b>, containing
312 * <b>len</b> bytes in <b>body</b> to every control connection that
313 * is interested in it. */
314 static void
315 send_control_event(uint16_t event, uint32_t len, const char *body)
317 connection_t **conns;
318 int n_conns, i;
319 size_t buflen;
320 char *buf;
322 buflen = len + 2;
323 buf = tor_malloc_zero(buflen);
324 set_uint16(buf, htons(event));
325 memcpy(buf+2, body, len);
327 get_connection_array(&conns, &n_conns);
328 for (i = 0; i < n_conns; ++i) {
329 if (conns[i]->type == CONN_TYPE_CONTROL &&
330 conns[i]->state == CONTROL_CONN_STATE_OPEN &&
331 conns[i]->event_mask & (1<<event)) {
332 send_control_message(conns[i], CONTROL_CMD_EVENT, buflen, buf);
336 tor_free(buf);
339 /** Called when we receive a SETCONF message: parse the body and try
340 * to update our configuration. Reply with a DONE or ERROR message. */
341 static int
342 handle_control_setconf(connection_t *conn, uint32_t len, char *body)
344 int r;
345 struct config_line_t *lines=NULL;
347 if (config_get_lines(body, &lines) < 0) {
348 log_fn(LOG_WARN,"Controller gave us config lines we can't parse.");
349 send_control_error(conn, ERR_SYNTAX, "Couldn't parse configuration");
350 return 0;
353 if ((r=config_trial_assign(lines, 1)) < 0) {
354 log_fn(LOG_WARN,"Controller gave us config lines that didn't validate.");
355 if (r==-1) {
356 send_control_error(conn, ERR_UNRECOGNIZED_CONFIG_KEY,
357 "Unrecognized option");
358 } else {
359 send_control_error(conn, ERR_INVALID_CONFIG_VALUE,"Invalid option value");
361 config_free_lines(lines);
362 return 0;
365 config_free_lines(lines);
366 if (options_act() < 0) { /* acting on them failed. die. */
367 log_fn(LOG_ERR,"Acting on config options left us in a broken state. Dying.");
368 exit(1);
370 send_control_done(conn);
371 return 0;
374 /** Called when we receive a GETCONF message. Parse the request, and
375 * reply with a CONFVALUE or an ERROR message */
376 static int
377 handle_control_getconf(connection_t *conn, uint32_t body_len, const char *body)
379 smartlist_t *questions = NULL;
380 smartlist_t *answers = NULL;
381 char *msg = NULL;
382 size_t msg_len;
383 or_options_t *options = get_options();
385 questions = smartlist_create();
386 smartlist_split_string(questions, body, "\n",
387 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
388 answers = smartlist_create();
389 SMARTLIST_FOREACH(questions, const char *, q,
391 int recognized = config_option_is_recognized(q);
392 if (!recognized) {
393 send_control_error(conn, ERR_UNRECOGNIZED_CONFIG_KEY, q);
394 goto done;
395 } else {
396 struct config_line_t *answer = config_get_assigned_option(options,q);
398 while (answer) {
399 struct config_line_t *next;
400 size_t alen = strlen(answer->key)+strlen(answer->value)+3;
401 char *astr = tor_malloc(alen);
402 tor_snprintf(astr, alen, "%s %s\n", answer->key, answer->value);
403 smartlist_add(answers, astr);
405 next = answer->next;
406 tor_free(answer->key);
407 tor_free(answer->value);
408 tor_free(answer);
409 answer = next;
414 msg = smartlist_join_strings(answers, "", 0, &msg_len);
415 send_control_message(conn, CONTROL_CMD_CONFVALUE,
416 (uint16_t)msg_len, msg_len?msg:NULL);
418 done:
419 if (answers) SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
420 if (questions) SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
421 smartlist_free(answers);
422 smartlist_free(questions);
423 tor_free(msg);
425 return 0;
428 /** Called when we get a SETEVENTS message: update conn->event_mask,
429 * and reply with DONE or ERROR. */
430 static int
431 handle_control_setevents(connection_t *conn, uint32_t len, const char *body)
433 uint16_t event_code;
434 uint32_t event_mask = 0;
435 if (len % 2) {
436 send_control_error(conn, ERR_SYNTAX,
437 "Odd number of bytes in setevents message");
438 return 0;
441 for (; len; len -= 2, body += 2) {
442 event_code = ntohs(get_uint16(body));
443 if (event_code < _EVENT_MIN || event_code > _EVENT_MAX) {
444 send_control_error(conn, ERR_UNRECOGNIZED_EVENT_CODE,
445 "Unrecognized event code");
446 return 0;
448 event_mask |= (1 << event_code);
451 conn->event_mask = event_mask;
453 update_global_event_mask();
454 send_control_done(conn);
455 return 0;
458 /** Decode the hashed, base64'd password stored in <b>hashed</b>. If
459 * <b>buf</b> is provided, store the hashed password in the first
460 * S2K_SPECIFIER_LEN+DIGEST_LEN bytes of <b>buf</b>. Return 0 on
461 * success, -1 on failure.
464 decode_hashed_password(char *buf, const char *hashed)
466 char decoded[64];
467 if (base64_decode(decoded, sizeof(decoded), hashed, strlen(hashed))
468 != S2K_SPECIFIER_LEN+DIGEST_LEN) {
469 return -1;
471 if (buf)
472 memcpy(buf, decoded, sizeof(decoded));
473 return 0;
476 /** Called when we get an AUTHENTICATE message. Check whether the
477 * authentication is valid, and if so, update the connection's state to
478 * OPEN. Reply with DONE or ERROR.
480 static int
481 handle_control_authenticate(connection_t *conn, uint32_t len, const char *body)
483 or_options_t *options = get_options();
484 if (options->CookieAuthentication) {
485 if (len == AUTHENTICATION_COOKIE_LEN &&
486 !memcmp(authentication_cookie, body, len)) {
487 goto ok;
489 } else if (options->HashedControlPassword) {
490 char expected[S2K_SPECIFIER_LEN+DIGEST_LEN];
491 char received[DIGEST_LEN];
492 if (decode_hashed_password(expected, options->HashedControlPassword)<0) {
493 log_fn(LOG_WARN,"Couldn't decode HashedControlPassword: invalid base64");
494 goto err;
496 secret_to_key(received,DIGEST_LEN,body,len,expected);
497 if (!memcmp(expected+S2K_SPECIFIER_LEN, received, DIGEST_LEN))
498 goto ok;
499 goto err;
500 } else {
501 if (len == 0) {
502 /* if Tor doesn't demand any stronger authentication, then
503 * the controller can get in with a blank auth line. */
504 goto ok;
506 goto err;
509 err:
510 send_control_error(conn, ERR_REJECTED_AUTHENTICATION,"Authentication failed");
511 return 0;
513 log_fn(LOG_INFO, "Authenticated control connection (%d)", conn->s);
514 send_control_done(conn);
515 conn->state = CONTROL_CONN_STATE_OPEN;
516 return 0;
519 static int
520 handle_control_saveconf(connection_t *conn, uint32_t len,
521 const char *body)
523 if (save_current_config()<0) {
524 send_control_error(conn, ERR_INTERNAL,
525 "Unable to write configuration to disk.");
526 } else {
527 send_control_done(conn);
529 return 0;
532 static int
533 handle_control_signal(connection_t *conn, uint32_t len,
534 const char *body)
536 if (len != 1) {
537 send_control_error(conn, ERR_SYNTAX,
538 "Body of SIGNAL command too long or too short.");
539 } else if (control_signal_act((uint8_t)body[0]) < 0) {
540 send_control_error(conn, ERR_SYNTAX, "Unrecognized signal number.");
541 } else {
542 send_control_done(conn);
544 return 0;
547 static int
548 handle_control_mapaddress(connection_t *conn, uint32_t len, const char *body)
550 smartlist_t *elts;
551 smartlist_t *lines;
552 smartlist_t *reply;
553 char *r;
554 size_t sz;
555 lines = smartlist_create();
556 elts = smartlist_create();
557 reply = smartlist_create();
558 smartlist_split_string(lines, body, "\n",
559 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
560 SMARTLIST_FOREACH(lines, char *, line,
562 tor_strlower(line);
563 smartlist_split_string(elts, line, " ", 0, 2);
564 if (smartlist_len(elts) == 2) {
565 const char *from = smartlist_get(elts,0);
566 const char *to = smartlist_get(elts,1);
567 if (!is_plausible_address(from)) {
568 log_fn(LOG_WARN,"Skipping invalid argument '%s' in MapAddress msg",from);
569 } else if (!is_plausible_address(to)) {
570 log_fn(LOG_WARN,"Skipping invalid argument '%s' in MapAddress msg",to);
571 } else if (!strcmp(from, ".") || !strcmp(from, "0.0.0.0")) {
572 const char *addr = addressmap_register_virtual_address(
573 strcmp(from,".") ? RESOLVED_TYPE_HOSTNAME : RESOLVED_TYPE_IPV4,
574 tor_strdup(to));
575 if (!addr) {
576 log_fn(LOG_WARN,
577 "Unable to allocate address for '%s' in MapAddress msg",line);
578 } else {
579 size_t anslen = strlen(addr)+strlen(to)+2;
580 char *ans = tor_malloc(anslen);
581 tor_snprintf(ans, anslen, "%s %s", addr, to);
582 smartlist_add(reply, ans);
584 } else {
585 addressmap_register(from, tor_strdup(to), 1);
586 smartlist_add(reply, tor_strdup(line));
588 } else {
589 log_fn(LOG_WARN, "Skipping MapAddress line with wrong number of items.");
591 SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
592 smartlist_clear(elts);
594 SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
595 smartlist_free(lines);
596 smartlist_free(elts);
598 r = smartlist_join_strings(reply, "\n", 1, &sz);
599 send_control_done2(conn,r,sz);
601 SMARTLIST_FOREACH(reply, char *, cp, tor_free(cp));
602 smartlist_free(reply);
603 tor_free(r);
604 return 0;
607 /** Lookup the 'getinfo' entry <b>question</b>, and return
608 * the answer in <b>*answer</b> (or NULL if key not recognized).
609 * Return 0 if success, or -1 if internal error. */
610 static int
611 handle_getinfo_helper(const char *question, char **answer)
613 *answer = NULL; /* unrecognized key by default */
614 if (!strcmp(question, "version")) {
615 *answer = tor_strdup(VERSION);
616 } else if (!strcmpstart(question, "desc/id/")) {
617 routerinfo_t *ri = router_get_by_hexdigest(question+strlen("desc/id/"));
618 if (ri && ri->signed_descriptor)
619 *answer = tor_strdup(ri->signed_descriptor);
620 } else if (!strcmpstart(question, "desc/name/")) {
621 routerinfo_t *ri = router_get_by_nickname(question+strlen("desc/name/"));
622 if (ri && ri->signed_descriptor)
623 *answer = tor_strdup(ri->signed_descriptor);
624 } else if (!strcmp(question, "network-status")) {
625 routerlist_t *routerlist;
626 router_get_routerlist(&routerlist);
627 if (!routerlist || !routerlist->routers ||
628 list_server_status(routerlist->routers, NULL, answer) < 0) {
629 return -1;
631 } else if (!strcmpstart(question, "addr-mappings/")) {
632 time_t min_e, max_e;
633 smartlist_t *mappings;
634 if (!strcmp(question, "addr-mappings/all")) {
635 min_e = 0; max_e = TIME_MAX;
636 } else if (!strcmp(question, "addr-mappings/cache")) {
637 min_e = 2; max_e = TIME_MAX;
638 } else if (!strcmp(question, "addr-mappings/config")) {
639 min_e = 0; max_e = 0;
640 } else if (!strcmp(question, "addr-mappings/control")) {
641 min_e = 1; max_e = 1;
642 } else {
643 return 0;
645 mappings = smartlist_create();
646 addressmap_get_mappings(mappings, min_e, max_e);
647 *answer = smartlist_join_strings(mappings, "\n", 1, NULL);
648 SMARTLIST_FOREACH(mappings, char *, cp, tor_free(cp));
649 smartlist_free(mappings);
651 return 0;
654 static int
655 handle_control_getinfo(connection_t *conn, uint32_t len, const char *body)
657 smartlist_t *questions = NULL;
658 smartlist_t *answers = NULL;
659 char *msg = NULL, *ans;
660 size_t msg_len;
662 questions = smartlist_create();
663 smartlist_split_string(questions, body, "\n",
664 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
665 answers = smartlist_create();
666 SMARTLIST_FOREACH(questions, const char *, q,
668 if (handle_getinfo_helper(q, &ans) < 0) {
669 send_control_error(conn, ERR_INTERNAL, body);
670 goto done;
671 } if (!ans) {
672 send_control_error(conn, ERR_UNRECOGNIZED_CONFIG_KEY, body);
673 goto done;
675 smartlist_add(answers, tor_strdup(q));
676 smartlist_add(answers, ans);
679 msg = smartlist_join_strings2(answers, "\0", 1, 1, &msg_len);
680 tor_assert(msg_len > 0); /* it will at least be terminated */
681 send_control_message(conn, CONTROL_CMD_INFOVALUE,
682 msg_len, msg);
684 done:
685 if (answers) SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
686 if (questions) SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
687 smartlist_free(answers);
688 smartlist_free(questions);
689 tor_free(msg);
691 return 0;
693 static int
694 handle_control_extendcircuit(connection_t *conn, uint32_t len,
695 const char *body)
697 smartlist_t *router_nicknames, *routers;
698 uint32_t circ_id;
699 circuit_t *circ;
700 char reply[4];
701 if (len<5) {
702 send_control_error(conn, ERR_SYNTAX, "extendcircuit message too short");
703 return 0;
706 router_nicknames = smartlist_create();
707 routers = smartlist_create();
708 smartlist_split_string(router_nicknames, body+4, ",", 0, 0);
709 SMARTLIST_FOREACH(router_nicknames, const char *, n,
711 routerinfo_t *r = router_get_by_nickname(n);
712 if (!r) {
713 send_control_error(conn, ERR_NO_ROUTER, n);
714 goto done;
716 smartlist_add(routers, r);
718 if (!smartlist_len(routers)) {
719 send_control_error(conn, ERR_SYNTAX, "No router names provided");
720 goto done;
723 circ_id = ntohl(get_uint32(body));
724 if (!circ_id) {
725 /* start a new circuit */
726 circ = circuit_init(CIRCUIT_PURPOSE_C_GENERAL, 0, 0, 0);
727 } else {
728 circ = circuit_get_by_global_id(circ_id);
729 if (!circ) {
730 send_control_error(conn, ERR_NO_CIRC,
731 "No circuit found with given ID");
732 goto done;
736 /* now circ refers to something that is ready to be extended */
738 SMARTLIST_FOREACH(routers, routerinfo_t *, r,
740 circuit_append_new_exit(circ, r);
743 /* now that we've populated the cpath, start extending */
744 if (!circ_id) {
745 if (circuit_handle_first_hop(circ) < 0) {
746 circuit_mark_for_close(circ);
747 send_control_error(conn, ERR_INTERNAL, "couldn't start circuit");
748 goto done;
750 } else {
751 if (circ->state == CIRCUIT_STATE_OPEN) {
752 circ->state = CIRCUIT_STATE_BUILDING;
753 if (circuit_send_next_onion_skin(circ) < 0) {
754 log_fn(LOG_INFO,"send_next_onion_skin failed; circuit marked for closing.");
755 circuit_mark_for_close(circ);
756 send_control_error(conn, ERR_INTERNAL, "couldn't send onion skin");
757 goto done;
762 set_uint32(reply, htonl(circ->global_identifier));
763 send_control_done2(conn, reply, sizeof(reply));
764 done:
765 SMARTLIST_FOREACH(router_nicknames, char *, n, tor_free(n));
766 smartlist_free(router_nicknames);
767 smartlist_free(routers);
768 return 0;
770 static int handle_control_attachstream(connection_t *conn, uint32_t len,
771 const char *body)
773 uint32_t conn_id;
774 uint32_t circ_id;
775 connection_t *ap_conn;
776 circuit_t *circ;
778 if (len < 8) {
779 send_control_error(conn, ERR_SYNTAX, "attachstream message too short");
780 return 0;
783 conn_id = ntohl(get_uint32(body));
784 circ_id = ntohl(get_uint32(body+4));
786 if (!(ap_conn = connection_get_by_global_id(conn_id))) {
787 send_control_error(conn, ERR_NO_STREAM,
788 "No connection found with given ID");
789 return 0;
791 if (ap_conn->state != AP_CONN_STATE_CONTROLLER_WAIT) {
792 send_control_error(conn, ERR_NO_STREAM,
793 "Connection was not managed by controller.");
794 return 0;
797 if (!circ_id) {
798 ap_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
799 if (connection_ap_handshake_attach_circuit(ap_conn)<0)
800 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_CANT_ATTACH);
801 send_control_done(conn);
802 return 0;
805 if (!(circ = circuit_get_by_global_id(circ_id))) {
806 send_control_error(conn, ERR_NO_CIRC, "No circuit found with given ID");
807 return 0;
809 if (circ->state != CIRCUIT_STATE_OPEN) {
810 send_control_error(conn, ERR_INTERNAL, "Refuse to attach stream to non-open circ.");
811 return 0;
813 if (connection_ap_handshake_attach_chosen_circuit(ap_conn, circ) != 1) {
814 send_control_error(conn, ERR_INTERNAL, "Unable to attach stream.");
815 return 0;
817 send_control_done(conn);
818 return 0;
820 static int
821 handle_control_postdescriptor(connection_t *conn, uint32_t len,
822 const char *body)
824 const char *msg;
825 switch (router_load_single_router(body, &msg)) {
826 case -1:
827 send_control_error(conn,ERR_SYNTAX,msg?msg: "Could not parse descriptor");
828 break;
829 case 0:
830 send_control_done2(conn,msg?msg: "Descriptor not added",0);
831 break;
832 case 1:
833 send_control_done(conn);
834 return 0;
837 send_control_done(conn);
838 return 0;
840 static int
841 handle_control_redirectstream(connection_t *conn, uint32_t len,
842 const char *body)
844 connection_t *ap_conn;
845 uint32_t conn_id;
846 if (len < 6) {
847 send_control_error(conn, ERR_SYNTAX, "redirectstream message too short");
848 return 0;
850 conn_id = ntohl(get_uint32(body));
852 if (!(ap_conn = connection_get_by_global_id(conn_id))
853 || ap_conn->state != CONN_TYPE_AP
854 || !ap_conn->socks_request) {
855 send_control_error(conn, ERR_NO_STREAM,
856 "No AP connection found with given ID");
857 return 0;
859 strlcpy(ap_conn->socks_request->address, body+4,
860 sizeof(ap_conn->socks_request->address));
862 send_control_done(conn);
863 return 0;
865 static int
866 handle_control_closestream(connection_t *conn, uint32_t len,
867 const char *body)
869 uint32_t conn_id;
870 connection_t *ap_conn;
871 uint8_t reason;
873 if (len < 6) {
874 send_control_error(conn, ERR_SYNTAX, "closestream message too short");
875 return 0;
878 conn_id = ntohl(get_uint32(body));
879 reason = *(uint8_t*)(body+4);
881 if (!(ap_conn = connection_get_by_global_id(conn_id))
882 || ap_conn->state != CONN_TYPE_AP
883 || !ap_conn->socks_request) {
884 send_control_error(conn, ERR_NO_STREAM,
885 "No AP connection found with given ID");
886 return 0;
888 connection_mark_unattached_ap(ap_conn, reason);
889 send_control_done(conn);
890 return 0;
893 static int
894 handle_control_closecircuit(connection_t *conn, uint32_t len,
895 const char *body)
897 uint32_t circ_id;
898 circuit_t *circ;
899 int safe;
901 if (len < 5) {
902 send_control_error(conn, ERR_SYNTAX, "closecircuit message too short");
903 return 0;
905 circ_id = ntohl(get_uint32(body));
906 safe = (*(uint8_t*)(body+4)) & 1;
908 if (!(circ = circuit_get_by_global_id(circ_id))) {
909 send_control_error(conn, ERR_NO_CIRC,
910 "No circuit found with given ID");
911 return 0;
914 if (!safe || !circ->p_streams) {
915 circuit_mark_for_close(circ);
918 send_control_done(conn);
919 return 0;
922 /** Called when <b>conn</b> has no more bytes left on its outbuf. */
924 connection_control_finished_flushing(connection_t *conn) {
925 tor_assert(conn);
926 tor_assert(conn->type == CONN_TYPE_CONTROL);
928 connection_stop_writing(conn);
929 return 0;
932 /** Called when <b>conn</b> has gotten its socket closed. */
933 int connection_control_reached_eof(connection_t *conn) {
934 log_fn(LOG_INFO,"Control connection reached EOF. Closing.");
935 connection_mark_for_close(conn);
936 return 0;
939 /** Called when <b>conn</b> has received more bytes on its inbuf.
942 connection_control_process_inbuf(connection_t *conn) {
943 uint32_t body_len;
944 uint16_t command_type;
945 char *body;
947 tor_assert(conn);
948 tor_assert(conn->type == CONN_TYPE_CONTROL);
950 again:
951 /* Try to suck a control message from the buffer. */
952 switch (fetch_from_buf_control(conn->inbuf, &body_len, &command_type, &body))
954 case -1:
955 tor_free(body);
956 log_fn(LOG_WARN, "Error in control command. Failing.");
957 return -1;
958 case 0:
959 /* Control command not all here yet. Wait. */
960 return 0;
961 case 1:
962 /* We got a command. Process it. */
963 break;
964 default:
965 tor_assert(0);
968 /* We got a command. If we need authentication, only authentication
969 * commands will be considered. */
970 if (conn->state == CONTROL_CONN_STATE_NEEDAUTH &&
971 command_type != CONTROL_CMD_AUTHENTICATE) {
972 log_fn(LOG_WARN, "Rejecting '%s' command; authentication needed.",
973 control_cmd_to_string(command_type));
974 send_control_error(conn, ERR_UNAUTHORIZED, "Authentication required");
975 tor_free(body);
976 goto again;
979 /* Okay, we're willing to process the command. */
980 switch (command_type)
982 case CONTROL_CMD_SETCONF:
983 if (handle_control_setconf(conn, body_len, body))
984 return -1;
985 break;
986 case CONTROL_CMD_GETCONF:
987 if (handle_control_getconf(conn, body_len, body))
988 return -1;
989 break;
990 case CONTROL_CMD_SETEVENTS:
991 if (handle_control_setevents(conn, body_len, body))
992 return -1;
993 break;
994 case CONTROL_CMD_AUTHENTICATE:
995 if (handle_control_authenticate(conn, body_len, body))
996 return -1;
997 break;
998 case CONTROL_CMD_SAVECONF:
999 if (handle_control_saveconf(conn, body_len, body))
1000 return -1;
1001 break;
1002 case CONTROL_CMD_SIGNAL:
1003 if (handle_control_signal(conn, body_len, body))
1004 return -1;
1005 break;
1006 case CONTROL_CMD_MAPADDRESS:
1007 if (handle_control_mapaddress(conn, body_len, body))
1008 return -1;
1009 break;
1010 case CONTROL_CMD_GETINFO:
1011 if (handle_control_getinfo(conn, body_len, body))
1012 return -1;
1013 break;
1014 case CONTROL_CMD_EXTENDCIRCUIT:
1015 if (handle_control_extendcircuit(conn, body_len, body))
1016 return -1;
1017 break;
1018 case CONTROL_CMD_ATTACHSTREAM:
1019 if (handle_control_attachstream(conn, body_len, body))
1020 return -1;
1021 break;
1022 case CONTROL_CMD_POSTDESCRIPTOR:
1023 if (handle_control_postdescriptor(conn, body_len, body))
1024 return -1;
1025 break;
1026 case CONTROL_CMD_REDIRECTSTREAM:
1027 if (handle_control_redirectstream(conn, body_len, body))
1028 return -1;
1029 break;
1030 case CONTROL_CMD_CLOSESTREAM:
1031 if (handle_control_closestream(conn, body_len, body))
1032 return -1;
1033 break;
1034 case CONTROL_CMD_CLOSECIRCUIT:
1035 if (handle_control_closecircuit(conn, body_len, body))
1036 return -1;
1037 break;
1038 case CONTROL_CMD_ERROR:
1039 case CONTROL_CMD_DONE:
1040 case CONTROL_CMD_CONFVALUE:
1041 case CONTROL_CMD_EVENT:
1042 case CONTROL_CMD_INFOVALUE:
1043 log_fn(LOG_WARN, "Received client-only '%s' command; ignoring.",
1044 control_cmd_to_string(command_type));
1045 send_control_error(conn, ERR_UNRECOGNIZED_TYPE,
1046 "Command type only valid from server to tor client");
1047 break;
1048 case CONTROL_CMD_FRAGMENTHEADER:
1049 case CONTROL_CMD_FRAGMENT:
1050 log_fn(LOG_WARN, "Recieved command fragment out of order; ignoring.");
1051 send_control_error(conn, ERR_SYNTAX, "Bad fragmentation on command.");
1052 default:
1053 log_fn(LOG_WARN, "Received unrecognized command type %d; ignoring.",
1054 (int)command_type);
1055 send_control_error(conn, ERR_UNRECOGNIZED_TYPE,
1056 "Unrecognized command type");
1057 break;
1059 tor_free(body);
1060 goto again; /* There might be more data. */
1063 /** Something has happened to circuit <b>circ</b>: tell any interested
1064 * control connections. */
1066 control_event_circuit_status(circuit_t *circ, circuit_status_event_t tp)
1068 char *path, *msg;
1069 size_t path_len;
1070 if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS))
1071 return 0;
1072 tor_assert(circ);
1073 tor_assert(CIRCUIT_IS_ORIGIN(circ));
1075 path = circuit_list_path(circ,0);
1076 path_len = strlen(path);
1077 msg = tor_malloc(1+4+path_len+1); /* event, circid, path, NUL. */
1078 msg[0] = (uint8_t) tp;
1079 set_uint32(msg+1, htonl(circ->global_identifier));
1080 strlcpy(msg+5,path,path_len+1);
1082 send_control_event(EVENT_CIRCUIT_STATUS, (uint32_t)(path_len+6), msg);
1083 tor_free(path);
1084 tor_free(msg);
1085 return 0;
1088 /** Something has happened to the stream associated with AP connection
1089 * <b>conn</b>: tell any interested control connections. */
1091 control_event_stream_status(connection_t *conn, stream_status_event_t tp)
1093 char *msg;
1094 size_t len;
1095 char buf[256], buf2[256];
1096 tor_assert(conn->type == CONN_TYPE_AP);
1097 tor_assert(conn->socks_request);
1099 if (!EVENT_IS_INTERESTING(EVENT_STREAM_STATUS))
1100 return 0;
1102 if (conn->chosen_exit_name)
1103 tor_snprintf(buf2, sizeof(buf2), ".%s.exit", conn->chosen_exit_name);
1104 tor_snprintf(buf, sizeof(buf), "%s%s:%d",
1105 conn->socks_request->address,
1106 conn->chosen_exit_name ? buf2 : "",
1107 conn->socks_request->port),
1108 len = strlen(buf);
1109 msg = tor_malloc(5+len+1);
1110 msg[0] = (uint8_t) tp;
1111 set_uint32(msg+1, htonl(conn->global_identifier));
1112 strlcpy(msg+5, buf, len+1);
1114 send_control_event(EVENT_STREAM_STATUS, (uint32_t)(5+len+1), msg);
1115 tor_free(msg);
1116 return 0;
1119 /** Something has happened to the OR connection <b>conn</b>: tell any
1120 * interested control connections. */
1122 control_event_or_conn_status(connection_t *conn,or_conn_status_event_t tp)
1124 char buf[HEX_DIGEST_LEN+3]; /* status, dollar, identity, NUL */
1125 size_t len;
1127 tor_assert(conn->type == CONN_TYPE_OR);
1129 if (!EVENT_IS_INTERESTING(EVENT_OR_CONN_STATUS))
1130 return 0;
1132 buf[0] = (uint8_t)tp;
1133 strlcpy(buf+1,conn->nickname,sizeof(buf)-1);
1134 len = strlen(buf+1);
1135 send_control_event(EVENT_OR_CONN_STATUS, (uint32_t)(len+1), buf);
1136 return 0;
1139 /** A second or more has elapsed: tell any interested control
1140 * connections how much bandwidth we used. */
1142 control_event_bandwidth_used(uint32_t n_read, uint32_t n_written)
1144 char buf[8];
1146 if (!EVENT_IS_INTERESTING(EVENT_BANDWIDTH_USED))
1147 return 0;
1149 set_uint32(buf, htonl(n_read));
1150 set_uint32(buf+4, htonl(n_written));
1151 send_control_event(EVENT_BANDWIDTH_USED, 8, buf);
1153 return 0;
1156 /** We got a log message: tell any interested control connections. */
1157 void
1158 control_event_logmsg(int severity, const char *msg)
1160 int oldlog = EVENT_IS_INTERESTING(EVENT_LOG_OBSOLETE) &&
1161 (severity == LOG_NOTICE || severity == LOG_WARN || severity == LOG_ERR);
1162 int event = log_severity_to_event(severity);
1164 if (event<0 || !EVENT_IS_INTERESTING(event))
1165 event = 0;
1167 if (oldlog || event) {
1168 size_t len = strlen(msg);
1169 if (event)
1170 send_control_event(event, (uint32_t)(len+1), msg);
1171 if (oldlog)
1172 send_control_event(EVENT_LOG_OBSOLETE, (uint32_t)(len+1), msg);
1176 /** Called whenever we receive new router descriptors: tell any
1177 * interested control connections. <b>routers</b> is a list of
1178 * DIGEST_LEN-byte identity digests.
1180 int control_event_descriptors_changed(smartlist_t *routers)
1182 size_t len;
1183 char *msg;
1184 smartlist_t *identities;
1185 char buf[HEX_DIGEST_LEN+1];
1187 if (!EVENT_IS_INTERESTING(EVENT_NEW_DESC))
1188 return 0;
1189 identities = smartlist_create();
1190 SMARTLIST_FOREACH(routers, routerinfo_t *, r,
1192 base16_encode(buf,sizeof(buf),r->identity_digest,DIGEST_LEN);
1193 smartlist_add(identities, tor_strdup(buf));
1195 msg = smartlist_join_strings(identities, ",", 1, &len);
1196 send_control_event(EVENT_NEW_DESC, len+1, msg);
1198 SMARTLIST_FOREACH(identities, char *, cp, tor_free(cp));
1199 smartlist_free(identities);
1200 tor_free(msg);
1201 return 0;
1204 /** Choose a random authentication cookie and write it to disk.
1205 * Anybody who can read the cookie from disk will be considered
1206 * authorized to use the control connection. */
1208 init_cookie_authentication(int enabled)
1210 char fname[512];
1212 if (!enabled) {
1213 authentication_cookie_is_set = 0;
1214 return 0;
1217 tor_snprintf(fname, sizeof(fname), "%s/control_auth_cookie",
1218 get_options()->DataDirectory);
1219 crypto_rand(authentication_cookie, AUTHENTICATION_COOKIE_LEN);
1220 authentication_cookie_is_set = 1;
1221 if (write_bytes_to_file(fname, authentication_cookie,
1222 AUTHENTICATION_COOKIE_LEN, 1)) {
1223 log_fn(LOG_WARN,"Error writing authentication cookie.");
1224 return -1;
1227 return 0;