control_cmd.c 75.1 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
 * Copyright (c) 2007-2019, The Tor Project, Inc. */
/* See LICENSE for licensing information */

/**
 * \file control_cmd.c
 * \brief Implement various commands for Tor's control-socket interface.
 **/

#define CONTROL_MODULE_PRIVATE
#define CONTROL_CMD_PRIVATE
#define CONTROL_EVENTS_PRIVATE

#include "core/or/or.h"
#include "app/config/config.h"
16
#include "lib/confmgt/confparse.h"
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include "app/main/main.h"
#include "core/mainloop/connection.h"
#include "core/or/circuitbuild.h"
#include "core/or/circuitlist.h"
#include "core/or/circuituse.h"
#include "core/or/connection_edge.h"
#include "feature/client/addressmap.h"
#include "feature/client/dnsserv.h"
#include "feature/client/entrynodes.h"
#include "feature/control/control.h"
#include "feature/control/control_auth.h"
#include "feature/control/control_cmd.h"
#include "feature/control/control_events.h"
#include "feature/control/control_getinfo.h"
31
#include "feature/control/control_proto.h"
32
33
34
35
36
37
38
39
40
41
42
#include "feature/hs/hs_control.h"
#include "feature/nodelist/nodelist.h"
#include "feature/nodelist/routerinfo.h"
#include "feature/nodelist/routerlist.h"
#include "feature/rend/rendclient.h"
#include "feature/rend/rendcommon.h"
#include "feature/rend/rendparse.h"
#include "feature/rend/rendservice.h"
#include "lib/crypt_ops/crypto_rand.h"
#include "lib/crypt_ops/crypto_util.h"
#include "lib/encoding/confline.h"
43
#include "lib/encoding/kvline.h"
44
45
46
47
48

#include "core/or/cpath_build_state_st.h"
#include "core/or/entry_connection_st.h"
#include "core/or/origin_circuit_st.h"
#include "core/or/socks_request_st.h"
49
#include "feature/control/control_cmd_args_st.h"
50
51
52
53
54
55
56
#include "feature/control/control_connection_st.h"
#include "feature/nodelist/node_st.h"
#include "feature/nodelist/routerinfo_st.h"
#include "feature/rend/rend_authorized_client_st.h"
#include "feature/rend/rend_encoded_v2_service_descriptor_st.h"
#include "feature/rend/rend_service_descriptor_st.h"

57
58
static int control_setconf_helper(control_connection_t *conn,
                                  const control_cmd_args_t *args,
59
60
61
62
63
64
                                  int use_defaults);

/** Yield true iff <b>s</b> is the state of a control_connection_t that has
 * finished authentication and is accepting commands. */
#define STATE_IS_OPEN(s) ((s) == CONTROL_CONN_STATE_OPEN)

65
66
67
68
69
70
71
72
73
74
75
76
77
/**
 * Release all storage held in <b>args</b>
 **/
void
control_cmd_args_free_(control_cmd_args_t *args)
{
  if (! args)
    return;

  if (args->args) {
    SMARTLIST_FOREACH(args->args, char *, c, tor_free(c));
    smartlist_free(args->args);
  }
78
  config_free_lines(args->kwargs);
79
  tor_free(args->cmddata);
80
81
82
83

  tor_free(args);
}

84
85
86
87
88
89
90
91
92
93
94
95
96
97
/** Erase all memory held in <b>args</b>. */
void
control_cmd_args_wipe(control_cmd_args_t *args)
{
  if (!args)
    return;

  if (args->args) {
    SMARTLIST_FOREACH(args->args, char *, c, memwipe(c, 0, strlen(c)));
  }
  for (config_line_t *line = args->kwargs; line; line = line->next) {
    memwipe(line->key, 0, strlen(line->key));
    memwipe(line->value, 0, strlen(line->value));
  }
98
99
  if (args->cmddata)
    memwipe(args->cmddata, 0, args->cmddata_len);
100
101
}

102
103
104
105
106
107
108
109
110
111
112
113
114
115
/**
 * Return true iff any element of the NULL-terminated <b>array</b> matches
 * <b>kwd</b>. Case-insensitive.
 **/
static bool
string_array_contains_keyword(const char **array, const char *kwd)
{
  for (unsigned i = 0; array[i]; ++i) {
    if (! strcasecmp(array[i], kwd))
      return true;
  }
  return false;
}

116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
/** Helper for argument parsing: check whether the keyword arguments just
 * parsed in <b>result</b> were well-formed according to <b>syntax</b>.
 *
 * On success, return 0.  On failure, return -1 and set *<b>error_out</b>
 * to a newly allocated error string.
 **/
