summaryrefslogtreecommitdiffstats
path: root/sys/netgraph/ng_base.c
blob: 037ad04bc13e76956ba94be479c893c77ed41a84 (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

/*
 * ng_base.c
 *
 * Copyright (c) 1996-1999 Whistle Communications, Inc.
 * All rights reserved.
 * 
 * Subject to the following obligations and disclaimer of warranty, use and
 * redistribution of this software, in source or object code forms, with or
 * without modifications are expressly permitted by Whistle Communications;
 * provided, however, that:
 * 1. Any and all reproductions of the source or object code must include the
 *    copyright notice above and the following disclaimer of warranties; and
 * 2. No rights are granted, in any manner or form, to use Whistle
 *    Communications, Inc. trademarks, including the mark "WHISTLE
 *    COMMUNICATIONS" on advertising, endorsements, or otherwise except as
 *    such appears in the above copyright notice or in the software.
 * 
 * THIS SOFTWARE IS BEING PROVIDED BY WHISTLE COMMUNICATIONS "AS IS", AND
 * TO THE MAXIMUM EXTENT PERMITTED BY LAW, WHISTLE COMMUNICATIONS MAKES NO
 * REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, REGARDING THIS SOFTWARE,
 * INCLUDING WITHOUT LIMITATION, ANY AND ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
 * WHISTLE COMMUNICATIONS DOES NOT WARRANT, GUARANTEE, OR MAKE ANY
 * REPRESENTATIONS REGARDING THE USE OF, OR THE RESULTS OF THE USE OF THIS
 * SOFTWARE IN TERMS OF ITS CORRECTNESS, ACCURACY, RELIABILITY OR OTHERWISE.
 * IN NO EVENT SHALL WHISTLE COMMUNICATIONS BE LIABLE FOR ANY DAMAGES
 * RESULTING FROM OR ARISING OUT OF ANY USE OF THIS SOFTWARE, INCLUDING
 * WITHOUT LIMITATION, ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
 * PUNITIVE, OR CONSEQUENTIAL DAMAGES, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES, LOSS OF USE, DATA OR PROFITS, HOWEVER CAUSED AND UNDER ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF WHISTLE COMMUNICATIONS IS ADVISED OF THE POSSIBILITY
 * OF SUCH DAMAGE.
 *
 * Authors: Julian Elischer <julian@whistle.com>
 *          Archie Cobbs <archie@whistle.com>
 *
 * $FreeBSD$
 * $Whistle: ng_base.c,v 1.39 1999/01/28 23:54:53 julian Exp $
 */

/*
 * This file implements the base netgraph code.
 */

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/errno.h>
#include <sys/kernel.h>
#include <sys/malloc.h>
#include <sys/syslog.h>
#include <sys/linker.h>
#include <sys/queue.h>
#include <sys/mbuf.h>
#include <sys/ctype.h>
#include <machine/limits.h>

#include <net/netisr.h>

#include <netgraph/ng_message.h>
#include <netgraph/netgraph.h>
#include <netgraph/ng_parse.h>

MODULE_VERSION(netgraph, 1);

/* List of all nodes */
static LIST_HEAD(, struct ng_node) nodelist;

/* List of installed types */
static LIST_HEAD(, struct ng_type) typelist;

/* Hash releted definitions */
#define ID_HASH_SIZE 32 /* most systems wont need even this many */
static LIST_HEAD(, struct ng_node) ID_hash[ID_HASH_SIZE];
/* Don't nead to initialise them because it's a LIST */

/* Internal functions */
static int	ng_add_hook(node_p node, const char *name, hook_p * hookp);
static int	ng_connect(hook_p hook1, hook_p hook2);
static void	ng_disconnect_hook(hook_p hook);
static int	ng_generic_msg(node_p here, struct ng_mesg *msg,
			const char *retaddr, struct ng_mesg ** resp,
			hook_p hook);
static ng_ID_t	ng_decodeidname(const char *name);
static int	ngb_mod_event(module_t mod, int event, void *data);
static void	ngintr(void);

/* Our own netgraph malloc type */
MALLOC_DEFINE(M_NETGRAPH, "netgraph", "netgraph structures and ctrl messages");

/* Set this to Debugger("X") to catch all errors as they occur */
#ifndef TRAP_ERROR
#define TRAP_ERROR
#endif

static	ng_ID_t nextID = 1;

#ifdef INVARIANTS
#define CHECK_DATA_MBUF(m)	do {					\
		struct mbuf *n;						\
		int total;						\
									\
		if (((m)->m_flags & M_PKTHDR) == 0)			\
			panic("%s: !PKTHDR", __FUNCTION__);		\
		for (total = 0, n = (m); n != NULL; n = n->m_next)	\
			total += n->m_len;				\
		if ((m)->m_pkthdr.len != total) {			\
			panic("%s: %d != %d",				\
			    __FUNCTION__, (m)->m_pkthdr.len, total);	\
		}							\
	} while (0)
#else
#define CHECK_DATA_MBUF(m)
#endif


/************************************************************************
	Parse type definitions for generic messages
************************************************************************/

/* Handy structure parse type defining macro */
#define DEFINE_PARSE_STRUCT_TYPE(lo, up, args)				\
static const struct ng_parse_struct_info				\
	ng_ ## lo ## _type_info = NG_GENERIC_ ## up ## _INFO args;	\
static const struct ng_parse_type ng_generic_ ## lo ## _type = {	\
	&ng_parse_struct_type,						\
	&ng_ ## lo ## _type_info					\
}

DEFINE_PARSE_STRUCT_TYPE(mkpeer, MKPEER, ());
DEFINE_PARSE_STRUCT_TYPE(connect, CONNECT, ());
DEFINE_PARSE_STRUCT_TYPE(name, NAME, ());
DEFINE_PARSE_STRUCT_TYPE(rmhook, RMHOOK, ());
DEFINE_PARSE_STRUCT_TYPE(nodeinfo, NODEINFO, ());
DEFINE_PARSE_STRUCT_TYPE(typeinfo, TYPEINFO, ());
DEFINE_PARSE_STRUCT_TYPE(linkinfo, LINKINFO, (&ng_generic_nodeinfo_type));

/* Get length of an array when the length is stored as a 32 bit
   value immediately preceeding the array -- as with struct namelist
   and struct typelist. */
static int
ng_generic_list_getLength(const struct ng_parse_type *type,
	const u_char *start, const u_char *buf)
{
	return *((const u_int32_t *)(buf - 4));
}

/* Get length of the array of struct linkinfo inside a struct hooklist */
static int
ng_generic_linkinfo_getLength(const struct ng_parse_type *type,
	const u_char *start, const u_char *buf)
{
	const struct hooklist *hl = (const struct hooklist *)start;

	return hl->nodeinfo.hooks;
}

/* Array type for a variable length array of struct namelist */
static const struct ng_parse_array_info ng_nodeinfoarray_type_info = {
	&ng_generic_nodeinfo_type,
	&ng_generic_list_getLength
};
static const struct ng_parse_type ng_generic_nodeinfoarray_type = {
	&ng_parse_array_type,
	&ng_nodeinfoarray_type_info
};

/* Array type for a variable length array of struct typelist */
static const struct ng_parse_array_info ng_typeinfoarray_type_info = {
	&ng_generic_typeinfo_type,
	&ng_generic_list_getLength
};
static const struct ng_parse_type ng_generic_typeinfoarray_type = {
	&ng_parse_array_type,
	&ng_typeinfoarray_type_info
};

