control.c 122 KB
Newer Older
1
2
/* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
 * Copyright (c) 2007, The Tor Project, Inc. */
3
4
/* See LICENSE for licensing information */
/* $Id$ */
5
6
const char control_c_id[] =
  "$Id$";
7

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

14
15
#define CONTROL_PRIVATE

16
17
#include "or.h"

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

22
/* Recognized asynchronous event types.  It's okay to expand this list
23
 * because it is used both as a list of v0 event types, and as indices
24
25
 * into the bitfield to determine which controllers want which events.
 */
Roger Dingledine's avatar
Roger Dingledine committed
26
27
28
29
30
#define _EVENT_MIN             0x0001
#define EVENT_CIRCUIT_STATUS   0x0001
#define EVENT_STREAM_STATUS    0x0002
#define EVENT_OR_CONN_STATUS   0x0003
#define EVENT_BANDWIDTH_USED   0x0004
31
#define EVENT_LOG_OBSOLETE     0x0005 /* Can reclaim this. */
Roger Dingledine's avatar
Roger Dingledine committed
32
33
34
35
36
37
38
#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
39
// #define EVENT_AUTHDIR_NEWDESCS 0x000D
Roger Dingledine's avatar
Roger Dingledine committed
40
#define EVENT_DESCCHANGED      0x000E
41
#define EVENT_NS               0x000F
42
43
44
#define EVENT_STATUS_CLIENT    0x0010
#define EVENT_STATUS_SERVER    0x0011
#define EVENT_STATUS_GENERAL   0x0012
45
#define EVENT_GUARD            0x0013
46
47
#define EVENT_STREAM_BANDWIDTH_USED   0x0014
#define _EVENT_MAX             0x0014
48
/* If _EVENT_MAX ever hits 0x0020, we need to make the mask wider. */
49

50
/** Bitfield: The bit 1&lt;&lt;e is set if <b>any</b> open control
Nick Mathewson's avatar
Nick Mathewson committed
51
52
 * 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
53
 * has interest in without having to walk over the global connection
Nick Mathewson's avatar
Nick Mathewson committed
54
55
 * list to find out.
 **/
56
57
58
typedef uint32_t event_mask_t;
static event_mask_t global_event_mask1long = 0;
static event_mask_t global_event_mask1short = 0;
59

60
61
62
/** 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
63
64
/** Macro: true if any control connection is interested in events of type
 * <b>e</b>. */
65
#define EVENT_IS_INTERESTING(e) \
66
67
68
  ((global_event_mask1long|global_event_mask1short) & (1<<(e)))
#define EVENT_IS_INTERESTING1L(e) (global_event_mask1long & (1<<(e)))
#define EVENT_IS_INTERESTING1S(e) (global_event_mask1short & (1<<(e)))
Nick Mathewson's avatar
Nick Mathewson committed
69
70
71

/** If we're using cookie-type authentication, how long should our cookies be?
 */
72
#define AUTHENTICATION_COOKIE_LEN 32
Nick Mathewson's avatar
Nick Mathewson committed
73
74
75

/** If true, we've set authentication_cookie to a secret code and
 * stored it to disk. */
76
77
78
static int authentication_cookie_is_set = 0;
static char authentication_cookie[AUTHENTICATION_COOKIE_LEN];

79
80
81
82
83
84
85
#define SHORT_NAMES 1
#define LONG_NAMES 2
#define ALL_NAMES (SHORT_NAMES|LONG_NAMES)
#define EXTENDED_FORMAT 4
#define NONEXTENDED_FORMAT 8
#define ALL_FORMATS (EXTENDED_FORMAT|NONEXTENDED_FORMAT)
typedef int event_format_t;
86

87
static void connection_printf_to_buf(control_connection_t *conn,
88
                                     const char *format, ...)
89
  CHECK_PRINTF(2,3);
90
static void send_control_done(control_connection_t *conn);
91
92
static void send_control_event(uint16_t event, event_format_t which,
                               const char *format, ...)
93
  CHECK_PRINTF(3,4);
94
static void send_control_event_extended(uint16_t event, event_format_t which,
95
96
                                         const char *format, ...)
  CHECK_PRINTF(3,4);
97
static int handle_control_setconf(control_connection_t *conn, uint32_t len,
98
                                  char *body);
