aboutsummaryrefslogtreecommitdiff
path: root/src/or/control.c
blob: 4e9206866e49feb52467bbda8465500fa3a2fa32 (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
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
/* Copyright 2004-2005 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.
 **/

#define NEW_LOG_INTERFACE
#include "or.h"

#define STATE_IS_OPEN(s) ((s) == CONTROL_CONN_STATE_OPEN_V0 ||       \
                          (s) == CONTROL_CONN_STATE_OPEN_V1)
#define STATE_IS_V0(s) ((s) == CONTROL_CONN_STATE_NEEDAUTH_V0 || \
                        (s) == CONTROL_CONN_STATE_OPEN_V0)

/*
 * See control-spec.txt and control-spec-v0.txt for full details on protocol(s).
 */

/* Recognized message type codes. */
#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

/* 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_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
#define _EVENT_MAX            0x000C

/** Array mapping from message type codes to human-readable message
 * type names. Used for compatibility with version 0 of the control
 * protocol. */
static const char * CONTROL0_COMMANDS[_CONTROL0_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_mask0 = 0;
static uint32_t global_event_mask1 = 0;

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

/** Macro: true if any control connection is interested in events of type
 * <b>e</b>. */
#define EVENT_IS_INTERESTING0(e) (global_event_mask0 & (1<<(e)))
#define EVENT_IS_INTERESTING1(e) (global_event_mask1 & (1<<(e)))
#define EVENT_IS_INTERESTING(e) \
  ((global_event_mask0|global_event_mask1) & (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 connection_printf_to_buf(connection_t *conn, const char *format, ...)
  CHECK_PRINTF(2,3);
/*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);
static void send_control0_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_control0_error(connection_t *conn, uint16_t error,
                               const char *message);
static void send_control0_event(uint16_t event, uint32_t len, const char *body);
static void send_control1_event(uint16_t event, const char *format, ...)
  CHECK_PRINTF(2,3);
static int handle_control_setconf(connection_t *conn, uint32_t len,
                                  char *body);
static int handle_control_resetconf(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);
static int handle_control_closestream(connection_t *conn, uint32_t len,
                                      const char *body);
static int handle_control_closecircuit(connection_t *conn, uint32_t len,
                                       const char *body);
static int write_stream_target_to_buf(connection_t *conn, char *buf, size_t len);

/** 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<=_CONTROL0_CMD_MAX_RECOGNIZED) ? CONTROL0_COMMANDS[cmd] : "Unknown";
}

/** Given a control event code for a message event, return the corresponding
 * log severity. */
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;
  }
}

/** Given a log severity, return the corresponding control event code. */
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;
  }
}

/** Set <b>global_event_maskX</b> (where X is 0 or 1) to the bitwise OR
 * of each live control connection's event_mask field. */
void
control_update_global_event_mask(void)
{
  connection_t **conns;
  int n_conns, i;
  global_event_mask0 = 0;
  global_event_mask1 = 0;
  get_connection_array(&conns, &n_conns);
  for (i = 0; i < n_conns; ++i) {
    if (conns[i]->type == CONN_TYPE_CONTROL &&
        STATE_IS_OPEN(conns[i]->state)) {
      if (STATE_IS_V0(conns[i]->state))
        global_event_mask0 |= conns[i]->event_mask;
      else
        global_event_mask1 |= conns[i]->event_mask;
    }
  }

  control_adjust_event_log_severity();
}

/** 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. */
void
control_adjust_event_log_severity(void)
{
  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;
    }
  }
  if (EVENT_IS_INTERESTING(EVENT_LOG_OBSOLETE)) {
    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);
}

/** Append a NUL-terminated string <b>s</b> to the end of
 * <b>conn</b>-\>outbuf
 */
static INLINE void
connection_write_str_to_buf(const char *s, connection_t *conn)
{
  size_t len = strlen(s);
  connection_write_to_buf(s, len, conn);
}

/** 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
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;
  for (i=0; i<(int)len; ++i) {
    if (data[i]== '\n')
      sz_out += 2; /* Maybe add a CR; maybe add a dot. */
  }
  *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++;
  }
  if (outp < *out+2 || memcmp(outp-2, "\r\n", 2)) {
    *outp++ = '\r';
    *outp++ = '\n';
  }
  *outp++ = '.';
  *outp++ = '\r';
  *outp++ = '\n';
  *outp = '\0'; /* NUL-terminate just in case. */
  tor_assert((outp - *out) <= (int)sz_out);
  return outp - *out;
}

/** 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
read_escaped_data(const char *data, size_t len, int translate_newlines,
                  char **out)
{
  char *outp;
  const char *next;
  const char *end;

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

  end = data+len;

  while (data < end) {
    if (*data == '.')
      ++data;
    if (translate_newlines)
      next = tor_memmem(data, end-data, "\r\n", 2);
    else
      next = tor_memmem(data, end-data, "\r\n.", 3);
    if (next) {
      memcpy(outp, data, next-data);
      outp += (next-data);
      data = next+2;
    } else {
      memcpy(outp, data, end-data);
      outp += (end-data);
      *outp = '\0';
      return outp - *out;
    }
    if (translate_newlines) {
      *outp++ = '\n';
    } else {
      *outp++ = '\r';
      *outp++ = '\n';
    }
  }

  *outp = '\0';
  return outp - *out;
}

/** 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
 * NULL. */
static const char *
get_escaped_string(const char *start, size_t in_len_max,
                   char **out, size_t *out_len)
{
  const char *cp, *end;
  char *outp;
  size_t len=0;

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

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

  /* 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;

  cp = start+1;
  while (cp < end) {
    if (*cp == '\\')
      ++cp;
    *outp++ = *cp++;
  }
  *outp = '\0';
  tor_assert((outp - *out) == (int)*out_len);

  return end+1;
}

/** 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.
 *
 * Currently the length of the message is limited to 1024 (including the
 * ending \n\r\0. */
static void
connection_printf_to_buf(connection_t *conn, const char *format, ...)
{
#define CONNECTION_PRINTF_TO_BUF_BUFFERSIZE 1024
  va_list ap;
  char buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE];
  int r;
  size_t len;
  va_start(ap,format);
  r = tor_vsnprintf(buf, sizeof(buf), format, ap);
  va_end(ap);
  len = strlen(buf);
  if (memcmp("\r\n\0", buf+len-2, 3)) {
    buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE-1] = '\0';
    buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE-2] = '\n';
    buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE-3] = '\r';
  }
  connection_write_to_buf(buf, len, conn);
}

/** 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_control0_message(connection_t *conn, uint16_t type, uint32_t len,
                     const char *body)
{
  char buf[10];
  tor_assert(conn);
  tor_assert(STATE_IS_V0(conn->state));
  tor_assert(len || !body);
  tor_assert(type <= _CONTROL0_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(CONTROL0_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(CONTROL0_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)
{
  if (STATE_IS_V0(conn->state)) {
    send_control0_message(conn, CONTROL0_CMD_DONE, 0, NULL);
  } else {
    connection_write_str_to_buf("250 OK\r\n", conn);
  }
}

/** 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>.
 */
static void
send_control_done2(connection_t *conn, const char *msg, size_t len)
{
  if (len==0)
    len = strlen(msg);
  send_control0_message(conn, CONTROL0_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_control0_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_control0_message(conn, CONTROL0_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_control0_event(uint16_t event, uint32_t len, const char *body)
{
  connection_t **conns;
  int n_conns, i;
  size_t buflen;
  char *buf;

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

  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]->marked_for_close &&
        conns[i]->state == CONTROL_CONN_STATE_OPEN_V0 &&
        conns[i]->event_mask & (1<<event)) {
      send_control0_message(conns[i], CONTROL0_CMD_EVENT, buflen, buf);
      if (event == EVENT_ERR_MSG)
        _connection_controller_force_write(conns[i]);
    }
  }

  tor_free(buf);
}

/* Send an event to all v1 controllers that are listening for code
 * <b>event</b>.  The event's body is given by <b>msg</b>. */
static void
send_control1_event_string(uint16_t event, const char *msg)
{
  connection_t **conns;
  int n_conns, i;

  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 &&
        !conns[i]->marked_for_close &&
        conns[i]->state == CONTROL_CONN_STATE_OPEN_V1 &&
        conns[i]->event_mask & (1<<event)) {
      connection_write_to_buf(msg, strlen(msg), conns[i]);
      if (event == EVENT_ERR_MSG)
        _connection_controller_force_write(conns[i]);
    }
  }
}

