control.c 121 KB
Newer Older
Roger Dingledine's avatar
Roger Dingledine committed
1
/* Copyright 2004-2006 Roger Dingledine, Nick Mathewson. */
2
3
/* See LICENSE for licensing information */
/* $Id$ */
4
5
const char control_c_id[] =
  "$Id$";
6

Nick Mathewson's avatar
Nick Mathewson committed
7
/**
8
9
 * \file control.c
 * \brief Implementation for Tor's control-socket interface.
10
 **/
Nick Mathewson's avatar
Nick Mathewson committed
11

12
13
#include "or.h"

14
#define STATE_IS_OPEN(s) ((s) == CONTROL_CONN_STATE_OPEN_V0 ||          \
15
                          (s) == CONTROL_CONN_STATE_OPEN_V1)
16
#define STATE_IS_V0(s) ((s) == CONTROL_CONN_STATE_NEEDAUTH_V0 ||        \
17
18
19
                        (s) == CONTROL_CONN_STATE_OPEN_V0)

/*
20
21
22
 * See control-spec.txt and control-spec-v0.txt for full details on
 * protocol(s).
 *
Nick Mathewson's avatar
Nick Mathewson committed
23
24
 */

25
26
/* Recognized version 0 message type codes; do not add new codes to this list.
 * Version 0 is dead; version 1 doesn't use codes. */
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#define CONTROL0_CMD_ERROR        0x0000
#define CONTROL0_CMD_DONE         0x0001
#define CONTROL0_CMD_SETCONF      0x0002
#define CONTROL0_CMD_GETCONF      0x0003
#define CONTROL0_CMD_CONFVALUE    0x0004
#define CONTROL0_CMD_SETEVENTS    0x0005
#define CONTROL0_CMD_EVENT        0x0006
#define CONTROL0_CMD_AUTHENTICATE 0x0007
#define CONTROL0_CMD_SAVECONF     0x0008
#define CONTROL0_CMD_SIGNAL       0x0009
#define CONTROL0_CMD_MAPADDRESS   0x000A
#define CONTROL0_CMD_GETINFO      0x000B
#define CONTROL0_CMD_INFOVALUE    0x000C
#define CONTROL0_CMD_EXTENDCIRCUIT  0x000D
#define CONTROL0_CMD_ATTACHSTREAM   0x000E
#define CONTROL0_CMD_POSTDESCRIPTOR 0x000F
#define CONTROL0_CMD_FRAGMENTHEADER 0x0010
#define CONTROL0_CMD_FRAGMENT       0x0011
#define CONTROL0_CMD_REDIRECTSTREAM 0x0012
#define CONTROL0_CMD_CLOSESTREAM    0x0013
#define CONTROL0_CMD_CLOSECIRCUIT   0x0014
#define _CONTROL0_CMD_MAX_RECOGNIZED 0x0014
49

50
/* Recognized version 0 error codes.  Do not expand. */
51
#define ERR_UNSPECIFIED             0x0000
Nick Mathewson's avatar
Nick Mathewson committed
52
53
54
55
56
57
58
59
#define ERR_INTERNAL                0x0001
#define ERR_UNRECOGNIZED_TYPE       0x0002
#define ERR_SYNTAX                  0x0003
#define ERR_UNRECOGNIZED_CONFIG_KEY 0x0004
#define ERR_INVALID_CONFIG_VALUE    0x0005
#define ERR_UNRECOGNIZED_EVENT_CODE 0x0006
#define ERR_UNAUTHORIZED            0x0007
#define ERR_REJECTED_AUTHENTICATION 0x0008
60
#define ERR_RESOURCE_EXHAUSETED     0x0009
61
62
#define ERR_NO_STREAM               0x000A
#define ERR_NO_CIRC                 0x000B
63
#define ERR_NO_ROUTER               0x000C
64

65
/* Recognized asynchronous event types.  It's okay to expand this list
66
 * because it is used both as a list of v0 event types, and as indices
67
68
 * into the bitfield to determine which controllers want which events.
 */