static int
kvline_check_keyword_args(const control_cmd_args_t *result,
                          const control_cmd_syntax_t *syntax,
                          char **error_out)
{
  if (result->kwargs == NULL) {
    tor_asprintf(error_out, "Cannot parse keyword argument(s)");
    return -1;
  }

  if (! syntax->allowed_keywords) {
    /* All keywords are permitted. */
    return 0;
  }

  /* Check for unpermitted arguments */
  const config_line_t *line;
  for (line = result->kwargs; line; line = line->next) {
    if (! string_array_contains_keyword(syntax->allowed_keywords,
                                        line->key)) {
      tor_asprintf(error_out, "Unrecognized keyword argument %s",
                   escaped(line->key));
      return -1;
    }
  }

  return 0;
}

151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
/**
 * Helper: parse the arguments to a command according to <b>syntax</b>.  On
 * success, set *<b>error_out</b> to NULL and return a newly allocated
 * control_cmd_args_t.  On failure, set *<b>error_out</b> to newly allocated
 * error string, and return NULL.
 **/
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)
{
  *error_out = NULL;
  control_cmd_args_t *result = tor_malloc_zero(sizeof(control_cmd_args_t));
  const char *cmdline;
  char *cmdline_alloc = NULL;
168
  tor_assert(syntax->max_args < INT_MAX || syntax->max_args == UINT_MAX);
169
170
171

  result->command = command;

172
173
174
175
176
  if (syntax->store_raw_body) {
    tor_assert(body[body_len] == 0);
    result->raw_body = body;
  }

177
  const char *eol = memchr(body, '\n', body_len);
178
  if (syntax->want_cmddata) {
179
180
181
182
183
184
185
    if (! eol || (eol+1) == body+body_len) {
      *error_out = tor_strdup("Empty body");
      goto err;
    }
    cmdline_alloc = tor_memdup_nulterm(body, eol-body);
    cmdline = cmdline_alloc;
    ++eol;
186
187
    result->cmddata_len = read_escaped_data(eol, (body+body_len)-eol,
                                           &result->cmddata);
188
189
190
191
192
193
194
195
196
197
  } else {
    if (eol && (eol+1) != body+body_len) {
      *error_out = tor_strdup("Unexpected body");
      goto err;
    }
    cmdline = body;
  }

  result->args = smartlist_new();
  smartlist_split_string(result->args, cmdline, " ",
198
199
                         SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK,
                         (int)(syntax->max_args+1));
200
201
202
203
204
  size_t n_args = smartlist_len(result->args);
  if (n_args < syntax->min_args) {
    tor_asprintf(error_out, "Need at least %u argument(s)",
                 syntax->min_args);
    goto err;
205
  } else if (n_args > syntax->max_args && ! syntax->accept_keywords) {
206
207
208
209
210
    tor_asprintf(error_out, "Cannot accept more than %u argument(s)",
                 syntax->max_args);
    goto err;
  }

211
  if (n_args > syntax->max_args) {
212
213
214
    /* We have extra arguments after the positional arguments, and we didn't
       treat them as an error, so they must count as keyword arguments: Either
       K=V pairs, or flags, or both. */
215
216
217
218
219
    tor_assert(n_args == syntax->max_args + 1);
    tor_assert(syntax->accept_keywords);
    char *remainder = smartlist_pop_last(result->args);
    result->kwargs = kvline_parse(remainder, syntax->kvline_flags);
    tor_free(remainder);
220
    if (kvline_check_keyword_args(result, syntax, error_out) < 0) {
221
222
223
224
      goto err;
    }
  }

225
226
227
228
229
230
231
232
233
234
  tor_assert_nonfatal(*error_out == NULL);
  goto done;
 err:
  tor_assert_nonfatal(*error_out != NULL);
  control_cmd_args_free(result);
 done:
  tor_free(cmdline_alloc);
  return result;
}

235
236
237
238
239
240
241
242
243
244
245
/**
 * Return true iff <b>lines</b> contains <b>flags</b> as a no-value
 * (keyword-only) entry.
 **/
static bool
config_lines_contain_flag(const config_line_t *lines, const char *flag)
{
  const config_line_t *line = config_line_find_case(lines, flag);
  return line && !strcmp(line->value, "");
}

246
247
248
249
250
251
static const control_cmd_syntax_t setconf_syntax = {
  .max_args=0,
  .accept_keywords=true,
  .kvline_flags=KV_OMIT_VALS|KV_QUOTED,
};

252
253
254
255
/** Called when we receive a SETCONF message: parse the body and try
 * to update our configuration.  Reply with a DONE or ERROR message.
 * Modifies the contents of body.*/
static int
256
257
handle_control_setconf(control_connection_t *conn,
                       const control_cmd_args_t *args)
258
{
259
  return control_setconf_helper(conn, args, 0);
260
261
}

