control.c 157 KB
Newer Older
1
/* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
2
 * Copyright (c) 2007-2012, The Tor Project, Inc. */
3
4
/* See LICENSE for licensing information */

Nick Mathewson's avatar
Nick Mathewson committed
5
/**
6
7
 * \file control.c
 * \brief Implementation for Tor's control-socket interface.
Roger Dingledine's avatar
Roger Dingledine committed
8
 *   See doc/spec/control-spec.txt for full details on protocol.
9
 **/
Nick Mathewson's avatar
Nick Mathewson committed
10

11
12
#define CONTROL_PRIVATE

13
#include "or.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
14
#include "buffers.h"
15
16
#include "channel.h"
#include "channeltls.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
17
#include "circuitbuild.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
18
#include "circuitlist.h"
19
#include "circuitstats.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
20
#include "circuituse.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
21
#include "config.h"
22
#include "confparse.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
23
#include "connection.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
24
#include "connection_edge.h"
25
#include "connection_or.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
26
#include "control.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
27
#include "directory.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
28
#include "dirserv.h"
29
#include "dnsserv.h"
30
#include "entrynodes.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
31
#include "geoip.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
32
#include "hibernate.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
33
#include "main.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
34
#include "networkstatus.h"
35
#include "nodelist.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
36
#include "policies.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
37
#include "reasons.h"
38
#include "rephist.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
39
#include "router.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
40
#include "routerlist.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
41
#include "routerparse.h"
42

43
#ifndef _WIN32
44
45
46
47
#include <pwd.h>
#include <sys/resource.h>
#endif

48
49
#include "procmon.h"

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

54
/* Recognized asynchronous event types.  It's okay to expand this list
55
 * because it is used both as a list of v0 event types, and as indices
56
57
 * into the bitfield to determine which controllers want which events.
 */
58
#define EVENT_MIN_             0x0001
Roger Dingledine's avatar
Roger Dingledine committed
59
60
61
62
#define EVENT_CIRCUIT_STATUS   0x0001
#define EVENT_STREAM_STATUS    0x0002
#define EVENT_OR_CONN_STATUS   0x0003
#define EVENT_BANDWIDTH_USED   0x0004
Nick Mathewson's avatar
Nick Mathewson committed
63
#define EVENT_CIRCUIT_STATUS_MINOR 0x0005
Roger Dingledine's avatar
Roger Dingledine committed
64
65
66
67
68
69
70
#define EVENT_NEW_DESC         0x0006
#define EVENT_DEBUG_MSG        0x0007
#define EVENT_INFO_MSG         0x0008
#define EVENT_NOTICE_MSG       0x0009
#define EVENT_WARN_MSG         0x000A
#define EVENT_ERR_MSG          0x000B
#define EVENT_ADDRMAP          0x000C
71
// #define EVENT_AUTHDIR_NEWDESCS 0x000D
Roger Dingledine's avatar
Roger Dingledine committed
72
#define EVENT_DESCCHANGED      0x000E
73
// #define EVENT_NS               0x000F
74
75
76
#define EVENT_STATUS_CLIENT    0x0010
#define EVENT_STATUS_SERVER    0x0011
#define EVENT_STATUS_GENERAL   0x0012
77
#define EVENT_GUARD            0x0013
78
#define EVENT_STREAM_BANDWIDTH_USED   0x0014
79
#define EVENT_CLIENTS_SEEN     0x0015
80
#define EVENT_NEWCONSENSUS     0x0016
81
#define EVENT_BUILDTIMEOUT_SET     0x0017
82
#define EVENT_SIGNAL           0x0018
83
#define EVENT_CONF_CHANGED     0x0019
84
85
#define EVENT_MAX_             0x0019
/* If EVENT_MAX_ ever hits 0x0020, we need to make the mask wider. */
86

87
/** Bitfield: The bit 1&lt;&lt;e is set if <b>any</b> open control
Nick Mathewson's avatar
Nick Mathewson committed
88
89
 * connection is interested in events of type <b>e</b>.  We use this
 * so that we can decide to skip generating event messages that nobody
Roger Dingledine's avatar
Roger Dingledine committed
90
 * has interest in without having to walk over the global connection
Nick Mathewson's avatar
Nick Mathewson committed
91
92
 * list to find out.
 **/
93
typedef uint32_t event_mask_t;
94