/* Array type for array of struct linkinfo in struct hooklist */
static const struct ng_parse_array_info ng_generic_linkinfo_array_type_info = {
	&ng_generic_linkinfo_type,
	&ng_generic_linkinfo_getLength
};
static const struct ng_parse_type ng_generic_linkinfo_array_type = {
	&ng_parse_array_type,
	&ng_generic_linkinfo_array_type_info
};

DEFINE_PARSE_STRUCT_TYPE(typelist, TYPELIST, (&ng_generic_nodeinfoarray_type));
DEFINE_PARSE_STRUCT_TYPE(hooklist, HOOKLIST,
	(&ng_generic_nodeinfo_type, &ng_generic_linkinfo_array_type));
DEFINE_PARSE_STRUCT_TYPE(listnodes, LISTNODES,
	(&ng_generic_nodeinfoarray_type));

/* List of commands and how to convert arguments to/from ASCII */
static const struct ng_cmdlist ng_generic_cmds[] = {
	{
	  NGM_GENERIC_COOKIE,
	  NGM_SHUTDOWN,
	  "shutdown",
	  NULL,
	  NULL
	},
	{
	  NGM_GENERIC_COOKIE,
	  NGM_MKPEER,
	  "mkpeer",
	  &ng_generic_mkpeer_type,
	  NULL
	},
	{
	  NGM_GENERIC_COOKIE,
	  NGM_CONNECT,
	  "connect",
	  &ng_generic_connect_type,
	  NULL
	},
	{
	  NGM_GENERIC_COOKIE,
	  NGM_NAME,
	  "name",
	  &ng_generic_name_type,
	  NULL
	},
	{
	  NGM_GENERIC_COOKIE,
	  NGM_RMHOOK,
	  "rmhook",
	  &ng_generic_rmhook_type,
	  NULL
	},
	{
	  NGM_GENERIC_COOKIE,
	  NGM_NODEINFO,
	  "nodeinfo",
	  NULL,
	  &ng_generic_nodeinfo_type
	},
	{
	  NGM_GENERIC_COOKIE,
	  NGM_LISTHOOKS,
	  "listhooks",
	  NULL,
	  &ng_generic_hooklist_type
	},
	{
	  NGM_GENERIC_COOKIE,
	  NGM_LISTNAMES,
	  "listnames",
	  NULL,
	  &ng_generic_listnodes_type	/* same as NGM_LISTNODES */
	},
	{
	  NGM_GENERIC_COOKIE,
	  NGM_LISTNODES,
	  "listnodes",
	  NULL,
	  &ng_generic_listnodes_type
	},
	{
	  NGM_GENERIC_COOKIE,
	  NGM_LISTTYPES,
	  "listtypes",
	  NULL,
	  &ng_generic_typeinfo_type
	},
	{
	  NGM_GENERIC_COOKIE,
	  NGM_TEXT_STATUS,
	  "textstatus",
	  NULL,
	  &ng_parse_string_type
	},
	{
	  NGM_GENERIC_COOKIE,
	  NGM_ASCII2BINARY,
	  "ascii2binary",
	  &ng_parse_ng_mesg_type,
	  &ng_parse_ng_mesg_type
	},
	{
	  NGM_GENERIC_COOKIE,
	  NGM_BINARY2ASCII,
	  "binary2ascii",
	  &ng_parse_ng_mesg_type,
	  &ng_parse_ng_mesg_type
	},
	{ 0 }
};

/************************************************************************
			Node routines
************************************************************************/

/*
 * Instantiate a node of the requested type
 */
int
ng_make_node(const char *typename, node_p *nodepp)
{
	struct ng_type *type;

	/* Check that the type makes sense */
	if (typename == NULL) {
		TRAP_ERROR;
		return (EINVAL);
	}

	/* Locate the node type */
	if ((type = ng_findtype(typename)) == NULL) {
		char filename[NG_TYPELEN + 4];
		linker_file_t lf;
		int error;

		/* Not found, try to load it as a loadable module */
		snprintf(filename, sizeof(filename), "ng_%s", typename);
		error = linker_load_file(filename, &lf);
		if (error != 0)
			return (error);
		lf->userrefs++;		/* pretend loaded by the syscall */

		/* Try again, as now the type should have linked itself in */
		if ((type = ng_findtype(typename)) == NULL)
			return (ENXIO);
	}

	/* Call the constructor */
	if (type->constructor != NULL)
		return ((*type->constructor)(nodepp));
	else
		return (ng_make_node_common(type, nodepp));
}

/*
 * Generic node creation. Called by node constructors.
 * The returned node has a reference count of 1.
 */
int
ng_make_node_common(struct ng_type *type, node_p *nodepp)
{
	node_p node;

	/* Require the node type to have been already installed */
	if (ng_findtype(type->name) == NULL) {
		TRAP_ERROR;
		return (EINVAL);
	}

	/* Make a node and try attach it to the type */
	MALLOC(node, node_p, sizeof(*node), M_NETGRAPH, M_WAITOK);
	if (node == NULL) {
		TRAP_ERROR;
		return (ENOMEM);
	}
	bzero(node, sizeof(*node));
	node->type = type;
	node->refs++;				/* note reference */
	type->refs++;

	/* Link us into the node linked list */
	LIST_INSERT_HEAD(&nodelist, node, nodes);

	/* Initialize hook list for new node */
	LIST_INIT(&node->hooks);

	/* get an ID and put us in the hash chain */
	node->ID = nextID++; /* 137 per second for 1 year before wrap */
	LIST_INSERT_HEAD(&ID_hash[node->ID % ID_HASH_SIZE], node, idnodes);

	/* Done */
	*nodepp = node;
	return (0);
}

/*
 * Forceably start the shutdown process on a node. Either call
 * it's shutdown method, or do the default shutdown if there is
 * no type-specific method.
 *
 * Persistent nodes must have a type-specific method which
 * resets the NG_INVALID flag.
 */
void
ng_rmnode(node_p node)
{
	/* Check if it's already shutting down */
	if ((node->flags & NG_INVALID) != 0)
		return;

	/* Add an extra reference so it doesn't go away during this */
	node->refs++;

	/* Mark it invalid so any newcomers know not to try use it */
	node->flags |= NG_INVALID;

	/* Ask the type if it has anything to do in this case */
	if (node->type && node->type->shutdown)
		(*node->type->shutdown)(node);
	else {				/* do the default thing */
		ng_unname(node);
		ng_cutlinks(node);
		ng_unref(node);
	}

	/* Remove extra reference, possibly the last */
	ng_unref(node);
}

/*
 * Called by the destructor to remove any STANDARD external references
 */
void
ng_cutlinks(node_p node)
{
	hook_p  hook;

	/* Make sure that this is set to stop infinite loops */
	node->flags |= NG_INVALID;

	/* If we have sleepers, wake them up; they'll see NG_INVALID */
	if (node->sleepers)
		wakeup(node);

	/* Notify all remaining connected nodes to disconnect */
	while ((hook = LIST_FIRST(&node->hooks)) != NULL)
		ng_destroy_hook(hook);
}

/*
 * Remove a reference to the node, possibly the last
 */
void
ng_unref(node_p node)
{
	if (--node->refs <= 0) {
		node->type->refs--;
		LIST_REMOVE(node, nodes);
		LIST_REMOVE(node, idnodes);
		FREE(node, M_NETGRAPH);
	}
}

