control_cmd.c 75.6 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/* 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"
#include "app/config/confparse.h"
#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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
  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)
      connection_printf_to_buf(conn,
                               "552-Unrecognized configuration key \"%s\"\r\n",
                               (char*)smartlist_get(unrecognized, i));
    connection_printf_to_buf(conn,
                             "552 Unrecognized configuration key \"%s\"\r\n",
                             (char*)smartlist_get(unrecognized, len-1));
  } 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 {
    connection_write_str_to_buf("250 OK\r\n", conn);
  }

  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
359
{
  setopt_err_t retval;
  char *errstring = NULL;
  const char *msg = NULL;

360
  retval = options_init_from_string(NULL, args->cmddata,
361
                                    CMD_RUN_TOR, NULL, &errstring);
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396

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

  switch (retval) {
  case SETOPT_ERR_PARSE:
    msg = "552 Invalid config file";
    break;
  case SETOPT_ERR_TRANSITION:
    msg = "553 Transition not allowed";
    break;
  case SETOPT_ERR_SETTING:
    msg = "553 Unable to set option";
    break;
  case SETOPT_ERR_MISC:
  default:
    msg = "550 Unable to load config";
    break;
  case SETOPT_OK:
    break;
  }
  if (msg) {
    if (errstring)
      connection_printf_to_buf(conn, "%s: %s\r\n", msg, errstring);
    else
      connection_printf_to_buf(conn, "%s\r\n", msg);
  } else {
    send_control_done(conn);
  }
  tor_free(errstring);
  return 0;
}

397
398
399
400
static const control_cmd_syntax_t setevents_syntax = {
  .max_args = UINT_MAX
};

401
402
403
/** Called when we get a SETEVENTS message: update conn->event_mask,
 * and reply with DONE or ERROR. */
static int
404
405
handle_control_setevents(control_connection_t *conn,
                         const control_cmd_args_t *args)
406
407
408
{
  int event_code;
  event_mask_t event_mask = 0;
409
  const smartlist_t *events = args->args;
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445

  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) {
          connection_printf_to_buf(conn, "552 Unrecognized event \"%s\"\r\n",
                                   ev);
          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;
}

446
447
448
449
450
451
static const control_cmd_syntax_t saveconf_syntax = {
  .max_args = 0,
  .accept_keywords = true,
  .kvline_flags=KV_OMIT_VALS,
};

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

469
470
471
472
473
static const control_cmd_syntax_t signal_syntax = {
  .min_args = 1,
  .max_args = 1,
};

474
475
476
477
/** 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
478
479
handle_control_signal(control_connection_t *conn,
                      const control_cmd_args_t *args)
480
481
482
483
{
  int sig = -1;
  int i;

484
485
  tor_assert(smartlist_len(args->args) == 1);
  const char *s = smartlist_get(args->args, 0);
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509

  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)
    connection_printf_to_buf(conn, "552 Unrecognized signal code \"%s\"\r\n",
                             s);
  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;
}

510
511
512
513
static const control_cmd_syntax_t takeownership_syntax = {
  .max_args = UINT_MAX, // This should probably become zero. XXXXX
};

514
515
516
517
/** 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
518
519
handle_control_takeownership(control_connection_t *conn,
                             const control_cmd_args_t *args)
520
{
521
  (void)args;
522
523
524
525
526
527
528
529
530
531
532

  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;
}

533
534
535
536
static const control_cmd_syntax_t dropownership_syntax = {
  .max_args = UINT_MAX, // This should probably become zero. XXXXX
};

537
538
539
540
/** 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
541
542
handle_control_dropownership(control_connection_t *conn,
                             const control_cmd_args_t *args)
543
{
544
  (void)args;
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
584
585
586
587
588

  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
589
590
control_setconf_helper(control_connection_t *conn,
                       const control_cmd_args_t *args,
591
592
593
594
595
596
597
                       int use_defaults)
{
  setopt_err_t opt_err;
  char *errstring = NULL;
  const unsigned flags =
    CAL_CLEAR_FIRST | (use_defaults ? CAL_USE_DEFAULTS : 0);

598
599
  // We need a copy here, since confparse.c wants to canonicalize cases.
  config_line_t *lines = config_lines_dup(args->kwargs);
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643

  opt_err = options_trial_assign(lines, flags, &errstring);
  {
    const char *msg;
    switch (opt_err) {
      case SETOPT_ERR_MISC:
        msg = "552 Unrecognized option";
        break;
      case SETOPT_ERR_PARSE:
        msg = "513 Unacceptable option value";
        break;
      case SETOPT_ERR_TRANSITION:
        msg = "553 Transition not allowed";
        break;
      case SETOPT_ERR_SETTING:
      default:
        msg = "553 Unable to set option";
        break;
      case SETOPT_OK:
        config_free_lines(lines);
        send_control_done(conn);
        return 0;
    }
    log_warn(LD_CONTROL,
             "Controller gave us config lines that didn't validate: %s",
             errstring);
    connection_printf_to_buf(conn, "%s: %s\r\n", msg, 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);
}

644
static const control_cmd_syntax_t mapaddress_syntax = {
645
  .max_args=1,
646
647
648
  .accept_keywords=true,
};

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

  reply = smartlist_new();
660
661
662
663
664
  const config_line_t *line;
  for (line = args->kwargs; line; line = line->next) {
    const char *from = line->key;
    const char *to = line->value;
    {
665
666
667
668
669
670
671
672
673
674
675
676
677
678
      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,
679
                   "451-resource exhausted: skipping '%s=%s'", from,to);
680
681
          log_warn(LD_CONTROL,
                   "Unable to allocate address for '%s' in MapAddress msg",
682
                   safe_str_client(to));
683
684
685
686
687
688
689
690
691
        } 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 "
692
                                 " '%s=%s': %s", from, to, msg);
693
          log_warn(LD_CONTROL,
694
695
                   "Skipping invalid argument '%s=%s' in MapAddress msg: %s",
                   from, to, msg);
696
        } else {
697
          smartlist_add_asprintf(reply, "250-%s=%s", from, to);
698
699
700
        }
      }
    }
701
  }
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733

  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 {
    const char *response =
      "512 syntax error: not enough arguments to mapaddress.\r\n";
    connection_buf_add(response, strlen(response), TO_CONN(conn));
  }

  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;
}

734
735
736
737
738
739
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
};
740
741
742
743

/** Called when we get an EXTENDCIRCUIT message.  Try to extend the listed
 * circuit, and report success or failure. */