99
static int handle_control_resetconf(control_connection_t *conn, uint32_t len,
100
                                    char *body);
101
static int handle_control_getconf(control_connection_t *conn, uint32_t len,
102
                                  const char *body);
103
static int handle_control_setevents(control_connection_t *conn, uint32_t len,
104
                                    const char *body);
105
106
static int handle_control_authenticate(control_connection_t *conn,
                                       uint32_t len,
107
                                       const char *body);
108
static int handle_control_saveconf(control_connection_t *conn, uint32_t len,
109
                                   const char *body);
110
static int handle_control_signal(control_connection_t *conn, uint32_t len,
111
                                 const char *body);
112
static int handle_control_mapaddress(control_connection_t *conn, uint32_t len,
113
                                     const char *body);
114
static char *list_getinfo_options(void);
115
static int handle_control_getinfo(control_connection_t *conn, uint32_t len,
116
                                  const char *body);
117
118
static int handle_control_extendcircuit(control_connection_t *conn,
                                        uint32_t len,
119
                                        const char *body);
120
121
static int handle_control_setcircuitpurpose(control_connection_t *conn,
                                            uint32_t len, const char *body);
122
123
static int handle_control_attachstream(control_connection_t *conn,
                                       uint32_t len,
124
                                        const char *body);
125
126
static int handle_control_postdescriptor(control_connection_t *conn,
                                         uint32_t len,
127
                                         const char *body);
128
129
static int handle_control_redirectstream(control_connection_t *conn,
                                         uint32_t len,
130
                                         const char *body);
131
static int handle_control_closestream(control_connection_t *conn, uint32_t len,
132
                                      const char *body);
133
134
static int handle_control_closecircuit(control_connection_t *conn,
                                       uint32_t len,
135
                                       const char *body);
136
137
static int handle_control_resolve(control_connection_t *conn, uint32_t len,
                                  const char *body);
138
139
140
static int handle_control_usefeature(control_connection_t *conn,
                                     uint32_t len,
                                     const char *body);
141
static int write_stream_target_to_buf(edge_connection_t *conn, char *buf,
142
                                      size_t len);
143
144
static void orconn_target_get_name(int long_names, char *buf, size_t len,
                                   or_connection_t *conn);
145
static char *get_cookie_file(void);
146

147
148
/** Given a control event code for a message event, return the corresponding
 * log severity. */
149
150
151
152
153
154
155
156
157
158
159
160
161
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;
  }
}

162
/** Given a log severity, return the corresponding control event code. */
163
164
165
166
167
168
169
170
171
172
173
174
175
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;
  }
}

176
177
/** Set <b>global_event_mask*</b> to the bitwise OR of each live control
 * connection's event_mask field. */
178
179
void
control_update_global_event_mask(void)
180
{
181
  smartlist_t *conns = get_connection_array();
182
  event_mask_t old_mask, new_mask;
183
  old_mask = global_event_mask1short;
184
185
  old_mask |= global_event_mask1long;

186
187
  global_event_mask1short = 0;
  global_event_mask1long = 0;
188
189
190
191
192
  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);
193
      if (conn->use_long_names)
194
        global_event_mask1long |= conn->event_mask;
195
      else
196
        global_event_mask1short |= conn->event_mask;
197
    }
198
  });
199

200
  new_mask = global_event_mask1short;
201
202
203
204
  new_mask |= global_event_mask1long;

  /* Handle the aftermath.  Set up the log callback to tell us only what
   * we want to hear...*/
205
  control_adjust_event_log_severity();
206
207
208
209
210

  /* ...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)) {
211
212
213
214
215
    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;
216
      }
217
    });
218
  }
219
220
}

221
222
223
/** 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. */
224
void
225
control_adjust_event_log_severity(void)
226
{
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
  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;
    }
  }
242
243
  if (EVENT_IS_INTERESTING(EVENT_LOG_OBSOLETE) ||
      EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL)) {
244
245
246
247
248
249
250
251
    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;
  }
  change_callback_log_severity(event_to_log_severity(min_log_event),
                               event_to_log_severity(max_log_event),
                               control_event_logmsg);
252
253
}