95
96
97
/** An event mask of all the events that any controller is interested in
 * receiving. */
static event_mask_t global_event_mask = 0;
98

99
100
101
/** True iff we have disabled log messages from being sent to the controller */
static int disable_log_messages = 0;

Nick Mathewson's avatar
Nick Mathewson committed
102
103
/** Macro: true if any control connection is interested in events of type
 * <b>e</b>. */
104
#define EVENT_IS_INTERESTING(e) \
105
  (global_event_mask & (1<<(e)))
Nick Mathewson's avatar
Nick Mathewson committed
106
107
108

/** If we're using cookie-type authentication, how long should our cookies be?
 */
109
#define AUTHENTICATION_COOKIE_LEN 32
Nick Mathewson's avatar
Nick Mathewson committed
110
111
112

/** If true, we've set authentication_cookie to a secret code and
 * stored it to disk. */
113
static int authentication_cookie_is_set = 0;
114
115
/** If authentication_cookie_is_set, a secret cookie that we've stored to disk
 * and which we're using to authenticate controllers.  (If the controller can
Robert Ransom's avatar
Robert Ransom committed
116
 * read it off disk, it has permission to connect.) */
117
118
static char authentication_cookie[AUTHENTICATION_COOKIE_LEN];

119
120
121
122
123
124
#define SAFECOOKIE_SERVER_TO_CONTROLLER_CONSTANT \
  "Tor safe cookie authentication server-to-controller hash"
#define SAFECOOKIE_CONTROLLER_TO_SERVER_CONSTANT \
  "Tor safe cookie authentication controller-to-server hash"
#define SAFECOOKIE_SERVER_NONCE_LEN DIGEST256_LEN

125
126
127
128
129
130
131
/** A sufficiently large size to record the last bootstrap phase string. */
#define BOOTSTRAP_MSG_LEN 1024

/** What was the last bootstrap phase message we sent? We keep track
 * of this so we can respond to getinfo status/bootstrap-phase queries. */
static char last_sent_bootstrap_message[BOOTSTRAP_MSG_LEN];

132
133
/** Flag for event_format_t.  Indicates that we should use the one standard
    format.
134
 */
135
#define ALL_FORMATS 1
136
137

/** Bit field of flags to select how to format a controller event.  Recognized
138
 * flag is ALL_FORMATS. */
139
typedef int event_format_t;
140

141
static void connection_printf_to_buf(control_connection_t *conn,
142
                                     const char *format, ...)
143
  CHECK_PRINTF(2,3);
144
145
146
147
148
149
150
static void send_control_event_impl(uint16_t event, event_format_t which,
                                    const char *format, va_list ap)
  CHECK_PRINTF(3,0);
static int control_event_status(int type, int severity, const char *format,
                                va_list args)
  CHECK_PRINTF(3,0);

151
static void send_control_done(control_connection_t *conn);
152
153
static void send_control_event(uint16_t event, event_format_t which,
                               const char *format, ...)
154
  CHECK_PRINTF(3,4);
155
static int handle_control_setconf(control_connection_t *conn, uint32_t len,
156
                                  char *body);
157
static int handle_control_resetconf(control_connection_t *conn, uint32_t len,
158
                                    char *body);
159
static int handle_control_getconf(control_connection_t *conn, uint32_t len,
160
                                  const char *body);
161
162
static int handle_control_loadconf(control_connection_t *conn, uint32_t len,
                                  const char *body);
163
static int handle_control_setevents(control_connection_t *conn, uint32_t len,
164
                                    const char *body);
165
166
static int handle_control_authenticate(control_connection_t *conn,
                                       uint32_t len,
167
                                       const char *body);
168
static int handle_control_signal(control_connection_t *conn, uint32_t len,
169
                                 const char *body);
170
static int handle_control_mapaddress(control_connection_t *conn, uint32_t len,
171
                                     const char *body);
172
static char *list_getinfo_options(void);
173
static int handle_control_getinfo(control_connection_t *conn, uint32_t len,
174
                                  const char *body);
175
176
static int handle_control_extendcircuit(control_connection_t *conn,
                                        uint32_t len,
177
                                        const char *body);
178
179
static int handle_control_setcircuitpurpose(control_connection_t *conn,
                                            uint32_t len, const char *body);