/*
 * Wait for a node to come ready. Returns a node with a reference count;
 * don't forget to drop it when we are done with it using ng_release_node().
 */
int
ng_wait_node(node_p node, char *msg)
{
	int s, error = 0;

	if (msg == NULL)
		msg = "netgraph";
	s = splnet();
	node->sleepers++;
	node->refs++;		/* the sleeping process counts as a reference */
	while ((node->flags & (NG_BUSY | NG_INVALID)) == NG_BUSY)
		error = tsleep(node, (PZERO + 1) | PCATCH, msg, 0);
	node->sleepers--;
	if (node->flags & NG_INVALID) {
		TRAP_ERROR;
		error = ENXIO;
	} else {
		KASSERT(node->refs > 1,
		    ("%s: refs=%d", __FUNCTION__, node->refs));
		node->flags |= NG_BUSY;
	}
	splx(s);

	/* Release the reference we had on it */
	if (error != 0)
		ng_unref(node);
	return error;
}

/*
 * Release a node acquired via ng_wait_node()
 */
void
ng_release_node(node_p node)
{
	/* Declare that we don't want it */
	node->flags &= ~NG_BUSY;

	/* If we have sleepers, then wake them up */
	if (node->sleepers)
		wakeup(node);

	/* We also have a reference.. drop it too */
	ng_unref(node);
}

/************************************************************************
			Node ID handling
************************************************************************/
static node_p
ng_ID2node(ng_ID_t ID)
{
	node_p np;
	LIST_FOREACH(np, &ID_hash[ID % ID_HASH_SIZE], idnodes) {
		if (np->ID == ID)
			break;
	}
	return(np);
}

ng_ID_t
ng_node2ID(node_p node)
{
	return (node->ID);
}

/************************************************************************
			Node name handling
************************************************************************/

/*
 * Assign a node a name. Once assigned, the name cannot be changed.
 */
int
ng_name_node(node_p node, const char *name)
{
	int i;

	/* Check the name is valid */
	for (i = 0; i < NG_NODELEN + 1; i++) {
		if (name[i] == '\0' || name[i] == '.' || name[i] == ':')
			break;
	}
	if (i == 0 || name[i] != '\0') {
		TRAP_ERROR;
		return (EINVAL);
	}
	if (ng_decodeidname(name) != 0) { /* valid IDs not allowed here */
		TRAP_ERROR;
		return (EINVAL);
	}

	/* Check the node isn't already named */
	if (node->name != NULL) {
		TRAP_ERROR;
		return (EISCONN);
	}

	/* Check the name isn't already being used */
	if (ng_findname(node, name) != NULL) {
		TRAP_ERROR;
		return (EADDRINUSE);
	}

	/* Allocate space and copy it */
	MALLOC(node->name, char *, strlen(name) + 1, M_NETGRAPH, M_WAITOK);
	if (node->name == NULL) {
		TRAP_ERROR;
		return (ENOMEM);
	}
	strcpy(node->name, name);

	/* The name counts as a reference */
	node->refs++;
	return (0);
}

/*
 * Find a node by absolute name. The name should NOT end with ':'
 * The name "." means "this node" and "[xxx]" means "the node
 * with ID (ie, at address) xxx".
 *
 * Returns the node if found, else NULL.
 */
node_p
ng_findname(node_p this, const char *name)
{
	node_p node;
	ng_ID_t temp;

	/* "." means "this node" */
	if (strcmp(name, ".") == 0)
		return(this);

	/* Check for name-by-ID */
	if ((temp = ng_decodeidname(name)) != 0) {
		return (ng_ID2node(temp));
	}

	/* Find node by name */
	LIST_FOREACH(node, &nodelist, nodes) {
		if (node->name != NULL && strcmp(node->name, name) == 0)
			break;
	}
	return (node);
}

/*
 * Decode a ID name, eg. "[f03034de]". Returns 0 if the
 * string is not valid, otherwise returns the value.
 */
static ng_ID_t
ng_decodeidname(const char *name)
{
	const int len = strlen(name);
	char *eptr;
	u_long val;

	/* Check for proper length, brackets, no leading junk */
	if (len < 3 || name[0] != '[' || name[len - 1] != ']'
	    || !isxdigit(name[1]))
		return (0);

	/* Decode number */
	val = strtoul(name + 1, &eptr, 16);
	if (eptr - name != len - 1 || val == ULONG_MAX || val == 0)
		return ((ng_ID_t)0);
	return (ng_ID_t)val;
}

/*
 * Remove a name from a node. This should only be called
 * when shutting down and removing the node.
 */
void
ng_unname(node_p node)
{
	if (node->name) {
		FREE(node->name, M_NETGRAPH);
		node->name = NULL;
		ng_unref(node);
	}
}

/************************************************************************
			Hook routines

 Names are not optional. Hooks are always connected, except for a
 brief moment within these routines.

************************************************************************/

/*
 * Remove a hook reference
 */
static void
ng_unref_hook(hook_p hook)
{
	if (--hook->refs == 0)
		FREE(hook, M_NETGRAPH);
}

/*
 * Add an unconnected hook to a node. Only used internally.
 */
static int
ng_add_hook(node_p node, const char *name, hook_p *hookp)
{
	hook_p hook;
	int error = 0;

	/* Check that the given name is good */
	if (name == NULL) {
		TRAP_ERROR;
		return (EINVAL);
	}
	if (ng_findhook(node, name) != NULL) {
		TRAP_ERROR;
		return (EEXIST);
	}

	/* Allocate the hook and link it up */
	MALLOC(hook, hook_p, sizeof(*hook), M_NETGRAPH, M_WAITOK);
	if (hook == NULL) {
		TRAP_ERROR;
		return (ENOMEM);
	}
	bzero(hook, sizeof(*hook));
	hook->refs = 1;
	hook->flags = HK_INVALID;
	hook->node = node;
	node->refs++;		/* each hook counts as a reference */

	/* Check if the node type code has something to say about it */
	if (node->type->newhook != NULL)
		if ((error = (*node->type->newhook)(node, hook, name)) != 0)
			goto fail;

	/*
	 * The 'type' agrees so far, so go ahead and link it in.
	 * We'll ask again later when we actually connect the hooks.
	 */
	LIST_INSERT_HEAD(&node->hooks, hook, hooks);
	node->numhooks++;

	/* Set hook name */
	MALLOC(hook->name, char *, strlen(name) + 1, M_NETGRAPH, M_WAITOK);
	if (hook->name == NULL) {
		error = ENOMEM;
		LIST_REMOVE(hook, hooks);
		node->numhooks--;
fail:
		hook->node = NULL;
		ng_unref(node);
		ng_unref_hook(hook);	/* this frees the hook */
		return (error);
	}
	strcpy(hook->name, name);
	if (hookp)
		*hookp = hook;
	return (error);
}

/*
 * Connect a pair of hooks. Only used internally.
 */
static int
ng_connect(hook_p hook1, hook_p hook2)
{
	int     error;

	hook1->peer = hook2;
	hook2->peer = hook1;

	/* Give each node the opportunity to veto the impending connection */
	if (hook1->node->type->connect) {
		if ((error = (*hook1->node->type->connect) (hook1))) {
			ng_destroy_hook(hook1);	/* also zaps hook2 */
			return (error);
		}
	}
	if (hook2->node->type->connect) {
		if ((error = (*hook2->node->type->connect) (hook2))) {
			ng_destroy_hook(hook2);	/* also zaps hook1 */
			return (error);
		}
	}
	hook1->flags &= ~HK_INVALID;
	hook2->flags &= ~HK_INVALID;
	return (0);
}