262
263
264
265
266
267
static const control_cmd_syntax_t resetconf_syntax = {
  .max_args=0,
  .accept_keywords=true,
  .kvline_flags=KV_OMIT_VALS|KV_QUOTED,
};

268
269
270
271
/** Called when we receive a RESETCONF message: parse the body and try
 * to update our configuration.  Reply with a DONE or ERROR message.
 * Modifies the contents of body. */
static int
272
273
handle_control_resetconf(control_connection_t *conn,
                         const control_cmd_args_t *args)
274
{
275
  return control_setconf_helper(conn, args, 1);
276
277
}

278
279
280
281
static const control_cmd_syntax_t getconf_syntax = {
  .max_args=UINT_MAX
};

282
283
284
/** Called when we receive a GETCONF message.  Parse the request, and
 * reply with a CONFVALUE or an ERROR message */
static int
285
286
handle_control_getconf(control_connection_t *conn,
                       const control_cmd_args_t *args)
287
{
288
  const smartlist_t *questions = args->args;
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
  smartlist_t *answers = smartlist_new();
  smartlist_t *unrecognized = smartlist_new();
  char *msg = NULL;
  size_t msg_len;
  const or_options_t *options = get_options();
  int i, len;

  SMARTLIST_FOREACH_BEGIN(questions, const char *, q) {
    if (!option_is_recognized(q)) {
      smartlist_add(unrecognized, (char*) q);
    } else {
      config_line_t *answer = option_get_assignment(options,q);
      if (!answer) {
        const char *name = option_get_canonical_name(q);
        smartlist_add_asprintf(answers, "250-%s\r\n", name);
      }

      while (answer) {
        config_line_t *next;
        smartlist_add_asprintf(answers, "250-%s=%s\r\n",
                     answer->key, answer->value);

        next = answer->next;
        tor_free(answer->key);
        tor_free(answer->value);
        tor_free(answer);
        answer = next;
      }
    }
  } SMARTLIST_FOREACH_END(q);

  if ((len = smartlist_len(unrecognized))) {
    for (i=0; i < len-1; ++i)
322
      control_printf_midreply(conn, 552,
323
324
                              "Unrecognized configuration key \"%s\"",
                              (char*)smartlist_get(unrecognized, i));
325
    control_printf_endreply(conn, 552,
326
327
                            "Unrecognized configuration key \"%s\"",
                            (char*)smartlist_get(unrecognized, len-1));
328
329
330
331
332
333
334
  } else if ((len = smartlist_len(answers))) {
    char *tmp = smartlist_get(answers, len-1);
    tor_assert(strlen(tmp)>4);
    tmp[3] = ' ';
    msg = smartlist_join_strings(answers, "", 0, &msg_len);
    connection_buf_add(msg, msg_len, TO_CONN(conn));
  } else {
335
    send_control_done(conn);
336
337
338
339
340
341
342
343
344
345
346
  }

  SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
  smartlist_free(answers);
  smartlist_free(unrecognized);

  tor_free(msg);

  return 0;
}

347
static const control_cmd_syntax_t loadconf_syntax = {
348
  .want_cmddata = true
349
350
};

351
352
/** Called when we get a +LOADCONF message. */
static int
353
354
handle_control_loadconf(control_connection_t *conn,
                        const control_cmd_args_t *args)
355
356
357
358
{
  setopt_err_t retval;
  char *errstring = NULL;

359
  retval = options_init_from_string(NULL, args->cmddata,
360
                                    CMD_RUN_TOR, NULL, &errstring);
361
362
363
364
365
366

  if (retval != SETOPT_OK)
    log_warn(LD_CONTROL,
             "Controller gave us config file that didn't validate: %s",
             errstring);

Taylor Yu's avatar
Taylor Yu committed
367
368
369
370
#define SEND_ERRMSG(code, msg)                          \
  control_printf_endreply(conn, code, msg "%s%s",       \
                          errstring ? ": " : "",        \
                          errstring ? errstring : "")
371
372
  switch (retval) {
  case SETOPT_ERR_PARSE:
Taylor Yu's avatar
Taylor Yu committed
373
    SEND_ERRMSG(552, "Invalid config file");
374
375
    break;
  case SETOPT_ERR_TRANSITION:
Taylor Yu's avatar
Taylor Yu committed
376
    SEND_ERRMSG(553, "Transition not allowed");
377
378
    break;
  case SETOPT_ERR_SETTING:
Taylor Yu's avatar
Taylor Yu committed
379
    SEND_ERRMSG(553, "Unable to set option");
380
381
382
    break;
  case SETOPT_ERR_MISC:
  default:
Taylor Yu's avatar
Taylor Yu committed
383
    SEND_ERRMSG(550, "Unable to load config");
384
385
386
    break;
  case SETOPT_OK:
    send_control_done(conn);
Taylor Yu's avatar
Taylor Yu committed
387
    break;
388
  }
Taylor Yu's avatar
Taylor Yu committed
389
#undef SEND_ERRMSG
390
391
392
393
  tor_free(errstring);
  return 0;
}

