File: kernel_pfkeyv2.c

package info (click to toggle)
libreswan 5.2-2.3
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 81,644 kB
  • sloc: ansic: 129,988; sh: 32,018; xml: 20,646; python: 10,303; makefile: 3,022; javascript: 1,506; sed: 574; yacc: 511; perl: 264; awk: 52
file content (1842 lines) | stat: -rw-r--r-- 52,549 bytes parent folder | download | duplicates (2)
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
/* Interface to the PF_KEY v2 IPsec mechanism, for Libreswan
 *
 * Copyright (C)  2022  Andrew Cagney
 *
 * 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.  See <https://www.gnu.org/licenses/gpl2.txt>.
 *
 * 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.
 */

#include <errno.h>
#include <unistd.h>

#include <fcntl.h>
#include <sys/types.h>

#include "lsw_socket.h"

#include "ip_info.h"
#include "ip_encap.h"
#include "chunk.h"
#include "hunk.h"
#include "ike_alg_integ.h"	/* for ike_alg_integ_none; */

#include "kernel.h"
#include "kernel_alg.h"
#include "kernel_sadb.h"
#include "kernel_policy.h"
#include "log.h"
#include "rnd.h"
#include "initiate.h"
#include "acquire.h"
#include "server.h"		/* for add_fd_read_listener() */
#include "ipsec_interface.h"
#include "kernel_ipsec_interface.h"

static pid_t pfkeyv2_pid;
static uint32_t pfkeyv2_seq;
static int pfkeyv2_fd;

static void pfkeyv2_process_msg(int fd, void *arg, struct logger *logger);

#define SIZEOF_SADB_ADDRESS (sizeof(struct sadb_address) + sizeof(ip_sockaddr))
#define SIZEOF_SADB_BASE sizeof(struct sadb_msg)
#define SIZEOF_SADB_IDENT sizeof(struct sadb_ident)
#define SIZEOF_SADB_KEY (sizeof(struct sadb_key) +  1024 / 8 /*key*/)
#define SIZEOF_SADB_LIFETIME sizeof(struct sadb_lifetime)
#define SIZEOF_SADB_SA sizeof(struct sadb_sa)
#define SIZEOF_SADB_SENS sizeof(struct sadb_sens)
#define SIZEOF_SADB_SPIRANGE sizeof(struct sadb_spirange)
#define SIZEOF_SADB_X_POLICY (sizeof(struct sadb_x_policy) + SIZEOF_SADB_X_IPSECREQUEST * 2)
#define SIZEOF_SADB_X_SA2 sizeof(struct sadb_x_sa2)
#define SIZEOF_SADB_X_IPSECREQUEST (sizeof(struct sadb_x_ipsecrequest) + SIZEOF_SADB_ADDRESS * 2)
#define SIZEOF_SADB_X_SA_REPLAY sizeof(struct sadb_x_sa_replay) /* FreeBSD */
#define SIZEOF_SADB_PROTOCOL (sizeof(struct sadb_protocol)) /* OpenBSD */
#define SIZEOF_SADB_X_UDPENCAP (sizeof(struct sadb_x_udpencap)) /* OpenBSD */
#define SIZEOF_SADB_X_IFACE (sizeof(struct sadb_x_iface)) /* OpenBSD */

struct outbuf {
	const char *what;
	chunk_t buf;
	unsigned seq;
	const struct logger *logger;
	struct sadb_msg *base;
	/* cursor */
	void *ptr;
	size_t len;
};

static void ldbg_outbuf(struct verbose verbose, struct outbuf *msg)
{
	vdbg("msg: %p + %zu = %p + %zu = %p",
	     msg->buf.ptr, (msg->ptr - (void*)msg->buf.ptr),
	     msg->ptr, msg->len,
	     (msg->ptr + msg->len));
	vassert((msg->ptr + msg->len) == (msg->buf.ptr + msg->buf.len));
}

static size_t msg_len(const void *start, struct outbuf *msg)
{
	return (msg->ptr - start) / sizeof (uint64_t);
}

/*
 * Build and emit structures.
 *
 * - the *_INIT macros exist because remembering to correctly
 *   initializing .TYPE##_len is a pain
 *
 * - the *_INIT expand to the structures contents, and not the the
 *   brace wrapped structure because it ends up expanding MACRO({ a,
 *   b, c}) and that confuses the compiler, sigh.
 *
 * - it's assumed that, at all times, the chunk has correct memory
 *   alignment; that holds for pfkeyV2
 */

#define SADB_INIT(TYPE, ...)						\
	.TYPE##_len = sizeof(struct TYPE) / sizeof(uint64_t),		\
		##__VA_ARGS__						\