/*
 * Find a hook
 *
 * Node types may supply their own optimized routines for finding
 * hooks.  If none is supplied, we just do a linear search.
 */
hook_p
ng_findhook(node_p node, const char *name)
{
	hook_p hook;

	if (node->type->findhook != NULL)
		return (*node->type->findhook)(node, name);
	LIST_FOREACH(hook, &node->hooks, hooks) {
		if (hook->name != NULL && strcmp(hook->name, name) == 0)
			return (hook);
	}
	return (NULL);
}

/*
 * Destroy a hook
 *
 * As hooks are always attached, this really destroys two hooks.
 * The one given, and the one attached to it. Disconnect the hooks
 * from each other first.
 */
void
ng_destroy_hook(hook_p hook)
{
	hook_p peer = hook->peer;

	hook->flags |= HK_INVALID;		/* as soon as possible */
	if (peer) {
		peer->flags |= HK_INVALID;	/* as soon as possible */
		hook->peer = NULL;
		peer->peer = NULL;
		ng_disconnect_hook(peer);
	}
	ng_disconnect_hook(hook);
}

/*
 * Notify the node of the hook's demise. This may result in more actions
 * (e.g. shutdown) but we don't do that ourselves and don't know what
 * happens there. If there is no appropriate handler, then just remove it
 * (and decrement the reference count of it's node which in turn might
 * make something happen).
 */
static void
ng_disconnect_hook(hook_p hook)
{
	node_p node = hook->node;

	/*
	 * Remove the hook from the node's list to avoid possible recursion
	 * in case the disconnection results in node shutdown.
	 */
	LIST_REMOVE(hook, hooks);
	node->numhooks--;
	if (node->type->disconnect) {
		/*
		 * The type handler may elect to destroy the peer so don't
		 * trust its existance after this point.
		 */
		(*node->type->disconnect) (hook);
	}
	ng_unref(node);		/* might be the last reference */
	if (hook->name)
		FREE(hook->name, M_NETGRAPH);
	hook->node = NULL;	/* may still be referenced elsewhere */
	ng_unref_hook(hook);
}

/*
 * Take two hooks on a node and merge the connection so that the given node
 * is effectively bypassed.
 */
int
ng_bypass(hook_p hook1, hook_p hook2)
{
	if (hook1->node != hook2->node)
		return (EINVAL);
	hook1->peer->peer = hook2->peer;
	hook2->peer->peer = hook1->peer;

	/* XXX If we ever cache methods on hooks update them as well */
	hook1->peer = NULL;
	hook2->peer = NULL;
	ng_destroy_hook(hook1);
	ng_destroy_hook(hook2);
	return (0);
}

/*
 * Install a new netgraph type
 */
int
ng_newtype(struct ng_type *tp)
{
	const size_t namelen = strlen(tp->name);

	/* Check version and type name fields */
	if (tp->version != NG_VERSION || namelen == 0 || namelen > NG_TYPELEN) {
		TRAP_ERROR;
		return (EINVAL);
	}

	/* Check for name collision */
	if (ng_findtype(tp->name) != NULL) {
		TRAP_ERROR;
		return (EEXIST);
	}

	/* Link in new type */
	LIST_INSERT_HEAD(&typelist, tp, types);
	tp->refs = 0;
	return (0);
}

/*
 * Look for a type of the name given
 */
struct ng_type *
ng_findtype(const char *typename)
{
	struct ng_type *type;

	LIST_FOREACH(type, &typelist, types) {
		if (strcmp(type->name, typename) == 0)
			break;
	}
	return (type);
}


/************************************************************************
			Composite routines
************************************************************************/

/*
 * Make a peer and connect. The order is arranged to minimise
 * the work needed to back out in case of error.
 */
int
ng_mkpeer(node_p node, const char *name, const char *name2, char *type)
{
	node_p  node2;
	hook_p  hook;
	hook_p  hook2;
	int     error;

	if ((error = ng_add_hook(node, name, &hook)))
		return (error);
	if ((error = ng_make_node(type, &node2))) {
		ng_destroy_hook(hook);
		return (error);
	}
	if ((error = ng_add_hook(node2, name2, &hook2))) {
		ng_rmnode(node2);
		ng_destroy_hook(hook);
		return (error);
	}

	/*
	 * Actually link the two hooks together.. on failure they are
	 * destroyed so we don't have to do that here.
	 */
	if ((error = ng_connect(hook, hook2)))
		ng_rmnode(node2);
	return (error);
}

/*
 * Connect two nodes using the specified hooks
 */
int
ng_con_nodes(node_p node, const char *name, node_p node2, const char *name2)
{
	int     error;
	hook_p  hook;
	hook_p  hook2;

	if ((error = ng_add_hook(node, name, &hook)))
		return (error);
	if ((error = ng_add_hook(node2, name2, &hook2))) {
		ng_destroy_hook(hook);
		return (error);
	}
	return (ng_connect(hook, hook2));
}

/*
 * Parse and verify a string of the form:  <NODE:><PATH>
 *
 * Such a string can refer to a specific node or a specific hook
 * on a specific node, depending on how you look at it. In the
 * latter case, the PATH component must not end in a dot.
 *
 * Both <NODE:> and <PATH> are optional. The <PATH> is a string
 * of hook names separated by dots. This breaks out the original
 * string, setting *nodep to "NODE" (or NULL if none) and *pathp
 * to "PATH" (or NULL if degenerate). Also, *hookp will point to
 * the final hook component of <PATH>, if any, otherwise NULL.
 *
 * This returns -1 if the path is malformed. The char ** are optional.
 */

int
ng_path_parse(char *addr, char **nodep, char **pathp, char **hookp)
{
	char   *node, *path, *hook;
	int     k;

	/*
	 * Extract absolute NODE, if any
	 */
	for (path = addr; *path && *path != ':'; path++);
	if (*path) {
		node = addr;	/* Here's the NODE */
		*path++ = '\0';	/* Here's the PATH */

		/* Node name must not be empty */
		if (!*node)
			return -1;

		/* A name of "." is OK; otherwise '.' not allowed */
		if (strcmp(node, ".") != 0) {
			for (k = 0; node[k]; k++)
				if (node[k] == '.')
					return -1;
		}
	} else {
		node = NULL;	/* No absolute NODE */
		path = addr;	/* Here's the PATH */
	}

	/* Snoop for illegal characters in PATH */
	for (k = 0; path[k]; k++)
		if (path[k] == ':')
			return -1;

	/* Check for no repeated dots in PATH */
	for (k = 0; path[k]; k++)
		if (path[k] == '.' && path[k + 1] == '.')
			return -1;

	/* Remove extra (degenerate) dots from beginning or end of PATH */
	if (path[0] == '.')
		path++;
	if (*path && path[strlen(path) - 1] == '.')
		path[strlen(path) - 1] = 0;

	/* If PATH has a dot, then we're not talking about a hook */
	if (*path) {
		for (hook = path, k = 0; path[k]; k++)
			if (path[k] == '.') {
				hook = NULL;
				break;
			}
	} else
		path = hook = NULL;

	/* Done */
	if (nodep)
		*nodep = node;
	if (pathp)
		*pathp = path;
	if (hookp)
		*hookp = hook;
	return (0);
}

/*
 * Given a path, which may be absolute or relative, and a starting node,
 * return the destination node. Compute the "return address" if desired.
 */