394
395
396
397
static const control_cmd_syntax_t setevents_syntax = {
  .max_args = UINT_MAX
};

398
399
400
/** Called when we get a SETEVENTS message: update conn->event_mask,
 * and reply with DONE or ERROR. */
static int
401
402
handle_control_setevents(control_connection_t *conn,
                         const control_cmd_args_t *args)
403
404
405
{
  int event_code;
  event_mask_t event_mask = 0;
406
  const smartlist_t *events = args->args;
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426

  SMARTLIST_FOREACH_BEGIN(events, const char *, ev)
    {
      if (!strcasecmp(ev, "EXTENDED") ||
          !strcasecmp(ev, "AUTHDIR_NEWDESCS")) {
        log_warn(LD_CONTROL, "The \"%s\" SETEVENTS argument is no longer "
                 "supported.", ev);
        continue;
      } else {
        int i;
        event_code = -1;

        for (i = 0; control_event_table[i].event_name != NULL; ++i) {
          if (!strcasecmp(ev, control_event_table[i].event_name)) {
            event_code = control_event_table[i].event_code;
            break;
          }
        }

        if (event_code == -1) {
427
          control_printf_endreply(conn, 552, "Unrecognized event \"%s\"", ev);
428
429
430
431
432
433
434
435
436
437
438
439
440
441
          return 0;
        }
      }
      event_mask |= (((event_mask_t)1) << event_code);
    }
  SMARTLIST_FOREACH_END(ev);

  conn->event_mask = event_mask;

  control_update_global_event_mask();
  send_control_done(conn);
  return 0;
}

442
443
444
445
446
447
static const control_cmd_syntax_t saveconf_syntax = {
  .max_args = 0,
  .accept_keywords = true,
  .kvline_flags=KV_OMIT_VALS,
};

448
449
450
/** Called when we get a SAVECONF command. Try to flush the current options to
 * disk, and report success or failure. */
static int
451
452
handle_control_saveconf(control_connection_t *conn,
                        const control_cmd_args_t *args)
453
{
454
  bool force = config_lines_contain_flag(args->kwargs, "FORCE");
455
456
  const or_options_t *options = get_options();
  if ((!force && options->IncludeUsed) || options_save_current() < 0) {
457
458
    control_write_endreply(conn, 551,
                           "Unable to write configuration to disk.");
459
460
461
462
463
464
  } else {
    send_control_done(conn);
  }
  return 0;
}

465
466
467
468
469
static const control_cmd_syntax_t signal_syntax = {
  .min_args = 1,
  .max_args = 1,
};

470
471
472
473
/** Called when we get a SIGNAL command. React to the provided signal, and
 * report success or failure. (If the signal results in a shutdown, success
 * may not be reported.) */
static int
474
475
handle_control_signal(control_connection_t *conn,
                      const control_cmd_args_t *args)
476
477
478
479
{
  int sig = -1;
  int i;

480
481
  tor_assert(smartlist_len(args->args) == 1);
  const char *s = smartlist_get(args->args, 0);
482
483
484
485
486
487
488
489
490

  for (i = 0; signal_table[i].signal_name != NULL; ++i) {
    if (!strcasecmp(s, signal_table[i].signal_name)) {
      sig = signal_table[i].sig;
      break;
    }
  }

  if (sig < 0)
491
    control_printf_endreply(conn, 552, "Unrecognized signal code \"%s\"", s);
492
493
494
495
496
497
498
499
500
501
502
503
504
  if (sig < 0)
    return 0;

  send_control_done(conn);
  /* Flush the "done" first if the signal might make us shut down. */
  if (sig == SIGTERM || sig == SIGINT)
    connection_flush(TO_CONN(conn));

  activate_signal(sig);

  return 0;
}

505
506
507
508
static const control_cmd_syntax_t takeownership_syntax = {
  .max_args = UINT_MAX, // This should probably become zero. XXXXX
};

509
510
511
512
/** Called when we get a TAKEOWNERSHIP command.  Mark this connection
 * as an owning connection, so that we will exit if the connection
 * closes. */
static int
513
514
handle_control_takeownership(control_connection_t *conn,
                             const control_cmd_args_t *args)
515
{
516
  (void)args;
517
518
519
520
521
522
523
524
525
526
527

  conn->is_owning_control_connection = 1;

  log_info(LD_CONTROL, "Control connection %d has taken ownership of this "
           "Tor instance.",
           (int)(conn->base_.s));

  send_control_done(conn);
  return 0;
}

