make dist: only include files from practracker dir intentionally.
[tor.git] / src / feature / control / control.c
blob436bf423cf24b3b102f61886b094b748bd22243d
1 /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
2 * Copyright (c) 2007-2019, The Tor Project, Inc. */
3 /* See LICENSE for licensing information */
5 /**
6 * \file control.c
7 * \brief Implementation for Tor's control-socket interface.
9 * A "controller" is an external program that monitors and controls a Tor
10 * instance via a text-based protocol. It connects to Tor via a connection
11 * to a local socket.
13 * The protocol is line-driven. The controller sends commands terminated by a
14 * CRLF. Tor sends lines that are either <em>replies</em> to what the
15 * controller has said, or <em>events</em> that Tor sends to the controller
16 * asynchronously based on occurrences in the Tor network model.
18 * See the control-spec.txt file in the torspec.git repository for full
19 * details on protocol.
21 * This module generally has two kinds of entry points: those based on having
22 * received a command on a controller socket, which are handled in
23 * connection_control_process_inbuf(), and dispatched to individual functions
24 * with names like control_handle_COMMANDNAME(); and those based on events
25 * that occur elsewhere in Tor, which are handled by functions with names like
26 * control_event_EVENTTYPE().
28 * Controller events are not sent immediately; rather, they are inserted into
29 * the queued_control_events array, and flushed later from
30 * flush_queued_events_cb(). Doing this simplifies our callgraph greatly,
31 * by limiting the number of places in Tor that can call back into the network
32 * stack.
33 **/
35 #define CONTROL_MODULE_PRIVATE
36 #define CONTROL_PRIVATE
38 #include "core/or/or.h"
39 #include "app/config/config.h"
40 #include "app/main/main.h"
41 #include "core/mainloop/connection.h"
42 #include "core/mainloop/mainloop.h"
43 #include "core/or/connection_or.h"
44 #include "core/proto/proto_control0.h"
45 #include "core/proto/proto_http.h"
46 #include "feature/control/control.h"
47 #include "feature/control/control_auth.h"
48 #include "feature/control/control_cmd.h"
49 #include "feature/control/control_events.h"
50 #include "feature/control/control_proto.h"
51 #include "feature/rend/rendcommon.h"
52 #include "feature/rend/rendservice.h"
53 #include "lib/evloop/procmon.h"
55 #include "feature/control/control_connection_st.h"
57 #ifdef HAVE_UNISTD_H
58 #include <unistd.h>
59 #endif
60 #ifdef HAVE_SYS_STAT_H
61 #include <sys/stat.h>
62 #endif
64 /** Convert a connection_t* to an control_connection_t*; assert if the cast is
65 * invalid. */
66 control_connection_t *
67 TO_CONTROL_CONN(connection_t *c)
69 tor_assert(c->magic == CONTROL_CONNECTION_MAGIC);
70 return DOWNCAST(control_connection_t, c);
73 /** Create and add a new controller connection on <b>sock</b>. If
74 * <b>CC_LOCAL_FD_IS_OWNER</b> is set in <b>flags</b>, this Tor process should
75 * exit when the connection closes. If <b>CC_LOCAL_FD_IS_AUTHENTICATED</b>
76 * is set, then the connection does not need to authenticate.
78 int
79 control_connection_add_local_fd(tor_socket_t sock, unsigned flags)
81 if (BUG(! SOCKET_OK(sock)))
82 return -1;
83 const int is_owner = !!(flags & CC_LOCAL_FD_IS_OWNER);
84 const int is_authenticated = !!(flags & CC_LOCAL_FD_IS_AUTHENTICATED);
85 control_connection_t *control_conn = control_connection_new(AF_UNSPEC);
86 connection_t *conn = TO_CONN(control_conn);
87 conn->s = sock;
88 tor_addr_make_unspec(&conn->addr);
89 conn->port = 1;
90 conn->address = tor_strdup("<local socket>");
92 /* We take ownership of this socket so that later, when we close it,
93 * we don't freak out. */
94 tor_take_socket_ownership(sock);
96 if (set_socket_nonblocking(sock) < 0 ||
97 connection_add(conn) < 0) {
98 connection_free(conn);
99 return -1;
102 control_conn->is_owning_control_connection = is_owner;
104 if (connection_init_accepted_conn(conn, NULL) < 0) {
105 connection_mark_for_close(conn);
106 return -1;
109 if (is_authenticated) {
110 conn->state = CONTROL_CONN_STATE_OPEN;
113 return 0;
116 /** Write all of the open control ports to ControlPortWriteToFile */
117 void
118 control_ports_write_to_file(void)
120 smartlist_t *lines;
121 char *joined = NULL;
122 const or_options_t *options = get_options();
124 if (!options->ControlPortWriteToFile)
125 return;
127 lines = smartlist_new();
129 SMARTLIST_FOREACH_BEGIN(get_connection_array(), const connection_t *, conn) {
130 if (conn->type != CONN_TYPE_CONTROL_LISTENER || conn->marked_for_close)
131 continue;
132 #ifdef AF_UNIX
133 if (conn->socket_family == AF_UNIX) {
134 smartlist_add_asprintf(lines, "UNIX_PORT=%s\n", conn->address);
135 continue;
137 #endif /* defined(AF_UNIX) */
138 smartlist_add_asprintf(lines, "PORT=%s:%d\n", conn->address, conn->port);
139 } SMARTLIST_FOREACH_END(conn);
141 joined = smartlist_join_strings(lines, "", 0, NULL);
143 if (write_str_to_file(options->ControlPortWriteToFile, joined, 0) < 0) {
144 log_warn(LD_CONTROL, "Writing %s failed: %s",
145 options->ControlPortWriteToFile, strerror(errno));
147 #ifndef _WIN32
148 if (options->ControlPortFileGroupReadable) {
149 if (chmod(options->ControlPortWriteToFile, 0640)) {
150 log_warn(LD_FS,"Unable to make %s group-readable.",
151 options->ControlPortWriteToFile);
154 #endif /* !defined(_WIN32) */
155 tor_free(joined);
156 SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
157 smartlist_free(lines);
160 const struct signal_name_t signal_table[] = {
161 { SIGHUP, "RELOAD" },
162 { SIGHUP, "HUP" },
163 { SIGINT, "SHUTDOWN" },
164 { SIGUSR1, "DUMP" },
165 { SIGUSR1, "USR1" },
166 { SIGUSR2, "DEBUG" },
167 { SIGUSR2, "USR2" },
168 { SIGTERM, "HALT" },
169 { SIGTERM, "TERM" },
170 { SIGTERM, "INT" },
171 { SIGNEWNYM, "NEWNYM" },
172 { SIGCLEARDNSCACHE, "CLEARDNSCACHE"},
173 { SIGHEARTBEAT, "HEARTBEAT"},
174 { SIGACTIVE, "ACTIVE" },
175 { SIGDORMANT, "DORMANT" },
176 { 0, NULL },
179 /** Called when <b>conn</b> has no more bytes left on its outbuf. */
181 connection_control_finished_flushing(control_connection_t *conn)
183 tor_assert(conn);
184 return 0;
187 /** Called when <b>conn</b> has gotten its socket closed. */
189 connection_control_reached_eof(control_connection_t *conn)
191 tor_assert(conn);
193 log_info(LD_CONTROL,"Control connection reached EOF. Closing.");
194 connection_mark_for_close(TO_CONN(conn));
195 return 0;
198 /** Shut down this Tor instance in the same way that SIGINT would, but
199 * with a log message appropriate for the loss of an owning controller. */
200 static void
201 lost_owning_controller(const char *owner_type, const char *loss_manner)
203 log_notice(LD_CONTROL, "Owning controller %s has %s -- exiting now.",
204 owner_type, loss_manner);
206 activate_signal(SIGTERM);
209 /** Called when <b>conn</b> is being freed. */
210 void
211 connection_control_closed(control_connection_t *conn)
213 tor_assert(conn);
215 conn->event_mask = 0;
216 control_update_global_event_mask();
218 /* Close all ephemeral Onion Services if any.
219 * The list and it's contents are scrubbed/freed in connection_free_.
221 if (conn->ephemeral_onion_services) {
222 SMARTLIST_FOREACH_BEGIN(conn->ephemeral_onion_services, char *, cp) {
223 if (rend_valid_v2_service_id(cp)) {
224 rend_service_del_ephemeral(cp);
225 } else if (hs_address_is_valid(cp)) {
226 hs_service_del_ephemeral(cp);
227 } else {
228 /* An invalid .onion in our list should NEVER happen */
229 tor_fragile_assert();
231 } SMARTLIST_FOREACH_END(cp);
234 if (conn->is_owning_control_connection) {
235 lost_owning_controller("connection", "closed");
239 /** Return true iff <b>cmd</b> is allowable (or at least forgivable) at this
240 * stage of the protocol. */
241 static int
242 is_valid_initial_command(control_connection_t *conn, const char *cmd)
244 if (conn->base_.state == CONTROL_CONN_STATE_OPEN)
245 return 1;
246 if (!strcasecmp(cmd, "PROTOCOLINFO"))
247 return (!conn->have_sent_protocolinfo &&
248 conn->safecookie_client_hash == NULL);
249 if (!strcasecmp(cmd, "AUTHCHALLENGE"))
250 return (conn->safecookie_client_hash == NULL);
251 if (!strcasecmp(cmd, "AUTHENTICATE") ||
252 !strcasecmp(cmd, "QUIT"))
253 return 1;
254 return 0;
257 /** Do not accept any control command of more than 1MB in length. Anything
258 * that needs to be anywhere near this long probably means that one of our
259 * interfaces is broken. */
260 #define MAX_COMMAND_LINE_LENGTH (1024*1024)
262 /** Wrapper around peek_buf_has_control0 command: presents the same
263 * interface as that underlying functions, but takes a connection_t intead of
264 * a buf_t.
266 static int
267 peek_connection_has_control0_command(connection_t *conn)
269 return peek_buf_has_control0_command(conn->inbuf);
272 static int
273 peek_connection_has_http_command(connection_t *conn)
275 return peek_buf_has_http_command(conn->inbuf);
279 * Helper: take a nul-terminated command of given length, and find where the
280 * command starts and the arguments begin. Separate them, allocate a new
281 * string in <b>current_cmd_out</b> for the command, and return a pointer
282 * to the arguments.
284 STATIC char *
285 control_split_incoming_command(char *incoming_cmd,
286 size_t *data_len,
287 char **current_cmd_out)
289 const bool is_multiline = *data_len && incoming_cmd[0] == '+';
290 size_t cmd_len = 0;
291 while (cmd_len < *data_len
292 && !TOR_ISSPACE(incoming_cmd[cmd_len]))
293 ++cmd_len;
295 *current_cmd_out = tor_memdup_nulterm(incoming_cmd, cmd_len);
296 char *args = incoming_cmd+cmd_len;
297 tor_assert(*data_len>=cmd_len);
298 *data_len -= cmd_len;
299 if (is_multiline) {
300 // Only match horizontal space: any line after the first is data,
301 // not arguments.
302 while ((*args == '\t' || *args == ' ') && *data_len) {
303 ++args;
304 --*data_len;
306 } else {
307 while (TOR_ISSPACE(*args) && *data_len) {
308 ++args;
309 --*data_len;
313 return args;
316 static const char CONTROLPORT_IS_NOT_AN_HTTP_PROXY_MSG[] =
317 "HTTP/1.0 501 Tor ControlPort is not an HTTP proxy"
318 "\r\nContent-Type: text/html; charset=iso-8859-1\r\n\r\n"
319 "<html>\n"
320 "<head>\n"
321 "<title>Tor's ControlPort is not an HTTP proxy</title>\n"
322 "</head>\n"
323 "<body>\n"
324 "<h1>Tor's ControlPort is not an HTTP proxy</h1>\n"
325 "<p>\n"
326 "It appears you have configured your web browser to use Tor's control port"
327 " as an HTTP proxy.\n"
328 "This is not correct: Tor's default SOCKS proxy port is 9050.\n"
329 "Please configure your client accordingly.\n"
330 "</p>\n"
331 "<p>\n"
332 "See <a href=\"https://www.torproject.org/documentation.html\">"
333 "https://www.torproject.org/documentation.html</a> for more "
334 "information.\n"
335 "<!-- Plus this comment, to make the body response more than 512 bytes, so "
336 " IE will be willing to display it. Comment comment comment comment "
337 " comment comment comment comment comment comment comment comment.-->\n"
338 "</p>\n"
339 "</body>\n"
340 "</html>\n";
342 /** Called when data has arrived on a v1 control connection: Try to fetch
343 * commands from conn->inbuf, and execute them.
346 connection_control_process_inbuf(control_connection_t *conn)
348 size_t data_len;
349 uint32_t cmd_data_len;
350 char *args;
352 tor_assert(conn);
353 tor_assert(conn->base_.state == CONTROL_CONN_STATE_OPEN ||
354 conn->base_.state == CONTROL_CONN_STATE_NEEDAUTH);
356 if (!conn->incoming_cmd) {
357 conn->incoming_cmd = tor_malloc(1024);
358 conn->incoming_cmd_len = 1024;
359 conn->incoming_cmd_cur_len = 0;
362 if (conn->base_.state == CONTROL_CONN_STATE_NEEDAUTH &&
363 peek_connection_has_control0_command(TO_CONN(conn))) {
364 /* Detect v0 commands and send a "no more v0" message. */
365 size_t body_len;
366 char buf[128];
367 set_uint16(buf+2, htons(0x0000)); /* type == error */
368 set_uint16(buf+4, htons(0x0001)); /* code == internal error */
369 strlcpy(buf+6, "The v0 control protocol is not supported by Tor 0.1.2.17 "
370 "and later; upgrade your controller.",
371 sizeof(buf)-6);
372 body_len = 2+strlen(buf+6)+2; /* code, msg, nul. */
373 set_uint16(buf+0, htons(body_len));
374 connection_buf_add(buf, 4+body_len, TO_CONN(conn));
376 connection_mark_and_flush(TO_CONN(conn));
377 return 0;
380 /* If the user has the HTTP proxy port and the control port confused. */
381 if (conn->base_.state == CONTROL_CONN_STATE_NEEDAUTH &&
382 peek_connection_has_http_command(TO_CONN(conn))) {
383 connection_write_str_to_buf(CONTROLPORT_IS_NOT_AN_HTTP_PROXY_MSG, conn);
384 log_notice(LD_CONTROL, "Received HTTP request on ControlPort");
385 connection_mark_and_flush(TO_CONN(conn));
386 return 0;
389 again:
390 while (1) {
391 size_t last_idx;
392 int r;
393 /* First, fetch a line. */
394 do {
395 data_len = conn->incoming_cmd_len - conn->incoming_cmd_cur_len;
396 r = connection_buf_get_line(TO_CONN(conn),
397 conn->incoming_cmd+conn->incoming_cmd_cur_len,
398 &data_len);
399 if (r == 0)
400 /* Line not all here yet. Wait. */
401 return 0;
402 else if (r == -1) {
403 if (data_len + conn->incoming_cmd_cur_len > MAX_COMMAND_LINE_LENGTH) {
404 control_write_endreply(conn, 500, "Line too long.");
405 connection_stop_reading(TO_CONN(conn));
406 connection_mark_and_flush(TO_CONN(conn));
408 while (conn->incoming_cmd_len < data_len+conn->incoming_cmd_cur_len)
409 conn->incoming_cmd_len *= 2;
410 conn->incoming_cmd = tor_realloc(conn->incoming_cmd,
411 conn->incoming_cmd_len);
413 } while (r != 1);
415 tor_assert(data_len);
417 last_idx = conn->incoming_cmd_cur_len;
418 conn->incoming_cmd_cur_len += (int)data_len;
420 /* We have appended a line to incoming_cmd. Is the command done? */
421 if (last_idx == 0 && *conn->incoming_cmd != '+')
422 /* One line command, didn't start with '+'. */
423 break;
424 /* XXXX this code duplication is kind of dumb. */
425 if (last_idx+3 == conn->incoming_cmd_cur_len &&
426 tor_memeq(conn->incoming_cmd + last_idx, ".\r\n", 3)) {
427 /* Just appended ".\r\n"; we're done. Remove it. */
428 conn->incoming_cmd[last_idx] = '\0';
429 conn->incoming_cmd_cur_len -= 3;
430 break;
431 } else if (last_idx+2 == conn->incoming_cmd_cur_len &&
432 tor_memeq(conn->incoming_cmd + last_idx, ".\n", 2)) {
433 /* Just appended ".\n"; we're done. Remove it. */
434 conn->incoming_cmd[last_idx] = '\0';
435 conn->incoming_cmd_cur_len -= 2;
436 break;
438 /* Otherwise, read another line. */
440 data_len = conn->incoming_cmd_cur_len;
442 /* Okay, we now have a command sitting on conn->incoming_cmd. See if we
443 * recognize it.
445 tor_free(conn->current_cmd);
446 args = control_split_incoming_command(conn->incoming_cmd, &data_len,
447 &conn->current_cmd);
448 if (BUG(!conn->current_cmd))
449 return -1;
451 /* If the connection is already closing, ignore further commands */
452 if (TO_CONN(conn)->marked_for_close) {
453 return 0;
456 /* Otherwise, Quit is always valid. */
457 if (!strcasecmp(conn->current_cmd, "QUIT")) {
458 control_write_endreply(conn, 250, "closing connection");
459 connection_mark_and_flush(TO_CONN(conn));
460 return 0;
463 if (conn->base_.state == CONTROL_CONN_STATE_NEEDAUTH &&
464 !is_valid_initial_command(conn, conn->current_cmd)) {
465 control_write_endreply(conn, 514, "Authentication required.");
466 connection_mark_for_close(TO_CONN(conn));
467 return 0;
470 if (data_len >= UINT32_MAX) {
471 control_write_endreply(conn, 500, "A 4GB command? Nice try.");
472 connection_mark_for_close(TO_CONN(conn));
473 return 0;
476 cmd_data_len = (uint32_t)data_len;
477 if (handle_control_command(conn, cmd_data_len, args) < 0)
478 return -1;
480 conn->incoming_cmd_cur_len = 0;
481 goto again;
484 /** Cached liveness for network liveness events and GETINFO
487 static int network_is_live = 0;
490 get_cached_network_liveness(void)
492 return network_is_live;
495 void
496 set_cached_network_liveness(int liveness)
498 network_is_live = liveness;
501 /** A copy of the process specifier of Tor's owning controller, or
502 * NULL if this Tor instance is not currently owned by a process. */
503 static char *owning_controller_process_spec = NULL;
505 /** A process-termination monitor for Tor's owning controller, or NULL
506 * if this Tor instance is not currently owned by a process. */
507 static tor_process_monitor_t *owning_controller_process_monitor = NULL;
509 /** Process-termination monitor callback for Tor's owning controller
510 * process. */
511 static void
512 owning_controller_procmon_cb(void *unused)
514 (void)unused;
516 lost_owning_controller("process", "vanished");
519 /** Set <b>process_spec</b> as Tor's owning controller process.
520 * Exit on failure. */
521 void
522 monitor_owning_controller_process(const char *process_spec)
524 const char *msg;
526 tor_assert((owning_controller_process_spec == NULL) ==
527 (owning_controller_process_monitor == NULL));
529 if (owning_controller_process_spec != NULL) {
530 if ((process_spec != NULL) && !strcmp(process_spec,
531 owning_controller_process_spec)) {
532 /* Same process -- return now, instead of disposing of and
533 * recreating the process-termination monitor. */
534 return;
537 /* We are currently owned by a process, and we should no longer be
538 * owned by it. Free the process-termination monitor. */
539 tor_process_monitor_free(owning_controller_process_monitor);
540 owning_controller_process_monitor = NULL;
542 tor_free(owning_controller_process_spec);
543 owning_controller_process_spec = NULL;
546 tor_assert((owning_controller_process_spec == NULL) &&
547 (owning_controller_process_monitor == NULL));
549 if (process_spec == NULL)
550 return;
552 owning_controller_process_spec = tor_strdup(process_spec);
553 owning_controller_process_monitor =
554 tor_process_monitor_new(tor_libevent_get_base(),
555 owning_controller_process_spec,
556 LD_CONTROL,
557 owning_controller_procmon_cb, NULL,
558 &msg);
560 if (owning_controller_process_monitor == NULL) {
561 log_err(LD_BUG, "Couldn't create process-termination monitor for "
562 "owning controller: %s. Exiting.",
563 msg);
564 owning_controller_process_spec = NULL;
565 tor_shutdown_event_loop_and_exit(1);
569 /** Free any leftover allocated memory of the control.c subsystem. */
570 void
571 control_free_all(void)
573 control_auth_free_all();
574 control_events_free_all();
575 control_cmd_free_all();
576 control_event_bootstrap_reset();