180
181
static int handle_control_attachstream(control_connection_t *conn,
                                       uint32_t len,
182
                                        const char *body);
183
184
static int handle_control_postdescriptor(control_connection_t *conn,
                                         uint32_t len,
185
                                         const char *body);
186
187
static int handle_control_redirectstream(control_connection_t *conn,
                                         uint32_t len,
188
                                         const char *body);
189
static int handle_control_closestream(control_connection_t *conn, uint32_t len,
190
                                      const char *body);
191
192
static int handle_control_closecircuit(control_connection_t *conn,
                                       uint32_t len,
193
                                       const char *body);
194
195
static int handle_control_resolve(control_connection_t *conn, uint32_t len,
                                  const char *body);
196
197
198
static int handle_control_usefeature(control_connection_t *conn,
                                     uint32_t len,
                                     const char *body);
199
static int write_stream_target_to_buf(entry_connection_t *conn, char *buf,
200
                                      size_t len);
201
static void orconn_target_get_name(char *buf, size_t len,
202
                                   or_connection_t *conn);
203
static char *get_cookie_file(void);
204

205
206
/** Given a control event code for a message event, return the corresponding
 * log severity. */
207
208
209
210
211
212
213
214
215
216
217
218
219
static INLINE int
event_to_log_severity(int event)
{
  switch (event) {
    case EVENT_DEBUG_MSG: return LOG_DEBUG;
    case EVENT_INFO_MSG: return LOG_INFO;
    case EVENT_NOTICE_MSG: return LOG_NOTICE;
    case EVENT_WARN_MSG: return LOG_WARN;
    case EVENT_ERR_MSG: return LOG_ERR;
    default: return -1;
  }
}

220
/** Given a log severity, return the corresponding control event code. */
221
222
223
224
225
226
227
228
229
230
231
232
233
static INLINE int
log_severity_to_event(int severity)
{
  switch (severity) {
    case LOG_DEBUG: return EVENT_DEBUG_MSG;
    case LOG_INFO: return EVENT_INFO_MSG;
    case LOG_NOTICE: return EVENT_NOTICE_MSG;
    case LOG_WARN: return EVENT_WARN_MSG;
    case LOG_ERR: return EVENT_ERR_MSG;
    default: return -1;
  }
}

234
235
/** Set <b>global_event_mask*</b> to the bitwise OR of each live control
 * connection's event_mask field. */
236
237
void
control_update_global_event_mask(void)
238
{
239
  smartlist_t *conns = get_connection_array();
240
  event_mask_t old_mask, new_mask;
241
  old_mask = global_event_mask;
242

243
  global_event_mask = 0;
244
245
246
247
248
  SMARTLIST_FOREACH(conns, connection_t *, _conn,
  {
    if (_conn->type == CONN_TYPE_CONTROL &&
        STATE_IS_OPEN(_conn->state)) {
      control_connection_t *conn = TO_CONTROL_CONN(_conn);
249
      global_event_mask |= conn->event_mask;
250
    }
251
  });
252

253
  new_mask = global_event_mask;
254
255
256

  /* Handle the aftermath.  Set up the log callback to tell us only what
   * we want to hear...*/
257
  control_adjust_event_log_severity();
258
259
260
261
262

  /* ...then, if we've started logging stream bw, clear the appropriate
   * fields. */
  if (! (old_mask & EVENT_STREAM_BANDWIDTH_USED) &&
      (new_mask & EVENT_STREAM_BANDWIDTH_USED)) {
263
264
265
266
267
    SMARTLIST_FOREACH(conns, connection_t *, conn,
    {
      if (conn->type == CONN_TYPE_AP) {
        edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
        edge_conn->n_written = edge_conn->n_read = 0;
268
      }
269
    });
270
  }
271
272
}

273
274
275
/** Adjust the log severities that result in control_event_logmsg being called
 * to match the severity of log messages that any controllers are interested
 * in. */
276
void
277
control_adjust_event_log_severity(void)
278
{
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
  int i;
  int min_log_event=EVENT_ERR_MSG, max_log_event=EVENT_DEBUG_MSG;

  for (i = EVENT_DEBUG_MSG; i <= EVENT_ERR_MSG; ++i) {
    if (EVENT_IS_INTERESTING(i)) {
      min_log_event = i;
      break;
    }
  }
  for (i = EVENT_ERR_MSG; i >= EVENT_DEBUG_MSG; --i) {
    if (EVENT_IS_INTERESTING(i)) {
      max_log_event = i;
      break;
    }
  }
294
  if (EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL)) {
295
296
297
298
299
    if (min_log_event > EVENT_NOTICE_MSG)
      min_log_event = EVENT_NOTICE_MSG;
    if (max_log_event < EVENT_ERR_MSG)
      max_log_event = EVENT_ERR_MSG;
  }