Roger Dingledine's avatar
Roger Dingledine committed
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#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
#define EVENT_LOG_OBSOLETE     0x0005
#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 LAST_V0_EVENT          0x000B
#define EVENT_ADDRMAP          0x000C
83
#define EVENT_AUTHDIR_NEWDESCS 0x000D
Roger Dingledine's avatar
Roger Dingledine committed
84
#define EVENT_DESCCHANGED      0x000E
85
#define EVENT_NS               0x000F
86
87
88
#define EVENT_STATUS_CLIENT    0x0010
#define EVENT_STATUS_SERVER    0x0011
#define EVENT_STATUS_GENERAL   0x0012
89
90
#define EVENT_GUARD            0x0013
#define _EVENT_MAX             0x0013
91
/* If _EVENT_MAX ever hits 0x0020, we need to make the mask wider. */
92

Nick Mathewson's avatar
Nick Mathewson committed
93
/** Array mapping from message type codes to human-readable message
94
 * type names. Used for compatibility with version 0 of the control
95
 * protocol.  Do not add new items to this list. */
96
static const char * CONTROL0_COMMANDS[_CONTROL0_CMD_MAX_RECOGNIZED+1] = {
97
98
99
100
101
102
103
104
  "error",
  "done",
  "setconf",
  "getconf",
  "confvalue",
  "setevents",
  "events",
  "authenticate",
105
  "saveconf",
106
107
108
109
110
111
  "signal",
  "mapaddress",
  "getinfo",
  "infovalue",
  "extendcircuit",
  "attachstream",
112
113
114
  "postdescriptor",
  "fragmentheader",
  "fragment",
115
116
117
  "redirectstream",
  "closestream",
  "closecircuit",
118
119
};

120
/** Bitfield: The bit 1&lt;&lt;e is set if <b>any</b> open control
Nick Mathewson's avatar
Nick Mathewson committed
121
122
 * 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
123
 * has interest in without having to walk over the global connection
Nick Mathewson's avatar
Nick Mathewson committed
124
125
 * list to find out.
 **/
126
static uint32_t global_event_mask0 = 0;
127
128
static uint32_t global_event_mask1long = 0;
static uint32_t global_event_mask1short = 0;
129

130
131
132
/** 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
133
134
/** Macro: true if any control connection is interested in events of type
 * <b>e</b>. */
135
#define EVENT_IS_INTERESTING0(e) (global_event_mask0 & (1<<(e)))
136
137
138
139
140
141
142
#define EVENT_IS_INTERESTING1(e) \
  ((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)))
#define EVENT_IS_INTERESTING(e)                                         \
  ((global_event_mask0|global_event_mask1short|global_event_mask1long)  \
   & (1<<(e)))
Nick Mathewson's avatar
Nick Mathewson committed
143
144
145

/** If we're using cookie-type authentication, how long should our cookies be?
 */
146
#define AUTHENTICATION_COOKIE_LEN 32
Nick Mathewson's avatar
Nick Mathewson committed
147
148
149

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

153
154
155
156
157
158
159
#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;
160

161
static void connection_printf_to_buf(control_connection_t *conn,
162
                                     const char *format, ...)
163
  CHECK_PRINTF(2,3);
164
165
166
167
/*static*/ size_t write_escaped_data(const char *data, size_t len,
                                     int translate_newlines, char **out);
/*static*/ size_t read_escaped_data(const char *data, size_t len,
                                    int translate_newlines,  char **out);
168
static void send_control0_message(control_connection_t *conn, uint16_t type,
169
                                 uint32_t len, const char *body);
170
171
static void send_control_done(control_connection_t *conn);
static void send_control_done2(control_connection_t *conn, const char *msg,
172
                               size_t len);
173
static void send_control0_error(control_connection_t *conn, uint16_t error,
174
                               const char *message);
175
176
static void send_control0_event(uint16_t event, uint32_t len,
                                const char *body);
177
static void send_control1_event(uint16_t event, event_format_t which,
178
179
                                const char *format, ...)
  CHECK_PRINTF(3,4);
180
181
182
static void send_control1_event_extended(uint16_t event, event_format_t which,
                                         const char *format, ...)
  CHECK_PRINTF(3,4);
183
static int handle_control_setconf(control_connection_t *conn, uint32_t len,
184
                                  char *body);
185
static int handle_control_resetconf(control_connection_t *conn, uint32_t len,
186
                                    char *body);
187
static int handle_control_getconf(control_connection_t *conn, uint32_t len,
188
                                  const char *body);
189
static int handle_control_setevents(control_connection_t *conn, uint32_t len,
190
                                    const char *body);
191
192
static int handle_control_authenticate(control_connection_t *conn,
                                       uint32_t len,
193
                                       const char *body);