int
ng_path2node(node_p here, const char *address, node_p *destp, char **rtnp,
	hook_p *lasthook)
{
	const	node_p start = here;
	char    fullpath[NG_PATHLEN + 1];
	char   *nodename, *path, pbuf[2];
	node_p  node;
	char   *cp;
	hook_p hook = NULL;

	/* Initialize */
	if (rtnp)
		*rtnp = NULL;
	if (destp == NULL)
		return EINVAL;
	*destp = NULL;

	/* Make a writable copy of address for ng_path_parse() */
	strncpy(fullpath, address, sizeof(fullpath) - 1);
	fullpath[sizeof(fullpath) - 1] = '\0';

	/* Parse out node and sequence of hooks */
	if (ng_path_parse(fullpath, &nodename, &path, NULL) < 0) {
		TRAP_ERROR;
		return EINVAL;
	}
	if (path == NULL) {
		pbuf[0] = '.';	/* Needs to be writable */
		pbuf[1] = '\0';
		path = pbuf;
	}

	/* For an absolute address, jump to the starting node */
	if (nodename) {
		node = ng_findname(here, nodename);
		if (node == NULL) {
			TRAP_ERROR;
			return (ENOENT);
		}
	} else
		node = here;

	/* Now follow the sequence of hooks */
	for (cp = path; node != NULL && *cp != '\0'; ) {
		char *segment;

		/*
		 * Break out the next path segment. Replace the dot we just
		 * found with a NUL; "cp" points to the next segment (or the
		 * NUL at the end).
		 */
		for (segment = cp; *cp != '\0'; cp++) {
			if (*cp == '.') {
				*cp++ = '\0';
				break;
			}
		}

		/* Empty segment */
		if (*segment == '\0')
			continue;

		/* We have a segment, so look for a hook by that name */
		hook = ng_findhook(node, segment);

		/* Can't get there from here... */
		if (hook == NULL
		    || hook->peer == NULL
		    || (hook->flags & HK_INVALID) != 0) {
			TRAP_ERROR;
			return (ENOENT);
		}

		/* Hop on over to the next node */
		node = hook->peer->node;
	}

	/* If node somehow missing, fail here (probably this is not needed) */
	if (node == NULL) {
		TRAP_ERROR;
		return (ENXIO);
	}

	/* Now compute return address, i.e., the path to the sender */
	if (rtnp != NULL) {
		MALLOC(*rtnp, char *, NG_NODELEN + 2, M_NETGRAPH, M_WAITOK);
		if (*rtnp == NULL) {
			TRAP_ERROR;
			return (ENOMEM);
		}
		if (start->name != NULL)
			sprintf(*rtnp, "%s:", start->name);
		else
			sprintf(*rtnp, "[%x]:", ng_node2ID(start));
	}

	/* Done */
	*destp = node;
	if (lasthook != NULL)
		*lasthook = hook ? hook->peer : NULL;
	return (0);
}

/*
 * Call the appropriate message handler for the object.
 * It is up to the message handler to free the message.
 * If it's a generic message, handle it generically, otherwise
 * call the type's message handler (if it exists)
 */

#define CALL_MSG_HANDLER(error, node, msg, retaddr, resp, hook)		\
do {									\
	if((msg)->header.typecookie == NGM_GENERIC_COOKIE) {		\
		(error) = ng_generic_msg((node), (msg),			\
			(retaddr), (resp), (hook));			\
	} else {							\
		if ((node)->type->rcvmsg != NULL) {			\
			(error) = (*(node)->type->rcvmsg)((node),	\
				(msg), (retaddr), (resp), (hook));	\
		} else {						\
			TRAP_ERROR;					\
			FREE((msg), M_NETGRAPH);			\
			(error) = EINVAL;				\
		}							\
	}								\
} while (0)


/*
 * Send a control message to a node
 */
int
ng_send_msg(node_p here, struct ng_mesg *msg, const char *address,
	    struct ng_mesg **rptr)
{
	node_p  dest = NULL;
	char   *retaddr = NULL;
	int     error;
	hook_p	lasthook;

	/* Find the target node */
	error = ng_path2node(here, address, &dest, &retaddr, &lasthook);
	if (error) {
		FREE(msg, M_NETGRAPH);
		return error;
	}

	/* Make sure the resp field is null before we start */
	if (rptr != NULL)
		*rptr = NULL;

	CALL_MSG_HANDLER(error, dest, msg, retaddr, rptr, lasthook);

	/* Make sure that if there is a response, it has the RESP bit set */
	if ((error == 0) && rptr && *rptr)
		(*rptr)->header.flags |= NGF_RESP;

	/*
	 * If we had a return address it is up to us to free it. They should
	 * have taken a copy if they needed to make a delayed response.
	 */
	if (retaddr)
		FREE(retaddr, M_NETGRAPH);
	return (error);
}

/*
 * Implement the 'generic' control messages
 */
static int
ng_generic_msg(node_p here, struct ng_mesg *msg, const char *retaddr,
	       struct ng_mesg **resp, hook_p lasthook)
{
	int error = 0;