300
301
302
303
304
305
306
  if (min_log_event <= max_log_event)
    change_callback_log_severity(event_to_log_severity(min_log_event),
                                 event_to_log_severity(max_log_event),
                                 control_event_logmsg);
  else
    change_callback_log_severity(LOG_ERR, LOG_ERR,
                                 control_event_logmsg);
307
308
}

309
310
311
312
313
314
315
316
317
318
/** Return true iff the event with code <b>c</b> is being sent to any current
 * control connection.  This is useful if the amount of work needed to prepare
 * to call the appropriate control_event_...() function is high.
 */
int
control_event_is_interesting(int event)
{
  return EVENT_IS_INTERESTING(event);
}

319
/** Append a NUL-terminated string <b>s</b> to the end of
320
 * <b>conn</b>-\>outbuf.
321
 */
322
static INLINE void
323
connection_write_str_to_buf(const char *s, control_connection_t *conn)
324
325
{
  size_t len = strlen(s);
326
  connection_write_to_buf(s, len, TO_CONN(conn));
327
328
}

329
/** Given a <b>len</b>-character string in <b>data</b>, made of lines
330
331
 * terminated by CRLF, allocate a new string in *<b>out</b>, and copy the
 * contents of <b>data</b> into *<b>out</b>, adding a period before any period
332
 * that appears at the start of a line, and adding a period-CRLF line at
333
334
 * the end. Replace all LF characters sequences with CRLF.  Return the number
 * of bytes in *<b>out</b>.
335
336
 */
/* static */ size_t
337
write_escaped_data(const char *data, size_t len, char **out)
338
339
340
{
  size_t sz_out = len+8;
  char *outp;
341
  const char *start = data, *end;
342
343
  int i;
  int start_of_line;
Nick Mathewson's avatar
Nick Mathewson committed
344
  for (i=0; i<(int)len; ++i) {
345
    if (data[i]== '\n')
346
      sz_out += 2; /* Maybe add a CR; maybe add a dot. */
347
348
349
350
351
352
  }
  *out = outp = tor_malloc(sz_out+1);
  end = data+len;
  start_of_line = 1;
  while (data < end) {
    if (*data == '\n') {
353
      if (data > start && data[-1] != '\r')
354
355
356
357
358
359
360
361
362
363
364
365
        *outp++ = '\r';
      start_of_line = 1;
    } else if (*data == '.') {
      if (start_of_line) {
        start_of_line = 0;
        *outp++ = '.';
      }
    } else {
      start_of_line = 0;
    }
    *outp++ = *data++;
  }
366
  if (outp < *out+2 || fast_memcmp(outp-2, "\r\n", 2)) {
367
368
369
    *outp++ = '\r';
    *outp++ = '\n';
  }
370
371
372
  *outp++ = '.';
  *outp++ = '\r';
  *outp++ = '\n';
373
  *outp = '\0'; /* NUL-terminate just in case. */
374
  tor_assert((outp - *out) <= (int)sz_out);
375
376
377
  return outp - *out;
}

378
379
380
/** Given a <b>len</b>-character string in <b>data</b>, made of lines
 * terminated by CRLF, allocate a new string in *<b>out</b>, and copy
 * the contents of <b>data</b> into *<b>out</b>, removing any period
381
382
 * that appears at the start of a line, and replacing all CRLF sequences
 * with LF.   Return the number of
383
 * bytes in *<b>out</b>. */