254
255
256
257
258
259
260
261
262
263
/** 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);
}

264
/** Append a NUL-terminated string <b>s</b> to the end of
265
 * <b>conn</b>-\>outbuf.
266
 */
267
static INLINE void
268
connection_write_str_to_buf(const char *s, control_connection_t *conn)
269
270
{
  size_t len = strlen(s);
271
  connection_write_to_buf(s, len, TO_CONN(conn));
272
273
}

274
/** Given a <b>len</b>-character string in <b>data</b>, made of lines
275
276
277
278
279
 * 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
 * that that appears at the start of a line, and adding a period-CRLF line at
 * the end. Replace all LF characters sequences with CRLF.  Return the number
 * of bytes in *<b>out</b>.
280
281
 */
/* static */ size_t
282
write_escaped_data(const char *data, size_t len, char **out)
283
284
285
{
  size_t sz_out = len+8;
  char *outp;
286
  const char *start = data, *end;
287
288
  int i;
  int start_of_line;
Nick Mathewson's avatar
Nick Mathewson committed
289
  for (i=0; i<(int)len; ++i) {
290
    if (data[i]== '\n')
291
      sz_out += 2; /* Maybe add a CR; maybe add a dot. */
292
293
294
295
296
297
  }
  *out = outp = tor_malloc(sz_out+1);
  end = data+len;
  start_of_line = 1;
  while (data < end) {
    if (*data == '\n') {
298
      if (data > start && data[-1] != '\r')
299
300
301
302
303
304
305
306
307
308
309
310
        *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++;
  }
311
312
313
314
  if (outp < *out+2 || memcmp(outp-2, "\r\n", 2)) {
    *outp++ = '\r';
    *outp++ = '\n';
  }
315
316
317
  *outp++ = '.';
  *outp++ = '\r';
  *outp++ = '\n';
318
  *outp = '\0'; /* NUL-terminate just in case. */
319
  tor_assert((outp - *out) <= (int)sz_out);
320
321
322
  return outp - *out;
}

323
324
325
/** 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
326
327
 * that appears at the start of a line, and replacing all CRLF sequences
 * with LF.   Return the number of
328
 * bytes in *<b>out</b>. */
329
/* static */ size_t
330
read_escaped_data(const char *data, size_t len, char **out)
331
332
333
{
  char *outp;
  const char *next;
334
335
336
  const char *end;

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

338
  end = data+len;
339

340
  while (data < end) {
341
    /* we're at the start of a line. */
342
343
    if (*data == '.')
      ++data;
344
    next = memchr(data, '\n', end-data);
345
    if (next) {
346
347
348
349
350
351
352
353
      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. */
354
    } else {
355
356
357
      memcpy(outp, data, end-data);
      outp += (end-data);
      *outp = '\0';
358
359
      return outp - *out;
    }
360
    *outp++ = '\n';
361
362
  }

363
  *outp = '\0';
364
365
  return outp - *out;
}
366

367
/** Given a pointer to a string starting at <b>start</b> containing
368
 * <b>in_len_max</b> characters, decode a string beginning with one double
369
 * quote, containing any number of non-quote characters or characters escaped
370
 * with a backslash, and ending with a final double quote.  Place the resulting
371
372
373
 * 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
374
 * NULL. */
375
static const char *
376
377
get_escaped_string(const char *start, size_t in_len_max,
                   char **out, size_t *out_len)
378
{
379
380
381
382
383
384
385
386
387
  const char *cp, *end;
  char *outp;
  size_t len=0;

  if (*start != '\"')
    return NULL;

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

389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
  /* Calculate length. */
  while (1) {
    if (cp >= end)
      return NULL;
    else if (*cp == '\\') {
      if (++cp == end)
        return NULL; /* Can't escape EOS. */
      ++cp;
      ++len;
    } else if (*cp == '\"') {
      break;
    } else {
      ++cp;
      ++len;
    }
  }
  end = cp;
  outp = *out = tor_malloc(len+1);
  *out_len = len;
408

409
410
411
412
413
414
415
  cp = start+1;
  while (cp < end) {
    if (*cp == '\\')
      ++cp;
    *outp++ = *cp++;
  }
  *outp = '\0';
416
  tor_assert((outp - *out) == (int)*out_len);
417
418
419
420

  return end+1;
}

421
422
423
/** Acts like sprintf, but writes its formatted string to the end of
 * <b>conn</b>-\>outbuf.  The message may be truncated if it is too long,
 * but it will always end with a CRLF sequence.
424
425
 *
 * Currently the length of the message is limited to 1024 (including the
426
 * ending \r\n\0. */
427
static void
428
connection_printf_to_buf(control_connection_t *conn, const char *format, ...)
429
{
430
#define CONNECTION_PRINTF_TO_BUF_BUFFERSIZE 1024
431
  va_list ap;
432
  char buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE];
433
434
435
  int r;
  size_t len;
  va_start(ap,format);
436
  r = tor_vsnprintf(buf, sizeof(buf), format, ap);
437
  va_end(ap);
438
439
440
441
  if (r<0) {
    log_warn(LD_BUG, "Unable to format string for controller.");
    return;
  }
442
443
  len = strlen(buf);
  if (memcmp("\r\n\0", buf+len-2, 3)) {
444
445
446
    buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE-1] = '\0';
    buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE-2] = '\n';
    buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE-3] = '\r';