static int
744
745
handle_control_extendcircuit(control_connection_t *conn,
                             const control_cmd_args_t *args)
746
{
747
  smartlist_t *router_nicknames=smartlist_new(), *nodes=NULL;
748
749
  origin_circuit_t *circ = NULL;
  uint8_t intended_purpose = CIRCUIT_PURPOSE_C_GENERAL;
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
  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;
    }
  }
773

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

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

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

800
801
  if (!zero_circ && !(circ = get_circ(circ_id))) {
    connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n", circ_id);
802
803
804
    goto done;
  }

805
806
  if (!path_str) {
    connection_printf_to_buf(conn, "512 syntax error: path required.\r\n");
807
808
809
    goto done;
  }

810
  smartlist_split_string(router_nicknames, path_str, ",", 0, 0);
811
812

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

828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
  if (!smartlist_len(nodes)) {
    connection_write_str_to_buf("512 No router names provided\r\n", conn);
    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);
      connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
      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);
      connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
      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);
        connection_write_str_to_buf("551 Couldn't send onion skin\r\n", conn);
        goto done;
      }
    }
  }

  connection_printf_to_buf(conn, "250 EXTENDED %lu\r\n",
                             (unsigned long)circ->global_identifier);
  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);
893
  tor_free(path_str_alloc);
894
895
896
  return 0;
}

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

902
903
904
905
/** 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,
906
                                 const control_cmd_args_t *args)
907
908
909
{
  origin_circuit_t *circ = NULL;
  uint8_t new_purpose;
910
  const char *circ_id = smartlist_get(args->args,0);
911

912
913
  if (!(circ = get_circ(circ_id))) {
    connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n", circ_id);
914
915
916
917
    goto done;
  }

  {
918
    const config_line_t *purp = config_line_find_case(args->kwargs, "PURPOSE");
919
920
921
922
    if (!purp) {
      connection_write_str_to_buf("552 No purpose given\r\n", conn);
      goto done;
    }
923
    new_purpose = circuit_purpose_from_string(purp->value);
924
    if (new_purpose == CIRCUIT_PURPOSE_UNKNOWN) {
925
926
      connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n",
                               purp->value);
927
928
929
930
931
932
933
934
935
936
937
      goto done;
    }
  }

  circuit_change_purpose(TO_CIRCUIT(circ), new_purpose);
  connection_write_str_to_buf("250 OK\r\n", conn);

 done:
  return 0;
}

938
939
940
941
942
943
944
945
946
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
};

947
948
949
/** Called when we get an ATTACHSTREAM message.  Try to attach the requested
 * stream, and report success or failure. */
static int
950
951
handle_control_attachstream(control_connection_t *conn,
                            const control_cmd_args_t *args)
952
953
954
955
956
{
  entry_connection_t *ap_conn = NULL;
  origin_circuit_t *circ = NULL;
  crypt_path_t *cpath=NULL;
  int hop=0, hop_line_ok=1;
957
958
959
960
  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");
961

962
963
964
965
966
  if (!(ap_conn = get_stream(stream_id))) {
    connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n", stream_id);
    return 0;
  } else if (!zero_circ && !(circ = get_circ(circ_id))) {
    connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n", circ_id);
967
968
    return 0;
  } else if (circ) {
969
970
    if (hoparg) {
      hop = (int) tor_parse_ulong(hoparg->value, 10, 0, INT_MAX,
971
972
                                  &hop_line_ok, NULL);
      if (!hop_line_ok) { /* broken hop line */
973
974
975
        connection_printf_to_buf(conn, "552 Bad value hop=%s\r\n",
                                 hoparg->value);
        return 0;
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
      }
    }
  }

  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) {
    connection_write_str_to_buf(
                    "555 Connection is not managed by controller.\r\n",
                    conn);
    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;
For faster browsing, not all history is shown. View entire blame