384
/* static */ size_t
385
read_escaped_data(const char *data, size_t len, char **out)
386
387
388
{
  char *outp;
  const char *next;
389
390
391
  const char *end;

  *out = outp = tor_malloc(len+1);
392

393
  end = data+len;
394

395
  while (data < end) {
396
    /* we're at the start of a line. */
397
398
    if (*data == '.')
      ++data;
399
    next = memchr(data, '\n', end-data);
400
    if (next) {
401
402
403
404
405
406
407
408
      size_t n_to_copy = next-data;
      /* Don't copy a CR that precedes this LF. */
      if (n_to_copy && *(next-1) == '\r')
        --n_to_copy;
      memcpy(outp, data, n_to_copy);
      outp += n_to_copy;
      data = next+1; /* This will point at the start of the next line,
                      * or the end of the string, or a period. */
409
    } else {
410
411
412
      memcpy(outp, data, end-data);
      outp += (end-data);
      *outp = '\0';
413
414
      return outp - *out;
    }
415
    *outp++ = '\n';
416
417
  }

418
  *outp = '\0';
419
420
  return outp - *out;
}
421

422
/** If the first <b>in_len_max</b> characters in <b>start</b> contain a
423
424
425
426
427
 * double-quoted string with escaped characters, return the length of that
 * string (as encoded, including quotes).  Otherwise return -1. */
static INLINE int
get_escaped_string_length(const char *start, size_t in_len_max,
                          int *chars_out)
428
429
{
  const char *cp, *end;
430
  int chars = 0;
431
432

  if (*start != '\"')
433
    return -1;
434
435
436
437
438
439

  cp = start+1;
  end = start+in_len_max;

  /* Calculate length. */
  while (1) {
440
441
442
    if (cp >= end) {
      return -1; /* Too long. */
    } else if (*cp == '\\') {
443
      if (++cp == end)
444
        return -1; /* Can't escape EOS. */
445
      ++cp;
446
      ++chars;
447
448
449
450
    } else if (*cp == '\"') {
      break;
    } else {
      ++cp;
451
      ++chars;
452
453
    }
  }
454
455
  if (chars_out)
    *chars_out = chars;
456
  return (int)(cp - start+1);
457
}
458

459
460
461
462
463
464
465
466
467
468
/** As decode_escaped_string, but does not decode the string: copies the
 * entire thing, including quotation marks. */
static const char *
extract_escaped_string(const char *start, size_t in_len_max,
                       char **out, size_t *out_len)
{
  int length = get_escaped_string_length(start, in_len_max, NULL);
  if (length<0)
    return NULL;
  *out_len = length;
469
  *out = tor_strndup(start, *out_len);
470
  return start+length;
471
472
}

473
/** Given a pointer to a string starting at <b>start</b> containing
474
 * <b>in_len_max</b> characters, decode a string beginning with one double
475
 * quote, containing any number of non-quote characters or characters escaped
476
 * with a backslash, and ending with a final double quote.  Place the resulting
477
478
479
 * string (unquoted, unescaped) into a newly allocated string in *<b>out</b>;
 * store its length in <b>out_len</b>.  On success, return a pointer to the
 * character immediately following the escaped string.  On failure, return
Roger Dingledine's avatar
Roger Dingledine committed
480
 * NULL. */
481
static const char *
482
decode_escaped_string(const char *start, size_t in_len_max,
483
                   char **out, size_t *out_len)
484
{
485
486
  const char *cp, *end;
  char *outp;
487
  int len, n_chars = 0;
488

489
490
  len = get_escaped_string_length(start, in_len_max, &n_chars);
  if (len<0)
491
492
    return NULL;

493
494
  end = start+len-1; /* Index of last quote. */
  tor_assert(*end == '\"');
495
  outp = *out = tor_malloc(len+1);
496
  *out_len = n_chars;
497

498
499
500
501
502
503
504
  cp = start+1;
  while (cp < end) {
    if (*cp == '\\')
      ++cp;
    *outp++ = *cp++;
  }
  *outp = '\0';
505
  tor_assert((outp - *out) == (int)*out_len);
506
507
508
509

  return end+1;
}

510
/** Acts like sprintf, but writes its formatted string to the end of
511
 * <b>conn</b>-\>outbuf. */
512
static void
513
connection_printf_to_buf(control_connection_t *conn, const char *format, ...)
514
515
{
  va_list ap;
516
517
518
  char *buf = NULL;
  int len;

519
  va_start(ap,format);
520
  len = tor_vasprintf(&buf, format, ap);
521
  va_end(ap);
522
523

  if (len < 0) {
524
525
    log_err(LD_BUG, "Unable to format string for controller.");
    tor_assert(0);
526
  }
527
528
529
530

  connection_write_to_buf(buf, (size_t)len, TO_CONN(conn));

  tor_free(buf);
531
532
}