/* 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, const char *format, ...)
{
#define SEND_CONTROL1_EVENT_BUFFERSIZE 1024
  int r;
  char buf[SEND_CONTROL1_EVENT_BUFFERSIZE]; /* XXXX Length */
  va_list ap;
  size_t len;

  va_start(ap, format);
  r = tor_vsnprintf(buf, sizeof(buf), format, ap);
  va_end(ap);

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

  send_control1_event_string(event, buf);
}

/** Given a text circuit <b>id</b>, return the corresponding circuit. */
static circuit_t *
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);
}

/** Given a text stream <b>id</b>, return the corresponding AP connection. */
static connection_t *
get_stream(const char *id)
{
  unsigned long n_id;
  int ok;
  connection_t *conn;
  n_id = tor_parse_ulong(id, 10, 0, ULONG_MAX, &ok, NULL);
  if (!ok)
    return NULL;
  conn = connection_get_by_global_id(n_id);
  if (!conn || conn->type != CONN_TYPE_AP)
    return NULL;
  return conn;
}

/** Helper for setconf and resetconf. Acts like setconf, except
 * it passes <b>use_defaults</b> on to options_trial_assign().
 */
static int
control_setconf_helper(connection_t *conn, uint32_t len, char *body,
                       int use_defaults, int clear_first)
{
  int r;
  config_line_t *lines=NULL;
  char *start = body;
  int v0 = STATE_IS_V0(conn->state);

  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);
      *outp++ = ' ';
      body = eq+1;
      if (*eq == '=') {
        if (*body != '\"') {
          while (!TOR_ISSPACE(*body))
            *outp++ = *body++;
        } else {
          char *val;
          size_t val_len;
          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);
            tor_free(config);
            return 0;
          }
          memcpy(outp, val, val_len);
          outp += val_len;
          tor_free(val);
        }
      }
      while (TOR_ISSPACE(*body))
        ++body;
      *outp++ = '\n';
    }
    *outp = '\0';

    if (config_get_lines(config, &lines) < 0) {
      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);
      tor_free(config);
      return 0;
    }
    tor_free(config);
  } else {
    if (config_get_lines(body, &lines) < 0) {
      warn(LD_CONTROL,"Controller gave us config lines we can't parse.");
      send_control0_error(conn, ERR_SYNTAX, "Couldn't parse configuration");
      return 0;
    }
  }

  if ((r=options_trial_assign(lines, use_defaults, clear_first)) < 0) {
    int v0_err;
    const char *msg;
    warn(LD_CONTROL,"Controller gave us config lines that didn't validate.");
    switch (r) {
      case -1:
        v0_err = ERR_UNRECOGNIZED_CONFIG_KEY;
        msg = "Unrecognized option";
        break;
      case -2:
        v0_err = ERR_INVALID_CONFIG_VALUE;
        msg = "Unrecognized option value";
        break;
      case -3:
        v0_err = ERR_INVALID_CONFIG_VALUE;
        msg = "Transition not allowed";
        break;
      case -4:
      default:
        v0_err = ERR_INVALID_CONFIG_VALUE;
        msg = "Unable to set option";
        break;
    }
    if (v0) {
      send_control0_error(conn, v0_err, msg);
    } else {
      connection_printf_to_buf(conn, "552 %s\r\n", msg);
    }
    config_free_lines(lines);
    return 0;
  }
  config_free_lines(lines);
  send_control_done(conn);
  return 0;
}

/** 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)
{
  return control_setconf_helper(conn, len, body, 0, 1);
}

/** 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
handle_control_resetconf(connection_t *conn, uint32_t len, char *body)
{
  int v0 = STATE_IS_V0(conn->state);
  tor_assert(!v0);
  return control_setconf_helper(conn, len, body, 1, 1);
}

/** 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;
  smartlist_t *unrecognized = NULL;
  char *msg = NULL;
  size_t msg_len;
  or_options_t *options = get_options();
  int v0 = STATE_IS_V0(conn->state);

  questions = smartlist_create();
  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);
  }
  answers = smartlist_create();
  unrecognized = smartlist_create();
  SMARTLIST_FOREACH(questions, char *, q,
  {
    if (!option_is_recognized(q)) {
      if (v0) {
        send_control0_error(conn, ERR_UNRECOGNIZED_CONFIG_KEY, q);
        goto done;
      } else {
        smartlist_add(unrecognized, q);
      }
    } else {
      config_line_t *answer = option_get_assignment(options,q);
      if (!v0 && !answer) {
        const char *name = option_get_canonical_name(q);
        size_t alen = strlen(name)+8;
        char *astr = tor_malloc(alen);
        tor_snprintf(astr, alen, "250-%s\r\n", name);
        smartlist_add(answers, astr);
      }

      while (answer) {
        config_line_t *next;
        size_t alen = strlen(answer->key)+strlen(answer->value)+8;
        char *astr = tor_malloc(alen);
        if (v0)
          tor_snprintf(astr, alen, "%s %s\n", answer->key, answer->value);
        else
          tor_snprintf(astr, alen, "250-%s=%s\r\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;
      }
    }
  });

  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,
                                 "552-Unrecognized configuration key \"%s\"\r\n",
                                 (char*)smartlist_get(unrecognized, i));
      connection_printf_to_buf(conn,
                               "552 Unrecognized configuration key \"%s\"\r\n",
                               (char*)smartlist_get(unrecognized, len-1));
    } else if ((len = smartlist_len(answers))) {
      char *tmp = smartlist_get(answers, len-1);
      tor_assert(strlen(tmp)>4);
      tmp[3] = ' ';
      msg = smartlist_join_strings(answers, "", 0, &msg_len);
      connection_write_to_buf(msg, msg_len, conn);
    } else {
      connection_write_str_to_buf("250 OK\r\n", conn);
    }
  }

 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);
  smartlist_free(unrecognized);
  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;
  unsigned int extended = 0;

  if (STATE_IS_V0(conn->state)) {
    if (len % 2) {
      send_control0_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 > LAST_V0_EVENT) {
        send_control0_error(conn, ERR_UNRECOGNIZED_EVENT_CODE,
                            "Unrecognized event code");
        return 0;
      }
      event_mask |= (1 << event_code);
    }
  } else {
    smartlist_t *events = smartlist_create();
    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 {
          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);
  }
  conn->event_mask = event_mask;
  conn->control_events_are_extended = extended;

  control_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 (!strcmpstart(hashed, "16:")) {
    if (base16_decode(decoded, sizeof(decoded), hashed+3, strlen(hashed+3))<0
        || strlen(hashed+3) != (S2K_SPECIFIER_LEN+DIGEST_LEN)*2) {
      return -1;
    }
  } else {
      if (base64_decode(decoded, sizeof(decoded), hashed, strlen(hashed))
          != S2K_SPECIFIER_LEN+DIGEST_LEN) {
        return -1;
      }
  }
  if (buf)
    memcpy(buf, decoded, S2K_SPECIFIER_LEN+DIGEST_LEN);
  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)
{
  int used_quoted_string = 0;
  or_options_t *options = get_options();
  char *password;
  size_t password_len;
  if (STATE_IS_V0(conn->state)) {
    password = (char*)body;
    password_len = len;
  } else {
    if (TOR_ISXDIGIT(body[0])) {
      int i = 0;
      while (TOR_ISXDIGIT(body[i]))
        ++i;
      password = tor_malloc(i/2 + 1);
      if (base16_decode(password, i/2+1, body, i)<0) {
        connection_write_str_to_buf("551 Invalid hexadecimal encoding.  Maybe you tried a plain text password?  If so, the standard requires you put it in double quotes.\r\n", conn);
        tor_free(password);
        return 0;
      }
      password_len = i/2;
    } 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 to put the password in double quotes.\r\n", conn);
        return 0;
      }
      used_quoted_string = 1;
    }
  }
  if (options->CookieAuthentication) {
    if (len == AUTHENTICATION_COOKIE_LEN &&
        !memcmp(authentication_cookie, password, password_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) {
      warn(LD_CONTROL,"Couldn't decode HashedControlPassword: invalid base16");
      goto err;
    }
    secret_to_key(received,DIGEST_LEN,password,password_len,expected);
    if (!memcmp(expected+S2K_SPECIFIER_LEN, received, DIGEST_LEN))
      goto ok;
    goto err;
  } else {
    /* if Tor doesn't demand any stronger authentication, then
     * the controller can get in with anything. */
    goto ok;
  }

 err:
  if (STATE_IS_V0(conn->state))
    send_control0_error(conn,ERR_REJECTED_AUTHENTICATION,"Authentication failed");
  else {
    tor_free(password);
    if (used_quoted_string)
      connection_write_str_to_buf("515 Authentication failed\r\n", conn);
    else
      connection_write_str_to_buf("515 Authentication failed.  Maybe you tried a plain text password?  If so, the standard requires you put it in double quotes.\r\n", conn);
  }
  return 0;
 ok:
  info(LD_CONTROL, "Authenticated control connection (%d)", conn->s);
  send_control_done(conn);
  if (STATE_IS_V0(conn->state))
    conn->state = CONTROL_CONN_STATE_OPEN_V0;
  else {
    conn->state = CONTROL_CONN_STATE_OPEN_V1;
    tor_free(password);
  }
  return 0;
}