528
529
530
531
static const control_cmd_syntax_t dropownership_syntax = {
  .max_args = UINT_MAX, // This should probably become zero. XXXXX
};

532
533
534
535
/** Called when we get a DROPOWNERSHIP command.  Mark this connection
 * as a non-owning connection, so that we will not exit if the connection
 * closes. */
static int
536
537
handle_control_dropownership(control_connection_t *conn,
                             const control_cmd_args_t *args)
538
{
539
  (void)args;
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583

  conn->is_owning_control_connection = 0;

  log_info(LD_CONTROL, "Control connection %d has dropped ownership of this "
           "Tor instance.",
           (int)(conn->base_.s));

  send_control_done(conn);
  return 0;
}

/** Given a text circuit <b>id</b>, return the corresponding circuit. */
static origin_circuit_t *
get_circ(const char *id)
{
  uint32_t n_id;
  int ok;
  n_id = (uint32_t) tor_parse_ulong(id, 10, 0, UINT32_MAX, &ok, NULL);
  if (!ok)
    return NULL;
  return circuit_get_by_global_id(n_id);
}

/** Given a text stream <b>id</b>, return the corresponding AP connection. */
static entry_connection_t *
get_stream(const char *id)
{
  uint64_t n_id;
  int ok;
  connection_t *conn;
  n_id = tor_parse_uint64(id, 10, 0, UINT64_MAX, &ok, NULL);
  if (!ok)
    return NULL;
  conn = connection_get_by_global_id(n_id);
  if (!conn || conn->type != CONN_TYPE_AP || conn->marked_for_close)
    return NULL;
  return TO_ENTRY_CONN(conn);
}

/** Helper for setconf and resetconf. Acts like setconf, except
 * it passes <b>use_defaults</b> on to options_trial_assign().  Modifies the
 * contents of body.
 */
static int
584
585
control_setconf_helper(control_connection_t *conn,
                       const control_cmd_args_t *args,
586
587
588
589
590
591
592
                       int use_defaults)
{
  setopt_err_t opt_err;
  char *errstring = NULL;
  const unsigned flags =
    CAL_CLEAR_FIRST | (use_defaults ? CAL_USE_DEFAULTS : 0);

593
594
  // We need a copy here, since confparse.c wants to canonicalize cases.
  config_line_t *lines = config_lines_dup(args->kwargs);
595
596
597

  opt_err = options_trial_assign(lines, flags, &errstring);
  {
Taylor Yu's avatar
Taylor Yu committed
598
599
600
#define SEND_ERRMSG(code, msg)                                  \
    control_printf_endreply(conn, code, msg ": %s", errstring);

601
602
    switch (opt_err) {
      case SETOPT_ERR_MISC:
Taylor Yu's avatar
Taylor Yu committed
603
        SEND_ERRMSG(552, "Unrecognized option");
604
605
        break;
      case SETOPT_ERR_PARSE:
Taylor Yu's avatar
Taylor Yu committed
606
        SEND_ERRMSG(513, "Unacceptable option value");
607
608
        break;
      case SETOPT_ERR_TRANSITION:
Taylor Yu's avatar
Taylor Yu committed
609
        SEND_ERRMSG(553, "Transition not allowed");
610
611
612
        break;
      case SETOPT_ERR_SETTING:
      default:
Taylor Yu's avatar
Taylor Yu committed
613
        SEND_ERRMSG(553, "Unable to set option");
614
615
616
617
618
619
        break;
      case SETOPT_OK:
        config_free_lines(lines);
        send_control_done(conn);
        return 0;
    }
Taylor Yu's avatar
Taylor Yu committed
620
#undef SEND_ERRMSG
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
    log_warn(LD_CONTROL,
             "Controller gave us config lines that didn't validate: %s",
             errstring);
    config_free_lines(lines);
    tor_free(errstring);
    return 0;
  }
}

/** Return true iff <b>addr</b> is unusable as a mapaddress target because of
 * containing funny characters. */
static int
address_is_invalid_mapaddress_target(const char *addr)
{
  if (!strcmpstart(addr, "*."))
    return address_is_invalid_destination(addr+2, 1);
  else
    return address_is_invalid_destination(addr, 1);
}

641
static const control_cmd_syntax_t mapaddress_syntax = {
642
643
644
  // no positional arguments are expected
  .max_args=0,
  // an arbitrary number of K=V entries are supported.
645
646
647
  .accept_keywords=true,
};

648
649
650
/** Called when we get a MAPADDRESS command; try to bind all listed addresses,
 * and report success or failure. */
static int
651
652
handle_control_mapaddress(control_connection_t *conn,
                          const control_cmd_args_t *args)