533
534
535
536
537
538
/** Write all of the open control ports to ControlPortWriteToFile */
void
control_ports_write_to_file(void)
{
  smartlist_t *lines;
  char *joined = NULL;
539
  const or_options_t *options = get_options();
540
541
542
543

  if (!options->ControlPortWriteToFile)
    return;

544
  lines = smartlist_new();
545
546
547
548
549
550

  SMARTLIST_FOREACH_BEGIN(get_connection_array(), const connection_t *, conn) {
    if (conn->type != CONN_TYPE_CONTROL_LISTENER || conn->marked_for_close)
      continue;
#ifdef AF_UNIX
    if (conn->socket_family == AF_UNIX) {
551
      smartlist_add_asprintf(lines, "UNIX_PORT=%s\n", conn->address);
552
553
554
      continue;
    }
#endif
555
    smartlist_add_asprintf(lines, "PORT=%s:%d\n", conn->address, conn->port);
556
557
558
559
560
561
562
563
  } SMARTLIST_FOREACH_END(conn);

  joined = smartlist_join_strings(lines, "", 0, NULL);

  if (write_str_to_file(options->ControlPortWriteToFile, joined, 0) < 0) {
    log_warn(LD_CONTROL, "Writing %s failed: %s",
             options->ControlPortWriteToFile, strerror(errno));
  }
564
#ifndef _WIN32
565
566
567
568
569
570
571
  if (options->ControlPortFileGroupReadable) {
    if (chmod(options->ControlPortWriteToFile, 0640)) {
      log_warn(LD_FS,"Unable to make %s group-readable.",
               options->ControlPortWriteToFile);
    }
  }
#endif
572
573
574
575
576
  tor_free(joined);
  SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  smartlist_free(lines);
}

577
/** Send a "DONE" message down the control connection <b>conn</b>. */
578
static void
579
send_control_done(control_connection_t *conn)
580
{
581
  connection_write_str_to_buf("250 OK\r\n", conn);
582
583
}

584
/** Send an event to all v1 controllers that are listening for code
585
586
 * <b>event</b>.  The event's body is given by <b>msg</b>.
 *
587
588
 * If <b>which</b> & SHORT_NAMES, the event contains short-format names: send
 * it to controllers that haven't enabled the VERBOSE_NAMES feature.  If
589
 * <b>which</b> & LONG_NAMES, the event contains long-format names: send it
Nick Mathewson's avatar
Nick Mathewson committed
590
 * to controllers that <em>have</em> enabled VERBOSE_NAMES.
591
 *
592
 * The EXTENDED_FORMAT and NONEXTENDED_FORMAT flags behave similarly with
593
 * respect to the EXTENDED_EVENTS feature. */
594
static void
595
596
send_control_event_string(uint16_t event, event_format_t which,
                          const char *msg)
597
{
598
  smartlist_t *conns = get_connection_array();
599
  (void)which;
600
  tor_assert(event >= EVENT_MIN_ && event <= EVENT_MAX_);
601

602
  SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
603
604
605
606
    if (conn->type == CONN_TYPE_CONTROL &&
        !conn->marked_for_close &&
        conn->state == CONTROL_CONN_STATE_OPEN) {
      control_connection_t *control_conn = TO_CONTROL_CONN(conn);
607

608
      if (control_conn->event_mask & (1<<event)) {
609
        int is_err = 0;
610
611
        connection_write_to_buf(msg, strlen(msg), TO_CONN(control_conn));
        if (event == EVENT_ERR_MSG)
612
613
614
615
616
617
618
619
          is_err = 1;
        else if (event == EVENT_STATUS_GENERAL)
          is_err = !strcmpstart(msg, "STATUS_GENERAL ERR ");
        else if (event == EVENT_STATUS_CLIENT)
          is_err = !strcmpstart(msg, "STATUS_CLIENT ERR ");
        else if (event == EVENT_STATUS_SERVER)
          is_err = !strcmpstart(msg, "STATUS_SERVER ERR ");
        if (is_err)
620
          connection_flush(TO_CONN(control_conn));
621
      }
622
    }
623
  } SMARTLIST_FOREACH_END(conn);
624
625
}