194
static int handle_control_saveconf(control_connection_t *conn, uint32_t len,
195
                                   const char *body);
196
static int handle_control_signal(control_connection_t *conn, uint32_t len,
197
                                 const char *body);
198
static int handle_control_mapaddress(control_connection_t *conn, uint32_t len,
199
                                     const char *body);
200
static char *list_getinfo_options(void);
201
static int handle_control_getinfo(control_connection_t *conn, uint32_t len,
202
                                  const char *body);
203
204
static int handle_control_extendcircuit(control_connection_t *conn,
                                        uint32_t len,
205
                                        const char *body);
206
207
static int handle_control_setpurpose(control_connection_t *conn,
                                     int for_circuits,
208
                                     uint32_t len, const char *body);
209
210
static int handle_control_attachstream(control_connection_t *conn,
                                       uint32_t len,
211
                                        const char *body);
212
213
static int handle_control_postdescriptor(control_connection_t *conn,
                                         uint32_t len,
214
                                         const char *body);
215
216
static int handle_control_redirectstream(control_connection_t *conn,
                                         uint32_t len,
217
                                         const char *body);
218
static int handle_control_closestream(control_connection_t *conn, uint32_t len,
219
                                      const char *body);
220
221
static int handle_control_closecircuit(control_connection_t *conn,
                                       uint32_t len,
222
                                       const char *body);
223
224
225
static int handle_control_usefeature(control_connection_t *conn,
                                     uint32_t len,
                                     const char *body);
226
static int write_stream_target_to_buf(edge_connection_t *conn, char *buf,
227
                                      size_t len);
228
229
static void orconn_target_get_name(int long_names, char *buf, size_t len,
                                   or_connection_t *conn);
230

Nick Mathewson's avatar
Nick Mathewson committed
231
232
/** Given a possibly invalid message type code <b>cmd</b>, return a
 * human-readable string equivalent. */
233
234
235
static INLINE const char *
control_cmd_to_string(uint16_t cmd)
{
236
237
  return (cmd<=_CONTROL0_CMD_MAX_RECOGNIZED) ?
                      CONTROL0_COMMANDS[cmd] : "Unknown";
238
239
}

240
241
/** Given a control event code for a message event, return the corresponding
 * log severity. */
242
243
244
245
246
247
248
249
250
251
252
253
254
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;
  }
}

255
/** Given a log severity, return the corresponding control event code. */
256
257
258
259
260
261
262
263
264
265
266
267
268
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;
  }
}

269
270
/** Set <b>global_event_mask*</b> to the bitwise OR of each live control
 * connection's event_mask field. */
271
272
void
control_update_global_event_mask(void)
273
274
275
{
  connection_t **conns;
  int n_conns, i;
276
  global_event_mask0 = 0;
277
278
  global_event_mask1short = 0;
  global_event_mask1long = 0;
279
280
281
  get_connection_array(&conns, &n_conns);
  for (i = 0; i < n_conns; ++i) {
    if (conns[i]->type == CONN_TYPE_CONTROL &&
282
        STATE_IS_OPEN(conns[i]->state)) {
283
284
285
      control_connection_t *conn = TO_CONTROL_CONN(conns[i]);
      if (STATE_IS_V0(conn->_base.state))
        global_event_mask0 |= conn->event_mask;
286
287
      else if (conn->use_long_names)
        global_event_mask1long |= conn->event_mask;
288
      else
289
        global_event_mask1short |= conn->event_mask;
290
291
    }
  }
292

293
  control_adjust_event_log_severity();
294
295
}

296
297
298
/** 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. */
299
void
300
control_adjust_event_log_severity(void)
301
{
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
  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;
    }
  }
317
318
  if (EVENT_IS_INTERESTING(EVENT_LOG_OBSOLETE) ||
      EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL)) {
319
320
321
322
323
324
325
326
    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);
327
328
}

329
330
331
/** Append a NUL-terminated string <b>s</b> to the end of
 * <b>conn</b>-\>outbuf
 */
332
static INLINE void
333
connection_write_str_to_buf(const char *s, control_connection_t *conn)
334
335
{
  size_t len = strlen(s);
336
  connection_write_to_buf(s, len, TO_CONN(conn));
337
338
}