/** Called when we get a SAVECONF command. Try to flush the current options to
 * disk, and report success or failure. */
static int
handle_control_saveconf(connection_t *conn, uint32_t len,
                        const char *body)
{
  if (options_save_current()<0) {
    if (STATE_IS_V0(conn->state))
      send_control0_error(conn, ERR_INTERNAL,
                          "Unable to write configuration to disk.");
    else
      connection_write_str_to_buf("551 Unable to write configuration to disk.",
                                  conn);
  } else {
    send_control_done(conn);
  }
  return 0;
}

/** Called when we get a SIGNAL command. React to the provided signal, and
 * report success or failure. (If the signal results in a shutdown, success
 * may not be reported.) */
static int
handle_control_signal(connection_t *conn, uint32_t len,
                      const char *body)
{
  int sig;
  if (STATE_IS_V0(conn->state)) {
    if (len != 1) {
      send_control0_error(conn, ERR_SYNTAX,
                          "Body of SIGNAL command too long or too short.");
      return 0;
    } else {
      sig = (uint8_t)body[0];
    }
  } else {
    int n = 0;
    char *s;
    while (body[n] && ! TOR_ISSPACE(body[n]))
      ++n;
    s = tor_strndup(body, n);
    if (!strcasecmp(s, "RELOAD") || !strcasecmp(s, "HUP"))
      sig = SIGHUP;
    else if (!strcasecmp(s, "SHUTDOWN") || !strcasecmp(s, "INT"))
      sig = SIGINT;
    else if (!strcasecmp(s, "DUMP") || !strcasecmp(s, "USR1"))
      sig = SIGUSR1;
    else if (!strcasecmp(s, "DEBUG") || !strcasecmp(s, "USR2"))
      sig = SIGUSR2;
    else if (!strcasecmp(s, "HALT") || !strcasecmp(s, "TERM"))
      sig = SIGTERM;
    else {
      connection_printf_to_buf(conn, "552 Unrecognized signal code \"%s\"\r\n",
                               body);
      sig = -1;
    }
    tor_free(s);
    if (sig<0)
      return 0;
  }

  if (control_signal_act(sig) < 0) {
    if (STATE_IS_V0(conn->state))
      send_control0_error(conn, ERR_SYNTAX, "Unrecognized signal number.");
    else
      connection_write_str_to_buf("551 Internal error acting on signal\r\n",
                                  conn);
  } else {
    send_control_done(conn);
  }
  return 0;
}