653
654
655
656
657
658
{
  smartlist_t *reply;
  char *r;
  size_t sz;

  reply = smartlist_new();
659
660
661
662
663
  const config_line_t *line;
  for (line = args->kwargs; line; line = line->next) {
    const char *from = line->key;
    const char *to = line->value;
    {
664
665
666
667
668
669
670
671
672
673
674
675
676
677
      if (address_is_invalid_mapaddress_target(to)) {
        smartlist_add_asprintf(reply,
                     "512-syntax error: invalid address '%s'", to);
        log_warn(LD_CONTROL,
                 "Skipping invalid argument '%s' in MapAddress msg", to);
      } else if (!strcmp(from, ".") || !strcmp(from, "0.0.0.0") ||
                 !strcmp(from, "::")) {
        const char type =
          !strcmp(from,".") ? RESOLVED_TYPE_HOSTNAME :
          (!strcmp(from, "0.0.0.0") ? RESOLVED_TYPE_IPV4 : RESOLVED_TYPE_IPV6);
        const char *address = addressmap_register_virtual_address(
                                                     type, tor_strdup(to));
        if (!address) {
          smartlist_add_asprintf(reply,
678
                   "451-resource exhausted: skipping '%s=%s'", from,to);
679
680
          log_warn(LD_CONTROL,
                   "Unable to allocate address for '%s' in MapAddress msg",
681
                   safe_str_client(to));
682
683
684
685
686
687
688
689
690
        } else {
          smartlist_add_asprintf(reply, "250-%s=%s", address, to);
        }
      } else {
        const char *msg;
        if (addressmap_register_auto(from, to, 1,
                                     ADDRMAPSRC_CONTROLLER, &msg) < 0) {
          smartlist_add_asprintf(reply,
                                 "512-syntax error: invalid address mapping "
691
                                 " '%s=%s': %s", from, to, msg);
692
          log_warn(LD_CONTROL,
693
694
                   "Skipping invalid argument '%s=%s' in MapAddress msg: %s",
                   from, to, msg);
695
        } else {
696
          smartlist_add_asprintf(reply, "250-%s=%s", from, to);
697
698
699
        }
      }
    }
700
  }
701
702
703
704
705
706
707

  if (smartlist_len(reply)) {
    ((char*)smartlist_get(reply,smartlist_len(reply)-1))[3] = ' ';
    r = smartlist_join_strings(reply, "\r\n", 1, &sz);
    connection_buf_add(r, sz, TO_CONN(conn));
    tor_free(r);
  } else {
708
709
    control_write_endreply(conn, 512, "syntax error: "
                           "not enough arguments to mapaddress.");
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
  }

  SMARTLIST_FOREACH(reply, char *, cp, tor_free(cp));
  smartlist_free(reply);
  return 0;
}

/** Given a string, convert it to a circuit purpose. */
static uint8_t
circuit_purpose_from_string(const char *string)
{
  if (!strcasecmpstart(string, "purpose="))
    string += strlen("purpose=");

  if (!strcasecmp(string, "general"))
    return CIRCUIT_PURPOSE_C_GENERAL;
  else if (!strcasecmp(string, "controller"))
    return CIRCUIT_PURPOSE_CONTROLLER;
  else
    return CIRCUIT_PURPOSE_UNKNOWN;
}

732
733
734
735
736
737
static const control_cmd_syntax_t extendcircuit_syntax = {
  .min_args=1,
  .max_args=1, // see note in function
  .accept_keywords=true,
  .kvline_flags=KV_OMIT_VALS
};
738
739
740
741

/** Called when we get an EXTENDCIRCUIT message.  Try to extend the listed
 * circuit, and report success or failure. */
static int
742
743
handle_control_extendcircuit(control_connection_t *conn,
                             const control_cmd_args_t *args)