339
340
341
342
343
344
345
346
347
/** 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>, adding a period
 * before any period that that appears at the start of a line, and
 * adding a period-CRLF line at the end. If <b>translate_newlines</b>
 * is true, replace all LF characters sequences with CRLF.  Return the
 * number of bytes in *<b>out</b>.
 */
/* static */ size_t
348
349
350
351
352
353
354
355
write_escaped_data(const char *data, size_t len, int translate_newlines,
                   char **out)
{
  size_t sz_out = len+8;
  char *outp;
  const char *end;
  int i;
  int start_of_line;
Nick Mathewson's avatar
Nick Mathewson committed
356
  for (i=0; i<(int)len; ++i) {
357
    if (data[i]== '\n')
358
      sz_out += 2; /* Maybe add a CR; maybe add a dot. */
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
  }
  *out = outp = tor_malloc(sz_out+1);
  end = data+len;
  start_of_line = 1;
  while (data < end) {
    if (*data == '\n') {
      if (translate_newlines)
        *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++;
  }
378
379
380
381
  if (outp < *out+2 || memcmp(outp-2, "\r\n", 2)) {
    *outp++ = '\r';
    *outp++ = '\n';
  }
382
383
384
  *outp++ = '.';
  *outp++ = '\r';
  *outp++ = '\n';
385
  *outp = '\0'; /* NUL-terminate just in case. */
386
  tor_assert((outp - *out) <= (int)sz_out);
387
388
389
  return outp - *out;
}

390
391
392
393
394
395
396
/** 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
 * that appears at the start of a line.  If <b>translate_newlines</b>
 * is true, replace all CRLF sequences with LF.  Return the number of
 * bytes in *<b>out</b>. */
/*static*/ size_t
397
398
399
400
401
read_escaped_data(const char *data, size_t len, int translate_newlines,
                  char **out)
{
  char *outp;
  const char *next;
402
403
404
  const char *end;

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

406
  end = data+len;
407

408
  while (data < end) {
409
410
411
    if (*data == '.')
      ++data;
    if (translate_newlines)
412
      next = tor_memmem(data, end-data, "\r\n", 2);
413
    else
414
      next = tor_memmem(data, end-data, "\r\n.", 3);
415
416
417
418
419
    if (next) {
      memcpy(outp, data, next-data);
      outp += (next-data);
      data = next+2;
    } else {
420
421
422
      memcpy(outp, data, end-data);
      outp += (end-data);
      *outp = '\0';
423
424
425
426
427
428
429
430
431
432
      return outp - *out;
    }
    if (translate_newlines) {
      *outp++ = '\n';
    } else {
      *outp++ = '\r';
      *outp++ = '\n';
    }
  }

433
  *outp = '\0';
434
435
  return outp - *out;
}
436

437
438
439
440
441
442
443
/** Given a pointer to a string starting at <b>start</b> containing
 * <b>in_len_max</b> characters, decode a string beginning with a single
 * quote, containing any number of non-quote characters or characters escaped
 * with a backslash, and ending with a final quote.  Place the resulting
 * 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
444
 * NULL. */
445
static const char *
446
447
get_escaped_string(const char *start, size_t in_len_max,
                   char **out, size_t *out_len)
448
{
449
450
451
452
453
454
455
456
457
  const char *cp, *end;
  char *outp;
  size_t len=0;

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

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

459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
  /* 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;
478

479
480
481
482
483
484
485
  cp = start+1;
  while (cp < end) {
    if (*cp == '\\')
      ++cp;
    *outp++ = *cp++;
  }
  *outp = '\0';
486
  tor_assert((outp - *out) == (int)*out_len);
487
488
489
490

  return end+1;
}

491
492
493
/** 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.
494
495
496
 *
 * Currently the length of the message is limited to 1024 (including the
 * ending \n\r\0. */
497
static void
498
connection_printf_to_buf(control_connection_t *conn, const char *format, ...)
499
{
500
#define CONNECTION_PRINTF_TO_BUF_BUFFERSIZE 1024
501
  va_list ap;
502
  char buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE];
503
504
505
  int r;
  size_t len;
  va_start(ap,format);
506
  r = tor_vsnprintf(buf, sizeof(buf), format, ap);
507
  va_end(ap);
508
509
510
511
  if (r<0) {
    log_warn(LD_BUG, "Unable to format string for controller.");
    return;
  }
512
513
  len = strlen(buf);
  if (memcmp("\r\n\0", buf+len-2, 3)) {
514
515
516
    buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE-1] = '\0';
    buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE-2] = '\n';
    buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE-3] = '\r';