447
  }
448
  connection_write_to_buf(buf, len, TO_CONN(conn));
449
450
}

451
/** Send a "DONE" message down the control connection <b>conn</b>. */
452
static void
453
send_control_done(control_connection_t *conn)
454
{
455
  connection_write_str_to_buf("250 OK\r\n", conn);
456
457
}

458
/* Send an event to all v1 controllers that are listening for code
459
460
 * <b>event</b>.  The event's body is given by <b>msg</b>.
 *
461
462
 * 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
463
 * <b>which</b> & LONG_NAMES, the event contains long-format names: send it
464
465
 * to contollers that <em>have</em> enabled VERBOSE_NAMES.
 *
466
 * The EXTENDED_FORMAT and NONEXTENDED_FORMAT flags behave similarly with
467
 * respect to the EXTENDED_EVENTS feature. */
468
static void
469
470
send_control_event_string(uint16_t event, event_format_t which,
                          const char *msg)
471
{
472
  smartlist_t *conns = get_connection_array();
473
474
  tor_assert(event >= _EVENT_MIN && event <= _EVENT_MAX);

475
476
477
478
479
480
  SMARTLIST_FOREACH(conns, connection_t *, conn,
  {
    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);
481
482
483
484
485
      if (control_conn->use_long_names) {
        if (!(which & LONG_NAMES))
          continue;
      } else {
        if (!(which & SHORT_NAMES))
486
          continue;
487
488
489
490
491
492
      }
      if (control_conn->use_extended_events) {
        if (!(which & EXTENDED_FORMAT))
          continue;
      } else {
        if (!(which & NONEXTENDED_FORMAT))
493
494
          continue;
      }
495
      if (control_conn->event_mask & (1<<event)) {
496
        int is_err = 0;
497
498
        connection_write_to_buf(msg, strlen(msg), TO_CONN(control_conn));
        if (event == EVENT_ERR_MSG)
499
500
501
502
503
504
505
506
          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)
507
          connection_handle_write(TO_CONN(control_conn), 1);
508
      }
509
    }
510
  });
511
512
}

513
514
515
516
517
518
519
520
521
522
/** Helper for send_control1_event and send_control1_event_extended:
 * 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
 * <b>format</b>, and other arguments as provided.
 *
 * If <b>extended</b> is true, and the format contains a single '@' character,
 * it will be replaced with a space and all text after that character will be
 * sent only to controllers that have enabled extended events.
 *
 * Currently the length of the message is limited to 1024 (including the
Roger Dingledine's avatar
Roger Dingledine committed
523
 * ending \n\r\0). */
524
static void
525
send_control_event_impl(uint16_t event, event_format_t which, int extended,
526
                         const char *format, va_list ap)