/** Called when we get a MAPADDRESS command; try to bind all listed addresses,
 * and report success or failrue. */
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;
  int v0 = STATE_IS_V0(conn->state);
  lines = smartlist_create();
  elts = smartlist_create();
  reply = smartlist_create();
  if (v0)
    smartlist_split_string(lines, body, "\n",
                           SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  else
    smartlist_split_string(lines, body, " ",
                           SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  /* XXXX Make errors conformant. */
  SMARTLIST_FOREACH(lines, char *, line,
  {
    tor_strlower(line);
    if (v0)
      smartlist_split_string(elts, line, " ", 0, 2);
    else
      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)) {
        warn(LD_CONTROL,"Skipping invalid argument '%s' in MapAddress msg",from);
      } else if (!is_plausible_address(to)) {
        warn(LD_CONTROL,"Skipping invalid argument '%s' in MapAddress msg",to);
      } else if (!strcmp(from, ".") || !strcmp(from, "0.0.0.0")) {
        const char *address = addressmap_register_virtual_address(
              !strcmp(from,".") ? RESOLVED_TYPE_HOSTNAME : RESOLVED_TYPE_IPV4,
               tor_strdup(to));
        if (!address) {
          warn(LD_CONTROL,
               "Unable to allocate address for '%s' in MapAddress msg",
               safe_str(line));
        } else {
          size_t anslen = strlen(address)+strlen(to)+8;
          char *ans = tor_malloc(anslen);
          if (v0)
            tor_snprintf(ans, anslen, "%s %s", address, to);
          else
            tor_snprintf(ans, anslen, "250-%s=%s", address, to);
          smartlist_add(reply, ans);
        }
      } else {
        addressmap_register(from, tor_strdup(to), 1);
        if (v0)
          smartlist_add(reply, tor_strdup(line));
        else {
          size_t anslen = strlen(line)+8;
          char *ans = tor_malloc(anslen);
          tor_snprintf(ans, anslen, "250-%s", line);
          smartlist_add(reply, ans);
        }
      }
    } else {
      warn(LD_CONTROL, "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);

  if (v0) {
    r = smartlist_join_strings(reply, "\n", 1, &sz);
    send_control_done2(conn,r,sz);
  } else {
    if (smartlist_len(reply))
      ((char*)smartlist_get(reply,smartlist_len(reply)-1))[3] = ' ';
    r = smartlist_join_strings(reply, "\r\n", 1, &sz);
    connection_write_to_buf(r, sz, conn);
  }

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

/** Return a newly allocated string listing all valid GETINFO fields as
 * required by GETINFO info/names. */
static char *
list_getinfo_options(void)
{
  return tor_strdup(
    "accounting/bytes Number of bytes read/written so far in interval.\n"
    "accounting/bytes-left Number of bytes left to read/write in interval.\n"
    "accounting/enabled Is accounting currently enabled?\n"
    "accounting/hibernating Are we hibernating or awake?\n"
    "accounting/interval-end Time when interval ends.\n"
    "accounting/interval-start Time when interval starts.\n"
    "accounting/interval-wake Time to wake up in this interval.\n"
    "addr-mappings/all All current remapped addresses.\n"
    "addr-mappings/cache Addresses remapped by DNS cache.\n"
    "addr-mappings/configl Addresses remapped from configuration options.\n"
    "addr-mappings/control Addresses remapped by a controller.\n"
    "circuit-status Status of each current circuit.\n"
    "config/names List of configuration options, types, and documentation.\n"
    "desc/id/* Server descriptor by hex ID\n"
    "desc/name/* Server descriptor by nickname.\n"
    "helper-nodes Which nodes will we use as helpers?\n"
    "info/names List of GETINFO options, types, and documentation.\n"
    "network-status List of hex IDs, nicknames, server statuses.\n"
    "orconn-status Status of each current OR connection.\n"
    "stream-status Status of each current application stream.\n"
    "version The current version of Tor.\n");
}

/** Lookup the 'getinfo' entry <b>question</b>, and return
 * the answer in <b>*answer</b> (or NULL if key not recognized).
 * Return 0 if success, or -1 if internal error. */
static int
handle_getinfo_helper(const char *question, char **answer)
{
  *answer = NULL; /* unrecognized key by default */
  if (!strcmp(question, "version")) {
    *answer = tor_strdup(VERSION);
  } else if (!strcmp(question, "config-file")) {
    *answer = tor_strdup(get_torrc_fname());
  } else if (!strcmpstart(question, "accounting/")) {
    return accounting_getinfo_helper(question, answer);
  } else if (!strcmpstart(question, "helper-nodes")) {
    return helper_nodes_getinfo_helper(question, answer);
  } else if (!strcmpstart(question, "config/")) {
    return config_getinfo_helper(question, answer);
  } else if (!strcmp(question, "info/names")) {
    *answer = list_getinfo_options();
  } else if (!strcmpstart(question, "desc/id/")) {
    routerinfo_t *ri = router_get_by_hexdigest(question+strlen("desc/id/"));
    if (ri && ri->signed_descriptor)
      *answer = tor_strdup(ri->signed_descriptor);
  } else if (!strcmpstart(question, "desc/name/")) {
    routerinfo_t *ri = router_get_by_nickname(question+strlen("desc/name/"),1);
    if (ri && ri->signed_descriptor)
      *answer = tor_strdup(ri->signed_descriptor);
  } else if (!strcmpstart(question, "unregistered-servers-")) {
    *answer = dirserver_getinfo_unregistered(question +
                                             strlen("unregistered-servers-"));
  } else if (!strcmp(question, "network-status")) {
    routerlist_t *routerlist = router_get_routerlist();
    if (!routerlist || !routerlist->routers ||
        list_server_status(routerlist->routers, answer) < 0) {
      return -1;
    }
  } else if (!strcmp(question, "circuit-status")) {
    circuit_t *circ;
    smartlist_t *status = smartlist_create();
    for (circ = _circuit_get_global_list(); circ; circ = circ->next) {
      char *s, *path;
      size_t slen;
      const char *state;
      if (! CIRCUIT_IS_ORIGIN(circ) || circ->marked_for_close)
        continue;
      path = circuit_list_path(circ,0);
      if (circ->state == CIRCUIT_STATE_OPEN)
        state = "BUILT";
      else if (strlen(path))
        state = "EXTENDED";
      else
        state = "LAUNCHED";

      slen = strlen(path)+strlen(state)+20;
      s = tor_malloc(slen+1);
      tor_snprintf(s, slen, "%lu %s %s", (unsigned long)circ->global_identifier,
                   state, path);
      smartlist_add(status, s);
      tor_free(path);
    }
    *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
    SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
    smartlist_free(status);
  } else if (!strcmp(question, "stream-status")) {
    connection_t **conns;
    int n_conns, i;
    char buf[256];
    smartlist_t *status = smartlist_create();
    get_connection_array(&conns, &n_conns);
    for (i=0; i < n_conns; ++i) {
      const char *state;
      char *s;
      size_t slen;
      circuit_t *circ;
      if (conns[i]->type != CONN_TYPE_AP ||
          conns[i]->marked_for_close ||
          conns[i]->state == AP_CONN_STATE_SOCKS_WAIT)
        continue;
      switch (conns[i]->state)
        {
        case AP_CONN_STATE_CONTROLLER_WAIT:
        case AP_CONN_STATE_CIRCUIT_WAIT:
          if (conns[i]->socks_request &&
              conns[i]->socks_request->command == SOCKS_COMMAND_RESOLVE)
            state = "NEWRESOLVE";
          else
            state = "NEW";
          break;
        case AP_CONN_STATE_RENDDESC_WAIT:
        case AP_CONN_STATE_CONNECT_WAIT:
          state = "SENTCONNECT"; break;
        case AP_CONN_STATE_RESOLVE_WAIT:
          state = "SENTRESOLVE"; break;
        case AP_CONN_STATE_OPEN:
          state = "SUCCEEDED"; break;
        default:
          warn(LD_BUG, "Asked for stream in unknown state %d",
                 conns[i]->state);
          continue;
        }
      circ = circuit_get_by_edge_conn(conns[i]);
      write_stream_target_to_buf(conns[i], buf, sizeof(buf));
      slen = strlen(buf)+strlen(state)+32;
      s = tor_malloc(slen+1);
      tor_snprintf(s, slen, "%lu %s %lu %s",
                   (unsigned long) conns[i]->global_identifier,state,
                   circ?(unsigned long)circ->global_identifier : 0ul,
                   buf);
      smartlist_add(status, s);
    }
    *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
    SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
    smartlist_free(status);
  } else if (!strcmp(question, "orconn-status")) {
    connection_t **conns;
    int n_conns, i;
    smartlist_t *status = smartlist_create();
    get_connection_array(&conns, &n_conns);
    for (i=0; i < n_conns; ++i) {
      const char *state;
      char *s;
      size_t slen;
      if (conns[i]->type != CONN_TYPE_OR || conns[i]->marked_for_close)
        continue;
      if (conns[i]->state == OR_CONN_STATE_OPEN)
        state = "CONNECTED";
      else
        state = "LAUNCHED";
      slen = strlen(conns[i]->nickname)+strlen(state)+2;
      s = tor_malloc(slen+1);
      tor_snprintf(s, slen, "%s %s",conns[i]->nickname,state);
      smartlist_add(status, s);
    }
    *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
    SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
    smartlist_free(status);
  } else if (!strcmpstart(question, "addr-mappings/")) {
    time_t min_e, max_e;
    smartlist_t *mappings;
    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 0;
    }
    mappings = smartlist_create();
    addressmap_get_mappings(mappings, min_e, max_e);
    *answer = smartlist_join_strings(mappings, "\n", 0, NULL);
    SMARTLIST_FOREACH(mappings, char *, cp, tor_free(cp));
    smartlist_free(mappings);
  }
  return 0;
}

/** Called when we receive a GETINFO command.  Try to fetch all requested
 * information, and reply with information or error message. */
static int
handle_control_getinfo(connection_t *conn, uint32_t len, const char *body)
{
  smartlist_t *questions = NULL;
  smartlist_t *answers = NULL;
  smartlist_t *unrecognized = NULL;
  char *msg = NULL, *ans = NULL;
  size_t msg_len;
  int v0 = STATE_IS_V0(conn->state);

  questions = smartlist_create();
  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);
  answers = smartlist_create();
  unrecognized = smartlist_create();
  SMARTLIST_FOREACH(questions, const char *, q,
  {
    if (handle_getinfo_helper(q, &ans) < 0) {
      if (v0)
        send_control0_error(conn, ERR_INTERNAL, body);
      else
        connection_write_str_to_buf("551 Internal error\r\n", conn);
      goto done;
    }
    if (!ans) {
      if (v0) {
        send_control0_error(conn, ERR_UNRECOGNIZED_CONFIG_KEY, body);
        goto done;
      } else
        smartlist_add(unrecognized, (char*)q);
    } else {
      smartlist_add(answers, tor_strdup(q));
      smartlist_add(answers, ans);
    }
  });
  if (smartlist_len(unrecognized)) {
    int i;
    tor_assert(!v0);
    for (i=0; i < smartlist_len(unrecognized)-1; ++i)
      connection_printf_to_buf(conn,
                               "552-Unrecognized key \"%s\"\r\n",
                               (char*)smartlist_get(unrecognized, i));
    connection_printf_to_buf(conn,
                             "552 Unrecognized key \"%s\"\r\n",
                             (char*)smartlist_get(unrecognized, i));
    goto done;
  }

  if (v0) {
    msg = smartlist_join_strings2(answers, "\0", 1, 1, &msg_len);
    tor_assert(msg_len > 0); /* it will at least be terminated */
    send_control0_message(conn, CONTROL0_CMD_INFOVALUE,
                          msg_len, msg);
  } else if (smartlist_len(answers)) {
    int i;
    for (i = 0; i < smartlist_len(answers); i += 2) {
      char *k = smartlist_get(answers, i);
      char *v = smartlist_get(answers, i+1);
      /*XXXX Not an adequate test! XXXX011 */
      if (!strchr(v, '\n') && !strchr(v, '\r')) {
        connection_printf_to_buf(conn, "250-%s=", k);
        connection_write_str_to_buf(v, conn);
        connection_write_str_to_buf("\r\n", conn);
      } else {
        char *esc = NULL;
        size_t len;
        len = write_escaped_data(v, strlen(v), 1, &esc);
        connection_printf_to_buf(conn, "250+%s=\r\n", k);
        connection_write_to_buf(esc, len, conn);
        tor_free(esc);
      }
    }
    connection_write_str_to_buf("250 OK\r\n", conn);
  }

 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);
  smartlist_free(unrecognized);
  tor_free(msg);

  return 0;
}

/** Called when we get an EXTENDCIRCUIT message.  Try to extend the listed
 * circuit, and report success or failure. */