744
{
745
  smartlist_t *router_nicknames=smartlist_new(), *nodes=NULL;
746
747
  origin_circuit_t *circ = NULL;
  uint8_t intended_purpose = CIRCUIT_PURPOSE_C_GENERAL;
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
  const config_line_t *kwargs = args->kwargs;
  const char *circ_id = smartlist_get(args->args, 0);
  const char *path_str = NULL;
  char *path_str_alloc = NULL;

  /* The syntax for this command is unfortunate. The second argument is
     optional, and is a comma-separated list long-format fingerprints, which
     can (historically!) contain an equals sign.

     Here we check the second argument to see if it's a path, and if so we
     remove it from the kwargs list and put it in path_str.
  */
  if (kwargs) {
    const config_line_t *arg1 = kwargs;
    if (!strcmp(arg1->value, "")) {
      path_str = arg1->key;
      kwargs = kwargs->next;
    } else if (arg1->key[0] == '$') {
      tor_asprintf(&path_str_alloc, "%s=%s", arg1->key, arg1->value);
      path_str = path_str_alloc;
      kwargs = kwargs->next;
    }
  }
771

772
773
  const config_line_t *purpose_line = config_line_find_case(kwargs, "PURPOSE");
  bool zero_circ = !strcmp("0", circ_id);
774

775
776
777
  if (purpose_line) {
    intended_purpose = circuit_purpose_from_string(purpose_line->value);
    if (intended_purpose == CIRCUIT_PURPOSE_UNKNOWN) {
778
      control_printf_endreply(conn, 552, "Unknown purpose \"%s\"",
779
                              purpose_line->value);
780
      goto done;
781
    }
782
  }
783

784
785
786
  if (zero_circ) {
    if (!path_str) {
      // "EXTENDCIRCUIT 0" with no path.
787
788
      circ = circuit_launch(intended_purpose, CIRCLAUNCH_NEED_CAPACITY);
      if (!circ) {
789
        control_write_endreply(conn, 551, "Couldn't start circuit");
790
      } else {
791
792
        control_printf_endreply(conn, 250, "EXTENDED %lu",
                                (unsigned long)circ->global_identifier);
793
794
795
796
797
      }
      goto done;
    }
  }

798
  if (!zero_circ && !(circ = get_circ(circ_id))) {
799
    control_printf_endreply(conn, 552, "Unknown circuit \"%s\"", circ_id);
800
801
802
    goto done;
  }

803
  if (!path_str) {
804
    control_write_endreply(conn, 512, "syntax error: path required.");
805
806
807
    goto done;
  }

808
  smartlist_split_string(router_nicknames, path_str, ",", 0, 0);
809
810

  nodes = smartlist_new();
811
  bool first_node = zero_circ;
812
813
814
  SMARTLIST_FOREACH_BEGIN(router_nicknames, const char *, n) {
    const node_t *node = node_get_by_nickname(n, 0);
    if (!node) {
815
      control_printf_endreply(conn, 552, "No such router \"%s\"", n);
816
817
818
      goto done;
    }
    if (!node_has_preferred_descriptor(node, first_node)) {
819
      control_printf_endreply(conn, 552, "No descriptor for \"%s\"", n);
820
821
822
      goto done;
    }
    smartlist_add(nodes, (void*)node);
823
    first_node = false;
824
  } SMARTLIST_FOREACH_END(n);
825

826
  if (!smartlist_len(nodes)) {
827
    control_write_endreply(conn, 512, "No router names provided");
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
    goto done;
  }

  if (zero_circ) {
    /* start a new circuit */
    circ = origin_circuit_init(intended_purpose, 0);
  }

  /* now circ refers to something that is ready to be extended */
  first_node = zero_circ;
  SMARTLIST_FOREACH(nodes, const node_t *, node,
  {
    extend_info_t *info = extend_info_from_node(node, first_node);
    if (!info) {
      tor_assert_nonfatal(first_node);
      log_warn(LD_CONTROL,
               "controller tried to connect to a node that lacks a suitable "
               "descriptor, or which doesn't have any "
               "addresses that are allowed by the firewall configuration; "
               "circuit marked for closing.");
      circuit_mark_for_close(TO_CIRCUIT(circ), -END_CIRC_REASON_CONNECTFAILED);
849
      control_write_endreply(conn, 551, "Couldn't start circuit");
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
      goto done;
    }
    circuit_append_new_exit(circ, info);
    if (circ->build_state->desired_path_len > 1) {
      circ->build_state->onehop_tunnel = 0;
    }
    extend_info_free(info);
    first_node = 0;
  });

  /* now that we've populated the cpath, start extending */
  if (zero_circ) {
    int err_reason = 0;
    if ((err_reason = circuit_handle_first_hop(circ)) < 0) {
      circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
865
      control_write_endreply(conn, 551, "Couldn't start circuit");
866
867
868
869
870
871
872
873
874
875
876
      goto done;
    }
  } else {
    if (circ->base_.state == CIRCUIT_STATE_OPEN ||
        circ->base_.state == CIRCUIT_STATE_GUARD_WAIT) {
      int err_reason = 0;
      circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
      if ((err_reason = circuit_send_next_onion_skin(circ)) < 0) {
        log_info(LD_CONTROL,
                 "send_next_onion_skin failed; circuit marked for closing.");
        circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
877
        control_write_endreply(conn, 551, "Couldn't send onion skin");
878
879
880
881
882
        goto done;
      }
    }
  }

883
  control_printf_endreply(conn, 250, "EXTENDED %lu",
884
                          (unsigned long)circ->global_identifier);
885
886
887
888
889
890
  if (zero_circ) /* send a 'launched' event, for completeness */
    circuit_event_status(circ, CIRC_EVENT_LAUNCHED, 0);
 done:
  SMARTLIST_FOREACH(router_nicknames, char *, n, tor_free(n));
  smartlist_free(router_nicknames);
  smartlist_free(nodes);
891
  tor_free(path_str_alloc);
892
893
894
  return 0;
}