	if (msg->header.typecookie != NGM_GENERIC_COOKIE) {
		TRAP_ERROR;
		FREE(msg, M_NETGRAPH);
		return (EINVAL);
	}
	switch (msg->header.cmd) {
	case NGM_SHUTDOWN:
		ng_rmnode(here);
		break;
	case NGM_MKPEER:
	    {
		struct ngm_mkpeer *const mkp = (struct ngm_mkpeer *) msg->data;

		if (msg->header.arglen != sizeof(*mkp)) {
			TRAP_ERROR;
			return (EINVAL);
		}
		mkp->type[sizeof(mkp->type) - 1] = '\0';
		mkp->ourhook[sizeof(mkp->ourhook) - 1] = '\0';
		mkp->peerhook[sizeof(mkp->peerhook) - 1] = '\0';
		error = ng_mkpeer(here, mkp->ourhook, mkp->peerhook, mkp->type);
		break;
	    }
	case NGM_CONNECT:
	    {
		struct ngm_connect *const con =
			(struct ngm_connect *) msg->data;
		node_p node2;

		if (msg->header.arglen != sizeof(*con)) {
			TRAP_ERROR;
			return (EINVAL);
		}
		con->path[sizeof(con->path) - 1] = '\0';
		con->ourhook[sizeof(con->ourhook) - 1] = '\0';
		con->peerhook[sizeof(con->peerhook) - 1] = '\0';
		error = ng_path2node(here, con->path, &node2, NULL, NULL);
		if (error)
			break;
		error = ng_con_nodes(here, con->ourhook, node2, con->peerhook);
		break;
	    }
	case NGM_NAME:
	    {
		struct ngm_name *const nam = (struct ngm_name *) msg->data;

		if (msg->header.arglen != sizeof(*nam)) {
			TRAP_ERROR;
			return (EINVAL);
		}
		nam->name[sizeof(nam->name) - 1] = '\0';
		error = ng_name_node(here, nam->name);
		break;
	    }
	case NGM_RMHOOK:
	    {
		struct ngm_rmhook *const rmh = (struct ngm_rmhook *) msg->data;
		hook_p hook;

		if (msg->header.arglen != sizeof(*rmh)) {
			TRAP_ERROR;
			return (EINVAL);
		}
		rmh->ourhook[sizeof(rmh->ourhook) - 1] = '\0';
		if ((hook = ng_findhook(here, rmh->ourhook)) != NULL)
			ng_destroy_hook(hook);
		break;
	    }
	case NGM_NODEINFO:
	    {
		struct nodeinfo *ni;
		struct ng_mesg *rp;

		/* Get response struct */
		if (resp == NULL) {
			error = EINVAL;
			break;
		}
		NG_MKRESPONSE(rp, msg, sizeof(*ni), M_NOWAIT);
		if (rp == NULL) {
			error = ENOMEM;
			break;
		}

		/* Fill in node info */
		ni = (struct nodeinfo *) rp->data;
		if (here->name != NULL)
			strncpy(ni->name, here->name, NG_NODELEN);
		strncpy(ni->type, here->type->name, NG_TYPELEN);
		ni->id = ng_node2ID(here);
		ni->hooks = here->numhooks;
		*resp = rp;
		break;
	    }
	case NGM_LISTHOOKS:
	    {
		const int nhooks = here->numhooks;
		struct hooklist *hl;
		struct nodeinfo *ni;
		struct ng_mesg *rp;
		hook_p hook;

		/* Get response struct */
		if (resp == NULL) {
			error = EINVAL;
			break;
		}
		NG_MKRESPONSE(rp, msg, sizeof(*hl)
		    + (nhooks * sizeof(struct linkinfo)), M_NOWAIT);
		if (rp == NULL) {
			error = ENOMEM;
			break;
		}
		hl = (struct hooklist *) rp->data;
		ni = &hl->nodeinfo;

		/* Fill in node info */
		if (here->name)
			strncpy(ni->name, here->name, NG_NODELEN);
		strncpy(ni->type, here->type->name, NG_TYPELEN);
		ni->id = ng_node2ID(here);

		/* Cycle through the linked list of hooks */
		ni->hooks = 0;
		LIST_FOREACH(hook, &here->hooks, hooks) {
			struct linkinfo *const link = &hl->link[ni->hooks];

			if (ni->hooks >= nhooks) {
				log(LOG_ERR, "%s: number of %s changed\n",
				    __FUNCTION__, "hooks");
				break;
			}
			if ((hook->flags & HK_INVALID) != 0)
				continue;
			strncpy(link->ourhook, hook->name, NG_HOOKLEN);
			strncpy(link->peerhook, hook->peer->name, NG_HOOKLEN);
			if (hook->peer->node->name != NULL)
				strncpy(link->nodeinfo.name,
				    hook->peer->node->name, NG_NODELEN);
			strncpy(link->nodeinfo.type,
			   hook->peer->node->type->name, NG_TYPELEN);
			link->nodeinfo.id = ng_node2ID(hook->peer->node);
			link->nodeinfo.hooks = hook->peer->node->numhooks;
			ni->hooks++;
		}
		*resp = rp;
		break;
	    }

	case NGM_LISTNAMES:
	case NGM_LISTNODES:
	    {
		const int unnamed = (msg->header.cmd == NGM_LISTNODES);
		struct namelist *nl;
		struct ng_mesg *rp;
		node_p node;
		int num = 0;

		if (resp == NULL) {
			error = EINVAL;
			break;
		}

		/* Count number of nodes */
		LIST_FOREACH(node, &nodelist, nodes) {
			if (unnamed || node->name != NULL)
				num++;
		}

		/* Get response struct */
		if (resp == NULL) {
			error = EINVAL;
			break;
		}
		NG_MKRESPONSE(rp, msg, sizeof(*nl)
		    + (num * sizeof(struct nodeinfo)), M_NOWAIT);
		if (rp == NULL) {
			error = ENOMEM;
			break;
		}
		nl = (struct namelist *) rp->data;

		/* Cycle through the linked list of nodes */
		nl->numnames = 0;
		LIST_FOREACH(node, &nodelist, nodes) {
			struct nodeinfo *const np = &nl->nodeinfo[nl->numnames];

			if (nl->numnames >= num) {
				log(LOG_ERR, "%s: number of %s changed\n",
				    __FUNCTION__, "nodes");
				break;
			}
			if ((node->flags & NG_INVALID) != 0)
				continue;
			if (!unnamed && node->name == NULL)
				continue;
			if (node->name != NULL)
				strncpy(np->name, node->name, NG_NODELEN);
			strncpy(np->type, node->type->name, NG_TYPELEN);
			np->id = ng_node2ID(node);
			np->hooks = node->numhooks;
			nl->numnames++;
		}
		*resp = rp;
		break;
	    }

	case NGM_LISTTYPES:
	    {
		struct typelist *tl;
		struct ng_mesg *rp;
		struct ng_type *type;
		int num = 0;

		if (resp == NULL) {
			error = EINVAL;
			break;
		}

		/* Count number of types */
		LIST_FOREACH(type, &typelist, types)
			num++;

		/* Get response struct */
		if (resp == NULL) {
			error = EINVAL;
			break;
		}
		NG_MKRESPONSE(rp, msg, sizeof(*tl)
		    + (num * sizeof(struct typeinfo)), M_NOWAIT);
		if (rp == NULL) {
			error = ENOMEM;
			break;
		}
		tl = (struct typelist *) rp->data;

		/* Cycle through the linked list of types */
		tl->numtypes = 0;
		LIST_FOREACH(type, &typelist, types) {
			struct typeinfo *const tp = &tl->typeinfo[tl->numtypes];

			if (tl->numtypes >= num) {
				log(LOG_ERR, "%s: number of %s changed\n",
				    __FUNCTION__, "types");
				break;
			}
			strncpy(tp->type_name, type->name, NG_TYPELEN);
			tp->numnodes = type->refs;
			tl->numtypes++;
		}
		*resp = rp;
		break;
	    }

	case NGM_BINARY2ASCII:
	    {
		int bufSize = 2000;	/* XXX hard coded constant */
		const struct ng_parse_type *argstype;
		const struct ng_cmdlist *c;
		struct ng_mesg *rp, *binary, *ascii;

		/* Data area must contain a valid netgraph message */
		binary = (struct ng_mesg *)msg->data;
		if (msg->header.arglen < sizeof(struct ng_mesg)
		    || msg->header.arglen - sizeof(struct ng_mesg) 
		      < binary->header.arglen) {
			error = EINVAL;
			break;
		}

		/* Get a response message with lots of room */
		NG_MKRESPONSE(rp, msg, sizeof(*ascii) + bufSize, M_NOWAIT);
		if (rp == NULL) {
			error = ENOMEM;
			break;
		}
		ascii = (struct ng_mesg *)rp->data;

		/* Copy binary message header to response message payload */
		bcopy(binary, ascii, sizeof(*binary));

		/* Find command by matching typecookie and command number */
		for (c = here->type->cmdlist;
		    c != NULL && c->name != NULL; c++) {
			if (binary->header.typecookie == c->cookie
			    && binary->header.cmd == c->cmd)
				break;
		}
		if (c == NULL || c->name == NULL) {
			for (c = ng_generic_cmds; c->name != NULL; c++) {
				if (binary->header.typecookie == c->cookie
				    && binary->header.cmd == c->cmd)
					break;
			}
			if (c->name == NULL) {
				FREE(rp, M_NETGRAPH);
				error = ENOSYS;
				break;
			}
		}

		/* Convert command name to ASCII */
		snprintf(ascii->header.cmdstr, sizeof(ascii->header.cmdstr),
		    "%s", c->name);

		/* Convert command arguments to ASCII */
		argstype = (binary->header.flags & NGF_RESP) ?
		    c->respType : c->mesgType;
		if (argstype == NULL)
			*ascii->data = '\0';
		else {
			if ((error = ng_unparse(argstype,
			    (u_char *)binary->data,
			    ascii->data, bufSize)) != 0) {
				FREE(rp, M_NETGRAPH);
				break;
			}
		}

		/* Return the result as struct ng_mesg plus ASCII string */
		bufSize = strlen(ascii->data) + 1;
		ascii->header.arglen = bufSize;
		rp->header.arglen = sizeof(*ascii) + bufSize;
		*resp = rp;
		break;
	    }

	case NGM_ASCII2BINARY:
	    {
		int bufSize = 2000;	/* XXX hard coded constant */
		const struct ng_cmdlist *c;
		const struct ng_parse_type *argstype;
		struct ng_mesg *rp, *ascii, *binary;
		int off = 0;

		/* Data area must contain at least a struct ng_mesg + '\0' */
		ascii = (struct ng_mesg *)msg->data;
		if (msg->header.arglen < sizeof(*ascii) + 1
		    || ascii->header.arglen < 1
		    || msg->header.arglen
		      < sizeof(*ascii) + ascii->header.arglen) {
			error = EINVAL;
			break;
		}
		ascii->data[ascii->header.arglen - 1] = '\0';

		/* Get a response message with lots of room */
		NG_MKRESPONSE(rp, msg, sizeof(*binary) + bufSize, M_NOWAIT);
		if (rp == NULL) {
			error = ENOMEM;
			break;
		}
		binary = (struct ng_mesg *)rp->data;

		/* Copy ASCII message header to response message payload */
		bcopy(ascii, binary, sizeof(*ascii));

		/* Find command by matching ASCII command string */
		for (c = here->type->cmdlist;
		    c != NULL && c->name != NULL; c++) {
			if (strcmp(ascii->header.cmdstr, c->name) == 0)
				break;
		}
		if (c == NULL || c->name == NULL) {
			for (c = ng_generic_cmds; c->name != NULL; c++) {
				if (strcmp(ascii->header.cmdstr, c->name) == 0)
					break;
			}
			if (c->name == NULL) {
				FREE(rp, M_NETGRAPH);
				error = ENOSYS;
				break;
			}
		}

		/* Convert command name to binary */
		binary->header.cmd = c->cmd;
		binary->header.typecookie = c->cookie;

		/* Convert command arguments to binary */
		argstype = (binary->header.flags & NGF_RESP) ?
		    c->respType : c->mesgType;
		if (argstype == NULL)
			bufSize = 0;
		else {
			if ((error = ng_parse(argstype, ascii->data,
			    &off, (u_char *)binary->data, &bufSize)) != 0) {
				FREE(rp, M_NETGRAPH);
				break;
			}
		}

		/* Return the result */
		binary->header.arglen = bufSize;
		rp->header.arglen = sizeof(*binary) + bufSize;
		*resp = rp;
		break;
	    }

	case NGM_TEXT_STATUS:
		/*
		 * This one is tricky as it passes the command down to the
		 * actual node, even though it is a generic type command.
		 * This means we must assume that the msg is already freed
		 * when control passes back to us.
		 */
		if (resp == NULL) {
			error = EINVAL;
			break;
		}
		if (here->type->rcvmsg != NULL)
			return((*here->type->rcvmsg)(here, msg, retaddr,
			resp, lasthook));
		/* Fall through if rcvmsg not supported */
	default:
		TRAP_ERROR;
		error = EINVAL;
	}
	FREE(msg, M_NETGRAPH);
	return (error);
}

