aboutsummaryrefslogtreecommitdiff
path: root/src/or/control.c
blob: e8f6d0e35eca0ec61e0a3d84056975a230bffd04 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
/* Copyright 2004 Roger Dingledine, Nick Mathewson. */
/* See LICENSE for licensing information */
/* $Id$ */
const char control_c_id[] = "$Id$";

/**
 * \file control.c
 *
 * \brief Implementation for Tor's control-socket interface.
 */

#include "or.h"

/* Protocol outline: a bidirectional stream, over which each side
 * sends a series of messages.  Each message has a two-byte length field,
 * a two-byte typecode, and a variable-length body whose length is
 * given in the length field.
 *
 * By default, the server only sends messages in response to client messages.
 * Every client message gets a message in response.  The client may, however,
 * _request_ that other messages be delivered asynchronously.
 *
 *
 * Every message type is either client-only or server-only, and every
 * server message type is either synchronous-only (only occurs in
 * response to a client request) or asynchronous-only (never is an
 * answer to a client request.
 *
 * See control-spec.txt for full details.
 */

/* Recognized message type codes. */
#define CONTROL_CMD_ERROR        0x0000
#define CONTROL_CMD_DONE         0x0001
#define CONTROL_CMD_SETCONF      0x0002
#define CONTROL_CMD_GETCONF      0x0003
#define CONTROL_CMD_CONFVALUE    0x0004
#define CONTROL_CMD_SETEVENTS    0x0005
#define CONTROL_CMD_EVENT        0x0006
#define CONTROL_CMD_AUTHENTICATE 0x0007
#define CONTROL_CMD_SAVECONF     0x0008
#define CONTROL_CMD_SIGNAL       0x0009
#define CONTROL_CMD_MAPADDRESS   0x000A
#define CONTROL_CMD_GETINFO      0x000B
#define CONTROL_CMD_INFOVALUE    0x000C
#define CONTROL_CMD_EXTENDCIRCUIT  0x000D
#define CONTROL_CMD_ATTACHSTREAM   0x000E
#define CONTROL_CMD_POSTDESCRIPTOR 0x000F
#define CONTROL_CMD_FRAGMENTHEADER 0x0010
#define CONTROL_CMD_FRAGMENT       0x0011
#define CONTROL_CMD_REDIRECTSTREAM  0x0012
#define _CONTROL_CMD_MAX_RECOGNIZED 0x0012

/* Recognized error codes. */
#define ERR_UNSPECIFIED             0x0000
#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
#define ERR_RESOURCE_EXHAUSETED     0x0009
#define ERR_NO_STREAM               0x000A
#define ERR_NO_CIRC                 0x000B
#define ERR_NO_ROUTER               0x000C

/* Recognized asynchronous event types. */
#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_WARNING         0x0005
#define EVENT_NEW_DESC        0x0006
#define _EVENT_MAX            0x0006

/** Array mapping from message type codes to human-readable message
 * type names.  */
static const char * CONTROL_COMMANDS[_CONTROL_CMD_MAX_RECOGNIZED+1] = {
  "error",
  "done",
  "setconf",
  "getconf",
  "confvalue",
  "setevents",
  "events",
  "authenticate",
  "saveconf",
  "signal",
  "mapaddress",
  "getinfo",
  "infovalue",
  "extendcircuit",
  "attachstream",
  "postdescriptor",
  "fragmentheader",
  "fragment",
};

/** Bitfield: The bit 1&lt;&lt;e is set if <b>any</b> open control
 * 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
 * has interest in without having to walk over the global connection
 * list to find out.
 **/
static uint32_t global_event_mask = 0;

/** Macro: true if any control connection is interested in events of type
 * <b>e</b>. */
#define EVENT_IS_INTERESTING(e) (global_event_mask & (1<<(e)))

/** If we're using cookie-type authentication, how long should our cookies be?
 */
#define AUTHENTICATION_COOKIE_LEN 32

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

static void update_global_event_mask(void);
static void send_control_message(connection_t *conn, uint16_t type,
                                 uint32_t len, const char *body);
static void send_control_done(connection_t *conn);
static void send_control_done2(connection_t *conn, const char *msg, size_t len);
static void send_control_error(connection_t *conn, uint16_t error,
                               const char *message);
static void send_control_event(uint16_t event, uint32_t len, const char *body);
static int handle_control_setconf(connection_t *conn, uint32_t len,
                                  char *body);