895
896
897
898
899
static const control_cmd_syntax_t setcircuitpurpose_syntax = {
  .max_args=1,
  .accept_keywords=true,
};

900
901
902
903
/** Called when we get a SETCIRCUITPURPOSE message. If we can find the
 * circuit and it's a valid purpose, change it. */
static int
handle_control_setcircuitpurpose(control_connection_t *conn,
904
                                 const control_cmd_args_t *args)
905
906
907
{
  origin_circuit_t *circ = NULL;
  uint8_t new_purpose;
908
  const char *circ_id = smartlist_get(args->args,0);
909

910
  if (!(circ = get_circ(circ_id))) {
911
    control_printf_endreply(conn, 552, "Unknown circuit \"%s\"", circ_id);
912
913
914
915
    goto done;
  }

  {
916
    const config_line_t *purp = config_line_find_case(args->kwargs, "PURPOSE");
917
    if (!purp) {
918
      control_write_endreply(conn, 552, "No purpose given");
919
920
      goto done;
    }
921
    new_purpose = circuit_purpose_from_string(purp->value);
922
    if (new_purpose == CIRCUIT_PURPOSE_UNKNOWN) {
923
      control_printf_endreply(conn, 552, "Unknown purpose \"%s\"",
924
                              purp->value);
925
926
927
928
929
      goto done;
    }
  }

  circuit_change_purpose(TO_CIRCUIT(circ), new_purpose);
930
  send_control_done(conn);
931
932
933
934
935

 done:
  return 0;
}

936
937
938
939
940
941
942
943
944
static const char *attachstream_keywords[] = {
  "HOP", NULL
};
static const control_cmd_syntax_t attachstream_syntax = {
  .min_args=2, .max_args=2,
  .accept_keywords=true,
  .allowed_keywords=attachstream_keywords
};

945
946
947
/** Called when we get an ATTACHSTREAM message.  Try to attach the requested
 * stream, and report success or failure. */
static int
948
949
handle_control_attachstream(control_connection_t *conn,
                            const control_cmd_args_t *args)
950
951
952
953
954
{
  entry_connection_t *ap_conn = NULL;
  origin_circuit_t *circ = NULL;
  crypt_path_t *cpath=NULL;
  int hop=0, hop_line_ok=1;
955
956
957
958
  const char *stream_id = smartlist_get(args->args, 0);
  const char *circ_id = smartlist_get(args->args, 1);
  int zero_circ = !strcmp(circ_id, "0");
  const config_line_t *hoparg = config_line_find_case(args->kwargs, "HOP");
959

960
  if (!(ap_conn = get_stream(stream_id))) {
961
    control_printf_endreply(conn, 552, "Unknown stream \"%s\"", stream_id);
962
963
    return 0;
  } else if (!zero_circ && !(circ = get_circ(circ_id))) {
964
    control_printf_endreply(conn, 552, "Unknown circuit \"%s\"", circ_id);
965
966
    return 0;
  } else if (circ) {
967
968
    if (hoparg) {
      hop = (int) tor_parse_ulong(hoparg->value, 10, 0, INT_MAX,
969
970
                                  &hop_line_ok, NULL);
      if (!hop_line_ok) { /* broken hop line */
971
        control_printf_endreply(conn, 552, "Bad value hop=%s",
972
                                hoparg->value);
973
        return 0;
974
975
976
977
978
979
980
      }
    }
  }

  if (ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONTROLLER_WAIT &&
      ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONNECT_WAIT &&
      ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_RESOLVE_WAIT) {
981
982
    control_write_endreply(conn, 555,
                           "Connection is not managed by controller.");
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
    return 0;
  }

  /* Do we need to detach it first? */
  if (ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONTROLLER_WAIT) {
    edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
    circuit_t *tmpcirc = circuit_get_by_edge_conn(edge_conn);
    connection_edge_end(edge_conn, END_STREAM_REASON_TIMEOUT);
    /* Un-mark it as ending, since we're going to reuse it. */
    edge_conn->edge_has_sent_end = 0;
    edge_conn->end_reason = 0;
    if (tmpcirc)
      circuit_detach_stream(tmpcirc, edge_conn);
    CONNECTION_AP_EXPECT_NONPENDING(ap_conn);
    TO_CONN(edge_conn)->state = AP_CONN_STATE_CONTROLLER_WAIT;
  }

  if (circ && (circ->base_.state != CIRCUIT_STATE_OPEN)) {
For faster browsing, not all history is shown. View entire blame