/*
 * Send a data packet to a node. If the recipient has no
 * 'receive data' method, then silently discard the packet.
 */
int 
ng_send_data(hook_p hook, struct mbuf *m, meta_p meta,
	struct mbuf **ret_m, meta_p *ret_meta)
{
	ng_rcvdata_t *rcvdata;
	int error;

	CHECK_DATA_MBUF(m);
	if (hook && (hook->flags & HK_INVALID) == 0) {
		rcvdata = hook->peer->node->type->rcvdata;
		if (rcvdata != NULL)
			error = (*rcvdata)(hook->peer, m, meta,
					ret_m, ret_meta);
		else {
			error = 0;
			NG_FREE_DATA(m, meta);
		}
	} else {
		TRAP_ERROR;
		error = ENOTCONN;
		NG_FREE_DATA(m, meta);
	}
	return (error);
}

/*
 * Send a queued data packet to a node. If the recipient has no
 * 'receive queued data' method, then try the 'receive data' method above.
 */
int 
ng_send_dataq(hook_p hook, struct mbuf *m, meta_p meta,
	struct mbuf **ret_m, meta_p *ret_meta)
{
	ng_rcvdata_t *rcvdata;
	int error;

	CHECK_DATA_MBUF(m);
	if (hook && (hook->flags & HK_INVALID) == 0) {
		rcvdata = hook->peer->node->type->rcvdataq;
		if (rcvdata != NULL)
			error = (*rcvdata)(hook->peer, m, meta,
					ret_m, ret_meta);
		else {
			rcvdata = hook->peer->node->type->rcvdata;
			if (rcvdata != NULL) {
				error = (*rcvdata)(hook->peer, m, meta,
					ret_m, ret_meta);
			} else {
				error = 0;
				NG_FREE_DATA(m, meta);
			}
		}
	} else {
		TRAP_ERROR;
		error = ENOTCONN;
		NG_FREE_DATA(m, meta);
	}
	return (error);
}

/*
 * Copy a 'meta'.
 *
 * Returns new meta, or NULL if original meta is NULL or ENOMEM.
 */
meta_p
ng_copy_meta(meta_p meta)
{
	meta_p meta2;

	if (meta == NULL)
		return (NULL);
	MALLOC(meta2, meta_p, meta->used_len, M_NETGRAPH, M_NOWAIT);
	if (meta2 == NULL)
		return (NULL);
	meta2->allocated_len = meta->used_len;
	bcopy(meta, meta2, meta->used_len);
	return (meta2);
}

/************************************************************************
			Module routines
************************************************************************/

/*
 * Handle the loading/unloading of a netgraph node type module
 */
int
ng_mod_event(module_t mod, int event, void *data)
{
	struct ng_type *const type = data;
	int s, error = 0;

	switch (event) {
	case MOD_LOAD:

		/* Register new netgraph node type */
		s = splnet();
		if ((error = ng_newtype(type)) != 0) {
			splx(s);
			break;
		}

		/* Call type specific code */
		if (type->mod_event != NULL)
			if ((error = (*type->mod_event)(mod, event, data)) != 0)
				LIST_REMOVE(type, types);
		splx(s);
		break;

	case MOD_UNLOAD:
		s = splnet();
		if (type->refs != 0)		/* make sure no nodes exist! */
			error = EBUSY;
		else {
			if (type->mod_event != NULL) {	/* check with type */
				error = (*type->mod_event)(mod, event, data);
				if (error != 0) {	/* type refuses.. */
					splx(s);
					break;
				}
			}
			LIST_REMOVE(type, types);
		}
		splx(s);
		break;

	default:
		if (type->mod_event != NULL)
			error = (*type->mod_event)(mod, event, data);
		else
			error = 0;		/* XXX ? */
		break;
	}
	return (error);
}

/*
 * Handle loading and unloading for this code.
 * The only thing we need to link into is the NETISR strucure.
 */
