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