static int
handle_control_extendcircuit(connection_t *conn, uint32_t len,
                             const char *body)
{
  smartlist_t *router_nicknames=NULL, *routers=NULL;
  uint32_t circ_id;
  circuit_t *circ = NULL;
  int zero_circ, v0;
  char reply[4];

  v0 = STATE_IS_V0(conn->state);
  router_nicknames = smartlist_create();

  if (v0) {
    if (len<5) {
      send_control0_error(conn, ERR_SYNTAX, "extendcircuit message too short");
      goto done;
    }
    smartlist_split_string(router_nicknames, body+4, ",", 0, 0);
    circ_id = ntohl(get_uint32(body));
    if (!circ_id) {
      /* start a new circuit */
      zero_circ = 1;
    } else {
      circ = circuit_get_by_global_id(circ_id);
      zero_circ = 0;
      if (!circ) {
        send_control0_error(conn, ERR_NO_CIRC,
                            "No circuit found with given ID");
        goto done;
      }
    }
  } else { /* v1 */
    smartlist_t *args;
    args = smartlist_create();
    smartlist_split_string(args, body, " ",
                           SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
    if (smartlist_len(args)<2)
      connection_printf_to_buf(conn,"512 Missing argument to EXTENDCIRCUIT\r\n");

    zero_circ = !strcmp("0", (char*)smartlist_get(args,0));
    if (!zero_circ && !(circ = get_circ(smartlist_get(args,0)))) {
      connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
                               (char*)smartlist_get(args, 0));
    }
    smartlist_split_string(router_nicknames, smartlist_get(args,1), ",", 0, 0);

    SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
    smartlist_free(args);
    if (!zero_circ && !circ) {
      goto done;
    }
  }

  routers = smartlist_create();
  SMARTLIST_FOREACH(router_nicknames, const char *, n,
  {
    routerinfo_t *r = router_get_by_nickname(n, 1);
    if (!r) {
      if (v0)
        send_control0_error(conn, ERR_NO_ROUTER, n);
      else
        connection_printf_to_buf(conn, "552 No such router \"%s\"\r\n", n);
      goto done;
    }
    smartlist_add(routers, r);
  });
  if (!smartlist_len(routers)) {
    if (v0)
      send_control0_error(conn, ERR_SYNTAX, "No router names provided");
    else
      connection_write_str_to_buf("512 No router names provided\r\n", conn);
    goto done;
  }

  if (zero_circ) {
    /* start a new circuit */
    circ = circuit_init(CIRCUIT_PURPOSE_C_GENERAL, 0, 0, 0);
  }

  /* now circ refers to something that is ready to be extended */
  SMARTLIST_FOREACH(routers, routerinfo_t *, r,
  {
    extend_info_t *info = extend_info_from_router(r);
    circuit_append_new_exit(circ, info);
    extend_info_free(info);
  });

  /* now that we've populated the cpath, start extending */
  if (zero_circ) {
    if (circuit_handle_first_hop(circ) < 0) {
      circuit_mark_for_close(circ);
      if (v0)
        send_control0_error(conn, ERR_INTERNAL, "couldn't start circuit");
      else
        connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
      goto done;
    }
  } else {
    if (circ->state == CIRCUIT_STATE_OPEN) {
      circ->state = CIRCUIT_STATE_BUILDING;
      if (circuit_send_next_onion_skin(circ) < 0) {
        info(LD_CONTROL,"send_next_onion_skin failed; circuit marked for closing.");
        circuit_mark_for_close(circ);
        if (v0)
          send_control0_error(conn, ERR_INTERNAL, "couldn't send onion skin");
        else
          connection_write_str_to_buf("551 Couldn't send onion skinr\n", conn);
        goto done;
      }
    }
  }

  if (v0) {
    set_uint32(reply, htonl(circ->global_identifier));
    send_control_done2(conn, reply, sizeof(reply));
  } else {
    connection_printf_to_buf(conn, "250 EXTENDED %lu\r\n",
                             (unsigned long)circ->global_identifier);
  }
 done:
  SMARTLIST_FOREACH(router_nicknames, char *, n, tor_free(n));
  smartlist_free(router_nicknames);
  if (routers)
    smartlist_free(routers);
  return 0;
}

/** Called when we get an ATTACHSTREAM message.  Try to attach the requested
 * stream, and report success or failure. */
static int
handle_control_attachstream(connection_t *conn, uint32_t len,
                            const char *body)
{
  connection_t *ap_conn = NULL;
  circuit_t *circ = NULL;
  int zero_circ;

  if (STATE_IS_V0(conn->state)) {
    uint32_t conn_id;
    uint32_t circ_id;
    if (len < 8) {
      send_control0_error(conn, ERR_SYNTAX, "attachstream message too short");
      return 0;
    }

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

    if (!(ap_conn = connection_get_by_global_id(conn_id))) {
      send_control0_error(conn, ERR_NO_STREAM,
                          "No connection found with given ID");
      return 0;
    }
    if (circ_id && !(circ = circuit_get_by_global_id(circ_id))) {
      send_control0_error(conn, ERR_NO_CIRC, "No circuit found with given ID");
      return 0;
    }
  } else {
    smartlist_t *args;
    args = smartlist_create();
    smartlist_split_string(args, body, " ",
                           SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
    if (smartlist_len(args)<2)
      connection_printf_to_buf(conn,"512 Missing argument to ATTACHSTREAM\r\n");

    zero_circ = !strcmp("0", (char*)smartlist_get(args,1));

    if (!(ap_conn = get_stream(smartlist_get(args, 0)))) {
      connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
                               (char*)smartlist_get(args, 0));
    } else if (!zero_circ && !(circ = get_circ(smartlist_get(args, 1)))) {
      connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
                               (char*)smartlist_get(args, 1));
    }
    SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
    smartlist_free(args);
    if (!ap_conn || (!zero_circ && !circ))
      return 0;
  }

  if (ap_conn->state != AP_CONN_STATE_CONTROLLER_WAIT) {
    if (STATE_IS_V0(conn->state)) {
      send_control0_error(conn, ERR_NO_STREAM,
                          "Connection is not managed by controller.");
    } else {
      connection_write_str_to_buf(
                              "555 Connection is not managed by controller.\r\n",
                                  conn);
    }
    return 0;
  }

  if (zero_circ) {
    ap_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
    if (connection_ap_handshake_attach_circuit(ap_conn)<0)
      connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_CANT_ATTACH);
    send_control_done(conn);
    return 0;
  }
  if (circ->state != CIRCUIT_STATE_OPEN) {
    if (STATE_IS_V0(conn->state))
      send_control0_error(conn, ERR_INTERNAL, "Refuse to attach stream to non-open circ.");
    else
      connection_write_str_to_buf(
                              "551 Can't attach stream to non-open circuit\r\n",
                              conn);
    return 0;
  }
  if (connection_ap_handshake_attach_chosen_circuit(ap_conn, circ) != 1) {
    if (STATE_IS_V0(conn->state))
      send_control0_error(conn, ERR_INTERNAL, "Unable to attach stream.");
    else
      connection_write_str_to_buf("551 Unable to attach stream\r\n", conn);
    return 0;
  }
  send_control_done(conn);
  return 0;
}

/** Called when we get a POSTDESCRIPTOR message.  Try to learn the provided
 * descriptor, and report success or failure. */
static int
handle_control_postdescriptor(connection_t *conn, uint32_t len,
                              const char *body)
{
  char *desc;
  int v0 = STATE_IS_V0(conn->state);
  const char *msg=NULL;

  if (v0)
    desc = (char*)body;
  else {
    const char *cp = memchr(body, '\n', len);
    tor_assert(cp);
    read_escaped_data(cp, len-(cp-body), 1, &desc);
  }

  switch (router_load_single_router(desc, &msg)) {
  case -1:
    if (!msg) msg = "Could not parse descriptor";
    if (v0)
      send_control0_error(conn,ERR_SYNTAX,msg);
    else
      connection_printf_to_buf(conn, "554 %s\r\n", msg);
    break;
  case 0:
    if (!msg) msg = "Descriptor not added";
    if (v0)
      send_control_done2(conn,msg,0);
    else
      connection_printf_to_buf(conn, "251 %s\r\n",msg);
    break;
  case 1:
    send_control_done(conn);
    break;
  }

  if (!v0)
    tor_free(desc);
  return 0;
}

/** Called when we receive a REDIRECTSTERAM command.  Try to change the target
 * adderess of the named AP steream, and report success or failure. */
static int
handle_control_redirectstream(connection_t *conn, uint32_t len,
                              const char *body)
{
  connection_t *ap_conn = NULL;
  uint32_t conn_id;
  char *new_addr = NULL;
  if (STATE_IS_V0(conn->state)) {
    if (len < 6) {
      send_control0_error(conn, ERR_SYNTAX, "redirectstream 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_control0_error(conn, ERR_NO_STREAM,
                          "No AP connection found with given ID");
      return 0;
    }
    new_addr = tor_strdup(body+4);
  } else {
    smartlist_t *args;
    args = smartlist_create();
    smartlist_split_string(args, body, " ",
                           SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
    if (smartlist_len(args)<2)
      connection_printf_to_buf(conn,"512 Missing argument to REDIRECTSTREAM\r\n");
    else if (!(ap_conn = get_stream(smartlist_get(args, 0)))
             || !ap_conn->socks_request) {
      connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
                               (char*)smartlist_get(args, 0));
    } else {
      new_addr = tor_strdup(smartlist_get(args, 1));
    }

    SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
    smartlist_free(args);
    if (!new_addr)
      return 0;
  }

  strlcpy(ap_conn->socks_request->address, new_addr,
          sizeof(ap_conn->socks_request->address));
  tor_free(new_addr);
  send_control_done(conn);
  return 0;
}

/** Called when we get a CLOSESTREAM command; try to close the named stream
 * and report success or failure. */