static int
ngb_mod_event(module_t mod, int event, void *data)
{
	int s, error = 0;

	switch (event) {
	case MOD_LOAD:
		/* Register line discipline */
		s = splimp();
		error = register_netisr(NETISR_NETGRAPH, ngintr);
		splx(s);
		break;
	case MOD_UNLOAD:
		/* You cant unload it because an interface may be using it.  */
		error = EBUSY;
		break;
	default:
		error = EOPNOTSUPP;
		break;
	}
	return (error);
}

static moduledata_t netgraph_mod = {
	"netgraph",
	ngb_mod_event,
	(NULL)
};
DECLARE_MODULE(netgraph, netgraph_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE);

/************************************************************************
			Queueing routines
************************************************************************/

/* The structure for queueing across ISR switches */
struct ng_queue_entry {
	u_long	flags;
	struct ng_queue_entry *next;
	union {
		struct {
			hook_p		da_hook;	/*  target hook */
			struct mbuf	*da_m;
			meta_p		da_meta;
		} data;
		struct {
			struct ng_mesg	*msg_msg;
			node_p		msg_node;
			void		*msg_retaddr;
			hook_p		msg_lasthook;
		} msg;
	} body;
};
#define NGQF_DATA	0x01		/* the queue element is data */
#define NGQF_MESG	0x02		/* the queue element is a message */

static struct ng_queue_entry   *ngqbase;	/* items to be unqueued */
static struct ng_queue_entry   *ngqlast;	/* last item queued */
static const int		ngqroom = 64;	/* max items to queue */
static int			ngqsize;	/* number of items in queue */

static struct ng_queue_entry   *ngqfree;	/* free ones */
static const int		ngqfreemax = 16;/* cache at most this many */
static int			ngqfreesize;	/* number of cached entries */

/*
 * Get a queue entry
 */
static struct ng_queue_entry *
ng_getqblk(void)
{
	register struct ng_queue_entry *q;
	int s;

	/* Could be guarding against tty ints or whatever */
	s = splhigh();

	/* Try get a cached queue block, or else allocate a new one */
	if ((q = ngqfree) == NULL) {
		splx(s);
		if (ngqsize < ngqroom) {	/* don't worry about races */
			MALLOC(q, struct ng_queue_entry *,
			    sizeof(*q), M_NETGRAPH, M_NOWAIT);
		}
	} else {
		ngqfree = q->next;
		ngqfreesize--;
		splx(s);
	}
	return (q);
}

/*
 * Release a queue entry
 */
#define RETURN_QBLK(q)							\
do {									\
	int s;								\
	if (ngqfreesize < ngqfreemax) { /* don't worry about races */ 	\
		s = splhigh();						\
		(q)->next = ngqfree;					\
		ngqfree = (q);						\
		ngqfreesize++;						\
		splx(s);						\
	} else {							\
		FREE((q), M_NETGRAPH);					\
	}								\
} while (0)

/*
 * Running at a raised (but we don't know which) processor priority level,
 * put the data onto a queue to be picked up by another PPL (probably splnet)
 */
int
ng_queue_data(hook_p hook, struct mbuf *m, meta_p meta)
{
	struct ng_queue_entry *q;
	int s;

	if (hook == NULL) {
		NG_FREE_DATA(m, meta);
		return (0);
	}
	if ((q = ng_getqblk()) == NULL) {
		NG_FREE_DATA(m, meta);
		return (ENOBUFS);
	}

	/* Fill out the contents */
	q->flags = NGQF_DATA;
	q->next = NULL;
	q->body.data.da_hook = hook;
	q->body.data.da_m = m;
	q->body.data.da_meta = meta;
	hook->refs++;		/* don't let it go away while on the queue */

	/* Put it on the queue */
	s = splhigh();
	if (ngqbase) {
		ngqlast->next = q;
	} else {
		ngqbase = q;
	}
	ngqlast = q;
	ngqsize++;
	splx(s);

	/* Schedule software interrupt to handle it later */
	schednetisr(NETISR_NETGRAPH);
	return (0);
}

/*
 * Running at a raised (but we don't know which) processor priority level,
 * put the msg onto a queue to be picked up by another PPL (probably splnet)
 */
int
ng_queue_msg(node_p here, struct ng_mesg *msg, const char *address)
{
	register struct ng_queue_entry *q;
	int     s;
	node_p  dest = NULL;
	char   *retaddr = NULL;
	int     error;
	hook_p	lasthook = NULL;

	/* Find the target node. */
	error = ng_path2node(here, address, &dest, &retaddr, &lasthook);
	if (error) {
		FREE(msg, M_NETGRAPH);
		return (error);
	}
	if ((q = ng_getqblk()) == NULL) {
		FREE(msg, M_NETGRAPH);
		if (retaddr)
			FREE(retaddr, M_NETGRAPH);
		return (ENOBUFS);
	}

	/* Fill out the contents */
	q->flags = NGQF_MESG;
	q->next = NULL;
	q->body.msg.msg_node = dest;
	q->body.msg.msg_msg = msg;
	q->body.msg.msg_retaddr = retaddr;
	q->body.msg.msg_lasthook = lasthook;
	dest->refs++;		/* don't let it go away while on the queue */
	if (lasthook)
		lasthook->refs++; /* same for the hook */

	/* Put it on the queue */
	s = splhigh();
	if (ngqbase) {
		ngqlast->next = q;
	} else {
		ngqbase = q;
	}
	ngqlast = q;
	ngqsize++;
	splx(s);

	/* Schedule software interrupt to handle it later */
	schednetisr(NETISR_NETGRAPH);
	return (0);
}

/*
 * Pick an item off the queue, process it, and dispose of the queue entry.
 * Should be running at splnet.
 */
static void
ngintr(void)
{
	hook_p  hook;
	struct ng_queue_entry *ngq;
	struct mbuf *m;
	meta_p  meta;
	void   *retaddr;
	struct ng_mesg *msg;
	node_p  node;
	int     error = 0;
	int     s;

	while (1) {
		s = splhigh();
		if ((ngq = ngqbase)) {
			ngqbase = ngq->next;
			ngqsize--;
		}
		splx(s);
		if (ngq == NULL)
			return;
		switch (ngq->flags) {
		case NGQF_DATA:
			hook = ngq->body.data.da_hook;
			m = ngq->body.data.da_m;
			meta = ngq->body.data.da_meta;
			RETURN_QBLK(ngq);
			NG_SEND_DATAQ(error, hook, m, meta);
			ng_unref_hook(hook);
			break;
		case NGQF_MESG:
			node = ngq->body.msg.msg_node;
			msg = ngq->body.msg.msg_msg;
			retaddr = ngq->body.msg.msg_retaddr;
			hook = ngq->body.msg.msg_lasthook;
			RETURN_QBLK(ngq);
			if (hook) {
				if ((hook->refs == 1)
		    		|| (hook->flags & HK_INVALID) != 0) {
				/* If the hook only has one ref left
					then we can't use it */
					ng_unref_hook(hook);
					hook = NULL;
				} else {
					ng_unref_hook(hook);
				}
			}
			/* similarly, if the node is a zombie.. */
			if (node->flags & NG_INVALID) {
				FREE(msg, M_NETGRAPH);
			} else {
				CALL_MSG_HANDLER(error, node, msg,
						 retaddr, NULL, hook);
			}
			ng_unref(node);
			if (retaddr)
				FREE(retaddr, M_NETGRAPH);
			break;
		default:
			RETURN_QBLK(ngq);
		}
	}
}


OpenPOWER on IntegriCloud