static int handle_control_getconf(connection_t *conn, uint32_t len,
                                  const char *body);
static int handle_control_setevents(connection_t *conn, uint32_t len,
                                    const char *body);
static int handle_control_authenticate(connection_t *conn, uint32_t len,
                                       const char *body);
static int handle_control_saveconf(connection_t *conn, uint32_t len,
                                   const char *body);
static int handle_control_signal(connection_t *conn, uint32_t len,
                                 const char *body);
static int handle_control_mapaddress(connection_t *conn, uint32_t len,
                                     const char *body);
static int handle_control_getinfo(connection_t *conn, uint32_t len,
                                  const char *body);
static int handle_control_extendcircuit(connection_t *conn, uint32_t len,
                                        const char *body);
static int handle_control_attachstream(connection_t *conn, uint32_t len,
                                        const char *body);
static int handle_control_postdescriptor(connection_t *conn, uint32_t len,
                                         const char *body);
static int handle_control_redirectstream(connection_t *conn, uint32_t len,
                                         const char *body);

/** Given a possibly invalid message type code <b>cmd</b>, return a
 * human-readable string equivalent. */
static INLINE const char *
control_cmd_to_string(uint16_t cmd)
{
  return (cmd<=_CONTROL_CMD_MAX_RECOGNIZED) ? CONTROL_COMMANDS[cmd] : "Unknown";
}

/** Set <b>global_event_mask</b> to the bitwise OR of each live control
 * connection's event_mask field. */
static void update_global_event_mask(void)
{
  connection_t **conns;
  int n_conns, i;

  global_event_mask = 0;
  get_connection_array(&conns, &n_conns);
  for (i = 0; i < n_conns; ++i) {
    if (conns[i]->type == CONN_TYPE_CONTROL &&
        conns[i]->state == CONTROL_CONN_STATE_OPEN) {
      global_event_mask |= conns[i]->event_mask;
    }
  }
}

/** Send a message of type <b>type</b> containing <b>len</b> bytes
 * from <b>body</b> along the control connection <b>conn</b> */
static void
send_control_message(connection_t *conn, uint16_t type, uint32_t len,
                     const char *body)
{
  char buf[10];
  tor_assert(conn);
  tor_assert(len || !body);
  tor_assert(type <= _CONTROL_CMD_MAX_RECOGNIZED);
  if (len < 65536) {
    set_uint16(buf, htons(len));
    set_uint16(buf+2, htons(type));
    connection_write_to_buf(buf, 4, conn);
    if (len)
      connection_write_to_buf(body, len, conn);
  } else {
    set_uint16(buf, htons(65535));
    set_uint16(buf+2, htons(CONTROL_CMD_FRAGMENTHEADER));
    set_uint16(buf+4, htons(type));
    set_uint32(buf+6, htonl(len));
    connection_write_to_buf(buf, 10, conn);
    connection_write_to_buf(body, 65535-6, conn);
    len -= (65535-6);
    body += (65535-6);
    while (len) {
      size_t chunklen = (len<65535)?len:65535;
      set_uint16(buf, htons((uint16_t)chunklen));
      set_uint16(buf+2, htons(CONTROL_CMD_FRAGMENT));
      connection_write_to_buf(buf, 4, conn);
      connection_write_to_buf(body, chunklen, conn);
      len -= chunklen;
      body += chunklen;
    }
  }
}

/** Send a "DONE" message down the control connection <b>conn</b> */
static void
send_control_done(connection_t *conn)
{
  send_control_message(conn, CONTROL_CMD_DONE, 0, NULL);
}

static void send_control_done2(connection_t *conn, const char *msg, size_t len)
{
  send_control_message(conn, CONTROL_CMD_DONE, len, msg);
}

/** Send an error message with error code <b>error</b> and body
 * <b>message</b> down the connection <b>conn</b> */
static void
send_control_error(connection_t *conn, uint16_t error, const char *message)
{
  char buf[256];
  size_t len;
  set_uint16(buf, htons(error));
  len = strlen(message);
  tor_assert(len < (256-2));
  memcpy(buf+2, message, len);
  send_control_message(conn, CONTROL_CMD_ERROR, (uint16_t)(len+2), buf);
}

