aboutsummaryrefslogtreecommitdiffstats
path: root/tools/xenstore/xenstored_core.c
blob: 0f8ba64499d39d57183c96d4e35b0a254befe885 (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
/* 
    Simple prototype Xen Store Daemon providing simple tree-like database.
    Copyright (C) 2005 Rusty Russell IBM Corporation

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

#include <sys/types.h>
#include <sys/stat.h>
#include <poll.h>
#ifndef NO_SOCKETS
#include <sys/socket.h>
#include <sys/un.h>
#endif
#include <sys/time.h>
#include <time.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <syslog.h>
#include <string.h>
#include <errno.h>
#include <dirent.h>
#include <getopt.h>
#include <signal.h>
#include <assert.h>
#include <setjmp.h>

#include "utils.h"
#include "list.h"
#include "talloc.h"
#include "xenstore_lib.h"
#include "xenstored_core.h"
#include "xenstored_watch.h"
#include "xenstored_transaction.h"
#include "xenstored_domain.h"
#include "xenctrl.h"
#include "tdb.h"

#include "hashtable.h"

extern xc_evtchn *xce_handle; /* in xenstored_domain.c */
static int xce_pollfd_idx = -1;
static struct pollfd *fds;
static unsigned int current_array_size;
static unsigned int nr_fds;

#define ROUNDUP(_x, _w) (((unsigned long)(_x)+(1UL<<(_w))-1) & ~((1UL<<(_w))-1))

static bool verbose = false;
LIST_HEAD(connections);
static int tracefd = -1;
static bool recovery = true;
static bool remove_local = true;
static int reopen_log_pipe[2];
static int reopen_log_pipe0_pollfd_idx = -1;
static char *tracefile = NULL;
static TDB_CONTEXT *tdb_ctx = NULL;

static void corrupt(struct connection *conn, const char *fmt, ...);
static void check_store(void);

#define log(...)							\
	do {								\
		char *s = talloc_asprintf(NULL, __VA_ARGS__);		\
		trace("%s\n", s);					\
		syslog(LOG_ERR, "%s",  s);				\
		talloc_free(s);						\
	} while (0)


int quota_nb_entry_per_domain = 1000;
int quota_nb_watch_per_domain = 128;
int quota_max_entry_size = 2048; /* 2K */
int quota_max_transaction = 10;

TDB_CONTEXT *tdb_context(struct connection *conn)
{
	/* conn = NULL used in manual_node at setup. */
	if (!conn || !conn->transaction)
		return tdb_ctx;
	return tdb_transaction_context(conn->transaction);
}

bool replace_tdb(const char *newname, TDB_CONTEXT *newtdb)
{
	if (!(tdb_ctx->flags & TDB_INTERNAL))
		if (rename(newname, xs_daemon_tdb()) != 0)
			return false;
	tdb_close(tdb_ctx);
	tdb_ctx = talloc_steal(talloc_autofree_context(), newtdb);
	return true;
}

static char *sockmsg_string(enum xsd_sockmsg_type type)
{
	switch (type) {
	case XS_DEBUG: return "DEBUG";
	case XS_DIRECTORY: return "DIRECTORY";
	case XS_READ: return "READ";
	case XS_GET_PERMS: return "GET_PERMS";
	case XS_WATCH: return "WATCH";
	case XS_UNWATCH: return "UNWATCH";
	case XS_TRANSACTION_START: return "TRANSACTION_START";
	case XS_TRANSACTION_END: return "TRANSACTION_END";
	case XS_INTRODUCE: return "INTRODUCE";
	case XS_RELEASE: return "RELEASE";
	case XS_GET_DOMAIN_PATH: return "GET_DOMAIN_PATH";
	case XS_WRITE: return "WRITE";
	case XS_MKDIR: return "MKDIR";
	case XS_RM: return "RM";
	case XS_SET_PERMS: return "SET_PERMS";
	case XS_WATCH_EVENT: return "WATCH_EVENT";
	case XS_ERROR: return "ERROR";
	case XS_IS_DOMAIN_INTRODUCED: return "XS_IS_DOMAIN_INTRODUCED";
	case XS_RESUME: return "RESUME";
	case XS_SET_TARGET: return "SET_TARGET";
	case XS_RESET_WATCHES: return "RESET_WATCHES";
	default:
		return "**UNKNOWN**";
	}
}

void trace(const char *fmt, ...)
{
	va_list arglist;
	char *str;
	char sbuf[1024];
	int ret, dummy;

	if (tracefd < 0)
		return;

	/* try to use a static buffer */
	va_start(arglist, fmt);
	ret = vsnprintf(sbuf, 1024, fmt, arglist);
	va_end(arglist);

	if (ret <= 1024) {
		dummy = write(tracefd, sbuf, ret);
		return;
	}

	/* fail back to dynamic allocation */
	va_start(arglist, fmt);
	str = talloc_vasprintf(NULL, fmt, arglist);
	va_end(arglist);
	dummy = write(tracefd, str, strlen(str));
	talloc_free(str);
}

static void trace_io(const struct connection *conn,
		     const struct buffered_data *data,
		     int out)
{
	unsigned int i;
	time_t now;
	struct tm *tm;

#ifdef HAVE_DTRACE
	dtrace_io(conn, data, out);
#endif

	if (tracefd < 0)
		return;

	now = time(NULL);
	tm = localtime(&now);

	trace("%s %p %04d%02d%02d %02d:%02d:%02d %s (",
	      out ? "OUT" : "IN", conn,
	      tm->tm_year + 1900, tm->tm_mon + 1,
	      tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec,
	      sockmsg_string(data->hdr.msg.type));
	
	for (i = 0; i < data->hdr.msg.len; i++)
		trace("%c", (data->buffer[i] != '\0') ? data->buffer[i] : ' ');
	trace(")\n");
}

void trace_create(const void *data, const char *type)
{
	trace("CREATE %s %p\n", type, data);
}

void trace_destroy(const void *data, const char *type)
{
	trace("DESTROY %s %p\n", type, data);
}

/**
 * Signal handler for SIGHUP, which requests that the trace log is reopened
 * (in the main loop).  A single byte is written to reopen_log_pipe, to awaken
 * the poll() in the main loop.
 */
static void trigger_reopen_log(int signal __attribute__((unused)))
{
	char c = 'A';
	int dummy;
	dummy = write(reopen_log_pipe[1], &c, 1);
}


static void reopen_log(void)
{
	if (tracefile) {
		if (tracefd > 0)
			close(tracefd);

		tracefd = open(tracefile, O_WRONLY|O_CREAT|O_APPEND, 0600);

		if (tracefd < 0)
			perror("Could not open tracefile");
		else
			trace("\n***\n");
	}
}

static bool write_messages(struct connection *conn)
{
	int ret;
	struct buffered_data *out;

	out = list_top(&conn->out_list, struct buffered_data, list);
	if (out == NULL)
		return true;

	if (out->inhdr) {
		if (verbose)
			xprintf("Writing msg %s (%.*s) out to %p\n",
				sockmsg_string(out->hdr.msg.type),
				out->hdr.msg.len,
				out->buffer, conn);
		ret = conn->write(conn, out->hdr.raw + out->used,
				  sizeof(out->hdr) - out->used);
		if (ret < 0)
			return false;

		out->used += ret;
		if (out->used < sizeof(out->hdr))
			return true;

		out->inhdr = false;
		out->used = 0;

		/* Second write might block if non-zero. */
		if (out->hdr.msg.len && !conn->domain)
			return true;
	}

	ret = conn->write(conn, out->buffer + out->used,
			  out->hdr.msg.len - out->used);
	if (ret < 0)
		return false;

	out->used += ret;
	if (out->used != out->hdr.msg.len)
		return true;

	trace_io(conn, out, 1);

	list_del(&out->list);
	talloc_free(out);

	return true;
}

static int destroy_conn(void *_conn)
{
	struct connection *conn = _conn;

	/* Flush outgoing if possible, but don't block. */
	if (!conn->domain) {
		struct pollfd pfd;
		pfd.fd = conn->fd;
		pfd.events = POLLOUT;

		while (!list_empty(&conn->out_list)
		       && poll(&pfd, 1, 0) == 1)
			if (!write_messages(conn))
				break;
		close(conn->fd);
	}
        if (conn->target)
                talloc_unlink(conn, conn->target);
	list_del(&conn->list);
	trace_destroy(conn, "connection");
	return 0;
}

/* This function returns index inside the array if succeed, -1 if fail */
static int set_fd(int fd, short events)
{
	int ret;
	if (current_array_size < nr_fds + 1) {
		struct pollfd *new_fds = NULL;
		unsigned long newsize;

		/* Round up to 2^8 boundary, in practice this just
		 * make newsize larger than current_array_size.
		 */
		newsize = ROUNDUP(nr_fds + 1, 8);

		new_fds = realloc(fds, sizeof(struct pollfd)*newsize);
		if (!new_fds)
			goto fail;
		fds = new_fds;

		memset(&fds[0] + current_array_size, 0,
		       sizeof(struct pollfd ) * (newsize-current_array_size));
		current_array_size = newsize;
	}

	fds[nr_fds].fd = fd;
	fds[nr_fds].events = events;
	ret = nr_fds;
	nr_fds++;

	return ret;
fail:
	syslog(LOG_ERR, "realloc failed, ignoring fd %d\n", fd);
	return -1;
}

static void initialize_fds(int sock, int *p_sock_pollfd_idx,
			   int ro_sock, int *p_ro_sock_pollfd_idx,
			   int *ptimeout)
{
	struct connection *conn;

	if (fds)
		memset(fds, 0, sizeof(struct pollfd) * current_array_size);
	nr_fds = 0;

	*ptimeout = -1;

	if (sock != -1)
		*p_sock_pollfd_idx = set_fd(sock, POLLIN|POLLPRI);
	if (ro_sock != -1)
		*p_ro_sock_pollfd_idx = set_fd(ro_sock, POLLIN|POLLPRI);
	if (reopen_log_pipe[0] != -1)
		reopen_log_pipe0_pollfd_idx =
			set_fd(reopen_log_pipe[0], POLLIN|POLLPRI);

	if (xce_handle != NULL)
		xce_pollfd_idx = set_fd(xc_evtchn_fd(xce_handle),
					POLLIN|POLLPRI);

	list_for_each_entry(conn, &connections, list) {
		if (conn->domain) {
			if (domain_can_read(conn) ||
			    (domain_can_write(conn) &&
			     !list_empty(&conn->out_list)))
				*ptimeout = 0;
		} else {
			short events = POLLIN|POLLPRI;
			if (!list_empty(&conn->out_list))
				events |= POLLOUT;
			conn->pollfd_idx = set_fd(conn->fd, events);
		}
	}
}

/* Is child a subnode of parent, or equal? */
bool is_child(const char *child, const char *parent)
{
	unsigned int len = strlen(parent);

	/* / should really be "" for this algorithm to work, but that's a
	 * usability nightmare. */
	if (streq(parent, "/"))
		return true;

	if (strncmp(child, parent, len) != 0)
		return false;

	return child[len] == '/' || child[len] == '\0';
}

/* If it fails, returns NULL and sets errno. */
static struct node *read_node(struct connection *conn, const char *name)
{
	TDB_DATA key, data;
	uint32_t *p;
	struct node *node;
	TDB_CONTEXT * context = tdb_context(conn);

	key.dptr = (void *)name;
	key.dsize = strlen(name);
	data = tdb_fetch(context, key);

	if (data.dptr == NULL) {
		if (tdb_error(context) == TDB_ERR_NOEXIST)
			errno = ENOENT;
		else {
			log("TDB error on read: %s", tdb_errorstr(context));
			errno = EIO;
		}
		return NULL;
	}

	node = talloc(name, struct node);
	node->name = talloc_strdup(node, name);
	node->parent = NULL;
	node->tdb = tdb_context(conn);
	talloc_steal(node, data.dptr);

	/* Datalen, childlen, number of permissions */
	p = (uint32_t *)data.dptr;
	node->num_perms = p[0];
	node->datalen = p[1];
	node->childlen = p[2];

	/* Permissions are struct xs_permissions. */
	node->perms = (void *)&p[3];
	/* Data is binary blob (usually ascii, no nul). */
	node->data = node->perms + node->num_perms;
	/* Children is strings, nul separated. */
	node->children = node->data + node->datalen;

	return node;
}

static bool write_node(struct connection *conn, const struct node *node)
{
	/*
	 * conn will be null when this is called from manual_node.
	 * tdb_context copes with this.
	 */

	TDB_DATA key, data;
	void *p;

	key.dptr = (void *)node->name;
	key.dsize = strlen(node->name);

	data.dsize = 3*sizeof(uint32_t)
		+ node->num_perms*sizeof(node->perms[0])
		+ node->datalen + node->childlen;

	if (domain_is_unprivileged(conn) && data.dsize >= quota_max_entry_size)
		goto error;

	data.dptr = talloc_size(node, data.dsize);
	((uint32_t *)data.dptr)[0] = node->num_perms;
	((uint32_t *)data.dptr)[1] = node->datalen;
	((uint32_t *)data.dptr)[2] = node->childlen;
	p = data.dptr + 3 * sizeof(uint32_t);

	memcpy(p, node->perms, node->num_perms*sizeof(node->perms[0]));
	p += node->num_perms*sizeof(node->perms[0]);
	memcpy(p, node->data, node->datalen);
	p += node->datalen;
	memcpy(p, node->children, node->childlen);

	/* TDB should set errno, but doesn't even set ecode AFAICT. */
	if (tdb_store(tdb_context(conn), key, data, TDB_REPLACE) != 0) {
		corrupt(conn, "Write of %s failed", key.dptr);
		goto error;
	}
	return true;
 error:
	errno = ENOSPC;
	return false;
}

static enum xs_perm_type perm_for_conn(struct connection *conn,
				       struct xs_permissions *perms,
				       unsigned int num)
{
	unsigned int i;
	enum xs_perm_type mask = XS_PERM_READ|XS_PERM_WRITE|XS_PERM_OWNER;

	if (!conn->can_write)
		mask &= ~XS_PERM_WRITE;

	/* Owners and tools get it all... */
	if (!domain_is_unprivileged(conn) || perms[0].id == conn->id
                || (conn->target && perms[0].id == conn->target->id))
		return (XS_PERM_READ|XS_PERM_WRITE|XS_PERM_OWNER) & mask;

	for (i = 1; i < num; i++)
		if (perms[i].id == conn->id
                        || (conn->target && perms[i].id == conn->target->id))
			return perms[i].perms & mask;

	return perms[0].perms & mask;
}

static char *get_parent(const char *node)
{
	char *slash = strrchr(node + 1, '/');
	if (!slash)
		return talloc_strdup(node, "/");
	return talloc_asprintf(node, "%.*s", (int)(slash - node), node);
}

/* What do parents say? */
static enum xs_perm_type ask_parents(struct connection *conn, const char *name)
{
	struct node *node;

	do {
		name = get_parent(name);
		node = read_node(conn, name);
		if (node)
			break;
	} while (!streq(name, "/"));

	/* No permission at root?  We're in trouble. */
	if (!node) {
		corrupt(conn, "No permissions file at root");
		return XS_PERM_NONE;
	}

	return perm_for_conn(conn, node->perms, node->num_perms);
}

/* We have a weird permissions system.  You can allow someone into a
 * specific node without allowing it in the parents.  If it's going to
 * fail, however, we don't want the errno to indicate any information
 * about the node. */
static int errno_from_parents(struct connection *conn, const char *node,
			      int errnum, enum xs_perm_type perm)
{
	/* We always tell them about memory failures. */
	if (errnum == ENOMEM)
		return errnum;

	if (ask_parents(conn, node) & perm)
		return errnum;
	return EACCES;
}

/* If it fails, returns NULL and sets errno. */
struct node *get_node(struct connection *conn,
		      const char *name,
		      enum xs_perm_type perm)
{
	struct node *node;

	if (!name || !is_valid_nodename(name)) {
		errno = EINVAL;
		return NULL;
	}
	node = read_node(conn, name);
	/* If we don't have permission, we don't have node. */
	if (node) {
		if ((perm_for_conn(conn, node->perms, node->num_perms) & perm)
		    != perm) {
			errno = EACCES;
			node = NULL;
		}
	}
	/* Clean up errno if they weren't supposed to know. */
	if (!node) 
		errno = errno_from_parents(conn, name, errno, perm);
	return node;
}

static struct buffered_data *new_buffer(void *ctx)
{
	struct buffered_data *data;

	data = talloc_zero(ctx, struct buffered_data);
	if (data == NULL)
		return NULL;
	
	data->inhdr = true;
	return data;
}

/* Return length of string (including nul) at this offset.
 * If there is no nul, returns 0 for failure.
 */
static unsigned int get_string(const struct buffered_data *data,
			       unsigned int offset)
{
	const char *nul;

	if (offset >= data->used)
		return 0;

	nul = memchr(data->buffer + offset, 0, data->used - offset);
	if (!nul)
		return 0;

	return nul - (data->buffer + offset) + 1;
}

/* Break input into vectors, return the number, fill in up to num of them.
 * Always returns the actual number of nuls in the input.  Stores the
 * positions of the starts of the nul-terminated strings in vec.
 * Callers who use this and then rely only on vec[] will
 * ignore any data after the final nul.
 */
unsigned int get_strings(struct buffered_data *data,
			 char *vec[], unsigned int num)
{
	unsigned int off, i, len;

	off = i = 0;
	while ((len = get_string(data, off)) != 0) {
		if (i < num)
			vec[i] = data->buffer + off;
		i++;
		off += len;
	}
	return i;
}

void send_reply(struct connection *conn, enum xsd_sockmsg_type type,
		const void *data, unsigned int len)
{
	struct buffered_data *bdata;

	/* Message is a child of the connection context for auto-cleanup. */
	bdata = new_buffer(conn);
	bdata->buffer = talloc_array(bdata, char, len);

	/* Echo request header in reply unless this is an async watch event. */
	if (type != XS_WATCH_EVENT) {
		memcpy(&bdata->hdr.msg, &conn->in->hdr.msg,
		       sizeof(struct xsd_sockmsg));
	} else {
		memset(&bdata->hdr.msg, 0, sizeof(struct xsd_sockmsg));
	}

	/* Update relevant header fields and fill in the message body. */
	bdata->hdr.msg.type = type;
	bdata->hdr.msg.len = len;
	memcpy(bdata->buffer, data, len);

	/* Queue for later transmission. */
	list_add_tail(&bdata->list, &conn->out_list);
}

/* Some routines (write, mkdir, etc) just need a non-error return */
void send_ack(struct connection *conn, enum xsd_sockmsg_type type)
{
	send_reply(conn, type, "OK", sizeof("OK"));
}

void send_error(struct connection *conn, int error)
{
	unsigned int i;

	for (i = 0; error != xsd_errors[i].errnum; i++) {
		if (i == ARRAY_SIZE(xsd_errors) - 1) {
			eprintf("xenstored: error %i untranslatable", error);
			i = 0; 	/* EINVAL */
			break;
		}
	}
	send_reply(conn, XS_ERROR, xsd_errors[i].errstring,
			  strlen(xsd_errors[i].errstring) + 1);
}

static bool valid_chars(const char *node)
{
	/* Nodes can have lots of crap. */
	return (strspn(node, 
		       "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
		       "abcdefghijklmnopqrstuvwxyz"
		       "0123456789-/_@") == strlen(node));
}

bool is_valid_nodename(const char *node)
{
	/* Must start in /. */
	if (!strstarts(node, "/"))
		return false;

	/* Cannot end in / (unless it's just "/"). */
	if (strends(node, "/") && !streq(node, "/"))
		return false;

	/* No double //. */
	if (strstr(node, "//"))
		return false;

	if (strlen(node) > XENSTORE_ABS_PATH_MAX)
		return false;

	return valid_chars(node);
}

/* We expect one arg in the input: return NULL otherwise.
 * The payload must contain exactly one nul, at the end.
 */
static const char *onearg(struct buffered_data *in)
{
	if (!in->used || get_string(in, 0) != in->used)
		return NULL;
	return in->buffer;
}

static char *perms_to_strings(const void *ctx,
			      struct xs_permissions *perms, unsigned int num,
			      unsigned int *len)
{
	unsigned int i;
	char *strings = NULL;
	char buffer[MAX_STRLEN(unsigned int) + 1];

	for (*len = 0, i = 0; i < num; i++) {
		if (!xs_perm_to_string(&perms[i], buffer, sizeof(buffer)))
			return NULL;

		strings = talloc_realloc(ctx, strings, char,
					 *len + strlen(buffer) + 1);
		strcpy(strings + *len, buffer);
		*len += strlen(buffer) + 1;
	}
	return strings;
}

char *canonicalize(struct connection *conn, const char *node)
{
	const char *prefix;

	if (!node || (node[0] == '/') || (node[0] == '@'))
		return (char *)node;
	prefix = get_implicit_path(conn);
	if (prefix)
		return talloc_asprintf(node, "%s/%s", prefix, node);
	return (char *)node;
}

bool check_event_node(const char *node)
{
	if (!node || !strstarts(node, "@")) {
		errno = EINVAL;
		return false;
	}
	return true;
}

static void send_directory(struct connection *conn, const char *name)
{
	struct node *node;

	name = canonicalize(conn, name);
	node = get_node(conn, name, XS_PERM_READ);
	if (!node) {
		send_error(conn, errno);
		return;
	}

	send_reply(conn, XS_DIRECTORY, node->children, node->childlen);
}

static void do_read(struct connection *conn, const char *name)
{
	struct node *node;

	name = canonicalize(conn, name);
	node = get_node(conn, name, XS_PERM_READ);
	if (!node) {
		send_error(conn, errno);
		return;
	}

	send_reply(conn, XS_READ, node->data, node->datalen);
}

static void delete_node_single(struct connection *conn, struct node *node)
{
	TDB_DATA key;

	key.dptr = (void *)node->name;
	key.dsize = strlen(node->name);

	if (tdb_delete(tdb_context(conn), key) != 0) {
		corrupt(conn, "Could not delete '%s'", node->name);
		return;
	}
	domain_entry_dec(conn, node);
}

/* Must not be / */
static char *basename(const char *name)
{
	return strrchr(name, '/') + 1;
}

static struct node *construct_node(struct connection *conn, const char *name)
{
	const char *base;
	unsigned int baselen;
	struct node *parent, *node;
	char *children, *parentname = get_parent(name);

	/* If parent doesn't exist, create it. */
	parent = read_node(conn, parentname);
	if (!parent)
		parent = construct_node(conn, parentname);
	if (!parent)
		return NULL;

	if (domain_entry(conn) >= quota_nb_entry_per_domain)
		return NULL;

	/* Add child to parent. */
	base = basename(name);
	baselen = strlen(base) + 1;
	children = talloc_array(name, char, parent->childlen + baselen);
	memcpy(children, parent->children, parent->childlen);
	memcpy(children + parent->childlen, base, baselen);
	parent->children = children;
	parent->childlen += baselen;

	/* Allocate node */
	node = talloc(name, struct node);
	node->tdb = tdb_context(conn);
	node->name = talloc_strdup(node, name);

	/* Inherit permissions, except unprivileged domains own what they create */
	node->num_perms = parent->num_perms;
	node->perms = talloc_memdup(node, parent->perms,
				    node->num_perms * sizeof(node->perms[0]));
	if (domain_is_unprivileged(conn))
		node->perms[0].id = conn->id;

	/* No children, no data */
	node->children = node->data = NULL;
	node->childlen = node->datalen = 0;
	node->parent = parent;
	domain_entry_inc(conn, node);
	return node;
}

static int destroy_node(void *_node)
{
	struct node *node = _node;
	TDB_DATA key;

	if (streq(node->name, "/"))
		corrupt(NULL, "Destroying root node!");

	key.dptr = (void *)node->name;
	key.dsize = strlen(node->name);

	tdb_delete(node->tdb, key);
	return 0;
}

static struct node *create_node(struct connection *conn, 
				const char *name,
				void *data, unsigned int datalen)
{
	struct node *node, *i;

	node = construct_node(conn, name);
	if (!node)
		return NULL;

	node->data = data;
	node->datalen = datalen;

	/* We write out the nodes down, setting destructor in case
	 * something goes wrong. */
	for (i = node; i; i = i->parent) {
		if (!write_node(conn, i)) {
			domain_entry_dec(conn, i);
			return NULL;
		}
		talloc_set_destructor(i, destroy_node);
	}

	/* OK, now remove destructors so they stay around */
	for (i = node; i; i = i->parent)
		talloc_set_destructor(i, NULL);
	return node;
}

/* path, data... */
static void do_write(struct connection *conn, struct buffered_data *in)
{
	unsigned int offset, datalen;
	struct node *node;
	char *vec[1] = { NULL }; /* gcc4 + -W + -Werror fucks code. */
	char *name;

	/* Extra "strings" can be created by binary data. */
	if (get_strings(in, vec, ARRAY_SIZE(vec)) < ARRAY_SIZE(vec)) {
		send_error(conn, EINVAL);
		return;
	}

	offset = strlen(vec[0]) + 1;
	datalen = in->used - offset;

	name = canonicalize(conn, vec[0]);
	node = get_node(conn, name, XS_PERM_WRITE);
	if (!node) {
		/* No permissions, invalid input? */
		if (errno != ENOENT) {
			send_error(conn, errno);
			return;
		}
		node = create_node(conn, name, in->buffer + offset, datalen);
		if (!node) {
			send_error(conn, errno);
			return;
		}
	} else {
		node->data = in->buffer + offset;
		node->datalen = datalen;
		if (!write_node(conn, node)){
			send_error(conn, errno);
			return;
		}
	}

	add_change_node(conn->transaction, name, false);
	fire_watches(conn, name, false);
	send_ack(conn, XS_WRITE);
}

static void do_mkdir(struct connection *conn, const char *name)
{
	struct node *node;

	name = canonicalize(conn, name);
	node = get_node(conn, name, XS_PERM_WRITE);

	/* If it already exists, fine. */
	if (!node) {
		/* No permissions? */
		if (errno != ENOENT) {
			send_error(conn, errno);
			return;
		}
		node = create_node(conn, name, NULL, 0);
		if (!node) {
			send_error(conn, errno);
			return;
		}
		add_change_node(conn->transaction, name, false);
		fire_watches(conn, name, false);
	}
	send_ack(conn, XS_MKDIR);
}

static void delete_node(struct connection *conn, struct node *node)
{
	unsigned int i;

	/* Delete self, then delete children.  If we crash, then the worst
	   that can happen is the children will continue to take up space, but
	   will otherwise be unreachable. */
	delete_node_single(conn, node);

	/* Delete children, too. */
	for (i = 0; i < node->childlen; i += strlen(node->children+i) + 1) {
		struct node *child;

		child = read_node(conn, 
				  talloc_asprintf(node, "%s/%s", node->name,
						  node->children + i));
		if (child) {
			delete_node(conn, child);
		}
		else {
			trace("delete_node: No child '%s/%s' found!\n",
			      node->name, node->children + i);
			/* Skip it, we've already deleted the parent. */
		}
	}
}


/* Delete memory using memmove. */
static void memdel(void *mem, unsigned off, unsigned len, unsigned total)
{
	memmove(mem + off, mem + off + len, total - off - len);
}


static bool remove_child_entry(struct connection *conn, struct node *node,
			       size_t offset)
{
	size_t childlen = strlen(node->children + offset);
	memdel(node->children, offset, childlen + 1, node->childlen);
	node->childlen -= childlen + 1;
	return write_node(conn, node);
}


static bool delete_child(struct connection *conn,
			 struct node *node, const char *childname)
{
	unsigned int i;

	for (i = 0; i < node->childlen; i += strlen(node->children+i) + 1) {
		if (streq(node->children+i, childname)) {
			return remove_child_entry(conn, node, i);
		}
	}
	corrupt(conn, "Can't find child '%s' in %s", childname, node->name);
	return false;
}


static int _rm(struct connection *conn, struct node *node, const char *name)
{
	/* Delete from parent first, then if we crash, the worst that can
	   happen is the child will continue to take up space, but will
	   otherwise be unreachable. */
	struct node *parent = read_node(conn, get_parent(name));
	if (!parent) {
		send_error(conn, EINVAL);
		return 0;
	}

	if (!delete_child(conn, parent, basename(name))) {
		send_error(conn, EINVAL);
		return 0;
	}

	delete_node(conn, node);
	return 1;
}


static void internal_rm(const char *name)
{
	char *tname = talloc_strdup(NULL, name);
	struct node *node = read_node(NULL, tname);
	if (node)
		_rm(NULL, node, tname);
	talloc_free(node);
	talloc_free(tname);
}


static void do_rm(struct connection *conn, const char *name)
{
	struct node *node;

	name = canonicalize(conn, name);
	node = get_node(conn, name, XS_PERM_WRITE);
	if (!node) {
		/* Didn't exist already?  Fine, if parent exists. */
		if (errno == ENOENT) {
			node = read_node(conn, get_parent(name));
			if (node) {
				send_ack(conn, XS_RM);
				return;
			}
			/* Restore errno, just in case. */
			errno = ENOENT;
		}
		send_error(conn, errno);
		return;
	}

	if (streq(name, "/")) {
		send_error(conn, EINVAL);
		return;
	}

	if (_rm(conn, node, name)) {
		add_change_node(conn->transaction, name, true);
		fire_watches(conn, name, true);
		send_ack(conn, XS_RM);
	}
}


static void do_get_perms(struct connection *conn, const char *name)
{
	struct node *node;
	char *strings;
	unsigned int len;

	name = canonicalize(conn, name);
	node = get_node(conn, name, XS_PERM_READ);
	if (!node) {
		send_error(conn, errno);
		return;
	}

	strings = perms_to_strings(node, node->perms, node->num_perms, &len);
	if (!strings)
		send_error(conn, errno);
	else
		send_reply(conn, XS_GET_PERMS, strings, len);
}

static void do_set_perms(struct connection *conn, struct buffered_data *in)
{
	unsigned int num;
	struct xs_permissions *perms;
	char *name, *permstr;
	struct node *node;

	num = xs_count_strings(in->buffer, in->used);
	if (num < 2) {
		send_error(conn, EINVAL);
		return;
	}

	/* First arg is node name. */
	name = canonicalize(conn, in->buffer);
	permstr = in->buffer + strlen(in->buffer) + 1;
	num--;

	/* We must own node to do this (tools can do this too). */
	node = get_node(conn, name, XS_PERM_WRITE|XS_PERM_OWNER);
	if (!node) {
		send_error(conn, errno);
		return;
	}

	perms = talloc_array(node, struct xs_permissions, num);
	if (!xs_strings_to_perms(perms, num, permstr)) {
		send_error(conn, errno);
		return;
	}

	/* Unprivileged domains may not change the owner. */
	if (domain_is_unprivileged(conn) &&
	    perms[0].id != node->perms[0].id) {
		send_error(conn, EPERM);
		return;
	}

	domain_entry_dec(conn, node);
	node->perms = perms;
	node->num_perms = num;
	domain_entry_inc(conn, node);

	if (!write_node(conn, node)) {
		send_error(conn, errno);
		return;
	}

	add_change_node(conn->transaction, name, false);
	fire_watches(conn, name, false);
	send_ack(conn, XS_SET_PERMS);
}

static void do_debug(struct connection *conn, struct buffered_data *in)
{
	int num;

	if (conn->id != 0) {
		send_error(conn, EACCES);
		return;
	}

	num = xs_count_strings(in->buffer, in->used);

	if (streq(in->buffer, "print")) {
		if (num < 2) {
			send_error(conn, EINVAL);
			return;
		}
		xprintf("debug: %s", in->buffer + get_string(in, 0));
	}

	if (streq(in->buffer, "check"))
		check_store();

	send_ack(conn, XS_DEBUG);
}

/* Process "in" for conn: "in" will vanish after this conversation, so
 * we can talloc off it for temporary variables.  May free "conn".
 */
static void process_message(struct connection *conn, struct buffered_data *in)
{
	struct transaction *trans;

	trans = transaction_lookup(conn, in->hdr.msg.tx_id);
	if (IS_ERR(trans)) {
		send_error(conn, -PTR_ERR(trans));
		return;
	}

	assert(conn->transaction == NULL);
	conn->transaction = trans;

	switch (in->hdr.msg.type) {
	case XS_DIRECTORY:
		send_directory(conn, onearg(in));
		break;

	case XS_READ:
		do_read(conn, onearg(in));
		break;

	case XS_WRITE:
		do_write(conn, in);
		break;

	case XS_MKDIR:
		do_mkdir(conn, onearg(in));
		break;

	case XS_RM:
		do_rm(conn, onearg(in));
		break;

	case XS_GET_PERMS:
		do_get_perms(conn, onearg(in));
		break;

	case XS_SET_PERMS:
		do_set_perms(conn, in);
		break;

	case XS_DEBUG:
		do_debug(conn, in);
		break;

	case XS_WATCH:
		do_watch(conn, in);
		break;

	case XS_UNWATCH:
		do_unwatch(conn, in);
		break;

	case XS_TRANSACTION_START:
		do_transaction_start(conn, in);
		break;

	case XS_TRANSACTION_END:
		do_transaction_end(conn, onearg(in));
		break;

	case XS_INTRODUCE:
		do_introduce(conn, in);
		break;

	case XS_IS_DOMAIN_INTRODUCED:
		do_is_domain_introduced(conn, onearg(in));
		break;

	case XS_RELEASE:
		do_release(conn, onearg(in));
		break;

	case XS_GET_DOMAIN_PATH:
		do_get_domain_path(conn, onearg(in));
		break;

	case XS_RESUME:
		do_resume(conn, onearg(in));
		break;

	case XS_SET_TARGET:
		do_set_target(conn, in);
		break;

	case XS_RESET_WATCHES:
		do_reset_watches(conn);
		break;

	default:
		eprintf("Client unknown operation %i", in->hdr.msg.type);
		send_error(conn, ENOSYS);
		break;
	}

	conn->transaction = NULL;
}

static void consider_message(struct connection *conn)
{
	if (verbose)
		xprintf("Got message %s len %i from %p\n",
			sockmsg_string(conn->in->hdr.msg.type),
			conn->in->hdr.msg.len, conn);

	process_message(conn, conn->in);

	talloc_free(conn->in);
	conn->in = new_buffer(conn);
}

/* Errors in reading or allocating here mean we get out of sync, so we
 * drop the whole client connection. */
static void handle_input(struct connection *conn)
{
	int bytes;
	struct buffered_data *in = conn->in;

	/* Not finished header yet? */
	if (in->inhdr) {
		bytes = conn->read(conn, in->hdr.raw + in->used,
				   sizeof(in->hdr) - in->used);
		if (bytes < 0)
			goto bad_client;
		in->used += bytes;
		if (in->used != sizeof(in->hdr))
			return;

		if (in->hdr.msg.len > XENSTORE_PAYLOAD_MAX) {
			syslog(LOG_ERR, "Client tried to feed us %i",
			       in->hdr.msg.len);
			goto bad_client;
		}

		in->buffer = talloc_array(in, char, in->hdr.msg.len);
		if (!in->buffer)
			goto bad_client;
		in->used = 0;
		in->inhdr = false;
	}

	bytes = conn->read(conn, in->buffer + in->used,
			   in->hdr.msg.len - in->used);
	if (bytes < 0)
		goto bad_client;

	in->used += bytes;
	if (in->used != in->hdr.msg.len)
		return;

	trace_io(conn, in, 0);
	consider_message(conn);
	return;

bad_client:
	/* Kill it. */
	talloc_free(conn);
}

static void handle_output(struct connection *conn)
{
	if (!write_messages(conn))
		talloc_free(conn);
}

struct connection *new_connection(connwritefn_t *write, connreadfn_t *read)
{
	struct connection *new;

	new = talloc_zero(talloc_autofree_context(), struct connection);
	if (!new)
		return NULL;

	new->fd = -1;
	new->pollfd_idx = -1;
	new->write = write;
	new->read = read;
	new->can_write = true;
	new->transaction_started = 0;
	INIT_LIST_HEAD(&new->out_list);
	INIT_LIST_HEAD(&new->watches);
	INIT_LIST_HEAD(&new->transaction_list);

	new->in = new_buffer(new);
	if (new->in == NULL) {
		talloc_free(new);
		return NULL;
	}

	list_add_tail(&new->list, &connections);
	talloc_set_destructor(new, destroy_conn);
	trace_create(new, "connection");
	return new;
}

#ifdef NO_SOCKETS
static void accept_connection(int sock, bool canwrite)
{
}
#else
static int writefd(struct connection *conn, const void *data, unsigned int len)
{
	int rc;

	while ((rc = write(conn->fd, data, len)) < 0) {
		if (errno == EAGAIN) {
			rc = 0;
			break;
		}
		if (errno != EINTR)
			break;
	}

	return rc;
}

static int readfd(struct connection *conn, void *data, unsigned int len)
{
	int rc;

	while ((rc = read(conn->fd, data, len)) < 0) {
		if (errno == EAGAIN) {
			rc = 0;
			break;
		}
		if (errno != EINTR)
			break;
	}

	/* Reading zero length means we're done with this connection. */
	if ((rc == 0) && (len != 0)) {
		errno = EBADF;
		rc = -1;
	}

	return rc;
}

static void accept_connection(int sock, bool canwrite)
{
	int fd;
	struct connection *conn;

	fd = accept(sock, NULL, NULL);
	if (fd < 0)
		return;

	conn = new_connection(writefd, readfd);
	if (conn) {
		conn->fd = fd;
		conn->can_write = canwrite;
	} else
		close(fd);
}
#endif

static int tdb_flags;

/* We create initial nodes manually. */
static void manual_node(const char *name, const char *child)
{
	struct node *node;
	struct xs_permissions perms = { .id = 0, .perms = XS_PERM_NONE };

	node = talloc_zero(NULL, struct node);
	node->name = name;
	node->perms = &perms;
	node->num_perms = 1;
	node->children = (char *)child;
	if (child)
		node->childlen = strlen(child) + 1;

	if (!write_node(NULL, node))
		barf_perror("Could not create initial node %s", name);
	talloc_free(node);
}

static void setup_structure(void)
{
	char *tdbname;
	tdbname = talloc_strdup(talloc_autofree_context(), xs_daemon_tdb());

	if (!(tdb_flags & TDB_INTERNAL))
		tdb_ctx = tdb_open(tdbname, 0, tdb_flags, O_RDWR, 0);

	if (tdb_ctx) {
		/* XXX When we make xenstored able to restart, this will have
		   to become cleverer, checking for existing domains and not
		   removing the corresponding entries, but for now xenstored
		   cannot be restarted without losing all the registered
		   watches, which breaks all the backend drivers anyway.  We
		   can therefore get away with just clearing /local and
		   expecting Xend to put the appropriate entries back in.

		   When this change is made it is important to note that
		   dom0's entries must be cleaned up on reboot _before_ this
		   daemon starts, otherwise the backend drivers and dom0's
		   balloon driver will pick up stale entries.  In the case of
		   the balloon driver, this can be fatal.
		*/
		char *tlocal = talloc_strdup(NULL, "/local");

		check_store();

		if (remove_local) {
			internal_rm("/local");
			create_node(NULL, tlocal, NULL, 0);

			check_store();
		}

		talloc_free(tlocal);
	}
	else {
		tdb_ctx = tdb_open(tdbname, 7919, tdb_flags, O_RDWR|O_CREAT,
				   0640);
		if (!tdb_ctx)
			barf_perror("Could not create tdb file %s", tdbname);

		manual_node("/", "tool");
		manual_node("/tool", "xenstored");
		manual_node("/tool/xenstored", NULL);

		check_store();
	}
}


static unsigned int hash_from_key_fn(void *k)
{
	char *str = k;
	unsigned int hash = 5381;
	char c;

	while ((c = *str++))
		hash = ((hash << 5) + hash) + (unsigned int)c;

	return hash;
}


static int keys_equal_fn(void *key1, void *key2)
{
	return 0 == strcmp((char *)key1, (char *)key2);
}


static char *child_name(const char *s1, const char *s2)
{
	if (strcmp(s1, "/")) {
		return talloc_asprintf(NULL, "%s/%s", s1, s2);
	}
	else {
		return talloc_asprintf(NULL, "/%s", s2);
	}
}


static void remember_string(struct hashtable *hash, const char *str)
{
	char *k = malloc(strlen(str) + 1);
	strcpy(k, str);
	hashtable_insert(hash, k, (void *)1);
}


/**
 * A node has a children field that names the children of the node, separated
 * by NULs.  We check whether there are entries in there that are duplicated
 * (and if so, delete the second one), and whether there are any that do not
 * have a corresponding child node (and if so, delete them).  Each valid child
 * is then recursively checked.
 *
 * No deleting is performed if the recovery flag is cleared (i.e. -R was
 * passed on the command line).
 *
 * As we go, we record each node in the given reachable hashtable.  These
 * entries will be used later in clean_store.
 */
static void check_store_(const char *name, struct hashtable *reachable)
{
	struct node *node = read_node(NULL, name);

	if (node) {
		size_t i = 0;

		struct hashtable * children =
			create_hashtable(16, hash_from_key_fn, keys_equal_fn);

		remember_string(reachable, name);

		while (i < node->childlen) {
			size_t childlen = strlen(node->children + i);
			char * childname = child_name(node->name,
						      node->children + i);
			struct node *childnode = read_node(NULL, childname);
			
			if (childnode) {
				if (hashtable_search(children, childname)) {
					log("check_store: '%s' is duplicated!",
					    childname);

					if (recovery) {
						remove_child_entry(NULL, node,
								   i);
						i -= childlen + 1;
					}
				}
				else {
					remember_string(children, childname);
					check_store_(childname, reachable);
				}
			}
			else {
				log("check_store: No child '%s' found!\n",
				    childname);

				if (recovery) {
					remove_child_entry(NULL, node, i);
					i -= childlen + 1;
				}
			}

			talloc_free(childnode);
			talloc_free(childname);
			i += childlen + 1;
		}

		hashtable_destroy(children, 0 /* Don't free values (they are
						 all (void *)1) */);
		talloc_free(node);
	}
	else {
		/* Impossible, because no database should ever be without the
		   root, and otherwise, we've just checked in our caller
		   (which made a recursive call to get here). */
		   
		log("check_store: No child '%s' found: impossible!", name);
	}
}


/**
 * Helper to clean_store below.
 */
static int clean_store_(TDB_CONTEXT *tdb, TDB_DATA key, TDB_DATA val,
			void *private)
{
	struct hashtable *reachable = private;
	char * name = talloc_strndup(NULL, key.dptr, key.dsize);

	if (!hashtable_search(reachable, name)) {
		log("clean_store: '%s' is orphaned!", name);
		if (recovery) {
			tdb_delete(tdb, key);
		}
	}

	talloc_free(name);

	return 0;
}


/**
 * Given the list of reachable nodes, iterate over the whole store, and
 * remove any that were not reached.
 */
static void clean_store(struct hashtable *reachable)
{
	tdb_traverse(tdb_ctx, &clean_store_, reachable);
}


static void check_store(void)
{
	char * root = talloc_strdup(NULL, "/");
	struct hashtable * reachable =
		create_hashtable(16, hash_from_key_fn, keys_equal_fn);
 
	log("Checking store ...");
	check_store_(root, reachable);
	clean_store(reachable);
	log("Checking store complete.");

	hashtable_destroy(reachable, 0 /* Don't free values (they are all
					  (void *)1) */);
	talloc_free(root);
}


/* Something is horribly wrong: check the store. */
static void corrupt(struct connection *conn, const char *fmt, ...)
{
	va_list arglist;
	char *str;
	int saved_errno = errno;

	va_start(arglist, fmt);
	str = talloc_vasprintf(NULL, fmt, arglist);
	va_end(arglist);

	log("corruption detected by connection %i: err %s: %s",
	    conn ? (int)conn->id : -1, strerror(saved_errno), str);

	check_store();
}


#ifdef NO_SOCKETS
static void init_sockets(int **psock, int **pro_sock)
{
	static int minus_one = -1;
	*psock = *pro_sock = &minus_one;
}
#else
static int destroy_fd(void *_fd)
{
	int *fd = _fd;
	close(*fd);
	return 0;
}

static void init_sockets(int **psock, int **pro_sock)
{
	struct sockaddr_un addr;
	int *sock, *ro_sock;
	/* Create sockets for them to listen to. */
	*psock = sock = talloc(talloc_autofree_context(), int);
	*sock = socket(PF_UNIX, SOCK_STREAM, 0);
	if (*sock < 0)
		barf_perror("Could not create socket");
	*pro_sock = ro_sock = talloc(talloc_autofree_context(), int);
	*ro_sock = socket(PF_UNIX, SOCK_STREAM, 0);
	if (*ro_sock < 0)
		barf_perror("Could not create socket");
	talloc_set_destructor(sock, destroy_fd);
	talloc_set_destructor(ro_sock, destroy_fd);

	/* FIXME: Be more sophisticated, don't mug running daemon. */
	unlink(xs_daemon_socket());
	unlink(xs_daemon_socket_ro());

	addr.sun_family = AF_UNIX;
	strcpy(addr.sun_path, xs_daemon_socket());
	if (bind(*sock, (struct sockaddr *)&addr, sizeof(addr)) != 0)
		barf_perror("Could not bind socket to %s", xs_daemon_socket());
	strcpy(addr.sun_path, xs_daemon_socket_ro());
	if (bind(*ro_sock, (struct sockaddr *)&addr, sizeof(addr)) != 0)
		barf_perror("Could not bind socket to %s",
			    xs_daemon_socket_ro());
	if (chmod(xs_daemon_socket(), 0600) != 0
	    || chmod(xs_daemon_socket_ro(), 0660) != 0)
		barf_perror("Could not chmod sockets");

	if (listen(*sock, 1) != 0
	    || listen(*ro_sock, 1) != 0)
		barf_perror("Could not listen on sockets");


}
#endif

static void usage(void)
{
	fprintf(stderr,
"Usage:\n"
"\n"
"  xenstored <options>\n"
"\n"
"where options may include:\n"
"\n"
"  --no-domain-init    to state that xenstored should not initialise dom0,\n"
"  --pid-file <file>   giving a file for the daemon's pid to be written,\n"
"  --help              to output this message,\n"
"  --no-fork           to request that the daemon does not fork,\n"
"  --output-pid        to request that the pid of the daemon is output,\n"
"  --trace-file <file> giving the file for logging, and\n"
"  --entry-nb <nb>     limit the number of entries per domain,\n"
"  --entry-size <size> limit the size of entry per domain, and\n"
"  --watch-nb <nb>     limit the number of watches per domain,\n"
"  --transaction <nb>  limit the number of transaction allowed per domain,\n"
"  --no-recovery       to request that no recovery should be attempted when\n"
"                      the store is corrupted (debug only),\n"
"  --internal-db       store database in memory, not on disk\n"
"  --preserve-local    to request that /local is preserved on start-up,\n"
"  --verbose           to request verbose execution.\n");
}


static struct option options[] = {
	{ "no-domain-init", 0, NULL, 'D' },
	{ "entry-nb", 1, NULL, 'E' },
	{ "pid-file", 1, NULL, 'F' },
	{ "event", 1, NULL, 'e' },
	{ "help", 0, NULL, 'H' },
	{ "no-fork", 0, NULL, 'N' },
	{ "priv-domid", 1, NULL, 'p' },
	{ "output-pid", 0, NULL, 'P' },
	{ "entry-size", 1, NULL, 'S' },
	{ "trace-file", 1, NULL, 'T' },
	{ "transaction", 1, NULL, 't' },
	{ "no-recovery", 0, NULL, 'R' },
	{ "preserve-local", 0, NULL, 'L' },
	{ "internal-db", 0, NULL, 'I' },
	{ "verbose", 0, NULL, 'V' },
	{ "watch-nb", 1, NULL, 'W' },
	{ NULL, 0, NULL, 0 } };

extern void dump_conn(struct connection *conn); 
int dom0_event = 0;
int priv_domid = 0;

int main(int argc, char *argv[])
{
	int opt, *sock, *ro_sock;
	int sock_pollfd_idx = -1, ro_sock_pollfd_idx = -1;
	bool dofork = true;
	bool outputpid = false;
	bool no_domain_init = false;
	const char *pidfile = NULL;
	int timeout;

	while ((opt = getopt_long(argc, argv, "DE:F:HNPS:t:T:RLVW:", options,
				  NULL)) != -1) {
		switch (opt) {
		case 'D':
			no_domain_init = true;
			break;
		case 'E':
			quota_nb_entry_per_domain = strtol(optarg, NULL, 10);
			break;
		case 'F':
			pidfile = optarg;
			break;
		case 'H':
			usage();
			return 0;
		case 'N':
			dofork = false;
			break;
		case 'P':
			outputpid = true;
			break;
		case 'R':
			recovery = false;
			break;
		case 'L':
			remove_local = false;
			break;
		case 'S':
			quota_max_entry_size = strtol(optarg, NULL, 10);
			break;
		case 't':
			quota_max_transaction = strtol(optarg, NULL, 10);
			break;
		case 'T':
			tracefile = optarg;
			break;
		case 'I':
			tdb_flags = TDB_INTERNAL|TDB_NOLOCK;
			break;
		case 'V':
			verbose = true;
			break;
		case 'W':
			quota_nb_watch_per_domain = strtol(optarg, NULL, 10);
			break;
		case 'e':
			dom0_event = strtol(optarg, NULL, 10);
			break;
		case 'p':
			priv_domid = strtol(optarg, NULL, 10);
			break;
		}
	}
	if (optind != argc)
		barf("%s: No arguments desired", argv[0]);

	reopen_log();

	/* make sure xenstored directories exist */
	/* Errors ignored here, will be reported when we open files */
	mkdir(xs_daemon_rundir(), 0755);
	mkdir(xs_daemon_rootdir(), 0755);

	if (dofork) {
		openlog("xenstored", 0, LOG_DAEMON);
		daemonize();
	}
	if (pidfile)
		write_pidfile(pidfile);

	/* Talloc leak reports go to stderr, which is closed if we fork. */
	if (!dofork)
		talloc_enable_leak_report_full();

	/* Don't kill us with SIGPIPE. */
	signal(SIGPIPE, SIG_IGN);

	init_sockets(&sock, &ro_sock);
	init_pipe(reopen_log_pipe);

	/* Setup the database */
	setup_structure();

	/* Listen to hypervisor. */
	if (!no_domain_init)
		domain_init();

	/* Restore existing connections. */
	restore_existing_connections();

	if (outputpid) {
		printf("%ld\n", (long)getpid());
		fflush(stdout);
	}

	/* redirect to /dev/null now we're ready to accept connections */
	if (dofork)
		finish_daemonize();

	signal(SIGHUP, trigger_reopen_log);

	/* Get ready to listen to the tools. */
	initialize_fds(*sock, &sock_pollfd_idx, *ro_sock, &ro_sock_pollfd_idx,
		       &timeout);

	/* Tell the kernel we're up and running. */
	xenbus_notify_running();

	/* Main loop. */
	for (;;) {
		struct connection *conn, *next;

		if (poll(fds, nr_fds, timeout) < 0) {
			if (errno == EINTR)
				continue;
			barf_perror("Poll failed");
		}

		if (reopen_log_pipe0_pollfd_idx != -1) {
			if (fds[reopen_log_pipe0_pollfd_idx].revents
			    & ~POLLIN) {
				close(reopen_log_pipe[0]);
				close(reopen_log_pipe[1]);
				init_pipe(reopen_log_pipe);
			} else if (fds[reopen_log_pipe0_pollfd_idx].revents
				   & POLLIN) {
				char c;
				if (read(reopen_log_pipe[0], &c, 1) != 1)
					barf_perror("read failed");
				reopen_log();
			}
			reopen_log_pipe0_pollfd_idx = -1;
		}

		if (sock_pollfd_idx != -1) {
			if (fds[sock_pollfd_idx].revents & ~POLLIN) {
				barf_perror("sock poll failed");
				break;
			} else if (fds[sock_pollfd_idx].revents & POLLIN) {
				accept_connection(*sock, true);
				sock_pollfd_idx = -1;
			}
		}

		if (ro_sock_pollfd_idx != -1) {
			if (fds[ro_sock_pollfd_idx].revents & ~POLLIN) {
				barf_perror("ro sock poll failed");
				break;
			} else if (fds[ro_sock_pollfd_idx].revents & POLLIN) {
				accept_connection(*ro_sock, false);
				ro_sock_pollfd_idx = -1;
			}
		}

		if (xce_pollfd_idx != -1) {
			if (fds[xce_pollfd_idx].revents & ~POLLIN) {
				barf_perror("xce_handle poll failed");
				break;
			} else if (fds[xce_pollfd_idx].revents & POLLIN) {
				handle_event();
				xce_pollfd_idx = -1;
			}
		}

		next = list_entry(connections.next, typeof(*conn), list);
		if (&next->list != &connections)
			talloc_increase_ref_count(next);
		while (&next->list != &connections) {
			conn = next;

			next = list_entry(conn->list.next,
					  typeof(*conn), list);
			if (&next->list != &connections)
				talloc_increase_ref_count(next);

			if (conn->domain) {
				if (domain_can_read(conn))
					handle_input(conn);
				if (talloc_free(conn) == 0)
					continue;

				talloc_increase_ref_count(conn);
				if (domain_can_write(conn) &&
				    !list_empty(&conn->out_list))
					handle_output(conn);
				if (talloc_free(conn) == 0)
					continue;
			} else {
				if (conn->pollfd_idx != -1) {
					if (fds[conn->pollfd_idx].revents
					    & ~(POLLIN|POLLOUT))
						talloc_free(conn);
					else if (fds[conn->pollfd_idx].revents
						 & POLLIN)
						handle_input(conn);
				}
				if (talloc_free(conn) == 0)
					continue;

				talloc_increase_ref_count(conn);

				if (conn->pollfd_idx != -1) {
					if (fds[conn->pollfd_idx].revents
					    & ~(POLLIN|POLLOUT))
						talloc_free(conn);
					else if (fds[conn->pollfd_idx].revents
						 & POLLOUT)
						handle_output(conn);
				}
				if (talloc_free(conn) == 0)
					continue;

				conn->pollfd_idx = -1;
			}
		}

		initialize_fds(*sock, &sock_pollfd_idx, *ro_sock,
			       &ro_sock_pollfd_idx, &timeout);
	}
}

/*
 * Local variables:
 *  c-file-style: "linux"
 *  indent-tabs-mode: t
 *  c-indent-level: 8
 *  c-basic-offset: 8
 *  tab-width: 8
 * End:
 */