#define SADB_EXT_INIT(TYPE, EXTTYPE, ...)				\
	SADB_INIT(TYPE, .TYPE##_exttype = EXTTYPE, ##__VA_ARGS__)

#define put_sadb_struct(MSG, TYPE, ...)					\
	({								\
		struct TYPE ps_thing_ = { __VA_ARGS__ };		\
		struct outbuf *ps_req_ = MSG;				\
		struct TYPE *ps_ptr_ = hunk_put_thing(ps_req_, ps_thing_); \
		if (verbose.rc_flags != 0) {				\
			verbose("put %s ...", ps_req_->what);		\
			verbose.level++;				\
			llog_##TYPE(verbose, ps_req_->base, ps_ptr_);	\
			verbose.level--;				\
		}							\
		ps_ptr_;						\
	})

#define put_sadb(MSG, TYPE, ...)					\
	put_sadb_struct(MSG, TYPE, SADB_INIT(TYPE, __VA_ARGS__))

#define padup_sadb(MSG, NAME)						\
	({								\
		struct outbuf *req_ = MSG; /* eval once */		\
		/* ASSUME TYPE and VARIABLE have same name! */		\
		struct sadb_##NAME *ext_ = NAME; /* eval once */	\
		/* pad to 64-bit boundary */				\
		unsigned pad_ = req_->len % sizeof(uint64_t);		\
		req_->ptr += pad_;					\
		req_->len -= pad_;					\
		/* XXX: pexpect ..._len == sizeof(TYPE) */		\
		ext_->sadb_##NAME##_len = msg_len(ext_, req_);		\
		if (verbose.rc_flags != 0) {				\
			verbose("padup %s ...", req_->what);		\
			verbose.level++;				\
			llog_sadb_##NAME(verbose, req_->base, NAME);	\
			verbose.level--;				\
		}							\
	})

#define put_sadb_ext(REQ, TYPE, EXTTYPE, ...)				\
	put_sadb_struct(REQ, TYPE, SADB_EXT_INIT(TYPE, EXTTYPE, __VA_ARGS__))

struct pending {
	chunk_t msg;
	struct list_entry entry;
};

static size_t jam_pending(struct jambuf *buf, const struct pending *pending)
{
	return jam(buf, "%p", pending);
}

LIST_INFO(pending, entry, pending_info, jam_pending);

static struct list_head pending_queue = INIT_LIST_HEAD(&pending_queue, &pending_info);

struct inbuf {
	const char *what;
	shunk_t buf;
	shunk_t msg_cursor;
	shunk_t base_cursor;
	const struct sadb_msg *base;
	uint8_t buffer[65536];
};

static void queue_msg(const struct inbuf *msg)
{
	struct pending *pending = alloc_thing(struct pending, __func__);
	/* assume MSG still points at the entire buffer */
	pending->msg = clone_hunk(msg->buf, __func__);
	init_list_entry(&pending_info, pending, &pending->entry);
	insert_list_entry(&pending_queue, &pending->entry);
}

static bool recv_msg(struct inbuf *msg, const char *what, struct verbose verbose)
{
	*msg = (struct inbuf) { .what = what, };
	ssize_t s = recv(pfkeyv2_fd, msg->buffer, sizeof(msg->buffer), /*flags*/0);
	if (s < 0) {
		llog_errno(RC_LOG, verbose.logger, errno,
			   "receiving %s response: ", what);
		return false;
	}

	verbose("read %zd bytes for %s", s, msg->what);
	verbose.level++;

	msg->buf = shunk2(msg->buffer, s);
	llog_sadb(verbose, msg->buf);

	return true;
}

static bool msg_recv(struct inbuf *msg, const char *what, const struct sadb_msg *req,
		     struct verbose verbose)
{
	verbose("in %s() receiving message for %s", __func__, what);
	verbose.level++;

	while (true) {
		if (!recv_msg(msg, what, verbose)) {
			return false;
		}

		msg->msg_cursor = shunk2(msg->buf.ptr, msg->buf.len);
		msg->base = get_sadb_msg(&msg->msg_cursor, &msg->base_cursor, verbose);
		if (msg->base == NULL) {
			llog_pexpect(verbose.logger, HERE, "no base");
			return false;
		}

		if (msg->base->sadb_msg_seq == 0) {
			/* flip verbose to RC_LOG */
			struct verbose log = {
				.logger = verbose.logger,
				.rc_flags = RC_LOG,
			};
			llog(RC_LOG, log.logger,
			     "ignoring message with sequence number 0:");
			log.level++;
			llog_sadb(log, msg->buf);
			/* XXX: need to trigger event */
			queue_msg(msg);
			continue;
		}

		if (msg->base->sadb_msg_seq != req->sadb_msg_seq) {
			/* flip verbose to rc_log */
			struct verbose log = {
				.logger = verbose.logger,
				.rc_flags = RC_LOG,
			};
			llog(RC_LOG, log.logger,
			     "ignoring message with incorrect sequence number %u, expecting %u:",
			     msg->base->sadb_msg_seq, req->sadb_msg_seq);
			log.level++;
			llog_sadb(log, msg->buf);
			/* XXX: need to trigger event */
			queue_msg(msg);
			continue;
		}

		/*
		 * XXX: update when SA expired?
		 */
		if (msg->base->sadb_msg_errno == ENOENT) {
			llog_pexpect(verbose.logger, HERE, "ENOENT returned");
			return true;
		}

		if (msg->base->sadb_msg_errno != 0) {
			llog_errno(RC_LOG, verbose.logger, msg->base->sadb_msg_errno, "bad response: ");
			return false;
		}

		return true;
	}
}

static bool msg_sendrecv(struct outbuf *req, struct inbuf *recv,
			 struct verbose verbose)
{
	verbose("in %s()", __func__);
	verbose.level++;

	struct sadb_msg *msg = req->base;
	padup_sadb(req, msg);
	llog_sadb(verbose, HUNK_AS_SHUNK(req->buf));

	ssize_t s = send(pfkeyv2_fd, req->buf.ptr, req->ptr - (void*)req->buf.ptr, 0);
	if (s < 0) {
		fatal_errno(PLUTO_EXIT_KERNEL_FAIL, verbose.logger, errno,
			    "sending %s", req->what);
		return false;
	}

	return msg_recv(recv, req->what, msg, verbose);
}

static struct sadb_msg *put_sadb_base(struct outbuf *msg,
				      enum sadb_type type,
				      enum sadb_satype satype,
				      unsigned seq,
				      struct verbose verbose)
{
	verbose("%s", __func__);
	verbose.level++;

	struct sadb_msg *base = put_sadb(msg, sadb_msg,
					 .sadb_msg_version = PF_KEY_V2,
					 .sadb_msg_type = type,
					 .sadb_msg_errno = 0,
					 .sadb_msg_satype = satype,
					 .sadb_msg_seq = seq,
					 .sadb_msg_pid = pfkeyv2_pid);
	return base;
}

static struct sadb_sa *put_sadb_sa(struct outbuf *msg,
				   ipsec_spi_t spi,
				   enum sadb_satype satype,
				   enum sadb_sastate sastate,
				   unsigned replay_window,
				   unsigned saflags,
				   const struct integ_desc *integ,
				   const struct encrypt_desc *encrypt,
				   const struct ipcomp_desc *ipcomp,
				   struct verbose verbose)
{
	verbose("in %s() ...", __func__);
	verbose.level++;

	unsigned aalg = (integ == &ike_alg_integ_none && encrypt_desc_is_aead(encrypt) ? SADB_AALG_NONE :
			 integ != NULL ? integ->integ_sadb_aalg_id :
			 0);

	unsigned ealg = (encrypt != NULL ? encrypt->encrypt_sadb_ealg_id :
			 /* XXX: NetBSD treats IPCOMP like ENCRYPT */
			 ipcomp != NULL ? ipcomp->ipcomp_sadb_calg_id : 0);

	struct sadb_sa tmp = {
		SADB_EXT_INIT(sadb_sa, SADB_EXT_SA,
			      .sadb_sa_replay = replay_window,
			      .sadb_sa_state = sastate,
			      .sadb_sa_flags = saflags,
			      .sadb_sa_spi = spi,
			      .sadb_sa_auth = aalg,
			      .sadb_sa_encrypt = ealg),
	};
	struct sadb_sa *sa = hunk_put_thing(msg, tmp);
	llog_sadb_sa(verbose, msg->base, satype, sa);
	return sa;
}

static struct sockaddr *put_address_sockaddr(struct outbuf *msg,
					     const ip_address addr)
{
	ip_sockaddr sa = sockaddr_from_address(addr);
	return hunk_put(msg, &sa.sa.sa, sa.len);
}

/*
 * XXX: OpenBSD uses address+mask, instead of address/prefixlen;
 * protocol and prefix length were dropped from the structure.
 *
 * Ulgh!
 */
#ifdef sadb_address_prefixlen /* NetBSD FreeBSD */
static struct sadb_address *put_sadb_selector(struct outbuf *msg,
					      enum sadb_exttype srcdst_exttype,
					      const ip_selector selector,
					      struct verbose verbose)
{
	const struct ip_protocol *protocol = selector_protocol(selector);
	enum ipsec_proto proto = (protocol == &ip_protocol_all ? IPSEC_PROTO_ANY/*255*/ :
				  protocol != NULL ? protocol->ipproto :
				  pexpect(0));
	ip_address prefix = selector_prefix(selector);
	unsigned prefix_len = selector_prefix_len(selector);
	struct sadb_address *address =
		put_sadb_ext(msg, sadb_address, srcdst_exttype,
			     .sadb_address_proto = proto,
			     .sadb_address_prefixlen = prefix_len);
	put_address_sockaddr(msg, prefix);
	padup_sadb(msg, address);
	return address;
}
#endif

static struct sadb_address *put_sadb_address(struct outbuf *msg,
					     enum sadb_exttype srcdst_exttype,
					     const ip_address addr,
					     struct verbose verbose)
{
#ifdef sadb_address_prefixlen /* NetBSD FreeBSD */
	const struct ip_info *afi = address_info(addr);
	struct sadb_address *address =
		put_sadb_ext(msg, sadb_address, srcdst_exttype,
			     .sadb_address_proto = IPSEC_PROTO_ANY/*255*/,
			     .sadb_address_prefixlen = afi->mask_cnt);
#else /* OpenBSD */
	/*
	 * XXX: OpenBSD uses address+mask, instead of
	 * address/prefixlen; protocol and prefix length were dropped
	 * from the structure.
	 *
	 * Ulgh!
	 */
	struct sadb_address *address =
		put_sadb_ext(msg, sadb_address, srcdst_exttype);
#endif
	put_address_sockaddr(msg, addr);
	padup_sadb(msg, address);
	return address;
}

/*
 * XXX: the BSDs embed the host's port (when UDP) in the SA/SADB host
 * address.
 */

#if 0
static struct sockaddr *put_endpoint_sockaddr(struct outbuf *msg,
					      const ip_endpoint endpoint)
{
}

static struct sadb_address *put_sadb_endpoint(struct outbuf *msg,
					      enum sadb_exttype srcdst_exttype,
					      const ip_endpoint endpoint)
{
	pexpect(srcdst_exttype == SADB_EXT_ADDRESS_SRC ||
		srcdst_exttype == SADB_EXT_ADDRESS_DST);
	const struct ip_info *afi = endpoint_info(endpoint);
#ifdef sadb_address_prefixlen
	struct sadb_address *address =
		put_sadb_ext(msg, sadb_address, srcdst_exttype,
			     .sadb_address_proto = IPSEC_PROTO_ANY/*255*/,
			     .sadb_address_prefixlen = afi->mask_cnt);
#else
	/*
	 * XXX: OpenBSD uses address+mask, instead of
	 * address/prefixlen; protocol and prefix length were dropped
	 * from the structure.
	 *
	 * Ulgh!
	 */
	struct sadb_address *address =
		put_sadb_ext(msg, sadb_address, srcdst_exttype);
#endif
	put_endpoint_sockaddr(msg, endpoint);
	padup_sadb(msg, address);
	return address;
}
#endif

static struct sadb_key *put_sadb_key(struct outbuf *msg,
				     enum sadb_exttype key_alg,
				     shunk_t keyval,
				     struct verbose verbose)
{
	verbose("in %s() ...", __func__);
	verbose.level++;

	struct sadb_key *key =
		put_sadb_ext(msg, sadb_key, key_alg,
			     .sadb_key_bits = keyval.len * BITS_IN_BYTE);
	if (hunk_put_hunk(msg, keyval) == NULL) {
		llog_passert(verbose.logger, HERE, "bad key(E)");
	}
	padup_sadb(msg, key);
	return key;
}

static struct sadb_spirange *put_sadb_spirange(struct outbuf *msg, uintmax_t min, uintmax_t max,
					       struct verbose verbose)
{
	verbose("in %s() ...", __func__);
	verbose.level++;

	struct sadb_spirange *spirange =
		put_sadb_ext(msg, sadb_spirange, SADB_EXT_SPIRANGE,
			     .sadb_spirange_min = min,
			     .sadb_spirange_max = max);
	return spirange;
}

#ifdef SADB_X_EXT_SA2 /* FreeBSD NetBSD */
static struct sadb_x_sa2 *put_sadb_x_sa2(struct outbuf *msg,
					 enum ipsec_mode ipsec_mode,
					 reqid_t reqid,
					 struct verbose verbose)
{
	verbose("in %s() ...", __func__);
	verbose.level++;

	struct sadb_x_sa2 *x_sa2 =
		put_sadb_ext(msg, sadb_x_sa2, SADB_X_EXT_SA2,
			     .sadb_x_sa2_mode = ipsec_mode,
			     .sadb_x_sa2_sequence = 0,/*SPD sequence?*/
			     .sadb_x_sa2_reqid = reqid);
	return x_sa2;
}
#endif

static void msg_base(struct verbose verbose, struct outbuf *msg, const char *what,
		     chunk_t buf, enum sadb_type type,
		     enum sadb_satype satype)
{
	*msg = (struct outbuf) {
		.buf = buf,
		.ptr = buf.ptr,
		.len = buf.len,
		.what = what,
		.seq = ++pfkeyv2_seq,
		.logger = verbose.logger,
	};
	ldbg_outbuf(verbose, msg);
	msg->base = put_sadb_base(msg, type, satype, msg->seq, verbose);
}

static bool sadb_base_sendrecv(struct inbuf *resp,
			      enum sadb_type type,
			      enum sadb_satype satype,
			      struct verbose verbose)
{
	verbose("in %s() ...", __func__);
	verbose.level++;

	uint8_t reqbuf[SIZEOF_SADB_BASE];
	struct outbuf req;
	msg_base(verbose, &req, __func__,
		 chunk2(reqbuf, sizeof(reqbuf)),
		 type, satype);
	return msg_sendrecv(&req, resp, verbose);
}

static enum sadb_satype sadb_satype_from_protocol(const struct ip_protocol *proto)
{
	return (proto == &ip_protocol_esp ? SADB_SATYPE_ESP :
		proto == &ip_protocol_ah ? SADB_SATYPE_AH :
		proto == &ip_protocol_ipcomp ? SADB_X_SATYPE_IPCOMP :
		pexpect(0));
}

static bool register_alg(const struct sadb_msg *b,
			 shunk_t *msgext, const struct ike_alg_type *type,
			 struct verbose verbose)
{
	verbose("in %s() ...", __func__);
	verbose.level++;

	const struct sadb_supported *supported =
		hunk_get_thing(msgext, const struct sadb_supported);
	if (supported == NULL) {
		llog_pexpect(verbose.logger, HERE, "bad ext");
		return false;
	}

	llog_sadb_supported(verbose, b, supported);
	verbose.level++;

	unsigned nr_algs = ((supported->sadb_supported_len * sizeof(uint64_t) -
			     sizeof(struct sadb_supported)) / sizeof(struct sadb_alg));
	for (unsigned n = 0; n < nr_algs; n++) {

		const struct sadb_alg *alg =
			hunk_get_thing(msgext, const struct sadb_alg);
		if (alg == NULL) {
			llog_pexpect(verbose.logger, HERE, "bad ext");
			return false;
		}

		enum sadb_exttype exttype = supported->sadb_supported_exttype;
		llog_sadb_alg(verbose, b, exttype, alg);

		const struct ike_alg *ike_alg = ike_alg_by_sadb_alg_id(type, alg->sadb_alg_id);
		if (ike_alg != NULL) {
			kernel_alg_add(ike_alg);
		} else {
			vdbg("%s algorithm %d not recognized",
			     ike_alg_type_name(type),
			     alg->sadb_alg_id);
		}
	}
	return true;
}

static void register_satype(const struct ip_protocol *protocol, struct verbose verbose)
{
	verbose("in %s() sending %s request", __func__, protocol->name);
	verbose.level++;

	struct inbuf resp;
	if (!sadb_base_sendrecv(&resp, SADB_REGISTER,
				sadb_satype_from_protocol(protocol),
				verbose)) {
		return;
	}

	while (resp.base_cursor.len > 0) {

		shunk_t msgext;
		const struct sadb_ext *ext =
			get_sadb_ext(&resp.base_cursor, &msgext, verbose);
		if (ext == NULL) {
			llog_pexpect(verbose.logger, HERE, "bad ext");
			return;
		}

		enum sadb_exttype exttype = ext->sadb_ext_type;
		switch (exttype) {
		case SADB_EXT_SUPPORTED_AUTH:
			if (!register_alg(resp.base, &msgext, &ike_alg_integ, verbose)) {
				/* already logged */
				return;
			}
			break;
		case SADB_EXT_SUPPORTED_ENCRYPT:
			if (!register_alg(resp.base, &msgext, &ike_alg_encrypt, verbose)) {
				/* already logged */
				return;
			}
			break;
#ifdef SADB_X_EXT_SUPPORTED_COMP /* OpenBSD */
		case SADB_X_EXT_SUPPORTED_COMP:
			/*
			 * Handle COMP algorithms:
			 *
			 * + the original RFC 2367 makes no reference
			 * to compression, if it had been included it
			 * would have looked something like this.
			 *
			 * However, it's worth noting:
			 *
			 * + there's really only ever been one
			 * compression algorithm
			 *
			 * + using compression with IPsec has fallen
			 * out of favour (the benefit is marginal;
			 * it's not well tested on either Linux or
			 * [*]BSD)
			 */
			if (!register_alg(resp.base, &msgext, &ike_alg_ipcomp, verbose)) {
				/* already logged */
				return;
			}
			break;
#endif
		default:
			llog_pexpect(verbose.logger, HERE, "unknown ext");
			break;
		}
	}
}

static void kernel_pfkeyv2_init(struct logger *logger)
{
	VERBOSE_DBGP(DBG_BASE, logger, "initializing PFKEY V2");

	pfkeyv2_pid = getpid();

	/* initialize everything */
	pfkeyv2_fd = cloexec_socket(PF_KEY, SOCK_RAW, PF_KEY_V2);
	if (pfkeyv2_fd < 0) {
		fatal_errno(PLUTO_EXIT_KERNEL_FAIL, logger, errno,
			    "opening PF_KEY_V2 socket failed");
	}
	/* server.c will close this */
	add_fd_read_listener(pfkeyv2_fd, "pfkey v2 messages",
			     pfkeyv2_process_msg, NULL);
	ldbg(logger, "pfkey opened on %d with CLOEXEC", pfkeyv2_fd);

	/* register everything */

	register_satype(&ip_protocol_ah, verbose);
	register_satype(&ip_protocol_esp, verbose);
	register_satype(&ip_protocol_ipcomp, verbose);
}

static void kernel_pfkeyv2_flush(struct logger *logger)
{
	VERBOSE_DBGP(DBG_BASE, logger, "flushing");

	struct inbuf resp;
	sadb_base_sendrecv(&resp, SADB_FLUSH, SADB_SATYPE_UNSPEC, verbose);
#ifdef SADB_X_SPDFLUSH /* FreeBSD NetBSD */
	sadb_base_sendrecv(&resp, SADB_X_SPDFLUSH, SADB_SATYPE_UNSPEC, verbose);
#else /* OpenBSD */
	vlog("OpenBSD SADB_FLUSH does everything; SADB_X_SPDFLUSH not needed");
#endif
}

static void kernel_pfkeyv2_poke_holes(struct logger *logger)
{
	ldbg(logger, "does PFKEY need to poke holes in its kernel policies?");
}

static void kernel_pfkeyv2_plug_holes(struct logger *logger)
{
	ldbg(logger, "does PFKEY need to poke holes in its kernel policies?");
}

static ipsec_spi_t pfkeyv2_get_ipsec_spi(ipsec_spi_t avoid UNUSED,
					 const ip_address *src,
					 const ip_address *dst,
					 const struct ip_protocol *protocol,
					 reqid_t reqid,
					 uintmax_t min, uintmax_t max,
					 const char *story UNUSED,	/* often SAID string */
					 struct logger *logger)
{
	VERBOSE_DBGP(DBG_BASE, logger, "reqid=%d ...", reqid);

	/* GETSPI */
	/* send: <base, address, SPI range> */
	/* recv: <base, SA(*), address(SD)> */

	uint8_t reqbuf[SIZEOF_SADB_BASE +
#ifdef SADB_X_EXT_SA2 /* FreeBSD NetBSD */
		       SIZEOF_SADB_X_SA2 +
#endif
		       SIZEOF_SADB_ADDRESS * 2 +
		       SIZEOF_SADB_SPIRANGE];
	struct outbuf req;
	msg_base(verbose, &req, __func__,
		 chunk2(reqbuf, sizeof(reqbuf)),
		 SADB_GETSPI,
		 sadb_satype_from_protocol(protocol));

	/*
	 * XXX: the original PF_KEY_V2 RFC didn't leave space to
	 * specify REQID and/or transport mode (tunnel was assumed).
	 *
	 * SADB_X_SA2 provides a way to specify that (it's optional,
	 * but since the REQID is always specified, it might as well
	 * be included).
	 */

#ifdef SADB_X_EXT_SA2 /* FreeBSD NetBSD */
	put_sadb_x_sa2(&req, IPSEC_MODE_ANY, reqid, verbose);
#endif

	/* (tunnel_mode ? ipsec_mode_tunnel : ipsec_mode_transport), */

	put_sadb_address(&req, SADB_EXT_ADDRESS_SRC, *src, verbose);
	put_sadb_address(&req, SADB_EXT_ADDRESS_DST, *dst, verbose);
	put_sadb_spirange(&req, min, max, verbose);

	struct inbuf resp;
	if (!msg_sendrecv(&req, &resp, verbose)) {
		return 0;
	}

	ipsec_spi_t spi = 0;
	while (resp.base_cursor.len > 0) {

		shunk_t msgext;
		const struct sadb_ext *ext =
			get_sadb_ext(&resp.base_cursor, &msgext, verbose);
		if (msgext.ptr == NULL) {
			llog_pexpect(verbose.logger, HERE, "bad ext");
			return 0;
		}

		enum sadb_exttype exttype = ext->sadb_ext_type;
		switch (exttype) {
		case SADB_EXT_SA:
		{
			const struct sadb_sa *sa =
				hunk_get_thing(&msgext, const struct sadb_sa);
			if (sa == NULL) {
				llog_pexpect(verbose.logger, HERE, "getting sa");
				return 0;
			}
			llog_sadb_sa(verbose, resp.base, req.base->sadb_msg_satype, sa);
			spi = sa->sadb_sa_spi;
			break;
		}
		case SADB_EXT_ADDRESS_SRC:
		case SADB_EXT_ADDRESS_DST:
			/* ignore these */
			break;
		default:
			llog_pexpect(logger, HERE, "bad ext");
			break;
		}
	}
	return spi;
}

static bool pfkeyv2_del_ipsec_spi(ipsec_spi_t spi,
				  const struct ip_protocol *protocol,
				  const ip_address *src_address,
				  const ip_address *dst_address,
				  const char *story UNUSED,
				  struct logger *logger)
{
	VERBOSE_DBGP(DBG_BASE, logger, "...");
	/* DEL */
	/* send: <base, SA(*), address(SD)> */
	/* recv: <base, SA(*), address(SD)> */

	/* base */

	uint8_t reqbuf[SIZEOF_SADB_BASE +
		       SIZEOF_SADB_SA +
		       SIZEOF_SADB_ADDRESS * 2];
	struct outbuf req;
	msg_base(verbose, &req, __func__,
		 chunk2(reqbuf, sizeof(reqbuf)),
		 SADB_DELETE,
		 sadb_satype_from_protocol(protocol));

	/* SA(*) */

	put_sadb_sa(&req, spi, /*satype*/0, /*sastate*/0, /*replay*/0, /*saflags*/0,
		    /*integ*/NULL, /*encrypt*/NULL, /*ipcomp*/NULL, verbose);

	/* address(SD) */

	put_sadb_address(&req, SADB_EXT_ADDRESS_SRC, *src_address, verbose);
	put_sadb_address(&req, SADB_EXT_ADDRESS_DST, *dst_address, verbose);

	struct inbuf recv;
	if (!msg_sendrecv(&req, &recv, verbose)) {
		llog_pexpect(logger, HERE, "bad");
		return false;
	}

	return true;
}

static bool pfkeyv2_add_sa(const struct kernel_state *k,
			   bool replace,
			   struct logger *logger)
{
	VERBOSE_DBGP(DBG_BASE, logger, "...");

	/* UPDATE <base, SA, (lifetime(HSC),) address(SD),
	   (address(P),) key(AE), (identity(SD),) (sensitivity)> */
	/* ADD <base, SA, (lifetime(HS),) address(SD), (address(P),)
	   key(AE), (identity(SD),) (sensitivity)> */

	enum sadb_type type = (replace ? SADB_UPDATE : SADB_ADD);

	uint8_t reqbuf[SIZEOF_SADB_BASE +
		       SIZEOF_SADB_SA +
		       SIZEOF_SADB_LIFETIME * 3 +
		       SIZEOF_SADB_ADDRESS * 3 +
		       SIZEOF_SADB_KEY * 2 +
		       SIZEOF_SADB_IDENT * 2 +
#ifdef SADB_X_EXT_SA_REPLAY /* FreeBSD */
		       SIZEOF_SADB_X_SA_REPLAY +
#endif
#ifdef SADB_X_EXT_UDPENCAP /* OpenBSD */
		       SIZEOF_SADB_X_UDPENCAP +
#endif
#ifdef SADB_X_EXT_IFACE
		       SIZEOF_SADB_X_IFACE +
#endif
		       SIZEOF_SADB_SENS +
		       0];
	struct outbuf req;
	msg_base(verbose, &req, __func__,
		 chunk2(reqbuf, sizeof(reqbuf)),
		 type,
		 sadb_satype_from_protocol(k->proto));

	/* SA */

	unsigned saflags = 0;
#ifdef SADB_X_SAFLAGS_ESN /* FreeBSD OpenBSD */
	/*
	 * Both FreeBSD and OpenBSD support the ESN flag.
	 */
	if (k->esn) {
		saflags |= SADB_X_SAFLAGS_ESN;
	}
#endif
#ifdef SADB_X_SAFLAGS_TUNNEL /* OpenBSD */
	/*
	 * FreeBSD and NetBSD use a field in SADB_SA2 to convey this
	 * information.
	 *
	 * OpenBSD instead uses this bit.
	 */
	if (k->mode == KERNEL_MODE_TUNNEL) {
		saflags |= SADB_X_SAFLAGS_TUNNEL;
	}
#endif
#ifdef SADB_X_EXT_UDPENCAP /* OpenBSD */
	/*
	 * NetBSD and FreeBSD, like Linux, call setsockopt
	 * UDP_ENCAP_ESPINUDP on the IKE UDP socket when it is first
	 * opened/accepted.
	 *
	 * -> this means that the socket is always in UDPENCAP mode;
	 *    presumably the non-ESP marker doesn't change (always
	 *    stripped)
	 *
	 * OpenBSD instead uses the UDPENCAP bit when adding the SA to
	 * the kernel.
	 *
	 * -> this means that the kernel only finds out that the
	 *    socket is UDPENCAP when the SA is added; does this mean
	 *    that non-ESP marker handling changes?
	 */
	if (k->encap_type == &ip_encap_esp_in_udp) {
		saflags |= SADB_X_SAFLAGS_UDPENCAP;
	}
#endif

	/*
	 * Determine the size of the replay window:
	 *
	 * -> the field kernel_state .replay_window is the size of the
	 *    replay window in packets
	 *
	 * -> PF KEY v2's .sadb_sa_replay is the number of bytes
	 *    needed to store the register window bit-mask (one bit
	 *    per-packet)
	 *
	 *    FreeBSD's setkey describes it as "one eighth of the
	 *    anti-replay window size in packets".
	 *
	 * Hence the strange conversion below.
	 *
	 * What about a replay window larger than UINT8_MAX*8 (~2k
	 * packets)?
	 *
	 * FreeBSD:
	 *
	 *   Supports both the original .sadb_sa_replay and the
	 *   SADB_X_EXT_SA_REPLAY extension.  When .replay_window
	 *   exceeds UINT8_MAX*8, .sadb_sa_replay is set to UINT8_MAX
	 *   and a SADB_X_EXT_SA_REPLAY payload is added containing
	 *   .replay_window (in packets not bytes).
	 *
	 * NetBSD:
	 *
	 *   Supports the original .sadb_sa_replay.
	 *
	 * OpenBSD:
	 *
	 *   Supports the original .sadb_sa_replay.  The kernel
	 *   enforces an additional hardwired limit of 64 (*8).  Also,
	 *   on the way in, IKED hardwires the value to 65(*8),
	 *   IPSECCTL can't set the value at all, but ISAKMPD does
	 *   have a parameter.
	 *
	 *   Note: OpenBSD defines SADB_X_EXT_REPLAY but it has
	 *   nothing to do with this code.  It seems to be used by the
	 *   kernel to return the number of replays that were
	 *   detected.
	 */
	unsigned bytes_for_replay_window = BYTES_FOR_BITS(k->replay_window);
	unsigned saturated_bytes_for_replay_window =
		(bytes_for_replay_window > UINT8_MAX ? UINT8_MAX : bytes_for_replay_window);

	put_sadb_sa(&req, k->spi,
		    req.base->sadb_msg_satype,
		    SADB_SASTATE_MATURE,
		    /*sadb_sa_replay*/saturated_bytes_for_replay_window,
		    saflags,
		    k->integ, k->encrypt, k->ipcomp,
		    verbose);

	/*
	 * X_SA2
	 *
	 * This is needed to specify the stuff that should have been
	 * included in SA, notably tunnel vs transport and reqid
	 *
	 * Tunnel only applies to the inner most encapsulation.
	 * Right?  Why?  Which means it applies to the packet
	 * interface.
	 *
	 * XXX: why not just set "tunnel" on the inner-most kernel_sa?
	 */

#ifdef SADB_X_EXT_SA2 /* FreeBSD NetBSD */
	put_sadb_x_sa2(&req, IPSEC_MODE_ANY, k->reqid, verbose);
#endif

	/*
	 * address(SD)
	 *
	 * -> OpenBSD passes the UDP encapsulated destination port
	 *    using SADB_X_EXT_UDPENCAP; there doesn't seem to be a
	 *    way to pass the source port.
	 *
	 * -> Linux passes the UDP encapsulated source and destination
	 *    ports using using XFRMA_ENCAP.
	 *
	 * -> NetBSD, FreeBSD, and OpenBSD(?) can handle the address
	 *    including the port.
	 */
	put_sadb_address(&req, SADB_EXT_ADDRESS_SRC, k->src.address, verbose);
	put_sadb_address(&req, SADB_EXT_ADDRESS_DST, k->dst.address, verbose);

	/* (address(P)) */

	/* key(AE[C]) (AUTH/INTEG/ENCRYPT/IPCOMP) */

	if (k->integ_key.len > 0) {
		put_sadb_key(&req, SADB_EXT_KEY_AUTH, k->integ_key, verbose);
	}
	if (k->encrypt_key.len > 0) {
		put_sadb_key(&req, SADB_EXT_KEY_ENCRYPT, k->encrypt_key, verbose);
	}

	/* (lifetime(HSC)) */

	put_sadb_ext(&req, sadb_lifetime, SADB_EXT_LIFETIME_HARD,
		     .sadb_lifetime_addtime = deltasecs(k->sa_lifetime));
	put_sadb_ext(&req, sadb_lifetime, SADB_EXT_LIFETIME_SOFT,
		     .sadb_lifetime_addtime =  deltasecs(k->sa_lifetime));

	/* (identity(SD)) */

	/* (sensitivity) */

	/* replay (extended mix) */

#ifdef SADB_X_EXT_SA_REPLAY /* FreeBSD */
	/*
	 * Per-above, only emit this when .sadb_sa_replay isn't big
	 * enough (it's pretty big at 2k, Linux caps things to 4k).
	 *
	 * Unlike .sadb_sa_replay which is in bytes (8 packets per
	 * byte), .sadb_x_ext_sa_replay_replay is in packets - no
	 * conversion is required (FreeBSD's kernel converts the packet
	 * value back to bytes internally).
	 */
	if (bytes_for_replay_window > UINT8_MAX) {
		/* The -32 comes from FreeBSD!?! */
		pexpect(k->replay_window <= (UINT32_MAX - 32));
		put_sadb_ext(&req, sadb_x_sa_replay, sadb_x_ext_sa_replay,
			     .sadb_x_sa_replay_replay = k->replay_window);
	}
#endif

	/* udpencap (continued) */

#ifdef SADB_X_EXT_UDPENCAP /* OpenBSD */
	/*
	 * OpenBSD: This mechanism only provides a way to specify the
	 * destination port.  The source port is fixed at 4500 (or
	 * what ever is configured in the kernel).
	 *
	 * Linux's XFRMA_ENCAP includes both the source and
	 * destination port.
	 *
	 * FreeBSD and NetBSD do what?  It looks like they provide
	 * SADB_X_EXT_NAT_T_[SD]PORT and expect the SA/SPD host
	 * addresses to also include the port and protocol?
	 */
	if (k->encap_type == &ip_encap_esp_in_udp) {
		if (k->src.encap_port != 4500) {
			llog(RC_LOG, logger,
			     "SADB_X_EXT_UDPENCAP assumes the source port is 4500, not %d",
			     k->src.encap_port);
		}
		put_sadb_ext(&req, sadb_x_udpencap, sadb_x_ext_udpencap,
			     .sadb_x_udpencap_port = htons(k->dst.encap_port));
	}
#endif

#ifdef SADB_X_EXT_IFACE
	if (k->ipsec_interface != NULL) {
		unsigned ipsec_if_index = if_nametoindex(k->ipsec_interface->name);
		if (ipsec_if_index == 0) {
			llog_errno(RC_LOG, logger, errno,
				   "invalid ipsec-interface %s: ",
				   k->ipsec_interface->name);
		} else {
			enum ipsp_direction direction;
			switch (k->direction) {
			case DIRECTION_INBOUND: direction = ipsp_direction_in; break;
			case DIRECTION_OUTBOUND: direction = ipsp_direction_out; break;
			default:
				bad_case(k->direction);
			}
			put_sadb_ext(&req, sadb_x_iface, sadb_x_ext_iface,

				     .sadb_x_iface_unit = k->ipsec_interface->if_id,
				     .sadb_x_iface_direction = direction);
		}
	}
#endif

	/* UPDATE */
        /* <base, SA, (lifetime(HSC),) address(SD), (address(P),)
	   (identity(SD),) (sensitivity)> */
	/* ADD */
	/* <base, SA, (lifetime(HS),) address(SD), (identity(SD),)
	   (sensitivity)> */

	struct inbuf recv;
	if (!msg_sendrecv(&req, &recv, verbose)) {
		llog_pexpect(logger, HERE, "bad");
		return false;
	}

	return true;
}

static bool pfkeyv2_get_kernel_state(const struct kernel_state *k,
				     uint64_t *bytes,
				     uint64_t *add_time,
				     uint64_t *lastused UNUSED,
				     struct logger *logger)
{
	VERBOSE_DBGP(DBG_BASE, logger, "...");

	/* GET */
	/* <base, SA(*), address(SD)> */
	/* <base, SA, (lifetime(HSC),) address(SD), (address(P),) key(AE),
           (identity(SD),) (sensitivity)> */

	/* <base> */

	uint8_t reqbuf[SIZEOF_SADB_BASE +
		       SIZEOF_SADB_SA +
		       SIZEOF_SADB_ADDRESS * 2];
	struct outbuf req;
	msg_base(verbose, &req, __func__,
		 chunk2(reqbuf, sizeof(reqbuf)),
		 SADB_GET,
		 sadb_satype_from_protocol(k->proto));

	/* SA(*) */

	put_sadb_sa(&req, k->spi, /*satype*/0, /*sastate*/0, /*replay*/0, /*saflags*/0,
		    /*integ*/NULL, /*encrypt*/NULL, /*ipcomp*/NULL, verbose);

	/* address(SD) */

	put_sadb_address(&req, SADB_EXT_ADDRESS_SRC, k->src.address, verbose);
	put_sadb_address(&req, SADB_EXT_ADDRESS_DST, k->dst.address, verbose);

	struct inbuf resp;
	if (!msg_sendrecv(&req, &resp, verbose)) {
		llog_pexpect(logger, HERE, "bad");
		return false;
	}

	while (resp.base_cursor.len > 0) {

		shunk_t ext_cursor;
		const struct sadb_ext *ext =
			get_sadb_ext(&resp.base_cursor, &ext_cursor, verbose);
		if (ext_cursor.ptr == NULL) {
			llog_pexpect(verbose.logger, HERE, "bad ext");
			return false;
		}

		enum sadb_exttype exttype = ext->sadb_ext_type;
		switch (exttype) {
		case SADB_EXT_LIFETIME_CURRENT:
		{
			const struct sadb_lifetime *lifetime =
				hunk_get_thing(&ext_cursor, const struct sadb_lifetime);
			if (lifetime == NULL) {
				llog_pexpect(logger, HERE, "getting policy");
				return 0;
			}
			llog_sadb_lifetime(verbose, req.base, lifetime);
			*bytes = lifetime->sadb_lifetime_bytes;
			*add_time = lifetime->sadb_lifetime_addtime;
			break;
		}
		case SADB_EXT_ADDRESS_DST:
		case SADB_EXT_ADDRESS_SRC:
		case SADB_EXT_KEY_AUTH:
		case SADB_EXT_KEY_ENCRYPT:
		case SADB_EXT_SA:
#ifdef SADB_X_EXT_SA2 /* FreeBSD NetBSD */
		case SADB_X_EXT_SA2:
#endif
#ifdef SADB_X_EXT_NAT_T_TYPE /* FreeBSD NetBSD */
		case SADB_X_EXT_NAT_T_TYPE:
#endif
		case SADB_EXT_LIFETIME_HARD:
		case SADB_EXT_LIFETIME_SOFT:
#ifdef SADB_X_EXT_SA_REPLAY /* FreeBSD */
		case SADB_X_EXT_SA_REPLAY:
#endif
#ifdef SADB_X_EXT_LIFETIME_LASTUSE /* OpenBSD */
		case SADB_X_EXT_LIFETIME_LASTUSE:
#endif
#ifdef SADB_X_EXT_COUNTER /* OpenBSD */
		case  SADB_X_EXT_COUNTER:
#endif
#ifdef SADB_X_EXT_REPLAY /* OpenBSD */
		case SADB_X_EXT_REPLAY:
#endif
#ifdef SADB_X_EXT_IFACE /* OpenBSD */
		case SADB_X_EXT_IFACE:
#endif
			/* ignore these */
			break;
		default:
		{
			VERBOSE_LOG(logger, "%s(), ignoring unexpected:", __func__);
			llog_sadb_ext(verbose, req.base, ext, ext_cursor);
			break;
		}
		}
	}

	return false;
}

#ifdef SADB_X_EXT_POLICY /* FreeBSD NetBSD */
static struct sadb_x_ipsecrequest *put_sadb_x_ipsecrequest(struct outbuf *msg,
							   const struct kernel_policy *kernel_policy,
							   enum ipsec_mode mode,
							   const struct kernel_policy_rule *rule)
{
	VERBOSE_DBGP(DBG_BASE, msg->logger, "...");
	/*
	 * XXX: sadb_x_ipsecrequest screwed up the LEN parameter; it's
	 * in bytes.
	 */
	struct sadb_x_ipsecrequest *x_ipsecrequest =
		put_sadb(msg, sadb_x_ipsecrequest,
			 .sadb_x_ipsecrequest_proto = rule->proto,
			 .sadb_x_ipsecrequest_mode = mode,
			 .sadb_x_ipsecrequest_level = IPSEC_LEVEL_REQUIRE,
			 .sadb_x_ipsecrequest_reqid = /*rule->reqid*/0);
	/*
	 * setkey(8) man page says that transport mode doesn't require
	 * policy addresses (presumably the packet's address can be
	 * used).
	 *
	 * draft-schilcher-mobike-pfkey-extension-01 goes further and
	 * states: In the case that transport mode is used, no
	 * additional addresses are specified.
	 */
	if (mode == IPSEC_MODE_TUNNEL) {
		put_address_sockaddr(msg, kernel_policy->src.host);
		put_address_sockaddr(msg, kernel_policy->dst.host);
	}
	padup_sadb(msg, x_ipsecrequest);
	/* patch up mess? */
	x_ipsecrequest->sadb_x_ipsecrequest_len *= sizeof(uint64_t);
	return x_ipsecrequest;
}
#endif

#ifdef SADB_X_EXT_POLICY /* FreeBSD NetBSD */
static struct sadb_x_policy *put_sadb_x_policy(struct outbuf *req,
					       enum direction dir,
					       enum ipsec_policy policy_type,
					       enum kernel_policy_id policy_id,
					       const struct kernel_policy *kernel_policy)
{
	VERBOSE_DBGP(DBG_BASE, req->logger, "...");

	enum ipsec_dir policy_dir = (dir == DIRECTION_INBOUND ? IPSEC_DIR_INBOUND :
				     dir == DIRECTION_OUTBOUND ? IPSEC_DIR_OUTBOUND :
				     pexpect(0));

	struct sadb_x_policy *x_policy =
		put_sadb_ext(req, sadb_x_policy, SADB_X_EXT_POLICY,
			     .sadb_x_policy_type = policy_type,
			     .sadb_x_policy_dir = policy_dir,
			     .sadb_x_policy_id = policy_id);

	if (kernel_policy != NULL) {
#ifdef sadb_x_policy_priority
		x_policy->sadb_x_policy_priority = kernel_policy->priority.value;
#endif
		if (kernel_policy->nr_rules > 0) {
			PEXPECT(req->logger, (policy_type == IPSEC_POLICY_IPSEC ||
					      policy_type == IPSEC_POLICY_DISCARD));
			/*
			 * XXX: Only the first rule gets the worm; er
			 * tunnel flag.
			 *
			 * Should the caller take care of this?
			 */
			enum ipsec_mode mode =
				(kernel_policy->mode == KERNEL_MODE_TUNNEL ? IPSEC_MODE_TUNNEL :
				 kernel_policy->mode == KERNEL_MODE_TRANSPORT ? IPSEC_MODE_TRANSPORT :
				 pexpect(0));
			for (unsigned i = 0; i < kernel_policy->nr_rules; i++) {
				const struct kernel_policy_rule *rule = &kernel_policy->rule[i];
				put_sadb_x_ipsecrequest(req, kernel_policy, mode, rule);
				mode = IPSEC_MODE_TRANSPORT;
			}
		}
	}

	padup_sadb(req, x_policy);
	return x_policy;
}
#endif

#ifdef SADB_X_EXT_POLICY
static bool parse_sadb_x_policy(struct verbose verbose, const struct sadb_msg *b,
				shunk_t *ext_cursor,
				enum kernel_policy_id *policy_id)
{
	verbose.level++;
	shunk_t policy_cursor;
	const struct sadb_x_policy *policy =
		get_sadb_x_policy(ext_cursor, &policy_cursor, verbose);
	if (policy == NULL) {
		return false;
	}
	llog_sadb_x_policy(verbose, b, policy);
	verbose.level++;
	*policy_id = policy->sadb_x_policy_id;
	return true;
}
#endif

static bool kernel_pfkeyv2_policy_add(enum kernel_policy_op op,
				      enum direction dir,
				      const ip_selector *src_client,
				      const ip_selector *dst_client,
				      const struct kernel_policy *policy,
				      deltatime_t use_lifetime UNUSED,
				      struct logger *logger, const char *func)
{
	VERBOSE_DBGP(DBG_BASE, logger, "%s ...", func);
	if (policy->ipsec_interface != NULL) {
		ipsec_interface_buf ifb;
		vlog("BSD doesn't add kernel-policy to an ipsec-interface (%s)",
		     str_ipsec_interface(policy->ipsec_interface, &ifb));
		return true;
	}
#ifdef __OpenBSD__

	if (policy->nr_rules > 1) {
		/*
		 * For IPcomp+ESP where two policies need to
		 * installed, OpenBSD instead: installs a flow with
		 * one policy (i guess the first); SA pairs for IPsec
		 * and ESP; bundle (SADB_X_EXT_GRPSPIs) to group the
		 * two SAs.
		 */
		llog_pexpect(verbose.logger, HERE,
			     "multiple policies using SADB_X_EXT_GRPSPIS (GRouP SPI S) not implemented");
		return false;
	}

	enum sadb_type type = (op == KERNEL_POLICY_OP_ADD ? SADB_X_ADDFLOW :
			       op == KERNEL_POLICY_OP_REPLACE ? SADB_X_ADDFLOW :
			       pexpect(0));

	enum sadb_satype satype =
		(policy->rule[0].proto == KERNEL_PROTO_ESP ? SADB_SATYPE_ESP :
		 policy->rule[0].proto == KERNEL_PROTO_AH ? SADB_SATYPE_AH :
		 policy->rule[0].proto == KERNEL_PROTO_IPCOMP ? SADB_X_SATYPE_IPCOMP :
		 pexpect(0));

	uint8_t reqbuf[SIZEOF_SADB_BASE +
		       SIZEOF_SADB_PROTOCOL + /*flow*/
		       SIZEOF_SADB_ADDRESS * 2 + /*src/dst addr*/
		       SIZEOF_SADB_ADDRESS * 4 + /*src/dst addr/mask*/
		       SIZEOF_SADB_PROTOCOL + /*flow*/
		       0];

	struct outbuf req;
	msg_base(verbose, &req, __func__,
		 chunk2(reqbuf, sizeof(reqbuf)),
		 type, satype);

	/* flow type */

	unsigned policy_direction =
		(dir == DIRECTION_INBOUND ? IPSP_DIRECTION_IN :
		 dir == DIRECTION_OUTBOUND ? IPSP_DIRECTION_OUT :
		 pexpect(0));

	enum sadb_x_flow_type policy_type = UINT_MAX;
	const char *policy_name = NULL;
	switch (policy->shunt) {
	case SHUNT_TRAP:
		policy_type = SADB_X_FLOW_TYPE_ACQUIRE;
		policy_name = "%trap(acquire)";
		break;
	case SHUNT_IPSEC:
		policy_type = SADB_X_FLOW_TYPE_REQUIRE;
		policy_name = (policy->mode == KERNEL_MODE_TUNNEL ? ip_protocol_ipip.name :
			       policy->mode == KERNEL_MODE_TRANSPORT ? protocol_from_ipproto(policy->rule[policy->nr_rules-1].proto)->name :
			       "UNKNOWN");
		break;
	case SHUNT_PASS:
		policy_type = SADB_X_FLOW_TYPE_BYPASS;
		policy_name = "%pass(bypass)";
		break;
	case SHUNT_DROP:
		policy_type = SADB_X_FLOW_TYPE_DENY;
		policy_name = "%drop(deny)";
		break;
	case SHUNT_REJECT:
		policy_type = SADB_X_FLOW_TYPE_DENY;
		policy_name = "%reject(deny)";
		break;
	case SHUNT_HOLD:
		policy_type = SADB_X_FLOW_TYPE_DENY;
		policy_name = "%hold(deny)";
		break;
	case SHUNT_NONE:
		/* FAILURE=NONE should have been turned into
		 * NEGOTIATION */
		bad_case(policy->shunt);
	case SHUNT_UNSET:
		bad_case(policy->shunt);
	}
	PASSERT(logger, policy_type != UINT_MAX);
	PASSERT(logger, policy_name != NULL);

	ldbg(logger, "%s()   policy=%s", func, policy_name);

	put_sadb_ext(&req, sadb_protocol, SADB_X_EXT_FLOW_TYPE,
		     .sadb_protocol_direction = policy_direction,
		     .sadb_protocol_proto = policy_type);

	/* host_addr */

	if (policy->nr_rules > 0) {
		/*
		 * XXX: needing to look at OP_DIRECTION to decide if a
		 * switch-a-roo is needed when setting the PFKEYv2
		 * field's SRC/DST from the actual SRC/DST sure feels
		 * like a bug.
		 */
		switch (dir) {
		case DIRECTION_INBOUND:
			/* XXX: notice how DST gets SRC's value et.al. */
			put_sadb_address(&req, SADB_EXT_ADDRESS_DST, policy->src.host, verbose);
			put_sadb_address(&req, SADB_EXT_ADDRESS_SRC, policy->dst.host, verbose);
			break;
		case DIRECTION_OUTBOUND:
			put_sadb_address(&req, SADB_EXT_ADDRESS_SRC, policy->src.host, verbose);
			put_sadb_address(&req, SADB_EXT_ADDRESS_DST, policy->dst.host, verbose);
			break;
		}
	}

	/* selectors */

	put_sadb_address(&req, SADB_X_EXT_SRC_FLOW, selector_prefix(*src_client), verbose);
	put_sadb_address(&req, SADB_X_EXT_SRC_MASK, selector_prefix_mask(*src_client), verbose);
	put_sadb_address(&req, SADB_X_EXT_DST_FLOW, selector_prefix(*dst_client), verbose);
	put_sadb_address(&req, SADB_X_EXT_DST_MASK, selector_prefix_mask(*dst_client), verbose);

	/* which protocol? */

	put_sadb_ext(&req, sadb_protocol, SADB_X_EXT_PROTOCOL,
		     .sadb_protocol_proto = selector_protocol(*src_client)->ipproto);

	/* sa_srcd, sa_dstid: identity (sec_label?) */

#else

	/* SPDADD: <base, policy, address(SD), [lifetime(HS)]> */

	enum sadb_type type = (op == KERNEL_POLICY_OP_ADD ? SADB_X_SPDADD :
			       op == KERNEL_POLICY_OP_REPLACE ? SADB_X_SPDUPDATE :
			       pexpect(0));
	/* what NetBSD expects */
	enum sadb_satype satype = SADB_SATYPE_UNSPEC;
	uint8_t reqbuf[SIZEOF_SADB_BASE +
		       SIZEOF_SADB_X_POLICY +
		       SIZEOF_SADB_ADDRESS * 2 +
		       SIZEOF_SADB_LIFETIME * 2];
	struct outbuf req;
	msg_base(verbose, &req, __func__,
		 chunk2(reqbuf, sizeof(reqbuf)),
		 type, satype);

	/* address(SD) */

	put_sadb_selector(&req, SADB_EXT_ADDRESS_SRC, *src_client, verbose);
	put_sadb_selector(&req, SADB_EXT_ADDRESS_DST, *dst_client, verbose);

	/* [lifetime(HSC)] */

	put_sadb_ext(&req, sadb_lifetime, SADB_EXT_LIFETIME_HARD);

	/* policy */

	enum ipsec_policy policy_type = UINT_MAX;
	const char *policy_name = NULL;
	switch (policy->shunt) {
	case SHUNT_TRAP:
		policy_type = IPSEC_POLICY_IPSEC;
		policy_name = "%trap(ipsec)";
		break;
	case SHUNT_IPSEC:
		policy_type = IPSEC_POLICY_IPSEC;
		policy_name = (policy->mode == KERNEL_MODE_TUNNEL ? ip_protocol_ipip.name :
			       policy->mode == KERNEL_MODE_TRANSPORT ? protocol_from_ipproto(policy->rule[policy->nr_rules-1].proto)->name :
			       "UNKNOWN");
		break;
	case SHUNT_PASS:
		policy_type = IPSEC_POLICY_NONE;
		policy_name = "%pass(none)";
		break;
	case SHUNT_DROP:
		policy_type = IPSEC_POLICY_DISCARD;
		policy_name = "%drop(discard)";
		break;
	case SHUNT_REJECT:
		policy_type = IPSEC_POLICY_DISCARD;
		policy_name = "%reject(discard)";
		break;
	case SHUNT_HOLD:
		policy_type = IPSEC_POLICY_DISCARD;
		policy_name = "%hold(discard)";
		break;
	case SHUNT_NONE:
		/* FAILURE=NONE should have been turned into
		 * NEGOTIATION */
		bad_case(policy->shunt);
	case SHUNT_UNSET:
		bad_case(policy->shunt);
	}
	PASSERT(logger, policy_type != UINT_MAX);
	PASSERT(logger, policy_name != NULL);

	ldbg(logger, "%s()   policy=%s", func, policy_name);

	put_sadb_x_policy(&req, dir, policy_type,
			  policy->id, policy);

#endif

	/* send/req */

	struct inbuf resp;
	return msg_sendrecv(&req, &resp, verbose);
}

static bool kernel_pfkeyv2_policy_del(enum direction direction,
				      enum expect_kernel_policy expect_kernel_policy,
				      const ip_selector *src_child,
				      const ip_selector *dst_child,
				      const struct sa_marks *sa_marks UNUSED,
				      const struct ipsec_interface *ipsec_interface,
				      enum kernel_policy_id policy_id,
				      const shunk_t sec_label UNUSED,
				      struct logger *logger, const char *func)
{
	VERBOSE_DBGP(DBG_BASE, logger, "%s policy_id=%u ...", func, policy_id);
	if (ipsec_interface != NULL) {
		ipsec_interface_buf ifb;
		vlog("BSD doesn't add kernel-policy to an ipsec-interface (%s)",
		     str_ipsec_interface(ipsec_interface, &ifb));
		return true;
	}
#ifdef __OpenBSD__

	uint8_t reqbuf[SIZEOF_SADB_BASE +
		       SIZEOF_SADB_PROTOCOL + /*flow*/
		       SIZEOF_SADB_ADDRESS * 2 + /*src/dst addr*/
		       SIZEOF_SADB_ADDRESS * 4 + /*src/dst addr/mask*/
		       SIZEOF_SADB_PROTOCOL + /*flow*/
		       0];

	struct outbuf req;
	msg_base(verbose, &req, __func__,
		 chunk2(reqbuf, sizeof(reqbuf)),
		 SADB_X_DELFLOW,
		 SADB_SATYPE_UNSPEC);

	/* flow type */

	unsigned policy_direction =
		(direction == DIRECTION_INBOUND ? IPSP_DIRECTION_IN :
		 direction == DIRECTION_OUTBOUND ? IPSP_DIRECTION_OUT :
		 pexpect(0));

	put_sadb_ext(&req, sadb_protocol, SADB_X_EXT_FLOW_TYPE,
		     .sadb_protocol_direction = policy_direction,
		     .sadb_protocol_proto = SADB_X_FLOW_TYPE_REQUIRE);

	/* selectors */

	put_sadb_address(&req, SADB_X_EXT_SRC_FLOW, selector_prefix(*src_child), verbose);
	put_sadb_address(&req, SADB_X_EXT_SRC_MASK, selector_prefix_mask(*src_child), verbose);
	put_sadb_address(&req, SADB_X_EXT_DST_FLOW, selector_prefix(*dst_child), verbose);
	put_sadb_address(&req, SADB_X_EXT_DST_MASK, selector_prefix_mask(*dst_child), verbose);

	/* which protocol? */

	put_sadb_ext(&req, sadb_protocol, SADB_X_EXT_PROTOCOL,
		     .sadb_protocol_proto = selector_protocol(*src_child)->ipproto);

	/* sa_srcd, sa_dstid: identity (sec_label?) */

#else

	/* SPDADD: <base, policy, address(SD), [lifetime(HS)]> */

	uint8_t reqbuf[SIZEOF_SADB_BASE +
		       SIZEOF_SADB_X_POLICY +
		       SIZEOF_SADB_ADDRESS * 2 +
		       SIZEOF_SADB_LIFETIME * 2];
	struct outbuf req;
	msg_base(verbose, &req, __func__,
		 chunk2(reqbuf, sizeof(reqbuf)),
		 SADB_X_SPDDELETE,
		 SADB_SATYPE_UNSPEC);

	/* address(SD) */

	put_sadb_selector(&req, SADB_EXT_ADDRESS_SRC, *src_child, verbose);
	put_sadb_selector(&req, SADB_EXT_ADDRESS_DST, *dst_child, verbose);

	/* policy */

	put_sadb_x_policy(&req, direction,
			  IPSEC_POLICY_IPSEC, policy_id, NULL);

#endif

	/* send/req */

	struct inbuf resp;
	if (!msg_sendrecv(&req, &resp, verbose)) {
		switch (expect_kernel_policy) {
		case KERNEL_POLICY_PRESENT_OR_MISSING:
		case KERNEL_POLICY_MISSING:
			ldbg(logger, "%s()   ignoring pfkey error", func);
			break;
		case KERNEL_POLICY_PRESENT:
			llog_pexpect(logger, HERE, "%s()   receiving", func);
			return false;
		}
	}

	return true;
}

static bool parse_sadb_address(struct verbose verbose, const struct sadb_msg *b,
			       shunk_t *ext_cursor, ip_address *addr, ip_port *port)
{
	shunk_t address_cursor;
	const struct sadb_address *address =
		get_sadb_address(ext_cursor, &address_cursor, verbose);
	if (address == NULL) {
		return false;
	}
	llog_sadb_address(verbose, b, address);
	verbose.level++;
	if (!get_sadb_sockaddr_address_port(&address_cursor, addr, port, verbose)) {
		return false;
	}
	address_buf ab;
	port_buf pb;
	verbose("%s:%s", str_address(addr, &ab), str_hport(*port, &pb));
	return true;
}

static void parse_sadb_acquire(const struct sadb_msg *msg,
			       shunk_t msg_cursor,
			       const struct logger *logger)
{
	VERBOSE_DBGP(DBG_BASE, logger, "...");
	ip_address src_address = unset_address;
	ip_address dst_address = unset_address;
	ip_port src_port, dst_port;
	enum kernel_policy_id policy_id = 0;

	while (msg_cursor.len > 0) {

		shunk_t ext_cursor;
		const struct sadb_ext *ext =
			get_sadb_ext(&msg_cursor, &ext_cursor, verbose);
		if (ext == NULL) {
			llog_pexpect(verbose.logger, HERE, "bad ext");
			return;
		}

		enum sadb_exttype exttype = ext->sadb_ext_type;
		switch (exttype) {

		case SADB_EXT_ADDRESS_SRC:
			if (!parse_sadb_address(verbose, msg, &ext_cursor, &src_address, &src_port)) {
				return;
			}
			break;
		case SADB_EXT_ADDRESS_DST:
			if (!parse_sadb_address(verbose, msg, &ext_cursor, &dst_address, &dst_port)) {
				return;
			}
			break;
#ifdef SADB_X_EXT_POLICY /* FreeBSD NetBSD */
		case SADB_X_EXT_POLICY:
			policy_id = 0;
			if (!parse_sadb_x_policy(verbose, msg, &ext_cursor, &policy_id)) {
				return;
			}
			break;
#endif

		case SADB_EXT_PROPOSAL:
			if (DBGP(DBG_BASE)) {
				verbose("ignore: ");
				verbose.level++;
				llog_sadb_ext(verbose, msg, ext, ext_cursor);
				verbose.level--;
			}
			break;

		default:
			if (DBGP(DBG_BASE)) {
				verbose.level++;
				llog_sadb_ext(verbose, msg, ext, ext_cursor);
				verbose.level--;
			}
			break;
		}
	}

	if (address_is_unset(&src_address) || address_is_unset(&dst_address)) {
		ldbg(logger, "something isn't set");
		return;
	}

	ip_packet packet = packet_from_raw(HERE,
					   address_info(src_address),
					   &src_address.bytes,
					   &dst_address.bytes,
					   &ip_protocol_all,
					   src_port,
					   dst_port);
	struct kernel_acquire b = {
		.packet = packet,
		.by_acquire = true,
		.logger = logger, /*on-stack*/
		.background = true, /* no whack so doesn't matter */
		.sec_label = null_shunk,
		.policy_id = policy_id,
	};
	initiate_ondemand(&b);
}

static void process_pending(shunk_t payload, struct verbose verbose)
{
	verbose("in %s() processing ...", __func__);
	verbose.level++;

	llog_sadb(verbose, payload);

	shunk_t cursor = payload;
	shunk_t msg_cursor;
	const struct sadb_msg *msg = get_sadb_msg(&cursor, &msg_cursor, verbose);
	if (msg == NULL) {
		llog_pexpect(verbose.logger, HERE, "no msg");
	}

	switch (msg->sadb_msg_type) {
	case SADB_ACQUIRE:
		parse_sadb_acquire(msg, msg_cursor, verbose.logger);
		break;
	}
}

static void process_pending_queue(struct verbose verbose)
{
	struct pending *pending;
	FOR_EACH_LIST_ENTRY_OLD2NEW(pending, &pending_queue) {
		remove_list_entry(&pending->entry);
		process_pending(HUNK_AS_SHUNK(pending->msg), verbose);
		free_chunk_content(&pending->msg);
		pfree(pending);
	}
}

static void pfkeyv2_process_msg(int fd UNUSED, void *arg UNUSED, struct logger *logger)
{
	VERBOSE_DBGP(DBG_BASE, logger, "processing message");
	struct inbuf msg;
	if (!recv_msg(&msg, "process", verbose)) {
		return;
	}
	queue_msg(&msg);
	process_pending_queue(verbose);
}

static void kernel_pfkeyv2_shutdown(struct logger *logger)
{
	ldbg(logger, "%s() called; nothing to do", __func__);
}

static err_t kernel_directional_ipsec_is_enabled(struct logger *logger)
{
	ldbg(logger, "%s() called; nothing to do", __func__);
	return "not supported";
}

static err_t kernel_iptfs_ipsec_sa_is_enabled(struct logger *logger)
{
	ldbg(logger, "%s() called; nothing to do", __func__);
	return "not supported";
}

static err_t kernel_migrate_ipsec_sa_is_enabled(struct logger *logger)
{
	ldbg(logger, "%s() called; nothing to do", __func__);
	return "not supported";
}

static const char *pfkeyv2_protostack_names[] = {
	"pfkeyv2",
	"pfkey",
	"bsdkame", /* provide compatible name */
	NULL,
};

const struct kernel_ops pfkeyv2_kernel_ops = {
	.protostack_names = pfkeyv2_protostack_names,
	.updown_name = "bsd",
	.interface_name = "PF_KEY v2",
	.overlap_supported = false,	/* XXX: delete this? */
	.sha2_truncbug_support = false,
#ifdef SADB_X_SAFLAGS_ESN /* FreeBSD OpenBSD */
	.esn_supported = true,		/* FreeBSD and OpenBSD? */
#endif
#ifdef SADB_X_EXT_SA_REPLAY /* FreeBSD */
	/* .sadb_x_sa_replay_replay is in packets */
	.max_replay_window = (UINT32_MAX - 32), /* packets */
#elif defined(__OpenBSD__)
	/* kernel limits value to 64 * 8 packet bits per-byte */
	.max_replay_window = 64 * 8, /* packets */
#else
	/* .sadb_sa_replay is in bytes with 1 bit per packet */
	.max_replay_window = UINT8_MAX * 8, /* packets */
#endif

	.init = kernel_pfkeyv2_init,
	.flush = kernel_pfkeyv2_flush,
	.poke_holes = kernel_pfkeyv2_poke_holes,
	.plug_holes = kernel_pfkeyv2_plug_holes,
	.shutdown = kernel_pfkeyv2_shutdown,

	.get_ipsec_spi = pfkeyv2_get_ipsec_spi,
	.del_ipsec_spi = pfkeyv2_del_ipsec_spi,
	.add_sa = pfkeyv2_add_sa,
	.get_kernel_state = pfkeyv2_get_kernel_state,
	.policy_del = kernel_pfkeyv2_policy_del,
	.policy_add = kernel_pfkeyv2_policy_add,
	.ipsec_interface = &kernel_ipsec_interface_ifconfig,
	.directional_ipsec_sa_is_enabled = kernel_directional_ipsec_is_enabled,
	.iptfs_ipsec_sa_is_enabled = kernel_iptfs_ipsec_sa_is_enabled,
	.migrate_ipsec_sa_is_enabled = kernel_migrate_ipsec_sa_is_enabled,
};