tor  0.4.2.0-alpha-dev
control.c
Go to the documentation of this file.
1 /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
2  * Copyright (c) 2007-2019, The Tor Project, Inc. */
3 /* See LICENSE for licensing information */
4 
35 #define CONTROL_MODULE_PRIVATE
36 #define CONTROL_PRIVATE
37 
38 #include "core/or/or.h"
39 #include "app/config/config.h"
40 #include "app/main/main.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"
53 #include "lib/evloop/procmon.h"
54 
55 #include "feature/control/control_connection_st.h"
56 
57 #ifdef HAVE_UNISTD_H
58 #include <unistd.h>
59 #endif
60 #ifdef HAVE_SYS_STAT_H
61 #include <sys/stat.h>
62 #endif
63 
68 {
69  tor_assert(c->magic == CONTROL_CONNECTION_MAGIC);
70  return DOWNCAST(control_connection_t, c);
71 }
72 
78 int
80 {
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>");
91 
92  /* We take ownership of this socket so that later, when we close it,
93  * we don't freak out. */
95 
96  if (set_socket_nonblocking(sock) < 0 ||
97  connection_add(conn) < 0) {
98  connection_free(conn);
99  return -1;
100  }
101 
102  control_conn->is_owning_control_connection = is_owner;
103 
104  if (connection_init_accepted_conn(conn, NULL) < 0) {
105  connection_mark_for_close(conn);
106  return -1;
107  }
108 
109  if (is_authenticated) {
111  }
112 
113  return 0;
114 }
115 
117 void
119 {
120  smartlist_t *lines;
121  char *joined = NULL;
122  const or_options_t *options = get_options();
123 
124  if (!options->ControlPortWriteToFile)
125  return;
126 
127  lines = smartlist_new();
128 
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;
136  }
137 #endif /* defined(AF_UNIX) */
138  smartlist_add_asprintf(lines, "PORT=%s:%d\n", conn->address, conn->port);
139  } SMARTLIST_FOREACH_END(conn);
140 
141  joined = smartlist_join_strings(lines, "", 0, NULL);
142 
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));
146  }
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);
152  }
153  }
154 #endif /* !defined(_WIN32) */
155  tor_free(joined);
156  SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
157  smartlist_free(lines);
158 }
159 
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 },
177 };
178 
180 int
182 {
183  tor_assert(conn);
184  return 0;
185 }
186 
188 int
190 {
191  tor_assert(conn);
192 
193  log_info(LD_CONTROL,"Control connection reached EOF. Closing.");
194  connection_mark_for_close(TO_CONN(conn));
195  return 0;
196 }
197 
200 static void
201 lost_owning_controller(const char *owner_type, const char *loss_manner)
202 {
203  log_notice(LD_CONTROL, "Owning controller %s has %s -- exiting now.",
204  owner_type, loss_manner);
205 
206  activate_signal(SIGTERM);
207 }
208 
210 void
212 {
213  tor_assert(conn);
214 
215  conn->event_mask = 0;
217 
218  /* Close all ephemeral Onion Services if any.
219  * The list and it's contents are scrubbed/freed in connection_free_.
220  */
221  if (conn->ephemeral_onion_services) {
223  if (rend_valid_v2_service_id(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 */
230  }
231  } SMARTLIST_FOREACH_END(cp);
232  }
233 
234  if (conn->is_owning_control_connection) {
235  lost_owning_controller("connection", "closed");
236  }
237 }
238 
241 static int
243 {
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;
255 }
256 
260 #define MAX_COMMAND_LINE_LENGTH (1024*1024)
261 
266 static int
268 {
269  return peek_buf_has_control0_command(conn->inbuf);
270 }
271 
272 static int
273 peek_connection_has_http_command(connection_t *conn)
274 {
275  return peek_buf_has_http_command(conn->inbuf);
276 }
277 
284 STATIC char *
286  size_t *data_len,
287  char **current_cmd_out)
288 {
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;
294 
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;
305  }
306  } else {
307  while (TOR_ISSPACE(*args) && *data_len) {
308  ++args;
309  --*data_len;
310  }
311  }
312 
313  return args;
314 }
315 
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";
341 
345 int
347 {
348  size_t data_len;
349  uint32_t cmd_data_len;
350  char *args;
351 
352  tor_assert(conn);
353  tor_assert(conn->base_.state == CONTROL_CONN_STATE_OPEN ||
354  conn->base_.state == CONTROL_CONN_STATE_NEEDAUTH);
355 
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;
360  }
361 
362  if (conn->base_.state == CONTROL_CONN_STATE_NEEDAUTH &&
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));
375 
376  connection_mark_and_flush(TO_CONN(conn));
377  return 0;
378  }
379 
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;
387  }
388 
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;
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));
407  }
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);
412  }
413  } while (r != 1);
414 
415  tor_assert(data_len);
416 
417  last_idx = conn->incoming_cmd_cur_len;
418  conn->incoming_cmd_cur_len += (int)data_len;
419 
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;
437  }
438  /* Otherwise, read another line. */
439  }
440  data_len = conn->incoming_cmd_cur_len;
441 
442  /* Okay, we now have a command sitting on conn->incoming_cmd. See if we
443  * recognize it.
444  */
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;
450 
451  /* If the connection is already closing, ignore further commands */
452  if (TO_CONN(conn)->marked_for_close) {
453  return 0;
454  }
455 
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;
461  }
462 
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;
468  }
469 
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;
474  }
475 
476  cmd_data_len = (uint32_t)data_len;
477  if (handle_control_command(conn, cmd_data_len, args) < 0)
478  return -1;
479 
480  conn->incoming_cmd_cur_len = 0;
481  goto again;
482 }
483 
487 static int network_is_live = 0;
488 
489 int
490 get_cached_network_liveness(void)
491 {
492  return network_is_live;
493 }
494 
495 void
496 set_cached_network_liveness(int liveness)
497 {
498  network_is_live = liveness;
499 }
500 
503 static char *owning_controller_process_spec = NULL;
504 
508 
511 static void
513 {
514  (void)unused;
515 
516  lost_owning_controller("process", "vanished");
517 }
518 
521 void
522 monitor_owning_controller_process(const char *process_spec)
523 {
524  const char *msg;
525 
528 
529  if (owning_controller_process_spec != NULL) {
530  if ((process_spec != NULL) && !strcmp(process_spec,
532  /* Same process -- return now, instead of disposing of and
533  * recreating the process-termination monitor. */
534  return;
535  }
536 
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);
541 
544  }
545 
548 
549  if (process_spec == NULL)
550  return;
551 
552  owning_controller_process_spec = tor_strdup(process_spec);
554  tor_process_monitor_new(tor_libevent_get_base(),
556  LD_CONTROL,
558  &msg);
559 
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);
566  }
567 }
568 
570 void
572 {
573  control_auth_free_all();
574  control_events_free_all();
575  control_cmd_free_all();
577 }
tor_socket_t s
Definition: connection_st.h:88
int set_socket_nonblocking(tor_socket_t sock)
Definition: socket.c:561
Header file for rendcommon.c.
#define CONN_TYPE_CONTROL_LISTENER
Definition: connection.h:38
Header file for control_auth.c.
#define SMARTLIST_FOREACH_BEGIN(sl, type, var)
#define TO_CONN(c)
Definition: or.h:735
void tor_addr_make_unspec(tor_addr_t *a)
Definition: address.c:225
tor_addr_t addr
Header file for connection.c.
void connection_write_str_to_buf(const char *s, control_connection_t *conn)
Definition: control_proto.c:30
static void set_uint16(void *cp, uint16_t v)
Definition: bytes.h:73
void tor_take_socket_ownership(tor_socket_t s)
Definition: socket.c:335
#define DOWNCAST(to, ptr)
Definition: or.h:110
uint8_t state
Definition: connection_st.h:44
Headers for procmon.c.
void monitor_owning_controller_process(const char *process_spec)
Definition: control.c:522
#define CONTROL_CONN_STATE_OPEN
Definition: control.h:19
Header file for config.c.
control_connection_t * TO_CONTROL_CONN(connection_t *c)
Definition: control.c:67
static int network_is_live
Definition: control.c:487
static int is_valid_initial_command(control_connection_t *conn, const char *cmd)
Definition: control.c:242
uint16_t port
void connection_control_closed(control_connection_t *conn)
Definition: control.c:211
#define tor_free(p)
Definition: malloc.h:52
void tor_shutdown_event_loop_and_exit(int exitcode)
Definition: mainloop.c:764
#define tor_fragile_assert()
Definition: util_bug.h:241
Header file for mainloop.c.
Header file for main.c.
unsigned int have_sent_protocolinfo
control_connection_t * control_connection_new(int socket_family)
Definition: connection.c:426
int handle_control_command(control_connection_t *conn, uint32_t cmd_data_len, char *args)
Definition: control_cmd.c:2380
#define SOCKET_OK(s)
Definition: nettypes.h:39
struct buf_t * inbuf
Definition: connection_st.h:93
tor_assert(buffer)
#define LD_CONTROL
Definition: log.h:77
void control_free_all(void)
Definition: control.c:571
int connection_control_reached_eof(control_connection_t *conn)
Definition: control.c:189
int tor_memeq(const void *a, const void *b, size_t sz)
Definition: di_ops.c:107
static int peek_connection_has_control0_command(connection_t *conn)
Definition: control.c:267
void control_update_global_event_mask(void)
int connection_control_process_inbuf(control_connection_t *conn)
Definition: control.c:346
#define CONTROL_CONN_STATE_NEEDAUTH
Definition: control.h:22
int connection_init_accepted_conn(connection_t *conn, const listener_connection_t *listener)
Definition: connection.c:1869
void smartlist_add_asprintf(struct smartlist_t *sl, const char *pattern,...)
Definition: smartlist.c:36
static tor_process_monitor_t * owning_controller_process_monitor
Definition: control.c:507
#define MAX_COMMAND_LINE_LENGTH
Definition: control.c:260
Master header file for Tor-specific functionality.
void control_event_bootstrap_reset(void)
int control_connection_add_local_fd(tor_socket_t sock, unsigned flags)
Definition: control.c:79
char * ControlPortWriteToFile
STATIC char * control_split_incoming_command(char *incoming_cmd, size_t *data_len, char **current_cmd_out)
Definition: control.c:285
int rend_valid_v2_service_id(const char *query)
Definition: rendcommon.c:719
static void owning_controller_procmon_cb(void *unused)
Definition: control.c:512
Header file for control_cmd.c.
int rend_service_del_ephemeral(const char *service_id)
Definition: rendservice.c:972
int ControlPortFileGroupReadable
Header file for rendservice.c.
#define tor_socket_t
Definition: nettypes.h:36
#define LD_FS
Definition: log.h:67
char * smartlist_join_strings(smartlist_t *sl, const char *join, int terminate, size_t *len_out)
Definition: smartlist.c:279
#define SMARTLIST_FOREACH(sl, type, var, cmd)
unsigned int is_owning_control_connection
void control_write_endreply(control_connection_t *conn, int code, const char *s)
int connection_control_finished_flushing(control_connection_t *conn)
Definition: control.c:181
Header file for control.c.
static char * owning_controller_process_spec
Definition: control.c:503
uint32_t magic
Definition: connection_st.h:41
Header file for control_proto.c.
Header file for connection_or.c.
smartlist_t * ephemeral_onion_services
Header file for control_events.c.
tor_process_monitor_t * tor_process_monitor_new(struct event_base *base, const char *process_spec, log_domain_mask_t log_domain, tor_procmon_callback_t cb, void *cb_arg, const char **msg)
Definition: procmon.c:181
int connection_buf_get_line(connection_t *conn, char *data, size_t *data_len)
Definition: connection.c:3892
static void lost_owning_controller(const char *owner_type, const char *loss_manner)
Definition: control.c:201
#define LD_BUG
Definition: log.h:83
void control_ports_write_to_file(void)
Definition: control.c:118