static int
handle_control_closestream(connection_t *conn, uint32_t len,
                           const char *body)
{
  connection_t *ap_conn=NULL;
  uint8_t reason=0;

  if (STATE_IS_V0(conn->state)) {
    uint32_t conn_id;
    if (len < 6) {
      send_control0_error(conn, ERR_SYNTAX, "closestream message too short");
      return 0;
    }

    conn_id = ntohl(get_uint32(body));
    reason = *(uint8_t*)(body+4);

    if (!(ap_conn = connection_get_by_global_id(conn_id))
        || ap_conn->state != CONN_TYPE_AP
        || !ap_conn->socks_request) {
      send_control0_error(conn, ERR_NO_STREAM,
                          "No AP connection found with given ID");
      return 0;
    }
  } else {
    smartlist_t *args;
    int ok;
    args = smartlist_create();
    smartlist_split_string(args, body, " ",
                           SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
    if (smartlist_len(args)<2)
      connection_printf_to_buf(conn, "512 Missing argument to CLOSESTREAM\r\n");
    else if (!(ap_conn = get_stream(smartlist_get(args, 0))))
      connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
                               (char*)smartlist_get(args, 0));
    else {
      reason = (uint8_t) tor_parse_ulong(smartlist_get(args,1), 10, 0, 255,
                                         &ok, NULL);
      if (!ok) {
        connection_printf_to_buf(conn, "552 Unrecognized reason \"%s\"\r\n",
                                 (char*)smartlist_get(args, 1));
        ap_conn = NULL;
      }
    }
    SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
    smartlist_free(args);
    if (!ap_conn)
      return 0;
  }

  connection_mark_unattached_ap(ap_conn, reason);
  send_control_done(conn);
  return 0;
}

/** Called when we get a CLOSECIRCUIT command; try to close the named circuit
 * and report success or failure. */
static int
handle_control_closecircuit(connection_t *conn, uint32_t len,
                            const char *body)
{
  circuit_t *circ = NULL;
  int safe = 0;

  if (STATE_IS_V0(conn->state)) {
    uint32_t circ_id;
    if (len < 5) {
      send_control0_error(conn, ERR_SYNTAX, "closecircuit message too short");
      return 0;
    }
    circ_id = ntohl(get_uint32(body));
    safe = (*(uint8_t*)(body+4)) & 1;

    if (!(circ = circuit_get_by_global_id(circ_id))) {
      send_control0_error(conn, ERR_NO_CIRC,
                          "No circuit found with given ID");
      return 0;
    }
  } else {
    smartlist_t *args;
    args = smartlist_create();
    smartlist_split_string(args, body, " ",
                           SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
    if (smartlist_len(args)<1)
      connection_printf_to_buf(conn, "512 Missing argument to CLOSECIRCUIT\r\n");
    else if (!(circ=get_circ(smartlist_get(args, 0))))
      connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
                               (char*)smartlist_get(args, 0));
    else {
      int i;
      for (i=1; i < smartlist_len(args); ++i) {
        if (!strcasecmp(smartlist_get(args, i), "IfUnused"))
          safe = 1;
        else
          info(LD_CONTROL, "Skipping unknown option %s",
               (char*)smartlist_get(args,i));
      }
    }
    SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
    smartlist_free(args);
    if (!circ)
      return 0;
  }

  if (!safe || !circ->p_streams) {
    circuit_mark_for_close(circ);
  }

  send_control_done(conn);
  return 0;
}

/** Called when we get a v0 FRAGMENTHEADER or FRAGMENT command; try to append
 * the data to conn->incoming_cmd, setting conn->incoming_(type|len|cur_len)
 * as appropriate.  If the command is malformed, drop it and all pending
 * fragments and report failure.
 */
static int
handle_control_fragments(connection_t *conn, uint16_t command_type,
                         uint32_t body_len, char *body)
{
  if (command_type == CONTROL0_CMD_FRAGMENTHEADER) {
    if (conn->incoming_cmd) {
      warn(LD_CONTROL, "Dropping incomplete fragmented command");
      tor_free(conn->incoming_cmd);
    }
    if (body_len < 6) {
      send_control0_error(conn, ERR_SYNTAX, "FRAGMENTHEADER too short.");
      return 0;
    }
    conn->incoming_cmd_type = ntohs(get_uint16(body));
    conn->incoming_cmd_len = ntohl(get_uint32(body+2));
    conn->incoming_cmd_cur_len = 0;
    conn->incoming_cmd = tor_malloc(conn->incoming_cmd_len);
    body += 6;
    body_len -= 6;
  } else if (command_type == CONTROL0_CMD_FRAGMENT) {
    if (!conn->incoming_cmd) {
      send_control0_error(conn, ERR_SYNTAX, "Out-of-place FRAGMENT");
      return 0;
    }
  } else {
    tor_assert(0);
  }

  if (conn->incoming_cmd_cur_len + body_len > conn->incoming_cmd_len) {
    tor_free(conn->incoming_cmd);
    send_control0_error(conn, ERR_SYNTAX,
                       "Fragmented data exceeds declared length");
    return 0;
  }
  memcpy(conn->incoming_cmd + conn->incoming_cmd_cur_len,
         body, body_len);
  conn->incoming_cmd_cur_len += body_len;
  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)
{
  tor_assert(conn);
  tor_assert(conn->type == CONN_TYPE_CONTROL);

  info(LD_CONTROL,"Control connection reached EOF. Closing.");
  connection_mark_for_close(conn);
  return 0;
}

/** Called when data has arrived on a v1 control connection: Try to fetch
 * commands from conn->inbuf, and execute them.
 */
static int
connection_control_process_inbuf_v1(connection_t *conn)
{
  size_t data_len;
  int cmd_len;
  char *args;

  tor_assert(conn);
  tor_assert(conn->type == CONN_TYPE_CONTROL);
  tor_assert(conn->state == CONTROL_CONN_STATE_OPEN_V1 ||
             conn->state == CONTROL_CONN_STATE_NEEDAUTH_V1);

  if (!conn->incoming_cmd) {
    conn->incoming_cmd = tor_malloc(1024);
    conn->incoming_cmd_len = 1024;
    conn->incoming_cmd_cur_len = 0;
  }

 again:
  while (1) {
    size_t last_idx;
    int r;
    /* First, fetch a line. */
    do {
      data_len = conn->incoming_cmd_len - conn->incoming_cmd_cur_len;
      r = fetch_from_buf_line(conn->inbuf,
                              conn->incoming_cmd+conn->incoming_cmd_cur_len,
                              &data_len);
      if (r == 0)
        /* Line not all here yet. Wait. */
        return 0;
      else if (r == -1) {
          while (conn->incoming_cmd_len < data_len+conn->incoming_cmd_cur_len)
            conn->incoming_cmd_len *= 2;
          conn->incoming_cmd = tor_realloc(conn->incoming_cmd,
                                           conn->incoming_cmd_len);
      }
    } while (r != 1);

    tor_assert(data_len);

    last_idx = conn->incoming_cmd_cur_len;
    conn->incoming_cmd_cur_len += data_len;

    /* We have appended a line to incoming_cmd.  Is the command done? */
    if (last_idx == 0 && *conn->incoming_cmd != '+')
      /* One line command, didn't start with '+'. */
      break;
    if (last_idx+3 == conn->incoming_cmd_cur_len &&
        !memcmp(conn->incoming_cmd + last_idx, ".\r\n", 3)) {
      /* Just appended ".\r\n"; we're done. Remove it. */
      conn->incoming_cmd_cur_len -= 3;
      break;
    }
    /* Otherwise, read another line. */
  }
  data_len = conn->incoming_cmd_cur_len;
  /* Okay, we now have a command sitting on conn->incoming_cmd. See if we
   * recognize it.
   */
  cmd_len = 0;
  while ((size_t)cmd_len < data_len
         && !TOR_ISSPACE(conn->incoming_cmd[cmd_len]))
    ++cmd_len;

  data_len -= cmd_len;
  conn->incoming_cmd[cmd_len]='\0';
  args = conn->incoming_cmd+cmd_len+1;
  while (*args == ' ' || *args == '\t') {
    ++args;
    --data_len;
  }

  if (!strcasecmp(conn->incoming_cmd, "QUIT")) {
    connection_write_str_to_buf("250 closing connection\r\n", conn);
    connection_mark_for_close(conn);
    return 0;
  }

  if (conn->state == CONTROL_CONN_STATE_NEEDAUTH_V1 &&
      strcasecmp(conn->incoming_cmd, "AUTHENTICATE")) {
    connection_write_str_to_buf("514 Authentication required.\r\n", conn);
    conn->incoming_cmd_cur_len = 0;
    goto again;
  }

  if (!strcasecmp(conn->incoming_cmd, "SETCONF")) {
    if (handle_control_setconf(conn, data_len, args))
      return -1;
  } else if (!strcasecmp(conn->incoming_cmd, "RESETCONF")) {
    if (handle_control_resetconf(conn, data_len, args))
      return -1;
  } else if (!strcasecmp(conn->incoming_cmd, "GETCONF")) {
    if (handle_control_getconf(conn, data_len, args))
      return -1;
  } else if (!strcasecmp(conn->incoming_cmd, "SETEVENTS")) {
    if (handle_control_setevents(conn, data_len, args))
      return -1;
  } else if (!strcasecmp(conn->incoming_cmd, "AUTHENTICATE")) {
    if (handle_control_authenticate(conn, data_len, args))
      return -1;
  } else if (!strcasecmp(conn->incoming_cmd, "SAVECONF")) {
    if (handle_control_saveconf(conn, data_len, args))
      return -1;
  } else if (!strcasecmp(conn->incoming_cmd, "SIGNAL")) {
    if (handle_control_signal(conn, data_len, args))
      return -1;
  } else if (!strcasecmp(conn->incoming_cmd, "MAPADDRESS")) {
    if (handle_control_mapaddress(conn, data_len, args))
      return -1;
  } else if (!strcasecmp(conn->incoming_cmd, "GETINFO")) {
    if (handle_control_getinfo(conn, data_len, args))
      return -1;
  } else if (!strcasecmp(conn->incoming_cmd, "EXTENDCIRCUIT")) {
    if (handle_control_extendcircuit(conn, data_len, args))
      return -1;
  } else if (!strcasecmp(conn->incoming_cmd, "ATTACHSTREAM")) {
    if (handle_control_attachstream(conn, data_len, args))
      return -1;
  } else if (!strcasecmp(conn->incoming_cmd, "+POSTDESCRIPTOR")) {
    if (handle_control_postdescriptor(conn, data_len, args))
      return -1;
  } else if (!strcasecmp(conn->incoming_cmd, "REDIRECTSTREAM")) {
    if (handle_control_redirectstream(conn, data_len, args))
      return -1;
  } else if (!strcasecmp(conn->incoming_cmd, "CLOSESTREAM")) {
    if (handle_control_closestream(conn, data_len, args))
      return -1;
  } else if (!strcasecmp(conn->incoming_cmd, "CLOSECIRCUIT")) {
    if (handle_control_closecircuit(conn, data_len, args))
      return -1;
  } else {
    connection_printf_to_buf(conn, "510 Unrecognized command \"%s\"\r\n",
                             conn->incoming_cmd);
  }

  conn->incoming_cmd_cur_len = 0;
  goto again;
}

