Only set a cookie when we intend to.
[tor.git] / src / or / control.c
blob958e5dc804dc290b97db292124331a84641a6006
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_MAX_RECOGNIZED 0x0008
44 /* Recognized error codes. */
45 #define ERR_UNSPECIFIED 0x0000
46 #define ERR_INTERNAL 0x0001
47 #define ERR_UNRECOGNIZED_TYPE 0x0002
48 #define ERR_SYNTAX 0x0003
49 #define ERR_UNRECOGNIZED_CONFIG_KEY 0x0004
50 #define ERR_INVALID_CONFIG_VALUE 0x0005
51 #define ERR_UNRECOGNIZED_EVENT_CODE 0x0006
52 #define ERR_UNAUTHORIZED 0x0007
53 #define ERR_REJECTED_AUTHENTICATION 0x0008
55 /* Recognized asynchronous event types. */
56 #define _EVENT_MIN 0x0001
57 #define EVENT_CIRCUIT_STATUS 0x0001
58 #define EVENT_STREAM_STATUS 0x0002
59 #define EVENT_OR_CONN_STATUS 0x0003
60 #define EVENT_BANDWIDTH_USED 0x0004
61 #define EVENT_WARNING 0x0005
62 #define _EVENT_MAX 0x0005
64 /** Array mapping from message type codes to human-readable message
65 * type names. */
66 static const char * CONTROL_COMMANDS[] = {
67 "error",
68 "done",
69 "setconf",
70 "getconf",
71 "confvalue",
72 "setevents",
73 "events",
74 "authenticate",
75 "saveconf",
78 /** Bitfield: The bit 1&lt;&lt;e is set if <b>any</b> open control
79 * connection is interested in events of type <b>e</b>. We use this
80 * so that we can decide to skip generating event messages that nobody
81 * has interest in without having to walk over the global connection
82 * list to find out.
83 **/
84 static uint32_t global_event_mask = 0;
86 /** Macro: true if any control connection is interested in events of type
87 * <b>e</b>. */
88 #define EVENT_IS_INTERESTING(e) (global_event_mask & (1<<(e)))
90 /** If we're using cookie-type authentication, how long should our cookies be?
92 #define AUTHENTICATION_COOKIE_LEN 32
94 /** If true, we've set authentication_cookie to a secret code and
95 * stored it to disk. */
96 static int authentication_cookie_is_set = 0;
97 static char authentication_cookie[AUTHENTICATION_COOKIE_LEN];
99 static void update_global_event_mask(void);
100 static void send_control_message(connection_t *conn, uint16_t type,
101 uint16_t len, const char *body);
102 static void send_control_done(connection_t *conn);
103 static void send_control_error(connection_t *conn, uint16_t error,
104 const char *message);
105 static void send_control_event(uint16_t event, uint16_t len, const char *body);
106 static int handle_control_setconf(connection_t *conn, uint16_t len,
107 char *body);
108 static int handle_control_getconf(connection_t *conn, uint16_t len,
109 const char *body);
110 static int handle_control_setevents(connection_t *conn, uint16_t len,
111 const char *body);
112 static int handle_control_authenticate(connection_t *conn, uint16_t len,
113 const char *body);
114 static int handle_control_saveconf(connection_t *conn, uint16_t len,
115 const char *body);
117 /** Given a possibly invalid message type code <b>cmd</b>, return a
118 * human-readable string equivalent. */
119 static INLINE const char *
120 control_cmd_to_string(uint16_t cmd)
122 return (cmd<=_CONTROL_CMD_MAX_RECOGNIZED) ? CONTROL_COMMANDS[cmd] : "Unknown";
125 /** Set <b>global_event_mask</b> to the bitwise OR of each live control
126 * connection's event_mask field. */
127 static void update_global_event_mask(void)
129 connection_t **conns;
130 int n_conns, i;
132 global_event_mask = 0;
133 get_connection_array(&conns, &n_conns);
134 for (i = 0; i < n_conns; ++i) {
135 if (conns[i]->type == CONN_TYPE_CONTROL &&
136 conns[i]->state == CONTROL_CONN_STATE_OPEN) {
137 global_event_mask |= conns[i]->event_mask;
142 /** Send a message of type <b>type</b> containing <b>len</b> bytes
143 * from <b>body</b> along the control connection <b>conn</b> */
144 static void
145 send_control_message(connection_t *conn, uint16_t type, uint16_t len,
146 const char *body)
148 char buf[4];
149 tor_assert(conn);
150 tor_assert(len || !body);
151 tor_assert(type <= _CONTROL_CMD_MAX_RECOGNIZED);
152 set_uint16(buf, htons(len));
153 set_uint16(buf+2, htons(type));
154 connection_write_to_buf(buf, 4, conn);
155 if (len)
156 connection_write_to_buf(body, len, conn);
159 /** Send a "DONE" message down the control connection <b>conn</b> */
160 static void
161 send_control_done(connection_t *conn)
163 send_control_message(conn, CONTROL_CMD_DONE, 0, NULL);
166 /** Send an error message with error code <b>error</b> and body
167 * <b>message</b> down the connection <b>conn</b> */
168 static void
169 send_control_error(connection_t *conn, uint16_t error, const char *message)
171 char buf[256];
172 size_t len;
173 set_uint16(buf, htons(error));
174 len = strlen(message);
175 tor_assert(len < (256-2));
176 memcpy(buf+2, message, len);
177 send_control_message(conn, CONTROL_CMD_ERROR, (uint16_t)(len+2), buf);
180 /** Send an 'event' message of event type <b>event</b>, containing
181 * <b>len</b> bytes in <b>body</b> to every control connection that
182 * is interested in it. */
183 static void
184 send_control_event(uint16_t event, uint16_t len, const char *body)
186 connection_t **conns;
187 int n_conns, i;
188 size_t buflen;
189 char *buf;
191 buflen = len + 2;
192 buf = tor_malloc_zero(buflen);
193 set_uint16(buf, htons(event));
194 memcpy(buf+2, body, len);
196 get_connection_array(&conns, &n_conns);
197 for (i = 0; i < n_conns; ++i) {
198 if (conns[i]->type == CONN_TYPE_CONTROL &&
199 conns[i]->state == CONTROL_CONN_STATE_OPEN &&
200 conns[i]->event_mask & (1<<event)) {
201 send_control_message(conns[i], CONTROL_CMD_EVENT, (uint16_t)(buflen), buf);
205 tor_free(buf);
208 /** Called when we receive a SETCONF message: parse the body and try
209 * to update our configuration. Reply with a DONE or ERROR message. */
210 static int
211 handle_control_setconf(connection_t *conn, uint16_t len, char *body)
213 int r;
214 struct config_line_t *lines=NULL;
216 if (config_get_lines(body, &lines) < 0) {
217 log_fn(LOG_WARN,"Controller gave us config lines we can't parse.");
218 send_control_error(conn, ERR_SYNTAX, "Couldn't parse configuration");
219 return 0;
222 if ((r=config_trial_assign(lines, 1)) < 0) {
223 log_fn(LOG_WARN,"Controller gave us config lines that didn't validate.");
224 if (r==-1) {
225 send_control_error(conn, ERR_UNRECOGNIZED_CONFIG_KEY,
226 "Unrecognized option");
227 } else {
228 send_control_error(conn, ERR_INVALID_CONFIG_VALUE,"Invalid option value");
230 config_free_lines(lines);
231 return 0;
234 config_free_lines(lines);
235 if (options_act() < 0) { /* acting on them failed. die. */
236 log_fn(LOG_ERR,"Acting on config options left us in a broken state. Dying.");
237 exit(1);
239 send_control_done(conn);
240 return 0;
243 /** Called when we receive a GETCONF message. Parse the request, and
244 * reply with a CONFVALUE or an ERROR message */
245 static int
246 handle_control_getconf(connection_t *conn, uint16_t body_len, const char *body)
248 smartlist_t *questions = NULL;
249 smartlist_t *answers = NULL;
250 char *msg = NULL;
251 size_t msg_len;
252 or_options_t *options = get_options();
254 questions = smartlist_create();
255 smartlist_split_string(questions, body, "\n",
256 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
257 answers = smartlist_create();
258 SMARTLIST_FOREACH(questions, const char *, q,
260 int recognized = config_option_is_recognized(q);
261 if (!recognized) {
262 send_control_error(conn, ERR_UNRECOGNIZED_CONFIG_KEY, body);
263 goto done;
264 } else {
265 struct config_line_t *answer = config_get_assigned_option(options,q);
267 while (answer) {
268 struct config_line_t *next;
269 size_t alen = strlen(answer->key)+strlen(answer->value)+2;
270 char *astr = tor_malloc(alen);
271 tor_snprintf(astr, alen, "%s %s\n", answer->key, answer->value);
272 smartlist_add(answers, astr);
274 next = answer->next;
275 tor_free(answer->key);
276 tor_free(answer->value);
277 tor_free(answer);
278 answer = next;
283 msg = smartlist_join_strings(answers, "", 0, &msg_len);
284 send_control_message(conn, CONTROL_CMD_CONFVALUE,
285 (uint16_t)msg_len, msg_len?msg:NULL);
287 done:
288 if (answers) SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
289 if (questions) SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
290 smartlist_free(answers);
291 smartlist_free(questions);
292 tor_free(msg);
294 return 0;
297 /** Called when we get a SETEVENTS message: update conn->event_mask,
298 * and reply with DONE or ERROR. */
299 static int
300 handle_control_setevents(connection_t *conn, uint16_t len, const char *body)
302 uint16_t event_code;
303 uint32_t event_mask = 0;
304 if (len % 2) {
305 send_control_error(conn, ERR_SYNTAX,
306 "Odd number of bytes in setevents message");
307 return 0;
310 for (; len; len -= 2, body += 2) {
311 event_code = ntohs(get_uint16(body));
312 if (event_code < _EVENT_MIN || event_code > _EVENT_MAX) {
313 send_control_error(conn, ERR_UNRECOGNIZED_EVENT_CODE,
314 "Unrecognized event code");
315 return 0;
317 event_mask |= (1 << event_code);
320 conn->event_mask = event_mask;
322 update_global_event_mask();
323 send_control_done(conn);
324 return 0;
327 /** Called when we get an AUTHENTICATE message. Check whether the
328 * authentication is valid, and if so, update the connection's state to
329 * OPEN. Reply with DONE or ERROR.
331 static int
332 handle_control_authenticate(connection_t *conn, uint16_t len, const char *body)
334 or_options_t *options = get_options();
335 if (options->CookieAuthentication) {
336 if (len == AUTHENTICATION_COOKIE_LEN &&
337 !memcmp(authentication_cookie, body, len)) {
338 goto ok;
340 } else if (options->HashedControlPassword) {
341 char expected[S2K_SPECIFIER_LEN+DIGEST_LEN];
342 char received[DIGEST_LEN];
343 if (base64_decode(expected,sizeof(expected),
344 options->HashedControlPassword,
345 strlen(options->HashedControlPassword))<0) {
346 log_fn(LOG_WARN,"Couldn't decode HashedControlPassword: invalid base64");
347 goto err;
349 secret_to_key(received,DIGEST_LEN,body,len,expected);
350 if (!memcmp(expected+S2K_SPECIFIER_LEN, received, DIGEST_LEN))
351 goto ok;
352 goto err;
353 } else {
354 if (len == 0) {
355 /* if Tor doesn't demand any stronger authentication, then
356 * the controller can get in with a blank auth line. */
357 goto ok;
359 goto err;
362 err:
363 send_control_error(conn, ERR_REJECTED_AUTHENTICATION,"Authentication failed");
364 return 0;
366 log_fn(LOG_INFO, "Authenticated control connection (%d)", conn->s);
367 send_control_done(conn);
368 conn->state = CONTROL_CONN_STATE_OPEN;
369 return 0;
372 static int
373 handle_control_saveconf(connection_t *conn, uint16_t len,
374 const char *body)
376 if (save_current_config()<0) {
377 send_control_error(conn, ERR_INTERNAL,
378 "Unable to write configuration to disk.");
379 } else {
380 send_control_done(conn);
382 return 0;
385 /** Called when <b>conn</b> has no more bytes left on its outbuf. */
387 connection_control_finished_flushing(connection_t *conn) {
388 tor_assert(conn);
389 tor_assert(conn->type == CONN_TYPE_CONTROL);
391 connection_stop_writing(conn);
392 return 0;
395 /** Called when <b>conn</b> has gotten its socket closed. */
396 int connection_control_reached_eof(connection_t *conn) {
397 log_fn(LOG_INFO,"Control connection reached EOF. Closing.");
398 connection_mark_for_close(conn);
399 return 0;
402 /** Called when <b>conn</b> has received more bytes on its inbuf.
405 connection_control_process_inbuf(connection_t *conn) {
406 uint16_t body_len, command_type;
407 char *body;
409 tor_assert(conn);
410 tor_assert(conn->type == CONN_TYPE_CONTROL);
412 again:
413 /* Try to suck a control message from the buffer. */
414 switch (fetch_from_buf_control(conn->inbuf, &body_len, &command_type, &body))
416 case -1:
417 tor_free(body);
418 log_fn(LOG_WARN, "Error in control command. Failing.");
419 return -1;
420 case 0:
421 /* Control command not all here yet. Wait. */
422 return 0;
423 case 1:
424 /* We got a command. Process it. */
425 break;
426 default:
427 tor_assert(0);
430 /* We got a command. If we need authentication, only authentication
431 * commands will be considered. */
432 if (conn->state == CONTROL_CONN_STATE_NEEDAUTH &&
433 command_type != CONTROL_CMD_AUTHENTICATE) {
434 log_fn(LOG_WARN, "Rejecting '%s' command; authentication needed.",
435 control_cmd_to_string(command_type));
436 send_control_error(conn, ERR_UNAUTHORIZED, "Authentication required");
437 tor_free(body);
438 goto again;
441 /* Okay, we're willing to process the command. */
442 switch (command_type)
444 case CONTROL_CMD_SETCONF:
445 if (handle_control_setconf(conn, body_len, body))
446 return -1;
447 break;
448 case CONTROL_CMD_GETCONF:
449 if (handle_control_getconf(conn, body_len, body))
450 return -1;
451 break;
452 case CONTROL_CMD_SETEVENTS:
453 if (handle_control_setevents(conn, body_len, body))
454 return -1;
455 break;
456 case CONTROL_CMD_AUTHENTICATE:
457 if (handle_control_authenticate(conn, body_len, body))
458 return -1;
459 break;
460 case CONTROL_CMD_SAVECONF:
461 if (handle_control_saveconf(conn, body_len, body))
462 return -1;
463 break;
464 case CONTROL_CMD_ERROR:
465 case CONTROL_CMD_DONE:
466 case CONTROL_CMD_CONFVALUE:
467 case CONTROL_CMD_EVENT:
468 log_fn(LOG_WARN, "Received client-only '%s' command; ignoring.",
469 control_cmd_to_string(command_type));
470 send_control_error(conn, ERR_UNRECOGNIZED_TYPE,
471 "Command type only valid from server to tor client");
472 break;
473 default:
474 log_fn(LOG_WARN, "Received unrecognized command type %d; ignoring.",
475 (int)command_type);
476 send_control_error(conn, ERR_UNRECOGNIZED_TYPE,
477 "Unrecognized command type");
478 break;
480 tor_free(body);
481 goto again; /* There might be more data. */
484 /** Something has happened to circuit <b>circ</b>: tell any interested
485 * control connections. */
487 control_event_circuit_status(circuit_t *circ, circuit_status_event_t tp)
489 char *path, *msg;
490 size_t path_len;
491 if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS))
492 return 0;
493 tor_assert(circ);
494 tor_assert(CIRCUIT_IS_ORIGIN(circ));
496 path = circuit_list_path(circ,0);
497 path_len = strlen(path);
498 msg = tor_malloc(1+4+path_len+1); /* event, circid, path, NUL. */
499 msg[0] = (uint8_t) tp;
500 set_uint32(msg+1, htonl(circ->global_identifier));
501 strlcpy(msg+5,path,path_len+1);
503 send_control_event(EVENT_STREAM_STATUS, (uint16_t)(path_len+6), msg);
504 tor_free(path);
505 tor_free(msg);
506 return 0;
509 /** Something has happened to the stream associated with AP connection
510 * <b>conn</b>: tell any interested control connections. */
512 control_event_stream_status(connection_t *conn, stream_status_event_t tp)
514 char *msg;
515 size_t len;
516 tor_assert(conn->type == CONN_TYPE_AP);
517 tor_assert(conn->socks_request);
519 if (!EVENT_IS_INTERESTING(EVENT_STREAM_STATUS))
520 return 0;
522 len = strlen(conn->socks_request->address);
523 msg = tor_malloc(5+len+1);
524 msg[0] = (uint8_t) tp;
525 set_uint32(msg+1, htonl(conn->s)); /* ???? Is this a security problem? */
526 strlcpy(msg+5, conn->socks_request->address, len+1);
528 send_control_event(EVENT_STREAM_STATUS, (uint16_t)(5+len+1), msg);
529 tor_free(msg);
530 return 0;
533 /** Something has happened to the OR connection <b>conn</b>: tell any
534 * interested control connections. */
536 control_event_or_conn_status(connection_t *conn,or_conn_status_event_t tp)
538 char buf[HEX_DIGEST_LEN+3]; /* status, dollar, identity, NUL */
539 size_t len;
541 tor_assert(conn->type == CONN_TYPE_OR);
543 if (!EVENT_IS_INTERESTING(EVENT_OR_CONN_STATUS))
544 return 0;
546 buf[0] = (uint8_t)tp;
547 strlcpy(buf+1,conn->nickname,sizeof(buf)-1);
548 len = strlen(buf+1);
549 send_control_event(EVENT_OR_CONN_STATUS, (uint16_t)(len+1), buf);
550 return 0;
553 /** A second or more has elapsed: tell any interested control
554 * connections how much bandwidth we used. */
556 control_event_bandwidth_used(uint32_t n_read, uint32_t n_written)
558 char buf[8];
560 if (!EVENT_IS_INTERESTING(EVENT_BANDWIDTH_USED))
561 return 0;
563 set_uint32(buf, htonl(n_read));
564 set_uint32(buf+4, htonl(n_written));
565 send_control_event(EVENT_BANDWIDTH_USED, 8, buf);
567 return 0;
570 /** We got a log message: tell any interested control connections. */
571 void
572 control_event_logmsg(int severity, const char *msg)
574 size_t len;
575 if (severity > LOG_WARN) /* Less important than warning? ignore for now. */
576 return;
577 if (!EVENT_IS_INTERESTING(EVENT_WARNING))
578 return;
580 len = strlen(msg);
581 send_control_event(EVENT_WARNING, (uint16_t)(len+1), msg);
584 /** Choose a random authentication cookie and write it to disk.
585 * Anybody who can read the cookie from disk will be considered
586 * authorized to use the control connection. */
588 init_cookie_authentication(int enabled)
590 char fname[512];
592 if (!enabled) {
593 authentication_cookie_is_set = 0;
594 return 0;
597 tor_snprintf(fname, sizeof(fname), "%s/control_auth_cookie",
598 get_options()->DataDirectory);
599 crypto_rand(authentication_cookie, AUTHENTICATION_COOKIE_LEN);
600 authentication_cookie_is_set = 1;
601 if (write_bytes_to_file(fname, authentication_cookie,
602 AUTHENTICATION_COOKIE_LEN, 1)) {
603 log_fn(LOG_WARN,"Error writing authentication cookie.");
604 return -1;
607 return 0;