tor  0.4.1.0-alpha-dev
control.c
Go to the documentation of this file.
1 
2 /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3  * Copyright (c) 2007-2019, The Tor Project, Inc. */
4 /* See LICENSE for licensing information */
5 
36 #define CONTROL_PRIVATE
37 #define OCIRC_EVENT_PRIVATE
38 
39 #include "core/or/or.h"
40 #include "app/config/config.h"
41 #include "app/config/confparse.h"
42 #include "app/main/main.h"
44 #include "core/mainloop/mainloop.h"
45 #include "core/or/channel.h"
46 #include "core/or/channeltls.h"
47 #include "core/or/circuitbuild.h"
48 #include "core/or/circuitlist.h"
49 #include "core/or/circuitstats.h"
50 #include "core/or/circuituse.h"
51 #include "core/or/command.h"
53 #include "core/or/connection_or.h"
54 #include "core/or/ocirc_event.h"
55 #include "core/or/policies.h"
56 #include "core/or/reasons.h"
57 #include "core/or/versions.h"
58 #include "core/proto/proto_control0.h"
59 #include "core/proto/proto_http.h"
60 #include "feature/client/addressmap.h"
61 #include "feature/client/bridges.h"
62 #include "feature/client/dnsserv.h"
66 #include "feature/control/getinfo_geoip.h"
72 #include "feature/hs/hs_cache.h"
73 #include "feature/hs/hs_common.h"
74 #include "feature/hs/hs_control.h"
83 #include "feature/relay/router.h"
85 #include "feature/relay/selftest.h"
88 #include "feature/rend/rendparse.h"
91 #include "feature/stats/predict_ports.h"
92 #include "lib/buf/buffers.h"
95 #include "lib/encoding/confline.h"
97 #include "lib/version/torversion.h"
98 
99 #include "feature/dircache/cached_dir_st.h"
100 #include "feature/control/control_connection_st.h"
101 #include "core/or/cpath_build_state_st.h"
102 #include "core/or/entry_connection_st.h"
103 #include "feature/nodelist/extrainfo_st.h"
104 #include "feature/nodelist/networkstatus_st.h"
105 #include "feature/nodelist/node_st.h"
106 #include "core/or/or_connection_st.h"
107 #include "core/or/or_circuit_st.h"
108 #include "core/or/origin_circuit_st.h"
109 #include "feature/nodelist/microdesc_st.h"
110 #include "feature/rend/rend_authorized_client_st.h"
111 #include "feature/rend/rend_encoded_v2_service_descriptor_st.h"
112 #include "feature/rend/rend_service_descriptor_st.h"
113 #include "feature/nodelist/routerinfo_st.h"
114 #include "feature/nodelist/routerlist_st.h"
115 #include "core/or/socks_request_st.h"
116 
117 #ifdef HAVE_UNISTD_H
118 #include <unistd.h>
119 #endif
120 #ifdef HAVE_SYS_STAT_H
121 #include <sys/stat.h>
122 #endif
123 
124 #ifndef _WIN32
125 #include <pwd.h>
126 #include <sys/resource.h>
127 #endif
128 
130 #include "lib/evloop/procmon.h"
132 
135 #define STATE_IS_OPEN(s) ((s) == CONTROL_CONN_STATE_OPEN)
136 
143 typedef uint64_t event_mask_t;
144 
148 
150 static int disable_log_messages = 0;
151 
154 #define EVENT_IS_INTERESTING(e) \
155  (!! (global_event_mask & EVENT_MASK_(e)))
156 
158 #define ANY_EVENT_IS_INTERESTING(e) \
159  (!! (global_event_mask & (e)))
160 
163 #define AUTHENTICATION_COOKIE_LEN 32
164 
171 static uint8_t *authentication_cookie = NULL;
172 
173 #define SAFECOOKIE_SERVER_TO_CONTROLLER_CONSTANT \
174  "Tor safe cookie authentication server-to-controller hash"
175 #define SAFECOOKIE_CONTROLLER_TO_SERVER_CONSTANT \
176  "Tor safe cookie authentication controller-to-server hash"
177 #define SAFECOOKIE_SERVER_NONCE_LEN DIGEST256_LEN
178 
183 
185  const char *format, ...)
186  CHECK_PRINTF(2,3);
187 static void send_control_event_impl(uint16_t event,
188  const char *format, va_list ap)
189  CHECK_PRINTF(2,0);
190 static int control_event_status(int type, int severity, const char *format,
191  va_list args)
192  CHECK_PRINTF(3,0);
193 
194 static void send_control_done(control_connection_t *conn);
195 static void send_control_event(uint16_t event,
196  const char *format, ...)
197  CHECK_PRINTF(2,3);
198 static int handle_control_setconf(control_connection_t *conn, uint32_t len,
199  char *body);
200 static int handle_control_resetconf(control_connection_t *conn, uint32_t len,
201  char *body);
202 static int handle_control_getconf(control_connection_t *conn, uint32_t len,
203  const char *body);
204 static int handle_control_loadconf(control_connection_t *conn, uint32_t len,
205  const char *body);
206 static int handle_control_setevents(control_connection_t *conn, uint32_t len,
207  const char *body);
209  uint32_t len,
210  const char *body);
211 static int handle_control_signal(control_connection_t *conn, uint32_t len,
212  const char *body);
213 static int handle_control_mapaddress(control_connection_t *conn, uint32_t len,
214  const char *body);
215 static char *list_getinfo_options(void);
216 static int handle_control_getinfo(control_connection_t *conn, uint32_t len,
217  const char *body);
219  uint32_t len,
220  const char *body);
222  uint32_t len, const char *body);
224  uint32_t len,
225  const char *body);
227  uint32_t len,
228  const char *body);
230  uint32_t len,
231  const char *body);
232 static int handle_control_closestream(control_connection_t *conn, uint32_t len,
233  const char *body);
235  uint32_t len,
236  const char *body);
237 static int handle_control_resolve(control_connection_t *conn, uint32_t len,
238  const char *body);
240  uint32_t len,
241  const char *body);
242 static int handle_control_hsfetch(control_connection_t *conn, uint32_t len,
243  const char *body);
244 static int handle_control_hspost(control_connection_t *conn, uint32_t len,
245  const char *body);
246 static int handle_control_add_onion(control_connection_t *conn, uint32_t len,
247  const char *body);
248 static int handle_control_del_onion(control_connection_t *conn, uint32_t len,
249  const char *body);
250 static int write_stream_target_to_buf(entry_connection_t *conn, char *buf,
251  size_t len);
252 static void orconn_target_get_name(char *buf, size_t len,
253  or_connection_t *conn);
254 
255 static int get_cached_network_liveness(void);
256 static void set_cached_network_liveness(int liveness);
257 
258 static void flush_queued_events_cb(mainloop_event_t *event, void *arg);
259 
260 static char * download_status_to_string(const download_status_t *dl);
261 static void control_get_bytes_rw_last_sec(uint64_t *r, uint64_t *w);
262 
267 {
268  tor_assert(c->magic == CONTROL_CONNECTION_MAGIC);
269  return DOWNCAST(control_connection_t, c);
270 }
271 
274 static inline int
276 {
277  switch (event) {
278  case EVENT_DEBUG_MSG: return LOG_DEBUG;
279  case EVENT_INFO_MSG: return LOG_INFO;
280  case EVENT_NOTICE_MSG: return LOG_NOTICE;
281  case EVENT_WARN_MSG: return LOG_WARN;
282  case EVENT_ERR_MSG: return LOG_ERR;
283  default: return -1;
284  }
285 }
286 
288 static inline int
290 {
291  switch (severity) {
292  case LOG_DEBUG: return EVENT_DEBUG_MSG;
293  case LOG_INFO: return EVENT_INFO_MSG;
294  case LOG_NOTICE: return EVENT_NOTICE_MSG;
295  case LOG_WARN: return EVENT_WARN_MSG;
296  case LOG_ERR: return EVENT_ERR_MSG;
297  default: return -1;
298  }
299 }
300 
302 static void
304 {
305  origin_circuit_t *ocirc;
306  SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
307  if (!CIRCUIT_IS_ORIGIN(circ))
308  continue;
309  ocirc = TO_ORIGIN_CIRCUIT(circ);
310  ocirc->n_written_circ_bw = ocirc->n_read_circ_bw = 0;
313  }
314  SMARTLIST_FOREACH_END(circ);
315 }
316 
319 void
321 {
322  smartlist_t *conns = get_connection_array();
323  event_mask_t old_mask, new_mask;
324  old_mask = global_event_mask;
325  int any_old_per_sec_events = control_any_per_second_event_enabled();
326 
327  global_event_mask = 0;
328  SMARTLIST_FOREACH(conns, connection_t *, _conn,
329  {
330  if (_conn->type == CONN_TYPE_CONTROL &&
331  STATE_IS_OPEN(_conn->state)) {
332  control_connection_t *conn = TO_CONTROL_CONN(_conn);
333  global_event_mask |= conn->event_mask;
334  }
335  });
336 
337  new_mask = global_event_mask;
338 
339  /* Handle the aftermath. Set up the log callback to tell us only what
340  * we want to hear...*/
342 
343  /* Macro: true if ev was false before and is true now. */
344 #define NEWLY_ENABLED(ev) \
345  (! (old_mask & (ev)) && (new_mask & (ev)))
346 
347  /* ...then, if we've started logging stream or circ bw, clear the
348  * appropriate fields. */
349  if (NEWLY_ENABLED(EVENT_STREAM_BANDWIDTH_USED)) {
350  SMARTLIST_FOREACH(conns, connection_t *, conn,
351  {
352  if (conn->type == CONN_TYPE_AP) {
353  edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
354  edge_conn->n_written = edge_conn->n_read = 0;
355  }
356  });
357  }
358  if (NEWLY_ENABLED(EVENT_CIRC_BANDWIDTH_USED)) {
360  }
361  if (NEWLY_ENABLED(EVENT_BANDWIDTH_USED)) {
362  uint64_t r, w;
364  }
365  if (any_old_per_sec_events != control_any_per_second_event_enabled()) {
366  rescan_periodic_events(get_options());
367  }
368 
369 #undef NEWLY_ENABLED
370 }
371 
375 void
377 {
378  int i;
379  int min_log_event=EVENT_ERR_MSG, max_log_event=EVENT_DEBUG_MSG;
380 
381  for (i = EVENT_DEBUG_MSG; i <= EVENT_ERR_MSG; ++i) {
382  if (EVENT_IS_INTERESTING(i)) {
383  min_log_event = i;
384  break;
385  }
386  }
387  for (i = EVENT_ERR_MSG; i >= EVENT_DEBUG_MSG; --i) {
388  if (EVENT_IS_INTERESTING(i)) {
389  max_log_event = i;
390  break;
391  }
392  }
393  if (EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL)) {
394  if (min_log_event > EVENT_NOTICE_MSG)
395  min_log_event = EVENT_NOTICE_MSG;
396  if (max_log_event < EVENT_ERR_MSG)
397  max_log_event = EVENT_ERR_MSG;
398  }
399  if (min_log_event <= max_log_event)
401  event_to_log_severity(max_log_event),
403  else
406 }
407 
412 int
414 {
415  return EVENT_IS_INTERESTING(event);
416 }
417 
419 int
421 {
423  EVENT_MASK_(EVENT_BANDWIDTH_USED) |
424  EVENT_MASK_(EVENT_CELL_STATS) |
425  EVENT_MASK_(EVENT_CIRC_BANDWIDTH_USED) |
426  EVENT_MASK_(EVENT_CONN_BW) |
427  EVENT_MASK_(EVENT_STREAM_BANDWIDTH_USED)
428  );
429 }
430 
431 /* The value of 'get_bytes_read()' the previous time that
432  * control_get_bytes_rw_last_sec() as called. */
433 static uint64_t stats_prev_n_read = 0;
434 /* The value of 'get_bytes_written()' the previous time that
435  * control_get_bytes_rw_last_sec() as called. */
436 static uint64_t stats_prev_n_written = 0;
437 
444 static void
446  uint64_t *n_written)
447 {
448  const uint64_t stats_n_bytes_read = get_bytes_read();
449  const uint64_t stats_n_bytes_written = get_bytes_written();
450 
451  *n_read = stats_n_bytes_read - stats_prev_n_read;
452  *n_written = stats_n_bytes_written - stats_prev_n_written;
453  stats_prev_n_read = stats_n_bytes_read;
454  stats_prev_n_written = stats_n_bytes_written;
455 }
456 
461 void
463 {
465  return;
466 
467  uint64_t bytes_read, bytes_written;
468  control_get_bytes_rw_last_sec(&bytes_read, &bytes_written);
469  control_event_bandwidth_used((uint32_t)bytes_read,(uint32_t)bytes_written);
470 
475 }
476 
480 static inline void
482 {
483  size_t len = strlen(s);
484  connection_buf_add(s, len, TO_CONN(conn));
485 }
486 
494 STATIC size_t
495 write_escaped_data(const char *data, size_t len, char **out)
496 {
497  tor_assert(len < SIZE_MAX - 9);
498  size_t sz_out = len+8+1;
499  char *outp;
500  const char *start = data, *end;
501  size_t i;
502  int start_of_line;
503  for (i=0; i < len; ++i) {
504  if (data[i] == '\n') {
505  sz_out += 2; /* Maybe add a CR; maybe add a dot. */
506  if (sz_out >= SIZE_T_CEILING) {
507  log_warn(LD_BUG, "Input to write_escaped_data was too long");
508  *out = tor_strdup(".\r\n");
509  return 3;
510  }
511  }
512  }
513  *out = outp = tor_malloc(sz_out);
514  end = data+len;
515  start_of_line = 1;
516  while (data < end) {
517  if (*data == '\n') {
518  if (data > start && data[-1] != '\r')
519  *outp++ = '\r';
520  start_of_line = 1;
521  } else if (*data == '.') {
522  if (start_of_line) {
523  start_of_line = 0;
524  *outp++ = '.';
525  }
526  } else {
527  start_of_line = 0;
528  }
529  *outp++ = *data++;
530  }
531  if (outp < *out+2 || fast_memcmp(outp-2, "\r\n", 2)) {
532  *outp++ = '\r';
533  *outp++ = '\n';
534  }
535  *outp++ = '.';
536  *outp++ = '\r';
537  *outp++ = '\n';
538  *outp = '\0'; /* NUL-terminate just in case. */
539  tor_assert(outp >= *out);
540  tor_assert((size_t)(outp - *out) <= sz_out);
541  return outp - *out;
542 }
543 
550 STATIC size_t
551 read_escaped_data(const char *data, size_t len, char **out)
552 {
553  char *outp;
554  const char *next;
555  const char *end;
556 
557  *out = outp = tor_malloc(len+1);
558 
559  end = data+len;
560 
561  while (data < end) {
562  /* we're at the start of a line. */
563  if (*data == '.')
564  ++data;
565  next = memchr(data, '\n', end-data);
566  if (next) {
567  size_t n_to_copy = next-data;
568  /* Don't copy a CR that precedes this LF. */
569  if (n_to_copy && *(next-1) == '\r')
570  --n_to_copy;
571  memcpy(outp, data, n_to_copy);
572  outp += n_to_copy;
573  data = next+1; /* This will point at the start of the next line,
574  * or the end of the string, or a period. */
575  } else {
576  memcpy(outp, data, end-data);
577  outp += (end-data);
578  *outp = '\0';
579  return outp - *out;
580  }
581  *outp++ = '\n';
582  }
583 
584  *outp = '\0';
585  return outp - *out;
586 }
587 
591 static inline int
592 get_escaped_string_length(const char *start, size_t in_len_max,
593  int *chars_out)
594 {
595  const char *cp, *end;
596  int chars = 0;
597 
598  if (*start != '\"')
599  return -1;
600 
601  cp = start+1;
602  end = start+in_len_max;
603 
604  /* Calculate length. */
605  while (1) {
606  if (cp >= end) {
607  return -1; /* Too long. */
608  } else if (*cp == '\\') {
609  if (++cp == end)
610  return -1; /* Can't escape EOS. */
611  ++cp;
612  ++chars;
613  } else if (*cp == '\"') {
614  break;
615  } else {
616  ++cp;
617  ++chars;
618  }
619  }
620  if (chars_out)
621  *chars_out = chars;
622  return (int)(cp - start+1);
623 }
624 
627 static const char *
628 extract_escaped_string(const char *start, size_t in_len_max,
629  char **out, size_t *out_len)
630 {
631  int length = get_escaped_string_length(start, in_len_max, NULL);
632  if (length<0)
633  return NULL;
634  *out_len = length;
635  *out = tor_strndup(start, *out_len);
636  return start+length;
637 }
638 
647 static const char *
648 decode_escaped_string(const char *start, size_t in_len_max,
649  char **out, size_t *out_len)
650 {
651  const char *cp, *end;
652  char *outp;
653  int len, n_chars = 0;
654 
655  len = get_escaped_string_length(start, in_len_max, &n_chars);
656  if (len<0)
657  return NULL;
658 
659  end = start+len-1; /* Index of last quote. */
660  tor_assert(*end == '\"');
661  outp = *out = tor_malloc(len+1);
662  *out_len = n_chars;
663 
664  cp = start+1;
665  while (cp < end) {
666  if (*cp == '\\')
667  ++cp;
668  *outp++ = *cp++;
669  }
670  *outp = '\0';
671  tor_assert((outp - *out) == (int)*out_len);
672 
673  return end+1;
674 }
675 
681 int
683 {
684  if (BUG(! SOCKET_OK(sock)))
685  return -1;
686  const int is_owner = !!(flags & CC_LOCAL_FD_IS_OWNER);
687  const int is_authenticated = !!(flags & CC_LOCAL_FD_IS_AUTHENTICATED);
688  control_connection_t *control_conn = control_connection_new(AF_UNSPEC);
689  connection_t *conn = TO_CONN(control_conn);
690  conn->s = sock;
691  tor_addr_make_unspec(&conn->addr);
692  conn->port = 1;
693  conn->address = tor_strdup("<local socket>");
694 
695  /* We take ownership of this socket so that later, when we close it,
696  * we don't freak out. */
698 
699  if (set_socket_nonblocking(sock) < 0 ||
700  connection_add(conn) < 0) {
701  connection_free(conn);
702  return -1;
703  }
704 
705  control_conn->is_owning_control_connection = is_owner;
706 
707  if (connection_init_accepted_conn(conn, NULL) < 0) {
708  connection_mark_for_close(conn);
709  return -1;
710  }
711 
712  if (is_authenticated) {
714  }
715 
716  return 0;
717 }
718 
721 static void
722 connection_printf_to_buf(control_connection_t *conn, const char *format, ...)
723 {
724  va_list ap;
725  char *buf = NULL;
726  int len;
727 
728  va_start(ap,format);
729  len = tor_vasprintf(&buf, format, ap);
730  va_end(ap);
731 
732  if (len < 0) {
733  log_err(LD_BUG, "Unable to format string for controller.");
734  tor_assert(0);
735  }
736 
737  connection_buf_add(buf, (size_t)len, TO_CONN(conn));
738 
739  tor_free(buf);
740 }
741 
743 void
745 {
746  smartlist_t *lines;
747  char *joined = NULL;
748  const or_options_t *options = get_options();
749 
750  if (!options->ControlPortWriteToFile)
751  return;
752 
753  lines = smartlist_new();
754 
755  SMARTLIST_FOREACH_BEGIN(get_connection_array(), const connection_t *, conn) {
756  if (conn->type != CONN_TYPE_CONTROL_LISTENER || conn->marked_for_close)
757  continue;
758 #ifdef AF_UNIX
759  if (conn->socket_family == AF_UNIX) {
760  smartlist_add_asprintf(lines, "UNIX_PORT=%s\n", conn->address);
761  continue;
762  }
763 #endif /* defined(AF_UNIX) */
764  smartlist_add_asprintf(lines, "PORT=%s:%d\n", conn->address, conn->port);
765  } SMARTLIST_FOREACH_END(conn);
766 
767  joined = smartlist_join_strings(lines, "", 0, NULL);
768 
769  if (write_str_to_file(options->ControlPortWriteToFile, joined, 0) < 0) {
770  log_warn(LD_CONTROL, "Writing %s failed: %s",
771  options->ControlPortWriteToFile, strerror(errno));
772  }
773 #ifndef _WIN32
774  if (options->ControlPortFileGroupReadable) {
775  if (chmod(options->ControlPortWriteToFile, 0640)) {
776  log_warn(LD_FS,"Unable to make %s group-readable.",
777  options->ControlPortWriteToFile);
778  }
779  }
780 #endif /* !defined(_WIN32) */
781  tor_free(joined);
782  SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
783  smartlist_free(lines);
784 }
785 
787 static void
789 {
790  connection_write_str_to_buf("250 OK\r\n", conn);
791 }
792 
795 typedef struct queued_event_s {
796  uint16_t event;
797  char *msg;
799 
803 
807 
810 
813 
817 
818 void
819 control_initialize_event_queue(void)
820 {
821  if (queued_control_events == NULL) {
822  queued_control_events = smartlist_new();
823  }
824 
825  if (flush_queued_events_event == NULL) {
826  struct event_base *b = tor_libevent_get_base();
827  if (b) {
831  }
832  }
833 
834  if (queued_control_events_lock == NULL) {
837  }
838 }
839 
840 static int *
841 get_block_event_queue(void)
842 {
844  if (PREDICT_UNLIKELY(val == NULL)) {
845  val = tor_malloc_zero(sizeof(int));
847  }
848  return val;
849 }
850 
862 MOCK_IMPL(STATIC void,
863 queue_control_event_string,(uint16_t event, char *msg))
864 {
865  /* This is redundant with checks done elsewhere, but it's a last-ditch
866  * attempt to avoid queueing something we shouldn't have to queue. */
867  if (PREDICT_UNLIKELY( ! EVENT_IS_INTERESTING(event) )) {
868  tor_free(msg);
869  return;
870  }
871 
872  int *block_event_queue = get_block_event_queue();
873  if (*block_event_queue) {
874  tor_free(msg);
875  return;
876  }
877 
878  queued_event_t *ev = tor_malloc(sizeof(*ev));
879  ev->event = event;
880  ev->msg = msg;
881 
882  /* No queueing an event while queueing an event */
883  ++*block_event_queue;
884 
888 
889  int activate_event = 0;
891  activate_event = 1;
893  }
894 
896 
897  --*block_event_queue;
898 
899  /* We just put an event on the queue; mark the queue to be
900  * flushed. We only do this from the main thread for now; otherwise,
901  * we'd need to incur locking overhead in Libevent or use a socket.
902  */
903  if (activate_event) {
906  }
907 }
908 
909 #define queued_event_free(ev) \
910  FREE_AND_NULL(queued_event_t, queued_event_free_, (ev))
911 
913 static void
915 {
916  if (ev == NULL)
917  return;
918 
919  tor_free(ev->msg);
920  tor_free(ev);
921 }
922 
927 static void
929 {
930  /* Make sure that we get all the pending log events, if there are any. */
932 
933  if (PREDICT_UNLIKELY(queued_control_events == NULL)) {
934  return;
935  }
936  smartlist_t *all_conns = get_connection_array();
937  smartlist_t *controllers = smartlist_new();
938  smartlist_t *queued_events;
939 
940  int *block_event_queue = get_block_event_queue();
941  ++*block_event_queue;
942 
944  /* No queueing an event while flushing events. */
946  queued_events = queued_control_events;
947  queued_control_events = smartlist_new();
949 
950  /* Gather all the controllers that will care... */
951  SMARTLIST_FOREACH_BEGIN(all_conns, connection_t *, conn) {
952  if (conn->type == CONN_TYPE_CONTROL &&
953  !conn->marked_for_close &&
954  conn->state == CONTROL_CONN_STATE_OPEN) {
955  control_connection_t *control_conn = TO_CONTROL_CONN(conn);
956 
957  smartlist_add(controllers, control_conn);
958  }
959  } SMARTLIST_FOREACH_END(conn);
960 
961  SMARTLIST_FOREACH_BEGIN(queued_events, queued_event_t *, ev) {
962  const event_mask_t bit = ((event_mask_t)1) << ev->event;
963  const size_t msg_len = strlen(ev->msg);
965  control_conn) {
966  if (control_conn->event_mask & bit) {
967  connection_buf_add(ev->msg, msg_len, TO_CONN(control_conn));
968  }
969  } SMARTLIST_FOREACH_END(control_conn);
970 
971  queued_event_free(ev);
972  } SMARTLIST_FOREACH_END(ev);
973 
974  if (force) {
976  control_conn) {
977  connection_flush(TO_CONN(control_conn));
978  } SMARTLIST_FOREACH_END(control_conn);
979  }
980 
981  smartlist_free(queued_events);
982  smartlist_free(controllers);
983 
984  --*block_event_queue;
985 }
986 
989 static void
991 {
992  (void) event;
993  (void) arg;
995 }
996 
1002 MOCK_IMPL(STATIC void,
1003 send_control_event_string,(uint16_t event,
1004  const char *msg))
1005 {
1006  tor_assert(event >= EVENT_MIN_ && event <= EVENT_MAX_);
1007  queue_control_event_string(event, tor_strdup(msg));
1008 }
1009 
1014 static void
1016  const char *format, va_list ap)
1017 {
1018  char *buf = NULL;
1019  int len;
1020 
1021  len = tor_vasprintf(&buf, format, ap);
1022  if (len < 0) {
1023  log_warn(LD_BUG, "Unable to format event for controller.");
1024  return;
1025  }
1026 
1027  queue_control_event_string(event, buf);
1028 }
1029 
1033 static void
1034 send_control_event(uint16_t event,
1035  const char *format, ...)
1036 {
1037  va_list ap;
1038  va_start(ap, format);
1039  send_control_event_impl(event, format, ap);
1040  va_end(ap);
1041 }
1042 
1044 static origin_circuit_t *
1045 get_circ(const char *id)
1046 {
1047  uint32_t n_id;
1048  int ok;
1049  n_id = (uint32_t) tor_parse_ulong(id, 10, 0, UINT32_MAX, &ok, NULL);
1050  if (!ok)
1051  return NULL;
1052  return circuit_get_by_global_id(n_id);
1053 }
1054 
1056 static entry_connection_t *
1057 get_stream(const char *id)
1058 {
1059  uint64_t n_id;
1060  int ok;
1061  connection_t *conn;
1062  n_id = tor_parse_uint64(id, 10, 0, UINT64_MAX, &ok, NULL);
1063  if (!ok)
1064  return NULL;
1065  conn = connection_get_by_global_id(n_id);
1066  if (!conn || conn->type != CONN_TYPE_AP || conn->marked_for_close)
1067  return NULL;
1068  return TO_ENTRY_CONN(conn);
1069 }
1070 
1075 static int
1076 control_setconf_helper(control_connection_t *conn, uint32_t len, char *body,
1077  int use_defaults)
1078 {
1079  setopt_err_t opt_err;
1080  config_line_t *lines=NULL;
1081  char *start = body;
1082  char *errstring = NULL;
1083  const unsigned flags =
1084  CAL_CLEAR_FIRST | (use_defaults ? CAL_USE_DEFAULTS : 0);
1085 
1086  char *config;
1087  smartlist_t *entries = smartlist_new();
1088 
1089  /* We have a string, "body", of the format '(key(=val|="val")?)' entries
1090  * separated by space. break it into a list of configuration entries. */
1091  while (*body) {
1092  char *eq = body;
1093  char *key;
1094  char *entry;
1095  while (!TOR_ISSPACE(*eq) && *eq != '=')
1096  ++eq;
1097  key = tor_strndup(body, eq-body);
1098  body = eq+1;
1099  if (*eq == '=') {
1100  char *val=NULL;
1101  size_t val_len=0;
1102  if (*body != '\"') {
1103  char *val_start = body;
1104  while (!TOR_ISSPACE(*body))
1105  body++;
1106  val = tor_strndup(val_start, body-val_start);
1107  val_len = strlen(val);
1108  } else {
1109  body = (char*)extract_escaped_string(body, (len - (body-start)),
1110  &val, &val_len);
1111  if (!body) {
1112  connection_write_str_to_buf("551 Couldn't parse string\r\n", conn);
1113  SMARTLIST_FOREACH(entries, char *, cp, tor_free(cp));
1114  smartlist_free(entries);
1115  tor_free(key);
1116  return 0;
1117  }
1118  }
1119  tor_asprintf(&entry, "%s %s", key, val);
1120  tor_free(key);
1121  tor_free(val);
1122  } else {
1123  entry = key;
1124  }
1125  smartlist_add(entries, entry);
1126  while (TOR_ISSPACE(*body))
1127  ++body;
1128  }
1129 
1130  smartlist_add_strdup(entries, "");
1131  config = smartlist_join_strings(entries, "\n", 0, NULL);
1132  SMARTLIST_FOREACH(entries, char *, cp, tor_free(cp));
1133  smartlist_free(entries);
1134 
1135  if (config_get_lines(config, &lines, 0) < 0) {
1136  log_warn(LD_CONTROL,"Controller gave us config lines we can't parse.");
1137  connection_write_str_to_buf("551 Couldn't parse configuration\r\n",
1138  conn);
1139  tor_free(config);
1140  return 0;
1141  }
1142  tor_free(config);
1143 
1144  opt_err = options_trial_assign(lines, flags, &errstring);
1145  {
1146  const char *msg;
1147  switch (opt_err) {
1148  case SETOPT_ERR_MISC:
1149  msg = "552 Unrecognized option";
1150  break;
1151  case SETOPT_ERR_PARSE:
1152  msg = "513 Unacceptable option value";
1153  break;
1154  case SETOPT_ERR_TRANSITION:
1155  msg = "553 Transition not allowed";
1156  break;
1157  case SETOPT_ERR_SETTING:
1158  default:
1159  msg = "553 Unable to set option";
1160  break;
1161  case SETOPT_OK:
1162  config_free_lines(lines);
1163  send_control_done(conn);
1164  return 0;
1165  }
1166  log_warn(LD_CONTROL,
1167  "Controller gave us config lines that didn't validate: %s",
1168  errstring);
1169  connection_printf_to_buf(conn, "%s: %s\r\n", msg, errstring);
1170  config_free_lines(lines);
1171  tor_free(errstring);
1172  return 0;
1173  }
1174 }
1175 
1179 static int
1180 handle_control_setconf(control_connection_t *conn, uint32_t len, char *body)
1181 {
1182  return control_setconf_helper(conn, len, body, 0);
1183 }
1184 
1188 static int
1189 handle_control_resetconf(control_connection_t *conn, uint32_t len, char *body)
1190 {
1191  return control_setconf_helper(conn, len, body, 1);
1192 }
1193 
1196 static int
1198  const char *body)
1199 {
1200  smartlist_t *questions = smartlist_new();
1201  smartlist_t *answers = smartlist_new();
1202  smartlist_t *unrecognized = smartlist_new();
1203  char *msg = NULL;
1204  size_t msg_len;
1205  const or_options_t *options = get_options();
1206  int i, len;
1207 
1208  (void) body_len; /* body is NUL-terminated; so we can ignore len. */
1209  smartlist_split_string(questions, body, " ",
1210  SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1211  SMARTLIST_FOREACH_BEGIN(questions, const char *, q) {
1212  if (!option_is_recognized(q)) {
1213  smartlist_add(unrecognized, (char*) q);
1214  } else {
1215  config_line_t *answer = option_get_assignment(options,q);
1216  if (!answer) {
1217  const char *name = option_get_canonical_name(q);
1218  smartlist_add_asprintf(answers, "250-%s\r\n", name);
1219  }
1220 
1221  while (answer) {
1222  config_line_t *next;
1223  smartlist_add_asprintf(answers, "250-%s=%s\r\n",
1224  answer->key, answer->value);
1225 
1226  next = answer->next;
1227  tor_free(answer->key);
1228  tor_free(answer->value);
1229  tor_free(answer);
1230  answer = next;
1231  }
1232  }
1233  } SMARTLIST_FOREACH_END(q);
1234 
1235  if ((len = smartlist_len(unrecognized))) {
1236  for (i=0; i < len-1; ++i)
1238  "552-Unrecognized configuration key \"%s\"\r\n",
1239  (char*)smartlist_get(unrecognized, i));
1241  "552 Unrecognized configuration key \"%s\"\r\n",
1242  (char*)smartlist_get(unrecognized, len-1));
1243  } else if ((len = smartlist_len(answers))) {
1244  char *tmp = smartlist_get(answers, len-1);
1245  tor_assert(strlen(tmp)>4);
1246  tmp[3] = ' ';
1247  msg = smartlist_join_strings(answers, "", 0, &msg_len);
1248  connection_buf_add(msg, msg_len, TO_CONN(conn));
1249  } else {
1250  connection_write_str_to_buf("250 OK\r\n", conn);
1251  }
1252 
1253  SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
1254  smartlist_free(answers);
1255  SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
1256  smartlist_free(questions);
1257  smartlist_free(unrecognized);
1258 
1259  tor_free(msg);
1260 
1261  return 0;
1262 }
1263 
1265 static int
1267  const char *body)
1268 {
1269  setopt_err_t retval;
1270  char *errstring = NULL;
1271  const char *msg = NULL;
1272  (void) len;
1273 
1274  retval = options_init_from_string(NULL, body, CMD_RUN_TOR, NULL, &errstring);
1275 
1276  if (retval != SETOPT_OK)
1277  log_warn(LD_CONTROL,
1278  "Controller gave us config file that didn't validate: %s",
1279  errstring);
1280 
1281  switch (retval) {
1282  case SETOPT_ERR_PARSE:
1283  msg = "552 Invalid config file";
1284  break;
1285  case SETOPT_ERR_TRANSITION:
1286  msg = "553 Transition not allowed";
1287  break;
1288  case SETOPT_ERR_SETTING:
1289  msg = "553 Unable to set option";
1290  break;
1291  case SETOPT_ERR_MISC:
1292  default:
1293  msg = "550 Unable to load config";
1294  break;
1295  case SETOPT_OK:
1296  break;
1297  }
1298  if (msg) {
1299  if (errstring)
1300  connection_printf_to_buf(conn, "%s: %s\r\n", msg, errstring);
1301  else
1302  connection_printf_to_buf(conn, "%s\r\n", msg);
1303  } else {
1304  send_control_done(conn);
1305  }
1306  tor_free(errstring);
1307  return 0;
1308 }
1309 
1312  uint16_t event_code;
1313  const char *event_name;
1314 };
1317 static const struct control_event_t control_event_table[] = {
1318  { EVENT_CIRCUIT_STATUS, "CIRC" },
1319  { EVENT_CIRCUIT_STATUS_MINOR, "CIRC_MINOR" },
1320  { EVENT_STREAM_STATUS, "STREAM" },
1321  { EVENT_OR_CONN_STATUS, "ORCONN" },
1322  { EVENT_BANDWIDTH_USED, "BW" },
1323  { EVENT_DEBUG_MSG, "DEBUG" },
1324  { EVENT_INFO_MSG, "INFO" },
1325  { EVENT_NOTICE_MSG, "NOTICE" },
1326  { EVENT_WARN_MSG, "WARN" },
1327  { EVENT_ERR_MSG, "ERR" },
1328  { EVENT_NEW_DESC, "NEWDESC" },
1329  { EVENT_ADDRMAP, "ADDRMAP" },
1330  { EVENT_DESCCHANGED, "DESCCHANGED" },
1331  { EVENT_NS, "NS" },
1332  { EVENT_STATUS_GENERAL, "STATUS_GENERAL" },
1333  { EVENT_STATUS_CLIENT, "STATUS_CLIENT" },
1334  { EVENT_STATUS_SERVER, "STATUS_SERVER" },
1335  { EVENT_GUARD, "GUARD" },
1336  { EVENT_STREAM_BANDWIDTH_USED, "STREAM_BW" },
1337  { EVENT_CLIENTS_SEEN, "CLIENTS_SEEN" },
1338  { EVENT_NEWCONSENSUS, "NEWCONSENSUS" },
1339  { EVENT_BUILDTIMEOUT_SET, "BUILDTIMEOUT_SET" },
1340  { EVENT_GOT_SIGNAL, "SIGNAL" },
1341  { EVENT_CONF_CHANGED, "CONF_CHANGED"},
1342  { EVENT_CONN_BW, "CONN_BW" },
1343  { EVENT_CELL_STATS, "CELL_STATS" },
1344  { EVENT_CIRC_BANDWIDTH_USED, "CIRC_BW" },
1345  { EVENT_TRANSPORT_LAUNCHED, "TRANSPORT_LAUNCHED" },
1346  { EVENT_HS_DESC, "HS_DESC" },
1347  { EVENT_HS_DESC_CONTENT, "HS_DESC_CONTENT" },
1348  { EVENT_NETWORK_LIVENESS, "NETWORK_LIVENESS" },
1349  { 0, NULL },
1350 };
1351 
1354 static int
1356  const char *body)
1357 {
1358  int event_code;
1359  event_mask_t event_mask = 0;
1360  smartlist_t *events = smartlist_new();
1361 
1362  (void) len;
1363 
1364  smartlist_split_string(events, body, " ",
1365  SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1366  SMARTLIST_FOREACH_BEGIN(events, const char *, ev)
1367  {
1368  if (!strcasecmp(ev, "EXTENDED") ||
1369  !strcasecmp(ev, "AUTHDIR_NEWDESCS")) {
1370  log_warn(LD_CONTROL, "The \"%s\" SETEVENTS argument is no longer "
1371  "supported.", ev);
1372  continue;
1373  } else {
1374  int i;
1375  event_code = -1;
1376 
1377  for (i = 0; control_event_table[i].event_name != NULL; ++i) {
1378  if (!strcasecmp(ev, control_event_table[i].event_name)) {
1379  event_code = control_event_table[i].event_code;
1380  break;
1381  }
1382  }
1383 
1384  if (event_code == -1) {
1385  connection_printf_to_buf(conn, "552 Unrecognized event \"%s\"\r\n",
1386  ev);
1387  SMARTLIST_FOREACH(events, char *, e, tor_free(e));
1388  smartlist_free(events);
1389  return 0;
1390  }
1391  }
1392  event_mask |= (((event_mask_t)1) << event_code);
1393  }
1394  SMARTLIST_FOREACH_END(ev);
1395  SMARTLIST_FOREACH(events, char *, e, tor_free(e));
1396  smartlist_free(events);
1397 
1398  conn->event_mask = event_mask;
1399 
1401  send_control_done(conn);
1402  return 0;
1403 }
1404 
1410 smartlist_t *
1412 {
1413  char decoded[64];
1414  config_line_t *cl;
1415  smartlist_t *sl = smartlist_new();
1416 
1417  tor_assert(passwords);
1418 
1419  for (cl = passwords; cl; cl = cl->next) {
1420  const char *hashed = cl->value;
1421 
1422  if (!strcmpstart(hashed, "16:")) {
1423  if (base16_decode(decoded, sizeof(decoded), hashed+3, strlen(hashed+3))
1425  || strlen(hashed+3) != (S2K_RFC2440_SPECIFIER_LEN+DIGEST_LEN)*2) {
1426  goto err;
1427  }
1428  } else {
1429  if (base64_decode(decoded, sizeof(decoded), hashed, strlen(hashed))
1431  goto err;
1432  }
1433  }
1434  smartlist_add(sl,
1435  tor_memdup(decoded, S2K_RFC2440_SPECIFIER_LEN+DIGEST_LEN));
1436  }
1437 
1438  return sl;
1439 
1440  err:
1441  SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
1442  smartlist_free(sl);
1443  return NULL;
1444 }
1445 
1450 static int
1452  const char *body)
1453 {
1454  int used_quoted_string = 0;
1455  const or_options_t *options = get_options();
1456  const char *errstr = "Unknown error";
1457  char *password;
1458  size_t password_len;
1459  const char *cp;
1460  int i;
1461  int bad_cookie=0, bad_password=0;
1462  smartlist_t *sl = NULL;
1463 
1464  if (!len) {
1465  password = tor_strdup("");
1466  password_len = 0;
1467  } else if (TOR_ISXDIGIT(body[0])) {
1468  cp = body;
1469  while (TOR_ISXDIGIT(*cp))
1470  ++cp;
1471  i = (int)(cp - body);
1472  tor_assert(i>0);
1473  password_len = i/2;
1474  password = tor_malloc(password_len + 1);
1475  if (base16_decode(password, password_len+1, body, i)
1476  != (int) password_len) {
1478  "551 Invalid hexadecimal encoding. Maybe you tried a plain text "
1479  "password? If so, the standard requires that you put it in "
1480  "double quotes.\r\n", conn);
1481  connection_mark_for_close(TO_CONN(conn));
1482  tor_free(password);
1483  return 0;
1484  }
1485  } else {
1486  if (!decode_escaped_string(body, len, &password, &password_len)) {
1487  connection_write_str_to_buf("551 Invalid quoted string. You need "
1488  "to put the password in double quotes.\r\n", conn);
1489  connection_mark_for_close(TO_CONN(conn));
1490  return 0;
1491  }
1492  used_quoted_string = 1;
1493  }
1494 
1495  if (conn->safecookie_client_hash != NULL) {
1496  /* The controller has chosen safe cookie authentication; the only
1497  * acceptable authentication value is the controller-to-server
1498  * response. */
1499 
1501 
1502  if (password_len != DIGEST256_LEN) {
1503  log_warn(LD_CONTROL,
1504  "Got safe cookie authentication response with wrong length "
1505  "(%d)", (int)password_len);
1506  errstr = "Wrong length for safe cookie response.";
1507  goto err;
1508  }
1509 
1510  if (tor_memneq(conn->safecookie_client_hash, password, DIGEST256_LEN)) {
1511  log_warn(LD_CONTROL,
1512  "Got incorrect safe cookie authentication response");
1513  errstr = "Safe cookie response did not match expected value.";
1514  goto err;
1515  }
1516 
1518  goto ok;
1519  }
1520 
1521  if (!options->CookieAuthentication && !options->HashedControlPassword &&
1522  !options->HashedControlSessionPassword) {
1523  /* if Tor doesn't demand any stronger authentication, then
1524  * the controller can get in with anything. */
1525  goto ok;
1526  }
1527 
1528  if (options->CookieAuthentication) {
1529  int also_password = options->HashedControlPassword != NULL ||
1530  options->HashedControlSessionPassword != NULL;
1531  if (password_len != AUTHENTICATION_COOKIE_LEN) {
1532  if (!also_password) {
1533  log_warn(LD_CONTROL, "Got authentication cookie with wrong length "
1534  "(%d)", (int)password_len);
1535  errstr = "Wrong length on authentication cookie.";
1536  goto err;
1537  }
1538  bad_cookie = 1;
1539  } else if (tor_memneq(authentication_cookie, password, password_len)) {
1540  if (!also_password) {
1541  log_warn(LD_CONTROL, "Got mismatched authentication cookie");
1542  errstr = "Authentication cookie did not match expected value.";
1543  goto err;
1544  }
1545  bad_cookie = 1;
1546  } else {
1547  goto ok;
1548  }
1549  }
1550 
1551  if (options->HashedControlPassword ||
1552  options->HashedControlSessionPassword) {
1553  int bad = 0;
1554  smartlist_t *sl_tmp;
1555  char received[DIGEST_LEN];
1556  int also_cookie = options->CookieAuthentication;
1557  sl = smartlist_new();
1558  if (options->HashedControlPassword) {
1560  if (!sl_tmp)
1561  bad = 1;
1562  else {
1563  smartlist_add_all(sl, sl_tmp);
1564  smartlist_free(sl_tmp);
1565  }
1566  }
1567  if (options->HashedControlSessionPassword) {
1569  if (!sl_tmp)
1570  bad = 1;
1571  else {
1572  smartlist_add_all(sl, sl_tmp);
1573  smartlist_free(sl_tmp);
1574  }
1575  }
1576  if (bad) {
1577  if (!also_cookie) {
1578  log_warn(LD_BUG,
1579  "Couldn't decode HashedControlPassword: invalid base16");
1580  errstr="Couldn't decode HashedControlPassword value in configuration.";
1581  goto err;
1582  }
1583  bad_password = 1;
1584  SMARTLIST_FOREACH(sl, char *, str, tor_free(str));
1585  smartlist_free(sl);
1586  sl = NULL;
1587  } else {
1588  SMARTLIST_FOREACH(sl, char *, expected,
1589  {
1591  password,password_len,expected);
1592  if (tor_memeq(expected + S2K_RFC2440_SPECIFIER_LEN,
1593  received, DIGEST_LEN))
1594  goto ok;
1595  });
1596  SMARTLIST_FOREACH(sl, char *, str, tor_free(str));
1597  smartlist_free(sl);
1598  sl = NULL;
1599 
1600  if (used_quoted_string)
1601  errstr = "Password did not match HashedControlPassword value from "
1602  "configuration";
1603  else
1604  errstr = "Password did not match HashedControlPassword value from "
1605  "configuration. Maybe you tried a plain text password? "
1606  "If so, the standard requires that you put it in double quotes.";
1607  bad_password = 1;
1608  if (!also_cookie)
1609  goto err;
1610  }
1611  }
1612 
1614  tor_assert(bad_password && bad_cookie);
1615  log_warn(LD_CONTROL, "Bad password or authentication cookie on controller.");
1616  errstr = "Password did not match HashedControlPassword *or* authentication "
1617  "cookie.";
1618 
1619  err:
1620  tor_free(password);
1621  connection_printf_to_buf(conn, "515 Authentication failed: %s\r\n", errstr);
1622  connection_mark_for_close(TO_CONN(conn));
1623  if (sl) { /* clean up */
1624  SMARTLIST_FOREACH(sl, char *, str, tor_free(str));
1625  smartlist_free(sl);
1626  }
1627  return 0;
1628  ok:
1629  log_info(LD_CONTROL, "Authenticated control connection ("TOR_SOCKET_T_FORMAT
1630  ")", conn->base_.s);
1631  send_control_done(conn);
1632  conn->base_.state = CONTROL_CONN_STATE_OPEN;
1633  tor_free(password);
1634  if (sl) { /* clean up */
1635  SMARTLIST_FOREACH(sl, char *, str, tor_free(str));
1636  smartlist_free(sl);
1637  }
1638  return 0;
1639 }
1640 
1643 static int
1645  const char *body)
1646 {
1647  (void) len;
1648 
1649  int force = !strcmpstart(body, "FORCE");
1650  const or_options_t *options = get_options();
1651  if ((!force && options->IncludeUsed) || options_save_current() < 0) {
1653  "551 Unable to write configuration to disk.\r\n", conn);
1654  } else {
1655  send_control_done(conn);
1656  }
1657  return 0;
1658 }
1659 
1660 struct signal_t {
1661  int sig;
1662  const char *signal_name;
1663 };
1664 
1665 static const struct signal_t signal_table[] = {
1666  { SIGHUP, "RELOAD" },
1667  { SIGHUP, "HUP" },
1668  { SIGINT, "SHUTDOWN" },
1669  { SIGUSR1, "DUMP" },
1670  { SIGUSR1, "USR1" },
1671  { SIGUSR2, "DEBUG" },
1672  { SIGUSR2, "USR2" },
1673  { SIGTERM, "HALT" },
1674  { SIGTERM, "TERM" },
1675  { SIGTERM, "INT" },
1676  { SIGNEWNYM, "NEWNYM" },
1677  { SIGCLEARDNSCACHE, "CLEARDNSCACHE"},
1678  { SIGHEARTBEAT, "HEARTBEAT"},
1679  { SIGACTIVE, "ACTIVE" },
1680  { SIGDORMANT, "DORMANT" },
1681  { 0, NULL },
1682 };
1683 
1687 static int
1689  const char *body)
1690 {
1691  int sig = -1;
1692  int i;
1693  int n = 0;
1694  char *s;
1695 
1696  (void) len;
1697 
1698  while (body[n] && ! TOR_ISSPACE(body[n]))
1699  ++n;
1700  s = tor_strndup(body, n);
1701 
1702  for (i = 0; signal_table[i].signal_name != NULL; ++i) {
1703  if (!strcasecmp(s, signal_table[i].signal_name)) {
1704  sig = signal_table[i].sig;
1705  break;
1706  }
1707  }
1708 
1709  if (sig < 0)
1710  connection_printf_to_buf(conn, "552 Unrecognized signal code \"%s\"\r\n",
1711  s);
1712  tor_free(s);
1713  if (sig < 0)
1714  return 0;
1715 
1716  send_control_done(conn);
1717  /* Flush the "done" first if the signal might make us shut down. */
1718  if (sig == SIGTERM || sig == SIGINT)
1719  connection_flush(TO_CONN(conn));
1720 
1721  activate_signal(sig);
1722 
1723  return 0;
1724 }
1725 
1729 static int
1731  const char *body)
1732 {
1733  (void)len;
1734  (void)body;
1735 
1736  conn->is_owning_control_connection = 1;
1737 
1738  log_info(LD_CONTROL, "Control connection %d has taken ownership of this "
1739  "Tor instance.",
1740  (int)(conn->base_.s));
1741 
1742  send_control_done(conn);
1743  return 0;
1744 }
1745 
1749 static int
1751  const char *body)
1752 {
1753  (void)len;
1754  (void)body;
1755 
1756  conn->is_owning_control_connection = 0;
1757 
1758  log_info(LD_CONTROL, "Control connection %d has dropped ownership of this "
1759  "Tor instance.",
1760  (int)(conn->base_.s));
1761 
1762  send_control_done(conn);
1763  return 0;
1764 }
1765 
1768 static int
1770 {
1771  if (!strcmpstart(addr, "*."))
1772  return address_is_invalid_destination(addr+2, 1);
1773  else
1774  return address_is_invalid_destination(addr, 1);
1775 }
1776 
1779 static int
1781  const char *body)
1782 {
1783  smartlist_t *elts;
1784  smartlist_t *lines;
1785  smartlist_t *reply;
1786  char *r;
1787  size_t sz;
1788  (void) len; /* body is NUL-terminated, so it's safe to ignore the length. */
1789 
1790  lines = smartlist_new();
1791  elts = smartlist_new();
1792  reply = smartlist_new();
1793  smartlist_split_string(lines, body, " ",
1794  SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1795  SMARTLIST_FOREACH_BEGIN(lines, char *, line) {
1796  tor_strlower(line);
1797  smartlist_split_string(elts, line, "=", 0, 2);
1798  if (smartlist_len(elts) == 2) {
1799  const char *from = smartlist_get(elts,0);
1800  const char *to = smartlist_get(elts,1);
1802  smartlist_add_asprintf(reply,
1803  "512-syntax error: invalid address '%s'", to);
1804  log_warn(LD_CONTROL,
1805  "Skipping invalid argument '%s' in MapAddress msg", to);
1806  } else if (!strcmp(from, ".") || !strcmp(from, "0.0.0.0") ||
1807  !strcmp(from, "::")) {
1808  const char type =
1809  !strcmp(from,".") ? RESOLVED_TYPE_HOSTNAME :
1810  (!strcmp(from, "0.0.0.0") ? RESOLVED_TYPE_IPV4 : RESOLVED_TYPE_IPV6);
1811  const char *address = addressmap_register_virtual_address(
1812  type, tor_strdup(to));
1813  if (!address) {
1814  smartlist_add_asprintf(reply,
1815  "451-resource exhausted: skipping '%s'", line);
1816  log_warn(LD_CONTROL,
1817  "Unable to allocate address for '%s' in MapAddress msg",
1818  safe_str_client(line));
1819  } else {
1820  smartlist_add_asprintf(reply, "250-%s=%s", address, to);
1821  }
1822  } else {
1823  const char *msg;
1824  if (addressmap_register_auto(from, to, 1,
1825  ADDRMAPSRC_CONTROLLER, &msg) < 0) {
1826  smartlist_add_asprintf(reply,
1827  "512-syntax error: invalid address mapping "
1828  " '%s': %s", line, msg);
1829  log_warn(LD_CONTROL,
1830  "Skipping invalid argument '%s' in MapAddress msg: %s",
1831  line, msg);
1832  } else {
1833  smartlist_add_asprintf(reply, "250-%s", line);
1834  }
1835  }
1836  } else {
1837  smartlist_add_asprintf(reply, "512-syntax error: mapping '%s' is "
1838  "not of expected form 'foo=bar'.", line);
1839  log_info(LD_CONTROL, "Skipping MapAddress '%s': wrong "
1840  "number of items.",
1841  safe_str_client(line));
1842  }
1843  SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
1844  smartlist_clear(elts);
1845  } SMARTLIST_FOREACH_END(line);
1846  SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
1847  smartlist_free(lines);
1848  smartlist_free(elts);
1849 
1850  if (smartlist_len(reply)) {
1851  ((char*)smartlist_get(reply,smartlist_len(reply)-1))[3] = ' ';
1852  r = smartlist_join_strings(reply, "\r\n", 1, &sz);
1853  connection_buf_add(r, sz, TO_CONN(conn));
1854  tor_free(r);
1855  } else {
1856  const char *response =
1857  "512 syntax error: not enough arguments to mapaddress.\r\n";
1858  connection_buf_add(response, strlen(response), TO_CONN(conn));
1859  }
1860 
1861  SMARTLIST_FOREACH(reply, char *, cp, tor_free(cp));
1862  smartlist_free(reply);
1863  return 0;
1864 }
1865 
1868 static int
1869 getinfo_helper_misc(control_connection_t *conn, const char *question,
1870  char **answer, const char **errmsg)
1871 {
1872  (void) conn;
1873  if (!strcmp(question, "version")) {
1874  *answer = tor_strdup(get_version());
1875  } else if (!strcmp(question, "bw-event-cache")) {
1876  *answer = get_bw_samples();
1877  } else if (!strcmp(question, "config-file")) {
1878  const char *a = get_torrc_fname(0);
1879  if (a)
1880  *answer = tor_strdup(a);
1881  } else if (!strcmp(question, "config-defaults-file")) {
1882  const char *a = get_torrc_fname(1);
1883  if (a)
1884  *answer = tor_strdup(a);
1885  } else if (!strcmp(question, "config-text")) {
1886  *answer = options_dump(get_options(), OPTIONS_DUMP_MINIMAL);
1887  } else if (!strcmp(question, "config-can-saveconf")) {
1888  *answer = tor_strdup(get_options()->IncludeUsed ? "0" : "1");
1889  } else if (!strcmp(question, "info/names")) {
1890  *answer = list_getinfo_options();
1891  } else if (!strcmp(question, "dormant")) {
1892  int dormant = rep_hist_circbuilding_dormant(time(NULL));
1893  *answer = tor_strdup(dormant ? "1" : "0");
1894  } else if (!strcmp(question, "events/names")) {
1895  int i;
1896  smartlist_t *event_names = smartlist_new();
1897 
1898  for (i = 0; control_event_table[i].event_name != NULL; ++i) {
1899  smartlist_add(event_names, (char *)control_event_table[i].event_name);
1900  }
1901 
1902  *answer = smartlist_join_strings(event_names, " ", 0, NULL);
1903 
1904  smartlist_free(event_names);
1905  } else if (!strcmp(question, "signal/names")) {
1906  smartlist_t *signal_names = smartlist_new();
1907  int j;
1908  for (j = 0; signal_table[j].signal_name != NULL; ++j) {
1909  smartlist_add(signal_names, (char*)signal_table[j].signal_name);
1910  }
1911 
1912  *answer = smartlist_join_strings(signal_names, " ", 0, NULL);
1913 
1914  smartlist_free(signal_names);
1915  } else if (!strcmp(question, "features/names")) {
1916  *answer = tor_strdup("VERBOSE_NAMES EXTENDED_EVENTS");
1917  } else if (!strcmp(question, "address")) {
1918  uint32_t addr;
1919  if (router_pick_published_address(get_options(), &addr, 0) < 0) {
1920  *errmsg = "Address unknown";
1921  return -1;
1922  }
1923  *answer = tor_dup_ip(addr);
1924  } else if (!strcmp(question, "traffic/read")) {
1925  tor_asprintf(answer, "%"PRIu64, (get_bytes_read()));
1926  } else if (!strcmp(question, "traffic/written")) {
1927  tor_asprintf(answer, "%"PRIu64, (get_bytes_written()));
1928  } else if (!strcmp(question, "uptime")) {
1929  long uptime_secs = get_uptime();
1930  tor_asprintf(answer, "%ld", uptime_secs);
1931  } else if (!strcmp(question, "process/pid")) {
1932  int myPid = -1;
1933 
1934 #ifdef _WIN32
1935  myPid = _getpid();
1936 #else
1937  myPid = getpid();
1938 #endif
1939 
1940  tor_asprintf(answer, "%d", myPid);
1941  } else if (!strcmp(question, "process/uid")) {
1942 #ifdef _WIN32
1943  *answer = tor_strdup("-1");
1944 #else
1945  int myUid = geteuid();
1946  tor_asprintf(answer, "%d", myUid);
1947 #endif /* defined(_WIN32) */
1948  } else if (!strcmp(question, "process/user")) {
1949 #ifdef _WIN32
1950  *answer = tor_strdup("");
1951 #else
1952  int myUid = geteuid();
1953  const struct passwd *myPwEntry = tor_getpwuid(myUid);
1954 
1955  if (myPwEntry) {
1956  *answer = tor_strdup(myPwEntry->pw_name);
1957  } else {
1958  *answer = tor_strdup("");
1959  }
1960 #endif /* defined(_WIN32) */
1961  } else if (!strcmp(question, "process/descriptor-limit")) {
1962  int max_fds = get_max_sockets();
1963  tor_asprintf(answer, "%d", max_fds);
1964  } else if (!strcmp(question, "limits/max-mem-in-queues")) {
1965  tor_asprintf(answer, "%"PRIu64,
1966  (get_options()->MaxMemInQueues));
1967  } else if (!strcmp(question, "fingerprint")) {
1968  crypto_pk_t *server_key;
1969  if (!server_mode(get_options())) {
1970  *errmsg = "Not running in server mode";
1971  return -1;
1972  }
1973  server_key = get_server_identity_key();
1974  *answer = tor_malloc(HEX_DIGEST_LEN+1);
1975  crypto_pk_get_fingerprint(server_key, *answer, 0);
1976  }
1977  return 0;
1978 }
1979 
1989 static char *
1991  const signed_descriptor_t *ri,
1992  const signed_descriptor_t *ei)
1993 {
1994  char *out = NULL, *outp;
1995  int i;
1996  const char *router_sig;
1997  const char *ei_body = signed_descriptor_get_body(ei);
1998  size_t ri_len = ri->signed_descriptor_len;
1999  size_t ei_len = ei->signed_descriptor_len;
2000  if (!ei_body)
2001  goto bail;
2002 
2003  outp = out = tor_malloc(ri_len+ei_len+1);
2004  if (!(router_sig = tor_memstr(ri_body, ri_len, "\nrouter-signature")))
2005  goto bail;
2006  ++router_sig;
2007  memcpy(out, ri_body, router_sig-ri_body);
2008  outp += router_sig-ri_body;
2009 
2010  for (i=0; i < 2; ++i) {
2011  const char *kwd = i ? "\nwrite-history " : "\nread-history ";
2012  const char *cp, *eol;
2013  if (!(cp = tor_memstr(ei_body, ei_len, kwd)))
2014  continue;
2015  ++cp;
2016  if (!(eol = memchr(cp, '\n', ei_len - (cp-ei_body))))
2017  continue;
2018  memcpy(outp, cp, eol-cp+1);
2019  outp += eol-cp+1;
2020  }
2021  memcpy(outp, router_sig, ri_len - (router_sig-ri_body));
2022  *outp++ = '\0';
2023  tor_assert(outp-out < (int)(ri_len+ei_len+1));
2024 
2025  return out;
2026  bail:
2027  tor_free(out);
2028  return tor_strndup(ri_body, ri->signed_descriptor_len);
2029 }
2030 
2033 static int
2035  const char *question,
2036  char **answer, const char **errmsg)
2037 {
2038  int type;
2039  smartlist_t *res;
2040 
2041  (void)control_conn;
2042  (void)errmsg;
2043 
2044  if (!strcmp(question, "net/listeners/or"))
2045  type = CONN_TYPE_OR_LISTENER;
2046  else if (!strcmp(question, "net/listeners/extor"))
2048  else if (!strcmp(question, "net/listeners/dir"))
2049  type = CONN_TYPE_DIR_LISTENER;
2050  else if (!strcmp(question, "net/listeners/socks"))
2051  type = CONN_TYPE_AP_LISTENER;
2052  else if (!strcmp(question, "net/listeners/trans"))
2054  else if (!strcmp(question, "net/listeners/natd"))
2056  else if (!strcmp(question, "net/listeners/httptunnel"))
2058  else if (!strcmp(question, "net/listeners/dns"))
2060  else if (!strcmp(question, "net/listeners/control"))
2062  else
2063  return 0; /* unknown key */
2064 
2065  res = smartlist_new();
2066  SMARTLIST_FOREACH_BEGIN(get_connection_array(), connection_t *, conn) {
2067  struct sockaddr_storage ss;
2068  socklen_t ss_len = sizeof(ss);
2069 
2070  if (conn->type != type || conn->marked_for_close || !SOCKET_OK(conn->s))
2071  continue;
2072 
2073  if (getsockname(conn->s, (struct sockaddr *)&ss, &ss_len) < 0) {
2074  smartlist_add_asprintf(res, "%s:%d", conn->address, (int)conn->port);
2075  } else {
2076  char *tmp = tor_sockaddr_to_str((struct sockaddr *)&ss);
2077  smartlist_add(res, esc_for_log(tmp));
2078  tor_free(tmp);
2079  }
2080 
2081  } SMARTLIST_FOREACH_END(conn);
2082 
2083  *answer = smartlist_join_strings(res, " ", 0, NULL);
2084 
2085  SMARTLIST_FOREACH(res, char *, cp, tor_free(cp));
2086  smartlist_free(res);
2087  return 0;
2088 }
2089 
2092 STATIC int
2094  const char *question,
2095  char **answer, const char **errmsg)
2096 {
2097  (void)control_conn;
2098  (void)errmsg;
2099 
2100  struct timeval now;
2101  tor_gettimeofday(&now);
2102  char timebuf[ISO_TIME_LEN+1];
2103 
2104  if (!strcmp(question, "current-time/local"))
2105  format_local_iso_time_nospace(timebuf, (time_t)now.tv_sec);
2106  else if (!strcmp(question, "current-time/utc"))
2107  format_iso_time_nospace(timebuf, (time_t)now.tv_sec);
2108  else
2109  return 0;
2110 
2111  *answer = tor_strdup(timebuf);
2112  return 0;
2113 }
2114 
2117 STATIC int
2119  const char *question, char **answer,
2120  const char **errmsg)
2121 {
2122  (void) control_conn;
2123  if (!strcmpstart(question, "desc/id/")) {
2124  const routerinfo_t *ri = NULL;
2125  const node_t *node = node_get_by_hex_id(question+strlen("desc/id/"), 0);
2126  if (node)
2127  ri = node->ri;
2128  if (ri) {
2129  const char *body = signed_descriptor_get_body(&ri->cache_info);
2130  if (body)
2131  *answer = tor_strndup(body, ri->cache_info.signed_descriptor_len);
2132  } else if (! we_fetch_router_descriptors(get_options())) {
2133  /* Descriptors won't be available, provide proper error */
2134  *errmsg = "We fetch microdescriptors, not router "
2135  "descriptors. You'll need to use md/id/* "
2136  "instead of desc/id/*.";
2137  return 0;
2138  }
2139  } else if (!strcmpstart(question, "desc/name/")) {
2140  const routerinfo_t *ri = NULL;
2141  /* XXX Setting 'warn_if_unnamed' here is a bit silly -- the
2142  * warning goes to the user, not to the controller. */
2143  const node_t *node =
2144  node_get_by_nickname(question+strlen("desc/name/"), 0);
2145  if (node)
2146  ri = node->ri;
2147  if (ri) {
2148  const char *body = signed_descriptor_get_body(&ri->cache_info);
2149  if (body)
2150  *answer = tor_strndup(body, ri->cache_info.signed_descriptor_len);
2151  } else if (! we_fetch_router_descriptors(get_options())) {
2152  /* Descriptors won't be available, provide proper error */
2153  *errmsg = "We fetch microdescriptors, not router "
2154  "descriptors. You'll need to use md/name/* "
2155  "instead of desc/name/*.";
2156  return 0;
2157  }
2158  } else if (!strcmp(question, "desc/download-enabled")) {
2159  int r = we_fetch_router_descriptors(get_options());
2160  tor_asprintf(answer, "%d", !!r);
2161  } else if (!strcmp(question, "desc/all-recent")) {
2163  smartlist_t *sl = smartlist_new();
2164  if (routerlist && routerlist->routers) {
2166  {
2167  const char *body = signed_descriptor_get_body(&ri->cache_info);
2168  if (body)
2169  smartlist_add(sl,
2170  tor_strndup(body, ri->cache_info.signed_descriptor_len));
2171  });
2172  }
2173  *answer = smartlist_join_strings(sl, "", 0, NULL);
2174  SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
2175  smartlist_free(sl);
2176  } else if (!strcmp(question, "desc/all-recent-extrainfo-hack")) {
2177  /* XXXX Remove this once Torstat asks for extrainfos. */
2179  smartlist_t *sl = smartlist_new();
2180  if (routerlist && routerlist->routers) {
2182  const char *body = signed_descriptor_get_body(&ri->cache_info);
2183  signed_descriptor_t *ei = extrainfo_get_by_descriptor_digest(
2184  ri->cache_info.extra_info_digest);
2185  if (ei && body) {
2187  &ri->cache_info, ei));
2188  } else if (body) {
2189  smartlist_add(sl,
2190  tor_strndup(body, ri->cache_info.signed_descriptor_len));
2191  }
2192  } SMARTLIST_FOREACH_END(ri);
2193  }
2194  *answer = smartlist_join_strings(sl, "", 0, NULL);
2195  SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
2196  smartlist_free(sl);
2197  } else if (!strcmpstart(question, "hs/client/desc/id/")) {
2198  hostname_type_t addr_type;
2199 
2200  question += strlen("hs/client/desc/id/");
2201  if (rend_valid_v2_service_id(question)) {
2202  addr_type = ONION_V2_HOSTNAME;
2203  } else if (hs_address_is_valid(question)) {
2204  addr_type = ONION_V3_HOSTNAME;
2205  } else {
2206  *errmsg = "Invalid address";
2207  return -1;
2208  }
2209 
2210  if (addr_type == ONION_V2_HOSTNAME) {
2211  rend_cache_entry_t *e = NULL;
2212  if (!rend_cache_lookup_entry(question, -1, &e)) {
2213  /* Descriptor found in cache */
2214  *answer = tor_strdup(e->desc);
2215  } else {
2216  *errmsg = "Not found in cache";
2217  return -1;
2218  }
2219  } else {
2220  ed25519_public_key_t service_pk;
2221  const char *desc;
2222 
2223  /* The check before this if/else makes sure of this. */
2224  tor_assert(addr_type == ONION_V3_HOSTNAME);
2225 
2226  if (hs_parse_address(question, &service_pk, NULL, NULL) < 0) {
2227  *errmsg = "Invalid v3 address";
2228  return -1;
2229  }
2230 
2231  desc = hs_cache_lookup_encoded_as_client(&service_pk);
2232  if (desc) {
2233  *answer = tor_strdup(desc);
2234  } else {
2235  *errmsg = "Not found in cache";
2236  return -1;
2237  }
2238  }
2239  } else if (!strcmpstart(question, "hs/service/desc/id/")) {
2240  hostname_type_t addr_type;
2241 
2242  question += strlen("hs/service/desc/id/");
2243  if (rend_valid_v2_service_id(question)) {
2244  addr_type = ONION_V2_HOSTNAME;
2245  } else if (hs_address_is_valid(question)) {
2246  addr_type = ONION_V3_HOSTNAME;
2247  } else {
2248  *errmsg = "Invalid address";
2249  return -1;
2250  }
2251  rend_cache_entry_t *e = NULL;
2252 
2253  if (addr_type == ONION_V2_HOSTNAME) {
2254  if (!rend_cache_lookup_v2_desc_as_service(question, &e)) {
2255  /* Descriptor found in cache */
2256  *answer = tor_strdup(e->desc);
2257  } else {
2258  *errmsg = "Not found in cache";
2259  return -1;
2260  }
2261  } else {
2262  ed25519_public_key_t service_pk;
2263  char *desc;
2264 
2265  /* The check before this if/else makes sure of this. */
2266  tor_assert(addr_type == ONION_V3_HOSTNAME);
2267 
2268  if (hs_parse_address(question, &service_pk, NULL, NULL) < 0) {
2269  *errmsg = "Invalid v3 address";
2270  return -1;
2271  }
2272 
2273  desc = hs_service_lookup_current_desc(&service_pk);
2274  if (desc) {
2275  /* Newly allocated string, we have ownership. */
2276  *answer = desc;
2277  } else {
2278  *errmsg = "Not found in cache";
2279  return -1;
2280  }
2281  }
2282  } else if (!strcmp(question, "md/all")) {
2283  const smartlist_t *nodes = nodelist_get_list();
2284  tor_assert(nodes);
2285 
2286  if (smartlist_len(nodes) == 0) {
2287  *answer = tor_strdup("");
2288  return 0;
2289  }
2290 
2291  smartlist_t *microdescs = smartlist_new();
2292 
2293  SMARTLIST_FOREACH_BEGIN(nodes, node_t *, n) {
2294  if (n->md && n->md->body) {
2295  char *copy = tor_strndup(n->md->body, n->md->bodylen);
2296  smartlist_add(microdescs, copy);
2297  }
2298  } SMARTLIST_FOREACH_END(n);
2299 
2300  *answer = smartlist_join_strings(microdescs, "", 0, NULL);
2301  SMARTLIST_FOREACH(microdescs, char *, md, tor_free(md));
2302  smartlist_free(microdescs);
2303  } else if (!strcmpstart(question, "md/id/")) {
2304  const node_t *node = node_get_by_hex_id(question+strlen("md/id/"), 0);
2305  const microdesc_t *md = NULL;
2306  if (node) md = node->md;
2307  if (md && md->body) {
2308  *answer = tor_strndup(md->body, md->bodylen);
2309  }
2310  } else if (!strcmpstart(question, "md/name/")) {
2311  /* XXX Setting 'warn_if_unnamed' here is a bit silly -- the
2312  * warning goes to the user, not to the controller. */
2313  const node_t *node = node_get_by_nickname(question+strlen("md/name/"), 0);
2314  /* XXXX duplicated code */
2315  const microdesc_t *md = NULL;
2316  if (node) md = node->md;
2317  if (md && md->body) {
2318  *answer = tor_strndup(md->body, md->bodylen);
2319  }
2320  } else if (!strcmp(question, "md/download-enabled")) {
2321  int r = we_fetch_microdescriptors(get_options());
2322  tor_asprintf(answer, "%d", !!r);
2323  } else if (!strcmpstart(question, "desc-annotations/id/")) {
2324  const routerinfo_t *ri = NULL;
2325  const node_t *node =
2326  node_get_by_hex_id(question+strlen("desc-annotations/id/"), 0);
2327  if (node)
2328  ri = node->ri;
2329  if (ri) {
2330  const char *annotations =
2331  signed_descriptor_get_annotations(&ri->cache_info);
2332  if (annotations)
2333  *answer = tor_strndup(annotations,
2334  ri->cache_info.annotations_len);
2335  }
2336  } else if (!strcmpstart(question, "dir/server/")) {
2337  size_t answer_len = 0;
2338  char *url = NULL;
2339  smartlist_t *descs = smartlist_new();
2340  const char *msg;
2341  int res;
2342  char *cp;
2343  tor_asprintf(&url, "/tor/%s", question+4);
2344  res = dirserv_get_routerdescs(descs, url, &msg);
2345  if (res) {
2346  log_warn(LD_CONTROL, "getinfo '%s': %s", question, msg);
2347  smartlist_free(descs);
2348  tor_free(url);
2349  *errmsg = msg;
2350  return -1;
2351  }
2353  answer_len += sd->signed_descriptor_len);
2354  cp = *answer = tor_malloc(answer_len+1);
2356  {
2357  memcpy(cp, signed_descriptor_get_body(sd),
2358  sd->signed_descriptor_len);
2359  cp += sd->signed_descriptor_len;
2360  });
2361  *cp = '\0';
2362  tor_free(url);
2363  smartlist_free(descs);
2364  } else if (!strcmpstart(question, "dir/status/")) {
2365  *answer = tor_strdup("");
2366  } else if (!strcmp(question, "dir/status-vote/current/consensus")) { /* v3 */
2367  if (we_want_to_fetch_flavor(get_options(), FLAV_NS)) {
2368  const cached_dir_t *consensus = dirserv_get_consensus("ns");
2369  if (consensus)
2370  *answer = tor_strdup(consensus->dir);
2371  }
2372  if (!*answer) { /* try loading it from disk */
2374  if (mapped) {
2375  *answer = tor_memdup_nulterm(mapped->data, mapped->size);
2376  tor_munmap_file(mapped);
2377  }
2378  if (!*answer) { /* generate an error */
2379  *errmsg = "Could not open cached consensus. "
2380  "Make sure FetchUselessDescriptors is set to 1.";
2381  return -1;
2382  }
2383  }
2384  } else if (!strcmp(question, "network-status")) { /* v1 */
2385  static int network_status_warned = 0;
2386  if (!network_status_warned) {
2387  log_warn(LD_CONTROL, "GETINFO network-status is deprecated; it will "
2388  "go away in a future version of Tor.");
2389  network_status_warned = 1;
2390  }
2392  if (!routerlist || !routerlist->routers ||
2393  list_server_status_v1(routerlist->routers, answer, 1) < 0) {
2394  return -1;
2395  }
2396  } else if (!strcmpstart(question, "extra-info/digest/")) {
2397  question += strlen("extra-info/digest/");
2398  if (strlen(question) == HEX_DIGEST_LEN) {
2399  char d[DIGEST_LEN];
2400  signed_descriptor_t *sd = NULL;
2401  if (base16_decode(d, sizeof(d), question, strlen(question))
2402  == sizeof(d)) {
2403  /* XXXX this test should move into extrainfo_get_by_descriptor_digest,
2404  * but I don't want to risk affecting other parts of the code,
2405  * especially since the rules for using our own extrainfo (including
2406  * when it might be freed) are different from those for using one
2407  * we have downloaded. */
2409  sd = &(router_get_my_extrainfo()->cache_info);
2410  else
2411  sd = extrainfo_get_by_descriptor_digest(d);
2412  }
2413  if (sd) {
2414  const char *body = signed_descriptor_get_body(sd);
2415  if (body)
2416  *answer = tor_strndup(body, sd->signed_descriptor_len);
2417  }
2418  }
2419  }
2420 
2421  return 0;
2422 }
2423 
2427 static char *
2429 {
2430  int len;
2431  char *result, *s;
2432 
2433  /* Allow for newlines, and a \0 at the end */
2434  len = smartlist_len(sl) * (HEX_DIGEST_LEN + 1) + 1;
2435  result = tor_malloc_zero(len);
2436 
2437  s = result;
2438  SMARTLIST_FOREACH_BEGIN(sl, const char *, digest) {
2439  base16_encode(s, HEX_DIGEST_LEN + 1, digest, DIGEST_LEN);
2440  s[HEX_DIGEST_LEN] = '\n';
2441  s += HEX_DIGEST_LEN + 1;
2442  } SMARTLIST_FOREACH_END(digest);
2443  *s = '\0';
2444 
2445  return result;
2446 }
2447 
2451 static char *
2453 {
2454  char *rv = NULL;
2455  char tbuf[ISO_TIME_LEN+1];
2456  const char *schedule_str, *want_authority_str;
2457  const char *increment_on_str, *backoff_str;
2458 
2459  if (dl) {
2460  /* Get some substrings of the eventual output ready */
2462 
2463  switch (dl->schedule) {
2464  case DL_SCHED_GENERIC:
2465  schedule_str = "DL_SCHED_GENERIC";
2466  break;
2467  case DL_SCHED_CONSENSUS:
2468  schedule_str = "DL_SCHED_CONSENSUS";
2469  break;
2470  case DL_SCHED_BRIDGE:
2471  schedule_str = "DL_SCHED_BRIDGE";
2472  break;
2473  default:
2474  schedule_str = "unknown";
2475  break;
2476  }
2477 
2478  switch (dl->want_authority) {
2479  case DL_WANT_ANY_DIRSERVER:
2480  want_authority_str = "DL_WANT_ANY_DIRSERVER";
2481  break;
2482  case DL_WANT_AUTHORITY:
2483  want_authority_str = "DL_WANT_AUTHORITY";
2484  break;
2485  default:
2486  want_authority_str = "unknown";
2487  break;
2488  }
2489 
2490  switch (dl->increment_on) {
2491  case DL_SCHED_INCREMENT_FAILURE:
2492  increment_on_str = "DL_SCHED_INCREMENT_FAILURE";
2493  break;
2494  case DL_SCHED_INCREMENT_ATTEMPT:
2495  increment_on_str = "DL_SCHED_INCREMENT_ATTEMPT";
2496  break;
2497  default:
2498  increment_on_str = "unknown";
2499  break;
2500  }
2501 
2502  backoff_str = "DL_SCHED_RANDOM_EXPONENTIAL";
2503 
2504  /* Now assemble them */
2505  tor_asprintf(&rv,
2506  "next-attempt-at %s\n"
2507  "n-download-failures %u\n"
2508  "n-download-attempts %u\n"
2509  "schedule %s\n"
2510  "want-authority %s\n"
2511  "increment-on %s\n"
2512  "backoff %s\n"
2513  "last-backoff-position %u\n"
2514  "last-delay-used %d\n",
2515  tbuf,
2516  dl->n_download_failures,
2517  dl->n_download_attempts,
2518  schedule_str,
2519  want_authority_str,
2520  increment_on_str,
2521  backoff_str,
2523  dl->last_delay_used);
2524  }
2525 
2526  return rv;
2527 }
2528 
2530 STATIC void
2532  download_status_t **dl_to_emit,
2533  const char **errmsg)
2534 {
2535  /*
2536  * We get the one for the current bootstrapped status by default, or
2537  * take an extra /bootstrap or /running suffix
2538  */
2539  if (strcmp(flavor, "ns") == 0) {
2540  *dl_to_emit = networkstatus_get_dl_status_by_flavor(FLAV_NS);
2541  } else if (strcmp(flavor, "ns/bootstrap") == 0) {
2542  *dl_to_emit = networkstatus_get_dl_status_by_flavor_bootstrap(FLAV_NS);
2543  } else if (strcmp(flavor, "ns/running") == 0 ) {
2544  *dl_to_emit = networkstatus_get_dl_status_by_flavor_running(FLAV_NS);
2545  } else if (strcmp(flavor, "microdesc") == 0) {
2546  *dl_to_emit = networkstatus_get_dl_status_by_flavor(FLAV_MICRODESC);
2547  } else if (strcmp(flavor, "microdesc/bootstrap") == 0) {
2548  *dl_to_emit =
2549  networkstatus_get_dl_status_by_flavor_bootstrap(FLAV_MICRODESC);
2550  } else if (strcmp(flavor, "microdesc/running") == 0) {
2551  *dl_to_emit =
2552  networkstatus_get_dl_status_by_flavor_running(FLAV_MICRODESC);
2553  } else {
2554  *errmsg = "Unknown flavor";
2555  }
2556 }
2557 
2559 STATIC void
2560 getinfo_helper_downloads_cert(const char *fp_sk_req,
2561  download_status_t **dl_to_emit,
2562  smartlist_t **digest_list,
2563  const char **errmsg)
2564 {
2565  const char *sk_req;
2566  char id_digest[DIGEST_LEN];
2567  char sk_digest[DIGEST_LEN];
2568 
2569  /*
2570  * We have to handle four cases; fp_sk_req is the request with
2571  * a prefix of "downloads/cert/" snipped off.
2572  *
2573  * Case 1: fp_sk_req = "fps"
2574  * - We should emit a digest_list with a list of all the identity
2575  * fingerprints that can be queried for certificate download status;
2576  * get it by calling list_authority_ids_with_downloads().
2577  *
2578  * Case 2: fp_sk_req = "fp/<fp>" for some fingerprint fp
2579  * - We want the default certificate for this identity fingerprint's
2580  * download status; this is the download we get from URLs starting
2581  * in /fp/ on the directory server. We can get it with
2582  * id_only_download_status_for_authority_id().
2583  *
2584  * Case 3: fp_sk_req = "fp/<fp>/sks" for some fingerprint fp
2585  * - We want a list of all signing key digests for this identity
2586  * fingerprint which can be queried for certificate download status.
2587  * Get it with list_sk_digests_for_authority_id().
2588  *
2589  * Case 4: fp_sk_req = "fp/<fp>/<sk>" for some fingerprint fp and
2590  * signing key digest sk
2591  * - We want the download status for the certificate for this specific
2592  * signing key and fingerprint. These correspond to the ones we get
2593  * from URLs starting in /fp-sk/ on the directory server. Get it with
2594  * list_sk_digests_for_authority_id().
2595  */
2596 
2597  if (strcmp(fp_sk_req, "fps") == 0) {
2598  *digest_list = list_authority_ids_with_downloads();
2599  if (!(*digest_list)) {
2600  *errmsg = "Failed to get list of authority identity digests (!)";
2601  }
2602  } else if (!strcmpstart(fp_sk_req, "fp/")) {
2603  fp_sk_req += strlen("fp/");
2604  /* Okay, look for another / to tell the fp from fp-sk cases */
2605  sk_req = strchr(fp_sk_req, '/');
2606  if (sk_req) {
2607  /* okay, split it here and try to parse <fp> */
2608  if (base16_decode(id_digest, DIGEST_LEN,
2609  fp_sk_req, sk_req - fp_sk_req) == DIGEST_LEN) {
2610  /* Skip past the '/' */
2611  ++sk_req;
2612  if (strcmp(sk_req, "sks") == 0) {
2613  /* We're asking for the list of signing key fingerprints */
2614  *digest_list = list_sk_digests_for_authority_id(id_digest);
2615  if (!(*digest_list)) {
2616  *errmsg = "Failed to get list of signing key digests for this "
2617  "authority identity digest";
2618  }
2619  } else {
2620  /* We've got a signing key digest */
2621  if (base16_decode(sk_digest, DIGEST_LEN,
2622  sk_req, strlen(sk_req)) == DIGEST_LEN) {
2623  *dl_to_emit =
2624  download_status_for_authority_id_and_sk(id_digest, sk_digest);
2625  if (!(*dl_to_emit)) {
2626  *errmsg = "Failed to get download status for this identity/"
2627  "signing key digest pair";
2628  }
2629  } else {
2630  *errmsg = "That didn't look like a signing key digest";
2631  }
2632  }
2633  } else {
2634  *errmsg = "That didn't look like an identity digest";
2635  }
2636  } else {
2637  /* We're either in downloads/certs/fp/<fp>, or we can't parse <fp> */
2638  if (strlen(fp_sk_req) == HEX_DIGEST_LEN) {
2639  if (base16_decode(id_digest, DIGEST_LEN,
2640  fp_sk_req, strlen(fp_sk_req)) == DIGEST_LEN) {
2641  *dl_to_emit = id_only_download_status_for_authority_id(id_digest);
2642  if (!(*dl_to_emit)) {
2643  *errmsg = "Failed to get download status for this authority "
2644  "identity digest";
2645  }
2646  } else {
2647  *errmsg = "That didn't look like a digest";
2648  }
2649  } else {
2650  *errmsg = "That didn't look like a digest";
2651  }
2652  }
2653  } else {
2654  *errmsg = "Unknown certificate download status query";
2655  }
2656 }
2657 
2659 STATIC void
2660 getinfo_helper_downloads_desc(const char *desc_req,
2661  download_status_t **dl_to_emit,
2662  smartlist_t **digest_list,
2663  const char **errmsg)
2664 {
2665  char desc_digest[DIGEST_LEN];
2666  /*
2667  * Two cases to handle here:
2668  *
2669  * Case 1: desc_req = "descs"
2670  * - Emit a list of all router descriptor digests, which we get by
2671  * calling router_get_descriptor_digests(); this can return NULL
2672  * if we have no current ns-flavor consensus.
2673  *
2674  * Case 2: desc_req = <fp>
2675  * - Check on the specified fingerprint and emit its download_status_t
2676  * using router_get_dl_status_by_descriptor_digest().
2677  */
2678 
2679  if (strcmp(desc_req, "descs") == 0) {
2680  *digest_list = router_get_descriptor_digests();
2681  if (!(*digest_list)) {
2682  *errmsg = "We don't seem to have a networkstatus-flavored consensus";
2683  }
2684  /*
2685  * Microdescs don't use the download_status_t mechanism, so we don't
2686  * answer queries about their downloads here; see microdesc.c.
2687  */
2688  } else if (strlen(desc_req) == HEX_DIGEST_LEN) {
2689  if (base16_decode(desc_digest, DIGEST_LEN,
2690  desc_req, strlen(desc_req)) == DIGEST_LEN) {
2691  /* Okay we got a digest-shaped thing; try asking for it */
2692  *dl_to_emit = router_get_dl_status_by_descriptor_digest(desc_digest);
2693  if (!(*dl_to_emit)) {
2694  *errmsg = "No such descriptor digest found";
2695  }
2696  } else {
2697  *errmsg = "That didn't look like a digest";
2698  }
2699  } else {
2700  *errmsg = "Unknown router descriptor download status query";
2701  }
2702 }
2703 
2705 STATIC void
2706 getinfo_helper_downloads_bridge(const char *bridge_req,
2707  download_status_t **dl_to_emit,
2708  smartlist_t **digest_list,
2709  const char **errmsg)
2710 {
2711  char bridge_digest[DIGEST_LEN];
2712  /*
2713  * Two cases to handle here:
2714  *
2715  * Case 1: bridge_req = "bridges"
2716  * - Emit a list of all bridge identity digests, which we get by
2717  * calling list_bridge_identities(); this can return NULL if we are
2718  * not using bridges.
2719  *
2720  * Case 2: bridge_req = <fp>
2721  * - Check on the specified fingerprint and emit its download_status_t
2722  * using get_bridge_dl_status_by_id().
2723  */
2724 
2725  if (strcmp(bridge_req, "bridges") == 0) {
2726  *digest_list = list_bridge_identities();
2727  if (!(*digest_list)) {
2728  *errmsg = "We don't seem to be using bridges";
2729  }
2730  } else if (strlen(bridge_req) == HEX_DIGEST_LEN) {
2731  if (base16_decode(bridge_digest, DIGEST_LEN,
2732  bridge_req, strlen(bridge_req)) == DIGEST_LEN) {
2733  /* Okay we got a digest-shaped thing; try asking for it */
2734  *dl_to_emit = get_bridge_dl_status_by_id(bridge_digest);
2735  if (!(*dl_to_emit)) {
2736  *errmsg = "No such bridge identity digest found";
2737  }
2738  } else {
2739  *errmsg = "That didn't look like a digest";
2740  }
2741  } else {
2742  *errmsg = "Unknown bridge descriptor download status query";
2743  }
2744 }
2745 
2748 STATIC int
2750  const char *question, char **answer,
2751  const char **errmsg)
2752 {
2753  download_status_t *dl_to_emit = NULL;
2754  smartlist_t *digest_list = NULL;
2755 
2756  /* Assert args are sane */
2757  tor_assert(control_conn != NULL);
2758  tor_assert(question != NULL);
2759  tor_assert(answer != NULL);
2760  tor_assert(errmsg != NULL);
2761 
2762  /* We check for this later to see if we should supply a default */
2763  *errmsg = NULL;
2764 
2765  /* Are we after networkstatus downloads? */
2766  if (!strcmpstart(question, "downloads/networkstatus/")) {
2768  question + strlen("downloads/networkstatus/"),
2769  &dl_to_emit, errmsg);
2770  /* Certificates? */
2771  } else if (!strcmpstart(question, "downloads/cert/")) {
2773  question + strlen("downloads/cert/"),
2774  &dl_to_emit, &digest_list, errmsg);
2775  /* Router descriptors? */
2776  } else if (!strcmpstart(question, "downloads/desc/")) {
2778  question + strlen("downloads/desc/"),
2779  &dl_to_emit, &digest_list, errmsg);
2780  /* Bridge descriptors? */
2781  } else if (!strcmpstart(question, "downloads/bridge/")) {
2783  question + strlen("downloads/bridge/"),
2784  &dl_to_emit, &digest_list, errmsg);
2785  } else {
2786  *errmsg = "Unknown download status query";
2787  }
2788 
2789  if (dl_to_emit) {
2790  *answer = download_status_to_string(dl_to_emit);
2791 
2792  return 0;
2793  } else if (digest_list) {
2794  *answer = digest_list_to_string(digest_list);
2795  SMARTLIST_FOREACH(digest_list, void *, s, tor_free(s));
2796  smartlist_free(digest_list);
2797 
2798  return 0;
2799  } else {
2800  if (!(*errmsg)) {
2801  *errmsg = "Unknown error";
2802  }
2803 
2804  return -1;
2805  }
2806 }
2807 
2810 static char *
2812 {
2813  char *rv;
2814  smartlist_t *descparts = smartlist_new();
2815 
2816  {
2817  char *vpath = circuit_list_path_for_controller(circ);
2818  if (*vpath) {
2819  smartlist_add(descparts, vpath);
2820  } else {
2821  tor_free(vpath); /* empty path; don't put an extra space in the result */
2822  }
2823  }
2824 
2825  {
2826  cpath_build_state_t *build_state = circ->build_state;
2827  smartlist_t *flaglist = smartlist_new();
2828  char *flaglist_joined;
2829 
2830  if (build_state->onehop_tunnel)
2831  smartlist_add(flaglist, (void *)"ONEHOP_TUNNEL");
2832  if (build_state->is_internal)
2833  smartlist_add(flaglist, (void *)"IS_INTERNAL");
2834  if (build_state->need_capacity)
2835  smartlist_add(flaglist, (void *)"NEED_CAPACITY");
2836  if (build_state->need_uptime)
2837  smartlist_add(flaglist, (void *)"NEED_UPTIME");
2838 
2839  /* Only emit a BUILD_FLAGS argument if it will have a non-empty value. */
2840  if (smartlist_len(flaglist)) {
2841  flaglist_joined = smartlist_join_strings(flaglist, ",", 0, NULL);
2842 
2843  smartlist_add_asprintf(descparts, "BUILD_FLAGS=%s", flaglist_joined);
2844 
2845  tor_free(flaglist_joined);
2846  }
2847 
2848  smartlist_free(flaglist);
2849  }
2850 
2851  smartlist_add_asprintf(descparts, "PURPOSE=%s",
2853 
2854  {
2855  const char *hs_state =
2857 
2858  if (hs_state != NULL) {
2859  smartlist_add_asprintf(descparts, "HS_STATE=%s", hs_state);
2860  }
2861  }
2862 
2863  if (circ->rend_data != NULL || circ->hs_ident != NULL) {
2864  char addr[HS_SERVICE_ADDR_LEN_BASE32 + 1];
2865  const char *onion_address;
2866  if (circ->rend_data) {
2867  onion_address = rend_data_get_address(circ->rend_data);
2868  } else {
2869  hs_build_address(&circ->hs_ident->identity_pk, HS_VERSION_THREE, addr);
2870  onion_address = addr;
2871  }
2872  smartlist_add_asprintf(descparts, "REND_QUERY=%s", onion_address);
2873  }
2874 
2875  {
2876  char tbuf[ISO_TIME_USEC_LEN+1];
2877  format_iso_time_nospace_usec(tbuf, &circ->base_.timestamp_created);
2878 
2879  smartlist_add_asprintf(descparts, "TIME_CREATED=%s", tbuf);
2880  }
2881 
2882  // Show username and/or password if available.
2883  if (circ->socks_username_len > 0) {
2884  char* socks_username_escaped = esc_for_log_len(circ->socks_username,
2885  (size_t) circ->socks_username_len);
2886  smartlist_add_asprintf(descparts, "SOCKS_USERNAME=%s",
2887  socks_username_escaped);
2888  tor_free(socks_username_escaped);
2889  }
2890  if (circ->socks_password_len > 0) {
2891  char* socks_password_escaped = esc_for_log_len(circ->socks_password,
2892  (size_t) circ->socks_password_len);
2893  smartlist_add_asprintf(descparts, "SOCKS_PASSWORD=%s",
2894  socks_password_escaped);
2895  tor_free(socks_password_escaped);
2896  }
2897 
2898  rv = smartlist_join_strings(descparts, " ", 0, NULL);
2899 
2900  SMARTLIST_FOREACH(descparts, char *, cp, tor_free(cp));
2901  smartlist_free(descparts);
2902 
2903  return rv;
2904 }
2905 
2908 static int
2910  const char *question, char **answer,
2911  const char **errmsg)
2912 {
2913  const or_options_t *options = get_options();
2914  (void) control_conn;
2915  if (!strcmp(question, "circuit-status")) {
2916  smartlist_t *status = smartlist_new();
2917  SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ_) {
2918  origin_circuit_t *circ;
2919  char *circdesc;
2920  const char *state;
2921  if (! CIRCUIT_IS_ORIGIN(circ_) || circ_->marked_for_close)
2922  continue;
2923  circ = TO_ORIGIN_CIRCUIT(circ_);
2924 
2925  if (circ->base_.state == CIRCUIT_STATE_OPEN)
2926  state = "BUILT";
2927  else if (circ->base_.state == CIRCUIT_STATE_GUARD_WAIT)
2928  state = "GUARD_WAIT";
2929  else if (circ->cpath)
2930  state = "EXTENDED";
2931  else
2932  state = "LAUNCHED";
2933 
2934  circdesc = circuit_describe_status_for_controller(circ);
2935 
2936  smartlist_add_asprintf(status, "%lu %s%s%s",
2937  (unsigned long)circ->global_identifier,
2938  state, *circdesc ? " " : "", circdesc);
2939  tor_free(circdesc);
2940  }
2941  SMARTLIST_FOREACH_END(circ_);
2942  *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
2943  SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
2944  smartlist_free(status);
2945  } else if (!strcmp(question, "stream-status")) {
2946  smartlist_t *conns = get_connection_array();
2947  smartlist_t *status = smartlist_new();
2948  char buf[256];
2949  SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
2950  const char *state;
2951  entry_connection_t *conn;
2952  circuit_t *circ;
2953  origin_circuit_t *origin_circ = NULL;
2954  if (base_conn->type != CONN_TYPE_AP ||
2955  base_conn->marked_for_close ||
2956  base_conn->state == AP_CONN_STATE_SOCKS_WAIT ||
2957  base_conn->state == AP_CONN_STATE_NATD_WAIT)
2958  continue;
2959  conn = TO_ENTRY_CONN(base_conn);
2960  switch (base_conn->state)
2961  {
2964  if (conn->socks_request &&
2965  SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command))
2966  state = "NEWRESOLVE";
2967  else
2968  state = "NEW";
2969  break;
2972  state = "SENTCONNECT"; break;
2974  state = "SENTRESOLVE"; break;
2975  case AP_CONN_STATE_OPEN:
2976  state = "SUCCEEDED"; break;
2977  default:
2978  log_warn(LD_BUG, "Asked for stream in unknown state %d",
2979  base_conn->state);
2980  continue;
2981  }
2982  circ = circuit_get_by_edge_conn(ENTRY_TO_EDGE_CONN(conn));
2983  if (circ && CIRCUIT_IS_ORIGIN(circ))
2984  origin_circ = TO_ORIGIN_CIRCUIT(circ);
2985  write_stream_target_to_buf(conn, buf, sizeof(buf));
2986  smartlist_add_asprintf(status, "%lu %s %lu %s",
2987  (unsigned long) base_conn->global_identifier,state,
2988  origin_circ?
2989  (unsigned long)origin_circ->global_identifier : 0ul,
2990  buf);
2991  } SMARTLIST_FOREACH_END(base_conn);
2992  *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
2993  SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
2994  smartlist_free(status);
2995  } else if (!strcmp(question, "orconn-status")) {
2996  smartlist_t *conns = get_connection_array();
2997  smartlist_t *status = smartlist_new();
2998  SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
2999  const char *state;
3000  char name[128];
3001  or_connection_t *conn;
3002  if (base_conn->type != CONN_TYPE_OR || base_conn->marked_for_close)
3003  continue;
3004  conn = TO_OR_CONN(base_conn);
3005  if (conn->base_.state == OR_CONN_STATE_OPEN)
3006  state = "CONNECTED";
3007  else if (conn->nickname)
3008  state = "LAUNCHED";
3009  else
3010  state = "NEW";
3011  orconn_target_get_name(name, sizeof(name), conn);
3012  smartlist_add_asprintf(status, "%s %s", name, state);
3013  } SMARTLIST_FOREACH_END(base_conn);
3014  *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
3015  SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
3016  smartlist_free(status);
3017  } else if (!strcmpstart(question, "address-mappings/")) {
3018  time_t min_e, max_e;
3019  smartlist_t *mappings;
3020  question += strlen("address-mappings/");
3021  if (!strcmp(question, "all")) {
3022  min_e = 0; max_e = TIME_MAX;
3023  } else if (!strcmp(question, "cache")) {
3024  min_e = 2; max_e = TIME_MAX;
3025  } else if (!strcmp(question, "config")) {
3026  min_e = 0; max_e = 0;
3027  } else if (!strcmp(question, "control")) {
3028  min_e = 1; max_e = 1;
3029  } else {
3030  return 0;
3031  }
3032  mappings = smartlist_new();
3033  addressmap_get_mappings(mappings, min_e, max_e, 1);
3034  *answer = smartlist_join_strings(mappings, "\r\n", 0, NULL);
3035  SMARTLIST_FOREACH(mappings, char *, cp, tor_free(cp));
3036  smartlist_free(mappings);
3037  } else if (!strcmpstart(question, "status/")) {
3038  /* Note that status/ is not a catch-all for events; there's only supposed
3039  * to be a status GETINFO if there's a corresponding STATUS event. */
3040  if (!strcmp(question, "status/circuit-established")) {
3041  *answer = tor_strdup(have_completed_a_circuit() ? "1" : "0");
3042  } else if (!strcmp(question, "status/enough-dir-info")) {
3043  *answer = tor_strdup(router_have_minimum_dir_info() ? "1" : "0");
3044  } else if (!strcmp(question, "status/good-server-descriptor") ||
3045  !strcmp(question, "status/accepted-server-descriptor")) {
3046  /* They're equivalent for now, until we can figure out how to make
3047  * good-server-descriptor be what we want. See comment in
3048  * control-spec.txt. */
3049  *answer = tor_strdup(directories_have_accepted_server_descriptor()
3050  ? "1" : "0");
3051  } else if (!strcmp(question, "status/reachability-succeeded/or")) {
3052  *answer = tor_strdup(check_whether_orport_reachable(options) ?
3053  "1" : "0");
3054  } else if (!strcmp(question, "status/reachability-succeeded/dir")) {
3055  *answer = tor_strdup(check_whether_dirport_reachable(options) ?
3056  "1" : "0");
3057  } else if (!strcmp(question, "status/reachability-succeeded")) {
3058  tor_asprintf(answer, "OR=%d DIR=%d",
3059  check_whether_orport_reachable(options) ? 1 : 0,
3060  check_whether_dirport_reachable(options) ? 1 : 0);
3061  } else if (!strcmp(question, "status/bootstrap-phase")) {
3062  *answer = control_event_boot_last_msg();
3063  } else if (!strcmpstart(question, "status/version/")) {
3064  int is_server = server_mode(options);
3065  networkstatus_t *c = networkstatus_get_latest_consensus();
3066  version_status_t status;
3067  const char *recommended;
3068  if (c) {
3069  recommended = is_server ? c->server_versions : c->client_versions;
3070  status = tor_version_is_obsolete(VERSION, recommended);
3071  } else {
3072  recommended = "?";
3073  status = VS_UNKNOWN;
3074  }
3075 
3076  if (!strcmp(question, "status/version/recommended")) {
3077  *answer = tor_strdup(recommended);
3078  return 0;
3079  }
3080  if (!strcmp(question, "status/version/current")) {
3081  switch (status)
3082  {
3083  case VS_RECOMMENDED: *answer = tor_strdup("recommended"); break;
3084  case VS_OLD: *answer = tor_strdup("obsolete"); break;
3085  case VS_NEW: *answer = tor_strdup("new"); break;
3086  case VS_NEW_IN_SERIES: *answer = tor_strdup("new in series"); break;
3087  case VS_UNRECOMMENDED: *answer = tor_strdup("unrecommended"); break;
3088  case VS_EMPTY: *answer = tor_strdup("none recommended"); break;
3089  case VS_UNKNOWN: *answer = tor_strdup("unknown"); break;
3090  default: tor_fragile_assert();
3091  }
3092  }
3093  } else if (!strcmp(question, "status/clients-seen")) {
3094  char *bridge_stats = geoip_get_bridge_stats_controller(time(NULL));
3095  if (!bridge_stats) {
3096  *errmsg = "No bridge-client stats available";
3097  return -1;
3098  }
3099  *answer = bridge_stats;
3100  } else if (!strcmp(question, "status/fresh-relay-descs")) {
3101  if (!server_mode(options)) {
3102  *errmsg = "Only relays have descriptors";
3103  return -1;
3104  }
3105  routerinfo_t *r;
3106  extrainfo_t *e;
3107  if (router_build_fresh_descriptor(&r, &e) < 0) {
3108  *errmsg = "Error generating descriptor";
3109  return -1;
3110  }
3111  size_t size = r->cache_info.signed_descriptor_len + 1;
3112  if (e) {
3113  size += e->cache_info.signed_descriptor_len + 1;
3114  }
3115  tor_assert(r->cache_info.signed_descriptor_len);
3116  char *descs = tor_malloc(size);
3117  char *cp = descs;
3118  memcpy(cp, signed_descriptor_get_body(&r->cache_info),
3119  r->cache_info.signed_descriptor_len);
3120  cp += r->cache_info.signed_descriptor_len - 1;
3121  if (e) {
3122  if (cp[0] == '\0') {
3123  cp[0] = '\n';
3124  } else if (cp[0] != '\n') {
3125  cp[1] = '\n';
3126  cp++;
3127  }
3128  memcpy(cp, signed_descriptor_get_body(&e->cache_info),
3129  e->cache_info.signed_descriptor_len);
3130  cp += e->cache_info.signed_descriptor_len - 1;
3131  }
3132  if (cp[0] == '\n') {
3133  cp[0] = '\0';
3134  } else if (cp[0] != '\0') {
3135  cp[1] = '\0';
3136  }
3137  *answer = descs;
3138  routerinfo_free(r);
3139  extrainfo_free(e);
3140  } else {
3141  return 0;
3142  }
3143  }
3144  return 0;
3145 }
3146 
3149 STATIC int
3151  const char *question, char **answer,
3152  const char **errmsg)
3153 {
3154  smartlist_t *onion_list = NULL;
3155  (void) errmsg; /* no errors from this method */
3156 
3157  if (control_conn && !strcmp(question, "onions/current")) {
3158  onion_list = control_conn->ephemeral_onion_services;
3159  } else if (!strcmp(question, "onions/detached")) {
3160  onion_list = detached_onion_services;
3161  } else {
3162  return 0;
3163  }
3164  if (!onion_list || smartlist_len(onion_list) == 0) {
3165  if (answer) {
3166  *answer = tor_strdup("");
3167  }
3168  } else {
3169  if (answer) {
3170  *answer = smartlist_join_strings(onion_list, "\r\n", 0, NULL);
3171  }
3172  }
3173 
3174  return 0;
3175 }
3176 
3179 static int
3181  const char *question, char **answer,
3182  const char **errmsg)
3183 {
3184  (void)control_conn;
3185  (void)errmsg;
3186  if (strcmp(question, "network-liveness") == 0) {
3187  if (get_cached_network_liveness()) {
3188  *answer = tor_strdup("up");
3189  } else {
3190  *answer = tor_strdup("down");
3191  }
3192  }
3193 
3194  return 0;
3195 }
3196 
3199 static int
3201  const char *question, char **answer,
3202  const char **errmsg)
3203 {
3204  (void) control_conn;
3205  (void) errmsg;
3206 
3207  if (!strcmp(question, "sr/current")) {
3208  *answer = sr_get_current_for_control();
3209  } else if (!strcmp(question, "sr/previous")) {
3210  *answer = sr_get_previous_for_control();
3211  }
3212  /* Else statement here is unrecognized key so do nothing. */
3213 
3214  return 0;
3215 }
3216 
3226  const char *q, char **a,
3227  const char **error_out);
3228 
3230 typedef struct getinfo_item_t {
3231  const char *varname;
3234  const char *desc;
3235  int is_prefix;
3236 } getinfo_item_t;
3237 
3238 #define ITEM(name, fn, desc) { name, getinfo_helper_##fn, desc, 0 }
3239 #define PREFIX(name, fn, desc) { name, getinfo_helper_##fn, desc, 1 }
3240 #define DOC(name, desc) { name, NULL, desc, 0 }
3241 
3244 static const getinfo_item_t getinfo_items[] = {
3245  ITEM("version", misc, "The current version of Tor."),
3246  ITEM("bw-event-cache", misc, "Cached BW events for a short interval."),
3247  ITEM("config-file", misc, "Current location of the \"torrc\" file."),
3248  ITEM("config-defaults-file", misc, "Current location of the defaults file."),
3249  ITEM("config-text", misc,
3250  "Return the string that would be written by a saveconf command."),
3251  ITEM("config-can-saveconf", misc,
3252  "Is it possible to save the configuration to the \"torrc\" file?"),
3253  ITEM("accounting/bytes", accounting,
3254  "Number of bytes read/written so far in the accounting interval."),
3255  ITEM("accounting/bytes-left", accounting,
3256  "Number of bytes left to write/read so far in the accounting interval."),
3257  ITEM("accounting/enabled", accounting, "Is accounting currently enabled?"),
3258  ITEM("accounting/hibernating", accounting, "Are we hibernating or awake?"),
3259  ITEM("accounting/interval-start", accounting,
3260  "Time when the accounting period starts."),
3261  ITEM("accounting/interval-end", accounting,
3262  "Time when the accounting period ends."),
3263  ITEM("accounting/interval-wake", accounting,
3264  "Time to wake up in this accounting period."),
3265  ITEM("helper-nodes", entry_guards, NULL), /* deprecated */
3266  ITEM("entry-guards", entry_guards,
3267  "Which nodes are we using as entry guards?"),
3268  ITEM("fingerprint", misc, NULL),
3269  PREFIX("config/", config, "Current configuration values."),
3270  DOC("config/names",
3271  "List of configuration options, types, and documentation."),
3272  DOC("config/defaults",
3273  "List of default values for configuration options. "
3274  "See also config/names"),
3275  PREFIX("current-time/", current_time, "Current time."),
3276  DOC("current-time/local", "Current time on the local system."),
3277  DOC("current-time/utc", "Current UTC time."),
3278  PREFIX("downloads/networkstatus/", downloads,
3279  "Download statuses for networkstatus objects"),
3280  DOC("downloads/networkstatus/ns",
3281  "Download status for current-mode networkstatus download"),
3282  DOC("downloads/networkstatus/ns/bootstrap",
3283  "Download status for bootstrap-time networkstatus download"),
3284  DOC("downloads/networkstatus/ns/running",
3285  "Download status for run-time networkstatus download"),
3286  DOC("downloads/networkstatus/microdesc",
3287  "Download status for current-mode microdesc download"),
3288  DOC("downloads/networkstatus/microdesc/bootstrap",
3289  "Download status for bootstrap-time microdesc download"),
3290  DOC("downloads/networkstatus/microdesc/running",
3291  "Download status for run-time microdesc download"),
3292  PREFIX("downloads/cert/", downloads,
3293  "Download statuses for certificates, by id fingerprint and "
3294  "signing key"),
3295  DOC("downloads/cert/fps",
3296  "List of authority fingerprints for which any download statuses "
3297  "exist"),
3298  DOC("downloads/cert/fp/<fp>",
3299  "Download status for <fp> with the default signing key; corresponds "
3300  "to /fp/ URLs on directory server."),
3301  DOC("downloads/cert/fp/<fp>/sks",
3302  "List of signing keys for which specific download statuses are "
3303  "available for this id fingerprint"),
3304  DOC("downloads/cert/fp/<fp>/<sk>",
3305  "Download status for <fp> with signing key <sk>; corresponds "
3306  "to /fp-sk/ URLs on directory server."),
3307  PREFIX("downloads/desc/", downloads,
3308  "Download statuses for router descriptors, by descriptor digest"),
3309  DOC("downloads/desc/descs",
3310  "Return a list of known router descriptor digests"),
3311  DOC("downloads/desc/<desc>",
3312  "Return a download status for a given descriptor digest"),
3313  PREFIX("downloads/bridge/", downloads,
3314  "Download statuses for bridge descriptors, by bridge identity "
3315  "digest"),
3316  DOC("downloads/bridge/bridges",
3317  "Return a list of configured bridge identity digests with download "
3318  "statuses"),
3319  DOC("downloads/bridge/<desc>",
3320  "Return a download status for a given bridge identity digest"),
3321  ITEM("info/names", misc,
3322  "List of GETINFO options, types, and documentation."),
3323  ITEM("events/names", misc,
3324  "Events that the controller can ask for with SETEVENTS."),
3325  ITEM("signal/names", misc, "Signal names recognized by the SIGNAL command"),
3326  ITEM("features/names", misc, "What arguments can USEFEATURE take?"),
3327  PREFIX("desc/id/", dir, "Router descriptors by ID."),
3328  PREFIX("desc/name/", dir, "Router descriptors by nickname."),
3329  ITEM("desc/all-recent", dir,
3330  "All non-expired, non-superseded router descriptors."),
3331  ITEM("desc/download-enabled", dir,
3332  "Do we try to download router descriptors?"),
3333  ITEM("desc/all-recent-extrainfo-hack", dir, NULL), /* Hack. */
3334  ITEM("md/all", dir, "All known microdescriptors."),
3335  PREFIX("md/id/", dir, "Microdescriptors by ID"),
3336  PREFIX("md/name/", dir, "Microdescriptors by name"),
3337  ITEM("md/download-enabled", dir,
3338  "Do we try to download microdescriptors?"),
3339  PREFIX("extra-info/digest/", dir, "Extra-info documents by digest."),
3340  PREFIX("hs/client/desc/id", dir,
3341  "Hidden Service descriptor in client's cache by onion."),
3342  PREFIX("hs/service/desc/id/", dir,
3343  "Hidden Service descriptor in services's cache by onion."),
3344  PREFIX("net/listeners/", listeners, "Bound addresses by type"),
3345  ITEM("ns/all", networkstatus,
3346  "Brief summary of router status (v2 directory format)"),
3347  PREFIX("ns/id/", networkstatus,
3348  "Brief summary of router status by ID (v2 directory format)."),
3349  PREFIX("ns/name/", networkstatus,
3350  "Brief summary of router status by nickname (v2 directory format)."),
3351  PREFIX("ns/purpose/", networkstatus,
3352  "Brief summary of router status by purpose (v2 directory format)."),
3353  PREFIX("consensus/", networkstatus,
3354  "Information about and from the ns consensus."),
3355  ITEM("network-status", dir,
3356  "Brief summary of router status (v1 directory format)"),
3357  ITEM("network-liveness", liveness,
3358  "Current opinion on whether the network is live"),
3359  ITEM("circuit-status", events, "List of current circuits originating here."),
3360  ITEM("stream-status", events,"List of current streams."),
3361  ITEM("orconn-status", events, "A list of current OR connections."),
3362  ITEM("dormant", misc,
3363  "Is Tor dormant (not building circuits because it's idle)?"),
3364  PREFIX("address-mappings/", events, NULL),
3365  DOC("address-mappings/all", "Current address mappings."),
3366  DOC("address-mappings/cache", "Current cached DNS replies."),
3367  DOC("address-mappings/config",
3368  "Current address mappings from configuration."),
3369  DOC("address-mappings/control", "Current address mappings from controller."),
3370  PREFIX("status/", events, NULL),
3371  DOC("status/circuit-established",
3372  "Whether we think client functionality is working."),
3373  DOC("status/enough-dir-info",
3374  "Whether we have enough up-to-date directory information to build "
3375  "circuits."),
3376  DOC("status/bootstrap-phase",
3377  "The last bootstrap phase status event that Tor sent."),
3378  DOC("status/clients-seen",
3379  "Breakdown of client countries seen by a bridge."),
3380  DOC("status/fresh-relay-descs",
3381  "A fresh relay/ei descriptor pair for Tor's current state. Not stored."),
3382  DOC("status/version/recommended", "List of currently recommended versions."),
3383  DOC("status/version/current", "Status of the current version."),
3384  ITEM("address", misc, "IP address of this Tor host, if we can guess it."),
3385  ITEM("traffic/read", misc,"Bytes read since the process was started."),
3386  ITEM("traffic/written", misc,
3387  "Bytes written since the process was started."),
3388  ITEM("uptime", misc, "Uptime of the Tor daemon in seconds."),
3389  ITEM("process/pid", misc, "Process id belonging to the main tor process."),
3390  ITEM("process/uid", misc, "User id running the tor process."),
3391  ITEM("process/user", misc,
3392  "Username under which the tor process is running."),
3393  ITEM("process/descriptor-limit", misc, "File descriptor limit."),
3394  ITEM("limits/max-mem-in-queues", misc, "Actual limit on memory in queues"),
3395  PREFIX("desc-annotations/id/", dir, "Router annotations by hexdigest."),
3396  PREFIX("dir/server/", dir,"Router descriptors as retrieved from a DirPort."),
3397  PREFIX("dir/status/", dir,
3398  "v2 networkstatus docs as retrieved from a DirPort."),
3399  ITEM("dir/status-vote/current/consensus", dir,
3400  "v3 Networkstatus consensus as retrieved from a DirPort."),
3401  ITEM("exit-policy/default", policies,
3402  "The default value appended to the configured exit policy."),
3403  ITEM("exit-policy/reject-private/default", policies,
3404  "The default rules appended to the configured exit policy by"
3405  " ExitPolicyRejectPrivate."),
3406  ITEM("exit-policy/reject-private/relay", policies,
3407  "The relay-specific rules appended to the configured exit policy by"
3408  " ExitPolicyRejectPrivate and/or ExitPolicyRejectLocalInterfaces."),
3409  ITEM("exit-policy/full", policies, "The entire exit policy of onion router"),
3410  ITEM("exit-policy/ipv4", policies, "IPv4 parts of exit policy"),
3411  ITEM("exit-policy/ipv6", policies, "IPv6 parts of exit policy"),
3412  PREFIX("ip-to-country/", geoip, "Perform a GEOIP lookup"),
3413  ITEM("onions/current", onions,
3414  "Onion services owned by the current control connection."),
3415  ITEM("onions/detached", onions,
3416  "Onion services detached from the control connection."),
3417  ITEM("sr/current", sr, "Get current shared random value."),
3418  ITEM("sr/previous", sr, "Get previous shared random value."),
3419  { NULL, NULL, NULL, 0 }
3420 };
3421 
3423 static char *
3425 {
3426  int i;
3427  smartlist_t *lines = smartlist_new();
3428  char *ans;
3429  for (i = 0; getinfo_items[i].varname; ++i) {
3430  if (!getinfo_items[i].desc)
3431  continue;
3432 
3433  smartlist_add_asprintf(lines, "%s%s -- %s\n",
3434  getinfo_items[i].varname,
3435  getinfo_items[i].is_prefix ? "*" : "",
3436  getinfo_items[i].desc);
3437  }
3438  smartlist_sort_strings(lines);
3439 
3440  ans = smartlist_join_strings(lines, "", 0, NULL);
3441  SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
3442  smartlist_free(lines);
3443 
3444  return ans;
3445 }
3446 
3451 static int
3453  const char *question, char **answer,
3454  const char **err_out)
3455 {
3456  int i;
3457  *answer = NULL; /* unrecognized key by default */
3458 
3459  for (i = 0; getinfo_items[i].varname; ++i) {
3460  int match;
3461  if (getinfo_items[i].is_prefix)
3462  match = !strcmpstart(question, getinfo_items[i].varname);
3463  else
3464  match = !strcmp(question, getinfo_items[i].varname);
3465  if (match) {
3466  tor_assert(getinfo_items[i].fn);
3467  return getinfo_items[i].fn(control_conn, question, answer, err_out);
3468  }
3469  }
3470 
3471  return 0; /* unrecognized */
3472 }
3473 
3476 static int
3478  const char *body)
3479 {
3480  smartlist_t *questions = smartlist_new();
3481  smartlist_t *answers = smartlist_new();
3482  smartlist_t *unrecognized = smartlist_new();
3483  char *ans = NULL;
3484  int i;
3485  (void) len; /* body is NUL-terminated, so it's safe to ignore the length. */
3486 
3487  smartlist_split_string(questions, body, " ",
3488  SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
3489  SMARTLIST_FOREACH_BEGIN(questions, const char *, q) {
3490  const char *errmsg = NULL;
3491 
3492  if (handle_getinfo_helper(conn, q, &ans, &errmsg) < 0) {
3493  if (!errmsg)
3494  errmsg = "Internal error";
3495  connection_printf_to_buf(conn, "551 %s\r\n", errmsg);
3496  goto done;
3497  }
3498  if (!ans) {
3499  if (errmsg) /* use provided error message */
3500  smartlist_add_strdup(unrecognized, errmsg);
3501  else /* use default error message */
3502  smartlist_add_asprintf(unrecognized, "Unrecognized key \"%s\"", q);
3503  } else {
3504  smartlist_add_strdup(answers, q);
3505  smartlist_add(answers, ans);
3506  }
3507  } SMARTLIST_FOREACH_END(q);
3508 
3509  if (smartlist_len(unrecognized)) {
3510  /* control-spec section 2.3, mid-reply '-' or end of reply ' ' */
3511  for (i=0; i < smartlist_len(unrecognized)-1; ++i)
3513  "552-%s\r\n",
3514  (char *)smartlist_get(unrecognized, i));
3515 
3517  "552 %s\r\n",
3518  (char *)smartlist_get(unrecognized, i));
3519  goto done;
3520  }
3521 
3522  for (i = 0; i < smartlist_len(answers); i += 2) {
3523  char *k = smartlist_get(answers, i);
3524  char *v = smartlist_get(answers, i+1);
3525  if (!strchr(v, '\n') && !strchr(v, '\r')) {
3526  connection_printf_to_buf(conn, "250-%s=", k);
3527  connection_write_str_to_buf(v, conn);
3528  connection_write_str_to_buf("\r\n", conn);
3529  } else {
3530  char *esc = NULL;
3531  size_t esc_len;
3532  esc_len = write_escaped_data(v, strlen(v), &esc);
3533  connection_printf_to_buf(conn, "250+%s=\r\n", k);
3534  connection_buf_add(esc, esc_len, TO_CONN(conn));
3535  tor_free(esc);
3536  }
3537  }
3538  connection_write_str_to_buf("250 OK\r\n", conn);
3539 
3540  done:
3541  SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
3542  smartlist_free(answers);
3543  SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
3544  smartlist_free(questions);
3545  SMARTLIST_FOREACH(unrecognized, char *, cp, tor_free(cp));
3546  smartlist_free(unrecognized);
3547 
3548  return 0;
3549 }
3550 
3552 static uint8_t
3553 circuit_purpose_from_string(const char *string)
3554 {
3555  if (!strcasecmpstart(string, "purpose="))
3556  string += strlen("purpose=");
3557 
3558  if (!strcasecmp(string, "general"))
3560  else if (!strcasecmp(string, "controller"))
3562  else
3563  return CIRCUIT_PURPOSE_UNKNOWN;
3564 }
3565 
3571 static smartlist_t *
3572 getargs_helper(const char *command, control_connection_t *conn,
3573  const char *body, int min_args, int max_args)
3574 {
3575  smartlist_t *args = smartlist_new();
3576  smartlist_split_string(args, body, " ",
3577  SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
3578  if (smartlist_len(args) < min_args) {
3579  connection_printf_to_buf(conn, "512 Missing argument to %s\r\n",command);
3580  goto err;
3581  } else if (max_args >= 0 && smartlist_len(args) > max_args) {
3582  connection_printf_to_buf(conn, "512 Too many arguments to %s\r\n",command);
3583  goto err;
3584  }
3585  return args;
3586  err:
3587  SMARTLIST_FOREACH(args, char *, s, tor_free(s));
3588  smartlist_free(args);
3589  return NULL;
3590 }
3591 
3595 static const char *
3596 find_element_starting_with(smartlist_t *sl, int start_at, const char *prefix)
3597 {
3598  int i;
3599  for (i = start_at; i < smartlist_len(sl); ++i) {
3600  const char *elt = smartlist_get(sl, i);
3601  if (!strcasecmpstart(elt, prefix))
3602  return elt;
3603  }
3604  return NULL;
3605 }
3606 
3609 static int
3610 is_keyval_pair(const char *s)
3611 {
3612  /* An argument is a key-value pair if it has an =, and it isn't of the form
3613  * $fingeprint=name */
3614  return strchr(s, '=') && s[0] != '$';
3615 }
3616 
3619 static int
3621  const char *body)
3622 {
3623  smartlist_t *router_nicknames=NULL, *nodes=NULL;
3624  origin_circuit_t *circ = NULL;
3625  int zero_circ;
3626  uint8_t intended_purpose = CIRCUIT_PURPOSE_C_GENERAL;
3627  smartlist_t *args;
3628  (void) len;
3629 
3630  router_nicknames = smartlist_new();
3631 
3632  args = getargs_helper("EXTENDCIRCUIT", conn, body, 1, -1);
3633  if (!args)
3634  goto done;
3635 
3636  zero_circ = !strcmp("0", (char*)smartlist_get(args,0));
3637 
3638  if (zero_circ) {
3639  const char *purp = find_element_starting_with(args, 1, "PURPOSE=");
3640 
3641  if (purp) {
3642  intended_purpose = circuit_purpose_from_string(purp);
3643  if (intended_purpose == CIRCUIT_PURPOSE_UNKNOWN) {
3644  connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n", purp);
3645  SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
3646  smartlist_free(args);
3647  goto done;
3648  }
3649  }
3650 
3651  if ((smartlist_len(args) == 1) ||
3652  (smartlist_len(args) >= 2 && is_keyval_pair(smartlist_get(args, 1)))) {
3653  // "EXTENDCIRCUIT 0" || EXTENDCIRCUIT 0 foo=bar"
3654  circ = circuit_launch(intended_purpose, CIRCLAUNCH_NEED_CAPACITY);
3655  if (!circ) {
3656  connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
3657  } else {
3658  connection_printf_to_buf(conn, "250 EXTENDED %lu\r\n",
3659  (unsigned long)circ->global_identifier);
3660  }
3661  SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
3662  smartlist_free(args);
3663  goto done;
3664  }
3665  // "EXTENDCIRCUIT 0 router1,router2" ||
3666  // "EXTENDCIRCUIT 0 router1,router2 PURPOSE=foo"
3667  }
3668 
3669  if (!zero_circ && !(circ = get_circ(smartlist_get(args,0)))) {
3670  connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
3671  (char*)smartlist_get(args, 0));
3672  SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
3673  smartlist_free(args);
3674  goto done;
3675  }
3676 
3677  if (smartlist_len(args) < 2) {
3679  "512 syntax error: not enough arguments.\r\n");
3680  SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
3681  smartlist_free(args);
3682  goto done;
3683  }
3684 
3685  smartlist_split_string(router_nicknames, smartlist_get(args,1), ",", 0, 0);
3686 
3687  SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
3688  smartlist_free(args);
3689 
3690  nodes = smartlist_new();
3691  int first_node = zero_circ;
3692  SMARTLIST_FOREACH_BEGIN(router_nicknames, const char *, n) {
3693  const node_t *node = node_get_by_nickname(n, 0);
3694  if (!node) {
3695  connection_printf_to_buf(conn, "552 No such router \"%s\"\r\n", n);
3696  goto done;
3697  }
3698  if (!node_has_preferred_descriptor(node, first_node)) {
3699  connection_printf_to_buf(conn, "552 No descriptor for \"%s\"\r\n", n);
3700  goto done;
3701  }
3702  smartlist_add(nodes, (void*)node);
3703  first_node = 0;
3704  } SMARTLIST_FOREACH_END(n);
3705  if (!smartlist_len(nodes)) {
3706  connection_write_str_to_buf("512 No router names provided\r\n", conn);
3707  goto done;
3708  }
3709 
3710  if (zero_circ) {
3711  /* start a new circuit */
3712  circ = origin_circuit_init(intended_purpose, 0);
3713  }
3714 
3715  /* now circ refers to something that is ready to be extended */
3716  first_node = zero_circ;
3717  SMARTLIST_FOREACH(nodes, const node_t *, node,
3718  {
3719  extend_info_t *info = extend_info_from_node(node, first_node);
3720  if (!info) {
3721  tor_assert_nonfatal(first_node);
3722  log_warn(LD_CONTROL,
3723  "controller tried to connect to a node that lacks a suitable "
3724  "descriptor, or which doesn't have any "
3725  "addresses that are allowed by the firewall configuration; "
3726  "circuit marked for closing.");
3727  circuit_mark_for_close(TO_CIRCUIT(circ), -END_CIRC_REASON_CONNECTFAILED);
3728  connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
3729  goto done;
3730  }
3731  circuit_append_new_exit(circ, info);
3732  if (circ->build_state->desired_path_len > 1) {
3733  circ->build_state->onehop_tunnel = 0;
3734  }
3735  extend_info_free(info);
3736  first_node = 0;
3737  });
3738 
3739  /* now that we've populated the cpath, start extending */
3740  if (zero_circ) {
3741  int err_reason = 0;
3742  if ((err_reason = circuit_handle_first_hop(circ)) < 0) {
3743  circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
3744  connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
3745  goto done;
3746  }
3747  } else {
3748  if (circ->base_.state == CIRCUIT_STATE_OPEN ||
3749  circ->base_.state == CIRCUIT_STATE_GUARD_WAIT) {
3750  int err_reason = 0;
3752  if ((err_reason = circuit_send_next_onion_skin(circ)) < 0) {
3753  log_info(LD_CONTROL,
3754  "send_next_onion_skin failed; circuit marked for closing.");
3755  circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
3756  connection_write_str_to_buf("551 Couldn't send onion skin\r\n", conn);
3757  goto done;
3758  }
3759  }
3760  }
3761 
3762  connection_printf_to_buf(conn, "250 EXTENDED %lu\r\n",
3763  (unsigned long)circ->global_identifier);
3764  if (zero_circ) /* send a 'launched' event, for completeness */
3765  circuit_event_status(circ, CIRC_EVENT_LAUNCHED, 0);
3766  done:
3767  SMARTLIST_FOREACH(router_nicknames, char *, n, tor_free(n));
3768  smartlist_free(router_nicknames);
3769  smartlist_free(nodes);
3770  return 0;
3771 }
3772 
3775 static int
3777  uint32_t len, const char *body)
3778 {
3779  origin_circuit_t *circ = NULL;
3780  uint8_t new_purpose;
3781  smartlist_t *args;
3782  (void) len; /* body is NUL-terminated, so it's safe to ignore the length. */
3783 
3784  args = getargs_helper("SETCIRCUITPURPOSE", conn, body, 2, -1);
3785  if (!args)
3786  goto done;
3787 
3788  if (!(circ = get_circ(smartlist_get(args,0)))) {
3789  connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
3790  (char*)smartlist_get(args, 0));
3791  goto done;
3792  }
3793 
3794  {
3795  const char *purp = find_element_starting_with(args,1,"PURPOSE=");
3796  if (!purp) {
3797  connection_write_str_to_buf("552 No purpose given\r\n", conn);
3798  goto done;
3799  }
3800  new_purpose = circuit_purpose_from_string(purp);
3801  if (new_purpose == CIRCUIT_PURPOSE_UNKNOWN) {
3802  connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n", purp);
3803  goto done;
3804  }
3805  }
3806 
3807  circuit_change_purpose(TO_CIRCUIT(circ), new_purpose);
3808  connection_write_str_to_buf("250 OK\r\n", conn);
3809 
3810  done:
3811  if (args) {
3812  SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
3813  smartlist_free(args);
3814  }
3815  return 0;
3816 }
3817 
3820 static int
3822  const char *body)
3823 {
3824  entry_connection_t *ap_conn = NULL;
3825  origin_circuit_t *circ = NULL;
3826  int zero_circ;
3827  smartlist_t *args;
3828  crypt_path_t *cpath=NULL;
3829  int hop=0, hop_line_ok=1;
3830  (void) len;
3831 
3832  args = getargs_helper("ATTACHSTREAM", conn, body, 2, -1);
3833  if (!args)
3834  return 0;
3835 
3836  zero_circ = !strcmp("0", (char*)smartlist_get(args,1));
3837 
3838  if (!(ap_conn = get_stream(smartlist_get(args, 0)))) {
3839  connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
3840  (char*)smartlist_get(args, 0));
3841  } else if (!zero_circ && !(circ = get_circ(smartlist_get(args, 1)))) {
3842  connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
3843  (char*)smartlist_get(args, 1));
3844  } else if (circ) {
3845  const char *hopstring = find_element_starting_with(args,2,"HOP=");
3846  if (hopstring) {
3847  hopstring += strlen("HOP=");
3848  hop = (int) tor_parse_ulong(hopstring, 10, 0, INT_MAX,
3849  &hop_line_ok, NULL);
3850  if (!hop_line_ok) { /* broken hop line */
3851  connection_printf_to_buf(conn, "552 Bad value hop=%s\r\n", hopstring);
3852  }
3853  }
3854  }
3855  SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
3856  smartlist_free(args);
3857  if (!ap_conn || (!zero_circ && !circ) || !hop_line_ok)
3858  return 0;
3859 
3860  if (ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONTROLLER_WAIT &&
3861  ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONNECT_WAIT &&
3862  ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_RESOLVE_WAIT) {
3864  "555 Connection is not managed by controller.\r\n",
3865  conn);
3866  return 0;
3867  }
3868 
3869  /* Do we need to detach it first? */
3870  if (ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONTROLLER_WAIT) {
3871  edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
3872  circuit_t *tmpcirc = circuit_get_by_edge_conn(edge_conn);
3873  connection_edge_end(edge_conn, END_STREAM_REASON_TIMEOUT);
3874  /* Un-mark it as ending, since we're going to reuse it. */
3875  edge_conn->edge_has_sent_end = 0;
3876  edge_conn->end_reason = 0;
3877  if (tmpcirc)
3878  circuit_detach_stream(tmpcirc, edge_conn);
3879  CONNECTION_AP_EXPECT_NONPENDING(ap_conn);
3880  TO_CONN(edge_conn)->state = AP_CONN_STATE_CONTROLLER_WAIT;
3881  }
3882 
3883  if (circ && (circ->base_.state != CIRCUIT_STATE_OPEN)) {
3885  "551 Can't attach stream to non-open origin circuit\r\n",
3886  conn);
3887  return 0;
3888  }
3889  /* Is this a single hop circuit? */
3890  if (circ && (circuit_get_cpath_len(circ)<2 || hop==1)) {
3892  "551 Can't attach stream to this one-hop circuit.\r\n", conn);
3893  return 0;
3894  }
3895 
3896  if (circ && hop>0) {
3897  /* find this hop in the circuit, and set cpath */
3898  cpath = circuit_get_cpath_hop(circ, hop);
3899  if (!cpath) {
3901  "551 Circuit doesn't have %d hops.\r\n", hop);
3902  return 0;
3903  }
3904  }
3905  if (connection_ap_handshake_rewrite_and_attach(ap_conn, circ, cpath) < 0) {
3906  connection_write_str_to_buf("551 Unable to attach stream\r\n", conn);
3907  return 0;
3908  }
3909  send_control_done(conn);
3910  return 0;
3911 }
3912 
3915 static int
3917  const char *body)
3918 {
3919  char *desc;
3920  const char *msg=NULL;
3921  uint8_t purpose = ROUTER_PURPOSE_GENERAL;
3922  int cache = 0; /* eventually, we may switch this to 1 */
3923 
3924  const char *cp = memchr(body, '\n', len);
3925 
3926  if (cp == NULL) {
3927  connection_printf_to_buf(conn, "251 Empty body\r\n");
3928  return 0;
3929  }
3930  ++cp;
3931 
3932  char *cmdline = tor_memdup_nulterm(body, cp-body);
3933  smartlist_t *args = smartlist_new();
3934  smartlist_split_string(args, cmdline, " ",
3935  SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
3936  SMARTLIST_FOREACH_BEGIN(args, char *, option) {
3937  if (!strcasecmpstart(option, "purpose=")) {
3938  option += strlen("purpose=");
3939  purpose = router_purpose_from_string(option);
3940  if (purpose == ROUTER_PURPOSE_UNKNOWN) {
3941  connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n",
3942  option);
3943  goto done;
3944  }
3945  } else if (!strcasecmpstart(option, "cache=")) {
3946  option += strlen("cache=");
3947  if (!strcasecmp(option, "no"))
3948  cache = 0;
3949  else if (!strcasecmp(option, "yes"))
3950  cache = 1;
3951  else {
3952  connection_printf_to_buf(conn, "552 Unknown cache request \"%s\"\r\n",
3953  option);
3954  goto done;
3955  }
3956  } else { /* unrecognized argument? */
3958  "512 Unexpected argument \"%s\" to postdescriptor\r\n", option);
3959  goto done;
3960  }
3961  } SMARTLIST_FOREACH_END(option);
3962 
3963  read_escaped_data(cp, len-(cp-body), &desc);
3964 
3965  switch (router_load_single_router(desc, purpose, cache, &msg)) {
3966  case -1:
3967  if (!msg) msg = "Could not parse descriptor";
3968  connection_printf_to_buf(conn, "554 %s\r\n", msg);
3969  break;
3970  case 0:
3971  if (!msg) msg = "Descriptor not added";
3972  connection_printf_to_buf(conn, "251 %s\r\n",msg);
3973  break;
3974  case 1:
3975  send_control_done(conn);
3976  break;
3977  }
3978 
3979  tor_free(desc);
3980  done:
3981  SMARTLIST_FOREACH(args, char *, arg, tor_free(arg));
3982  smartlist_free(args);
3983  tor_free(cmdline);
3984  return 0;
3985 }
3986 
3989 static int
3991  const char *body)
3992 {
3993  entry_connection_t *ap_conn = NULL;
3994  char *new_addr = NULL;
3995  uint16_t new_port = 0;
3996  smartlist_t *args;
3997  (void) len;
3998 
3999  args = getargs_helper("REDIRECTSTREAM", conn, body, 2, -1);
4000  if (!args)
4001  return 0;
4002 
4003  if (!(ap_conn = get_stream(smartlist_get(args, 0)))
4004  || !ap_conn->socks_request) {
4005  connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
4006  (char*)smartlist_get(args, 0));
4007  } else {
4008  int ok = 1;
4009  if (smartlist_len(args) > 2) { /* they included a port too */
4010  new_port = (uint16_t) tor_parse_ulong(smartlist_get(args, 2),
4011  10, 1, 65535, &ok, NULL);
4012  }
4013  if (!ok) {
4014  connection_printf_to_buf(conn, "512 Cannot parse port \"%s\"\r\n",
4015  (char*)smartlist_get(args, 2));
4016  } else {
4017  new_addr = tor_strdup(smartlist_get(args, 1));
4018  }
4019  }
4020 
4021  SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
4022  smartlist_free(args);
4023  if (!new_addr)
4024  return 0;
4025 
4026  strlcpy(ap_conn->socks_request->address, new_addr,
4027  sizeof(ap_conn->socks_request->address));
4028  if (new_port)
4029  ap_conn->socks_request->port = new_port;
4030  tor_free(new_addr);
4031  send_control_done(conn);
4032  return 0;
4033 }
4034 
4037 static int
4039  const char *body)
4040 {
4041  entry_connection_t *ap_conn=NULL;
4042  uint8_t reason=0;
4043  smartlist_t *args;
4044  int ok;
4045  (void) len;
4046 
4047  args = getargs_helper("CLOSESTREAM", conn, body, 2, -1);
4048  if (!args)
4049  return 0;
4050 
4051  else if (!(ap_conn = get_stream(smartlist_get(args, 0))))
4052  connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
4053  (char*)smartlist_get(args, 0));
4054  else {
4055  reason = (uint8_t) tor_parse_ulong(smartlist_get(args,1), 10, 0, 255,
4056  &ok, NULL);
4057  if (!ok) {
4058  connection_printf_to_buf(conn, "552 Unrecognized reason \"%s\"\r\n",
4059  (char*)smartlist_get(args, 1));
4060  ap_conn = NULL;
4061  }
4062  }
4063  SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
4064  smartlist_free(args);
4065  if (!ap_conn)
4066  return 0;
4067 
4068  connection_mark_unattached_ap(ap_conn, reason);
4069  send_control_done(conn);
4070  return 0;
4071 }
4072 
4075 static int
4077  const char *body)
4078 {
4079  origin_circuit_t *circ = NULL;
4080  int safe = 0;
4081  smartlist_t *args;
4082  (void) len;
4083 
4084  args = getargs_helper("CLOSECIRCUIT", conn, body, 1, -1);
4085  if (!args)
4086  return 0;
4087 
4088  if (!(circ=get_circ(smartlist_get(args, 0))))
4089  connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
4090  (char*)smartlist_get(args, 0));
4091  else {
4092  int i;
4093  for (i=1; i < smartlist_len(args); ++i) {
4094  if (!strcasecmp(smartlist_get(args, i), "IfUnused"))
4095  safe = 1;
4096  else
4097  log_info(LD_CONTROL, "Skipping unknown option %s",
4098  (char*)smartlist_get(args,i));
4099  }
4100  }
4101  SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
4102  smartlist_free(args);
4103  if (!circ)
4104  return 0;
4105 
4106  if (!safe || !circ->p_streams) {
4107  circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_REQUESTED);
4108  }
4109 
4110  send_control_done(conn);
4111  return 0;
4112 }
4113 
4116 static int
4118  const char *body)
4119 {
4120  smartlist_t *args, *failed;
4121  int is_reverse = 0;
4122  (void) len; /* body is nul-terminated; it's safe to ignore the length */
4123 
4124  if (!(conn->event_mask & (((event_mask_t)1)<<EVENT_ADDRMAP))) {
4125  log_warn(LD_CONTROL, "Controller asked us to resolve an address, but "
4126  "isn't listening for ADDRMAP events. It probably won't see "
4127  "the answer.");
4128  }
4129  args = smartlist_new();
4130  smartlist_split_string(args, body, " ",
4131  SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
4132  {
4133  const char *modearg = find_element_starting_with(args, 0, "mode=");
4134  if (modearg && !strcasecmp(modearg, "mode=reverse"))
4135  is_reverse = 1;
4136  }
4137  failed = smartlist_new();
4138  SMARTLIST_FOREACH(args, const char *, arg, {
4139  if (!is_keyval_pair(arg)) {
4140  if (dnsserv_launch_request(arg, is_reverse, conn)<0)
4141  smartlist_add(failed, (char*)arg);
4142  }
4143  });
4144 
4145  send_control_done(conn);
4146  SMARTLIST_FOREACH(failed, const char *, arg, {
4147  control_event_address_mapped(arg, arg, time(NULL),
4148  "internal", 0);
4149  });
4150 
4151  SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
4152  smartlist_free(args);
4153  smartlist_free(failed);
4154  return 0;
4155 }
4156 
4158 static int
4160  const char *body)
4161 {
4162  const char *bad_arg = NULL;
4163  smartlist_t *args;
4164  (void)len;
4165 
4166  conn->have_sent_protocolinfo = 1;
4167  args = smartlist_new();
4168  smartlist_split_string(args, body, " ",
4169  SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
4170  SMARTLIST_FOREACH(args, const char *, arg, {
4171  int ok;
4172  tor_parse_long(arg, 10, 0, LONG_MAX, &ok, NULL);
4173  if (!ok) {
4174  bad_arg = arg;
4175  break;
4176  }
4177  });
4178  if (bad_arg) {
4179  connection_printf_to_buf(conn, "513 No such version %s\r\n",
4180  escaped(bad_arg));
4181  /* Don't tolerate bad arguments when not authenticated. */
4182  if (!STATE_IS_OPEN(TO_CONN(conn)->state))
4183  connection_mark_for_close(TO_CONN(conn));
4184  goto done;
4185  } else {
4186  const or_options_t *options = get_options();
4187  int cookies = options->CookieAuthentication;
4188  char *cfile = get_controller_cookie_file_name();
4189  char *abs_cfile;
4190  char *esc_cfile;
4191  char *methods;
4192  abs_cfile = make_path_absolute(cfile);
4193  esc_cfile = esc_for_log(abs_cfile);
4194  {
4195  int passwd = (options->HashedControlPassword != NULL ||
4196  options->HashedControlSessionPassword != NULL);
4197  smartlist_t *mlist = smartlist_new();
4198  if (cookies) {
4199  smartlist_add(mlist, (char*)"COOKIE");
4200  smartlist_add(mlist, (char*)"SAFECOOKIE");
4201  }
4202  if (passwd)
4203  smartlist_add(mlist, (char*)"HASHEDPASSWORD");
4204  if (!cookies && !passwd)
4205  smartlist_add(mlist, (char*)"NULL");
4206  methods = smartlist_join_strings(mlist, ",", 0, NULL);
4207  smartlist_free(mlist);
4208  }
4209 
4211  "250-PROTOCOLINFO 1\r\n"
4212  "250-AUTH METHODS=%s%s%s\r\n"
4213  "250-VERSION Tor=%s\r\n"
4214  "250 OK\r\n",
4215  methods,
4216  cookies?" COOKIEFILE=":"",
4217  cookies?esc_cfile:"",
4218  escaped(VERSION));
4219  tor_free(methods);
4220  tor_free(cfile);
4221  tor_free(abs_cfile);
4222  tor_free(esc_cfile);
4223  }
4224  done:
4225  SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
4226  smartlist_free(args);
4227  return 0;
4228 }
4229 
4231 static int
4233  const char *body)
4234 {
4235  const char *cp = body;
4236  char *client_nonce;
4237  size_t client_nonce_len;
4238  char server_hash[DIGEST256_LEN];
4239  char server_hash_encoded[HEX_DIGEST256_LEN+1];
4240  char server_nonce[SAFECOOKIE_SERVER_NONCE_LEN];
4241  char server_nonce_encoded[(2*SAFECOOKIE_SERVER_NONCE_LEN) + 1];
4242 
4243  cp += strspn(cp, " \t\n\r");
4244  if (!strcasecmpstart(cp, "SAFECOOKIE")) {
4245  cp += strlen("SAFECOOKIE");
4246  } else {
4247  connection_write_str_to_buf("513 AUTHCHALLENGE only supports SAFECOOKIE "
4248  "authentication\r\n", conn);
4249  connection_mark_for_close(TO_CONN(conn));
4250  return -1;
4251  }
4252 
4254  connection_write_str_to_buf("515 Cookie authentication is disabled\r\n",
4255  conn);
4256  connection_mark_for_close(TO_CONN(conn));
4257  return -1;
4258  }
4259 
4260  cp += strspn(cp, " \t\n\r");
4261  if (*cp == '"') {
4262  const char *newcp =
4263  decode_escaped_string(cp, len - (cp - body),
4264  &client_nonce, &client_nonce_len);
4265  if (newcp == NULL) {
4266  connection_write_str_to_buf("513 Invalid quoted client nonce\r\n",
4267  conn);
4268  connection_mark_for_close(TO_CONN(conn));
4269  return -1;
4270  }
4271  cp = newcp;
4272  } else {
4273  size_t client_nonce_encoded_len = strspn(cp, "0123456789ABCDEFabcdef");
4274 
4275  client_nonce_len = client_nonce_encoded_len / 2;
4276  client_nonce = tor_malloc_zero(client_nonce_len);
4277 
4278  if (base16_decode(client_nonce, client_nonce_len,
4279  cp, client_nonce_encoded_len)
4280  != (int) client_nonce_len) {
4281  connection_write_str_to_buf("513 Invalid base16 client nonce\r\n",
4282  conn);
4283  connection_mark_for_close(TO_CONN(conn));
4284  tor_free(client_nonce);
4285  return -1;
4286  }
4287 
4288  cp += client_nonce_encoded_len;
4289  }
4290 
4291  cp += strspn(cp, " \t\n\r");
4292  if (*cp != '\0' ||
4293  cp != body + len) {
4294  connection_write_str_to_buf("513 Junk at end of AUTHCHALLENGE command\r\n",
4295  conn);
4296  connection_mark_for_close(TO_CONN(conn));
4297  tor_free(client_nonce);
4298  return -1;
4299  }
4300  crypto_rand(server_nonce, SAFECOOKIE_SERVER_NONCE_LEN);
4301 
4302  /* Now compute and send the server-to-controller response, and the
4303  * server's nonce. */
4305 
4306  {
4307  size_t tmp_len = (AUTHENTICATION_COOKIE_LEN +
4308  client_nonce_len +
4309  SAFECOOKIE_SERVER_NONCE_LEN);
4310  char *tmp = tor_malloc_zero(tmp_len);
4311  char *client_hash = tor_malloc_zero(DIGEST256_LEN);
4313  memcpy(tmp + AUTHENTICATION_COOKIE_LEN, client_nonce, client_nonce_len);
4314  memcpy(tmp + AUTHENTICATION_COOKIE_LEN + client_nonce_len,
4315  server_nonce, SAFECOOKIE_SERVER_NONCE_LEN);
4316 
4317  crypto_hmac_sha256(server_hash,
4318  SAFECOOKIE_SERVER_TO_CONTROLLER_CONSTANT,
4319  strlen(SAFECOOKIE_SERVER_TO_CONTROLLER_CONSTANT),
4320  tmp,
4321  tmp_len);
4322 
4323  crypto_hmac_sha256(client_hash,
4324  SAFECOOKIE_CONTROLLER_TO_SERVER_CONSTANT,
4325  strlen(SAFECOOKIE_CONTROLLER_TO_SERVER_CONSTANT),
4326  tmp,
4327  tmp_len);
4328 
4329  conn->safecookie_client_hash = client_hash;
4330 
4331  tor_free(tmp);
4332  }
4333 
4334  base16_encode(server_hash_encoded, sizeof(server_hash_encoded),
4335  server_hash, sizeof(server_hash));
4336  base16_encode(server_nonce_encoded, sizeof(server_nonce_encoded),
4337  server_nonce, sizeof(server_nonce));
4338 
4340  "250 AUTHCHALLENGE SERVERHASH=%s "
4341  "SERVERNONCE=%s\r\n",
4342  server_hash_encoded,
4343  server_nonce_encoded);
4344 
4345  tor_free(client_nonce);
4346  return 0;
4347 }
4348 
4351 static int
4353  uint32_t len,
4354  const char *body)
4355 {
4356  smartlist_t *args;
4357  int bad = 0;
4358  (void) len; /* body is nul-terminated; it's safe to ignore the length */
4359  args = smartlist_new();
4360  smartlist_split_string(args, body, " ",
4361  SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
4362  SMARTLIST_FOREACH_BEGIN(args, const char *, arg) {
4363  if (!strcasecmp(arg, "VERBOSE_NAMES"))
4364  ;
4365  else if (!strcasecmp(arg, "EXTENDED_EVENTS"))
4366  ;
4367  else {
4368  connection_printf_to_buf(conn, "552 Unrecognized feature \"%s\"\r\n",
4369  arg);
4370  bad = 1;
4371  break;
4372  }
4373  } SMARTLIST_FOREACH_END(arg);
4374 
4375  if (!bad) {
4376  send_control_done(conn);
4377  }
4378 
4379  SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
4380  smartlist_free(args);
4381  return 0;
4382 }
4383 
4385 static int
4387  uint32_t len,
4388  const char *body)
4389 {
4390  smartlist_t *args;
4391  (void) len; /* body is nul-terminated; it's safe to ignore the length */
4392  args = smartlist_new();
4393  smartlist_split_string(args, body, " ",
4394  SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
4395 
4396  static int have_warned = 0;
4397  if (! have_warned) {
4398  log_warn(LD_CONTROL, "DROPGUARDS is dangerous; make sure you understand "
4399  "the risks before using it. It may be removed in a future "
4400  "version of Tor.");
4401  have_warned = 1;
4402  }
4403 
4404  if (smartlist_len(args)) {
4405  connection_printf_to_buf(conn, "512 Too many arguments to DROPGUARDS\r\n");
4406  } else {
4408  send_control_done(conn);
4409  }
4410 
4411  SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
4412  smartlist_free(args);
4413  return 0;
4414 }
4415 
4417 static int
4419  const char *body)
4420 {
4421  int i;
4422  char digest[DIGEST_LEN], *hsaddress = NULL, *arg1 = NULL, *desc_id = NULL;
4423  smartlist_t *args = NULL, *hsdirs = NULL;
4424  (void) len; /* body is nul-terminated; it's safe to ignore the length */
4425  static const char *hsfetch_command = "HSFETCH";
4426  static const char *v2_str = "v2-";
4427  const size_t v2_str_len = strlen(v2_str);
4428  rend_data_t *rend_query = NULL;
4429 
4430  /* Make sure we have at least one argument, the HSAddress. */
4431  args = getargs_helper(hsfetch_command, conn, body, 1, -1);
4432  if (!args) {
4433  goto exit;
4434  }
4435 
4436  /* Extract the first argument (either HSAddress or DescID). */
4437  arg1 = smartlist_get(args, 0);
4438  /* Test if it's an HS address without the .onion part. */
4439  if (rend_valid_v2_service_id(arg1)) {
4440  hsaddress = arg1;
4441  } else if (strcmpstart(arg1, v2_str) == 0 &&
4442  rend_valid_descriptor_id(arg1 + v2_str_len) &&
4443  base32_decode(digest, sizeof(digest), arg1 + v2_str_len,
4445  /* We have a well formed version 2 descriptor ID. Keep the decoded value
4446  * of the id. */
4447  desc_id = digest;
4448  } else {
4449  connection_printf_to_buf(conn, "513 Invalid argument \"%s\"\r\n",
4450  arg1);
4451  goto done;
4452  }
4453 
4454  static const char *opt_server = "SERVER=";
4455 
4456  /* Skip first argument because it's the HSAddress or DescID. */
4457  for (i = 1; i < smartlist_len(args); ++i) {
4458  const char *arg = smartlist_get(args, i);
4459  const node_t *node;
4460 
4461  if (!strcasecmpstart(arg, opt_server)) {
4462  const char *server;
4463 
4464  server = arg + strlen(opt_server);
4465  node = node_get_by_hex_id(server, 0);
4466  if (!node) {
4467  connection_printf_to_buf(conn, "552 Server \"%s\" not found\r\n",
4468  server);
4469  goto done;
4470  }
4471  if (!hsdirs) {
4472  /* Stores routerstatus_t object for each specified server. */
4473  hsdirs = smartlist_new();
4474  }
4475  /* Valid server, add it to our local list. */
4476  smartlist_add(hsdirs, node->rs);
4477  } else {
4478  connection_printf_to_buf(conn, "513 Unexpected argument \"%s\"\r\n",
4479  arg);
4480  goto done;
4481  }
4482  }
4483 
4484  rend_query = rend_data_client_create(hsaddress, desc_id, NULL,
4485  REND_NO_AUTH);
4486  if (rend_query == NULL) {
4487  connection_printf_to_buf(conn, "551 Error creating the HS query\r\n");
4488  goto done;
4489  }
4490 
4491  /* Using a descriptor ID, we force the user to provide at least one
4492  * hsdir server using the SERVER= option. */
4493  if (desc_id && (!hsdirs || !smartlist_len(hsdirs))) {
4494  connection_printf_to_buf(conn, "512 %s option is required\r\n",
4495  opt_server);
4496  goto done;
4497  }
4498 
4499  /* We are about to trigger HSDir fetch so send the OK now because after
4500  * that 650 event(s) are possible so better to have the 250 OK before them
4501  * to avoid out of order replies. */
4502  send_control_done(conn);
4503 
4504  /* Trigger the fetch using the built rend query and possibly a list of HS
4505  * directory to use. This function ignores the client cache thus this will
4506  * always send a fetch command. */
4507  rend_client_fetch_v2_desc(rend_query, hsdirs);
4508 
4509  done:
4510  SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
4511  smartlist_free(args);
4512  /* Contains data pointer that we don't own thus no cleanup. */
4513  smartlist_free(hsdirs);
4514  rend_data_free(rend_query);
4515  exit:
4516  return 0;
4517 }
4518 
4520 static int
4522  uint32_t len,
4523  const char *body)
4524 {
4525  static const char *opt_server = "SERVER=";
4526  static const char *opt_hsaddress = "HSADDRESS=";
4527  smartlist_t *hs_dirs = NULL;
4528  const char *encoded_desc = body;
4529  size_t encoded_desc_len = len;
4530  const char *onion_address = NULL;
4531 
4532  char *cp = memchr(body, '\n', len);
4533  if (cp == NULL) {
4534  connection_printf_to_buf(conn, "251 Empty body\r\n");
4535  return 0;
4536  }
4537  char *argline = tor_strndup(body, cp-body);
4538 
4539  smartlist_t *args = smartlist_new();
4540 
4541  /* If any SERVER= or HSADDRESS= options were specified, try to parse
4542  * the options line. */
4543  if (!strcasecmpstart(argline, opt_server) ||
4544  !strcasecmpstart(argline, opt_hsaddress)) {
4545  /* encoded_desc begins after a newline character */
4546  cp = cp + 1;
4547  encoded_desc = cp;
4548  encoded_desc_len = len-(cp-body);
4549 
4550  smartlist_split_string(args, argline, " ",
4551  SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
4552  SMARTLIST_FOREACH_BEGIN(args, const char *, arg) {
4553  if (!strcasecmpstart(arg, opt_server)) {
4554  const char *server = arg + strlen(opt_server);
4555  const node_t *node = node_get_by_hex_id(server, 0);
4556 
4557  if (!node || !node->rs) {
4558  connection_printf_to_buf(conn, "552 Server \"%s\" not found\r\n",
4559  server);
4560  goto done;
4561  }
4562  /* Valid server, add it to our local list. */
4563  if (!hs_dirs)
4564  hs_dirs = smartlist_new();
4565  smartlist_add(hs_dirs, node->rs);
4566  } else if (!strcasecmpstart(arg, opt_hsaddress)) {
4567  const char *address = arg + strlen(opt_hsaddress);
4568  if (!hs_address_is_valid(address)) {
4569  connection_printf_to_buf(conn, "512 Malformed onion address\r\n");
4570  goto done;
4571  }
4572  onion_address = address;
4573  } else {
4574  connection_printf_to_buf(conn, "512 Unexpected argument \"%s\"\r\n",
4575  arg);
4576  goto done;
4577  }
4578  } SMARTLIST_FOREACH_END(arg);
4579  }
4580 
4581  /* Handle the v3 case. */
4582  if (onion_address) {
4583  char *desc_str = NULL;
4584  read_escaped_data(encoded_desc, encoded_desc_len, &desc_str);
4585  if (hs_control_hspost_command(desc_str, onion_address, hs_dirs) < 0) {
4586  connection_printf_to_buf(conn, "554 Invalid descriptor\r\n");
4587  } else {
4588  send_control_done(conn);
4589  }
4590  tor_free(desc_str);
4591  goto done;
4592  }
4593 
4594  /* From this point on, it is only v2. */
4595 
4596  /* Read the dot encoded descriptor, and parse it. */
4598  tor_malloc_zero(sizeof(rend_encoded_v2_service_descriptor_t));
4599  read_escaped_data(encoded_desc, encoded_desc_len, &desc->desc_str);
4600 
4601  rend_service_descriptor_t *parsed = NULL;
4602  char *intro_content = NULL;
4603  size_t intro_size;
4604  size_t encoded_size;
4605  const char *next_desc;
4606  if (!rend_parse_v2_service_descriptor(&parsed, desc->desc_id, &intro_content,
4607  &intro_size, &encoded_size,
4608  &next_desc, desc->desc_str, 1)) {
4609  /* Post the descriptor. */
4610  char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
4611  if (!rend_get_service_id(parsed->pk, serviceid)) {
4612  smartlist_t *descs = smartlist_new();
4613  smartlist_add(descs, desc);
4614 
4615  /* We are about to trigger HS descriptor upload so send the OK now
4616  * because after that 650 event(s) are possible so better to have the
4617  * 250 OK before them to avoid out of order replies. */
4618  send_control_done(conn);
4619 
4620  /* Trigger the descriptor upload */
4621  directory_post_to_hs_dir(parsed, descs, hs_dirs, serviceid, 0);
4622  smartlist_free(descs);
4623  }
4624 
4625  rend_service_descriptor_free(parsed);
4626  } else {
4627  connection_printf_to_buf(conn, "554 Invalid descriptor\r\n");
4628  }
4629 
4630  tor_free(intro_content);
4631  rend_encoded_v2_service_descriptor_free(desc);
4632  done:
4633  tor_free(argline);
4634  smartlist_free(hs_dirs); /* Contents belong to the rend service code. */
4635  SMARTLIST_FOREACH(args, char *, arg, tor_free(arg));
4636  smartlist_free(args);
4637  return 0;
4638 }
4639 
4640 /* Helper function for ADD_ONION that adds an ephemeral service depending on
4641  * the given hs_version.
4642  *
4643  * The secret key in pk depends on the hs_version. The ownership of the key
4644  * used in pk is given to the HS subsystem so the caller must stop accessing
4645  * it after.
4646  *
4647  * The port_cfgs is a list of service port. Ownership transferred to service.
4648  * The max_streams refers to the MaxStreams= key.
4649  * The max_streams_close_circuit refers to the MaxStreamsCloseCircuit key.
4650  * The auth_type is the authentication type of the clients in auth_clients.
4651  * The ownership of that list is transferred to the service.
4652  *
4653  * On success (RSAE_OKAY), the address_out points to a newly allocated string
4654  * containing the onion address without the .onion part. On error, address_out
4655  * is untouched. */
4657 add_onion_helper_add_service(int hs_version,
4658  add_onion_secret_key_t *pk,
4659  smartlist_t *port_cfgs, int max_streams,
4660  int max_streams_close_circuit, int auth_type,
4661  smartlist_t *auth_clients, char **address_out)
4662 {
4664 
4665  tor_assert(pk);
4666  tor_assert(port_cfgs);
4667  tor_assert(address_out);
4668 
4669  switch (hs_version) {
4670  case HS_VERSION_TWO:
4671  ret = rend_service_add_ephemeral(pk->v2, port_cfgs, max_streams,
4672  max_streams_close_circuit, auth_type,
4673  auth_clients, address_out);
4674  break;
4675  case HS_VERSION_THREE:
4676  ret = hs_service_add_ephemeral(pk->v3, port_cfgs, max_streams,
4677  max_streams_close_circuit, address_out);
4678  break;
4679  default:
4680  tor_assert_unreached();
4681  }
4682 
4683  return ret;
4684 }
4685 
4688 static int
4690  uint32_t len,
4691  const char *body)
4692 {
4693  smartlist_t *args;
4694  int arg_len;
4695  (void) len; /* body is nul-terminated; it's safe to ignore the length */
4696  args = getargs_helper("ADD_ONION", conn, body, 2, -1);
4697  if (!args)
4698  return 0;
4699  arg_len = smartlist_len(args);
4700 
4701  /* Parse all of the arguments that do not involve handling cryptographic
4702  * material first, since there's no reason to touch that at all if any of
4703  * the other arguments are malformed.
4704  */
4705  smartlist_t *port_cfgs = smartlist_new();
4706  smartlist_t *auth_clients = NULL;
4707  smartlist_t *auth_created_clients = NULL;
4708  int discard_pk = 0;
4709  int detach = 0;
4710  int max_streams = 0;
4711  int max_streams_close_circuit = 0;
4712  rend_auth_type_t auth_type = REND_NO_AUTH;
4713  /* Default to adding an anonymous hidden service if no flag is given */
4714  int non_anonymous = 0;
4715  for (int i = 1; i < arg_len; i++) {
4716  static const char *port_prefix = "Port=";
4717  static const char *flags_prefix = "Flags=";
4718  static const char *max_s_prefix = "MaxStreams=";
4719  static const char *auth_prefix = "ClientAuth=";
4720 
4721  const char *arg = smartlist_get(args, (int)i);
4722  if (!strcasecmpstart(arg, port_prefix)) {
4723  /* "Port=VIRTPORT[,TARGET]". */
4724  const char *port_str = arg + strlen(port_prefix);
4725 
4727  rend_service_parse_port_config(port_str, ",", NULL);
4728  if (!cfg) {
4729  connection_printf_to_buf(conn, "512 Invalid VIRTPORT/TARGET\r\n");
4730  goto out;
4731  }
4732  smartlist_add(port_cfgs, cfg);
4733  } else if (!strcasecmpstart(arg, max_s_prefix)) {
4734  /* "MaxStreams=[0..65535]". */
4735  const char *max_s_str = arg + strlen(max_s_prefix);
4736  int ok = 0;
4737  max_streams = (int)tor_parse_long(max_s_str, 10, 0, 65535, &ok, NULL);
4738  if (!ok) {
4739  connection_printf_to_buf(conn, "512 Invalid MaxStreams\r\n");
4740  goto out;
4741  }
4742  } else if (!strcasecmpstart(arg, flags_prefix)) {
4743  /* "Flags=Flag[,Flag]", where Flag can be:
4744  * * 'DiscardPK' - If tor generates the keypair, do not include it in
4745  * the response.
4746  * * 'Detach' - Do not tie this onion service to any particular control
4747  * connection.
4748  * * 'MaxStreamsCloseCircuit' - Close the circuit if MaxStreams is
4749  * exceeded.
4750  * * 'BasicAuth' - Client authorization using the 'basic' method.
4751  * * 'NonAnonymous' - Add a non-anonymous Single Onion Service. If this
4752  * flag is present, tor must be in non-anonymous
4753  * hidden service mode. If this flag is absent,
4754  * tor must be in anonymous hidden service mode.
4755  */
4756  static const char *discard_flag = "DiscardPK";
4757  static const char *detach_flag = "Detach";
4758  static const char *max_s_close_flag = "MaxStreamsCloseCircuit";
4759  static const char *basicauth_flag = "BasicAuth";
4760  static const char *non_anonymous_flag = "NonAnonymous";
4761 
4762  smartlist_t *flags = smartlist_new();
4763  int bad = 0;
4764 
4765  smartlist_split_string(flags, arg + strlen(flags_prefix), ",",
4766  SPLIT_IGNORE_BLANK, 0);
4767  if (smartlist_len(flags) < 1) {
4768  connection_printf_to_buf(conn, "512 Invalid 'Flags' argument\r\n");
4769  bad = 1;
4770  }
4771  SMARTLIST_FOREACH_BEGIN(flags, const char *, flag)
4772  {
4773  if (!strcasecmp(flag, discard_flag)) {
4774  discard_pk = 1;
4775  } else if (!strcasecmp(flag, detach_flag)) {
4776  detach = 1;
4777  } else if (!strcasecmp(flag, max_s_close_flag)) {
4778  max_streams_close_circuit = 1;
4779  } else if (!strcasecmp(flag, basicauth_flag)) {
4780  auth_type = REND_BASIC_AUTH;
4781  } else if (!strcasecmp(flag, non_anonymous_flag)) {
4782  non_anonymous = 1;
4783  } else {
4785  "512 Invalid 'Flags' argument: %s\r\n",
4786  escaped(flag));
4787  bad = 1;
4788  break;
4789  }
4790  } SMARTLIST_FOREACH_END(flag);
4791  SMARTLIST_FOREACH(flags, char *, cp, tor_free(cp));
4792  smartlist_free(flags);
4793  if (bad)
4794  goto out;
4795  } else if (!strcasecmpstart(arg, auth_prefix)) {
4796  char *err_msg = NULL;
4797  int created = 0;
4798  rend_authorized_client_t *client =
4799  add_onion_helper_clientauth(arg + strlen(auth_prefix),
4800  &created, &err_msg);
4801  if (!client) {
4802  if (err_msg) {
4803  connection_write_str_to_buf(err_msg, conn);
4804  tor_free(err_msg);
4805  }
4806  goto out;
4807  }
4808 
4809  if (auth_clients != NULL) {
4810  int bad = 0;
4811  SMARTLIST_FOREACH_BEGIN(auth_clients, rend_authorized_client_t *, ac) {
4812  if (strcmp(ac->client_name, client->client_name) == 0) {
4813  bad = 1;
4814  break;
4815  }
4816  } SMARTLIST_FOREACH_END(ac);
4817  if (bad) {
4819  "512 Duplicate name in ClientAuth\r\n");
4820  rend_authorized_client_free(client);
4821  goto out;
4822  }
4823  } else {
4824  auth_clients = smartlist_new();
4825  auth_created_clients = smartlist_new();
4826  }
4827  smartlist_add(auth_clients, client);
4828  if (created) {
4829  smartlist_add(auth_created_clients, client);
4830  }
4831  } else {
4832  connection_printf_to_buf(conn, "513 Invalid argument\r\n");
4833  goto out;
4834  }
4835  }
4836  if (smartlist_len(port_cfgs) == 0) {
4837  connection_printf_to_buf(conn, "512 Missing 'Port' argument\r\n");
4838  goto out;
4839  } else if (auth_type == REND_NO_AUTH && auth_clients != NULL) {
4840  connection_printf_to_buf(conn, "512 No auth type specified\r\n");
4841  goto out;
4842  } else if (auth_type != REND_NO_AUTH && auth_clients == NULL) {
4843  connection_printf_to_buf(conn, "512 No auth clients specified\r\n");
4844  goto out;
4845  } else if ((auth_type == REND_BASIC_AUTH &&
4846  smartlist_len(auth_clients) > 512) ||
4847  (auth_type == REND_STEALTH_AUTH &&
4848  smartlist_len(auth_clients) > 16)) {
4849  connection_printf_to_buf(conn, "512 Too many auth clients\r\n");
4850  goto out;
4851  } else if (non_anonymous != rend_service_non_anonymous_mode_enabled(
4852  get_options())) {
4853  /* If we failed, and the non-anonymous flag is set, Tor must be in
4854  * anonymous hidden service mode.
4855  * The error message changes based on the current Tor config:
4856  * 512 Tor is in anonymous hidden service mode
4857  * 512 Tor is in non-anonymous hidden service mode
4858  * (I've deliberately written them out in full here to aid searchability.)
4859  */
4860  connection_printf_to_buf(conn, "512 Tor is in %sanonymous hidden service "
4861  "mode\r\n",
4862  non_anonymous ? "" : "non-");
4863  goto out;
4864  }
4865 
4866  /* Parse the "keytype:keyblob" argument. */
4867  int hs_version = 0;
4868  add_onion_secret_key_t pk = { NULL };
4869  const char *key_new_alg = NULL;
4870  char *key_new_blob = NULL;
4871  char *err_msg = NULL;
4872 
4873  if (add_onion_helper_keyarg(smartlist_get(args, 0), discard_pk,
4874  &key_new_alg, &key_new_blob, &pk, &hs_version,
4875  &err_msg) < 0) {
4876  if (err_msg) {
4877  connection_write_str_to_buf(err_msg, conn);
4878  tor_free(err_msg);
4879  }
4880  goto out;
4881  }
4882  tor_assert(!err_msg);
4883 
4884  /* Hidden service version 3 don't have client authentication support so if
4885  * ClientAuth was given, send back an error. */
4886  if (hs_version == HS_VERSION_THREE && auth_clients) {
4887  connection_printf_to_buf(conn, "513 ClientAuth not supported\r\n");
4888  goto out;
4889  }
4890 
4891  /* Create the HS, using private key pk, client authentication auth_type,
4892  * the list of auth_clients, and port config port_cfg.
4893  * rend_service_add_ephemeral() will take ownership of pk and port_cfg,
4894  * regardless of success/failure.
4895  */
4896  char *service_id = NULL;
4897  int ret = add_onion_helper_add_service(hs_version, &pk, port_cfgs,
4898  max_streams,
4899  max_streams_close_circuit, auth_type,
4900  auth_clients, &service_id);
4901  port_cfgs = NULL; /* port_cfgs is now owned by the rendservice code. */
4902  auth_clients = NULL; /* so is auth_clients */
4903  switch (ret) {
4904  case RSAE_OKAY:
4905  {
4906  if (detach) {
4908  detached_onion_services = smartlist_new();
4910  } else {
4911  if (!conn->ephemeral_onion_services)
4912  conn->ephemeral_onion_services = smartlist_new();
4913  smartlist_add(conn->ephemeral_onion_services, service_id);
4914  }
4915 
4916  tor_assert(service_id);
4917  connection_printf_to_buf(conn, "250-ServiceID=%s\r\n", service_id);
4918  if (key_new_alg) {
4919  tor_assert(key_new_blob);
4920  connection_printf_to_buf(conn, "250-PrivateKey=%s:%s\r\n",
4921  key_new_alg, key_new_blob);
4922  }
4923  if (auth_created_clients) {
4924  SMARTLIST_FOREACH(auth_created_clients, rend_authorized_client_t *, ac, {
4925  char *encoded = rend_auth_encode_cookie(ac->descriptor_cookie,
4926  auth_type);
4927  tor_assert(encoded);
4928  connection_printf_to_buf(conn, "250-ClientAuth=%s:%s\r\n",
4929  ac->client_name, encoded);
4930  memwipe(encoded, 0, strlen(encoded));
4931  tor_free(encoded);
4932  });
4933  }
4934 
4935  connection_printf_to_buf(conn, "250 OK\r\n");
4936  break;
4937  }
4938  case RSAE_BADPRIVKEY:
4939  connection_printf_to_buf(conn, "551 Failed to generate onion address\r\n");
4940  break;
4941  case RSAE_ADDREXISTS:
4942  connection_printf_to_buf(conn, "550 Onion address collision\r\n");
4943  break;
4944  case RSAE_BADVIRTPORT:
4945  connection_printf_to_buf(conn, "512 Invalid VIRTPORT/TARGET\r\n");
4946  break;
4947  case RSAE_BADAUTH:
4948  connection_printf_to_buf(conn, "512 Invalid client authorization\r\n");
4949  break;
4950  case RSAE_INTERNAL: /* FALLSTHROUGH */
4951  default:
4952  connection_printf_to_buf(conn, "551 Failed to add Onion Service\r\n");
4953  }
4954  if (key_new_blob) {
4955  memwipe(key_new_blob, 0, strlen(key_new_blob));
4956  tor_free(key_new_blob);
4957  }
4958 
4959  out:
4960  if (port_cfgs) {
4962  rend_service_port_config_free(p));
4963  smartlist_free(port_cfgs);
4964  }
4965 
4966  if (auth_clients) {
4967  SMARTLIST_FOREACH(auth_clients, rend_authorized_client_t *, ac,
4968  rend_authorized_client_free(ac));
4969  smartlist_free(auth_clients);
4970  }
4971  if (auth_created_clients) {
4972  // Do not free entries; they are the same as auth_clients
4973  smartlist_free(auth_created_clients);
4974  }
4975 
4976  SMARTLIST_FOREACH(args, char *, cp, {
4977  memwipe(cp, 0, strlen(cp));
4978  tor_free(cp);
4979  });
4980  smartlist_free(args);
4981  return 0;
4982 }
4983 
4993 STATIC int
4994 add_onion_helper_keyarg(const char *arg, int discard_pk,
4995  const char **key_new_alg_out, char **key_new_blob_out,
4996  add_onion_secret_key_t *decoded_key, int *hs_version,
4997  char **err_msg_out)
4998 {
4999  smartlist_t *key_args = smartlist_new();
5000  crypto_pk_t *pk = NULL;
5001  const char *key_new_alg = NULL;
5002  char *key_new_blob = NULL;
5003  char *err_msg = NULL;
5004  int ret = -1;
5005 
5006  smartlist_split_string(key_args, arg, ":", SPLIT_IGNORE_BLANK, 0);
5007  if (smartlist_len(key_args) != 2) {
5008  err_msg = tor_strdup("512 Invalid key type/blob\r\n");
5009  goto err;
5010  }
5011 
5012  /* The format is "KeyType:KeyBlob". */
5013  static const char *key_type_new = "NEW";
5014  static const char *key_type_best = "BEST";
5015  static const char *key_type_rsa1024 = "RSA1024";
5016  static const char *key_type_ed25519_v3 = "ED25519-V3";
5017 
5018  const char *key_type = smartlist_get(key_args, 0);
5019  const char *key_blob = smartlist_get(key_args, 1);
5020 
5021  if (!strcasecmp(key_type_rsa1024, key_type)) {
5022  /* "RSA:<Base64 Blob>" - Loading a pre-existing RSA1024 key. */
5023  pk = crypto_pk_base64_decode_private(key_blob, strlen(key_blob));
5024  if (!pk) {
5025  err_msg = tor_strdup("512 Failed to decode RSA key\r\n");
5026  goto err;
5027  }
5028  if (crypto_pk_num_bits(pk) != PK_BYTES*8) {
5029  crypto_pk_free(pk);
5030  err_msg = tor_strdup("512 Invalid RSA key size\r\n");
5031  goto err;
5032  }
5033  decoded_key->v2 = pk;
5034  *hs_version = HS_VERSION_TWO;
5035  } else if (!strcasecmp(key_type_ed25519_v3, key_type)) {
5036  /* "ED25519-V3:<Base64 Blob>" - Loading a pre-existing ed25519 key. */
5037  ed25519_secret_key_t *sk = tor_malloc_zero(sizeof(*sk));
5038  if (base64_decode((char *) sk->seckey, sizeof(sk->seckey), key_blob,
5039  strlen(key_blob)) != sizeof(sk->seckey)) {
5040  tor_free(sk);
5041  err_msg = tor_strdup("512 Failed to decode ED25519-V3 key\r\n");
5042  goto err;
5043  }
5044  decoded_key->v3 = sk;
5045  *hs_version = HS_VERSION_THREE;
5046  } else if (!strcasecmp(key_type_new, key_type)) {
5047  /* "NEW:<Algorithm>" - Generating a new key, blob as algorithm. */
5048  if (!strcasecmp(key_type_rsa1024, key_blob) ||
5049  !strcasecmp(key_type_best, key_blob)) {
5050  /* "RSA1024", RSA 1024 bit, also currently "BEST" by default. */
5051  pk = crypto_pk_new();
5052  if (crypto_pk_generate_key(pk)) {
5053  tor_asprintf(&err_msg, "551 Failed to generate %s key\r\n",
5054  key_type_rsa1024);
5055  goto err;
5056  }
5057  if (!discard_pk) {
5058  if (crypto_pk_base64_encode_private(pk, &key_new_blob)) {
5059  crypto_pk_free(pk);
5060  tor_asprintf(&err_msg, "551 Failed to encode %s key\r\n",
5061  key_type_rsa1024);
5062  goto err;
5063  }
5064  key_new_alg = key_type_rsa1024;
5065  }
5066  decoded_key->v2 = pk;
5067  *hs_version = HS_VERSION_TWO;
5068  } else if (!strcasecmp(key_type_ed25519_v3, key_blob)) {
5069  ed25519_secret_key_t *sk = tor_malloc_zero(sizeof(*sk));
5070  if (ed25519_secret_key_generate(sk, 1) < 0) {
5071  tor_free(sk);
5072  tor_asprintf(&err_msg, "551 Failed to generate %s key\r\n",
5073  key_type_ed25519_v3);
5074  goto err;
5075  }
5076  if (!discard_pk) {
5077  ssize_t len = base64_encode_size(sizeof(sk->seckey), 0) + 1;
5078  key_new_blob = tor_malloc_zero(len);
5079  if (base64_encode(key_new_blob, len, (const char *) sk->seckey,
5080  sizeof(sk->seckey), 0) != (len - 1)) {
5081  tor_free(sk);
5082  tor_free(key_new_blob);
5083  tor_asprintf(&err_msg, "551 Failed to encode %s key\r\n",
5084  key_type_ed25519_v3);
5085  goto err;
5086  }
5087  key_new_alg = key_type_ed25519_v3;
5088  }
5089  decoded_key->v3 = sk;
5090  *hs_version = HS_VERSION_THREE;
5091  } else {
5092  err_msg = tor_strdup("513 Invalid key type\r\n");
5093  goto err;
5094  }
5095  } else {
5096  err_msg = tor_strdup("513 Invalid key type\r\n");
5097  goto err;
5098  }
5099 
5100  /* Succeeded in loading or generating a private key. */
5101  ret = 0;
5102 
5103  err:
5104  SMARTLIST_FOREACH(key_args, char *, cp, {
5105  memwipe(cp, 0, strlen(cp));
5106  tor_free(cp);
5107  });
5108  smartlist_free(key_args);
5109 
5110  if (err_msg_out) {
5111  *err_msg_out = err_msg;
5112  } else {
5113  tor_free(err_msg);
5114  }
5115  *key_new_alg_out = key_new_alg;
5116  *key_new_blob_out = key_new_blob;
5117 
5118  return ret;
5119 }
5120 
5129 STATIC rend_authorized_client_t *
5130 add_onion_helper_clientauth(const char *arg, int *created, char **err_msg)
5131 {
5132  int ok = 0;
5133 
5134  tor_assert(arg);
5135  tor_assert(created);
5136  tor_assert(err_msg);
5137  *err_msg = NULL;
5138 
5139  smartlist_t *auth_args = smartlist_new();
5140  rend_authorized_client_t *client =
5141  tor_malloc_zero(sizeof(rend_authorized_client_t));
5142  smartlist_split_string(auth_args, arg, ":", 0, 0);
5143  if (smartlist_len(auth_args) < 1 || smartlist_len(auth_args) > 2) {
5144  *err_msg = tor_strdup("512 Invalid ClientAuth syntax\r\n");
5145  goto err;
5146  }
5147  client->client_name = tor_strdup(smartlist_get(auth_args, 0));
5148  if (smartlist_len(auth_args) == 2) {
5149  char *decode_err_msg = NULL;
5150  if (rend_auth_decode_cookie(smartlist_get(auth_args, 1),
5151  client->descriptor_cookie,
5152  NULL, &decode_err_msg) < 0) {
5153  tor_assert(decode_err_msg);
5154  tor_asprintf(err_msg, "512 %s\r\n", decode_err_msg);
5155  tor_free(decode_err_msg);
5156  goto err;
5157  }
5158  *created = 0;
5159  } else {
5160  crypto_rand((char *) client->descriptor_cookie, REND_DESC_COOKIE_LEN);
5161  *created = 1;
5162  }
5163 
5164  if (!rend_valid_client_name(client->client_name)) {
5165  *err_msg = tor_strdup("512 Invalid name in ClientAuth\r\n");
5166  goto err;
5167  }
5168 
5169  ok = 1;
5170  err:
5171  SMARTLIST_FOREACH(auth_args, char *, item, tor_free(item));
5172  smartlist_free(auth_args);
5173  if (!ok) {
5174  rend_authorized_client_free(client);
5175  client = NULL;
5176  }
5177  return client;
5178 }
5179 
5182 static int
5184  uint32_t len,
5185  const char *body)
5186 {
5187  int hs_version = 0;
5188  smartlist_t *args;
5189  (void) len; /* body is nul-terminated; it's safe to ignore the length */
5190  args = getargs_helper("DEL_ONION", conn, body, 1, 1);
5191  if (!args)
5192  return 0;
5193 
5194  const char *service_id = smartlist_get(args, 0);
5195  if (rend_valid_v2_service_id(service_id)) {
5196  hs_version = HS_VERSION_TWO;
5197  } else if (hs_address_is_valid(service_id)) {
5198  hs_version = HS_VERSION_THREE;
5199  } else {
5200  connection_printf_to_buf(conn, "512 Malformed Onion Service id\r\n");
5201  goto out;
5202  }
5203 
5204  /* Determine if the onion service belongs to this particular control
5205  * connection, or if it is in the global list of detached services. If it
5206  * is in neither, either the service ID is invalid in some way, or it
5207  * explicitly belongs to a different control connection, and an error
5208  * should be returned.
5209  */
5210  smartlist_t *services[2] = {
5213  };
5214  smartlist_t *onion_services = NULL;
5215  int idx = -1;
5216  for (size_t i = 0; i < ARRAY_LENGTH(services); i++) {
5217  idx = smartlist_string_pos(services[i], service_id);
5218  if (idx != -1) {
5219  onion_services = services[i];
5220  break;
5221  }
5222  }
5223  if (onion_services == NULL) {
5224  connection_printf_to_buf(conn, "552 Unknown Onion Service id\r\n");
5225  } else {
5226  int ret = -1;
5227  switch (hs_version) {
5228  case HS_VERSION_TWO:
5229  ret = rend_service_del_ephemeral(service_id);
5230  break;
5231  case HS_VERSION_THREE:
5232  ret = hs_service_del_ephemeral(service_id);
5233  break;
5234  default:
5235  /* The ret value will be -1 thus hitting the warning below. This should
5236  * never happen because of the check at the start of the function. */
5237  break;
5238  }
5239  if (ret < 0) {
5240  /* This should *NEVER* fail, since the service is on either the
5241  * per-control connection list, or the global one.
5242  */
5243  log_warn(LD_BUG, "Failed to remove Onion Service %s.",
5244  escaped(service_id));
5246  }
5247 
5248  /* Remove/scrub the service_id from the appropriate list. */
5249  char *cp = smartlist_get(onion_services, idx);
5250  smartlist_del(onion_services, idx);
5251  memwipe(cp, 0, strlen(cp));
5252  tor_free(cp);
5253 
5254  send_control_done(conn);
5255  }
5256 
5257  out:
5258  SMARTLIST_FOREACH(args, char *, cp, {
5259  memwipe(cp, 0, strlen(cp));
5260  tor_free(cp);
5261  });
5262  smartlist_free(args);
5263  return 0;
5264 }
5265 
5267 int
5269 {
5270  tor_assert(conn);
5271  return 0;
5272 }
5273 
5275 int
5277 {
5278  tor_assert(conn);
5279 
5280  log_info(LD_CONTROL,"Control connection reached EOF. Closing.");
5281  connection_mark_for_close(TO_CONN(conn));
5282  return 0;
5283 }
5284 
5287 static void
5288 lost_owning_controller(const char *owner_type, const char *loss_manner)
5289 {
5290  log_notice(LD_CONTROL, "Owning controller %s has %s -- exiting now.",
5291  owner_type, loss_manner);
5292 
5293  activate_signal(SIGTERM);
5294 }
5295 
5297 void
5299 {
5300  tor_assert(conn);
5301 
5302  conn->event_mask = 0;
5304 
5305  /* Close all ephemeral Onion Services if any.
5306  * The list and it's contents are scrubbed/freed in connection_free_.
5307  */
5308  if (conn->ephemeral_onion_services) {
5310  if (rend_valid_v2_service_id(cp)) {
5312  } else if (hs_address_is_valid(cp)) {
5313  hs_service_del_ephemeral(cp);
5314  } else {
5315  /* An invalid .onion in our list should NEVER happen */
5317  }
5318  } SMARTLIST_FOREACH_END(cp);
5319  }
5320 
5321  if (conn->is_owning_control_connection) {
5322  lost_owning_controller("connection", "closed");
5323  }
5324 }
5325 
5328 static int
5330 {
5331  if (conn->base_.state == CONTROL_CONN_STATE_OPEN)
5332  return 1;
5333  if (!strcasecmp(cmd, "PROTOCOLINFO"))
5334  return (!conn->have_sent_protocolinfo &&
5335  conn->safecookie_client_hash == NULL);
5336  if (!strcasecmp(cmd, "AUTHCHALLENGE"))
5337  return (conn->safecookie_client_hash == NULL);
5338  if (!strcasecmp(cmd, "AUTHENTICATE") ||
5339  !strcasecmp(cmd, "QUIT"))
5340  return 1;
5341  return 0;
5342 }
5343 
5347 #define MAX_COMMAND_LINE_LENGTH (1024*1024)
5348 
5353 static int
5355 {
5356  return peek_buf_has_control0_command(conn->inbuf);
5357 }
5358 
5359 static int
5360 peek_connection_has_http_command(connection_t *conn)
5361 {
5362  return peek_buf_has_http_command(conn->inbuf);
5363 }
5364 
5365 static const char CONTROLPORT_IS_NOT_AN_HTTP_PROXY_MSG[] =
5366  "HTTP/1.0 501 Tor ControlPort is not an HTTP proxy"
5367  "\r\nContent-Type: text/html; charset=iso-8859-1\r\n\r\n"
5368  "<html>\n"
5369  "<head>\n"
5370  "<title>Tor's ControlPort is not an HTTP proxy</title>\n"
5371  "</head>\n"
5372  "<body>\n"
5373  "<h1>Tor's ControlPort is not an HTTP proxy</h1>\n"
5374  "<p>\n"
5375  "It appears you have configured your web browser to use Tor's control port"
5376  " as an HTTP proxy.\n"
5377  "This is not correct: Tor's default SOCKS proxy port is 9050.\n"
5378  "Please configure your client accordingly.\n"
5379  "</p>\n"
5380  "<p>\n"
5381  "See <a href=\"https://www.torproject.org/documentation.html\">"
5382  "https://www.torproject.org/documentation.html</a> for more "
5383  "information.\n"
5384  "<!-- Plus this comment, to make the body response more than 512 bytes, so "
5385  " IE will be willing to display it. Comment comment comment comment "
5386  " comment comment comment comment comment comment comment comment.-->\n"
5387  "</p>\n"
5388  "</body>\n"
5389  "</html>\n";
5390 
5394 int
5396 {
5397  size_t data_len;
5398  uint32_t cmd_data_len;
5399  int cmd_len;
5400  char *args;
5401 
5402  tor_assert(conn);
5403  tor_assert(conn->base_.state == CONTROL_CONN_STATE_OPEN ||
5404  conn->base_.state == CONTROL_CONN_STATE_NEEDAUTH);
5405 
5406  if (!conn->incoming_cmd) {
5407  conn->incoming_cmd = tor_malloc(1024);
5408  conn->incoming_cmd_len = 1024;
5409  conn->incoming_cmd_cur_len = 0;
5410  }
5411 
5412  if (conn->base_.state == CONTROL_CONN_STATE_NEEDAUTH &&
5414  /* Detect v0 commands and send a "no more v0" message. */
5415  size_t body_len;
5416  char buf[128];
5417  set_uint16(buf+2, htons(0x0000)); /* type == error */
5418  set_uint16(buf+4, htons(0x0001)); /* code == internal error */
5419  strlcpy(buf+6, "The v0 control protocol is not supported by Tor 0.1.2.17 "
5420  "and later; upgrade your controller.",
5421  sizeof(buf)-6);
5422  body_len = 2+strlen(buf+6)+2; /* code, msg, nul. */
5423  set_uint16(buf+0, htons(body_len));
5424  connection_buf_add(buf, 4+body_len, TO_CONN(conn));
5425 
5426  connection_mark_and_flush(TO_CONN(conn));
5427  return 0;
5428  }
5429 
5430  /* If the user has the HTTP proxy port and the control port confused. */
5431  if (conn->base_.state == CONTROL_CONN_STATE_NEEDAUTH &&
5432  peek_connection_has_http_command(TO_CONN(conn))) {
5433  connection_write_str_to_buf(CONTROLPORT_IS_NOT_AN_HTTP_PROXY_MSG, conn);
5434  log_notice(LD_CONTROL, "Received HTTP request on ControlPort");
5435  connection_mark_and_flush(TO_CONN(conn));
5436  return 0;
5437  }
5438 
5439  again:
5440  while (1) {
5441  size_t last_idx;
5442  int r;
5443  /* First, fetch a line. */
5444  do {
5445  data_len = conn->incoming_cmd_len - conn->incoming_cmd_cur_len;
5446  r = connection_buf_get_line(TO_CONN(conn),
5447  conn->incoming_cmd+conn->incoming_cmd_cur_len,
5448  &data_len);
5449  if (r == 0)
5450  /* Line not all here yet. Wait. */
5451  return 0;
5452  else if (r == -1) {
5453  if (data_len + conn->incoming_cmd_cur_len > MAX_COMMAND_LINE_LENGTH) {
5454  connection_write_str_to_buf("500 Line too long.\r\n", conn);
5455  connection_stop_reading(TO_CONN(conn));
5456  connection_mark_and_flush(TO_CONN(conn));
5457  }
5458  while (conn->incoming_cmd_len < data_len+conn->incoming_cmd_cur_len)
5459  conn->incoming_cmd_len *= 2;
5460  conn->incoming_cmd = tor_realloc(conn->incoming_cmd,
5461  conn->incoming_cmd_len);
5462  }
5463  } while (r != 1);
5464 
5465  tor_assert(data_len);
5466 
5467  last_idx = conn->incoming_cmd_cur_len;
5468  conn->incoming_cmd_cur_len += (int)data_len;
5469 
5470  /* We have appended a line to incoming_cmd. Is the command done? */
5471  if (last_idx == 0 && *conn->incoming_cmd != '+')
5472  /* One line command, didn't start with '+'. */
5473  break;
5474  /* XXXX this code duplication is kind of dumb. */
5475  if (last_idx+3 == conn->incoming_cmd_cur_len &&
5476  tor_memeq(conn->incoming_cmd + last_idx, ".\r\n", 3)) {
5477  /* Just appended ".\r\n"; we're done. Remove it. */
5478  conn->incoming_cmd[last_idx] = '\0';
5479  conn->incoming_cmd_cur_len -= 3;
5480  break;
5481  } else if (last_idx+2 == conn->incoming_cmd_cur_len &&
5482  tor_memeq(conn->incoming_cmd + last_idx, ".\n", 2)) {
5483  /* Just appended ".\n"; we're done. Remove it. */
5484  conn->incoming_cmd[last_idx] = '\0';
5485  conn->incoming_cmd_cur_len -= 2;
5486  break;
5487  }
5488  /* Otherwise, read another line. */
5489  }
5490  data_len = conn->incoming_cmd_cur_len;
5491  /* Okay, we now have a command sitting on conn->incoming_cmd. See if we
5492  * recognize it.
5493  */
5494  cmd_len = 0;
5495  while ((size_t)cmd_len < data_len
5496  && !TOR_ISSPACE(conn->incoming_cmd[cmd_len]))
5497  ++cmd_len;
5498 
5499  conn->incoming_cmd[cmd_len]='\0';
5500  args = conn->incoming_cmd+cmd_len+1;
5501  tor_assert(data_len>(size_t)cmd_len);
5502  data_len -= (cmd_len+1); /* skip the command and NUL we added after it */
5503  while (TOR_ISSPACE(*args)) {
5504  ++args;
5505  --data_len;
5506  }
5507 
5508  /* If the connection is already closing, ignore further commands */
5509  if (TO_CONN(conn)->marked_for_close) {
5510  return 0;
5511  }
5512 
5513  /* Otherwise, Quit is always valid. */
5514  if (!strcasecmp(conn->incoming_cmd, "QUIT")) {
5515  connection_write_str_to_buf("250 closing connection\r\n", conn);
5516  connection_mark_and_flush(TO_CONN(conn));
5517  return 0;
5518  }
5519 
5520  if (conn->base_.state == CONTROL_CONN_STATE_NEEDAUTH &&
5521  !is_valid_initial_command(conn, conn->incoming_cmd)) {
5522  connection_write_str_to_buf("514 Authentication required.\r\n", conn);
5523  connection_mark_for_close(TO_CONN(conn));
5524  return 0;
5525  }
5526 
5527  if (data_len >= UINT32_MAX) {
5528  connection_write_str_to_buf("500 A 4GB command? Nice try.\r\n", conn);
5529  connection_mark_for_close(TO_CONN(conn));
5530  return 0;
5531  }
5532 
5533  /* XXXX Why is this not implemented as a table like the GETINFO
5534  * items are? Even handling the plus signs at the beginnings of
5535  * commands wouldn't be very hard with proper macros. */
5536  cmd_data_len = (uint32_t)data_len;
5537  if (!strcasecmp(conn->incoming_cmd, "SETCONF")) {
5538  if (handle_control_setconf(conn, cmd_data_len, args))
5539  return -1;
5540  } else if (!strcasecmp(conn->incoming_cmd, "RESETCONF")) {
5541  if (handle_control_resetconf(conn, cmd_data_len, args))
5542  return -1;
5543  } else if (!strcasecmp(conn->incoming_cmd, "GETCONF")) {
5544  if (handle_control_getconf(conn, cmd_data_len, args))
5545  return -1;
5546  } else if (!strcasecmp(conn->incoming_cmd, "+LOADCONF")) {
5547  if (handle_control_loadconf(conn, cmd_data_len, args))
5548  return -1;
5549  } else if (!strcasecmp(conn->incoming_cmd, "SETEVENTS")) {
5550  if (handle_control_setevents(conn, cmd_data_len, args))
5551  return -1;
5552  } else if (!strcasecmp(conn->incoming_cmd, "AUTHENTICATE")) {
5553  if (handle_control_authenticate(conn, cmd_data_len, args))
5554  return -1;
5555  } else if (!strcasecmp(conn->incoming_cmd, "SAVECONF")) {
5556  if (handle_control_saveconf(conn, cmd_data_len, args))
5557  return -1;
5558  } else if (!strcasecmp(conn->incoming_cmd, "SIGNAL")) {
5559  if (handle_control_signal(conn, cmd_data_len, args))
5560  return -1;
5561  } else if (!strcasecmp(conn->incoming_cmd, "TAKEOWNERSHIP")) {
5562  if (handle_control_takeownership(conn, cmd_data_len, args))
5563  return -1;
5564  } else if (!strcasecmp(conn->incoming_cmd, "DROPOWNERSHIP")) {
5565  if (handle_control_dropownership(conn, cmd_data_len, args))
5566  return -1;
5567  } else if (!strcasecmp(conn->incoming_cmd, "MAPADDRESS")) {
5568  if (handle_control_mapaddress(conn, cmd_data_len, args))
5569  return -1;
5570  } else if (!strcasecmp(conn->incoming_cmd, "GETINFO")) {
5571  if (handle_control_getinfo(conn, cmd_data_len, args))
5572  return -1;
5573  } else if (!strcasecmp(conn->incoming_cmd, "EXTENDCIRCUIT")) {
5574  if (handle_control_extendcircuit(conn, cmd_data_len, args))
5575  return -1;
5576  } else if (!strcasecmp(conn->incoming_cmd, "SETCIRCUITPURPOSE")) {
5577  if (handle_control_setcircuitpurpose(conn, cmd_data_len, args))
5578  return -1;
5579  } else if (!strcasecmp(conn->incoming_cmd, "SETROUTERPURPOSE")) {
5580  connection_write_str_to_buf("511 SETROUTERPURPOSE is obsolete.\r\n", conn);
5581  } else if (!strcasecmp(conn->incoming_cmd, "ATTACHSTREAM")) {
5582  if (handle_control_attachstream(conn, cmd_data_len, args))
5583  return -1;
5584  } else if (!strcasecmp(conn->incoming_cmd, "+POSTDESCRIPTOR")) {
5585  if (handle_control_postdescriptor(conn, cmd_data_len, args))
5586  return -1;
5587  } else if (!strcasecmp(conn->incoming_cmd, "REDIRECTSTREAM")) {
5588  if (handle_control_redirectstream(conn, cmd_data_len, args))
5589  return -1;
5590  } else if (!strcasecmp(conn->incoming_cmd, "CLOSESTREAM")) {
5591  if (handle_control_closestream(conn, cmd_data_len, args))
5592  return -1;
5593  } else if (!strcasecmp(conn->incoming_cmd, "CLOSECIRCUIT")) {
5594  if (handle_control_closecircuit(conn, cmd_data_len, args))
5595  return -1;
5596  } else if (!strcasecmp(conn->incoming_cmd, "USEFEATURE")) {
5597  if (handle_control_usefeature(conn, cmd_data_len, args))
5598  return -1;
5599  } else if (!strcasecmp(conn->incoming_cmd, "RESOLVE")) {
5600  if (handle_control_resolve(conn, cmd_data_len, args))
5601  return -1;
5602  } else if (!strcasecmp(conn->incoming_cmd, "PROTOCOLINFO")) {
5603  if (handle_control_protocolinfo(conn, cmd_data_len, args))
5604  return -1;
5605  } else if (!strcasecmp(conn->incoming_cmd, "AUTHCHALLENGE")) {
5606  if (handle_control_authchallenge(conn, cmd_data_len, args))
5607  return -1;
5608  } else if (!strcasecmp(conn->incoming_cmd, "DROPGUARDS")) {
5609  if (handle_control_dropguards(conn, cmd_data_len, args))
5610  return -1;
5611  } else if (!strcasecmp(conn->incoming_cmd, "HSFETCH")) {
5612  if (handle_control_hsfetch(conn, cmd_data_len, args))
5613  return -1;
5614  } else if (!strcasecmp(conn->incoming_cmd, "+HSPOST")) {
5615  if (handle_control_hspost(conn, cmd_data_len, args))
5616  return -1;
5617  } else if (!strcasecmp(conn->incoming_cmd, "ADD_ONION")) {
5618  int ret = handle_control_add_onion(conn, cmd_data_len, args);
5619  memwipe(args, 0, cmd_data_len); /* Scrub the private key. */
5620  if (ret)
5621  return -1;
5622  } else if (!strcasecmp(conn->incoming_cmd, "DEL_ONION")) {
5623  int ret = handle_control_del_onion(conn, cmd_data_len, args);
5624  memwipe(args, 0, cmd_data_len); /* Scrub the service id/pk. */
5625  if (ret)
5626  return -1;
5627  } else {
5628  connection_printf_to_buf(conn, "510 Unrecognized command \"%s\"\r\n",
5629  conn->incoming_cmd);
5630  }
5631 
5632  conn->incoming_cmd_cur_len = 0;
5633  goto again;
5634 }
5635 
5638 int
5640  int reason_code)
5641 {
5642  const char *status;
5643  char reasons[64] = "";
5644 
5645  if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS))
5646  return 0;
5647  tor_assert(circ);
5648 
5649  switch (tp)
5650  {
5651  case CIRC_EVENT_LAUNCHED: status = "LAUNCHED"; break;
5652  case CIRC_EVENT_BUILT: status = "BUILT"; break;
5653  case CIRC_EVENT_EXTENDED: status = "EXTENDED"; break;
5654  case CIRC_EVENT_FAILED: status = "FAILED"; break;
5655  case CIRC_EVENT_CLOSED: status = "CLOSED"; break;
5656  default:
5657  log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
5659  return 0;
5660  }
5661 
5662  if (tp == CIRC_EVENT_FAILED || tp == CIRC_EVENT_CLOSED) {
5663  const char *reason_str = circuit_end_reason_to_control_string(reason_code);
5664  char unk_reason_buf[16];
5665  if (!reason_str) {
5666  tor_snprintf(unk_reason_buf, 16, "UNKNOWN_%d", reason_code);
5667  reason_str = unk_reason_buf;
5668  }
5669  if (reason_code > 0 && reason_code & END_CIRC_REASON_FLAG_REMOTE) {
5670  tor_snprintf(reasons, sizeof(reasons),
5671  " REASON=DESTROYED REMOTE_REASON=%s", reason_str);
5672  } else {
5673  tor_snprintf(reasons, sizeof(reasons),
5674  " REASON=%s", reason_str);
5675  }
5676  }
5677 
5678  {
5679  char *circdesc = circuit_describe_status_for_controller(circ);
5680  const char *sp = strlen(circdesc) ? " " : "";
5681  send_control_event(EVENT_CIRCUIT_STATUS,
5682  "650 CIRC %lu %s%s%s%s\r\n",
5683  (unsigned long)circ->global_identifier,
5684  status, sp,
5685  circdesc,
5686  reasons);
5687  tor_free(circdesc);
5688  }
5689 
5690  return 0;
5691 }
5692 
5695 static int
5698  int purpose, const struct timeval *tv)
5699 {
5700  const char *event_desc;
5701  char event_tail[160] = "";
5702  if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS_MINOR))
5703  return 0;
5704  tor_assert(circ);
5705 
5706  switch (e)
5707  {
5708  case CIRC_MINOR_EVENT_PURPOSE_CHANGED:
5709  event_desc = "PURPOSE_CHANGED";
5710 
5711  {
5712  /* event_tail can currently be up to 68 chars long */
5713  const char *hs_state_str =
5715  tor_snprintf(event_tail, sizeof(event_tail),
5716  " OLD_PURPOSE=%s%s%s",
5718  (hs_state_str != NULL) ? " OLD_HS_STATE=" : "",
5719  (hs_state_str != NULL) ? hs_state_str : "");
5720  }
5721 
5722  break;
5723  case CIRC_MINOR_EVENT_CANNIBALIZED:
5724  event_desc = "CANNIBALIZED";
5725 
5726  {
5727  /* event_tail can currently be up to 130 chars long */
5728  const char *hs_state_str =
5730  const struct timeval *old_timestamp_began = tv;
5731  char tbuf[ISO_TIME_USEC_LEN+1];
5732  format_iso_time_nospace_usec(tbuf, old_timestamp_began);
5733 
5734  tor_snprintf(event_tail, sizeof(event_tail),
5735  " OLD_PURPOSE=%s%s%s OLD_TIME_CREATED=%s",
5737  (hs_state_str != NULL) ? " OLD_HS_STATE=" : "",
5738  (hs_state_str != NULL) ? hs_state_str : "",
5739  tbuf);
5740  }
5741 
5742  break;
5743  default:
5744  log_warn(LD_BUG, "Unrecognized status code %d", (int)e);
5746  return 0;
5747  }
5748 
5749  {
5750  char *circdesc = circuit_describe_status_for_controller(circ);
5751  const char *sp = strlen(circdesc) ? " " : "";
5752  send_control_event(EVENT_CIRCUIT_STATUS_MINOR,
5753  "650 CIRC_MINOR %lu %s%s%s%s\r\n",
5754  (unsigned long)circ->global_identifier,
5755  event_desc, sp,
5756  circdesc,
5757  event_tail);
5758  tor_free(circdesc);
5759  }
5760 
5761  return 0;
5762 }
5763 
5768 int
5770  int old_purpose)
5771 {
5773  CIRC_MINOR_EVENT_PURPOSE_CHANGED,
5774  old_purpose,
5775  NULL);
5776 }
5777 
5782 int
5784  int old_purpose,
5785  const struct timeval *old_tv_created)
5786 {
5788  CIRC_MINOR_EVENT_CANNIBALIZED,
5789  old_purpose,
5790  old_tv_created);
5791 }
5792 
5797 static int
5798 write_stream_target_to_buf(entry_connection_t *conn, char *buf, size_t len)
5799 {
5800  char buf2[256];
5801  if (conn->chosen_exit_name)
5802  if (tor_snprintf(buf2, sizeof(buf2), ".%s.exit", conn->chosen_exit_name)<0)
5803  return -1;
5804  if (!conn->socks_request)
5805  return -1;
5806  if (tor_snprintf(buf, len, "%s%s%s:%d",
5807  conn->socks_request->address,
5808  conn->chosen_exit_name ? buf2 : "",
5810  ENTRY_TO_EDGE_CONN(conn)) ? ".onion" : "",
5811  conn->socks_request->port)<0)
5812  return -1;
5813  return 0;
5814 }
5815 
5818 int
5820  int reason_code)
5821 {
5822  char reason_buf[64];
5823  char addrport_buf[64];
5824  const char *status;
5825  circuit_t *circ;
5826  origin_circuit_t *origin_circ = NULL;
5827  char buf[256];
5828  const char *purpose = "";
5829  tor_assert(conn->socks_request);
5830 
5831  if (!EVENT_IS_INTERESTING(EVENT_STREAM_STATUS))
5832  return 0;
5833 
5834  if (tp == STREAM_EVENT_CLOSED &&
5836  return 0;
5837 
5838  write_stream_target_to_buf(conn, buf, sizeof(buf));
5839 
5840  reason_buf[0] = '\0';
5841  switch (tp)
5842  {
5843  case STREAM_EVENT_SENT_CONNECT: status = "SENTCONNECT"; break;
5844  case STREAM_EVENT_SENT_RESOLVE: status = "SENTRESOLVE"; break;
5845  case STREAM_EVENT_SUCCEEDED: status = "SUCCEEDED"; break;
5846  case STREAM_EVENT_FAILED: status = "FAILED"; break;
5847  case STREAM_EVENT_CLOSED: status = "CLOSED"; break;
5848  case STREAM_EVENT_NEW: status = "NEW"; break;
5849  case STREAM_EVENT_NEW_RESOLVE: status = "NEWRESOLVE"; break;
5850  case STREAM_EVENT_FAILED_RETRIABLE: status = "DETACHED"; break;
5851  case STREAM_EVENT_REMAP: status = "REMAP"; break;
5852  default:
5853  log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
5854  return 0;
5855  }
5856  if (reason_code && (tp == STREAM_EVENT_FAILED ||
5857  tp == STREAM_EVENT_CLOSED ||
5858  tp == STREAM_EVENT_FAILED_RETRIABLE)) {
5859  const char *reason_str = stream_end_reason_to_control_string(reason_code);
5860  char *r = NULL;
5861  if (!reason_str) {
5862  tor_asprintf(&r, " UNKNOWN_%d", reason_code);
5863  reason_str = r;
5864  }
5865  if (reason_code & END_STREAM_REASON_FLAG_REMOTE)
5866  tor_snprintf(reason_buf, sizeof(reason_buf),
5867  " REASON=END REMOTE_REASON=%s", reason_str);
5868  else
5869  tor_snprintf(reason_buf, sizeof(reason_buf),
5870  " REASON=%s", reason_str);
5871  tor_free(r);
5872  } else if (reason_code && tp == STREAM_EVENT_REMAP) {
5873  switch (reason_code) {
5875  strlcpy(reason_buf, " SOURCE=CACHE", sizeof(reason_buf));
5876  break;
5878  strlcpy(reason_buf, " SOURCE=EXIT", sizeof(reason_buf));
5879  break;
5880  default:
5881  tor_snprintf(reason_buf, sizeof(reason_buf), " REASON=UNKNOWN_%d",
5882  reason_code);
5883  /* XXX do we want SOURCE=UNKNOWN_%d above instead? -RD */
5884  break;
5885  }
5886  }
5887 
5888  if (tp == STREAM_EVENT_NEW || tp == STREAM_EVENT_NEW_RESOLVE) {
5889  /*
5890  * When the control conn is an AF_UNIX socket and we have no address,
5891  * it gets set to "(Tor_internal)"; see dnsserv_launch_request() in
5892  * dnsserv.c.
5893  */
5894  if (strcmp(ENTRY_TO_CONN(conn)->address, "(Tor_internal)") != 0) {
5895  tor_snprintf(addrport_buf,sizeof(addrport_buf), " SOURCE_ADDR=%s:%d",
5896  ENTRY_TO_CONN(conn)->address, ENTRY_TO_CONN(conn)->port);
5897  } else {
5898  /*
5899  * else leave it blank so control on AF_UNIX doesn't need to make
5900  * something up.
5901  */
5902  addrport_buf[0] = '\0';
5903  }
5904  } else {
5905  addrport_buf[0] = '\0';
5906  }
5907 
5908  if (tp == STREAM_EVENT_NEW_RESOLVE) {
5909  purpose = " PURPOSE=DNS_REQUEST";
5910  } else if (tp == STREAM_EVENT_NEW) {
5911  if (conn->use_begindir) {
5912  connection_t *linked = ENTRY_TO_CONN(conn)->linked_conn;
5913  int linked_dir_purpose = -1;
5914  if (linked && linked->type == CONN_TYPE_DIR)
5915  linked_dir_purpose = linked->purpose;
5916  if (DIR_PURPOSE_IS_UPLOAD(linked_dir_purpose))
5917  purpose = " PURPOSE=DIR_UPLOAD";
5918  else
5919  purpose = " PURPOSE=DIR_FETCH";
5920  } else
5921  purpose = " PURPOSE=USER";
5922  }
5923 
5924  circ = circuit_get_by_edge_conn(ENTRY_TO_EDGE_CONN(conn));
5925  if (circ && CIRCUIT_IS_ORIGIN(circ))
5926  origin_circ = TO_ORIGIN_CIRCUIT(circ);
5927  send_control_event(EVENT_STREAM_STATUS,
5928  "650 STREAM %"PRIu64" %s %lu %s%s%s%s\r\n",
5929  (ENTRY_TO_CONN(conn)->global_identifier),
5930  status,
5931  origin_circ?
5932  (unsigned long)origin_circ->global_identifier : 0ul,
5933  buf, reason_buf, addrport_buf, purpose);
5934 
5935  /* XXX need to specify its intended exit, etc? */
5936 
5937  return 0;
5938 }
5939 
5943 static void
5944 orconn_target_get_name(char *name, size_t len, or_connection_t *conn)
5945 {
5946  const node_t *node = node_get_by_id(conn->identity_digest);
5947  if (node) {
5949  node_get_verbose_nickname(node, name);
5950  } else if (! tor_digest_is_zero(conn->identity_digest)) {
5951  name[0] = '$';
5952  base16_encode(name+1, len-1, conn->identity_digest,
5953  DIGEST_LEN);
5954  } else {
5955  tor_snprintf(name, len, "%s:%d",
5956  conn->base_.address, conn->base_.port);
5957  }
5958 }
5959 
5965 int
5967  int reason)
5968 {
5969  int ncircs = 0;
5970  const char *status;
5971  char name[128];
5972  char ncircs_buf[32] = {0}; /* > 8 + log10(2^32)=10 + 2 */
5973 
5974  if (!EVENT_IS_INTERESTING(EVENT_OR_CONN_STATUS))
5975  return 0;
5976 
5977  switch (tp)
5978  {
5979  case OR_CONN_EVENT_LAUNCHED: status = "LAUNCHED"; break;
5980  case OR_CONN_EVENT_CONNECTED: status = "CONNECTED"; break;
5981  case OR_CONN_EVENT_FAILED: status = "FAILED"; break;
5982  case OR_CONN_EVENT_CLOSED: status = "CLOSED"; break;
5983  case OR_CONN_EVENT_NEW: status = "NEW"; break;
5984  default:
5985  log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
5986  return 0;
5987  }
5988  if (conn->chan) {
5989  ncircs = circuit_count_pending_on_channel(TLS_CHAN_TO_BASE(conn->chan));
5990  } else {
5991  ncircs = 0;
5992  }
5993  ncircs += connection_or_get_num_circuits(conn);
5994  if (ncircs && (tp == OR_CONN_EVENT_FAILED || tp == OR_CONN_EVENT_CLOSED)) {
5995  tor_snprintf(ncircs_buf, sizeof(ncircs_buf), " NCIRCS=%d", ncircs);
5996  }
5997 
5998  orconn_target_get_name(name, sizeof(name), conn);
5999  send_control_event(EVENT_OR_CONN_STATUS,
6000  "650 ORCONN %s %s%s%s%s ID=%"PRIu64"\r\n",
6001  name, status,
6002  reason ? " REASON=" : "",
6004  ncircs_buf,
6005  (conn->base_.global_identifier));
6006 
6007  return 0;
6008 }
6009 
6013 int
6015 {
6016  struct timeval now;
6017  char tbuf[ISO_TIME_USEC_LEN+1];
6018  if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED)) {
6019  if (!edge_conn->n_read && !edge_conn->n_written)
6020  return 0;
6021 
6022  tor_gettimeofday(&now);
6023  format_iso_time_nospace_usec(tbuf, &now);
6024  send_control_event(EVENT_STREAM_BANDWIDTH_USED,
6025  "650 STREAM_BW %"PRIu64" %lu %lu %s\r\n",
6026  (edge_conn->base_.global_identifier),
6027  (unsigned long)edge_conn->n_read,
6028  (unsigned long)edge_conn->n_written,
6029  tbuf);
6030 
6031  edge_conn->n_written = edge_conn->n_read = 0;
6032  }
6033 
6034  return 0;
6035 }
6036 
6039 int
6041 {
6042  if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED)) {
6043  smartlist_t *conns = get_connection_array();
6044  edge_connection_t *edge_conn;
6045  struct timeval now;
6046  char tbuf[ISO_TIME_USEC_LEN+1];
6047 
6048  SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn)
6049  {
6050  if (conn->type != CONN_TYPE_AP)
6051  continue;
6052  edge_conn = TO_EDGE_CONN(conn);
6053  if (!edge_conn->n_read && !edge_conn->n_written)
6054  continue;
6055 
6056  tor_gettimeofday(&now);
6057  format_iso_time_nospace_usec(tbuf, &now);
6058  send_control_event(EVENT_STREAM_BANDWIDTH_USED,
6059  "650 STREAM_BW %"PRIu64" %lu %lu %s\r\n",
6060  (edge_conn->base_.global_identifier),
6061  (unsigned long)edge_conn->n_read,
6062  (unsigned long)edge_conn->n_written,
6063  tbuf);
6064 
6065  edge_conn->n_written = edge_conn->n_read = 0;
6066  }
6067  SMARTLIST_FOREACH_END(conn);
6068  }
6069 
6070  return 0;
6071 }
6072 
6075 int
6077 {
6078  if (!EVENT_IS_INTERESTING(EVENT_CIRC_BANDWIDTH_USED))
6079  return 0;
6080 
6081  SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
6082  if (!CIRCUIT_IS_ORIGIN(circ))
6083  continue;
6084 
6086  }
6087  SMARTLIST_FOREACH_END(circ);
6088 
6089  return 0;
6090 }
6091 
6100 int
6102 {
6103  struct timeval now;
6104  char tbuf[ISO_TIME_USEC_LEN+1];
6105 
6106  tor_assert(ocirc);
6107 
6108  if (!EVENT_IS_INTERESTING(EVENT_CIRC_BANDWIDTH_USED))
6109  return 0;
6110 
6111  /* n_read_circ_bw and n_written_circ_bw are always updated
6112  * when there is any new cell on a circuit, and set to 0 after
6113  * the event, below.
6114  *
6115  * Therefore, checking them is sufficient to determine if there
6116  * is new data to report. */
6117  if (!ocirc->n_read_circ_bw && !ocirc->n_written_circ_bw)
6118  return 0;
6119 
6120  tor_gettimeofday(&now);
6121  format_iso_time_nospace_usec(tbuf, &now);
6122  send_control_event(EVENT_CIRC_BANDWIDTH_USED,
6123  "650 CIRC_BW ID=%d READ=%lu WRITTEN=%lu TIME=%s "
6124  "DELIVERED_READ=%lu OVERHEAD_READ=%lu "
6125  "DELIVERED_WRITTEN=%lu OVERHEAD_WRITTEN=%lu\r\n",
6126  ocirc->global_identifier,
6127  (unsigned long)ocirc->n_read_circ_bw,
6128  (unsigned long)ocirc->n_written_circ_bw,
6129  tbuf,
6130  (unsigned long)ocirc->n_delivered_read_circ_bw,
6131  (unsigned long)ocirc->n_overhead_read_circ_bw,
6132  (unsigned long)ocirc->n_delivered_written_circ_bw,
6133  (unsigned long)ocirc->n_overhead_written_circ_bw);
6134  ocirc->n_written_circ_bw = ocirc->n_read_circ_bw = 0;
6137 
6138  return 0;
6139 }
6140 
6143 int
6145 {
6146  const char *conn_type_str;
6147  if (!get_options()->TestingEnableConnBwEvent ||
6148  !EVENT_IS_INTERESTING(EVENT_CONN_BW))
6149  return 0;
6150  if (!conn->n_read_conn_bw && !conn->n_written_conn_bw)
6151  return 0;
6152  switch (conn->type) {
6153  case CONN_TYPE_OR:
6154  conn_type_str = "OR";
6155  break;
6156  case CONN_TYPE_DIR:
6157  conn_type_str = "DIR";
6158  break;
6159  case CONN_TYPE_EXIT:
6160  conn_type_str = "EXIT";
6161  break;
6162  default:
6163  return 0;
6164  }
6165  send_control_event(EVENT_CONN_BW,
6166  "650 CONN_BW ID=%"PRIu64" TYPE=%s "
6167  "READ=%lu WRITTEN=%lu\r\n",
6168  (conn->global_identifier),
6169  conn_type_str,
6170  (unsigned long)conn->n_read_conn_bw,
6171  (unsigned long)conn->n_written_conn_bw);
6172  conn->n_written_conn_bw = conn->n_read_conn_bw = 0;
6173  return 0;
6174 }
6175 
6178 int
6180 {
6181  if (get_options()->TestingEnableConnBwEvent &&
6182  EVENT_IS_INTERESTING(EVENT_CONN_BW)) {
6183  SMARTLIST_FOREACH(get_connection_array(), connection_t *, conn,
6185  }
6186  return 0;
6187 }
6188 
6193 void
6194 sum_up_cell_stats_by_command(circuit_t *circ, cell_stats_t *cell_stats)
6195 {
6196  memset(cell_stats, 0, sizeof(cell_stats_t));
6198  const testing_cell_stats_entry_t *, ent) {
6199  tor_assert(ent->command <= CELL_COMMAND_MAX_);
6200  if (!ent->removed && !ent->exitward) {
6201  cell_stats->added_cells_appward[ent->command] += 1;
6202  } else if (!ent->removed && ent->exitward) {
6203  cell_stats->added_cells_exitward[ent->command] += 1;
6204  } else if (!ent->exitward) {
6205  cell_stats->removed_cells_appward[ent->command] += 1;
6206  cell_stats->total_time_appward[ent->command] += ent->waiting_time * 10;
6207  } else {
6208  cell_stats->removed_cells_exitward[ent->command] += 1;
6209  cell_stats->total_time_exitward[ent->command] += ent->waiting_time * 10;
6210  }
6211  } SMARTLIST_FOREACH_END(ent);
6213 }
6214 
6224 void
6225 append_cell_stats_by_command(smartlist_t *event_parts, const char *key,
6226  const uint64_t *include_if_non_zero,
6227  const uint64_t *number_to_include)
6228 {
6229  smartlist_t *key_value_strings = smartlist_new();
6230  int i;
6231  for (i = 0; i <= CELL_COMMAND_MAX_; i++) {
6232  if (include_if_non_zero[i] > 0) {
6233  smartlist_add_asprintf(key_value_strings, "%s:%"PRIu64,
6235  (number_to_include[i]));
6236  }
6237  }
6238  if (smartlist_len(key_value_strings) > 0) {
6239  char *joined = smartlist_join_strings(key_value_strings, ",", 0, NULL);
6240  smartlist_add_asprintf(event_parts, "%s=%s", key, joined);
6241  SMARTLIST_FOREACH(key_value_strings, char *, cp, tor_free(cp));
6242  tor_free(joined);
6243  }
6244  smartlist_free(key_value_strings);
6245 }
6246 
6249 void
6250 format_cell_stats(char **event_string, circuit_t *circ,
6251  cell_stats_t *cell_stats)
6252 {
6253  smartlist_t *event_parts = smartlist_new();
6254  if (CIRCUIT_IS_ORIGIN(circ)) {
6255  origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
6256  smartlist_add_asprintf(event_parts, "ID=%lu",
6257  (unsigned long)ocirc->global_identifier);
6258  } else if (TO_OR_CIRCUIT(circ)->p_chan) {
6259  or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
6260  smartlist_add_asprintf(event_parts, "InboundQueue=%lu",
6261  (unsigned long)or_circ->p_circ_id);
6262  smartlist_add_asprintf(event_parts, "InboundConn=%"PRIu64,
6263  (or_circ->p_chan->global_identifier));
6264  append_cell_stats_by_command(event_parts, "InboundAdded",
6265  cell_stats->added_cells_appward,
6266  cell_stats->added_cells_appward);
6267  append_cell_stats_by_command(event_parts, "InboundRemoved",
6268  cell_stats->removed_cells_appward,
6269  cell_stats->removed_cells_appward);
6270  append_cell_stats_by_command(event_parts, "InboundTime",
6271  cell_stats->removed_cells_appward,
6272  cell_stats->total_time_appward);
6273  }
6274  if (circ->n_chan) {
6275  smartlist_add_asprintf(event_parts, "OutboundQueue=%lu",
6276  (unsigned long)circ->n_circ_id);
6277  smartlist_add_asprintf(event_parts, "OutboundConn=%"PRIu64,
6278  (circ->n_chan->global_identifier));
6279  append_cell_stats_by_command(event_parts, "OutboundAdded",
6280  cell_stats->added_cells_exitward,
6281  cell_stats->added_cells_exitward);
6282  append_cell_stats_by_command(event_parts, "OutboundRemoved",
6283  cell_stats->removed_cells_exitward,
6284  cell_stats->removed_cells_exitward);
6285  append_cell_stats_by_command(event_parts, "OutboundTime",
6286  cell_stats->removed_cells_exitward,
6287  cell_stats->total_time_exitward);
6288  }
6289  *event_string = smartlist_join_strings(event_parts, " ", 0, NULL);
6290  SMARTLIST_FOREACH(event_parts, char *, cp, tor_free(cp));
6291  smartlist_free(event_parts);
6292 }
6293 
6296 int
6298 {
6299  cell_stats_t *cell_stats;
6300  char *event_string;
6301  if (!get_options()->TestingEnableCellStatsEvent ||
6302  !EVENT_IS_INTERESTING(EVENT_CELL_STATS))
6303  return 0;
6304  cell_stats = tor_malloc(sizeof(cell_stats_t));
6305  SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
6306  if (!circ->testing_cell_stats)
6307  continue;
6308  sum_up_cell_stats_by_command(circ, cell_stats);
6309  format_cell_stats(&event_string, circ, cell_stats);
6310  send_control_event(EVENT_CELL_STATS,
6311  "650 CELL_STATS %s\r\n", event_string);
6312  tor_free(event_string);
6313  }
6314  SMARTLIST_FOREACH_END(circ);
6315  tor_free(cell_stats);
6316  return 0;
6317 }
6318 
6319 /* about 5 minutes worth. */
6320 #define N_BW_EVENTS_TO_CACHE 300
6321 /* Index into cached_bw_events to next write. */
6322 static int next_measurement_idx = 0;
6323 /* number of entries set in n_measurements */
6324 static int n_measurements = 0;
6325 static struct cached_bw_event_s {
6326  uint32_t n_read;
6327  uint32_t n_written;
6328 } cached_bw_events[N_BW_EVENTS_TO_CACHE];
6329 
6332 int
6333 control_event_bandwidth_used(uint32_t n_read, uint32_t n_written)
6334 {
6335  cached_bw_events[next_measurement_idx].n_read = n_read;
6336  cached_bw_events[next_measurement_idx].n_written = n_written;
6337  if (++next_measurement_idx == N_BW_EVENTS_TO_CACHE)
6338  next_measurement_idx = 0;
6339  if (n_measurements < N_BW_EVENTS_TO_CACHE)
6340  ++n_measurements;
6341 
6342  if (EVENT_IS_INTERESTING(EVENT_BANDWIDTH_USED)) {
6343  send_control_event(EVENT_BANDWIDTH_USED,
6344  "650 BW %lu %lu\r\n",
6345  (unsigned long)n_read,
6346  (unsigned long)n_written);
6347  }
6348 
6349  return 0;
6350 }
6351 
6352 STATIC char *
6353 get_bw_samples(void)
6354 {
6355  int i;
6356  int idx = (next_measurement_idx + N_BW_EVENTS_TO_CACHE - n_measurements)
6357  % N_BW_EVENTS_TO_CACHE;
6358  tor_assert(0 <= idx && idx < N_BW_EVENTS_TO_CACHE);
6359 
6360  smartlist_t *elements = smartlist_new();
6361 
6362  for (i = 0; i < n_measurements; ++i) {
6363  tor_assert(0 <= idx && idx < N_BW_EVENTS_TO_CACHE);
6364  const struct cached_bw_event_s *bwe = &cached_bw_events[idx];
6365 
6366  smartlist_add_asprintf(elements, "%u,%u",
6367  (unsigned)bwe->n_read,
6368  (unsigned)bwe->n_written);
6369 
6370  idx = (idx + 1) % N_BW_EVENTS_TO_CACHE;
6371  }
6372 
6373  char *result = smartlist_join_strings(elements, " ", 0, NULL);
6374 
6375  SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
6376  smartlist_free(elements);
6377 
6378  return result;
6379 }
6380 
6384 void
6386 {
6388 }
6389 
6392 void
6394 {
6395  if (--disable_log_messages < 0)
6396  tor_assert(0);
6397 }
6398 
6400 void
6401 control_event_logmsg(int severity, uint32_t domain, const char *msg)
6402 {
6403  int event;
6404 
6405  /* Don't even think of trying to add stuff to a buffer from a cpuworker
6406  * thread. (See #25987 for plan to fix.) */
6407  if (! in_main_thread())
6408  return;
6409 
6411  return;
6412 
6413  if (domain == LD_BUG && EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL) &&
6414  severity <= LOG_NOTICE) {
6415  char *esc = esc_for_log(msg);
6417  control_event_general_status(severity, "BUG REASON=%s", esc);
6419  tor_free(esc);
6420  }
6421 
6422  event = log_severity_to_event(severity);
6423  if (event >= 0 && EVENT_IS_INTERESTING(event)) {
6424  char *b = NULL;
6425  const char *s;
6426  if (strchr(msg, '\n')) {
6427  char *cp;
6428  b = tor_strdup(msg);
6429  for (cp = b; *cp; ++cp)
6430  if (*cp == '\r' || *cp == '\n')
6431  *cp = ' ';
6432  }
6433  switch (severity) {
6434  case LOG_DEBUG: s = "DEBUG"; break;
6435  case LOG_INFO: s = "INFO"; break;
6436  case LOG_NOTICE: s = "NOTICE"; break;
6437  case LOG_WARN: s = "WARN"; break;
6438  case LOG_ERR: s = "ERR"; break;
6439  default: s = "UnknownLogSeverity"; break;
6440  }
6442  send_control_event(event, "650 %s %s\r\n", s, b?b:msg);
6443  if (severity == LOG_ERR) {
6444  /* Force a flush, since we may be about to die horribly */
6446  }
6448  tor_free(b);
6449  }
6450 }
6451 
6455 void
6457 {
6458  if (! in_main_thread()) {
6459  /* We can't handle this case yet, since we're using a
6460  * mainloop_event_t to invoke queued_events_flush_all. We ought to
6461  * use a different mechanism instead: see #25987.
6462  **/
6463  return;
6464  }
6467 }
6468 
6473 int
6475 {
6476  char *msg;
6477 
6478  if (!EVENT_IS_INTERESTING(EVENT_NEW_DESC))
6479  return 0;
6480 
6481  {
6482  smartlist_t *names = smartlist_new();
6483  char *ids;
6484  SMARTLIST_FOREACH(routers, routerinfo_t *, ri, {
6485  char *b = tor_malloc(MAX_VERBOSE_NICKNAME_LEN+1);
6487  smartlist_add(names, b);
6488  });
6489  ids = smartlist_join_strings(names, " ", 0, NULL);
6490  tor_asprintf(&msg, "650 NEWDESC %s\r\n", ids);
6491  send_control_event_string(EVENT_NEW_DESC, msg);
6492  tor_free(ids);
6493  tor_free(msg);
6494  SMARTLIST_FOREACH(names, char *, cp, tor_free(cp));
6495  smartlist_free(names);
6496  }
6497  return 0;
6498 }
6499 
6505 int
6506 control_event_address_mapped(const char *from, const char *to, time_t expires,
6507  const char *error, const int cached)
6508 {
6509  if (!EVENT_IS_INTERESTING(EVENT_ADDRMAP))
6510  return 0;
6511 
6512  if (expires < 3 || expires == TIME_MAX)
6513  send_control_event(EVENT_ADDRMAP,
6514  "650 ADDRMAP %s %s NEVER %s%s"
6515  "CACHED=\"%s\"\r\n",
6516  from, to, error?error:"", error?" ":"",
6517  cached?"YES":"NO");
6518  else {
6519  char buf[ISO_TIME_LEN+1];
6520  char buf2[ISO_TIME_LEN+1];