/** 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. */
static void
send_control_event(uint16_t event, uint32_t len, const char *body)
{
  connection_t **conns;
  int n_conns, i;
  size_t buflen;
  char *buf;

  buflen = len + 2;
  buf = tor_malloc_zero(buflen);
  set_uint16(buf, htons(event));
  memcpy(buf+2, body, len);

  get_connection_array(&conns, &n_conns);
  for (i = 0; i < n_conns; ++i) {
    if (conns[i]->type == CONN_TYPE_CONTROL &&
        conns[i]->state == CONTROL_CONN_STATE_OPEN &&
        conns[i]->event_mask & (1<<event)) {
      send_control_message(conns[i], CONTROL_CMD_EVENT, buflen, buf);
    }
  }

  tor_free(buf);
}

/** 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
handle_control_setconf(connection_t *conn, uint32_t len, char *body)
{
  int r;
  struct config_line_t *lines=NULL;

  if (config_get_lines(body, &lines) < 0) {
    log_fn(LOG_WARN,"Controller gave us config lines we can't parse.");
    send_control_error(conn, ERR_SYNTAX, "Couldn't parse configuration");
    return 0;
  }

  if ((r=config_trial_assign(lines, 1)) < 0) {
    log_fn(LOG_WARN,"Controller gave us config lines that didn't validate.");
    if (r==-1) {
      send_control_error(conn, ERR_UNRECOGNIZED_CONFIG_KEY,
                         "Unrecognized option");
    } else {
      send_control_error(conn, ERR_INVALID_CONFIG_VALUE,"Invalid option value");
    }
    config_free_lines(lines);
    return 0;
  }

  config_free_lines(lines);
  if (options_act() < 0) { /* acting on them failed. die. */
    log_fn(LOG_ERR,"Acting on config options left us in a broken state. Dying.");
    exit(1);
  }
  send_control_done(conn);
  return 0;
}

/** Called when we receive a GETCONF message.  Parse the request, and
 * reply with a CONFVALUE or an ERROR message */