517
  }
518
  connection_write_to_buf(buf, len, TO_CONN(conn));
519
520
}

Nick Mathewson's avatar
Nick Mathewson committed
521
522
/** Send a message of type <b>type</b> containing <b>len</b> bytes
 * from <b>body</b> along the control connection <b>conn</b> */
523
static void
524
525
send_control0_message(control_connection_t *conn, uint16_t type, uint32_t len,
                      const char *body)
526
{
527
  char buf[10];
528
  tor_assert(conn);
529
  tor_assert(STATE_IS_V0(conn->_base.state));
530
  tor_assert(len || !body);
531
  tor_assert(type <= _CONTROL0_CMD_MAX_RECOGNIZED);
532
533
534
  if (len < 65536) {
    set_uint16(buf, htons(len));
    set_uint16(buf+2, htons(type));
535
    connection_write_to_buf(buf, 4, TO_CONN(conn));
536
    if (len)
537
      connection_write_to_buf(body, len, TO_CONN(conn));
538
539
  } else {
    set_uint16(buf, htons(65535));
540
    set_uint16(buf+2, htons(CONTROL0_CMD_FRAGMENTHEADER));
541
542
    set_uint16(buf+4, htons(type));
    set_uint32(buf+6, htonl(len));
543
544
    connection_write_to_buf(buf, 10, TO_CONN(conn));
    connection_write_to_buf(body, 65535-6, TO_CONN(conn));
545
546
547
548
549
    len -= (65535-6);
    body += (65535-6);
    while (len) {
      size_t chunklen = (len<65535)?len:65535;
      set_uint16(buf, htons((uint16_t)chunklen));
550
      set_uint16(buf+2, htons(CONTROL0_CMD_FRAGMENT));
551
552
      connection_write_to_buf(buf, 4, TO_CONN(conn));
      connection_write_to_buf(body, chunklen, TO_CONN(conn));
553
554
555
556
      len -= chunklen;
      body += chunklen;
    }
  }
557
558
}

Nick Mathewson's avatar
Nick Mathewson committed
559
/** Send a "DONE" message down the control connection <b>conn</b> */
560
static void
561
send_control_done(control_connection_t *conn)
562
{
563
  if (STATE_IS_V0(conn->_base.state)) {
564
565
566
567
    send_control0_message(conn, CONTROL0_CMD_DONE, 0, NULL);
  } else {
    connection_write_str_to_buf("250 OK\r\n", conn);
  }
568
569
}

570
571
572
/** Send a "DONE" message down the v0 control message <b>conn</b>, with body
 * as provided in the <b>len</b> bytes at <b>msg</b>.
 */
573
static void
574
send_control_done2(control_connection_t *conn, const char *msg, size_t len)
575
{
576
577
  if (len==0)
    len = strlen(msg);
578
  send_control0_message(conn, CONTROL0_CMD_DONE, len, msg);
579
580
}

Nick Mathewson's avatar
Nick Mathewson committed
581
582
/** Send an error message with error code <b>error</b> and body
 * <b>message</b> down the connection <b>conn</b> */
583
static void
584
585
send_control0_error(control_connection_t *conn, uint16_t error,
                    const char *message)
586
587
588
589
590
591
592
{
  char buf[256];
  size_t len;
  set_uint16(buf, htons(error));
  len = strlen(message);
  tor_assert(len < (256-2));
  memcpy(buf+2, message, len);
593
  send_control0_message(conn, CONTROL0_CMD_ERROR, (uint16_t)(len+2), buf);
594
595
}

Nick Mathewson's avatar
Nick Mathewson committed
596
597
598
/** Send an 'event' message of event type <b>event</b>, containing
 * <b>len</b> bytes in <b>body</b> to every control connection that
 * is interested in it. */