/** Called when data has arrived on a v0 control connection: Try to fetch
 * commands from conn->inbuf, and execute them.
 */
static int
connection_control_process_inbuf_v0(connection_t *conn)
{
  uint32_t body_len;
  uint16_t command_type;
  char *body=NULL;

 again:
  /* Try to suck a control message from the buffer. */
  switch (fetch_from_buf_control0(conn->inbuf, &body_len, &command_type, &body,
                                  conn->state == CONTROL_CONN_STATE_NEEDAUTH_V0))
    {
    case -2:
      tor_free(body);
      info(LD_CONTROL, "Detected v1 control protocol on connection (fd %d)",
           conn->s);
      conn->state = CONTROL_CONN_STATE_NEEDAUTH_V1;
      return connection_control_process_inbuf_v1(conn);
    case -1:
      tor_free(body);
      warn(LD_CONTROL, "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_V0 &&
      command_type != CONTROL0_CMD_AUTHENTICATE) {
    info(LD_CONTROL, "Rejecting '%s' command; authentication needed.",
         control_cmd_to_string(command_type));
    send_control0_error(conn, ERR_UNAUTHORIZED, "Authentication required");
    tor_free(body);
    goto again;
  }

  if (command_type == CONTROL0_CMD_FRAGMENTHEADER ||
      command_type == CONTROL0_CMD_FRAGMENT) {
    if (handle_control_fragments(conn, command_type, body_len, body))
      return -1;
    tor_free(body);
    if (conn->incoming_cmd_cur_len != conn->incoming_cmd_len)
      goto again;

    command_type = conn->incoming_cmd_type;
    body_len = conn->incoming_cmd_len;
    body = conn->incoming_cmd;
    conn->incoming_cmd = NULL;
  } else if (conn->incoming_cmd) {
    warn(LD_CONTROL, "Dropping incomplete fragmented command");
    tor_free(conn->incoming_cmd);
  }

  /* Okay, we're willing to process the command. */
  switch (command_type)
    {
    case CONTROL0_CMD_SETCONF:
      if (handle_control_setconf(conn, body_len, body))
        return -1;
      break;
    case CONTROL0_CMD_GETCONF:
      if (handle_control_getconf(conn, body_len, body))
        return -1;
      break;
    case CONTROL0_CMD_SETEVENTS:
      if (handle_control_setevents(conn, body_len, body))
        return -1;
      break;
    case CONTROL0_CMD_AUTHENTICATE:
      if (handle_control_authenticate(conn, body_len, body))
        return -1;
      break;
    case CONTROL0_CMD_SAVECONF:
      if (handle_control_saveconf(conn, body_len, body))
        return -1;
      break;
    case CONTROL0_CMD_SIGNAL:
      if (handle_control_signal(conn, body_len, body))
        return -1;
      break;
    case CONTROL0_CMD_MAPADDRESS:
      if (handle_control_mapaddress(conn, body_len, body))
        return -1;
      break;
    case CONTROL0_CMD_GETINFO:
      if (handle_control_getinfo(conn, body_len, body))
        return -1;
      break;
    case CONTROL0_CMD_EXTENDCIRCUIT:
      if (handle_control_extendcircuit(conn, body_len, body))
        return -1;
      break;
    case CONTROL0_CMD_ATTACHSTREAM:
      if (handle_control_attachstream(conn, body_len, body))
        return -1;
      break;
    case CONTROL0_CMD_POSTDESCRIPTOR:
      if (handle_control_postdescriptor(conn, body_len, body))
        return -1;
      break;
    case CONTROL0_CMD_REDIRECTSTREAM:
      if (handle_control_redirectstream(conn, body_len, body))
        return -1;
      break;
    case CONTROL0_CMD_CLOSESTREAM:
      if (handle_control_closestream(conn, body_len, body))
        return -1;
      break;
    case CONTROL0_CMD_CLOSECIRCUIT:
      if (handle_control_closecircuit(conn, body_len, body))
        return -1;
      break;
    case CONTROL0_CMD_ERROR:
    case CONTROL0_CMD_DONE:
    case CONTROL0_CMD_CONFVALUE:
    case CONTROL0_CMD_EVENT:
    case CONTROL0_CMD_INFOVALUE:
      warn(LD_CONTROL, "Received client-only '%s' command; ignoring.",
             control_cmd_to_string(command_type));
      send_control0_error(conn, ERR_UNRECOGNIZED_TYPE,
                         "Command type only valid from server to tor client");
      break;
    case CONTROL0_CMD_FRAGMENTHEADER:
    case CONTROL0_CMD_FRAGMENT:
      warn(LD_CONTROL, "Recieved command fragment out of order; ignoring.");
      send_control0_error(conn, ERR_SYNTAX, "Bad fragmentation on command.");
    default:
      warn(LD_CONTROL, "Received unrecognized command type %d; ignoring.",
             (int)command_type);
      send_control0_error(conn, ERR_UNRECOGNIZED_TYPE,
                         "Unrecognized command type");
      break;
  }
  tor_free(body);
  goto again; /* There might be more data. */
}

/** Called when <b>conn</b> has received more bytes on its inbuf.
 */
int
connection_control_process_inbuf(connection_t *conn)
{
  tor_assert(conn);
  tor_assert(conn->type == CONN_TYPE_CONTROL);

  if (STATE_IS_V0(conn->state))
    return connection_control_process_inbuf_v0(conn);
  else
    return connection_control_process_inbuf_v1(conn);
}

/** 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;
  if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS))
    return 0;
  tor_assert(circ);
  tor_assert(CIRCUIT_IS_ORIGIN(circ));

  path = circuit_list_path(circ,0);
  if (EVENT_IS_INTERESTING0(EVENT_CIRCUIT_STATUS)) {
    size_t 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_control0_event(EVENT_CIRCUIT_STATUS, (uint32_t)(path_len+6), msg);
    tor_free(msg);
  }
  if (EVENT_IS_INTERESTING1(EVENT_CIRCUIT_STATUS)) {
    const char *status;
    switch (tp)
      {
      case CIRC_EVENT_LAUNCHED: status = "LAUNCHED"; break;
      case CIRC_EVENT_BUILT: status = "BUILT"; break;
      case CIRC_EVENT_EXTENDED: status = "EXTENDED"; break;
      case CIRC_EVENT_FAILED: status = "FAILED"; break;
      case CIRC_EVENT_CLOSED: status = "CLOSED"; break;
      default:
        warn(LD_BUG, "Unrecognized status code %d", (int)tp);
        return 0;
      }
    send_control1_event(EVENT_CIRCUIT_STATUS,
                        "650 CIRC %lu %s %s\r\n",
                        (unsigned long)circ->global_identifier,
                        status, path);
  }
  tor_free(path);

  return 0;
}

/** Given an AP connection <b>conn</b> and a <b>len</b>-character buffer
 * <b>buf</b>, determine the address:port combination requested on
 * <b>conn</b>, and write it to <b>buf</b>.  Return 0 on success, -1 on
 * failure. */
static int
write_stream_target_to_buf(connection_t *conn, char *buf, size_t len)
{
  char buf2[256];
  if (conn->chosen_exit_name)
    if (tor_snprintf(buf2, sizeof(buf2), ".%s.exit", conn->chosen_exit_name)<0)
      return -1;
  if (tor_snprintf(buf, len, "%s%s:%d",
                   conn->socks_request->address,
                   conn->chosen_exit_name ? buf2 : "",
                   conn->socks_request->port)<0)
    return -1;
  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;

  write_stream_target_to_buf(conn, buf, sizeof(buf));
  if (EVENT_IS_INTERESTING0(EVENT_STREAM_STATUS)) {
    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_control0_event(EVENT_STREAM_STATUS, (uint32_t)(5+len+1), msg);
    tor_free(msg);
  }
  if (EVENT_IS_INTERESTING1(EVENT_STREAM_STATUS)) {
    const char *status;
    circuit_t *circ;
    switch (tp)
      {
      case STREAM_EVENT_SENT_CONNECT: status = "SENTCONNECT"; break;
      case STREAM_EVENT_SENT_RESOLVE: status = "SENTRESOLVE"; break;
      case STREAM_EVENT_SUCCEEDED: status = "SUCCEEDED"; break;
      case STREAM_EVENT_FAILED: status = "FAILED"; break;
      case STREAM_EVENT_CLOSED: status = "CLOSED"; break;
      case STREAM_EVENT_NEW: status = "NEW"; break;
      case STREAM_EVENT_NEW_RESOLVE: status = "NEWRESOLVE"; break;
      case STREAM_EVENT_FAILED_RETRIABLE: status = "DETACHED"; break;
      default:
        warn(LD_BUG, "Unrecognized status code %d", (int)tp);
        return 0;
      }
    circ = circuit_get_by_edge_conn(conn);
    send_control1_event(EVENT_STREAM_STATUS,
                        "650 STREAM %lu %s %lu %s\r\n",
                        (unsigned long)conn->global_identifier, status,
                        circ?(unsigned long)circ->global_identifier : 0ul,
                        buf);
    /* XXX need to specify its intended exit, etc? */
  }
  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;

  if (EVENT_IS_INTERESTING0(EVENT_OR_CONN_STATUS)) {
    buf[0] = (uint8_t)tp;
    strlcpy(buf+1,conn->nickname,sizeof(buf)-1);
    len = strlen(buf+1);
    send_control0_event(EVENT_OR_CONN_STATUS, (uint32_t)(len+1), buf);
  }
  if (EVENT_IS_INTERESTING1(EVENT_OR_CONN_STATUS)) {
    const char *status;
    switch (tp)
      {
      case OR_CONN_EVENT_LAUNCHED: status = "LAUNCHED"; break;
      case OR_CONN_EVENT_CONNECTED: status = "CONNECTED"; break;
      case OR_CONN_EVENT_FAILED: status = "FAILED"; break;
      case OR_CONN_EVENT_CLOSED: status = "CLOSED"; break;
      default:
        warn(LD_BUG, "Unrecognized status code %d", (int)tp);
        return 0;
      }
    send_control1_event(EVENT_OR_CONN_STATUS,
                        "650 ORCONN %s %s\r\n",
                        conn->nickname, status);
  }
  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_INTERESTING0(EVENT_BANDWIDTH_USED)) {
    set_uint32(buf, htonl(n_read));
    set_uint32(buf+4, htonl(n_written));
    send_control0_event(EVENT_BANDWIDTH_USED, 8, buf);
  }
  if (EVENT_IS_INTERESTING1(EVENT_BANDWIDTH_USED)) {
    send_control1_event(EVENT_BANDWIDTH_USED,
                        "650 BW %lu %lu\r\n",
                        (unsigned long)n_read,
                        (unsigned long)n_written);
  }

  return 0;
}