static int
handle_control_getconf(connection_t *conn, uint32_t body_len, const char *body)
{
  smartlist_t *questions = NULL;
  smartlist_t *answers = NULL;
  char *msg = NULL;
  size_t msg_len;
  or_options_t *options = get_options();

  questions = smartlist_create();
  smartlist_split_string(questions, body, "\n",
                         SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  answers = smartlist_create();
  SMARTLIST_FOREACH(questions, const char *, q,
  {
    int recognized = config_option_is_recognized(q);
    if (!recognized) {
      send_control_error(conn, ERR_UNRECOGNIZED_CONFIG_KEY, body);
      goto done;
    } else {
      struct config_line_t *answer = config_get_assigned_option(options,q);

      while (answer) {
        struct config_line_t *next;
        size_t alen = strlen(answer->key)+strlen(answer->value)+3;
        char *astr = tor_malloc(alen);
        tor_snprintf(astr, alen, "%s %s\n", answer->key, answer->value);
        smartlist_add(answers, astr);

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

  msg = smartlist_join_strings(answers, "", 0, &msg_len);
  send_control_message(conn, CONTROL_CMD_CONFVALUE,
                       (uint16_t)msg_len, msg_len?msg:NULL);

 done:
  if (answers) SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
  if (questions) SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
  smartlist_free(answers);
  smartlist_free(questions);
  tor_free(msg);

  return 0;
}

/** Called when we get a SETEVENTS message: update conn->event_mask,
 * and reply with DONE or ERROR. */
static int
handle_control_setevents(connection_t *conn, uint32_t len, const char *body)
{
  uint16_t event_code;
  uint32_t event_mask = 0;
  if (len % 2) {
    send_control_error(conn, ERR_SYNTAX,
                       "Odd number of bytes in setevents message");
    return 0;
  }

  for (; len; len -= 2, body += 2) {
    event_code = ntohs(get_uint16(body));
    if (event_code < _EVENT_MIN || event_code > _EVENT_MAX) {
      send_control_error(conn, ERR_UNRECOGNIZED_EVENT_CODE,
                         "Unrecognized event code");
      return 0;
    }
    event_mask |= (1 << event_code);
  }

  conn->event_mask = event_mask;

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

/** Decode the hashed, base64'd password stored in <b>hashed</b>.  If
 * <b>buf</b> is provided, store the hashed password in the first
 * S2K_SPECIFIER_LEN+DIGEST_LEN bytes of <b>buf</b>.  Return 0 on
 * success, -1 on failure.
 */
int
decode_hashed_password(char *buf, const char *hashed)
{
  char decoded[64];
  if (base64_decode(decoded, sizeof(decoded), hashed, strlen(hashed))
      != S2K_SPECIFIER_LEN+DIGEST_LEN) {
    return -1;
  }
  if (buf)
    memcpy(buf, decoded, sizeof(decoded));
  return 0;
}

/** 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
handle_control_authenticate(connection_t *conn, uint32_t len, const char *body)
{
  or_options_t *options = get_options();
  if (options->CookieAuthentication) {
    if (len == AUTHENTICATION_COOKIE_LEN &&
        !memcmp(authentication_cookie, body, len)) {
      goto ok;
    }
  } else if (options->HashedControlPassword) {
    char expected[S2K_SPECIFIER_LEN+DIGEST_LEN];
    char received[DIGEST_LEN];
    if (decode_hashed_password(expected, options->HashedControlPassword)<0) {
      log_fn(LOG_WARN,"Couldn't decode HashedControlPassword: invalid base64");
      goto err;
    }
    secret_to_key(received,DIGEST_LEN,body,len,expected);
    if (!memcmp(expected+S2K_SPECIFIER_LEN, received, DIGEST_LEN))
      goto ok;
    goto err;
  } else {
    if (len == 0) {
      /* if Tor doesn't demand any stronger authentication, then
       * the controller can get in with a blank auth line. */
      goto ok;
    }
    goto err;
  }

 err:
  send_control_error(conn, ERR_REJECTED_AUTHENTICATION,"Authentication failed");
  return 0;
 ok:
  log_fn(LOG_INFO, "Authenticated control connection (%d)", conn->s);
  send_control_done(conn);
  conn->state = CONTROL_CONN_STATE_OPEN;
  return 0;
}

static int
handle_control_saveconf(connection_t *conn, uint32_t len,
                        const char *body)
{
  if (save_current_config()<0) {
    send_control_error(conn, ERR_INTERNAL,
                       "Unable to write configuration to disk.");
  } else {
    send_control_done(conn);
  }
  return 0;
}

static int
handle_control_signal(connection_t *conn, uint32_t len,
                      const char *body)
{
  if (len != 1) {
    send_control_error(conn, ERR_SYNTAX,
                       "Body of SIGNAL command too long or too short.");
  } else if (control_signal_act((uint8_t)body[0]) < 0) {
    send_control_error(conn, ERR_SYNTAX, "Unrecognized signal number.");
  } else {
    send_control_done(conn);
  }
  return 0;
}

static int
handle_control_mapaddress(connection_t *conn, uint32_t len, const char *body)
{
  smartlist_t *elts;
  smartlist_t *lines;
  smartlist_t *reply;
  char *r;
  size_t sz;
  lines = smartlist_create();
  elts = smartlist_create();
  reply = smartlist_create();
  smartlist_split_string(lines, body, "\n",
                         SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  SMARTLIST_FOREACH(lines, char *, line,
  {
    tor_strlower(line);
    smartlist_split_string(elts, line, " ", 0, 2);
    if (smartlist_len(elts) == 2) {
      const char *from = smartlist_get(elts,0);
      const char *to = smartlist_get(elts,1);
      if (!is_plausible_address(from)) {
        log_fn(LOG_WARN,"Skipping invalid argument '%s' in MapAddress msg",from);
      } else if (!is_plausible_address(to)) {
        log_fn(LOG_WARN,"Skipping invalid argument '%s' in MapAddress msg",to);
      } else if (!strcmp(from, ".") || !strcmp(from, "0.0.0.0")) {
        char *addr = addressmap_register_virtual_address(
               strcmp(from,".") ? RESOLVED_TYPE_HOSTNAME : RESOLVED_TYPE_IPV4,
               tor_strdup(to));
        if (!addr) {
          log_fn(LOG_WARN,
                 "Unable to allocate address for '%s' in MapAddress msg",line);
        } else {
          size_t anslen = strlen(addr)+strlen(to)+2;
          char *ans = tor_malloc(anslen);
          tor_snprintf(ans, anslen, "%s %s", addr, to);
          tor_free(addr);
          smartlist_add(reply, ans);
        }
      } else {
        addressmap_register(from, tor_strdup(to), 1);
        smartlist_add(reply, tor_strdup(line));
      }
    } else {
      log_fn(LOG_WARN, "Skipping MapAddress line with wrong number of items.");
    }
    SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
    smartlist_clear(elts);
  });
  SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  smartlist_free(lines);
  smartlist_free(elts);

  r = smartlist_join_strings(reply, "\n", 1, &sz);
  send_control_done2(conn,r,sz);

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

static char *
handle_getinfo_helper(const char *question)
{
  if (!strcmp(question, "version")) {
    return tor_strdup(VERSION);
  } else if (!strcmpstart(question, "desc/id/")) {
    routerinfo_t *ri = router_get_by_hexdigest(question+strlen("desc/id/"));
    if (!ri)
      return NULL;
    if (!ri->signed_descriptor)
      return NULL;
    return tor_strdup(ri->signed_descriptor);
  } else if (!strcmp(question, "desc/all-ids")) {
    routerlist_t *rl;
    char *answer, *cp;
    router_get_routerlist(&rl);
    if (!rl)
      return tor_strdup("");
    answer = tor_malloc(smartlist_len(rl->routers)*(HEX_DIGEST_LEN+1)+1);
    cp = answer;
    SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
    {
      base16_encode(cp, HEX_DIGEST_LEN+1, r->identity_digest, DIGEST_LEN);
      cp += HEX_DIGEST_LEN;
      *cp++ = ',';
    });
    return answer;
  } else if (!strcmpstart(question, "addr-mappings/")) {
    time_t min_e, max_e;
    smartlist_t *mappings;
    char *answer;
    if (!strcmp(question, "addr-mappings/all")) {
      min_e = 0; max_e = TIME_MAX;
    } else if (!strcmp(question, "addr-mappings/cache")) {
      min_e = 2; max_e = TIME_MAX;
    } else if (!strcmp(question, "addr-mappings/config")) {
      min_e = 0; max_e = 0;
    } else if (!strcmp(question, "addr-mappings/control")) {
      min_e = 1; max_e = 1;
    } else {
      return NULL;
    }
    mappings = smartlist_create();
    addressmap_get_mappings(mappings, min_e, max_e);
    answer = smartlist_join_strings(mappings, "\n", 1, NULL);
    SMARTLIST_FOREACH(mappings, char *, cp, tor_free(cp));
    smartlist_free(mappings);
    return answer;
  } else {
    /* unrecognized key */
    return NULL;
  }
}

static int
handle_control_getinfo(connection_t *conn, uint32_t len, const char *body)
{
  smartlist_t *questions = NULL;
  smartlist_t *answers = NULL;
  char *msg = NULL, *ans;
  size_t msg_len;

  questions = smartlist_create();
  smartlist_split_string(questions, body, "\n",
                         SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  answers = smartlist_create();
  msg_len = 0;
  SMARTLIST_FOREACH(questions, const char *, q,
  {
    ans = handle_getinfo_helper(q);
    if (!ans) {
      send_control_error(conn, ERR_UNRECOGNIZED_CONFIG_KEY, body);
      goto done;
    } else {
      smartlist_add(answers, tor_strdup(q));
      smartlist_add(answers, ans);
      msg_len += 2 + strlen(ans) + strlen(q);
    }
  });

  msg = smartlist_join_strings2(answers, "\0", 1, 1, &msg_len);
  send_control_message(conn, CONTROL_CMD_INFOVALUE,
                       msg_len, msg_len?msg:NULL);

 done:
  if (answers) SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
  if (questions) SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
  smartlist_free(answers);
  smartlist_free(questions);
  tor_free(msg);

  return 0;
}
static int
handle_control_extendcircuit(connection_t *conn, uint32_t len,
                             const char *body)
{
  smartlist_t *router_nicknames, *routers;
  uint32_t circ_id;
  circuit_t *circ;
  if (len<5) {
    send_control_error(conn, ERR_SYNTAX, "extendcircuit message too short");
    return 0;
  }
  circ_id = ntohl(get_uint32(body));
  if (!(circ = circuit_get_by_global_id(circ_id))) {
    send_control_error(conn, ERR_NO_STREAM,
                       "No connection found with given ID");
    return 0;
  }

  router_nicknames = smartlist_create();
  routers = smartlist_create();
  smartlist_split_string(router_nicknames, body, ",", 0, 0);
  SMARTLIST_FOREACH(router_nicknames, const char *, n,
    {
      routerinfo_t *r = router_get_by_nickname(n);
      if (!r) {
        send_control_error(conn, ERR_NO_ROUTER, "Unrecognized router name");
        goto done;
      }
      smartlist_add(routers, r);
    });

#if 1
  /*XXXX RD*/
  send_control_error(conn, ERR_INTERNAL, "EXTENDCIRCUIT not implemented.");
#else
  SMARTLIST_FOREACH(routers, routerinfo_t *, r,
    {
      /*XXXX RD*/
      if (circuit_extend_path(circ, r)<0) {
        send_control_error(conn, ERR_INTERNAL, "Unable to extend path.");
        goto done;
      }
    });
#endif

  send_control_done(conn);
 done:
  SMARTLIST_FOREACH(router_nicknames, char *, n, tor_free(n));
  smartlist_free(router_nicknames);
  smartlist_free(routers);
  return 0;
}
static int handle_control_attachstream(connection_t *conn, uint32_t len,
                                        const char *body)
{
  uint32_t conn_id;
  uint32_t circ_id;
  connection_t *ap_conn;
  circuit_t *circ;

  if (len < 8) {
    send_control_error(conn, ERR_SYNTAX, "attachstream message too short");
    return 0;
  }

  conn_id = ntohl(get_uint32(body));
  circ_id = ntohl(get_uint32(body+4));

  if (!(ap_conn = connection_get_by_global_id(conn_id))) {
    send_control_error(conn, ERR_NO_STREAM,
                       "No connection found with given ID");
    return 0;
  }
  if (ap_conn->state != AP_CONN_STATE_CONTROLLER_WAIT) {
    send_control_error(conn, ERR_NO_STREAM,
                       "Connection was not managed by controller.");
    return 0;
  }

  if (!circ_id) {
    ap_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
    if (connection_ap_handshake_attach_circuit(ap_conn)<0)
      connection_mark_for_close(ap_conn);

    return 0;
  }

  if (!(circ = circuit_get_by_global_id(circ_id))) {
    send_control_error(conn, ERR_NO_CIRC, "No circuit found with given ID");
    return 0;
  }
  if (connection_ap_handshake_attach_chosen_circuit(ap_conn, circ) != 1) {
    send_control_error(conn, ERR_INTERNAL, "Unable to attach stream.");
    return 0;
  }
  send_control_done(conn);
  return 0;
}
static int
handle_control_postdescriptor(connection_t *conn, uint32_t len,
                              const char *body)
{
  if (router_load_single_router(body)<0) {
    /* XXXX a more specific error would be nice. */
    send_control_error(conn,ERR_UNSPECIFIED,
                       "Could not parse descriptor or add it");
    return 0;
  }

  send_control_done(conn);
  return 0;
}
static int
handle_control_redirectstream(connection_t *conn, uint32_t len,
                              const char *body)
{
  connection_t *ap_conn;
  uint32_t conn_id;
  if (len < 6) {
    send_control_error(conn, ERR_SYNTAX, "attachstream message too short");
    return 0;
  }
  conn_id = ntohl(get_uint32(body));

  if (!(ap_conn = connection_get_by_global_id(conn_id))
      || ap_conn->state != CONN_TYPE_AP
      || !ap_conn->socks_request) {
    send_control_error(conn, ERR_NO_STREAM,
                       "No AP connection found with given ID");
    return 0;
  }
  strlcpy(ap_conn->socks_request->address, body+1,
          sizeof(ap_conn->socks_request->address));

  send_control_done(conn);
  return 0;
}


/** Called when <b>conn</b> has no more bytes left on its outbuf. */
int
connection_control_finished_flushing(connection_t *conn) {
  tor_assert(conn);
  tor_assert(conn->type == CONN_TYPE_CONTROL);

  connection_stop_writing(conn);
  return 0;
}

/** Called when <b>conn</b> has gotten its socket closed. */
int connection_control_reached_eof(connection_t *conn) {
  log_fn(LOG_INFO,"Control connection reached EOF. Closing.");
  connection_mark_for_close(conn);
  return 0;
}

/** Called when <b>conn</b> has received more bytes on its inbuf.
 */
int
connection_control_process_inbuf(connection_t *conn) {
  uint32_t body_len;
  uint16_t command_type;
  char *body;

  tor_assert(conn);
  tor_assert(conn->type == CONN_TYPE_CONTROL);

 again:
  /* Try to suck a control message from the buffer. */
  switch (fetch_from_buf_control(conn->inbuf, &body_len, &command_type, &body))
    {
    case -1:
      tor_free(body);
      log_fn(LOG_WARN, "Error in control command. Failing.");
      return -1;
    case 0:
      /* Control command not all here yet. Wait. */
      return 0;
    case 1:
      /* We got a command. Process it. */
      break;
    default:
      tor_assert(0);
    }

  /* We got a command.  If we need authentication, only authentication
   * commands will be considered. */
  if (conn->state == CONTROL_CONN_STATE_NEEDAUTH &&
      command_type != CONTROL_CMD_AUTHENTICATE) {
    log_fn(LOG_WARN, "Rejecting '%s' command; authentication needed.",
           control_cmd_to_string(command_type));
    send_control_error(conn, ERR_UNAUTHORIZED, "Authentication required");
    tor_free(body);
    goto again;
  }

  /* Okay, we're willing to process the command. */
  switch (command_type)
    {
    case CONTROL_CMD_SETCONF:
      if (handle_control_setconf(conn, body_len, body))
        return -1;
      break;
    case CONTROL_CMD_GETCONF:
      if (handle_control_getconf(conn, body_len, body))
        return -1;
      break;
    case CONTROL_CMD_SETEVENTS:
      if (handle_control_setevents(conn, body_len, body))
        return -1;
      break;
    case CONTROL_CMD_AUTHENTICATE:
      if (handle_control_authenticate(conn, body_len, body))
        return -1;
      break;
    case CONTROL_CMD_SAVECONF:
      if (handle_control_saveconf(conn, body_len, body))
        return -1;
      break;
    case CONTROL_CMD_SIGNAL:
      if (handle_control_signal(conn, body_len, body))
        return -1;
      break;
    case CONTROL_CMD_MAPADDRESS:
      if (handle_control_mapaddress(conn, body_len, body))
        return -1;
      break;
    case CONTROL_CMD_GETINFO:
      if (handle_control_getinfo(conn, body_len, body))
        return -1;
      break;
    case CONTROL_CMD_EXTENDCIRCUIT:
      if (handle_control_extendcircuit(conn, body_len, body))
        return -1;
      break;
    case CONTROL_CMD_ATTACHSTREAM:
      if (handle_control_attachstream(conn, body_len, body))
        return -1;
      break;
    case CONTROL_CMD_POSTDESCRIPTOR:
      if (handle_control_postdescriptor(conn, body_len, body))
        return -1;
      break;
    case CONTROL_CMD_REDIRECTSTREAM:
      if (handle_control_redirectstream(conn, body_len, body))
        return -1;
      break;
    case CONTROL_CMD_ERROR:
    case CONTROL_CMD_DONE:
    case CONTROL_CMD_CONFVALUE:
    case CONTROL_CMD_EVENT:
    case CONTROL_CMD_INFOVALUE:
      log_fn(LOG_WARN, "Received client-only '%s' command; ignoring.",
             control_cmd_to_string(command_type));
      send_control_error(conn, ERR_UNRECOGNIZED_TYPE,
                         "Command type only valid from server to tor client");
      break;
    case CONTROL_CMD_FRAGMENTHEADER:
    case CONTROL_CMD_FRAGMENT:
      log_fn(LOG_WARN, "Recieved command fragment out of order; ignoring.");
      send_control_error(conn, ERR_SYNTAX, "Bad fragmentation on command.");
    default:
      log_fn(LOG_WARN, "Received unrecognized command type %d; ignoring.",
             (int)command_type);
      send_control_error(conn, ERR_UNRECOGNIZED_TYPE,
                         "Unrecognized command type");
      break;
  }
  tor_free(body);
  goto again; /* There might be more data. */
}

/** Something has happened to circuit <b>circ</b>: tell any interested
 * control connections. */
int
control_event_circuit_status(circuit_t *circ, circuit_status_event_t tp)
{
  char *path, *msg;
  size_t path_len;
  if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS))
    return 0;
  tor_assert(circ);
  tor_assert(CIRCUIT_IS_ORIGIN(circ));

  path = circuit_list_path(circ,0);
  path_len = strlen(path);
  msg = tor_malloc(1+4+path_len+1); /* event, circid, path, NUL. */
  msg[0] = (uint8_t) tp;
  set_uint32(msg+1, htonl(circ->global_identifier));
  strlcpy(msg+5,path,path_len+1);

  send_control_event(EVENT_CIRCUIT_STATUS, (uint32_t)(path_len+6), msg);
  tor_free(path);
  tor_free(msg);
  return 0;
}

/** Something has happened to the stream associated with AP connection
 * <b>conn</b>: tell any interested control connections. */
int
control_event_stream_status(connection_t *conn, stream_status_event_t tp)
{
  char *msg;
  size_t len;
  char buf[256];
  tor_assert(conn->type == CONN_TYPE_AP);
  tor_assert(conn->socks_request);

  if (!EVENT_IS_INTERESTING(EVENT_STREAM_STATUS))
    return 0;

  tor_snprintf(buf, sizeof(buf), "%s:%d",
               conn->socks_request->address, conn->socks_request->port),
  len = strlen(buf);
  msg = tor_malloc(5+len+1);
  msg[0] = (uint8_t) tp;
  set_uint32(msg+1, htonl(conn->global_identifier));
  strlcpy(msg+5, buf, len+1);

  send_control_event(EVENT_STREAM_STATUS, (uint32_t)(5+len+1), msg);
  tor_free(msg);
  return 0;
}

/** Something has happened to the OR connection <b>conn</b>: tell any
 * interested control connections. */
int
control_event_or_conn_status(connection_t *conn,or_conn_status_event_t tp)
{
  char buf[HEX_DIGEST_LEN+3]; /* status, dollar, identity, NUL */
  size_t len;

  tor_assert(conn->type == CONN_TYPE_OR);

  if (!EVENT_IS_INTERESTING(EVENT_OR_CONN_STATUS))
    return 0;

  buf[0] = (uint8_t)tp;
  strlcpy(buf+1,conn->nickname,sizeof(buf)-1);
  len = strlen(buf+1);
  send_control_event(EVENT_OR_CONN_STATUS, (uint32_t)(len+1), buf);
  return 0;
}

/** A second or more has elapsed: tell any interested control
 * connections how much bandwidth we used. */
int
control_event_bandwidth_used(uint32_t n_read, uint32_t n_written)
{
  char buf[8];

  if (!EVENT_IS_INTERESTING(EVENT_BANDWIDTH_USED))
    return 0;

  set_uint32(buf, htonl(n_read));
  set_uint32(buf+4, htonl(n_written));
  send_control_event(EVENT_BANDWIDTH_USED, 8, buf);

  return 0;
}

/** We got a log message: tell any interested control connections. */
void
control_event_logmsg(int severity, const char *msg)
{
  size_t len;
  if (severity > LOG_NOTICE) /* Less important than notice? ignore for now. */
    return;
  if (!EVENT_IS_INTERESTING(EVENT_WARNING))
    return;

  len = strlen(msg);
  send_control_event(EVENT_WARNING, (uint32_t)(len+1), msg);
}

/** Called whenever we receive new router descriptors: tell any
 * interested control connections.  <b>routers</b> is a list of
 * DIGEST_LEN-byte identity digests.
 */
int control_event_descriptors_changed(smartlist_t *routers)
{
  size_t len;
  char *msg;
  smartlist_t *identities;
  char buf[HEX_DIGEST_LEN+1];

  if (!EVENT_IS_INTERESTING(EVENT_NEW_DESC))
    return 0;
  identities = smartlist_create();
  SMARTLIST_FOREACH(routers, routerinfo_t *, r,
  {
    base16_encode(buf,sizeof(buf),r->identity_digest,DIGEST_LEN);
    smartlist_add(identities, tor_strdup(buf));
  });
  msg = smartlist_join_strings(identities, ",", 1, &len);
  send_control_event(EVENT_NEW_DESC, len+1, msg);

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

/** Choose a random authentication cookie and write it to disk.
 * Anybody who can read the cookie from disk will be considered
 * authorized to use the control connection. */
int
init_cookie_authentication(int enabled)
{
  char fname[512];

  if (!enabled) {
    authentication_cookie_is_set = 0;
    return 0;
  }

  tor_snprintf(fname, sizeof(fname), "%s/control_auth_cookie",
               get_options()->DataDirectory);
  crypto_rand(authentication_cookie, AUTHENTICATION_COOKIE_LEN);
  authentication_cookie_is_set = 1;
  if (write_bytes_to_file(fname, authentication_cookie,
                          AUTHENTICATION_COOKIE_LEN, 1)) {
    log_fn(LOG_WARN,"Error writing authentication cookie.");
    return -1;
  }

  return 0;
}