Forward port changelog
[tor.git] / src / or / control.c
blob13954adae8e2c22cd102ea15d8f48cdee2bcbbad
1 /* Copyright 2004 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_MAX_RECOGNIZED 0x0009
45 /* Recognized error codes. */
46 #define ERR_UNSPECIFIED 0x0000
47 #define ERR_INTERNAL 0x0001
48 #define ERR_UNRECOGNIZED_TYPE 0x0002
49 #define ERR_SYNTAX 0x0003
50 #define ERR_UNRECOGNIZED_CONFIG_KEY 0x0004
51 #define ERR_INVALID_CONFIG_VALUE 0x0005
52 #define ERR_UNRECOGNIZED_EVENT_CODE 0x0006
53 #define ERR_UNAUTHORIZED 0x0007
54 #define ERR_REJECTED_AUTHENTICATION 0x0008
56 /* Recognized asynchronous event types. */
57 #define _EVENT_MIN 0x0001
58 #define EVENT_CIRCUIT_STATUS 0x0001
59 #define EVENT_STREAM_STATUS 0x0002
60 #define EVENT_OR_CONN_STATUS 0x0003
61 #define EVENT_BANDWIDTH_USED 0x0004
62 #define EVENT_WARNING 0x0005
63 #define _EVENT_MAX 0x0005
65 /** Array mapping from message type codes to human-readable message
66 * type names. */
67 static const char * CONTROL_COMMANDS[] = {
68 "error",
69 "done",
70 "setconf",
71 "getconf",
72 "confvalue",
73 "setevents",
74 "events",
75 "authenticate",
76 "saveconf",
79 /** Bitfield: The bit 1&lt;&lt;e is set if <b>any</b> open control
80 * connection is interested in events of type <b>e</b>. We use this
81 * so that we can decide to skip generating event messages that nobody
82 * has interest in without having to walk over the global connection
83 * list to find out.
84 **/
85 static uint32_t global_event_mask = 0;
87 /** Macro: true if any control connection is interested in events of type
88 * <b>e</b>. */
89 #define EVENT_IS_INTERESTING(e) (global_event_mask & (1<<(e)))
91 /** If we're using cookie-type authentication, how long should our cookies be?
93 #define AUTHENTICATION_COOKIE_LEN 32
95 /** If true, we've set authentication_cookie to a secret code and
96 * stored it to disk. */
97 static int authentication_cookie_is_set = 0;
98 static char authentication_cookie[AUTHENTICATION_COOKIE_LEN];
100 static void update_global_event_mask(void);
101 static void send_control_message(connection_t *conn, uint16_t type,
102 uint16_t len, const char *body);
103 static void send_control_done(connection_t *conn);
104 static void send_control_error(connection_t *conn, uint16_t error,
105 const char *message);
106 static void send_control_event(uint16_t event, uint16_t len, const char *body);
107 static int handle_control_setconf(connection_t *conn, uint16_t len,
108 char *body);
109 static int handle_control_getconf(connection_t *conn, uint16_t len,
110 const char *body);
111 static int handle_control_setevents(connection_t *conn, uint16_t len,
112 const char *body);
113 static int handle_control_authenticate(connection_t *conn, uint16_t len,
114 const char *body);
115 static int handle_control_saveconf(connection_t *conn, uint16_t len,
116 const char *body);
117 static int handle_control_signal(connection_t *conn, uint16_t len,
118 const char *body);
120 /** Given a possibly invalid message type code <b>cmd</b>, return a
121 * human-readable string equivalent. */
122 static INLINE const char *
123 control_cmd_to_string(uint16_t cmd)
125 return (cmd<=_CONTROL_CMD_MAX_RECOGNIZED) ? CONTROL_COMMANDS[cmd] : "Unknown";
128 /** Set <b>global_event_mask</b> to the bitwise OR of each live control
129 * connection's event_mask field. */
130 static void update_global_event_mask(void)
132 connection_t **conns;
133 int n_conns, i;
135 global_event_mask = 0;
136 get_connection_array(&conns, &n_conns);
137 for (i = 0; i < n_conns; ++i) {
138 if (conns[i]->type == CONN_TYPE_CONTROL &&
139 conns[i]->state == CONTROL_CONN_STATE_OPEN) {
140 global_event_mask |= conns[i]->event_mask;
145 /** Send a message of type <b>type</b> containing <b>len</b> bytes
146 * from <b>body</b> along the control connection <b>conn</b> */
147 static void
148 send_control_message(connection_t *conn, uint16_t type, uint16_t len,
149 const char *body)
151 char buf[4];
152 tor_assert(conn);
153 tor_assert(len || !body);
154 tor_assert(type <= _CONTROL_CMD_MAX_RECOGNIZED);
155 set_uint16(buf, htons(len));
156 set_uint16(buf+2, htons(type));
157 connection_write_to_buf(buf, 4, conn);
158 if (len)
159 connection_write_to_buf(body, len, conn);
162 /** Send a "DONE" message down the control connection <b>conn</b> */
163 static void
164 send_control_done(connection_t *conn)
166 send_control_message(conn, CONTROL_CMD_DONE, 0, NULL);
169 /** Send an error message with error code <b>error</b> and body
170 * <b>message</b> down the connection <b>conn</b> */
171 static void
172 send_control_error(connection_t *conn, uint16_t error, const char *message)
174 char buf[256];
175 size_t len;
176 set_uint16(buf, htons(error));
177 len = strlen(message);
178 tor_assert(len < (256-2));
179 memcpy(buf+2, message, len);
180 send_control_message(conn, CONTROL_CMD_ERROR, (uint16_t)(len+2), buf);
183 /** Send an 'event' message of event type <b>event</b>, containing
184 * <b>len</b> bytes in <b>body</b> to every control connection that
185 * is interested in it. */
186 static void
187 send_control_event(uint16_t event, uint16_t len, const char *body)
189 connection_t **conns;
190 int n_conns, i;
191 size_t buflen;
192 char *buf;
194 buflen = len + 2;
195 buf = tor_malloc_zero(buflen);
196 set_uint16(buf, htons(event));
197 memcpy(buf+2, body, len);
199 get_connection_array(&conns, &n_conns);
200 for (i = 0; i < n_conns; ++i) {
201 if (conns[i]->type == CONN_TYPE_CONTROL &&
202 conns[i]->state == CONTROL_CONN_STATE_OPEN &&
203 conns[i]->event_mask & (1<<event)) {
204 send_control_message(conns[i], CONTROL_CMD_EVENT, (uint16_t)(buflen), buf);
208 tor_free(buf);
211 /** Called when we receive a SETCONF message: parse the body and try
212 * to update our configuration. Reply with a DONE or ERROR message. */
213 static int
214 handle_control_setconf(connection_t *conn, uint16_t len, char *body)
216 int r;
217 struct config_line_t *lines=NULL;
219 if (config_get_lines(body, &lines) < 0) {
220 log_fn(LOG_WARN,"Controller gave us config lines we can't parse.");
221 send_control_error(conn, ERR_SYNTAX, "Couldn't parse configuration");
222 return 0;
225 if ((r=config_trial_assign(lines, 1)) < 0) {
226 log_fn(LOG_WARN,"Controller gave us config lines that didn't validate.");
227 if (r==-1) {
228 send_control_error(conn, ERR_UNRECOGNIZED_CONFIG_KEY,
229 "Unrecognized option");
230 } else {
231 send_control_error(conn, ERR_INVALID_CONFIG_VALUE,"Invalid option value");
233 config_free_lines(lines);
234 return 0;
237 config_free_lines(lines);
238 if (options_act() < 0) { /* acting on them failed. die. */
239 log_fn(LOG_ERR,"Acting on config options left us in a broken state. Dying.");
240 exit(1);
242 send_control_done(conn);
243 return 0;
246 /** Called when we receive a GETCONF message. Parse the request, and
247 * reply with a CONFVALUE or an ERROR message */
248 static int
249 handle_control_getconf(connection_t *conn, uint16_t body_len, const char *body)
251 smartlist_t *questions = NULL;
252 smartlist_t *answers = NULL;
253 char *msg = NULL;
254 size_t msg_len;
255 or_options_t *options = get_options();
257 questions = smartlist_create();
258 smartlist_split_string(questions, body, "\n",
259 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
260 answers = smartlist_create();
261 SMARTLIST_FOREACH(questions, const char *, q,
263 int recognized = config_option_is_recognized(q);
264 if (!recognized) {
265 send_control_error(conn, ERR_UNRECOGNIZED_CONFIG_KEY, body);
266 goto done;
267 } else {
268 struct config_line_t *answer = config_get_assigned_option(options,q);
270 while (answer) {
271 struct config_line_t *next;
272 size_t alen = strlen(answer->key)+strlen(answer->value)+3;
273 char *astr = tor_malloc(alen);
274 tor_snprintf(astr, alen, "%s %s\n", answer->key, answer->value);
275 smartlist_add(answers, astr);
277 next = answer->next;
278 tor_free(answer->key);
279 tor_free(answer->value);
280 tor_free(answer);
281 answer = next;
286 msg = smartlist_join_strings(answers, "", 0, &msg_len);
287 send_control_message(conn, CONTROL_CMD_CONFVALUE,
288 (uint16_t)msg_len, msg_len?msg:NULL);
290 done:
291 if (answers) SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
292 if (questions) SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
293 smartlist_free(answers);
294 smartlist_free(questions);
295 tor_free(msg);
297 return 0;
300 /** Called when we get a SETEVENTS message: update conn->event_mask,
301 * and reply with DONE or ERROR. */
302 static int
303 handle_control_setevents(connection_t *conn, uint16_t len, const char *body)
305 uint16_t event_code;
306 uint32_t event_mask = 0;
307 if (len % 2) {
308 send_control_error(conn, ERR_SYNTAX,
309 "Odd number of bytes in setevents message");
310 return 0;
313 for (; len; len -= 2, body += 2) {
314 event_code = ntohs(get_uint16(body));
315 if (event_code < _EVENT_MIN || event_code > _EVENT_MAX) {
316 send_control_error(conn, ERR_UNRECOGNIZED_EVENT_CODE,
317 "Unrecognized event code");
318 return 0;
320 event_mask |= (1 << event_code);
323 conn->event_mask = event_mask;
325 update_global_event_mask();
326 send_control_done(conn);
327 return 0;
330 /** Decode the hashed, base64'd password stored in <b>hashed</b>. If
331 * <b>buf</b> is provided, store the hashed password in the first
332 * S2K_SPECIFIER_LEN+DIGEST_LEN bytes of <b>buf</b>. Return 0 on
333 * success, -1 on failure.
336 decode_hashed_password(char *buf, const char *hashed)
338 char decoded[64];
339 if (base64_decode(decoded, sizeof(decoded), hashed, strlen(hashed))
340 != S2K_SPECIFIER_LEN+DIGEST_LEN) {
341 return -1;
343 if (buf)
344 memcpy(buf, decoded, sizeof(decoded));
345 return 0;
348 /** Called when we get an AUTHENTICATE message. Check whether the
349 * authentication is valid, and if so, update the connection's state to
350 * OPEN. Reply with DONE or ERROR.
352 static int
353 handle_control_authenticate(connection_t *conn, uint16_t len, const char *body)
355 or_options_t *options = get_options();
356 if (options->CookieAuthentication) {
357 if (len == AUTHENTICATION_COOKIE_LEN &&
358 !memcmp(authentication_cookie, body, len)) {
359 goto ok;
361 } else if (options->HashedControlPassword) {
362 char expected[S2K_SPECIFIER_LEN+DIGEST_LEN];
363 char received[DIGEST_LEN];
364 if (decode_hashed_password(expected, options->HashedControlPassword)<0) {
365 log_fn(LOG_WARN,"Couldn't decode HashedControlPassword: invalid base64");
366 goto err;
368 secret_to_key(received,DIGEST_LEN,body,len,expected);
369 if (!memcmp(expected+S2K_SPECIFIER_LEN, received, DIGEST_LEN))
370 goto ok;
371 goto err;
372 } else {
373 if (len == 0) {
374 /* if Tor doesn't demand any stronger authentication, then
375 * the controller can get in with a blank auth line. */
376 goto ok;
378 goto err;
381 err:
382 send_control_error(conn, ERR_REJECTED_AUTHENTICATION,"Authentication failed");
383 return 0;
385 log_fn(LOG_INFO, "Authenticated control connection (%d)", conn->s);
386 send_control_done(conn);
387 conn->state = CONTROL_CONN_STATE_OPEN;
388 return 0;
391 static int
392 handle_control_saveconf(connection_t *conn, uint16_t len,
393 const char *body)
395 if (save_current_config()<0) {
396 send_control_error(conn, ERR_INTERNAL,
397 "Unable to write configuration to disk.");
398 } else {
399 send_control_done(conn);
401 return 0;
404 static int
405 handle_control_signal(connection_t *conn, uint16_t len,
406 const char *body)
408 if (len != 1) {
409 send_control_error(conn, ERR_SYNTAX,
410 "Body of SIGNAL command too long or too short.");
411 } else if (control_signal_act((uint8_t)body[0]) < 0) {
412 send_control_error(conn, ERR_SYNTAX, "Unrecognized signal number.");
413 } else {
414 send_control_done(conn);
416 return 0;
419 /** Called when <b>conn</b> has no more bytes left on its outbuf. */
421 connection_control_finished_flushing(connection_t *conn) {
422 tor_assert(conn);
423 tor_assert(conn->type == CONN_TYPE_CONTROL);
425 connection_stop_writing(conn);
426 return 0;
429 /** Called when <b>conn</b> has gotten its socket closed. */
430 int connection_control_reached_eof(connection_t *conn) {
431 log_fn(LOG_INFO,"Control connection reached EOF. Closing.");
432 connection_mark_for_close(conn);
433 return 0;
436 /** Called when <b>conn</b> has received more bytes on its inbuf.
439 connection_control_process_inbuf(connection_t *conn) {
440 uint16_t body_len, command_type;
441 char *body;
443 tor_assert(conn);
444 tor_assert(conn->type == CONN_TYPE_CONTROL);
446 again:
447 /* Try to suck a control message from the buffer. */
448 switch (fetch_from_buf_control(conn->inbuf, &body_len, &command_type, &body))
450 case -1:
451 tor_free(body);
452 log_fn(LOG_WARN, "Error in control command. Failing.");
453 return -1;
454 case 0:
455 /* Control command not all here yet. Wait. */
456 return 0;
457 case 1:
458 /* We got a command. Process it. */
459 break;
460 default:
461 tor_assert(0);
464 /* We got a command. If we need authentication, only authentication
465 * commands will be considered. */
466 if (conn->state == CONTROL_CONN_STATE_NEEDAUTH &&
467 command_type != CONTROL_CMD_AUTHENTICATE) {
468 log_fn(LOG_WARN, "Rejecting '%s' command; authentication needed.",
469 control_cmd_to_string(command_type));
470 send_control_error(conn, ERR_UNAUTHORIZED, "Authentication required");
471 tor_free(body);
472 goto again;
475 /* Okay, we're willing to process the command. */
476 switch (command_type)
478 case CONTROL_CMD_SETCONF:
479 if (handle_control_setconf(conn, body_len, body))
480 return -1;
481 break;
482 case CONTROL_CMD_GETCONF:
483 if (handle_control_getconf(conn, body_len, body))
484 return -1;
485 break;
486 case CONTROL_CMD_SETEVENTS:
487 if (handle_control_setevents(conn, body_len, body))
488 return -1;
489 break;
490 case CONTROL_CMD_AUTHENTICATE:
491 if (handle_control_authenticate(conn, body_len, body))
492 return -1;
493 break;
494 case CONTROL_CMD_SAVECONF:
495 if (handle_control_saveconf(conn, body_len, body))
496 return -1;
497 break;
498 case CONTROL_CMD_SIGNAL:
499 if (handle_control_signal(conn, body_len, body))
500 return -1;
501 break;
502 case CONTROL_CMD_ERROR:
503 case CONTROL_CMD_DONE:
504 case CONTROL_CMD_CONFVALUE:
505 case CONTROL_CMD_EVENT:
506 log_fn(LOG_WARN, "Received client-only '%s' command; ignoring.",
507 control_cmd_to_string(command_type));
508 send_control_error(conn, ERR_UNRECOGNIZED_TYPE,
509 "Command type only valid from server to tor client");
510 break;
511 default:
512 log_fn(LOG_WARN, "Received unrecognized command type %d; ignoring.",
513 (int)command_type);
514 send_control_error(conn, ERR_UNRECOGNIZED_TYPE,
515 "Unrecognized command type");
516 break;
518 tor_free(body);
519 goto again; /* There might be more data. */
522 /** Something has happened to circuit <b>circ</b>: tell any interested
523 * control connections. */
525 control_event_circuit_status(circuit_t *circ, circuit_status_event_t tp)
527 char *path, *msg;
528 size_t path_len;
529 if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS))
530 return 0;
531 tor_assert(circ);
532 tor_assert(CIRCUIT_IS_ORIGIN(circ));
534 path = circuit_list_path(circ,0);
535 path_len = strlen(path);
536 msg = tor_malloc(1+4+path_len+1); /* event, circid, path, NUL. */
537 msg[0] = (uint8_t) tp;
538 set_uint32(msg+1, htonl(circ->global_identifier));
539 strlcpy(msg+5,path,path_len+1);
541 send_control_event(EVENT_CIRCUIT_STATUS, (uint16_t)(path_len+6), msg);
542 tor_free(path);
543 tor_free(msg);
544 return 0;
547 /** Something has happened to the stream associated with AP connection
548 * <b>conn</b>: tell any interested control connections. */
550 control_event_stream_status(connection_t *conn, stream_status_event_t tp)
552 char *msg;
553 size_t len;
554 char buf[256];
555 tor_assert(conn->type == CONN_TYPE_AP);
556 tor_assert(conn->socks_request);
558 if (!EVENT_IS_INTERESTING(EVENT_STREAM_STATUS))
559 return 0;
561 tor_snprintf(buf, sizeof(buf), "%s:%d",
562 conn->socks_request->address, conn->socks_request->port),
563 len = strlen(buf);
564 msg = tor_malloc(5+len+1);
565 msg[0] = (uint8_t) tp;
566 set_uint32(msg+1, htonl(conn->s)); /* ???? Is this a security problem? */
567 strlcpy(msg+5, buf, len+1);
569 send_control_event(EVENT_STREAM_STATUS, (uint16_t)(5+len+1), msg);
570 tor_free(msg);
571 return 0;
574 /** Something has happened to the OR connection <b>conn</b>: tell any
575 * interested control connections. */
577 control_event_or_conn_status(connection_t *conn,or_conn_status_event_t tp)
579 char buf[HEX_DIGEST_LEN+3]; /* status, dollar, identity, NUL */
580 size_t len;
582 tor_assert(conn->type == CONN_TYPE_OR);
584 if (!EVENT_IS_INTERESTING(EVENT_OR_CONN_STATUS))
585 return 0;
587 buf[0] = (uint8_t)tp;
588 strlcpy(buf+1,conn->nickname,sizeof(buf)-1);
589 len = strlen(buf+1);
590 send_control_event(EVENT_OR_CONN_STATUS, (uint16_t)(len+1), buf);
591 return 0;
594 /** A second or more has elapsed: tell any interested control
595 * connections how much bandwidth we used. */
597 control_event_bandwidth_used(uint32_t n_read, uint32_t n_written)
599 char buf[8];
601 if (!EVENT_IS_INTERESTING(EVENT_BANDWIDTH_USED))
602 return 0;
604 set_uint32(buf, htonl(n_read));
605 set_uint32(buf+4, htonl(n_written));
606 send_control_event(EVENT_BANDWIDTH_USED, 8, buf);
608 return 0;
611 /** We got a log message: tell any interested control connections. */
612 void
613 control_event_logmsg(int severity, const char *msg)
615 size_t len;
616 if (severity > LOG_NOTICE) /* Less important than notice? ignore for now. */
617 return;
618 if (!EVENT_IS_INTERESTING(EVENT_WARNING))
619 return;
621 len = strlen(msg);
622 send_control_event(EVENT_WARNING, (uint16_t)(len+1), msg);
625 /** Choose a random authentication cookie and write it to disk.
626 * Anybody who can read the cookie from disk will be considered
627 * authorized to use the control connection. */
629 init_cookie_authentication(int enabled)
631 char fname[512];
633 if (!enabled) {
634 authentication_cookie_is_set = 0;
635 return 0;
638 tor_snprintf(fname, sizeof(fname), "%s/control_auth_cookie",
639 get_options()->DataDirectory);
640 crypto_rand(authentication_cookie, AUTHENTICATION_COOKIE_LEN);
641 authentication_cookie_is_set = 1;
642 if (write_bytes_to_file(fname, authentication_cookie,
643 AUTHENTICATION_COOKIE_LEN, 1)) {
644 log_fn(LOG_WARN,"Error writing authentication cookie.");
645 return -1;
648 return 0;