Robert Ransom's avatar
Robert Ransom committed
626
/** Helper for send_control_event and control_event_status:
627
628
 * Send an event to all v1 controllers that are listening for code
 * <b>event</b>.  The event's body is created by the printf-style format in
629
 * <b>format</b>, and other arguments as provided. */
630
static void
631
632
send_control_event_impl(uint16_t event, event_format_t which,
                         const char *format, va_list ap)
633
{
634
635
636
637
638
  char *buf = NULL;
  int len;

  len = tor_vasprintf(&buf, format, ap);
  if (len < 0) {
639
640
641
    log_warn(LD_BUG, "Unable to format event for controller.");
    return;
  }
642

643
  send_control_event_string(event, which|ALL_FORMATS, buf);
644
645

  tor_free(buf);
646
647
}

648
/** Send an event to all v1 controllers that are listening for code
649
 * <b>event</b>.  The event's body is created by the printf-style format in
650
 * <b>format</b>, and other arguments as provided. */
651
static void
652
send_control_event(uint16_t event, event_format_t which,
653
                   const char *format, ...)
654
655
656
{
  va_list ap;
  va_start(ap, format);
657
  send_control_event_impl(event, which, format, ap);
658
  va_end(ap);
659
660
}

661
/** Given a text circuit <b>id</b>, return the corresponding circuit. */
662
static origin_circuit_t *
663
664
get_circ(const char *id)
{
665
  uint32_t n_id;
666
  int ok;
667
  n_id = (uint32_t) tor_parse_ulong(id, 10, 0, UINT32_MAX, &ok, NULL);
668
669
670
671
672
  if (!ok)
    return NULL;
  return circuit_get_by_global_id(n_id);
}

673
/** Given a text stream <b>id</b>, return the corresponding AP connection. */
674
static entry_connection_t *
675
676
get_stream(const char *id)
{
677
  uint64_t n_id;
678
  int ok;
679
680
  connection_t *conn;
  n_id = tor_parse_uint64(id, 10, 0, UINT64_MAX, &ok, NULL);
681
682
683
  if (!ok)
    return NULL;
  conn = connection_get_by_global_id(n_id);
684
  if (!conn || conn->type != CONN_TYPE_AP || conn->marked_for_close)
685
    return NULL;
686
  return TO_ENTRY_CONN(conn);
687
688
}

689
/** Helper for setconf and resetconf. Acts like setconf, except
690
691
 * it passes <b>use_defaults</b> on to options_trial_assign().  Modifies the
 * contents of body.
692
 */
693
static int
694
control_setconf_helper(control_connection_t *conn, uint32_t len, char *body,
695
                       int use_defaults)
696
{
697
  setopt_err_t opt_err;
698
  config_line_t *lines=NULL;
699
  char *start = body;
700
  char *errstring = NULL;
701
  const int clear_first = 1;
702

703
  char *config;
704
  smartlist_t *entries = smartlist_new();
705
706
707
708
709
710
711
712
713
714
715
716

  /* We have a string, "body", of the format '(key(=val|="val")?)' entries
   * separated by space.  break it into a list of configuration entries. */
  while (*body) {
    char *eq = body;
    char *key;
    char *entry;
    while (!TOR_ISSPACE(*eq) && *eq != '=')
      ++eq;
    key = tor_strndup(body, eq-body);
    body = eq+1;
    if (*eq == '=') {
Roger Dingledine's avatar
Roger Dingledine committed
717
718
      char *val=NULL;
      size_t val_len=0;
719
720
721
722
723
724
      if (*body != '\"') {
        char *val_start = body;
        while (!TOR_ISSPACE(*body))
          body++;
        val = tor_strndup(val_start, body-val_start);
        val_len = strlen(val);
725
      } else {
726
727
        body = (char*)extract_escaped_string(body, (len - (body-start)),
                                             &val, &val_len);
728
729
730
731
        if (!body) {
          connection_write_str_to_buf("551 Couldn't parse string\r\n", conn);
          SMARTLIST_FOREACH(entries, char *, cp, tor_free(cp));
          smartlist_free(entries);
732
          tor_free(key);
733
734
          return 0;
        }
735
      }
736
      tor_asprintf(&entry, "%s %s", key, val);
737
738
739
740
      tor_free(key);
      tor_free(val);
    } else {
      entry = key;
741
    }
742
743
744
745
    smartlist_add(entries, entry);
    while (TOR_ISSPACE(*body))
      ++body;
  }
746

747
748
749
750
  smartlist_add(entries, tor_strdup(""));
  config = smartlist_join_strings(entries, "\n", 0, NULL);
  SMARTLIST_FOREACH(entries, char *, cp, tor_free(cp));
  smartlist_free(entries);
751

752
  if (config_get_lines(config, &lines, 0) < 0) {
753
754
755
    log_warn(LD_CONTROL,"Controller gave us config lines we can't parse.");
    connection_write_str_to_buf("551 Couldn't parse configuration\r\n",
                                conn);
756
    tor_free(config);
757
    return 0;
758
  }
759
  tor_free(config);
760

761
762
  opt_err = options_trial_assign(lines, use_defaults, clear_first, &errstring);
  {
763
    const char *msg;
764
765
    switch (opt_err) {
      case SETOPT_ERR_MISC:
766
        msg = "552 Unrecognized option";
767
        break;
768
      case SETOPT_ERR_PARSE:
Roger Dingledine's avatar
Roger Dingledine committed
769
        msg = "513 Unacceptable option value";
770
        break;
771
      case SETOPT_ERR_TRANSITION:
772
        msg = "553 Transition not allowed";
773
        break;
774
      case SETOPT_ERR_SETTING:
775
      default:
776
        msg = "553 Unable to set option";
777
        break;
778
      case SETOPT_OK:
779
780
781
        config_free_lines(lines);
        send_control_done(conn);
        return 0;
782
    }
783
784
785
    log_warn(LD_CONTROL,
             "Controller gave us config lines that didn't validate: %s",
             errstring);
786
    connection_printf_to_buf(conn, "%s: %s\r\n", msg, errstring);
787
    config_free_lines(lines);
788
    tor_free(errstring);
789
790
    return 0;
  }
791
}
792