/** Called when we are sending a log message to the controllers: suspend
 * sending further log messages to the controllers until we're done.  Used by
 * CONN_LOG_PROTECT. */
void
disable_control_logging(void)
{
  ++disable_log_messages;
}

/** We're done sending a log message to the controllers: re-enable controller
 * logging.  Used by CONN_LOG_PROTECT. */
void
enable_control_logging(void)
{
  if (--disable_log_messages < 0)
    tor_assert(0);
}

/** We got a log message: tell any interested control connections. */
void
control_event_logmsg(int severity, int domain, const char *msg)
{
  int oldlog, event;

  if (disable_log_messages)
    return;

  oldlog = EVENT_IS_INTERESTING0(EVENT_LOG_OBSOLETE) &&
    (severity == LOG_NOTICE || severity == LOG_WARN || severity == LOG_ERR);
  event = log_severity_to_event(severity);

  if (event<0 || !EVENT_IS_INTERESTING0(event))
    event = 0;

  if (oldlog || event) {
    size_t len = strlen(msg);
    ++disable_log_messages;
    if (event)
      send_control0_event(event, (uint32_t)(len+1), msg);
    if (oldlog)
      send_control0_event(EVENT_LOG_OBSOLETE, (uint32_t)(len+1), msg);
    --disable_log_messages;
  }

  event = log_severity_to_event(severity);
  if (event >= 0 && EVENT_IS_INTERESTING1(event)) {
    char *b = NULL;
    const char *s;
    if (strchr(msg, '\n')) {
      char *cp;
      b = tor_strdup(msg);
      for (cp = b; *cp; ++cp)
        if (*cp == '\r' || *cp == '\n')
          *cp = ' ';
    }
    switch (severity) {
      case LOG_DEBUG: s = "DEBUG"; break;
      case LOG_INFO: s = "INFO"; break;
      case LOG_NOTICE: s = "NOTICE"; break;
      case LOG_WARN: s = "WARN"; break;
      case LOG_ERR: s = "ERR"; break;
      default: s = "UnknownLogSeverity"; break;
    }
    ++disable_log_messages;
    send_control1_event(event, "650 %s %s\r\n", s, b?b:msg);
    --disable_log_messages;
    tor_free(b);
  }
}

/** 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));
  });
  if (EVENT_IS_INTERESTING0(EVENT_NEW_DESC)) {
    msg = smartlist_join_strings(identities, ",", 0, &len);
    send_control0_event(EVENT_NEW_DESC, len+1, msg);
    tor_free(msg);
  }
  if (EVENT_IS_INTERESTING1(EVENT_NEW_DESC)) {
    msg = smartlist_join_strings(identities, " ", 0, &len);
    send_control1_event(EVENT_NEW_DESC, "650 NEWDESC %s\r\n", msg);
    tor_free(msg);
  }
  SMARTLIST_FOREACH(identities, char *, cp, tor_free(cp));
  smartlist_free(identities);

  return 0;
}

/** Called whenever an address mapping on <b>from<b> from changes to <b>to</b>.
 * <b>expires</b> values less than 3 are special; see connection_edge.c. */
int
control_event_address_mapped(const char *from, const char *to, time_t expires)
{
  if (!EVENT_IS_INTERESTING1(EVENT_ADDRMAP))
    return 0;

  if (expires < 3)
    send_control1_event(EVENT_ADDRMAP, "650 ADDRMAP %s %s NEVER\r\n", from, to);
  else {
    char buf[ISO_TIME_LEN+1];
    format_local_iso_time(buf,expires);
    send_control1_event(EVENT_ADDRMAP, "650 ADDRMAP %s %s \"%s\"\r\n",
                        from, to, buf);
  }

  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)) {
    warn(LD_FS,"Error writing authentication cookie.");
    return -1;
  }

  return 0;
}