527
{
528
529
  /* This is just a little longer than the longest allowed log message */
#define SEND_CONTROL1_EVENT_BUFFERSIZE 10064
530
  int r;
531
  char buf[SEND_CONTROL1_EVENT_BUFFERSIZE];
532
  size_t len;
533
  char *cp;
534
535

  r = tor_vsnprintf(buf, sizeof(buf), format, ap);
536
537
538
539
  if (r<0) {
    log_warn(LD_BUG, "Unable to format event for controller.");
    return;
  }
540
541
542
543
544
545
546
547
548

  len = strlen(buf);
  if (memcmp("\r\n\0", buf+len-2, 3)) {
    /* if it is not properly terminated, do it now */
    buf[SEND_CONTROL1_EVENT_BUFFERSIZE-1] = '\0';
    buf[SEND_CONTROL1_EVENT_BUFFERSIZE-2] = '\n';
    buf[SEND_CONTROL1_EVENT_BUFFERSIZE-3] = '\r';
  }

549
550
551
  if (extended && (cp = strchr(buf, '@'))) {
    which &= ~ALL_FORMATS;
    *cp = ' ';
552
    send_control_event_string(event, which|EXTENDED_FORMAT, buf);
553
    memcpy(cp, "\r\n\0", 3);
554
    send_control_event_string(event, which|NONEXTENDED_FORMAT, buf);
555
  } else {
556
    send_control_event_string(event, which|ALL_FORMATS, buf);
557
558
559
560
561
562
563
564
565
566
  }
}

/* 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
 * <b>format</b>, and other arguments as provided.
 *
 * Currently the length of the message is limited to 1024 (including the
 * ending \n\r\0. */
static void
567
send_control_event(uint16_t event, event_format_t which,
568
569
570
571
                    const char *format, ...)
{
  va_list ap;
  va_start(ap, format);
572
  send_control_event_impl(event, which, 0, format, ap);
573
574
575
576
577
578
579
580
581
582
583
584
585
586
  va_end(ap);
}

/* 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
 * <b>format</b>, and other arguments as provided.
 *
 * If the format contains a single '@' character, it will be replaced with a
 * space and all text after that character will be sent only to controllers
 * that have enabled extended events.
 *
 * Currently the length of the message is limited to 1024 (including the
 * ending \n\r\0. */
static void
587
send_control_event_extended(uint16_t event, event_format_t which,
588
589
590
591
                             const char *format, ...)
{
  va_list ap;
  va_start(ap, format);
592
  send_control_event_impl(event, which, 1, format, ap);
593
  va_end(ap);
594
595
}

596
/** Given a text circuit <b>id</b>, return the corresponding circuit. */
597
static origin_circuit_t *
598
599
600
601
602
603
604
605
606
607
get_circ(const char *id)
{
  unsigned long n_id;
  int ok;
  n_id = tor_parse_ulong(id, 10, 0, ULONG_MAX, &ok, NULL);
  if (!ok)
    return NULL;
  return circuit_get_by_global_id(n_id);
}

608
/** Given a text stream <b>id</b>, return the corresponding AP connection. */
609
static edge_connection_t *
610
611
612
613
get_stream(const char *id)
{
  unsigned long n_id;
  int ok;
614
  edge_connection_t *conn;
615
616
617
618
  n_id = tor_parse_ulong(id, 10, 0, ULONG_MAX, &ok, NULL);
  if (!ok)
    return NULL;
  conn = connection_get_by_global_id(n_id);
619
  if (!conn || conn->_base.type != CONN_TYPE_AP)
620
621
622
623
    return NULL;
  return conn;
}

624
/** Helper for setconf and resetconf. Acts like setconf, except
625
626
 * it passes <b>use_defaults</b> on to options_trial_assign().  Modifies the
 * contents of body.
627
 */
628
static int
629
control_setconf_helper(control_connection_t *conn, uint32_t len, char *body,
630
                       int use_defaults)
