Tor  0.4.4.0-alpha-dev
control_cmd.c
Go to the documentation of this file.
1 /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
2  * Copyright (c) 2007-2020, The Tor Project, Inc. */
3 /* See LICENSE for licensing information */
4 
5 /**
6  * \file control_cmd.c
7  * \brief Implement various commands for Tor's control-socket interface.
8  **/
9 
10 #define CONTROL_MODULE_PRIVATE
11 #define CONTROL_CMD_PRIVATE
12 #define CONTROL_EVENTS_PRIVATE
13 
14 #include "core/or/or.h"
15 #include "app/config/config.h"
16 #include "lib/confmgt/confmgt.h"
17 #include "app/main/main.h"
19 #include "core/or/circuitbuild.h"
20 #include "core/or/circuitlist.h"
21 #include "core/or/circuituse.h"
24 #include "feature/client/dnsserv.h"
29 #include "feature/control/control_hs.h"
31 #include "feature/control/control_getinfo.h"
33 #include "feature/hs/hs_control.h"
39 #include "feature/rend/rendparse.h"
43 #include "lib/encoding/confline.h"
44 #include "lib/encoding/kvline.h"
45 
57 
59  const control_cmd_args_t *args,
60  int use_defaults);
61 
62 /** Yield true iff <b>s</b> is the state of a control_connection_t that has
63  * finished authentication and is accepting commands. */
64 #define STATE_IS_OPEN(s) ((s) == CONTROL_CONN_STATE_OPEN)
65 
66 /**
67  * Release all storage held in <b>args</b>
68  **/
69 void
71 {
72  if (! args)
73  return;
74 
75  if (args->args) {
76  SMARTLIST_FOREACH(args->args, char *, c, tor_free(c));
77  smartlist_free(args->args);
78  }
79  config_free_lines(args->kwargs);
80  tor_free(args->cmddata);
81 
82  tor_free(args);
83 }
84 
85 /** Erase all memory held in <b>args</b>. */
86 void
88 {
89  if (!args)
90  return;
91 
92  if (args->args) {
93  SMARTLIST_FOREACH(args->args, char *, c, memwipe(c, 0, strlen(c)));
94  }
95  for (config_line_t *line = args->kwargs; line; line = line->next) {
96  memwipe(line->key, 0, strlen(line->key));
97  memwipe(line->value, 0, strlen(line->value));
98  }
99  if (args->cmddata)
100  memwipe(args->cmddata, 0, args->cmddata_len);
101 }
102 
103 /**
104  * Return true iff any element of the NULL-terminated <b>array</b> matches
105  * <b>kwd</b>. Case-insensitive.
106  **/
107 static bool
108 string_array_contains_keyword(const char **array, const char *kwd)
109 {
110  for (unsigned i = 0; array[i]; ++i) {
111  if (! strcasecmp(array[i], kwd))
112  return true;
113  }
114  return false;
115 }
116 
117 /** Helper for argument parsing: check whether the keyword arguments just
118  * parsed in <b>result</b> were well-formed according to <b>syntax</b>.
119  *
120  * On success, return 0. On failure, return -1 and set *<b>error_out</b>
121  * to a newly allocated error string.
122  **/
123 static int
125  const control_cmd_syntax_t *syntax,
126  char **error_out)
127 {
128  if (result->kwargs == NULL) {
129  tor_asprintf(error_out, "Cannot parse keyword argument(s)");
130  return -1;
131  }
132 
133  if (! syntax->allowed_keywords) {
134  /* All keywords are permitted. */
135  return 0;
136  }
137 
138  /* Check for unpermitted arguments */
139  const config_line_t *line;
140  for (line = result->kwargs; line; line = line->next) {
142  line->key)) {
143  tor_asprintf(error_out, "Unrecognized keyword argument %s",
144  escaped(line->key));
145  return -1;
146  }
147  }
148 
149  return 0;
150 }
151 
152 /**
153  * Helper: parse the arguments to a command according to <b>syntax</b>. On
154  * success, set *<b>error_out</b> to NULL and return a newly allocated
155  * control_cmd_args_t. On failure, set *<b>error_out</b> to newly allocated
156  * error string, and return NULL.
157  **/
160  const control_cmd_syntax_t *syntax,
161  size_t body_len,
162  const char *body,
163  char **error_out)
164 {
165  *error_out = NULL;
166  control_cmd_args_t *result = tor_malloc_zero(sizeof(control_cmd_args_t));
167  const char *cmdline;
168  char *cmdline_alloc = NULL;
169  tor_assert(syntax->max_args < INT_MAX || syntax->max_args == UINT_MAX);
170 
171  result->command = command;
172 
173  if (syntax->store_raw_body) {
174  tor_assert(body[body_len] == 0);
175  result->raw_body = body;
176  }
177 
178  const char *eol = memchr(body, '\n', body_len);
179  if (syntax->want_cmddata) {
180  if (! eol || (eol+1) == body+body_len) {
181  *error_out = tor_strdup("Empty body");
182  goto err;
183  }
184  cmdline_alloc = tor_memdup_nulterm(body, eol-body);
185  cmdline = cmdline_alloc;
186  ++eol;
187  result->cmddata_len = read_escaped_data(eol, (body+body_len)-eol,
188  &result->cmddata);
189  } else {
190  if (eol && (eol+1) != body+body_len) {
191  *error_out = tor_strdup("Unexpected body");
192  goto err;
193  }
194  cmdline = body;
195  }
196 
197  result->args = smartlist_new();
198  smartlist_split_string(result->args, cmdline, " ",
199  SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK,
200  (int)(syntax->max_args+1));
201  size_t n_args = smartlist_len(result->args);
202  if (n_args < syntax->min_args) {
203  tor_asprintf(error_out, "Need at least %u argument(s)",
204  syntax->min_args);
205  goto err;
206  } else if (n_args > syntax->max_args && ! syntax->accept_keywords) {
207  tor_asprintf(error_out, "Cannot accept more than %u argument(s)",
208  syntax->max_args);
209  goto err;
210  }
211 
212  if (n_args > syntax->max_args) {
213  /* We have extra arguments after the positional arguments, and we didn't
214  treat them as an error, so they must count as keyword arguments: Either
215  K=V pairs, or flags, or both. */
216  tor_assert(n_args == syntax->max_args + 1);
217  tor_assert(syntax->accept_keywords);
218  char *remainder = smartlist_pop_last(result->args);
219  result->kwargs = kvline_parse(remainder, syntax->kvline_flags);
220  tor_free(remainder);
221  if (kvline_check_keyword_args(result, syntax, error_out) < 0) {
222  goto err;
223  }
224  }
225 
226  tor_assert_nonfatal(*error_out == NULL);
227  goto done;
228  err:
229  tor_assert_nonfatal(*error_out != NULL);
230  control_cmd_args_free(result);
231  done:
232  tor_free(cmdline_alloc);
233  return result;
234 }
235 
236 /**
237  * Return true iff <b>lines</b> contains <b>flags</b> as a no-value
238  * (keyword-only) entry.
239  **/
240 static bool
241 config_lines_contain_flag(const config_line_t *lines, const char *flag)
242 {
243  const config_line_t *line = config_line_find_case(lines, flag);
244  return line && !strcmp(line->value, "");
245 }
246 
247 static const control_cmd_syntax_t setconf_syntax = {
248  .max_args=0,
249  .accept_keywords=true,
250  .kvline_flags=KV_OMIT_VALS|KV_QUOTED,
251 };
252 
253 /** Called when we receive a SETCONF message: parse the body and try
254  * to update our configuration. Reply with a DONE or ERROR message.
255  * Modifies the contents of body.*/
256 static int
258  const control_cmd_args_t *args)
259 {
260  return control_setconf_helper(conn, args, 0);
261 }
262 
263 static const control_cmd_syntax_t resetconf_syntax = {
264  .max_args=0,
265  .accept_keywords=true,
266  .kvline_flags=KV_OMIT_VALS|KV_QUOTED,
267 };
268 
269 /** Called when we receive a RESETCONF message: parse the body and try
270  * to update our configuration. Reply with a DONE or ERROR message.
271  * Modifies the contents of body. */
272 static int
274  const control_cmd_args_t *args)
275 {
276  return control_setconf_helper(conn, args, 1);
277 }
278 
279 static const control_cmd_syntax_t getconf_syntax = {
280  .max_args=UINT_MAX
281 };
282 
283 /** Called when we receive a GETCONF message. Parse the request, and
284  * reply with a CONFVALUE or an ERROR message */
285 static int
287  const control_cmd_args_t *args)
288 {
289  const smartlist_t *questions = args->args;
290  smartlist_t *answers = smartlist_new();
291  smartlist_t *unrecognized = smartlist_new();
292  const or_options_t *options = get_options();
293 
294  SMARTLIST_FOREACH_BEGIN(questions, const char *, q) {
295  if (!option_is_recognized(q)) {
296  control_reply_add_printf(unrecognized, 552,
297  "Unrecognized configuration key \"%s\"", q);
298  } else {
299  config_line_t *answer = option_get_assignment(options,q);
300  if (!answer) {
301  const char *name = option_get_canonical_name(q);
302  control_reply_add_one_kv(answers, 250, KV_OMIT_VALS, name, "");
303  }
304 
305  while (answer) {
306  config_line_t *next;
307  control_reply_add_one_kv(answers, 250, KV_RAW, answer->key,
308  answer->value);
309  next = answer->next;
310  tor_free(answer->key);
311  tor_free(answer->value);
312  tor_free(answer);
313  answer = next;
314  }
315  }
316  } SMARTLIST_FOREACH_END(q);
317 
318  if (smartlist_len(unrecognized)) {
319  control_write_reply_lines(conn, unrecognized);
320  } else if (smartlist_len(answers)) {
321  control_write_reply_lines(conn, answers);
322  } else {
323  send_control_done(conn);
324  }
325 
326  control_reply_free(answers);
327  control_reply_free(unrecognized);
328  return 0;
329 }
330 
331 static const control_cmd_syntax_t loadconf_syntax = {
332  .want_cmddata = true
333 };
334 
335 /** Called when we get a +LOADCONF message. */
336 static int
338  const control_cmd_args_t *args)
339 {
340  setopt_err_t retval;
341  char *errstring = NULL;
342 
343  retval = options_init_from_string(NULL, args->cmddata,
344  CMD_RUN_TOR, NULL, &errstring);
345 
346  if (retval != SETOPT_OK)
347  log_warn(LD_CONTROL,
348  "Controller gave us config file that didn't validate: %s",
349  errstring);
350 
351 #define SEND_ERRMSG(code, msg) \
352  control_printf_endreply(conn, code, msg "%s%s", \
353  errstring ? ": " : "", \
354  errstring ? errstring : "")
355  switch (retval) {
356  case SETOPT_ERR_PARSE:
357  SEND_ERRMSG(552, "Invalid config file");
358  break;
359  case SETOPT_ERR_TRANSITION:
360  SEND_ERRMSG(553, "Transition not allowed");
361  break;
362  case SETOPT_ERR_SETTING:
363  SEND_ERRMSG(553, "Unable to set option");
364  break;
365  case SETOPT_ERR_MISC:
366  default:
367  SEND_ERRMSG(550, "Unable to load config");
368  break;
369  case SETOPT_OK:
370  send_control_done(conn);
371  break;
372  }
373 #undef SEND_ERRMSG
374  tor_free(errstring);
375  return 0;
376 }
377 
378 static const control_cmd_syntax_t setevents_syntax = {
379  .max_args = UINT_MAX
380 };
381 
382 /** Called when we get a SETEVENTS message: update conn->event_mask,
383  * and reply with DONE or ERROR. */
384 static int
386  const control_cmd_args_t *args)
387 {
388  int event_code;
389  event_mask_t event_mask = 0;
390  const smartlist_t *events = args->args;
391 
392  SMARTLIST_FOREACH_BEGIN(events, const char *, ev)
393  {
394  if (!strcasecmp(ev, "EXTENDED") ||
395  !strcasecmp(ev, "AUTHDIR_NEWDESCS")) {
396  log_warn(LD_CONTROL, "The \"%s\" SETEVENTS argument is no longer "
397  "supported.", ev);
398  continue;
399  } else {
400  int i;
401  event_code = -1;
402 
403  for (i = 0; control_event_table[i].event_name != NULL; ++i) {
404  if (!strcasecmp(ev, control_event_table[i].event_name)) {
405  event_code = control_event_table[i].event_code;
406  break;
407  }
408  }
409 
410  if (event_code == -1) {
411  control_printf_endreply(conn, 552, "Unrecognized event \"%s\"", ev);
412  return 0;
413  }
414  }
415  event_mask |= (((event_mask_t)1) << event_code);
416  }
417  SMARTLIST_FOREACH_END(ev);
418 
419  conn->event_mask = event_mask;
420 
422  send_control_done(conn);
423  return 0;
424 }
425 
426 static const control_cmd_syntax_t saveconf_syntax = {
427  .max_args = 0,
428  .accept_keywords = true,
429  .kvline_flags=KV_OMIT_VALS,
430 };
431 
432 /** Called when we get a SAVECONF command. Try to flush the current options to
433  * disk, and report success or failure. */
434 static int
436  const control_cmd_args_t *args)
437 {
438  bool force = config_lines_contain_flag(args->kwargs, "FORCE");
439  const or_options_t *options = get_options();
440  if ((!force && options->IncludeUsed) || options_save_current() < 0) {
441  control_write_endreply(conn, 551,
442  "Unable to write configuration to disk.");
443  } else {
444  send_control_done(conn);
445  }
446  return 0;
447 }
448 
449 static const control_cmd_syntax_t signal_syntax = {
450  .min_args = 1,
451  .max_args = 1,
452 };
453 
454 /** Called when we get a SIGNAL command. React to the provided signal, and
455  * report success or failure. (If the signal results in a shutdown, success
456  * may not be reported.) */
457 static int
459  const control_cmd_args_t *args)
460 {
461  int sig = -1;
462  int i;
463 
464  tor_assert(smartlist_len(args->args) == 1);
465  const char *s = smartlist_get(args->args, 0);
466 
467  for (i = 0; signal_table[i].signal_name != NULL; ++i) {
468  if (!strcasecmp(s, signal_table[i].signal_name)) {
469  sig = signal_table[i].sig;
470  break;
471  }
472  }
473 
474  if (sig < 0)
475  control_printf_endreply(conn, 552, "Unrecognized signal code \"%s\"", s);
476  if (sig < 0)
477  return 0;
478 
479  send_control_done(conn);
480  /* Flush the "done" first if the signal might make us shut down. */
481  if (sig == SIGTERM || sig == SIGINT)
482  connection_flush(TO_CONN(conn));
483 
484  activate_signal(sig);
485 
486  return 0;
487 }
488 
489 static const control_cmd_syntax_t takeownership_syntax = {
490  .max_args = UINT_MAX, // This should probably become zero. XXXXX
491 };
492 
493 /** Called when we get a TAKEOWNERSHIP command. Mark this connection
494  * as an owning connection, so that we will exit if the connection
495  * closes. */
496 static int
498  const control_cmd_args_t *args)
499 {
500  (void)args;
501 
503 
504  log_info(LD_CONTROL, "Control connection %d has taken ownership of this "
505  "Tor instance.",
506  (int)(conn->base_.s));
507 
508  send_control_done(conn);
509  return 0;
510 }
511 
512 static const control_cmd_syntax_t dropownership_syntax = {
513  .max_args = UINT_MAX, // This should probably become zero. XXXXX
514 };
515 
516 /** Called when we get a DROPOWNERSHIP command. Mark this connection
517  * as a non-owning connection, so that we will not exit if the connection
518  * closes. */
519 static int
521  const control_cmd_args_t *args)
522 {
523  (void)args;
524 
526 
527  log_info(LD_CONTROL, "Control connection %d has dropped ownership of this "
528  "Tor instance.",
529  (int)(conn->base_.s));
530 
531  send_control_done(conn);
532  return 0;
533 }
534 
535 /** Given a text circuit <b>id</b>, return the corresponding circuit. */
536 static origin_circuit_t *
537 get_circ(const char *id)
538 {
539  uint32_t n_id;
540  int ok;
541  n_id = (uint32_t) tor_parse_ulong(id, 10, 0, UINT32_MAX, &ok, NULL);
542  if (!ok)
543  return NULL;
544  return circuit_get_by_global_id(n_id);
545 }
546 
547 /** Given a text stream <b>id</b>, return the corresponding AP connection. */
548 static entry_connection_t *
549 get_stream(const char *id)
550 {
551  uint64_t n_id;
552  int ok;
553  connection_t *conn;
554  n_id = tor_parse_uint64(id, 10, 0, UINT64_MAX, &ok, NULL);
555  if (!ok)
556  return NULL;
557  conn = connection_get_by_global_id(n_id);
558  if (!conn || conn->type != CONN_TYPE_AP || conn->marked_for_close)
559  return NULL;
560  return TO_ENTRY_CONN(conn);
561 }
562 
563 /** Helper for setconf and resetconf. Acts like setconf, except
564  * it passes <b>use_defaults</b> on to options_trial_assign(). Modifies the
565  * contents of body.
566  */
567 static int
569  const control_cmd_args_t *args,
570  int use_defaults)
571 {
572  setopt_err_t opt_err;
573  char *errstring = NULL;
574  const unsigned flags =
575  CAL_CLEAR_FIRST | (use_defaults ? CAL_USE_DEFAULTS : 0);
576 
577  // We need a copy here, since confmgt.c wants to canonicalize cases.
578  config_line_t *lines = config_lines_dup(args->kwargs);
579 
580  opt_err = options_trial_assign(lines, flags, &errstring);
581  {
582 #define SEND_ERRMSG(code, msg) \
583  control_printf_endreply(conn, code, msg ": %s", errstring);
584 
585  switch (opt_err) {
586  case SETOPT_ERR_MISC:
587  SEND_ERRMSG(552, "Unrecognized option");
588  break;
589  case SETOPT_ERR_PARSE:
590  SEND_ERRMSG(513, "Unacceptable option value");
591  break;
592  case SETOPT_ERR_TRANSITION:
593  SEND_ERRMSG(553, "Transition not allowed");
594  break;
595  case SETOPT_ERR_SETTING:
596  default:
597  SEND_ERRMSG(553, "Unable to set option");
598  break;
599  case SETOPT_OK:
600  config_free_lines(lines);
601  send_control_done(conn);
602  return 0;
603  }
604 #undef SEND_ERRMSG
605  log_warn(LD_CONTROL,
606  "Controller gave us config lines that didn't validate: %s",
607  errstring);
608  config_free_lines(lines);
609  tor_free(errstring);
610  return 0;
611  }
612 }
613 
614 /** Return true iff <b>addr</b> is unusable as a mapaddress target because of
615  * containing funny characters. */
616 static int
618 {
619  if (!strcmpstart(addr, "*."))
620  return address_is_invalid_destination(addr+2, 1);
621  else
622  return address_is_invalid_destination(addr, 1);
623 }
624 
625 static const control_cmd_syntax_t mapaddress_syntax = {
626  // no positional arguments are expected
627  .max_args=0,
628  // an arbitrary number of K=V entries are supported.
629  .accept_keywords=true,
630 };
631 
632 /** Called when we get a MAPADDRESS command; try to bind all listed addresses,
633  * and report success or failure. */
634 static int
636  const control_cmd_args_t *args)
637 {
638  smartlist_t *reply;
639  char *r;
640  size_t sz;
641 
642  reply = smartlist_new();
643  const config_line_t *line;
644  for (line = args->kwargs; line; line = line->next) {
645  const char *from = line->key;
646  const char *to = line->value;
647  {
650  "512-syntax error: invalid address '%s'", to);
651  log_warn(LD_CONTROL,
652  "Skipping invalid argument '%s' in MapAddress msg", to);
653  } else if (!strcmp(from, ".") || !strcmp(from, "0.0.0.0") ||
654  !strcmp(from, "::")) {
655  const char type =
656  !strcmp(from,".") ? RESOLVED_TYPE_HOSTNAME :
657  (!strcmp(from, "0.0.0.0") ? RESOLVED_TYPE_IPV4 : RESOLVED_TYPE_IPV6);
658  const char *address = addressmap_register_virtual_address(
659  type, tor_strdup(to));
660  if (!address) {
662  "451-resource exhausted: skipping '%s=%s'", from,to);
663  log_warn(LD_CONTROL,
664  "Unable to allocate address for '%s' in MapAddress msg",
665  safe_str_client(to));
666  } else {
667  smartlist_add_asprintf(reply, "250-%s=%s", address, to);
668  }
669  } else {
670  const char *msg;
671  if (addressmap_register_auto(from, to, 1,
672  ADDRMAPSRC_CONTROLLER, &msg) < 0) {
674  "512-syntax error: invalid address mapping "
675  " '%s=%s': %s", from, to, msg);
676  log_warn(LD_CONTROL,
677  "Skipping invalid argument '%s=%s' in MapAddress msg: %s",
678  from, to, msg);
679  } else {
680  smartlist_add_asprintf(reply, "250-%s=%s", from, to);
681  }
682  }
683  }
684  }
685 
686  if (smartlist_len(reply)) {
687  ((char*)smartlist_get(reply,smartlist_len(reply)-1))[3] = ' ';
688  r = smartlist_join_strings(reply, "\r\n", 1, &sz);
689  connection_buf_add(r, sz, TO_CONN(conn));
690  tor_free(r);
691  } else {
692  control_write_endreply(conn, 512, "syntax error: "
693  "not enough arguments to mapaddress.");
694  }
695 
696  SMARTLIST_FOREACH(reply, char *, cp, tor_free(cp));
697  smartlist_free(reply);
698  return 0;
699 }
700 
701 /** Given a string, convert it to a circuit purpose. */
702 static uint8_t
703 circuit_purpose_from_string(const char *string)
704 {
705  if (!strcasecmpstart(string, "purpose="))
706  string += strlen("purpose=");
707 
708  if (!strcasecmp(string, "general"))
710  else if (!strcasecmp(string, "controller"))
712  else
714 }
715 
716 static const control_cmd_syntax_t extendcircuit_syntax = {
717  .min_args=1,
718  .max_args=1, // see note in function
719  .accept_keywords=true,
720  .kvline_flags=KV_OMIT_VALS
721 };
722 
723 /** Called when we get an EXTENDCIRCUIT message. Try to extend the listed
724  * circuit, and report success or failure. */
725 static int
727  const control_cmd_args_t *args)
728 {
729  smartlist_t *router_nicknames=smartlist_new(), *nodes=NULL;
730  origin_circuit_t *circ = NULL;
731  uint8_t intended_purpose = CIRCUIT_PURPOSE_C_GENERAL;
732  const config_line_t *kwargs = args->kwargs;
733  const char *circ_id = smartlist_get(args->args, 0);
734  const char *path_str = NULL;
735  char *path_str_alloc = NULL;
736 
737  /* The syntax for this command is unfortunate. The second argument is
738  optional, and is a comma-separated list long-format fingerprints, which
739  can (historically!) contain an equals sign.
740 
741  Here we check the second argument to see if it's a path, and if so we
742  remove it from the kwargs list and put it in path_str.
743  */
744  if (kwargs) {
745  const config_line_t *arg1 = kwargs;
746  if (!strcmp(arg1->value, "")) {
747  path_str = arg1->key;
748  kwargs = kwargs->next;
749  } else if (arg1->key[0] == '$') {
750  tor_asprintf(&path_str_alloc, "%s=%s", arg1->key, arg1->value);
751  path_str = path_str_alloc;
752  kwargs = kwargs->next;
753  }
754  }
755 
756  const config_line_t *purpose_line = config_line_find_case(kwargs, "PURPOSE");
757  bool zero_circ = !strcmp("0", circ_id);
758 
759  if (purpose_line) {
760  intended_purpose = circuit_purpose_from_string(purpose_line->value);
761  if (intended_purpose == CIRCUIT_PURPOSE_UNKNOWN) {
762  control_printf_endreply(conn, 552, "Unknown purpose \"%s\"",
763  purpose_line->value);
764  goto done;
765  }
766  }
767 
768  if (zero_circ) {
769  if (!path_str) {
770  // "EXTENDCIRCUIT 0" with no path.
771  circ = circuit_launch(intended_purpose, CIRCLAUNCH_NEED_CAPACITY);
772  if (!circ) {
773  control_write_endreply(conn, 551, "Couldn't start circuit");
774  } else {
775  control_printf_endreply(conn, 250, "EXTENDED %lu",
776  (unsigned long)circ->global_identifier);
777  }
778  goto done;
779  }
780  }
781 
782  if (!zero_circ && !(circ = get_circ(circ_id))) {
783  control_printf_endreply(conn, 552, "Unknown circuit \"%s\"", circ_id);
784  goto done;
785  }
786 
787  if (!path_str) {
788  control_write_endreply(conn, 512, "syntax error: path required.");
789  goto done;
790  }
791 
792  smartlist_split_string(router_nicknames, path_str, ",", 0, 0);
793 
794  nodes = smartlist_new();
795  bool first_node = zero_circ;
796  SMARTLIST_FOREACH_BEGIN(router_nicknames, const char *, n) {
797  const node_t *node = node_get_by_nickname(n, 0);
798  if (!node) {
799  control_printf_endreply(conn, 552, "No such router \"%s\"", n);
800  goto done;
801  }
802  if (!node_has_preferred_descriptor(node, first_node)) {
803  control_printf_endreply(conn, 552, "No descriptor for \"%s\"", n);
804  goto done;
805  }
806  smartlist_add(nodes, (void*)node);
807  first_node = false;
808  } SMARTLIST_FOREACH_END(n);
809 
810  if (!smartlist_len(nodes)) {
811  control_write_endreply(conn, 512, "No router names provided");
812  goto done;
813  }
814 
815  if (zero_circ) {
816  /* start a new circuit */
817  circ = origin_circuit_init(intended_purpose, 0);
818  }
819 
820  /* now circ refers to something that is ready to be extended */
821  first_node = zero_circ;
822  SMARTLIST_FOREACH(nodes, const node_t *, node,
823  {
824  extend_info_t *info = extend_info_from_node(node, first_node);
825  if (!info) {
826  tor_assert_nonfatal(first_node);
827  log_warn(LD_CONTROL,
828  "controller tried to connect to a node that lacks a suitable "
829  "descriptor, or which doesn't have any "
830  "addresses that are allowed by the firewall configuration; "
831  "circuit marked for closing.");
832  circuit_mark_for_close(TO_CIRCUIT(circ), -END_CIRC_REASON_CONNECTFAILED);
833  control_write_endreply(conn, 551, "Couldn't start circuit");
834  goto done;
835  }
836  circuit_append_new_exit(circ, info);
837  if (circ->build_state->desired_path_len > 1) {
838  circ->build_state->onehop_tunnel = 0;
839  }
840  extend_info_free(info);
841  first_node = 0;
842  });
843 
844  /* now that we've populated the cpath, start extending */
845  if (zero_circ) {
846  int err_reason = 0;
847  if ((err_reason = circuit_handle_first_hop(circ)) < 0) {
848  circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
849  control_write_endreply(conn, 551, "Couldn't start circuit");
850  goto done;
851  }
852  } else {
853  if (circ->base_.state == CIRCUIT_STATE_OPEN ||
854  circ->base_.state == CIRCUIT_STATE_GUARD_WAIT) {
855  int err_reason = 0;
857  if ((err_reason = circuit_send_next_onion_skin(circ)) < 0) {
858  log_info(LD_CONTROL,
859  "send_next_onion_skin failed; circuit marked for closing.");
860  circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
861  control_write_endreply(conn, 551, "Couldn't send onion skin");
862  goto done;
863  }
864  }
865  }
866 
867  control_printf_endreply(conn, 250, "EXTENDED %lu",
868  (unsigned long)circ->global_identifier);
869  if (zero_circ) /* send a 'launched' event, for completeness */
870  circuit_event_status(circ, CIRC_EVENT_LAUNCHED, 0);
871  done:
872  SMARTLIST_FOREACH(router_nicknames, char *, n, tor_free(n));
873  smartlist_free(router_nicknames);
874  smartlist_free(nodes);
875  tor_free(path_str_alloc);
876  return 0;
877 }
878 
879 static const control_cmd_syntax_t setcircuitpurpose_syntax = {
880  .max_args=1,
881  .accept_keywords=true,
882 };
883 
884 /** Called when we get a SETCIRCUITPURPOSE message. If we can find the
885  * circuit and it's a valid purpose, change it. */
886 static int
888  const control_cmd_args_t *args)
889 {
890  origin_circuit_t *circ = NULL;
891  uint8_t new_purpose;
892  const char *circ_id = smartlist_get(args->args,0);
893 
894  if (!(circ = get_circ(circ_id))) {
895  control_printf_endreply(conn, 552, "Unknown circuit \"%s\"", circ_id);
896  goto done;
897  }
898 
899  {
900  const config_line_t *purp = config_line_find_case(args->kwargs, "PURPOSE");
901  if (!purp) {
902  control_write_endreply(conn, 552, "No purpose given");
903  goto done;
904  }
905  new_purpose = circuit_purpose_from_string(purp->value);
906  if (new_purpose == CIRCUIT_PURPOSE_UNKNOWN) {
907  control_printf_endreply(conn, 552, "Unknown purpose \"%s\"",
908  purp->value);
909  goto done;
910  }
911  }
912 
913  circuit_change_purpose(TO_CIRCUIT(circ), new_purpose);
914  send_control_done(conn);
915 
916  done:
917  return 0;
918 }
919 
920 static const char *attachstream_keywords[] = {
921  "HOP", NULL
922 };
923 static const control_cmd_syntax_t attachstream_syntax = {
924  .min_args=2, .max_args=2,
925  .accept_keywords=true,
926  .allowed_keywords=attachstream_keywords
927 };
928 
929 /** Called when we get an ATTACHSTREAM message. Try to attach the requested
930  * stream, and report success or failure. */
931 static int
933  const control_cmd_args_t *args)
934 {
935  entry_connection_t *ap_conn = NULL;
936  origin_circuit_t *circ = NULL;
937  crypt_path_t *cpath=NULL;
938  int hop=0, hop_line_ok=1;
939  const char *stream_id = smartlist_get(args->args, 0);
940  const char *circ_id = smartlist_get(args->args, 1);
941  int zero_circ = !strcmp(circ_id, "0");
942  const config_line_t *hoparg = config_line_find_case(args->kwargs, "HOP");
943 
944  if (!(ap_conn = get_stream(stream_id))) {
945  control_printf_endreply(conn, 552, "Unknown stream \"%s\"", stream_id);
946  return 0;
947  } else if (!zero_circ && !(circ = get_circ(circ_id))) {
948  control_printf_endreply(conn, 552, "Unknown circuit \"%s\"", circ_id);
949  return 0;
950  } else if (circ) {
951  if (hoparg) {
952  hop = (int) tor_parse_ulong(hoparg->value, 10, 0, INT_MAX,
953  &hop_line_ok, NULL);
954  if (!hop_line_ok) { /* broken hop line */
955  control_printf_endreply(conn, 552, "Bad value hop=%s",
956  hoparg->value);
957  return 0;
958  }
959  }
960  }
961 
962  if (ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONTROLLER_WAIT &&
963  ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONNECT_WAIT &&
964  ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_RESOLVE_WAIT) {
965  control_write_endreply(conn, 555,
966  "Connection is not managed by controller.");
967  return 0;
968  }
969 
970  /* Do we need to detach it first? */
971  if (ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONTROLLER_WAIT) {
972  edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
973  circuit_t *tmpcirc = circuit_get_by_edge_conn(edge_conn);
974  connection_edge_end(edge_conn, END_STREAM_REASON_TIMEOUT);
975  /* Un-mark it as ending, since we're going to reuse it. */
976  edge_conn->edge_has_sent_end = 0;
977  edge_conn->end_reason = 0;
978  if (tmpcirc)
979  circuit_detach_stream(tmpcirc, edge_conn);
980  CONNECTION_AP_EXPECT_NONPENDING(ap_conn);
981  TO_CONN(edge_conn)->state = AP_CONN_STATE_CONTROLLER_WAIT;
982  }
983 
984  if (circ && (circ->base_.state != CIRCUIT_STATE_OPEN)) {
985  control_write_endreply(conn, 551,
986  "Can't attach stream to non-open origin circuit");
987  return 0;
988  }
989  /* Is this a single hop circuit? */
990  if (circ && (circuit_get_cpath_len(circ)<2 || hop==1)) {
991  control_write_endreply(conn, 551,
992  "Can't attach stream to this one-hop circuit.");
993  return 0;
994  }
995 
996  if (circ && hop>0) {
997  /* find this hop in the circuit, and set cpath */
998  cpath = circuit_get_cpath_hop(circ, hop);
999  if (!cpath) {
1000  control_printf_endreply(conn, 551, "Circuit doesn't have %d hops.", hop);
1001  return 0;
1002  }
1003  }
1004  if (connection_ap_handshake_rewrite_and_attach(ap_conn, circ, cpath) < 0) {
1005  control_write_endreply(conn, 551, "Unable to attach stream");
1006  return 0;
1007  }
1008  send_control_done(conn);
1009  return 0;
1010 }
1011 
1012 static const char *postdescriptor_keywords[] = {
1013  "cache", "purpose", NULL,
1014 };
1015 
1016 static const control_cmd_syntax_t postdescriptor_syntax = {
1017  .max_args = 0,
1018  .accept_keywords = true,
1019  .allowed_keywords = postdescriptor_keywords,
1020  .want_cmddata = true,
1021 };
1022 
1023 /** Called when we get a POSTDESCRIPTOR message. Try to learn the provided
1024  * descriptor, and report success or failure. */
1025 static int
1027  const control_cmd_args_t *args)
1028 {
1029  const char *msg=NULL;
1030  uint8_t purpose = ROUTER_PURPOSE_GENERAL;
1031  int cache = 0; /* eventually, we may switch this to 1 */
1032  const config_line_t *line;
1033 
1034  line = config_line_find_case(args->kwargs, "purpose");
1035  if (line) {
1036  purpose = router_purpose_from_string(line->value);
1037  if (purpose == ROUTER_PURPOSE_UNKNOWN) {
1038  control_printf_endreply(conn, 552, "Unknown purpose \"%s\"",
1039  line->value);
1040  goto done;
1041  }
1042  }
1043  line = config_line_find_case(args->kwargs, "cache");
1044  if (line) {
1045  if (!strcasecmp(line->value, "no"))
1046  cache = 0;
1047  else if (!strcasecmp(line->value, "yes"))
1048  cache = 1;
1049  else {
1050  control_printf_endreply(conn, 552, "Unknown cache request \"%s\"",
1051  line->value);
1052  goto done;
1053  }
1054  }
1055 
1056  switch (router_load_single_router(args->cmddata, purpose, cache, &msg)) {
1057  case -1:
1058  if (!msg) msg = "Could not parse descriptor";
1059  control_write_endreply(conn, 554, msg);
1060  break;
1061  case 0:
1062  if (!msg) msg = "Descriptor not added";
1063  control_write_endreply(conn, 251, msg);
1064  break;
1065  case 1:
1066  send_control_done(conn);
1067  break;
1068  }
1069 
1070  done:
1071  return 0;
1072 }
1073 
1074 static const control_cmd_syntax_t redirectstream_syntax = {
1075  .min_args = 2,
1076  .max_args = UINT_MAX, // XXX should be 3.
1077 };
1078 
1079 /** Called when we receive a REDIRECTSTERAM command. Try to change the target
1080  * address of the named AP stream, and report success or failure. */
1081 static int
1083  const control_cmd_args_t *cmd_args)
1084 {
1085  entry_connection_t *ap_conn = NULL;
1086  char *new_addr = NULL;
1087  uint16_t new_port = 0;
1088  const smartlist_t *args = cmd_args->args;
1089 
1090  if (!(ap_conn = get_stream(smartlist_get(args, 0)))
1091  || !ap_conn->socks_request) {
1092  control_printf_endreply(conn, 552, "Unknown stream \"%s\"",
1093  (char*)smartlist_get(args, 0));
1094  } else {
1095  int ok = 1;
1096  if (smartlist_len(args) > 2) { /* they included a port too */
1097  new_port = (uint16_t) tor_parse_ulong(smartlist_get(args, 2),
1098  10, 1, 65535, &ok, NULL);
1099  }
1100  if (!ok) {
1101  control_printf_endreply(conn, 512, "Cannot parse port \"%s\"",
1102  (char*)smartlist_get(args, 2));
1103  } else {
1104  new_addr = tor_strdup(smartlist_get(args, 1));
1105  }
1106  }
1107 
1108  if (!new_addr)
1109  return 0;
1110 
1111  strlcpy(ap_conn->socks_request->address, new_addr,
1112  sizeof(ap_conn->socks_request->address));
1113  if (new_port)
1114  ap_conn->socks_request->port = new_port;
1115  tor_free(new_addr);
1116  send_control_done(conn);
1117  return 0;
1118 }
1119 
1120 static const control_cmd_syntax_t closestream_syntax = {
1121  .min_args = 2,
1122  .max_args = UINT_MAX, /* XXXX This is the original behavior, but
1123  * maybe we should change the spec. */
1124 };
1125 
1126 /** Called when we get a CLOSESTREAM command; try to close the named stream
1127  * and report success or failure. */
1128 static int
1130  const control_cmd_args_t *cmd_args)
1131 {
1132  entry_connection_t *ap_conn=NULL;
1133  uint8_t reason=0;
1134  int ok;
1135  const smartlist_t *args = cmd_args->args;
1136 
1137  tor_assert(smartlist_len(args) >= 2);
1138 
1139  if (!(ap_conn = get_stream(smartlist_get(args, 0))))
1140  control_printf_endreply(conn, 552, "Unknown stream \"%s\"",
1141  (char*)smartlist_get(args, 0));
1142  else {
1143  reason = (uint8_t) tor_parse_ulong(smartlist_get(args,1), 10, 0, 255,
1144  &ok, NULL);
1145  if (!ok) {
1146  control_printf_endreply(conn, 552, "Unrecognized reason \"%s\"",
1147  (char*)smartlist_get(args, 1));
1148  ap_conn = NULL;
1149  }
1150  }
1151  if (!ap_conn)
1152  return 0;
1153 
1154  connection_mark_unattached_ap(ap_conn, reason);
1155  send_control_done(conn);
1156  return 0;
1157 }
1158 
1159 static const control_cmd_syntax_t closecircuit_syntax = {
1160  .min_args=1, .max_args=1,
1161  .accept_keywords=true,
1162  .kvline_flags=KV_OMIT_VALS,
1163  // XXXX we might want to exclude unrecognized flags, but for now we
1164  // XXXX just ignore them for backward compatibility.
1165 };
1166 
1167 /** Called when we get a CLOSECIRCUIT command; try to close the named circuit
1168  * and report success or failure. */
1169 static int
1171  const control_cmd_args_t *args)
1172 {
1173  const char *circ_id = smartlist_get(args->args, 0);
1174  origin_circuit_t *circ = NULL;
1175 
1176  if (!(circ=get_circ(circ_id))) {
1177  control_printf_endreply(conn, 552, "Unknown circuit \"%s\"", circ_id);
1178  return 0;
1179  }
1180 
1181  bool safe = config_lines_contain_flag(args->kwargs, "IfUnused");
1182 
1183  if (!safe || !circ->p_streams) {
1184  circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_REQUESTED);
1185  }
1186 
1187  send_control_done(conn);
1188  return 0;
1189 }
1190 
1191 static const control_cmd_syntax_t resolve_syntax = {
1192  .max_args=0,
1193  .accept_keywords=true,
1194  .kvline_flags=KV_OMIT_VALS,
1195 };
1196 
1197 /** Called when we get a RESOLVE command: start trying to resolve
1198  * the listed addresses. */
1199 static int
1201  const control_cmd_args_t *args)
1202 {
1203  smartlist_t *failed;
1204  int is_reverse = 0;
1205 
1206  if (!(conn->event_mask & (((event_mask_t)1)<<EVENT_ADDRMAP))) {
1207  log_warn(LD_CONTROL, "Controller asked us to resolve an address, but "
1208  "isn't listening for ADDRMAP events. It probably won't see "
1209  "the answer.");
1210  }
1211 
1212  {
1213  const config_line_t *modearg = config_line_find_case(args->kwargs, "mode");
1214  if (modearg && !strcasecmp(modearg->value, "reverse"))
1215  is_reverse = 1;
1216  }
1217  failed = smartlist_new();
1218  for (const config_line_t *line = args->kwargs; line; line = line->next) {
1219  if (!strlen(line->value)) {
1220  const char *addr = line->key;
1221  if (dnsserv_launch_request(addr, is_reverse, conn)<0)
1222  smartlist_add(failed, (char*)addr);
1223  } else {
1224  // XXXX arguably we should reject unrecognized keyword arguments,
1225  // XXXX but the old implementation didn't do that.
1226  }
1227  }
1228 
1229  send_control_done(conn);
1230  SMARTLIST_FOREACH(failed, const char *, arg, {
1231  control_event_address_mapped(arg, arg, time(NULL),
1232  "internal", 0);
1233  });
1234 
1235  smartlist_free(failed);
1236  return 0;
1237 }
1238 
1239 static const control_cmd_syntax_t protocolinfo_syntax = {
1240  .max_args = UINT_MAX
1241 };
1242 
1243 /** Return a comma-separated list of authentication methods for
1244  handle_control_protocolinfo(). Caller must free this string. */
1245 static char *
1247 {
1248  int cookies = options->CookieAuthentication;
1249  char *methods;
1250  int passwd = (options->HashedControlPassword != NULL ||
1251  options->HashedControlSessionPassword != NULL);
1252  smartlist_t *mlist = smartlist_new();
1253 
1254  if (cookies) {
1255  smartlist_add(mlist, (char*)"COOKIE");
1256  smartlist_add(mlist, (char*)"SAFECOOKIE");
1257  }
1258  if (passwd)
1259  smartlist_add(mlist, (char*)"HASHEDPASSWORD");
1260  if (!cookies && !passwd)
1261  smartlist_add(mlist, (char*)"NULL");
1262  methods = smartlist_join_strings(mlist, ",", 0, NULL);
1263  smartlist_free(mlist);
1264 
1265  return methods;
1266 }
1267 
1268 /** Return escaped cookie filename. Caller must free this string.
1269  Return NULL if cookie authentication is disabled. */
1270 static char *
1272 {
1273  char *cfile = NULL, *abs_cfile = NULL, *esc_cfile = NULL;
1274 
1275  if (!options->CookieAuthentication)
1276  return NULL;
1277 
1279  abs_cfile = make_path_absolute(cfile);
1280  esc_cfile = esc_for_log(abs_cfile);
1281  tor_free(cfile);
1282  tor_free(abs_cfile);
1283  return esc_cfile;
1284 }
1285 
1286 /** Compose the auth methods line of a PROTOCOLINFO reply. */
1287 static void
1289 {
1290  const or_options_t *options = get_options();
1291  char *methods = get_authmethods(options);
1292  char *esc_cfile = get_esc_cfile(options);
1293 
1294  control_reply_add_str(reply, 250, "AUTH");
1295  control_reply_append_kv(reply, "METHODS", methods);
1296  if (esc_cfile)
1297  control_reply_append_kv(reply, "COOKIEFILE", esc_cfile);
1298 
1299  tor_free(methods);
1300  tor_free(esc_cfile);
1301 }
1302 
1303 /** Called when we get a PROTOCOLINFO command: send back a reply. */
1304 static int
1306  const control_cmd_args_t *cmd_args)
1307 {
1308  const char *bad_arg = NULL;
1309  const smartlist_t *args = cmd_args->args;
1310  smartlist_t *reply = NULL;
1311 
1312  conn->have_sent_protocolinfo = 1;
1313 
1314  SMARTLIST_FOREACH(args, const char *, arg, {
1315  int ok;
1316  tor_parse_long(arg, 10, 0, LONG_MAX, &ok, NULL);
1317  if (!ok) {
1318  bad_arg = arg;
1319  break;
1320  }
1321  });
1322  if (bad_arg) {
1323  control_printf_endreply(conn, 513, "No such version %s",
1324  escaped(bad_arg));
1325  /* Don't tolerate bad arguments when not authenticated. */
1326  if (!STATE_IS_OPEN(TO_CONN(conn)->state))
1327  connection_mark_for_close(TO_CONN(conn));
1328  return 0;
1329  }
1330  reply = smartlist_new();
1331  control_reply_add_str(reply, 250, "PROTOCOLINFO 1");
1332  add_authmethods(reply);
1333  control_reply_add_str(reply, 250, "VERSION");
1334  control_reply_append_kv(reply, "Tor", escaped(VERSION));
1335  control_reply_add_done(reply);
1336 
1337  control_write_reply_lines(conn, reply);
1338  control_reply_free(reply);
1339  return 0;
1340 }
1341 
1342 static const control_cmd_syntax_t usefeature_syntax = {
1343  .max_args = UINT_MAX
1344 };
1345 
1346 /** Called when we get a USEFEATURE command: parse the feature list, and
1347  * set up the control_connection's options properly. */
1348 static int
1350  const control_cmd_args_t *cmd_args)
1351 {
1352  const smartlist_t *args = cmd_args->args;
1353  int bad = 0;
1354  SMARTLIST_FOREACH_BEGIN(args, const char *, arg) {
1355  if (!strcasecmp(arg, "VERBOSE_NAMES"))
1356  ;
1357  else if (!strcasecmp(arg, "EXTENDED_EVENTS"))
1358  ;
1359  else {
1360  control_printf_endreply(conn, 552, "Unrecognized feature \"%s\"",
1361  arg);
1362  bad = 1;
1363  break;
1364  }
1365  } SMARTLIST_FOREACH_END(arg);
1366 
1367  if (!bad) {
1368  send_control_done(conn);
1369  }
1370 
1371  return 0;
1372 }
1373 
1374 static const control_cmd_syntax_t dropguards_syntax = {
1375  .max_args = 0,
1376 };
1377 
1378 /** Implementation for the DROPGUARDS command. */
1379 static int
1381  const control_cmd_args_t *args)
1382 {
1383  (void) args; /* We don't take arguments. */
1384 
1385  static int have_warned = 0;
1386  if (! have_warned) {
1387  log_warn(LD_CONTROL, "DROPGUARDS is dangerous; make sure you understand "
1388  "the risks before using it. It may be removed in a future "
1389  "version of Tor.");
1390  have_warned = 1;
1391  }
1392 
1394  send_control_done(conn);
1395 
1396  return 0;
1397 }
1398 
1399 static const char *hsfetch_keywords[] = {
1400  "SERVER", NULL,
1401 };
1402 static const control_cmd_syntax_t hsfetch_syntax = {
1403  .min_args = 1, .max_args = 1,
1404  .accept_keywords = true,
1405  .allowed_keywords = hsfetch_keywords,
1406 };
1407 
1408 /** Implementation for the HSFETCH command. */
1409 static int
1411  const control_cmd_args_t *args)
1412 
1413 {
1414  char digest[DIGEST_LEN], *desc_id = NULL;
1415  smartlist_t *hsdirs = NULL;
1416  static const char *v2_str = "v2-";
1417  const size_t v2_str_len = strlen(v2_str);
1418  rend_data_t *rend_query = NULL;
1419  ed25519_public_key_t v3_pk;
1420  uint32_t version;
1421  const char *hsaddress = NULL;
1422 
1423  /* Extract the first argument (either HSAddress or DescID). */
1424  const char *arg1 = smartlist_get(args->args, 0);
1425  /* Test if it's an HS address without the .onion part. */
1426  if (rend_valid_v2_service_id(arg1)) {
1427  hsaddress = arg1;
1428  version = HS_VERSION_TWO;
1429  } else if (strcmpstart(arg1, v2_str) == 0 &&
1430  rend_valid_descriptor_id(arg1 + v2_str_len) &&
1431  base32_decode(digest, sizeof(digest), arg1 + v2_str_len,
1434  /* We have a well formed version 2 descriptor ID. Keep the decoded value
1435  * of the id. */
1436  desc_id = digest;
1437  version = HS_VERSION_TWO;
1438  } else if (hs_address_is_valid(arg1)) {
1439  hsaddress = arg1;
1440  version = HS_VERSION_THREE;
1441  hs_parse_address(hsaddress, &v3_pk, NULL, NULL);
1442  } else {
1443  control_printf_endreply(conn, 513, "Invalid argument \"%s\"", arg1);
1444  goto done;
1445  }
1446 
1447  for (const config_line_t *line = args->kwargs; line; line = line->next) {
1448  if (!strcasecmp(line->key, "SERVER")) {
1449  const char *server = line->value;
1450 
1451  const node_t *node = node_get_by_hex_id(server, 0);
1452  if (!node) {
1453  control_printf_endreply(conn, 552, "Server \"%s\" not found", server);
1454  goto done;
1455  }
1456  if (!hsdirs) {
1457  /* Stores routerstatus_t cmddata for each specified server. */
1458  hsdirs = smartlist_new();
1459  }
1460  /* Valid server, add it to our local list. */
1461  smartlist_add(hsdirs, node->rs);
1462  } else {
1463  tor_assert_nonfatal_unreached();
1464  }
1465  }
1466 
1467  if (version == HS_VERSION_TWO) {
1468  rend_query = rend_data_client_create(hsaddress, desc_id, NULL,
1469  REND_NO_AUTH);
1470  if (rend_query == NULL) {
1471  control_write_endreply(conn, 551, "Error creating the HS query");
1472  goto done;
1473  }
1474  }
1475 
1476  /* Using a descriptor ID, we force the user to provide at least one
1477  * hsdir server using the SERVER= option. */
1478  if (desc_id && (!hsdirs || !smartlist_len(hsdirs))) {
1479  control_write_endreply(conn, 512, "SERVER option is required");
1480  goto done;
1481  }
1482 
1483  /* We are about to trigger HSDir fetch so send the OK now because after
1484  * that 650 event(s) are possible so better to have the 250 OK before them
1485  * to avoid out of order replies. */
1486  send_control_done(conn);
1487 
1488  /* Trigger the fetch using the built rend query and possibly a list of HS
1489  * directory to use. This function ignores the client cache thus this will
1490  * always send a fetch command. */
1491  if (version == HS_VERSION_TWO) {
1492  rend_client_fetch_v2_desc(rend_query, hsdirs);
1493  } else if (version == HS_VERSION_THREE) {
1494  hs_control_hsfetch_command(&v3_pk, hsdirs);
1495  }
1496 
1497  done:
1498  /* Contains data pointer that we don't own thus no cleanup. */
1499  smartlist_free(hsdirs);
1500  rend_data_free(rend_query);
1501  return 0;
1502 }
1503 
1504 static const char *hspost_keywords[] = {
1505  "SERVER", "HSADDRESS", NULL
1506 };
1507 static const control_cmd_syntax_t hspost_syntax = {
1508  .min_args = 0, .max_args = 0,
1509  .accept_keywords = true,
1510  .want_cmddata = true,
1511  .allowed_keywords = hspost_keywords
1512 };
1513 
1514 /** Implementation for the HSPOST command. */
1515 static int
1517  const control_cmd_args_t *args)
1518 {
1519  smartlist_t *hs_dirs = NULL;
1520  const char *encoded_desc = args->cmddata;
1521  size_t encoded_desc_len = args->cmddata_len;
1522  const char *onion_address = NULL;
1523  const config_line_t *line;
1524 
1525  for (line = args->kwargs; line; line = line->next) {
1526  if (!strcasecmpstart(line->key, "SERVER")) {
1527  const char *server = line->value;
1528  const node_t *node = node_get_by_hex_id(server, 0);
1529 
1530  if (!node || !node->rs) {
1531  control_printf_endreply(conn, 552, "Server \"%s\" not found",
1532  server);
1533  goto done;
1534  }
1535  /* Valid server, add it to our local list. */
1536  if (!hs_dirs)
1537  hs_dirs = smartlist_new();
1538  smartlist_add(hs_dirs, node->rs);
1539  } else if (!strcasecmpstart(line->key, "HSADDRESS")) {
1540  const char *address = line->value;
1541  if (!hs_address_is_valid(address)) {
1542  control_write_endreply(conn, 512, "Malformed onion address");
1543  goto done;
1544  }
1545  onion_address = address;
1546  } else {
1547  tor_assert_nonfatal_unreached();
1548  }
1549  }
1550 
1551  /* Handle the v3 case. */
1552  if (onion_address) {
1553  if (hs_control_hspost_command(encoded_desc, onion_address, hs_dirs) < 0) {
1554  control_write_endreply(conn, 554, "Invalid descriptor");
1555  } else {
1556  send_control_done(conn);
1557  }
1558  goto done;
1559  }
1560 
1561  /* From this point on, it is only v2. */
1562 
1563  /* parse it. */
1565  tor_malloc_zero(sizeof(rend_encoded_v2_service_descriptor_t));
1566  desc->desc_str = tor_memdup_nulterm(encoded_desc, encoded_desc_len);
1567 
1568  rend_service_descriptor_t *parsed = NULL;
1569  char *intro_content = NULL;
1570  size_t intro_size;
1571  size_t encoded_size;
1572  const char *next_desc;
1573  if (!rend_parse_v2_service_descriptor(&parsed, desc->desc_id, &intro_content,
1574  &intro_size, &encoded_size,
1575  &next_desc, desc->desc_str, 1)) {
1576  /* Post the descriptor. */
1577  char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
1578  if (!rend_get_service_id(parsed->pk, serviceid)) {
1579  smartlist_t *descs = smartlist_new();
1580  smartlist_add(descs, desc);
1581 
1582  /* We are about to trigger HS descriptor upload so send the OK now
1583  * because after that 650 event(s) are possible so better to have the
1584  * 250 OK before them to avoid out of order replies. */
1585  send_control_done(conn);
1586 
1587  /* Trigger the descriptor upload */
1588  directory_post_to_hs_dir(parsed, descs, hs_dirs, serviceid, 0);
1589  smartlist_free(descs);
1590  }
1591 
1592  rend_service_descriptor_free(parsed);
1593  } else {
1594  control_write_endreply(conn, 554, "Invalid descriptor");
1595  }
1596 
1597  tor_free(intro_content);
1598  rend_encoded_v2_service_descriptor_free(desc);
1599  done:
1600  smartlist_free(hs_dirs); /* Contents belong to the rend service code. */
1601  return 0;
1602 }
1603 
1604 /* Helper function for ADD_ONION that adds an ephemeral service depending on
1605  * the given hs_version.
1606  *
1607  * The secret key in pk depends on the hs_version. The ownership of the key
1608  * used in pk is given to the HS subsystem so the caller must stop accessing
1609  * it after.
1610  *
1611  * The port_cfgs is a list of service port. Ownership transferred to service.
1612  * The max_streams refers to the MaxStreams= key.
1613  * The max_streams_close_circuit refers to the MaxStreamsCloseCircuit key.
1614  * The auth_type is the authentication type of the clients in auth_clients.
1615  * The ownership of that list is transferred to the service.
1616  *
1617  * On success (RSAE_OKAY), the address_out points to a newly allocated string
1618  * containing the onion address without the .onion part. On error, address_out
1619  * is untouched. */
1621 add_onion_helper_add_service(int hs_version,
1622  add_onion_secret_key_t *pk,
1623  smartlist_t *port_cfgs, int max_streams,
1624  int max_streams_close_circuit, int auth_type,
1625  smartlist_t *auth_clients, char **address_out)
1626 {
1628 
1629  tor_assert(pk);
1630  tor_assert(port_cfgs);
1631  tor_assert(address_out);
1632 
1633  switch (hs_version) {
1634  case HS_VERSION_TWO:
1635  ret = rend_service_add_ephemeral(pk->v2, port_cfgs, max_streams,
1636  max_streams_close_circuit, auth_type,
1637  auth_clients, address_out);
1638  break;
1639  case HS_VERSION_THREE:
1640  ret = hs_service_add_ephemeral(pk->v3, port_cfgs, max_streams,
1641  max_streams_close_circuit, address_out);
1642  break;
1643  default:
1644  tor_assert_unreached();
1645  }
1646 
1647  return ret;
1648 }
1649 
1650 /** The list of onion services that have been added via ADD_ONION that do not
1651  * belong to any particular control connection.
1652  */
1654 
1655 /**
1656  * Return a list of detached onion services, or NULL if none exist.
1657  **/
1658 smartlist_t *
1660 {
1661  return detached_onion_services;
1662 }
1663 
1664 static const char *add_onion_keywords[] = {
1665  "Port", "Flags", "MaxStreams", "ClientAuth", NULL
1666 };
1667 static const control_cmd_syntax_t add_onion_syntax = {
1668  .min_args = 1, .max_args = 1,
1669  .accept_keywords = true,
1670  .allowed_keywords = add_onion_keywords
1671 };
1672 
1673 /** Called when we get a ADD_ONION command; parse the body, and set up
1674  * the new ephemeral Onion Service. */
1675 static int
1677  const control_cmd_args_t *args)
1678 {
1679  /* Parse all of the arguments that do not involve handling cryptographic
1680  * material first, since there's no reason to touch that at all if any of
1681  * the other arguments are malformed.
1682  */
1683  smartlist_t *port_cfgs = smartlist_new();
1684  smartlist_t *auth_clients = NULL;
1685  smartlist_t *auth_created_clients = NULL;
1686  int discard_pk = 0;
1687  int detach = 0;
1688  int max_streams = 0;
1689  int max_streams_close_circuit = 0;
1690  rend_auth_type_t auth_type = REND_NO_AUTH;
1691  int non_anonymous = 0;
1692  const config_line_t *arg;
1693 
1694  for (arg = args->kwargs; arg; arg = arg->next) {
1695  if (!strcasecmp(arg->key, "Port")) {
1696  /* "Port=VIRTPORT[,TARGET]". */
1698  rend_service_parse_port_config(arg->value, ",", NULL);
1699  if (!cfg) {
1700  control_write_endreply(conn, 512, "Invalid VIRTPORT/TARGET");
1701  goto out;
1702  }
1703  smartlist_add(port_cfgs, cfg);
1704  } else if (!strcasecmp(arg->key, "MaxStreams")) {
1705  /* "MaxStreams=[0..65535]". */
1706  int ok = 0;
1707  max_streams = (int)tor_parse_long(arg->value, 10, 0, 65535, &ok, NULL);
1708  if (!ok) {
1709  control_write_endreply(conn, 512, "Invalid MaxStreams");
1710  goto out;
1711  }
1712  } else if (!strcasecmp(arg->key, "Flags")) {
1713  /* "Flags=Flag[,Flag]", where Flag can be:
1714  * * 'DiscardPK' - If tor generates the keypair, do not include it in
1715  * the response.
1716  * * 'Detach' - Do not tie this onion service to any particular control
1717  * connection.
1718  * * 'MaxStreamsCloseCircuit' - Close the circuit if MaxStreams is
1719  * exceeded.
1720  * * 'BasicAuth' - Client authorization using the 'basic' method.
1721  * * 'NonAnonymous' - Add a non-anonymous Single Onion Service. If this
1722  * flag is present, tor must be in non-anonymous
1723  * hidden service mode. If this flag is absent,
1724  * tor must be in anonymous hidden service mode.
1725  */
1726  static const char *discard_flag = "DiscardPK";
1727  static const char *detach_flag = "Detach";
1728  static const char *max_s_close_flag = "MaxStreamsCloseCircuit";
1729  static const char *basicauth_flag = "BasicAuth";
1730  static const char *non_anonymous_flag = "NonAnonymous";
1731 
1732  smartlist_t *flags = smartlist_new();
1733  int bad = 0;
1734 
1735  smartlist_split_string(flags, arg->value, ",", SPLIT_IGNORE_BLANK, 0);
1736  if (smartlist_len(flags) < 1) {
1737  control_write_endreply(conn, 512, "Invalid 'Flags' argument");
1738  bad = 1;
1739  }
1740  SMARTLIST_FOREACH_BEGIN(flags, const char *, flag)
1741  {
1742  if (!strcasecmp(flag, discard_flag)) {
1743  discard_pk = 1;
1744  } else if (!strcasecmp(flag, detach_flag)) {
1745  detach = 1;
1746  } else if (!strcasecmp(flag, max_s_close_flag)) {
1747  max_streams_close_circuit = 1;
1748  } else if (!strcasecmp(flag, basicauth_flag)) {
1749  auth_type = REND_BASIC_AUTH;
1750  } else if (!strcasecmp(flag, non_anonymous_flag)) {
1751  non_anonymous = 1;
1752  } else {
1753  control_printf_endreply(conn, 512, "Invalid 'Flags' argument: %s",
1754  escaped(flag));
1755  bad = 1;
1756  break;
1757  }
1758  } SMARTLIST_FOREACH_END(flag);
1759  SMARTLIST_FOREACH(flags, char *, cp, tor_free(cp));
1760  smartlist_free(flags);
1761  if (bad)
1762  goto out;
1763 
1764  } else if (!strcasecmp(arg->key, "ClientAuth")) {
1765  int created = 0;
1766  rend_authorized_client_t *client =
1767  add_onion_helper_clientauth(arg->value, &created, conn);
1768  if (!client) {
1769  goto out;
1770  }
1771 
1772  if (auth_clients != NULL) {
1773  int bad = 0;
1774  SMARTLIST_FOREACH_BEGIN(auth_clients, rend_authorized_client_t *, ac) {
1775  if (strcmp(ac->client_name, client->client_name) == 0) {
1776  bad = 1;
1777  break;
1778  }
1779  } SMARTLIST_FOREACH_END(ac);
1780  if (bad) {
1781  control_write_endreply(conn, 512, "Duplicate name in ClientAuth");
1782  rend_authorized_client_free(client);
1783  goto out;
1784  }
1785  } else {
1786  auth_clients = smartlist_new();
1787  auth_created_clients = smartlist_new();
1788  }
1789  smartlist_add(auth_clients, client);
1790  if (created) {
1791  smartlist_add(auth_created_clients, client);
1792  }
1793  } else {
1794  tor_assert_nonfatal_unreached();
1795  goto out;
1796  }
1797  }
1798  if (smartlist_len(port_cfgs) == 0) {
1799  control_write_endreply(conn, 512, "Missing 'Port' argument");
1800  goto out;
1801  } else if (auth_type == REND_NO_AUTH && auth_clients != NULL) {
1802  control_write_endreply(conn, 512, "No auth type specified");
1803  goto out;
1804  } else if (auth_type != REND_NO_AUTH && auth_clients == NULL) {
1805  control_write_endreply(conn, 512, "No auth clients specified");
1806  goto out;
1807  } else if ((auth_type == REND_BASIC_AUTH &&
1808  smartlist_len(auth_clients) > 512) ||
1809  (auth_type == REND_STEALTH_AUTH &&
1810  smartlist_len(auth_clients) > 16)) {
1811  control_write_endreply(conn, 512, "Too many auth clients");
1812  goto out;
1813  } else if (non_anonymous != rend_service_non_anonymous_mode_enabled(
1814  get_options())) {
1815  /* If we failed, and the non-anonymous flag is set, Tor must be in
1816  * anonymous hidden service mode.
1817  * The error message changes based on the current Tor config:
1818  * 512 Tor is in anonymous hidden service mode
1819  * 512 Tor is in non-anonymous hidden service mode
1820  * (I've deliberately written them out in full here to aid searchability.)
1821  */
1822  control_printf_endreply(conn, 512,
1823  "Tor is in %sanonymous hidden service " "mode",
1824  non_anonymous ? "" : "non-");
1825  goto out;
1826  }
1827 
1828  /* Parse the "keytype:keyblob" argument. */
1829  int hs_version = 0;
1830  add_onion_secret_key_t pk = { NULL };
1831  const char *key_new_alg = NULL;
1832  char *key_new_blob = NULL;
1833 
1834  const char *onionkey = smartlist_get(args->args, 0);
1835  if (add_onion_helper_keyarg(onionkey, discard_pk,
1836  &key_new_alg, &key_new_blob, &pk, &hs_version,
1837  conn) < 0) {
1838  goto out;
1839  }
1840 
1841  /* Hidden service version 3 don't have client authentication support so if
1842  * ClientAuth was given, send back an error. */
1843  if (hs_version == HS_VERSION_THREE && auth_clients) {
1844  control_write_endreply(conn, 513, "ClientAuth not supported");
1845  goto out;
1846  }
1847 
1848  /* Create the HS, using private key pk, client authentication auth_type,
1849  * the list of auth_clients, and port config port_cfg.
1850  * rend_service_add_ephemeral() will take ownership of pk and port_cfg,
1851  * regardless of success/failure.
1852  */
1853  char *service_id = NULL;
1854  int ret = add_onion_helper_add_service(hs_version, &pk, port_cfgs,
1855  max_streams,
1856  max_streams_close_circuit, auth_type,
1857  auth_clients, &service_id);
1858  port_cfgs = NULL; /* port_cfgs is now owned by the rendservice code. */
1859  auth_clients = NULL; /* so is auth_clients */
1860  switch (ret) {
1861  case RSAE_OKAY:
1862  {
1863  if (detach) {
1867  } else {
1868  if (!conn->ephemeral_onion_services)
1870  smartlist_add(conn->ephemeral_onion_services, service_id);
1871  }
1872 
1873  tor_assert(service_id);
1874  control_printf_midreply(conn, 250, "ServiceID=%s", service_id);
1875  if (key_new_alg) {
1876  tor_assert(key_new_blob);
1877  control_printf_midreply(conn, 250, "PrivateKey=%s:%s",
1878  key_new_alg, key_new_blob);
1879  }
1880  if (auth_created_clients) {
1881  SMARTLIST_FOREACH(auth_created_clients, rend_authorized_client_t *, ac, {
1882  char *encoded = rend_auth_encode_cookie(ac->descriptor_cookie,
1883  auth_type);
1884  tor_assert(encoded);
1885  control_printf_midreply(conn, 250, "ClientAuth=%s:%s",
1886  ac->client_name, encoded);
1887  memwipe(encoded, 0, strlen(encoded));
1888  tor_free(encoded);
1889  });
1890  }
1891 
1892  send_control_done(conn);
1893  break;
1894  }
1895  case RSAE_BADPRIVKEY:
1896  control_write_endreply(conn, 551, "Failed to generate onion address");
1897  break;
1898  case RSAE_ADDREXISTS:
1899  control_write_endreply(conn, 550, "Onion address collision");
1900  break;
1901  case RSAE_BADVIRTPORT:
1902  control_write_endreply(conn, 512, "Invalid VIRTPORT/TARGET");
1903  break;
1904  case RSAE_BADAUTH:
1905  control_write_endreply(conn, 512, "Invalid client authorization");
1906  break;
1907  case RSAE_INTERNAL: /* FALLSTHROUGH */
1908  default:
1909  control_write_endreply(conn, 551, "Failed to add Onion Service");
1910  }
1911  if (key_new_blob) {
1912  memwipe(key_new_blob, 0, strlen(key_new_blob));
1913  tor_free(key_new_blob);
1914  }
1915 
1916  out:
1917  if (port_cfgs) {
1919  rend_service_port_config_free(p));
1920  smartlist_free(port_cfgs);
1921  }
1922 
1923  if (auth_clients) {
1924  SMARTLIST_FOREACH(auth_clients, rend_authorized_client_t *, ac,
1925  rend_authorized_client_free(ac));
1926  smartlist_free(auth_clients);
1927  }
1928  if (auth_created_clients) {
1929  // Do not free entries; they are the same as auth_clients
1930  smartlist_free(auth_created_clients);
1931  }
1932  return 0;
1933 }
1934 
1935 /** Helper function to handle parsing the KeyType:KeyBlob argument to the
1936  * ADD_ONION command. Return a new crypto_pk_t and if a new key was generated
1937  * and the private key not discarded, the algorithm and serialized private key,
1938  * or NULL and an optional control protocol error message on failure. The
1939  * caller is responsible for freeing the returned key_new_blob.
1940  *
1941  * Note: The error messages returned are deliberately vague to avoid echoing
1942  * key material.
1943  *
1944  * Note: conn is only used for writing control replies. For testing
1945  * purposes, it can be NULL if control_write_reply() is appropriately
1946  * mocked.
1947  */
1948 STATIC int
1949 add_onion_helper_keyarg(const char *arg, int discard_pk,
1950  const char **key_new_alg_out, char **key_new_blob_out,
1951  add_onion_secret_key_t *decoded_key, int *hs_version,
1952  control_connection_t *conn)
1953 {
1954  smartlist_t *key_args = smartlist_new();
1955  crypto_pk_t *pk = NULL;
1956  const char *key_new_alg = NULL;
1957  char *key_new_blob = NULL;
1958  int ret = -1;
1959 
1960  smartlist_split_string(key_args, arg, ":", SPLIT_IGNORE_BLANK, 0);
1961  if (smartlist_len(key_args) != 2) {
1962  control_write_endreply(conn, 512, "Invalid key type/blob");
1963  goto err;
1964  }
1965 
1966  /* The format is "KeyType:KeyBlob". */
1967  static const char *key_type_new = "NEW";
1968  static const char *key_type_best = "BEST";
1969  static const char *key_type_rsa1024 = "RSA1024";
1970  static const char *key_type_ed25519_v3 = "ED25519-V3";
1971 
1972  const char *key_type = smartlist_get(key_args, 0);
1973  const char *key_blob = smartlist_get(key_args, 1);
1974 
1975  if (!strcasecmp(key_type_rsa1024, key_type)) {
1976  /* "RSA:<Base64 Blob>" - Loading a pre-existing RSA1024 key. */
1977  pk = crypto_pk_base64_decode_private(key_blob, strlen(key_blob));
1978  if (!pk) {
1979  control_write_endreply(conn, 512, "Failed to decode RSA key");
1980  goto err;
1981  }
1982  if (crypto_pk_num_bits(pk) != PK_BYTES*8) {
1983  crypto_pk_free(pk);
1984  control_write_endreply(conn, 512, "Invalid RSA key size");
1985  goto err;
1986  }
1987  decoded_key->v2 = pk;
1988  *hs_version = HS_VERSION_TWO;
1989  } else if (!strcasecmp(key_type_ed25519_v3, key_type)) {
1990  /* parsing of private ed25519 key */
1991  /* "ED25519-V3:<Base64 Blob>" - Loading a pre-existing ed25519 key. */
1992  ed25519_secret_key_t *sk = tor_malloc_zero(sizeof(*sk));
1993  if (base64_decode((char *) sk->seckey, sizeof(sk->seckey), key_blob,
1994  strlen(key_blob)) != sizeof(sk->seckey)) {
1995  tor_free(sk);
1996  control_write_endreply(conn, 512, "Failed to decode ED25519-V3 key");
1997  goto err;
1998  }
1999  decoded_key->v3 = sk;
2000  *hs_version = HS_VERSION_THREE;
2001  } else if (!strcasecmp(key_type_new, key_type)) {
2002  /* "NEW:<Algorithm>" - Generating a new key, blob as algorithm. */
2003  if (!strcasecmp(key_type_rsa1024, key_blob)) {
2004  /* "RSA1024", RSA 1024 bit, also currently "BEST" by default. */
2005  pk = crypto_pk_new();
2006  if (crypto_pk_generate_key(pk)) {
2007  control_printf_endreply(conn, 551, "Failed to generate %s key",
2008  key_type_rsa1024);
2009  goto err;
2010  }
2011  if (!discard_pk) {
2012  if (crypto_pk_base64_encode_private(pk, &key_new_blob)) {
2013  crypto_pk_free(pk);
2014  control_printf_endreply(conn, 551, "Failed to encode %s key",
2015  key_type_rsa1024);
2016  goto err;
2017  }
2018  key_new_alg = key_type_rsa1024;
2019  }
2020  decoded_key->v2 = pk;
2021  *hs_version = HS_VERSION_TWO;
2022  } else if (!strcasecmp(key_type_ed25519_v3, key_blob) ||
2023  !strcasecmp(key_type_best, key_blob)) {
2024  /* "ED25519-V3", ed25519 key, also currently "BEST" by default. */
2025  ed25519_secret_key_t *sk = tor_malloc_zero(sizeof(*sk));
2026  if (ed25519_secret_key_generate(sk, 1) < 0) {
2027  tor_free(sk);
2028  control_printf_endreply(conn, 551, "Failed to generate %s key",
2029  key_type_ed25519_v3);
2030  goto err;
2031  }
2032  if (!discard_pk) {
2033  ssize_t len = base64_encode_size(sizeof(sk->seckey), 0) + 1;
2034  key_new_blob = tor_malloc_zero(len);
2035  if (base64_encode(key_new_blob, len, (const char *) sk->seckey,
2036  sizeof(sk->seckey), 0) != (len - 1)) {
2037  tor_free(sk);
2038  tor_free(key_new_blob);
2039  control_printf_endreply(conn, 551, "Failed to encode %s key",
2040  key_type_ed25519_v3);
2041  goto err;
2042  }
2043  key_new_alg = key_type_ed25519_v3;
2044  }
2045  decoded_key->v3 = sk;
2046  *hs_version = HS_VERSION_THREE;
2047  } else {
2048  control_write_endreply(conn, 513, "Invalid key type");
2049  goto err;
2050  }
2051  } else {
2052  control_write_endreply(conn, 513, "Invalid key type");
2053  goto err;
2054  }
2055 
2056  /* Succeeded in loading or generating a private key. */
2057  ret = 0;
2058 
2059  err:
2060  SMARTLIST_FOREACH(key_args, char *, cp, {
2061  memwipe(cp, 0, strlen(cp));
2062  tor_free(cp);
2063  });
2064  smartlist_free(key_args);
2065 
2066  *key_new_alg_out = key_new_alg;
2067  *key_new_blob_out = key_new_blob;
2068 
2069  return ret;
2070 }
2071 
2072 /** Helper function to handle parsing a ClientAuth argument to the
2073  * ADD_ONION command. Return a new rend_authorized_client_t, or NULL
2074  * and an optional control protocol error message on failure. The
2075  * caller is responsible for freeing the returned auth_client.
2076  *
2077  * If 'created' is specified, it will be set to 1 when a new cookie has
2078  * been generated.
2079  *
2080  * Note: conn is only used for writing control replies. For testing
2081  * purposes, it can be NULL if control_write_reply() is appropriately
2082  * mocked.
2083  */
2085 add_onion_helper_clientauth(const char *arg, int *created,
2086  control_connection_t *conn)
2087 {
2088  int ok = 0;
2089 
2090  tor_assert(arg);
2091  tor_assert(created);
2092 
2093  smartlist_t *auth_args = smartlist_new();
2094  rend_authorized_client_t *client =
2095  tor_malloc_zero(sizeof(rend_authorized_client_t));
2096  smartlist_split_string(auth_args, arg, ":", 0, 0);
2097  if (smartlist_len(auth_args) < 1 || smartlist_len(auth_args) > 2) {
2098  control_write_endreply(conn, 512, "Invalid ClientAuth syntax");
2099  goto err;
2100  }
2101  client->client_name = tor_strdup(smartlist_get(auth_args, 0));
2102  if (smartlist_len(auth_args) == 2) {
2103  char *decode_err_msg = NULL;
2104  if (rend_auth_decode_cookie(smartlist_get(auth_args, 1),
2105  client->descriptor_cookie,
2106  NULL, &decode_err_msg) < 0) {
2107  tor_assert(decode_err_msg);
2108  control_write_endreply(conn, 512, decode_err_msg);
2109  tor_free(decode_err_msg);
2110  goto err;
2111  }
2112  *created = 0;
2113  } else {
2114  crypto_rand((char *) client->descriptor_cookie, REND_DESC_COOKIE_LEN);
2115  *created = 1;
2116  }
2117 
2118  if (!rend_valid_client_name(client->client_name)) {
2119  control_write_endreply(conn, 512, "Invalid name in ClientAuth");
2120  goto err;
2121  }
2122 
2123  ok = 1;
2124  err:
2125  SMARTLIST_FOREACH(auth_args, char *, item, tor_free(item));
2126  smartlist_free(auth_args);
2127  if (!ok) {
2128  rend_authorized_client_free(client);
2129  client = NULL;
2130  }
2131  return client;
2132 }
2133 
2134 static const control_cmd_syntax_t del_onion_syntax = {
2135  .min_args = 1, .max_args = 1,
2136 };
2137 
2138 /** Called when we get a DEL_ONION command; parse the body, and remove
2139  * the existing ephemeral Onion Service. */
2140 static int
2142  const control_cmd_args_t *cmd_args)
2143 {
2144  int hs_version = 0;
2145  smartlist_t *args = cmd_args->args;
2146  tor_assert(smartlist_len(args) == 1);
2147 
2148  const char *service_id = smartlist_get(args, 0);
2149  if (rend_valid_v2_service_id(service_id)) {
2150  hs_version = HS_VERSION_TWO;
2151  } else if (hs_address_is_valid(service_id)) {
2152  hs_version = HS_VERSION_THREE;
2153  } else {
2154  control_write_endreply(conn, 512, "Malformed Onion Service id");
2155  goto out;
2156  }
2157 
2158  /* Determine if the onion service belongs to this particular control
2159  * connection, or if it is in the global list of detached services. If it
2160  * is in neither, either the service ID is invalid in some way, or it
2161  * explicitly belongs to a different control connection, and an error
2162  * should be returned.
2163  */
2164  smartlist_t *services[2] = {
2167  };
2168  smartlist_t *onion_services = NULL;
2169  int idx = -1;
2170  for (size_t i = 0; i < ARRAY_LENGTH(services); i++) {
2171  idx = smartlist_string_pos(services[i], service_id);
2172  if (idx != -1) {
2173  onion_services = services[i];
2174  break;
2175  }
2176  }
2177  if (onion_services == NULL) {
2178  control_write_endreply(conn, 552, "Unknown Onion Service id");
2179  } else {
2180  int ret = -1;
2181  switch (hs_version) {
2182  case HS_VERSION_TWO:
2183  ret = rend_service_del_ephemeral(service_id);
2184  break;
2185  case HS_VERSION_THREE:
2186  ret = hs_service_del_ephemeral(service_id);
2187  break;
2188  default:
2189  /* The ret value will be -1 thus hitting the warning below. This should
2190  * never happen because of the check at the start of the function. */
2191  break;
2192  }
2193  if (ret < 0) {
2194  /* This should *NEVER* fail, since the service is on either the
2195  * per-control connection list, or the global one.
2196  */
2197  log_warn(LD_BUG, "Failed to remove Onion Service %s.",
2198  escaped(service_id));
2200  }
2201 
2202  /* Remove/scrub the service_id from the appropriate list. */
2203  char *cp = smartlist_get(onion_services, idx);
2204  smartlist_del(onion_services, idx);
2205  memwipe(cp, 0, strlen(cp));
2206  tor_free(cp);
2207 
2208  send_control_done(conn);
2209  }
2210 
2211  out:
2212  return 0;
2213 }
2214 
2215 static const control_cmd_syntax_t obsolete_syntax = {
2216  .max_args = UINT_MAX
2217 };
2218 
2219 /**
2220  * Called when we get an obsolete command: tell the controller that it is
2221  * obsolete.
2222  */
2223 static int
2225  const control_cmd_args_t *args)
2226 {
2227  (void)args;
2228  char *command = tor_strdup(conn->current_cmd);
2230  control_printf_endreply(conn, 511, "%s is obsolete.", command);
2231  tor_free(command);
2232  return 0;
2233 }
2234 
2235 /**
2236  * Function pointer to a handler function for a controller command.
2237  **/
2238 typedef int (*handler_fn_t) (control_connection_t *conn,
2239  const control_cmd_args_t *args);
2240 
2241 /**
2242  * Definition for a controller command.
2243  */
2244 typedef struct control_cmd_def_t {
2245  /**
2246  * The name of the command. If the command is multiline, the name must
2247  * begin with "+". This is not case-sensitive. */
2248  const char *name;
2249  /**
2250  * A function to execute the command.
2251  */
2253  /**
2254  * Zero or more CMD_FL_* flags, or'd together.
2255  */
2256  unsigned flags;
2257  /**
2258  * For parsed command: a syntax description.
2259  */
2262 
2263 /**
2264  * Indicates that the command's arguments are sensitive, and should be
2265  * memwiped after use.
2266  */
2267 #define CMD_FL_WIPE (1u<<0)
2268 
2269 #ifndef COCCI
2270 /** Macro: declare a command with a one-line argument, a given set of flags,
2271  * and a syntax definition.
2272  **/
2273 #define ONE_LINE(name, flags) \
2274  { \
2275  #name, \
2276  handle_control_ ##name, \
2277  flags, \
2278  &name##_syntax, \
2279  }
2280 
2281 /**
2282  * Macro: declare a command with a multi-line argument and a given set of
2283  * flags.
2284  **/
2285 #define MULTLINE(name, flags) \
2286  { "+"#name, \
2287  handle_control_ ##name, \
2288  flags, \
2289  &name##_syntax \
2290  }
2291 
2292 /**
2293  * Macro: declare an obsolete command. (Obsolete commands give a different
2294  * error than non-existent ones.)
2295  **/
2296 #define OBSOLETE(name) \
2297  { #name, \
2298  handle_control_obsolete, \
2299  0, \
2300  &obsolete_syntax, \
2301  }
2302 #endif /* !defined(COCCI) */
2303 
2304 /**
2305  * An array defining all the recognized controller commands.
2306  **/
2308 {
2309  ONE_LINE(setconf, 0),
2310  ONE_LINE(resetconf, 0),
2311  ONE_LINE(getconf, 0),
2312  MULTLINE(loadconf, 0),
2313  ONE_LINE(setevents, 0),
2314  ONE_LINE(authenticate, CMD_FL_WIPE),
2315  ONE_LINE(saveconf, 0),
2316  ONE_LINE(signal, 0),
2317  ONE_LINE(takeownership, 0),
2318  ONE_LINE(dropownership, 0),
2319  ONE_LINE(mapaddress, 0),
2320  ONE_LINE(getinfo, 0),
2321  ONE_LINE(extendcircuit, 0),
2322  ONE_LINE(setcircuitpurpose, 0),
2323  OBSOLETE(setrouterpurpose),
2324  ONE_LINE(attachstream, 0),
2325  MULTLINE(postdescriptor, 0),
2326  ONE_LINE(redirectstream, 0),
2327  ONE_LINE(closestream, 0),
2328  ONE_LINE(closecircuit, 0),
2329  ONE_LINE(usefeature, 0),
2330  ONE_LINE(resolve, 0),
2331  ONE_LINE(protocolinfo, 0),
2332  ONE_LINE(authchallenge, CMD_FL_WIPE),
2333  ONE_LINE(dropguards, 0),
2334  ONE_LINE(hsfetch, 0),
2335  MULTLINE(hspost, 0),
2336  ONE_LINE(add_onion, CMD_FL_WIPE),
2337  ONE_LINE(del_onion, CMD_FL_WIPE),
2338  ONE_LINE(onion_client_auth_add, CMD_FL_WIPE),
2339  ONE_LINE(onion_client_auth_remove, 0),
2340  ONE_LINE(onion_client_auth_view, 0),
2341 };
2342 
2343 /**
2344  * The number of entries in CONTROL_COMMANDS.
2345  **/
2347 
2348 /**
2349  * Run a single control command, as defined by a control_cmd_def_t,
2350  * with a given set of arguments.
2351  */
2352 static int
2354  control_connection_t *conn,
2355  uint32_t cmd_data_len,
2356  char *args)
2357 {
2358  int rv = 0;
2359 
2360  control_cmd_args_t *parsed_args;
2361  char *err=NULL;
2362  tor_assert(def->syntax);
2363  parsed_args = control_cmd_parse_args(conn->current_cmd,
2364  def->syntax,
2365  cmd_data_len, args,
2366  &err);
2367  if (!parsed_args) {
2368  control_printf_endreply(conn, 512, "Bad arguments to %s: %s",
2369  conn->current_cmd, err?err:"");
2370  tor_free(err);
2371  } else {
2372  if (BUG(err))
2373  tor_free(err);
2374  if (def->handler(conn, parsed_args))
2375  rv = 0;
2376 
2377  if (def->flags & CMD_FL_WIPE)
2378  control_cmd_args_wipe(parsed_args);
2379 
2380  control_cmd_args_free(parsed_args);
2381  }
2382 
2383  if (def->flags & CMD_FL_WIPE)
2384  memwipe(args, 0, cmd_data_len);
2385 
2386  return rv;
2387 }
2388 
2389 /**
2390  * Run a given controller command, as selected by the current_cmd field of
2391  * <b>conn</b>.
2392  */
2393 int
2395  uint32_t cmd_data_len,
2396  char *args)
2397 {
2398  tor_assert(conn);
2399  tor_assert(args);
2400  tor_assert(args[cmd_data_len] == '\0');
2401 
2402  for (unsigned i = 0; i < N_CONTROL_COMMANDS; ++i) {
2403  const control_cmd_def_t *def = &CONTROL_COMMANDS[i];
2404  if (!strcasecmp(conn->current_cmd, def->name)) {
2405  return handle_single_control_command(def, conn, cmd_data_len, args);
2406  }
2407  }
2408 
2409  control_printf_endreply(conn, 510, "Unrecognized command \"%s\"",
2410  conn->current_cmd);
2411 
2412  return 0;
2413 }
2414 
2415 void
2416 control_cmd_free_all(void)
2417 {
2418  if (detached_onion_services) { /* Free the detached onion services */
2420  smartlist_free(detached_onion_services);
2421  }
2422 }
#define AP_CONN_STATE_CONNECT_WAIT
Header file for rendcommon.c.
#define CMD_FL_WIPE
Definition: control_cmd.c:2267
origin_circuit_t * circuit_launch(uint8_t purpose, int flags)
Definition: circuituse.c:1938
void crypto_rand(char *to, size_t n)
Definition: crypto_rand.c:477
Header for confline.c.
#define AP_CONN_STATE_RESOLVE_WAIT
config_line_t * option_get_assignment(const or_options_t *options, const char *key)
Definition: config.c:2639
Router descriptor structure.
unsigned int min_args
Definition: control_cmd.h:41
config_line_t * kvline_parse(const char *line, unsigned flags)
Definition: kvline.c:199
static int handle_control_closecircuit(control_connection_t *conn, const control_cmd_args_t *args)
Definition: control_cmd.c:1170
Header file for circuitbuild.c.
int rend_auth_decode_cookie(const char *cookie_in, uint8_t *cookie_out, rend_auth_type_t *auth_type_out, char **err_msg_out)
Definition: rendcommon.c:924
Common functions for using (pseudo-)random number generators.
Definition: node_st.h:34
Header file for control_auth.c.
smartlist_t * get_detached_onion_services(void)
Definition: control_cmd.c:1659
#define SMARTLIST_FOREACH_BEGIN(sl, type, var)
int hs_parse_address(const char *address, ed25519_public_key_t *key_out, uint8_t *checksum_out, uint8_t *version_out)
Definition: hs_common.c:914
#define TO_CONN(c)
Definition: or.h:735
unsigned int have_sent_protocolinfo
int rend_valid_descriptor_id(const char *query)
Definition: rendcommon.c:733
int connection_flush(connection_t *conn)
Definition: connection.c:4355
Header for addressmap.c.
uint64_t tor_parse_uint64(const char *s, int base, uint64_t min, uint64_t max, int *ok, char **next)
Definition: parse_int.c:110
extend_info_t * extend_info_from_node(const node_t *node, int for_direct_connect)
crypt_path_t * circuit_get_cpath_hop(origin_circuit_t *circ, int hopnum)
Definition: circuitlist.c:2076
int circuit_handle_first_hop(origin_circuit_t *circ)
Definition: circuitbuild.c:539
static char * get_authmethods(const or_options_t *options)
Definition: control_cmd.c:1246
static int handle_control_loadconf(control_connection_t *conn, const control_cmd_args_t *args)
Definition: control_cmd.c:337
#define ROUTER_PURPOSE_UNKNOWN
int ed25519_secret_key_generate(ed25519_secret_key_t *seckey_out, int extra_strong)
size_t read_escaped_data(const char *data, size_t len, char **out)
static int handle_control_getconf(control_connection_t *conn, const control_cmd_args_t *args)
Definition: control_cmd.c:286
Header file for connection.c.
unsigned long tor_parse_ulong(const char *s, int base, unsigned long min, unsigned long max, int *ok, char **next)
Definition: parse_int.c:78
origin_circuit_t * origin_circuit_init(uint8_t purpose, int flags)
Definition: circuitbuild.c:453
Header file for nodelist.c.
static int control_setconf_helper(control_connection_t *conn, const control_cmd_args_t *args, int use_defaults)
Definition: control_cmd.c:568
uint8_t state
Definition: circuit_st.h:110
Header file for rendparse.c.
int hs_address_is_valid(const char *address)
Definition: hs_common.c:950
void smartlist_add(smartlist_t *sl, void *element)
void * smartlist_pop_last(smartlist_t *sl)
Node information structure.
size_t base64_encode_size(size_t srclen, int flags)
Definition: binascii.c:166
static bool string_array_contains_keyword(const char **array, const char *kwd)
Definition: control_cmd.c:108
int hs_service_del_ephemeral(const char *address)
Definition: hs_service.c:3601
#define REND_DESC_ID_V2_LEN_BASE32
Definition: or.h:354
static smartlist_t * detached_onion_services
Definition: control_cmd.c:1653
#define TO_CIRCUIT(x)
Definition: or.h:951
static int handle_control_postdescriptor(control_connection_t *conn, const control_cmd_args_t *args)
Definition: control_cmd.c:1026
Header file for config.c.
void tor_strupper(char *s)
Definition: util_string.c:138
static uint8_t circuit_purpose_from_string(const char *string)
Definition: control_cmd.c:703
const or_options_t * get_options(void)
Definition: config.c:926
#define tor_assert(expr)
Definition: util_bug.h:102
Parsed v2 HS descriptor structure.
uint8_t router_purpose_from_string(const char *s)
Definition: routerinfo.c:74
#define STATE_IS_OPEN(s)
Definition: control_cmd.c:64
origin_circuit_t * circuit_get_by_global_id(uint32_t id)
Definition: circuitlist.c:1424
void circuit_set_state(circuit_t *circ, uint8_t state)
Definition: circuitlist.c:542
void send_control_done(control_connection_t *conn)
int circuit_event_status(origin_circuit_t *circ, circuit_status_event_t tp, int reason_code)
Definition: circuitlist.c:498
int strcmpstart(const char *s1, const char *s2)
Definition: util_string.c:206
#define tor_free(p)
Definition: malloc.h:52
Hidden-service authorized client structure.
#define tor_fragile_assert()
Definition: util_bug.h:246
int node_has_preferred_descriptor(const node_t *node, int for_direct_connect)
Definition: nodelist.c:1378
int smartlist_string_pos(const smartlist_t *sl, const char *element)
Definition: smartlist.c:106
const char * name
Definition: config.c:2441
const config_line_t * config_line_find_case(const config_line_t *lines, const char *key)
Definition: confline.c:87
int rend_client_fetch_v2_desc(rend_data_t *query, smartlist_t *hsdirs)
Definition: rendclient.c:675
int circuit_get_cpath_len(origin_circuit_t *circ)
Definition: circuitlist.c:2040
void memwipe(void *mem, uint8_t byte, size_t sz)
Definition: crypto_util.c:55
int crypto_pk_base64_encode_private(const crypto_pk_t *pk, char **priv_out)
Definition: crypto_rsa.c:618
smartlist_t * smartlist_new(void)
static int handle_control_protocolinfo(control_connection_t *conn, const control_cmd_args_t *cmd_args)
Definition: control_cmd.c:1305
#define ONE_LINE(name, flags)
Definition: control_cmd.c:2273
static int handle_control_obsolete(control_connection_t *conn, const control_cmd_args_t *args)
Definition: control_cmd.c:2224
int option_is_recognized(const char *key)
Definition: config.c:2623
static int handle_control_attachstream(control_connection_t *conn, const control_cmd_args_t *args)
Definition: control_cmd.c:932
char * get_controller_cookie_file_name(void)
Definition: control_auth.c:48
#define STATIC
Definition: testsupport.h:32
static entry_connection_t * get_stream(const char *id)
Definition: control_cmd.c:549
static int handle_control_signal(control_connection_t *conn, const control_cmd_args_t *args)
Definition: control_cmd.c:458
Header file for main.c.
rend_auth_type_t
Definition: or.h:402
#define ENTRY_TO_CONN(c)
Definition: or.h:738
Header file for dnsserv.c.
void control_reply_add_str(smartlist_t *reply, int code, const char *s)
Circuit-build-stse structure.
#define PK_BYTES
Definition: crypto_rsa.h:24
#define HS_VERSION_THREE
Definition: hs_common.h:26
#define CIRCUIT_PURPOSE_UNKNOWN
Definition: circuitlist.h:135
int base64_encode(char *dest, size_t destlen, const char *src, size_t srclen, int flags)
Definition: binascii.c:215
int addressmap_register_auto(const char *from, const char *to, time_t expires, addressmap_entry_source_t addrmap_source, const char **msg)
Definition: config.c:4944
int handle_control_command(control_connection_t *conn, uint32_t cmd_data_len, char *args)
Definition: control_cmd.c:2394
Definition for control_cmd_args_t.
rend_data_t * rend_data_client_create(const char *onion_address, const char *desc_id, const char *cookie, rend_auth_type_t auth_type)
Definition: hs_common.c:492
#define OBSOLETE(name)
Definition: control_cmd.c:2296
static bool config_lines_contain_flag(const config_line_t *lines, const char *flag)
Definition: control_cmd.c:241
static int handle_control_mapaddress(control_connection_t *conn, const control_cmd_args_t *args)
Definition: control_cmd.c:635
static int handle_control_closestream(control_connection_t *conn, const control_cmd_args_t *cmd_args)
Definition: control_cmd.c:1129
int base32_decode(char *dest, size_t destlen, const char *src, size_t srclen)
Definition: binascii.c:90
#define CIRCUIT_PURPOSE_CONTROLLER
Definition: circuitlist.h:120
const node_t * node_get_by_hex_id(const char *hex_id, unsigned flags)
Definition: nodelist.c:986
void control_printf_endreply(control_connection_t *conn, int code, const char *fmt,...)
#define MULTLINE(name, flags)
Definition: control_cmd.c:2285
Common functions for cryptographic routines.
crypto_pk_t * crypto_pk_base64_decode_private(const char *str, size_t len)
Definition: crypto_rsa.c:654
#define LD_CONTROL
Definition: log.h:80
int address_is_invalid_destination(const char *address, int client)
Definition: addressmap.c:1077
int CookieAuthentication
uint8_t seckey[ED25519_SECKEY_LEN]
int tor_asprintf(char **strp, const char *fmt,...)
Definition: printf.c:75
static int handle_control_resolve(control_connection_t *conn, const control_cmd_args_t *args)
Definition: control_cmd.c:1200
void control_printf_midreply(control_connection_t *conn, int code, const char *fmt,...)
const struct control_event_t control_event_table[]
void control_update_global_event_mask(void)
#define DIGEST_LEN
Definition: digest_sizes.h:20
Origin circuit structure.
tor_socket_t s
Definition: connection_st.h:93
void smartlist_add_asprintf(struct smartlist_t *sl, const char *pattern,...)
Definition: smartlist.c:36
rend_service_port_config_t * rend_service_parse_port_config(const char *string, const char *sep, char **err_msg_out)
Definition: rendservice.c:419
Master header file for Tor-specific functionality.
static const size_t N_CONTROL_COMMANDS
Definition: control_cmd.c:2346
#define CIRCUIT_STATE_OPEN
Definition: circuitlist.h:32
void control_reply_append_kv(smartlist_t *reply, const char *key, const char *val)
static origin_circuit_t * get_circ(const char *id)
Definition: control_cmd.c:537
Header file for circuitbuild.c.
int hs_control_hspost_command(const char *body, const char *onion_address, const smartlist_t *hsdirs_rs)
Definition: hs_control.c:204
void control_reply_add_one_kv(smartlist_t *reply, int code, int flags, const char *key, const char *val)
static int handle_control_hspost(control_connection_t *conn, const control_cmd_args_t *args)
Definition: control_cmd.c:1516
static int handle_control_resetconf(control_connection_t *conn, const control_cmd_args_t *args)
Definition: control_cmd.c:273
connection_t * connection_get_by_global_id(uint64_t id)
Definition: connection.c:4572
int rend_valid_v2_service_id(const char *query)
Definition: rendcommon.c:719
#define ROUTER_PURPOSE_GENERAL
Entry connection structure.
hs_service_add_ephemeral_status_t
Definition: hs_common.h:142
STATIC rend_authorized_client_t * add_onion_helper_clientauth(const char *arg, int *created, control_connection_t *conn)
Definition: control_cmd.c:2085
crypto_pk_t * crypto_pk_new(void)
STATIC int add_onion_helper_keyarg(const char *arg, int discard_pk, const char **key_new_alg_out, char **key_new_blob_out, add_onion_secret_key_t *decoded_key, int *hs_version, control_connection_t *conn)
Definition: control_cmd.c:1949
setopt_err_t
Definition: config.h:46
Header file for circuituse.c.
int dnsserv_launch_request(const char *name, int reverse, control_connection_t *control_conn)
Definition: dnsserv.c:210
Header file for control_cmd.c.
char * rend_auth_encode_cookie(const uint8_t *cookie_in, rend_auth_type_t auth_type)
Definition: rendcommon.c:888
int rend_service_del_ephemeral(const char *service_id)
Definition: rendservice.c:972
void control_cmd_args_wipe(control_cmd_args_t *args)
Definition: control_cmd.c:87
void smartlist_del(smartlist_t *sl, int idx)
void hs_control_hsfetch_command(const ed25519_public_key_t *onion_identity_pk, const smartlist_t *hsdirs)
Definition: hs_control.c:256
Header file for circuitlist.c.
Header file for rendservice.c.
uint16_t marked_for_close
void control_reply_add_printf(smartlist_t *reply, int code, const char *fmt,...)
void control_write_reply_lines(control_connection_t *conn, smartlist_t *lines)
int rend_valid_client_name(const char *client_name)
Definition: rendcommon.c:751
static int handle_single_control_command(const control_cmd_def_t *def, control_connection_t *conn, uint32_t cmd_data_len, char *args)
Definition: control_cmd.c:2353
const node_t * node_get_by_nickname(const char *nickname, unsigned flags)
Definition: nodelist.c:1013
unsigned int edge_has_sent_end
#define CIRCLAUNCH_NEED_CAPACITY
Definition: circuituse.h:43
unsigned int type
Definition: connection_st.h:50
#define ENTRY_TO_EDGE_CONN(c)
static int handle_control_redirectstream(control_connection_t *conn, const control_cmd_args_t *cmd_args)
Definition: control_cmd.c:1082
static int handle_control_extendcircuit(control_connection_t *conn, const control_cmd_args_t *args)
Definition: control_cmd.c:726
int router_load_single_router(const char *s, uint8_t purpose, int cache, const char **msg)
Definition: routerlist.c:1958
config_line_t * config_lines_dup(const config_line_t *inp)
Definition: confline.c:227
Header file for connection_edge.c.
#define REND_SERVICE_ID_LEN_BASE32
Definition: or.h:331
Header file containing control port event related code.
struct config_line_t * kwargs
static void add_authmethods(smartlist_t *reply)
Definition: control_cmd.c:1288
char * smartlist_join_strings(smartlist_t *sl, const char *join, int terminate, size_t *len_out)
Definition: smartlist.c:279
char * make_path_absolute(const char *fname)
Definition: path.c:261
static int handle_control_dropguards(control_connection_t *conn, const control_cmd_args_t *args)
Definition: control_cmd.c:1380
int circuit_send_next_onion_skin(origin_circuit_t *circ)
Definition: circuitbuild.c:937
int options_save_current(void)
Definition: config.c:7055
hs_service_add_ephemeral_status_t rend_service_add_ephemeral(crypto_pk_t *pk, smartlist_t *ports, int max_streams_per_circuit, int max_streams_close_circuit, rend_auth_type_t auth_type, smartlist_t *auth_clients, char **service_id_out)
Definition: rendservice.c:904
int base64_decode(char *dest, size_t destlen, const char *src, size_t srclen)
Definition: binascii.c:396
#define SMARTLIST_FOREACH(sl, type, var, cmd)
static int handle_control_setevents(control_connection_t *conn, const control_cmd_args_t *args)
Definition: control_cmd.c:385
const char * escaped(const char *s)
Definition: escape.c:126
setopt_err_t options_trial_assign(config_line_t *list, unsigned flags, char **msg)
Definition: config.c:2654
static int handle_control_takeownership(control_connection_t *conn, const control_cmd_args_t *args)
Definition: control_cmd.c:497
hs_service_add_ephemeral_status_t hs_service_add_ephemeral(ed25519_secret_key_t *sk, smartlist_t *ports, int max_streams_per_rdv_circuit, int max_streams_close_circuit, char **address_out)
Definition: hs_service.c:3527
cpath_build_state_t * build_state
int(* handler_fn_t)(control_connection_t *conn, const control_cmd_args_t *args)
Definition: control_cmd.c:2238
#define HS_VERSION_TWO
Definition: hs_common.h:24
static int handle_control_setcircuitpurpose(control_connection_t *conn, const control_cmd_args_t *args)
Definition: control_cmd.c:887
const char * option_get_canonical_name(const char *key)
Definition: config.c:2631
void control_write_endreply(control_connection_t *conn, int code, const char *s)
#define ARRAY_LENGTH(x)
static int handle_control_del_onion(control_connection_t *conn, const control_cmd_args_t *cmd_args)
Definition: control_cmd.c:2141
const control_cmd_syntax_t * syntax
Definition: control_cmd.c:2260
int rend_get_service_id(crypto_pk_t *pk, char *out)
Definition: rendcommon.c:706
#define CIRCUIT_STATE_GUARD_WAIT
Definition: circuitlist.h:30
struct smartlist_t * args
#define CIRCUIT_STATE_BUILDING
Definition: circuitlist.h:21
#define AP_CONN_STATE_CONTROLLER_WAIT
Header for kvline.c.
Controller connection structure.
static int handle_control_add_onion(control_connection_t *conn, const control_cmd_args_t *args)
Definition: control_cmd.c:1676
int connection_edge_end(edge_connection_t *conn, uint8_t reason)
Header file for control.c.
const char * name
Definition: control_cmd.c:2248
edge_connection_t * p_streams
#define CIRCUIT_PURPOSE_C_GENERAL
Definition: circuitlist.h:72
unsigned int max_args
Definition: control_cmd.h:46
static int kvline_check_keyword_args(const control_cmd_args_t *result, const control_cmd_syntax_t *syntax, char **error_out)
Definition: control_cmd.c:124
const char ** allowed_keywords
Definition: control_cmd.h:58
Header for confmgt.c.
static char * get_esc_cfile(const or_options_t *options)
Definition: control_cmd.c:1271
void control_cmd_args_free_(control_cmd_args_t *args)
Definition: control_cmd.c:70
long tor_parse_long(const char *s, int base, long min, long max, int *ok, char **next)
Definition: parse_int.c:59
tor_cmdline_mode_t command
Definition: config.c:2445
Client request structure.
Header file for control_proto.c.
int connection_ap_handshake_rewrite_and_attach(entry_connection_t *conn, origin_circuit_t *circ, crypt_path_t *cpath)
void circuit_change_purpose(circuit_t *circ, uint8_t new_purpose)
Definition: circuituse.c:3095
static int address_is_invalid_mapaddress_target(const char *addr)
Definition: control_cmd.c:617
static const control_cmd_def_t CONTROL_COMMANDS[]
Definition: control_cmd.c:2307
unsigned int is_owning_control_connection
circuit_t * circuit_get_by_edge_conn(edge_connection_t *conn)
Definition: circuitlist.c:1577
int rend_parse_v2_service_descriptor(rend_service_descriptor_t **parsed_out, char *desc_id_out, char **intro_points_encrypted_out, size_t *intro_points_encrypted_size_out, size_t *encoded_size_out, const char **next_out, const char *desc, int as_hsdir)
Definition: rendparse.c:72
char * esc_for_log(const char *s)
Definition: escape.c:30
void circuit_detach_stream(circuit_t *circ, edge_connection_t *conn)
Definition: circuituse.c:1388
char address[MAX_SOCKS_ADDR_LEN]
static int handle_control_usefeature(control_connection_t *conn, const control_cmd_args_t *cmd_args)
Definition: control_cmd.c:1349
int circuit_append_new_exit(origin_circuit_t *circ, extend_info_t *exit_ei)
int crypto_pk_num_bits(crypto_pk_t *env)
#define CAL_CLEAR_FIRST
Definition: confmgt.h:59
handler_fn_t handler
Definition: control_cmd.c:2252
STATIC control_cmd_args_t * control_cmd_parse_args(const char *command, const control_cmd_syntax_t *syntax, size_t body_len, const char *body, char **error_out)
Definition: control_cmd.c:159
setopt_err_t options_init_from_string(const char *cf_defaults, const char *cf, int command, const char *command_arg, char **msg)
Definition: config.c:4774
static int handle_control_setconf(control_connection_t *conn, const control_cmd_args_t *args)
Definition: control_cmd.c:257
#define CONN_TYPE_AP
Definition: connection.h:49
struct config_line_t * HashedControlSessionPassword
smartlist_t * ephemeral_onion_services
Header file for routerinfo.c.
Header file for rendclient.c.
socks_request_t * socks_request
Header file for control_events.c.
static int handle_control_hsfetch(control_connection_t *conn, const control_cmd_args_t *args)
Definition: control_cmd.c:1410
static int handle_control_dropownership(control_connection_t *conn, const control_cmd_args_t *args)
Definition: control_cmd.c:520
#define REND_DESC_COOKIE_LEN
Definition: or.h:366
const char * addressmap_register_virtual_address(int type, char *new_address)
Definition: addressmap.c:995
static int handle_control_saveconf(control_connection_t *conn, const control_cmd_args_t *args)
Definition: control_cmd.c:435
int strcasecmpstart(const char *s1, const char *s2)
Definition: util_string.c:216
#define control_reply_free(r)
Free and null a smartlist of control_reply_line_t.
static crypto_pk_t * onionkey
Definition: router.c:101
void remove_all_entry_guards(void)
Definition: entrynodes.c:3682
struct config_line_t * HashedControlPassword
int control_event_address_mapped(const char *from, const char *to, time_t expires, const char *error, const int cached)
#define CAL_USE_DEFAULTS
Definition: confmgt.h:50
#define LD_BUG
Definition: log.h:86
void control_reply_add_done(smartlist_t *reply)
Header file for routerlist.c.
void directory_post_to_hs_dir(rend_service_descriptor_t *renddesc, smartlist_t *descs, smartlist_t *hs_dirs, const char *service_id, int seconds_valid)
Definition: rendservice.c:3671
Encoded v2 HS descriptor structure.
int smartlist_split_string(smartlist_t *sl, const char *str, const char *sep, int flags, int max)