599
static void
600
send_control0_event(uint16_t event, uint32_t len, const char *body)
601
602
603
{
  connection_t **conns;
  int n_conns, i;
604
605
606
  size_t buflen;
  char *buf;

607
  tor_assert(event >= _EVENT_MIN && event <= LAST_V0_EVENT);
608

609
610
611
612
  buflen = len + 2;
  buf = tor_malloc_zero(buflen);
  set_uint16(buf, htons(event));
  memcpy(buf+2, body, len);
613
614
615
616

  get_connection_array(&conns, &n_conns);
  for (i = 0; i < n_conns; ++i) {
    if (conns[i]->type == CONN_TYPE_CONTROL &&
617
        !conns[i]->marked_for_close &&
618
619
620
621
622
        conns[i]->state == CONTROL_CONN_STATE_OPEN_V0) {
      control_connection_t *control_conn = TO_CONTROL_CONN(conns[i]);
      if (control_conn->event_mask & (1<<event)) {
        send_control0_message(control_conn, CONTROL0_CMD_EVENT, buflen, buf);
        if (event == EVENT_ERR_MSG)
623
          connection_handle_write(TO_CONN(control_conn), 1);
624
      }
625
626
    }
  }
627

628
  tor_free(buf);
629
630
}

631
/* Send an event to all v1 controllers that are listening for code
632
633
634
 * <b>event</b>.  The event's body is given by <b>msg</b>.
 *
 * docdoc which, is_extended */
635
static void
636
637
send_control1_event_string(uint16_t event, event_format_t which,
                           const char *msg)
638
639
{
  connection_t **conns;
640
  int n_conns, i;
641
642
643
644
645
646

  tor_assert(event >= _EVENT_MIN && event <= _EVENT_MAX);

  get_connection_array(&conns, &n_conns);
  for (i = 0; i < n_conns; ++i) {
    if (conns[i]->type == CONN_TYPE_CONTROL &&
647
        !conns[i]->marked_for_close &&
648
649
        conns[i]->state == CONTROL_CONN_STATE_OPEN_V1) {
      control_connection_t *control_conn = TO_CONTROL_CONN(conns[i]);
650
651
652
653
654
      if (control_conn->use_long_names) {
        if (!(which & LONG_NAMES))
          continue;
      } else {
        if (!(which & SHORT_NAMES))
655
          continue;
656
657
658
659
660
661
      }
      if (control_conn->use_extended_events) {
        if (!(which & EXTENDED_FORMAT))
          continue;
      } else {
        if (!(which & NONEXTENDED_FORMAT))
662
663
          continue;
      }
664
      if (control_conn->event_mask & (1<<event)) {
665
        int is_err = 0;
666
667
        connection_write_to_buf(msg, strlen(msg), TO_CONN(control_conn));
        if (event == EVENT_ERR_MSG)
668
669
670
671
672
673
674
675
          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)
676
          connection_handle_write(TO_CONN(control_conn), 1);
677
      }
678
679
680
681
    }
  }
}

682
static void
683
684
send_control1_event_impl(uint16_t event, event_format_t which, int extended,
                         const char *format, va_list ap)
685
686
687
688
689
{
#define SEND_CONTROL1_EVENT_BUFFERSIZE 1024
  int r;
  char buf[SEND_CONTROL1_EVENT_BUFFERSIZE]; /* XXXX Length */
  size_t len;
690
  char *cp;
691
692

  r = tor_vsnprintf(buf, sizeof(buf), format, ap);
693
694
695
696
  if (r<0) {
    log_warn(LD_BUG, "Unable to format event for controller.");
    return;
  }
697
698
699
700
701
702
703
704
705

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

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
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
  if (extended && (cp = strchr(buf, '@'))) {
    which &= ~ALL_FORMATS;
    *cp = ' ';
    send_control1_event_string(event, which|EXTENDED_FORMAT, buf);
    memcpy(cp, "\r\n\0", 3);
    send_control1_event_string(event, which|NONEXTENDED_FORMAT, buf);
  } else {
    send_control1_event_string(event, which|ALL_FORMATS, buf);
  }
}

/* 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
send_control1_event(uint16_t event, event_format_t which,
                    const char *format, ...)
{
  va_list ap;
  va_start(ap, format);
  send_control1_event_impl(event, which, 0, format, ap);
  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
send_control1_event_extended(uint16_t event, event_format_t which,
                             const char *format, ...)
{
  va_list ap;
  va_start(ap, format);
  send_control1_event_impl(event, which, 1, format, ap);
  va_end(ap);
751
752
}

753
/** Given a text circuit <b>id</b>, return the corresponding circuit. */
754
static origin_circuit_t *
755
756
757
758
759
760
761
762
763
764
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);
}