631
{
Nick Mathewson's avatar
Nick Mathewson committed
632
  int r;
633
  config_line_t *lines=NULL;
634
  char *start = body;
635
  char *errstring = NULL;
636
  const int clear_first = 1;
637

638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
  char *config;
  smartlist_t *entries = smartlist_create();

  /* 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 == '=') {
      char *val;
      size_t val_len;
      size_t ent_len;
      if (*body != '\"') {
        char *val_start = body;
        while (!TOR_ISSPACE(*body))
          body++;
        val = tor_strndup(val_start, body-val_start);
        val_len = strlen(val);
661
      } else {
662
663
664
665
666
667
668
669
        body = (char*)get_escaped_string(body, (len - (body-start)),
                                         &val, &val_len);
        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);
          return 0;
        }
670
      }
671
672
673
674
675
676
677
      ent_len = strlen(key)+val_len+3;
      entry = tor_malloc(ent_len+1);
      tor_snprintf(entry, ent_len, "%s %s", key, val);
      tor_free(key);
      tor_free(val);
    } else {
      entry = key;
678
    }
679
680
681
682
    smartlist_add(entries, entry);
    while (TOR_ISSPACE(*body))
      ++body;
  }
683

684
685
686
687
  smartlist_add(entries, tor_strdup(""));
  config = smartlist_join_strings(entries, "\n", 0, NULL);
  SMARTLIST_FOREACH(entries, char *, cp, tor_free(cp));
  smartlist_free(entries);
688

689
690
691
692
  if (config_get_lines(config, &lines) < 0) {
    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);
693
    tor_free(config);
694
    return 0;
695
  }
696
  tor_free(config);
697

698
699
  if ((r=options_trial_assign(lines, use_defaults,
                              clear_first, &errstring)) < 0) {
700
    const char *msg;
Roger Dingledine's avatar
Roger Dingledine committed
701
    log_warn(LD_CONTROL,
702
             "Controller gave us config lines that didn't validate: %s",
703
             errstring);
704
705
    switch (r) {
      case -1:
706
        msg = "552 Unrecognized option";
707
708
        break;
      case -2:
Roger Dingledine's avatar
Roger Dingledine committed
709
        msg = "513 Unacceptable option value";
710
711
        break;
      case -3:
712
        msg = "553 Transition not allowed";
713
714
715
        break;
      case -4:
      default:
716
        msg = "553 Unable to set option";
717
718
        break;
    }
719
    connection_printf_to_buf(conn, "%s: %s\r\n", msg, errstring);
720
    config_free_lines(lines);
721
    tor_free(errstring);
722
723
    return 0;
  }
724
  config_free_lines(lines);
725
  send_control_done(conn);
726
727
  return 0;
}
728

729
/** Called when we receive a SETCONF message: parse the body and try
730
731
 * to update our configuration.  Reply with a DONE or ERROR message.
 * Modifies the contents of body.*/
732
static int
733
handle_control_setconf(control_connection_t *conn, uint32_t len, char *body)
734
{
735
  return control_setconf_helper(conn, len, body, 0);
736
737
738
}

/** Called when we receive a RESETCONF message: parse the body and try
739
740
 * to update our configuration.  Reply with a DONE or ERROR message.
 * Modifies the contents of body. */
741
static int
742
handle_control_resetconf(control_connection_t *conn, uint32_t len, char *body)
743
{
744
  return control_setconf_helper(conn, len, body, 1);
745
746
}

Nick Mathewson's avatar
Nick Mathewson committed
747
748
/** Called when we receive a GETCONF message.  Parse the request, and
 * reply with a CONFVALUE or an ERROR message */
749
static int
750
751
handle_control_getconf(control_connection_t *conn, uint32_t body_len,
                       const char *body)
752
{
753
754
  smartlist_t *questions = NULL;
  smartlist_t *answers = NULL;
755
  smartlist_t *unrecognized = NULL;
756
757
  char *msg = NULL;
  size_t msg_len;
758
  or_options_t *options = get_options();
759
  int i, len;
760

761
  questions = smartlist_create();
762
  (void) body_len; /* body is nul-terminated; so we can ignore len. */
763
764
  smartlist_split_string(questions, body, " ",
                         SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
765
  answers = smartlist_create();
766
767
  unrecognized = smartlist_create();
  SMARTLIST_FOREACH(questions, char *, q,
768
  {
769
    if (!option_is_recognized(q)) {
770
      smartlist_add(unrecognized, q);
771
    } else {
772
      config_line_t *answer = option_get_assignment(options,q);
773
      if (!answer) {
774
        const char *name = option_get_canonical_name(q);
775
        size_t alen = strlen(name)+8;
776
        char *astr = tor_malloc(alen);
777
        tor_snprintf(astr, alen, "250-%s\r\n", name);
778
779
        smartlist_add(answers, astr);
      }
780

781
      while (answer) {
782
        config_line_t *next;
783
        size_t alen = strlen(answer->key)+strlen(answer->value)+8;
784
        char *astr = tor_malloc(alen);
785
786
        tor_snprintf(astr, alen, "250-%s=%s\r\n",
                     answer->key, answer->value);
787
788
        smartlist_add(answers, astr);

789
        next = answer->next;
790
791
        tor_free(answer->key);
        tor_free(answer->value);
792
793
794
795
        tor_free(answer);
        answer = next;
      }
    }
796
  });
797

798
799
800
  if ((len = smartlist_len(unrecognized))) {
    for (i=0; i < len-1; ++i)
      connection_printf_to_buf(conn,
801
802
                               "552-Unrecognized configuration key \"%s\"\r\n",
                               (char*)smartlist_get(unrecognized, i));
803
804
805
806
807
808
809
810
811
812
813
    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_write_to_buf(msg, msg_len, TO_CONN(conn));
  } else {
    connection_write_str_to_buf("250 OK\r\n", conn);
814
  }
815

816
817
818
819
820
821
822
823
  if (answers) {
    SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
    smartlist_free(answers);
  }
  if (questions) {
    SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
    smartlist_free(questions);
  }
824
  smartlist_free(unrecognized);
825
826
  tor_free(msg);

827
828
  return 0;
}
829

Nick Mathewson's avatar
Nick Mathewson committed
830
831
832
/** Called when we get a SETEVENTS message: update conn->event_mask,
 * and reply with DONE or ERROR. */
static int
833
834
handle_control_setevents(control_connection_t *conn, uint32_t len,
                         const char *body)
835
836
837
{
  uint16_t event_code;
  uint32_t event_mask = 0;
838
  unsigned int extended = 0;
839
840
  smartlist_t *events = smartlist_create();

841
  (void) len;
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
  smartlist_split_string(events, body, " ",
                         SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  SMARTLIST_FOREACH(events, const char *, ev,
    {
      if (!strcasecmp(ev, "EXTENDED")) {
        extended = 1;
        continue;
      } else if (!strcasecmp(ev, "CIRC"))
        event_code = EVENT_CIRCUIT_STATUS;
      else if (!strcasecmp(ev, "STREAM"))
        event_code = EVENT_STREAM_STATUS;
      else if (!strcasecmp(ev, "ORCONN"))
        event_code = EVENT_OR_CONN_STATUS;
      else if (!strcasecmp(ev, "BW"))
        event_code = EVENT_BANDWIDTH_USED;
      else if (!strcasecmp(ev, "DEBUG"))
        event_code = EVENT_DEBUG_MSG;
      else if (!strcasecmp(ev, "INFO"))
        event_code = EVENT_INFO_MSG;
      else if (!strcasecmp(ev, "NOTICE"))
        event_code = EVENT_NOTICE_MSG;
      else if (!strcasecmp(ev, "WARN"))
        event_code = EVENT_WARN_MSG;
      else if (!strcasecmp(ev, "ERR"))
        event_code = EVENT_ERR_MSG;
      else if (!strcasecmp(ev, "NEWDESC"))
        event_code = EVENT_NEW_DESC;
      else if (!strcasecmp(ev, "ADDRMAP"))
        event_code = EVENT_ADDRMAP;
      else if (!strcasecmp(ev, "AUTHDIR_NEWDESCS"))
        event_code = EVENT_AUTHDIR_NEWDESCS;
      else if (!strcasecmp(ev, "DESCCHANGED"))
        event_code = EVENT_DESCCHANGED;
      else if (!strcasecmp(ev, "NS"))
        event_code = EVENT_NS;
      else if (!strcasecmp(ev, "STATUS_GENERAL"))
        event_code = EVENT_STATUS_GENERAL;
      else if (!strcasecmp(ev, "STATUS_CLIENT"))
        event_code = EVENT_STATUS_CLIENT;
      else if (!strcasecmp(ev, "STATUS_SERVER"))
        event_code = EVENT_STATUS_SERVER;
      else if (!strcasecmp(ev, "GUARD"))
        event_code = EVENT_GUARD;
      else if (!strcasecmp(ev, "GUARDS")) {
887
888
889
        /* XXXX021 This check is here to tolerate the controllers that
         * depended on the buggy spec in 0.1.2.5-alpha through 0.1.2.10-rc.
         * Once those versions are obsolete, stop supporting this. */
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
        log_warn(LD_CONTROL, "Controller used obsolete 'GUARDS' event name; "
                 "use GUARD instead.");
        event_code = EVENT_GUARD;
      } else if (!strcasecmp(ev, "STREAM_BW"))
        event_code = EVENT_STREAM_BANDWIDTH_USED;
      else {
        connection_printf_to_buf(conn, "552 Unrecognized event \"%s\"\r\n",
                                 ev);
        SMARTLIST_FOREACH(events, char *, e, tor_free(e));
        smartlist_free(events);
        return 0;
      }
      event_mask |= (1 << event_code);
    });
  SMARTLIST_FOREACH(events, char *, e, tor_free(e));
  smartlist_free(events);

907
  conn->event_mask = event_mask;
908
909
  if (extended)
    conn->use_extended_events = 1;
910

911
  control_update_global_event_mask();
912
913
914
  send_control_done(conn);
  return 0;
}
915

916
917
918
/** Decode the hashed, base64'd passwords stored in <b>passwords</b>.
 * Return a smartlist of acceptable passwords (unterminated strings of
 * length S2K_SPECIFIER_LEN+DIGEST_LEN) on success, or NULL on failure.
919
 */
920
921
smartlist_t *
decode_hashed_passwords(config_line_t *passwords)
922
923
{
  char decoded[64];
924
925
926
927
928
929
930
931
932
933
934
935
  config_line_t *cl;
  smartlist_t *sl = smartlist_create();

  tor_assert(passwords);

  for (cl = passwords; cl; cl = cl->next) {
    const char *hashed = cl->value;

    if (!strcmpstart(hashed, "16:")) {
      if (base16_decode(decoded, sizeof(decoded), hashed+3, strlen(hashed+3))<0
          || strlen(hashed+3) != (S2K_SPECIFIER_LEN+DIGEST_LEN)*2) {
        goto err;
936
      }
937
938
939
940
941
942
943
    } else {
        if (base64_decode(decoded, sizeof(decoded), hashed, strlen(hashed))
            != S2K_SPECIFIER_LEN+DIGEST_LEN) {
          goto err;
        }
    }
    smartlist_add(sl, tor_memdup(decoded, S2K_SPECIFIER_LEN+DIGEST_LEN));
944
  }
945
946
947
948
949
950
951

  return sl;

 err:
  SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
  smartlist_free(sl);
  return NULL;
952
953
}

Nick Mathewson's avatar
Nick Mathewson committed
954
955
956
957
958
/** Called when we get an AUTHENTICATE message.  Check whether the
 * authentication is valid, and if so, update the connection's state to
 * OPEN.  Reply with DONE or ERROR.
 */
static int
959
960
handle_control_authenticate(control_connection_t *conn, uint32_t len,
                            const char *body)
961
{
962
  int used_quoted_string = 0;
963
  or_options_t *options = get_options();
964
  const char *errstr = NULL;
965
966
  char *password;
  size_t password_len;
967
968
  const char *cp;
  int i;
969
  int bad_cookie=0, bad_password=0;
970
  smartlist_t *sl = NULL;
971
972

  if (TOR_ISXDIGIT(body[0])) {
973
974
975
976
977
978
979
980
    cp = body;
    while (TOR_ISXDIGIT(*cp))
      ++cp;
    i = cp - body;
    tor_assert(i>0);
    password_len = i/2;
    password = tor_malloc(password_len + 1);
    if (base16_decode(password, password_len+1, body, i)<0) {
981
      connection_write_str_to_buf(
982
            "551 Invalid hexadecimal encoding.  Maybe you tried a plain text "
983
984
            "password?  If so, the standard requires that you put it in "
            "double quotes.\r\n", conn);
985
      connection_mark_for_close(TO_CONN(conn));
986
987
988
989
990
991
992
993
994
      tor_free(password);
      return 0;
    }
  } else if (TOR_ISSPACE(body[0])) {
    password = tor_strdup("");
    password_len = 0;
  } else {
    if (!get_escaped_string(body, len, &password, &password_len)) {
      connection_write_str_to_buf("551 Invalid quoted string.  You need "
995
            "to put the password in double quotes.\r\n", conn);
996
      connection_mark_for_close(TO_CONN(conn));
997
      return 0;
998
    }