793
/** Called when we receive a SETCONF message: parse the body and try
794
795
 * to update our configuration.  Reply with a DONE or ERROR message.
 * Modifies the contents of body.*/
796
static int
797
handle_control_setconf(control_connection_t *conn, uint32_t len, char *body)
798
{
799
  return control_setconf_helper(conn, len, body, 0);
800
801
802
}

/** Called when we receive a RESETCONF message: parse the body and try
803
804
 * to update our configuration.  Reply with a DONE or ERROR message.
 * Modifies the contents of body. */
805
static int
806
handle_control_resetconf(control_connection_t *conn, uint32_t len, char *body)
807
{
808
  return control_setconf_helper(conn, len, body, 1);
809
810
}

Nick Mathewson's avatar
Nick Mathewson committed
811
812
/** Called when we receive a GETCONF message.  Parse the request, and
 * reply with a CONFVALUE or an ERROR message */
813
static int
814
815
handle_control_getconf(control_connection_t *conn, uint32_t body_len,
                       const char *body)
816
{
817
818
819
  smartlist_t *questions = smartlist_new();
  smartlist_t *answers = smartlist_new();
  smartlist_t *unrecognized = smartlist_new();
820
821
  char *msg = NULL;
  size_t msg_len;
822
  const or_options_t *options = get_options();
823
  int i, len;
824

Nick Mathewson's avatar
Nick Mathewson committed
825
  (void) body_len; /* body is NUL-terminated; so we can ignore len. */
826
827
  smartlist_split_string(questions, body, " ",
                         SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
828
  SMARTLIST_FOREACH_BEGIN(questions, const char *, q) {
829
    if (!option_is_recognized(q)) {
830
      smartlist_add(unrecognized, (char*) q);
831
    } else {
832
      config_line_t *answer = option_get_assignment(options,q);
833
      if (!answer) {
834
        const char *name = option_get_canonical_name(q);
835
        smartlist_add_asprintf(answers, "250-%s\r\n", name);
836
      }
837

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

843
        next = answer->next;
844
845
        tor_free(answer->key);
        tor_free(answer->value);
846
847
848
849
        tor_free(answer);
        answer = next;
      }
    }
850
  } SMARTLIST_FOREACH_END(q);
851

852
853
854
  if ((len = smartlist_len(unrecognized))) {
    for (i=0; i < len-1; ++i)
      connection_printf_to_buf(conn,
855
856
                               "552-Unrecognized configuration key \"%s\"\r\n",
                               (char*)smartlist_get(unrecognized, i));
857
858
859
860
861
862