765
/** Given a text stream <b>id</b>, return the corresponding AP connection. */
766
static edge_connection_t *
767
768
769
770
get_stream(const char *id)
{
  unsigned long n_id;
  int ok;
771
  edge_connection_t *conn;
772
773
774
775
  n_id = tor_parse_ulong(id, 10, 0, ULONG_MAX, &ok, NULL);
  if (!ok)
    return NULL;
  conn = connection_get_by_global_id(n_id);
776
  if (!conn || conn->_base.type != CONN_TYPE_AP)
777
778
779
780
    return NULL;
  return conn;
}

781
/** Helper for setconf and resetconf. Acts like setconf, except
782
 * it passes <b>use_defaults</b> on to options_trial_assign().
783
 */
784
static int
785
control_setconf_helper(control_connection_t *conn, uint32_t len, char *body,
786
                       int use_defaults, int clear_first)
787
{
Nick Mathewson's avatar
Nick Mathewson committed
788
  int r;
789
  config_line_t *lines=NULL;
790
  char *start = body;
791
  char *errstring = NULL;
792
  int v0 = STATE_IS_V0(conn->_base.state);
793

794
795
796
797
798
799
800
801
802
  if (!v0) {
    char *config = tor_malloc(len+1);
    char *outp = config;
    while (*body) {
      char *eq = body;
      while (!TOR_ISSPACE(*eq) && *eq != '=')
        ++eq;
      memcpy(outp, body, eq-body);
      outp += (eq-body);
803
      *outp++ = ' ';
804
805
806
807
808
809
810
811
      body = eq+1;
      if (*eq == '=') {
        if (*body != '\"') {
          while (!TOR_ISSPACE(*body))
            *outp++ = *body++;
        } else {
          char *val;
          size_t val_len;
812
813
          body = (char*)get_escaped_string(body, (len - (body-start)),
                                           &val, &val_len);
814
815
816
817
818
819
820
          if (!body) {
            connection_write_str_to_buf("551 Couldn't parse string\r\n", conn);
            tor_free(config);
            return 0;
          }
          memcpy(outp, val, val_len);
          outp += val_len;
821
          tor_free(val);
822
823
824
825
826
827
828
829
830
        }
      }
      while (TOR_ISSPACE(*body))
        ++body;
      *outp++ = '\n';
    }
    *outp = '\0';

    if (config_get_lines(config, &lines) < 0) {
Roger Dingledine's avatar
Roger Dingledine committed
831
      log_warn(LD_CONTROL,"Controller gave us config lines we can't parse.");
832
833
      connection_write_str_to_buf("551 Couldn't parse configuration\r\n",
                                  conn);
834
835
836
837
838
839
      tor_free(config);
      return 0;
    }
    tor_free(config);
  } else {
    if (config_get_lines(body, &lines) < 0) {
840
841
      log_warn(LD_CONTROL,
               "V0 controller gave us config lines we can't parse.");
842
843
844
      send_control0_error(conn, ERR_SYNTAX, "Couldn't parse configuration");
      return 0;
    }
845
  }
846

847
848
  if ((r=options_trial_assign(lines, use_defaults,
                              clear_first, &errstring)) < 0) {
849
850
    int v0_err;
    const char *msg;
Roger Dingledine's avatar
Roger Dingledine committed
851
    log_warn(LD_CONTROL,
852
853
             "Controller gave us config lines that didn't validate: %s.",
             errstring);
854
855
856
    switch (r) {
      case -1:
        v0_err = ERR_UNRECOGNIZED_CONFIG_KEY;
857
        msg = "552 Unrecognized option";
858
859
860
        break;
      case -2:
        v0_err = ERR_INVALID_CONFIG_VALUE;
Roger Dingledine's avatar
Roger Dingledine committed
861
        msg = "513 Unacceptable option value";
862
863
864
        break;
      case -3:
        v0_err = ERR_INVALID_CONFIG_VALUE;
865
        msg = "553 Transition not allowed";
866
867
868
869
        break;
      case -4:
      default:
        v0_err = ERR_INVALID_CONFIG_VALUE;
870
        msg = "553 Unable to set option";
871
872
873
874
        break;
    }
    if (v0) {
      send_control0_error(conn, v0_err, msg);
Nick Mathewson's avatar
Nick Mathewson committed
875
    } else {
876
      connection_printf_to_buf(conn, "%s: %s\r\n", msg, errstring);
Nick Mathewson's avatar
Nick Mathewson committed
877
    }
878
    config_free_lines(lines);
879
    tor_free(errstring);
880
881
    return 0;
  }
882
  config_free_lines(lines);
883
  send_control_done(conn);
884
885
  return 0;
}
886

