tor

The Tor anonymity network
git clone https://git.dasho.dev/tor.git
Log | Files | Refs | README | LICENSE

control_cmd.c (72189B)


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