887
888
889
/** Called when we receive a SETCONF message: parse the body and try
 * to update our configuration.  Reply with a DONE or ERROR message. */
static int
890
handle_control_setconf(control_connection_t *conn, uint32_t len, char *body)
891
{
892
  return control_setconf_helper(conn, len, body, 0, 1);
893
894
895
896
897
}

/** Called when we receive a RESETCONF message: parse the body and try
 * to update our configuration.  Reply with a DONE or ERROR message. */
static int
898
handle_control_resetconf(control_connection_t *conn, uint32_t len, char *body)
899
{
900
  int v0 = STATE_IS_V0(conn->_base.state);
901
  tor_assert(!v0);
902
  return control_setconf_helper(conn, len, body, 1, 1);
903
904
}

Nick Mathewson's avatar
Nick Mathewson committed
905
906
/** Called when we receive a GETCONF message.  Parse the request, and
 * reply with a CONFVALUE or an ERROR message */
907
static int
908
909
handle_control_getconf(control_connection_t *conn, uint32_t body_len,
                       const char *body)
910
{
911
912
  smartlist_t *questions = NULL;
  smartlist_t *answers = NULL;
913
  smartlist_t *unrecognized = NULL;
914
915
  char *msg = NULL;
  size_t msg_len;
916
  or_options_t *options = get_options();
917
  int v0 = STATE_IS_V0(conn->_base.state);
918

919
  questions = smartlist_create();
920
  (void) body_len; /* body is nul-terminated; so we can ignore len. */
921
922
923
924
925
926
927
  if (v0) {
    smartlist_split_string(questions, body, "\n",
                           SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  } else {
    smartlist_split_string(questions, body, " ",
                           SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  }
928
  answers = smartlist_create();
929
930
  unrecognized = smartlist_create();
  SMARTLIST_FOREACH(questions, char *, q,
931
  {
932
    if (!option_is_recognized(q)) {
933
934
935
936
937
938
      if (v0) {
        send_control0_error(conn, ERR_UNRECOGNIZED_CONFIG_KEY, q);
        goto done;
      } else {
        smartlist_add(unrecognized, q);
      }
939
    } else {
940
      config_line_t *answer = option_get_assignment(options,q);
941
      if (!v0 && !answer) {
942
        const char *name = option_get_canonical_name(q);
943
        size_t alen = strlen(name)+8;
944
        char *astr = tor_malloc(alen);
945
        tor_snprintf(astr, alen, "250-%s\r\n", name);
946
947
        smartlist_add(answers, astr);
      }
948

949
      while (answer) {
950
        config_line_t *next;
951
        size_t alen = strlen(answer->key)+strlen(answer->value)+8;
952
        char *astr = tor_malloc(alen);
953
954
955
        if (v0)
          tor_snprintf(astr, alen, "%s %s\n", answer->key, answer->value);
        else
956
957
          tor_snprintf(astr, alen, "250-%s=%s\r\n",
                       answer->key, answer->value);
958
959
        smartlist_add(answers, astr);

960
        next = answer->next;
961
962
        tor_free(answer->key);
        tor_free(answer->value);
963
964
965
966
        tor_free(answer);
        answer = next;
      }
    }
967
  });
968

969
970
971
972
973
974
975
976
977
  if (v0) {
    msg = smartlist_join_strings(answers, "", 0, &msg_len);
    send_control0_message(conn, CONTROL0_CMD_CONFVALUE,
                          (uint16_t)msg_len, msg_len?msg:NULL);
  } else {
    int i,len;
    if ((len = smartlist_len(unrecognized))) {
      for (i=0; i < len-1; ++i)
        connection_printf_to_buf(conn,
978
979
                               "552-Unrecognized configuration key \"%s\"\r\n",
                               (char*)smartlist_get(unrecognized, i));
980
981
982
983
984
985
986
987
      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);
988
      connection_write_to_buf(msg, msg_len, TO_CONN(conn));
989
990
991
992
    } else {
      connection_write_str_to_buf("250 OK\r\n", conn);
    }
  }
993
994

 done:
995
996
997
998
999
1000
  if (answers) {
    SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
    smartlist_free(answers);
  }
  if (questions) {
    SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));