summaryrefslogtreecommitdiff
path: root/sys/net/if_pfsync.c
blob: 765bb4ac4000c7ef8d80f0d7e6a1d31102c56e70 (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
/*	$OpenBSD: if_pfsync.c,v 1.78 2007/06/01 18:44:22 henning Exp $	*/

/*
 * Copyright (c) 2002 Michael Shalayeff
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR OR HIS RELATIVES BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF MIND, USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON 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 ADVISED OF
 * THE POSSIBILITY OF SUCH DAMAGE.
 */


#include <sys/param.h>
#include <sys/proc.h>
#include <sys/systm.h>
#include <sys/time.h>
#include <sys/mbuf.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <sys/timeout.h>
#include <sys/kernel.h>

#include <net/if.h>
#include <net/if_types.h>
#include <net/route.h>
#include <net/bpf.h>
#include <netinet/in.h>
#include <netinet/if_ether.h>
#include <netinet/tcp.h>
#include <netinet/tcp_seq.h>

#ifdef	INET
#include <netinet/in_systm.h>
#include <netinet/in_var.h>
#include <netinet/ip.h>
#include <netinet/ip_var.h>
#endif

#ifdef INET6
#include <netinet6/nd6.h>
#endif /* INET6 */

#include "carp.h"
#if NCARP > 0
#include <netinet/ip_carp.h>
#endif

#include <net/pfvar.h>
#include <net/if_pfsync.h>

#include "bpfilter.h"
#include "pfsync.h"

#define PFSYNC_MINMTU	\
    (sizeof(struct pfsync_header) + sizeof(struct pf_state))

#ifdef PFSYNCDEBUG
#define DPRINTF(x)    do { if (pfsyncdebug) printf x ; } while (0)
int pfsyncdebug;
#else
#define DPRINTF(x)
#endif

struct pfsync_softc	*pfsyncif = NULL;
struct pfsyncstats	 pfsyncstats;

void	pfsyncattach(int);
int	pfsync_clone_create(struct if_clone *, int);
int	pfsync_clone_destroy(struct ifnet *);
void	pfsync_setmtu(struct pfsync_softc *, int);
int	pfsync_alloc_scrub_memory(struct pfsync_state_peer *,
	    struct pf_state_peer *);
int	pfsync_insert_net_state(struct pfsync_state *, u_int8_t);
void	pfsync_update_net_tdb(struct pfsync_tdb *);
int	pfsyncoutput(struct ifnet *, struct mbuf *, struct sockaddr *,
	    struct rtentry *);
int	pfsyncioctl(struct ifnet *, u_long, caddr_t);
void	pfsyncstart(struct ifnet *);

struct mbuf *pfsync_get_mbuf(struct pfsync_softc *, u_int8_t, void **);
int	pfsync_request_update(struct pfsync_state_upd *, struct in_addr *);
int	pfsync_sendout(struct pfsync_softc *);
int	pfsync_tdb_sendout(struct pfsync_softc *);
int	pfsync_sendout_mbuf(struct pfsync_softc *, struct mbuf *);
void	pfsync_timeout(void *);
void	pfsync_tdb_timeout(void *);
void	pfsync_send_bus(struct pfsync_softc *, u_int8_t);
void	pfsync_bulk_update(void *);
void	pfsync_bulkfail(void *);

int	pfsync_sync_ok;

struct if_clone	pfsync_cloner =
    IF_CLONE_INITIALIZER("pfsync", pfsync_clone_create, pfsync_clone_destroy);

void
pfsyncattach(int npfsync)
{
	if_clone_attach(&pfsync_cloner);
}
int
pfsync_clone_create(struct if_clone *ifc, int unit)
{
	struct ifnet *ifp;

	if (unit != 0)
		return (EINVAL);

	pfsync_sync_ok = 1;
	if ((pfsyncif = malloc(sizeof(*pfsyncif), M_DEVBUF, M_NOWAIT)) == NULL)
		return (ENOMEM);
	bzero(pfsyncif, sizeof(*pfsyncif));
	pfsyncif->sc_mbuf = NULL;
	pfsyncif->sc_mbuf_net = NULL;
	pfsyncif->sc_mbuf_tdb = NULL;
	pfsyncif->sc_statep.s = NULL;
	pfsyncif->sc_statep_net.s = NULL;
	pfsyncif->sc_statep_tdb.t = NULL;
	pfsyncif->sc_maxupdates = 128;
	pfsyncif->sc_sync_peer.s_addr = INADDR_PFSYNC_GROUP;
	pfsyncif->sc_sendaddr.s_addr = INADDR_PFSYNC_GROUP;
	pfsyncif->sc_ureq_received = 0;
	pfsyncif->sc_ureq_sent = 0;
	pfsyncif->sc_bulk_send_next = NULL;
	pfsyncif->sc_bulk_terminator = NULL;
	ifp = &pfsyncif->sc_if;
	snprintf(ifp->if_xname, sizeof ifp->if_xname, "pfsync%d", unit);
	ifp->if_softc = pfsyncif;
	ifp->if_ioctl = pfsyncioctl;
	ifp->if_output = pfsyncoutput;
	ifp->if_start = pfsyncstart;
	ifp->if_type = IFT_PFSYNC;
	ifp->if_snd.ifq_maxlen = ifqmaxlen;
	ifp->if_hdrlen = PFSYNC_HDRLEN;
	pfsync_setmtu(pfsyncif, ETHERMTU);
	timeout_set(&pfsyncif->sc_tmo, pfsync_timeout, pfsyncif);
	timeout_set(&pfsyncif->sc_tdb_tmo, pfsync_tdb_timeout, pfsyncif);
	timeout_set(&pfsyncif->sc_bulk_tmo, pfsync_bulk_update, pfsyncif);
	timeout_set(&pfsyncif->sc_bulkfail_tmo, pfsync_bulkfail, pfsyncif);
	if_attach(ifp);
	if_alloc_sadl(ifp);

#if NCARP > 0
	if_addgroup(ifp, "carp");
#endif

#if NBPFILTER > 0
	bpfattach(&pfsyncif->sc_if.if_bpf, ifp, DLT_PFSYNC, PFSYNC_HDRLEN);
#endif

	return (0);
}

int
pfsync_clone_destroy(struct ifnet *ifp)
{
#if NBPFILTER > 0
	bpfdetach(ifp);
#endif
	if_detach(ifp);
	free(pfsyncif, M_DEVBUF);
	pfsyncif = NULL;
	return (0);
}

/*
 * Start output on the pfsync interface.
 */
void
pfsyncstart(struct ifnet *ifp)
{
	struct mbuf *m;
	int s;

	for (;;) {
		s = splnet();
		IF_DROP(&ifp->if_snd);
		IF_DEQUEUE(&ifp->if_snd, m);
		splx(s);

		if (m == NULL)
			return;
		else
			m_freem(m);
	}
}

int
pfsync_alloc_scrub_memory(struct pfsync_state_peer *s,
    struct pf_state_peer *d)
{
	if (s->scrub.scrub_flag && d->scrub == NULL) {
		d->scrub = pool_get(&pf_state_scrub_pl, PR_NOWAIT);
		if (d->scrub == NULL)
			return (ENOMEM);
		bzero(d->scrub, sizeof(*d->scrub));
	}

	return (0);
}

int
pfsync_insert_net_state(struct pfsync_state *sp, u_int8_t chksum_flag)
{
	struct pf_state	*st = NULL;
	struct pf_state_key *sk = NULL;
	struct pf_rule *r = NULL;
	struct pfi_kif	*kif;

	if (sp->creatorid == 0 && pf_status.debug >= PF_DEBUG_MISC) {
		printf("pfsync_insert_net_state: invalid creator id:"
		    " %08x\n", ntohl(sp->creatorid));
		return (EINVAL);
	}

	kif = pfi_kif_get(sp->ifname);
	if (kif == NULL) {
		if (pf_status.debug >= PF_DEBUG_MISC)
			printf("pfsync_insert_net_state: "
			    "unknown interface: %s\n", sp->ifname);
		/* skip this state */
		return (0);
	}

	/*
	 * If the ruleset checksums match, it's safe to associate the state
	 * with the rule of that number.
	 */
	if (sp->rule != htonl(-1) && sp->anchor == htonl(-1) && chksum_flag)
		r = pf_main_ruleset.rules[
		    PF_RULESET_FILTER].active.ptr_array[ntohl(sp->rule)];
	else
		r = &pf_default_rule;

	if (!r->max_states || r->states < r->max_states)
		st = pool_get(&pf_state_pl, PR_NOWAIT);
	if (st == NULL) {
		pfi_kif_unref(kif, PFI_KIF_REF_NONE);
		return (ENOMEM);
	}
	bzero(st, sizeof(*st));

	if ((sk = pf_alloc_state_key(st)) == NULL) {
		pool_put(&pf_state_pl, st);
		pfi_kif_unref(kif, PFI_KIF_REF_NONE);
		return (ENOMEM);
	}

	/* allocate memory for scrub info */
	if (pfsync_alloc_scrub_memory(&sp->src, &st->src) ||
	    pfsync_alloc_scrub_memory(&sp->dst, &st->dst)) {
		pfi_kif_unref(kif, PFI_KIF_REF_NONE);
		if (st->src.scrub)
			pool_put(&pf_state_scrub_pl, st->src.scrub);
		pool_put(&pf_state_pl, st);
		pool_put(&pf_state_key_pl, sk);
		return (ENOMEM);
	}

	st->rule.ptr = r;
	/* XXX get pointers to nat_rule and anchor */

	/* XXX when we have nat_rule/anchors, use STATE_INC_COUNTERS */
	r->states++;

	/* fill in the rest of the state entry */
	pf_state_host_ntoh(&sp->lan, &sk->lan);
	pf_state_host_ntoh(&sp->gwy, &sk->gwy);
	pf_state_host_ntoh(&sp->ext, &sk->ext);

	pf_state_peer_ntoh(&sp->src, &st->src);
	pf_state_peer_ntoh(&sp->dst, &st->dst);

	bcopy(&sp->rt_addr, &st->rt_addr, sizeof(st->rt_addr));
	st->creation = time_second - ntohl(sp->creation);
	st->expire = ntohl(sp->expire) + time_second;

	sk->af = sp->af;
	sk->proto = sp->proto;
	sk->direction = sp->direction;
	st->log = sp->log;
	st->timeout = sp->timeout;
	st->allow_opts = sp->allow_opts;

	bcopy(sp->id, &st->id, sizeof(st->id));
	st->creatorid = sp->creatorid;
	st->sync_flags = PFSTATE_FROMSYNC;

	if (pf_insert_state(kif, st)) {
		pfi_kif_unref(kif, PFI_KIF_REF_NONE);
		/* XXX when we have nat_rule/anchors, use STATE_DEC_COUNTERS */
		r->states--;
		if (st->dst.scrub)
			pool_put(&pf_state_scrub_pl, st->dst.scrub);
		if (st->src.scrub)
			pool_put(&pf_state_scrub_pl, st->src.scrub);
		pool_put(&pf_state_pl, st);
		return (EINVAL);
	}

	return (0);
}

void
pfsync_input(struct mbuf *m, ...)
{
	struct ip *ip = mtod(m, struct ip *);
	struct pfsync_header *ph;
	struct pfsync_softc *sc = pfsyncif;
	struct pf_state *st;
	struct pf_state_key *sk;
	struct pf_state_cmp id_key;
	struct pfsync_state *sp;
	struct pfsync_state_upd *up;
	struct pfsync_state_del *dp;
	struct pfsync_state_clr *cp;
	struct pfsync_state_upd_req *rup;
	struct pfsync_state_bus *bus;
	struct pfsync_tdb *pt;
	struct in_addr src;
	struct mbuf *mp;
	int iplen, action, error, i, s, count, offp, sfail, stale = 0;
	u_int8_t chksum_flag = 0;

	pfsyncstats.pfsyncs_ipackets++;

	/* verify that we have a sync interface configured */
	if (!sc || !sc->sc_sync_ifp || !pf_status.running)
		goto done;

	/* verify that the packet came in on the right interface */
	if (sc->sc_sync_ifp != m->m_pkthdr.rcvif) {
		pfsyncstats.pfsyncs_badif++;
		goto done;
	}

	/* verify that the IP TTL is 255.  */
	if (ip->ip_ttl != PFSYNC_DFLTTL) {
		pfsyncstats.pfsyncs_badttl++;
		goto done;
	}

	iplen = ip->ip_hl << 2;

	if (m->m_pkthdr.len < iplen + sizeof(*ph)) {
		pfsyncstats.pfsyncs_hdrops++;
		goto done;
	}

	if (iplen + sizeof(*ph) > m->m_len) {
		if ((m = m_pullup(m, iplen + sizeof(*ph))) == NULL) {
			pfsyncstats.pfsyncs_hdrops++;
			goto done;
		}
		ip = mtod(m, struct ip *);
	}
	ph = (struct pfsync_header *)((char *)ip + iplen);

	/* verify the version */
	if (ph->version != PFSYNC_VERSION) {
		pfsyncstats.pfsyncs_badver++;
		goto done;
	}

	action = ph->action;
	count = ph->count;

	/* make sure it's a valid action code */
	if (action >= PFSYNC_ACT_MAX) {
		pfsyncstats.pfsyncs_badact++;
		goto done;
	}

	/* Cheaper to grab this now than having to mess with mbufs later */
	src = ip->ip_src;

	if (!bcmp(&ph->pf_chksum, &pf_status.pf_chksum, PF_MD5_DIGEST_LENGTH))
		chksum_flag++;

	switch (action) {
	case PFSYNC_ACT_CLR: {
		struct pf_state *nexts;
		struct pf_state_key *nextsk;
		struct pfi_kif *kif;
		u_int32_t creatorid;
		if ((mp = m_pulldown(m, iplen + sizeof(*ph),
		    sizeof(*cp), &offp)) == NULL) {
			pfsyncstats.pfsyncs_badlen++;
			return;
		}
		cp = (struct pfsync_state_clr *)(mp->m_data + offp);
		creatorid = cp->creatorid;

		s = splsoftnet();
		if (cp->ifname[0] == '\0') {
			for (st = RB_MIN(pf_state_tree_id, &tree_id);
			    st; st = nexts) {
				nexts = RB_NEXT(pf_state_tree_id, &tree_id, st);
				if (st->creatorid == creatorid) {
					st->sync_flags |= PFSTATE_FROMSYNC;
					pf_unlink_state(st);
				}
			}
		} else {
			if ((kif = pfi_kif_get(cp->ifname)) == NULL) {
				splx(s);
				return;
			}
			for (sk = RB_MIN(pf_state_tree_lan_ext,
			    &kif->pfik_lan_ext); sk; sk = nextsk) {
				nextsk = RB_NEXT(pf_state_tree_lan_ext,
				    &kif->pfik_lan_ext, sk);
				if (sk->state->creatorid == creatorid) {
					sk->state->sync_flags |=
					    PFSTATE_FROMSYNC;
					pf_unlink_state(sk->state);
				}
			}
		}
		splx(s);

		break;
	}
	case PFSYNC_ACT_INS:
		if ((mp = m_pulldown(m, iplen + sizeof(*ph),
		    count * sizeof(*sp), &offp)) == NULL) {
			pfsyncstats.pfsyncs_badlen++;
			return;
		}

		s = splsoftnet();
		for (i = 0, sp = (struct pfsync_state *)(mp->m_data + offp);
		    i < count; i++, sp++) {
			/* check for invalid values */
			if (sp->timeout >= PFTM_MAX ||
			    sp->src.state > PF_TCPS_PROXY_DST ||
			    sp->dst.state > PF_TCPS_PROXY_DST ||
			    sp->direction > PF_OUT ||
			    (sp->af != AF_INET && sp->af != AF_INET6)) {
				if (pf_status.debug >= PF_DEBUG_MISC)
					printf("pfsync_insert: PFSYNC_ACT_INS: "
					    "invalid value\n");
				pfsyncstats.pfsyncs_badstate++;
				continue;
			}

			if ((error = pfsync_insert_net_state(sp,
			    chksum_flag))) {
				if (error == ENOMEM) {
					splx(s);
					goto done;
				}
				continue;
			}
		}
		splx(s);
		break;
	case PFSYNC_ACT_UPD:
		if ((mp = m_pulldown(m, iplen + sizeof(*ph),
		    count * sizeof(*sp), &offp)) == NULL) {
			pfsyncstats.pfsyncs_badlen++;
			return;
		}

		s = splsoftnet();
		for (i = 0, sp = (struct pfsync_state *)(mp->m_data + offp);
		    i < count; i++, sp++) {
			int flags = PFSYNC_FLAG_STALE;

			/* check for invalid values */
			if (sp->timeout >= PFTM_MAX ||
			    sp->src.state > PF_TCPS_PROXY_DST ||
			    sp->dst.state > PF_TCPS_PROXY_DST) {
				if (pf_status.debug >= PF_DEBUG_MISC)
					printf("pfsync_insert: PFSYNC_ACT_UPD: "
					    "invalid value\n");
				pfsyncstats.pfsyncs_badstate++;
				continue;
			}

			bcopy(sp->id, &id_key.id, sizeof(id_key.id));
			id_key.creatorid = sp->creatorid;

			st = pf_find_state_byid(&id_key);
			if (st == NULL) {
				/* insert the update */
				if (pfsync_insert_net_state(sp, chksum_flag))
					pfsyncstats.pfsyncs_badstate++;
				continue;
			}
			sk = st->state_key;
			sfail = 0;
			if (sk->proto == IPPROTO_TCP) {
				/*
				 * The state should never go backwards except
				 * for syn-proxy states.  Neither should the
				 * sequence window slide backwards.
				 */
				if (st->src.state > sp->src.state &&
				    (st->src.state < PF_TCPS_PROXY_SRC ||
				    sp->src.state >= PF_TCPS_PROXY_SRC))
					sfail = 1;
				else if (SEQ_GT(st->src.seqlo,
				    ntohl(sp->src.seqlo)))
					sfail = 3;
				else if (st->dst.state > sp->dst.state) {
					/* There might still be useful
					 * information about the src state here,
					 * so import that part of the update,
					 * then "fail" so we send the updated
					 * state back to the peer who is missing
					 * our what we know. */
					pf_state_peer_ntoh(&sp->src, &st->src);
					/* XXX do anything with timeouts? */
					sfail = 7;
					flags = 0;
				} else if (st->dst.state >= TCPS_SYN_SENT &&
				    SEQ_GT(st->dst.seqlo, ntohl(sp->dst.seqlo)))
					sfail = 4;
			} else {
				/*
				 * Non-TCP protocol state machine always go
				 * forwards
				 */
				if (st->src.state > sp->src.state)
					sfail = 5;
				else if (st->dst.state > sp->dst.state)
					sfail = 6;
			}
			if (sfail) {
				if (pf_status.debug >= PF_DEBUG_MISC)
					printf("pfsync: %s stale update "
					    "(%d) id: %016llx "
					    "creatorid: %08x\n",
					    (sfail < 7 ?  "ignoring"
					     : "partial"), sfail,
					    betoh64(st->id),
					    ntohl(st->creatorid));
				pfsyncstats.pfsyncs_badstate++;

				if (!(sp->sync_flags & PFSTATE_STALE)) {
					/* we have a better state, send it */
					if (sc->sc_mbuf != NULL && !stale)
						pfsync_sendout(sc);
					stale++;
					if (!st->sync_flags)
						pfsync_pack_state(
						    PFSYNC_ACT_UPD, st, flags);
				}
				continue;
			}
	    		pfsync_alloc_scrub_memory(&sp->dst, &st->dst);
			pf_state_peer_ntoh(&sp->src, &st->src);
			pf_state_peer_ntoh(&sp->dst, &st->dst);
			st->expire = ntohl(sp->expire) + time_second;
			st->timeout = sp->timeout;
		}
		if (stale && sc->sc_mbuf != NULL)
			pfsync_sendout(sc);
		splx(s);
		break;
	/*
	 * It's not strictly necessary for us to support the "uncompressed"
	 * delete action, but it's relatively simple and maintains consistency.
	 */
	case PFSYNC_ACT_DEL:
		if ((mp = m_pulldown(m, iplen + sizeof(*ph),
		    count * sizeof(*sp), &offp)) == NULL) {
			pfsyncstats.pfsyncs_badlen++;
			return;
		}

		s = splsoftnet();
		for (i = 0, sp = (struct pfsync_state *)(mp->m_data + offp);
		    i < count; i++, sp++) {
			bcopy(sp->id, &id_key.id, sizeof(id_key.id));
			id_key.creatorid = sp->creatorid;

			st = pf_find_state_byid(&id_key);
			if (st == NULL) {
				pfsyncstats.pfsyncs_badstate++;
				continue;
			}
			st->sync_flags |= PFSTATE_FROMSYNC;
			pf_unlink_state(st);
		}
		splx(s);
		break;
	case PFSYNC_ACT_UPD_C: {
		int update_requested = 0;

		if ((mp = m_pulldown(m, iplen + sizeof(*ph),
		    count * sizeof(*up), &offp)) == NULL) {
			pfsyncstats.pfsyncs_badlen++;
			return;
		}

		s = splsoftnet();
		for (i = 0, up = (struct pfsync_state_upd *)(mp->m_data + offp);
		    i < count; i++, up++) {
			/* check for invalid values */
			if (up->timeout >= PFTM_MAX ||
			    up->src.state > PF_TCPS_PROXY_DST ||
			    up->dst.state > PF_TCPS_PROXY_DST) {
				if (pf_status.debug >= PF_DEBUG_MISC)
					printf("pfsync_insert: "
					    "PFSYNC_ACT_UPD_C: "
					    "invalid value\n");
				pfsyncstats.pfsyncs_badstate++;
				continue;
			}

			bcopy(up->id, &id_key.id, sizeof(id_key.id));
			id_key.creatorid = up->creatorid;

			st = pf_find_state_byid(&id_key);
			if (st == NULL) {
				/* We don't have this state. Ask for it. */
				error = pfsync_request_update(up, &src);
				if (error == ENOMEM) {
					splx(s);
					goto done;
				}
				update_requested = 1;
				pfsyncstats.pfsyncs_badstate++;
				continue;
			}
			sk = st->state_key;
			sfail = 0;
			if (sk->proto == IPPROTO_TCP) {
				/*
				 * The state should never go backwards except
				 * for syn-proxy states.  Neither should the
				 * sequence window slide backwards.
				 */
				if (st->src.state > up->src.state &&
				    (st->src.state < PF_TCPS_PROXY_SRC ||
				    up->src.state >= PF_TCPS_PROXY_SRC))
					sfail = 1;
				else if (st->dst.state > up->dst.state)
					sfail = 2;
				else if (SEQ_GT(st->src.seqlo,
				    ntohl(up->src.seqlo)))
					sfail = 3;
				else if (st->dst.state >= TCPS_SYN_SENT &&
				    SEQ_GT(st->dst.seqlo, ntohl(up->dst.seqlo)))
					sfail = 4;
			} else {
				/*
				 * Non-TCP protocol state machine always go
				 * forwards
				 */
				if (st->src.state > up->src.state)
					sfail = 5;
				else if (st->dst.state > up->dst.state)
					sfail = 6;
			}
			if (sfail) {
				if (pf_status.debug >= PF_DEBUG_MISC)
					printf("pfsync: ignoring stale update "
					    "(%d) id: %016llx "
					    "creatorid: %08x\n", sfail,
					    betoh64(st->id),
					    ntohl(st->creatorid));
				pfsyncstats.pfsyncs_badstate++;

				/* we have a better state, send it out */
				if ((!stale || update_requested) &&
				    sc->sc_mbuf != NULL) {
					pfsync_sendout(sc);
					update_requested = 0;
				}
				stale++;
				if (!st->sync_flags)
					pfsync_pack_state(PFSYNC_ACT_UPD, st,
					    PFSYNC_FLAG_STALE);
				continue;
			}
	    		pfsync_alloc_scrub_memory(&up->dst, &st->dst);
			pf_state_peer_ntoh(&up->src, &st->src);
			pf_state_peer_ntoh(&up->dst, &st->dst);
			st->expire = ntohl(up->expire) + time_second;
			st->timeout = up->timeout;
		}
		if ((update_requested || stale) && sc->sc_mbuf)
			pfsync_sendout(sc);
		splx(s);
		break;
	}
	case PFSYNC_ACT_DEL_C:
		if ((mp = m_pulldown(m, iplen + sizeof(*ph),
		    count * sizeof(*dp), &offp)) == NULL) {
			pfsyncstats.pfsyncs_badlen++;
			return;
		}

		s = splsoftnet();
		for (i = 0, dp = (struct pfsync_state_del *)(mp->m_data + offp);
		    i < count; i++, dp++) {
			bcopy(dp->id, &id_key.id, sizeof(id_key.id));
			id_key.creatorid = dp->creatorid;

			st = pf_find_state_byid(&id_key);
			if (st == NULL) {
				pfsyncstats.pfsyncs_badstate++;
				continue;
			}
			st->sync_flags |= PFSTATE_FROMSYNC;
			pf_unlink_state(st);
		}
		splx(s);
		break;
	case PFSYNC_ACT_INS_F:
	case PFSYNC_ACT_DEL_F:
		/* not implemented */
		break;
	case PFSYNC_ACT_UREQ:
		if ((mp = m_pulldown(m, iplen + sizeof(*ph),
		    count * sizeof(*rup), &offp)) == NULL) {
			pfsyncstats.pfsyncs_badlen++;
			return;
		}

		s = splsoftnet();
		if (sc->sc_mbuf != NULL)
			pfsync_sendout(sc);
		for (i = 0,
		    rup = (struct pfsync_state_upd_req *)(mp->m_data + offp);
		    i < count; i++, rup++) {
			bcopy(rup->id, &id_key.id, sizeof(id_key.id));
			id_key.creatorid = rup->creatorid;

			if (id_key.id == 0 && id_key.creatorid == 0) {
				sc->sc_ureq_received = time_uptime;
				if (sc->sc_bulk_send_next == NULL)
					sc->sc_bulk_send_next =
					    TAILQ_FIRST(&state_list);
				sc->sc_bulk_terminator = sc->sc_bulk_send_next;
				if (pf_status.debug >= PF_DEBUG_MISC)
					printf("pfsync: received "
					    "bulk update request\n");
				pfsync_send_bus(sc, PFSYNC_BUS_START);
				timeout_add(&sc->sc_bulk_tmo, 1 * hz);
			} else {
				st = pf_find_state_byid(&id_key);
				if (st == NULL) {
					pfsyncstats.pfsyncs_badstate++;
					continue;
				}
				if (!st->sync_flags)
					pfsync_pack_state(PFSYNC_ACT_UPD,
					    st, 0);
			}
		}
		if (sc->sc_mbuf != NULL)
			pfsync_sendout(sc);
		splx(s);
		break;
	case PFSYNC_ACT_BUS:
		/* If we're not waiting for a bulk update, who cares. */
		if (sc->sc_ureq_sent == 0)
			break;

		if ((mp = m_pulldown(m, iplen + sizeof(*ph),
		    sizeof(*bus), &offp)) == NULL) {
			pfsyncstats.pfsyncs_badlen++;
			return;
		}
		bus = (struct pfsync_state_bus *)(mp->m_data + offp);
		switch (bus->status) {
		case PFSYNC_BUS_START:
			timeout_add(&sc->sc_bulkfail_tmo,
			    pf_pool_limits[PF_LIMIT_STATES].limit /
			    (PFSYNC_BULKPACKETS * sc->sc_maxcount));
			if (pf_status.debug >= PF_DEBUG_MISC)
				printf("pfsync: received bulk "
				    "update start\n");
			break;
		case PFSYNC_BUS_END:
			if (time_uptime - ntohl(bus->endtime) >=
			    sc->sc_ureq_sent) {
				/* that's it, we're happy */
				sc->sc_ureq_sent = 0;
				sc->sc_bulk_tries = 0;
				timeout_del(&sc->sc_bulkfail_tmo);
#if NCARP > 0
				if (!pfsync_sync_ok)
					carp_group_demote_adj(&sc->sc_if, -1);
#endif
				pfsync_sync_ok = 1;
				if (pf_status.debug >= PF_DEBUG_MISC)
					printf("pfsync: received valid "
					    "bulk update end\n");
			} else {
				if (pf_status.debug >= PF_DEBUG_MISC)
					printf("pfsync: received invalid "
					    "bulk update end: bad timestamp\n");
			}
			break;
		}
		break;
	case PFSYNC_ACT_TDB_UPD:
		if ((mp = m_pulldown(m, iplen + sizeof(*ph),
		    count * sizeof(*pt), &offp)) == NULL) {
			pfsyncstats.pfsyncs_badlen++;
			return;
		}
		s = splsoftnet();
		for (i = 0, pt = (struct pfsync_tdb *)(mp->m_data + offp);
		    i < count; i++, pt++)
			pfsync_update_net_tdb(pt);
		splx(s);
		break;
	}

done:
	if (m)
		m_freem(m);
}

int
pfsyncoutput(struct ifnet *ifp, struct mbuf *m, struct sockaddr *dst,
	struct rtentry *rt)
{
	m_freem(m);
	return (0);
}

/* ARGSUSED */
int
pfsyncioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
{
	struct proc *p = curproc;
	struct pfsync_softc *sc = ifp->if_softc;
	struct ifreq *ifr = (struct ifreq *)data;
	struct ip_moptions *imo = &sc->sc_imo;
	struct pfsyncreq pfsyncr;
	struct ifnet    *sifp;
	int s, error;

	switch (cmd) {
	case SIOCSIFADDR:
	case SIOCAIFADDR:
	case SIOCSIFDSTADDR:
	case SIOCSIFFLAGS:
		if (ifp->if_flags & IFF_UP)
			ifp->if_flags |= IFF_RUNNING;
		else
			ifp->if_flags &= ~IFF_RUNNING;
		break;
	case SIOCSIFMTU:
		if (ifr->ifr_mtu < PFSYNC_MINMTU)
			return (EINVAL);
		if (ifr->ifr_mtu > MCLBYTES)
			ifr->ifr_mtu = MCLBYTES;
		s = splnet();
		if (ifr->ifr_mtu < ifp->if_mtu)
			pfsync_sendout(sc);
		pfsync_setmtu(sc, ifr->ifr_mtu);
		splx(s);
		break;
	case SIOCGETPFSYNC:
		bzero(&pfsyncr, sizeof(pfsyncr));
		if (sc->sc_sync_ifp)
			strlcpy(pfsyncr.pfsyncr_syncdev,
			    sc->sc_sync_ifp->if_xname, IFNAMSIZ);
		pfsyncr.pfsyncr_syncpeer = sc->sc_sync_peer;
		pfsyncr.pfsyncr_maxupdates = sc->sc_maxupdates;
		if ((error = copyout(&pfsyncr, ifr->ifr_data, sizeof(pfsyncr))))
			return (error);
		break;
	case SIOCSETPFSYNC:
		if ((error = suser(p, p->p_acflag)) != 0)
			return (error);
		if ((error = copyin(ifr->ifr_data, &pfsyncr, sizeof(pfsyncr))))
			return (error);

		if (pfsyncr.pfsyncr_syncpeer.s_addr == 0)
			sc->sc_sync_peer.s_addr = INADDR_PFSYNC_GROUP;
		else
			sc->sc_sync_peer.s_addr =
			    pfsyncr.pfsyncr_syncpeer.s_addr;

		if (pfsyncr.pfsyncr_maxupdates > 255)
			return (EINVAL);
		sc->sc_maxupdates = pfsyncr.pfsyncr_maxupdates;

		if (pfsyncr.pfsyncr_syncdev[0] == 0) {
			sc->sc_sync_ifp = NULL;
			if (sc->sc_mbuf_net != NULL) {
				/* Don't keep stale pfsync packets around. */
				s = splnet();
				m_freem(sc->sc_mbuf_net);
				sc->sc_mbuf_net = NULL;
				sc->sc_statep_net.s = NULL;
				splx(s);
			}
			if (imo->imo_num_memberships > 0) {
				in_delmulti(imo->imo_membership[--imo->imo_num_memberships]);
				imo->imo_multicast_ifp = NULL;
			}
			break;
		}

		if ((sifp = ifunit(pfsyncr.pfsyncr_syncdev)) == NULL)
			return (EINVAL);

		s = splnet();
		if (sifp->if_mtu < sc->sc_if.if_mtu ||
		    (sc->sc_sync_ifp != NULL &&
		    sifp->if_mtu < sc->sc_sync_ifp->if_mtu) ||
		    sifp->if_mtu < MCLBYTES - sizeof(struct ip))
			pfsync_sendout(sc);
		sc->sc_sync_ifp = sifp;

		pfsync_setmtu(sc, sc->sc_if.if_mtu);

		if (imo->imo_num_memberships > 0) {
			in_delmulti(imo->imo_membership[--imo->imo_num_memberships]);
			imo->imo_multicast_ifp = NULL;
		}

		if (sc->sc_sync_ifp &&
		    sc->sc_sync_peer.s_addr == INADDR_PFSYNC_GROUP) {
			struct in_addr addr;

			if (!(sc->sc_sync_ifp->if_flags & IFF_MULTICAST)) {
				sc->sc_sync_ifp = NULL;
				splx(s);
				return (EADDRNOTAVAIL);
			}

			addr.s_addr = INADDR_PFSYNC_GROUP;

			if ((imo->imo_membership[0] =
			    in_addmulti(&addr, sc->sc_sync_ifp)) == NULL) {
				sc->sc_sync_ifp = NULL;
				splx(s);
				return (ENOBUFS);
			}
			imo->imo_num_memberships++;
			imo->imo_multicast_ifp = sc->sc_sync_ifp;
			imo->imo_multicast_ttl = PFSYNC_DFLTTL;
			imo->imo_multicast_loop = 0;
		}

		if (sc->sc_sync_ifp ||
		    sc->sc_sendaddr.s_addr != INADDR_PFSYNC_GROUP) {
			/* Request a full state table update. */
			sc->sc_ureq_sent = time_uptime;
#if NCARP > 0
			if (pfsync_sync_ok)
				carp_group_demote_adj(&sc->sc_if, 1);
#endif
			pfsync_sync_ok = 0;
			if (pf_status.debug >= PF_DEBUG_MISC)
				printf("pfsync: requesting bulk update\n");
			timeout_add(&sc->sc_bulkfail_tmo, 5 * hz);
			error = pfsync_request_update(NULL, NULL);
			if (error == ENOMEM) {
				splx(s);
				return (ENOMEM);
			}
			pfsync_sendout(sc);
		}
		splx(s);

		break;

	default:
		return (ENOTTY);
	}

	return (0);
}

void
pfsync_setmtu(struct pfsync_softc *sc, int mtu_req)
{
	int mtu;

	if (sc->sc_sync_ifp && sc->sc_sync_ifp->if_mtu < mtu_req)
		mtu = sc->sc_sync_ifp->if_mtu;
	else
		mtu = mtu_req;

	sc->sc_maxcount = (mtu - sizeof(struct pfsync_header)) /
	    sizeof(struct pfsync_state);
	if (sc->sc_maxcount > 254)
	    sc->sc_maxcount = 254;
	sc->sc_if.if_mtu = sizeof(struct pfsync_header) +
	    sc->sc_maxcount * sizeof(struct pfsync_state);
}

struct mbuf *
pfsync_get_mbuf(struct pfsync_softc *sc, u_int8_t action, void **sp)
{
	struct pfsync_header *h;
	struct mbuf *m;
	int len;

	MGETHDR(m, M_DONTWAIT, MT_DATA);
	if (m == NULL) {
		sc->sc_if.if_oerrors++;
		return (NULL);
	}

	switch (action) {
	case PFSYNC_ACT_CLR:
		len = sizeof(struct pfsync_header) +
		    sizeof(struct pfsync_state_clr);
		break;
	case PFSYNC_ACT_UPD_C:
		len = (sc->sc_maxcount * sizeof(struct pfsync_state_upd)) +
		    sizeof(struct pfsync_header);
		break;
	case PFSYNC_ACT_DEL_C:
		len = (sc->sc_maxcount * sizeof(struct pfsync_state_del)) +
		    sizeof(struct pfsync_header);
		break;
	case PFSYNC_ACT_UREQ:
		len = (sc->sc_maxcount * sizeof(struct pfsync_state_upd_req)) +
		    sizeof(struct pfsync_header);
		break;
	case PFSYNC_ACT_BUS:
		len = sizeof(struct pfsync_header) +
		    sizeof(struct pfsync_state_bus);
		break;
	case PFSYNC_ACT_TDB_UPD:
		len = (sc->sc_maxcount * sizeof(struct pfsync_tdb)) +
		    sizeof(struct pfsync_header);
		break;
	default:
		len = (sc->sc_maxcount * sizeof(struct pfsync_state)) +
		    sizeof(struct pfsync_header);
		break;
	}

	if (len > MHLEN) {
		MCLGET(m, M_DONTWAIT);
		if ((m->m_flags & M_EXT) == 0) {
			m_free(m);
			sc->sc_if.if_oerrors++;
			return (NULL);
		}
		m->m_data += (MCLBYTES - len) &~ (sizeof(long) - 1);
	} else
		MH_ALIGN(m, len);

	m->m_pkthdr.rcvif = NULL;
	m->m_pkthdr.len = m->m_len = sizeof(struct pfsync_header);
	h = mtod(m, struct pfsync_header *);
	h->version = PFSYNC_VERSION;
	h->af = 0;
	h->count = 0;
	h->action = action;
	if (action != PFSYNC_ACT_TDB_UPD)
		bcopy(&pf_status.pf_chksum, &h->pf_chksum,
		    PF_MD5_DIGEST_LENGTH);

	*sp = (void *)((char *)h + PFSYNC_HDRLEN);
	if (action == PFSYNC_ACT_TDB_UPD)
		timeout_add(&sc->sc_tdb_tmo, hz);
	else
		timeout_add(&sc->sc_tmo, hz);
	return (m);
}

int
pfsync_pack_state(u_int8_t action, struct pf_state *st, int flags)
{
	struct ifnet *ifp = NULL;
	struct pfsync_softc *sc = pfsyncif;
	struct pfsync_header *h, *h_net;
	struct pfsync_state *sp = NULL;
	struct pfsync_state_upd *up = NULL;
	struct pfsync_state_del *dp = NULL;
	struct pf_state_key *sk = st->state_key;
	struct pf_rule *r;
	u_long secs;
	int s, ret = 0;
	u_int8_t i = 255, newaction = 0;

	if (sc == NULL)
		return (0);
	ifp = &sc->sc_if;

	/*
	 * If a packet falls in the forest and there's nobody around to
	 * hear, does it make a sound?
	 */
	if (ifp->if_bpf == NULL && sc->sc_sync_ifp == NULL &&
	    sc->sc_sync_peer.s_addr == INADDR_PFSYNC_GROUP) {
		/* Don't leave any stale pfsync packets hanging around. */
		if (sc->sc_mbuf != NULL) {
			m_freem(sc->sc_mbuf);
			sc->sc_mbuf = NULL;
			sc->sc_statep.s = NULL;
		}
		return (0);
	}

	if (action >= PFSYNC_ACT_MAX)
		return (EINVAL);

	s = splnet();
	if (sc->sc_mbuf == NULL) {
		if ((sc->sc_mbuf = pfsync_get_mbuf(sc, action,
		    (void *)&sc->sc_statep.s)) == NULL) {
			splx(s);
			return (ENOMEM);
		}
		h = mtod(sc->sc_mbuf, struct pfsync_header *);
	} else {
		h = mtod(sc->sc_mbuf, struct pfsync_header *);
		if (h->action != action) {
			pfsync_sendout(sc);
			if ((sc->sc_mbuf = pfsync_get_mbuf(sc, action,
			    (void *)&sc->sc_statep.s)) == NULL) {
				splx(s);
				return (ENOMEM);
			}
			h = mtod(sc->sc_mbuf, struct pfsync_header *);
		} else {
			/*
			 * If it's an update, look in the packet to see if
			 * we already have an update for the state.
			 */
			if (action == PFSYNC_ACT_UPD && sc->sc_maxupdates) {
				struct pfsync_state *usp =
				    (void *)((char *)h + PFSYNC_HDRLEN);

				for (i = 0; i < h->count; i++) {
					if (!memcmp(usp->id, &st->id,
					    PFSYNC_ID_LEN) &&
					    usp->creatorid == st->creatorid) {
						sp = usp;
						sp->updates++;
						break;
					}
					usp++;
				}
			}
		}
	}

	secs = time_second;

	st->pfsync_time = time_uptime;

	if (sp == NULL) {
		/* not a "duplicate" update */
		i = 255;
		sp = sc->sc_statep.s++;
		sc->sc_mbuf->m_pkthdr.len =
		    sc->sc_mbuf->m_len += sizeof(struct pfsync_state);
		h->count++;
		bzero(sp, sizeof(*sp));

		bcopy(&st->id, sp->id, sizeof(sp->id));
		sp->creatorid = st->creatorid;

		strlcpy(sp->ifname, st->u.s.kif->pfik_name, sizeof(sp->ifname));
		pf_state_host_hton(&sk->lan, &sp->lan);
		pf_state_host_hton(&sk->gwy, &sp->gwy);
		pf_state_host_hton(&sk->ext, &sp->ext);

		bcopy(&st->rt_addr, &sp->rt_addr, sizeof(sp->rt_addr));

		sp->creation = htonl(secs - st->creation);
		pf_state_counter_hton(st->packets[0], sp->packets[0]);
		pf_state_counter_hton(st->packets[1], sp->packets[1]);
		pf_state_counter_hton(st->bytes[0], sp->bytes[0]);
		pf_state_counter_hton(st->bytes[1], sp->bytes[1]);
		if ((r = st->rule.ptr) == NULL)
			sp->rule = htonl(-1);
		else
			sp->rule = htonl(r->nr);
		if ((r = st->anchor.ptr) == NULL)
			sp->anchor = htonl(-1);
		else
			sp->anchor = htonl(r->nr);
		sp->af = sk->af;
		sp->proto = sk->proto;
		sp->direction = sk->direction;
		sp->log = st->log;
		sp->allow_opts = st->allow_opts;
		sp->timeout = st->timeout;

		if (flags & PFSYNC_FLAG_STALE)
			sp->sync_flags |= PFSTATE_STALE;
	}

	pf_state_peer_hton(&st->src, &sp->src);
	pf_state_peer_hton(&st->dst, &sp->dst);

	if (st->expire <= secs)
		sp->expire = htonl(0);
	else
		sp->expire = htonl(st->expire - secs);

	/* do we need to build "compressed" actions for network transfer? */
	if (sc->sc_sync_ifp && flags & PFSYNC_FLAG_COMPRESS) {
		switch (action) {
		case PFSYNC_ACT_UPD:
			newaction = PFSYNC_ACT_UPD_C;
			break;
		case PFSYNC_ACT_DEL:
			newaction = PFSYNC_ACT_DEL_C;
			break;
		default:
			/* by default we just send the uncompressed states */
			break;
		}
	}

	if (newaction) {
		if (sc->sc_mbuf_net == NULL) {
			if ((sc->sc_mbuf_net = pfsync_get_mbuf(sc, newaction,
			    (void *)&sc->sc_statep_net.s)) == NULL) {
				splx(s);
				return (ENOMEM);
			}
		}
		h_net = mtod(sc->sc_mbuf_net, struct pfsync_header *);

		switch (newaction) {
		case PFSYNC_ACT_UPD_C:
			if (i != 255) {
				up = (void *)((char *)h_net +
				    PFSYNC_HDRLEN + (i * sizeof(*up)));
				up->updates++;
			} else {
				h_net->count++;
				sc->sc_mbuf_net->m_pkthdr.len =
				    sc->sc_mbuf_net->m_len += sizeof(*up);
				up = sc->sc_statep_net.u++;

				bzero(up, sizeof(*up));
				bcopy(&st->id, up->id, sizeof(up->id));
				up->creatorid = st->creatorid;
			}
			up->timeout = st->timeout;
			up->expire = sp->expire;
			up->src = sp->src;
			up->dst = sp->dst;
			break;
		case PFSYNC_ACT_DEL_C:
			sc->sc_mbuf_net->m_pkthdr.len =
			    sc->sc_mbuf_net->m_len += sizeof(*dp);
			dp = sc->sc_statep_net.d++;
			h_net->count++;

			bzero(dp, sizeof(*dp));
			bcopy(&st->id, dp->id, sizeof(dp->id));
			dp->creatorid = st->creatorid;
			break;
		}
	}

	if (h->count == sc->sc_maxcount ||
	    (sc->sc_maxupdates && (sp->updates >= sc->sc_maxupdates)))
		ret = pfsync_sendout(sc);

	splx(s);
	return (ret);
}

/* This must be called in splnet() */
int
pfsync_request_update(struct pfsync_state_upd *up, struct in_addr *src)
{
	struct ifnet *ifp = NULL;
	struct pfsync_header *h;
	struct pfsync_softc *sc = pfsyncif;
	struct pfsync_state_upd_req *rup;
	int ret = 0;

	if (sc == NULL)
		return (0);

	ifp = &sc->sc_if;
	if (sc->sc_mbuf == NULL) {
		if ((sc->sc_mbuf = pfsync_get_mbuf(sc, PFSYNC_ACT_UREQ,
		    (void *)&sc->sc_statep.s)) == NULL)
			return (ENOMEM);
		h = mtod(sc->sc_mbuf, struct pfsync_header *);
	} else {
		h = mtod(sc->sc_mbuf, struct pfsync_header *);
		if (h->action != PFSYNC_ACT_UREQ) {
			pfsync_sendout(sc);
			if ((sc->sc_mbuf = pfsync_get_mbuf(sc, PFSYNC_ACT_UREQ,
			    (void *)&sc->sc_statep.s)) == NULL)
				return (ENOMEM);
			h = mtod(sc->sc_mbuf, struct pfsync_header *);
		}
	}

	if (src != NULL)
		sc->sc_sendaddr = *src;
	sc->sc_mbuf->m_pkthdr.len = sc->sc_mbuf->m_len += sizeof(*rup);
	h->count++;
	rup = sc->sc_statep.r++;
	bzero(rup, sizeof(*rup));
	if (up != NULL) {
		bcopy(up->id, rup->id, sizeof(rup->id));
		rup->creatorid = up->creatorid;
	}

	if (h->count == sc->sc_maxcount)
		ret = pfsync_sendout(sc);

	return (ret);
}

int
pfsync_clear_states(u_int32_t creatorid, char *ifname)
{
	struct ifnet *ifp = NULL;
	struct pfsync_softc *sc = pfsyncif;
	struct pfsync_state_clr *cp;
	int s, ret;

	if (sc == NULL)
		return (0);

	ifp = &sc->sc_if;
	s = splnet();
	if (sc->sc_mbuf != NULL)
		pfsync_sendout(sc);
	if ((sc->sc_mbuf = pfsync_get_mbuf(sc, PFSYNC_ACT_CLR,
	    (void *)&sc->sc_statep.c)) == NULL) {
		splx(s);
		return (ENOMEM);
	}
	sc->sc_mbuf->m_pkthdr.len = sc->sc_mbuf->m_len += sizeof(*cp);
	cp = sc->sc_statep.c;
	cp->creatorid = creatorid;
	if (ifname != NULL)
		strlcpy(cp->ifname, ifname, IFNAMSIZ);

	ret = (pfsync_sendout(sc));
	splx(s);
	return (ret);
}

void
pfsync_timeout(void *v)
{
	struct pfsync_softc *sc = v;
	int s;

	s = splnet();
	pfsync_sendout(sc);
	splx(s);
}

void
pfsync_tdb_timeout(void *v)
{
	struct pfsync_softc *sc = v;
	int s;

	s = splnet();
	pfsync_tdb_sendout(sc);
	splx(s);
}

/* This must be called in splnet() */
void
pfsync_send_bus(struct pfsync_softc *sc, u_int8_t status)
{
	struct pfsync_state_bus *bus;

	if (sc->sc_mbuf != NULL)
		pfsync_sendout(sc);

	if (pfsync_sync_ok &&
	    (sc->sc_mbuf = pfsync_get_mbuf(sc, PFSYNC_ACT_BUS,
	    (void *)&sc->sc_statep.b)) != NULL) {
		sc->sc_mbuf->m_pkthdr.len = sc->sc_mbuf->m_len += sizeof(*bus);
		bus = sc->sc_statep.b;
		bus->creatorid = pf_status.hostid;
		bus->status = status;
		bus->endtime = htonl(time_uptime - sc->sc_ureq_received);
		pfsync_sendout(sc);
	}
}

void
pfsync_bulk_update(void *v)
{
	struct pfsync_softc *sc = v;
	int s, i = 0;
	struct pf_state *state;

	s = splnet();
	if (sc->sc_mbuf != NULL)
		pfsync_sendout(sc);

	/*
	 * Grab at most PFSYNC_BULKPACKETS worth of states which have not
	 * been sent since the latest request was made.
	 */
	state = sc->sc_bulk_send_next;
	if (state)
		do {
			/* send state update if syncable and not already sent */
			if (!state->sync_flags
			    && state->timeout < PFTM_MAX
			    && state->pfsync_time <= sc->sc_ureq_received) {
				pfsync_pack_state(PFSYNC_ACT_UPD, state, 0);
				i++;
			}

			/* figure next state to send */
			state = TAILQ_NEXT(state, u.s.entry_list);

			/* wrap to start of list if we hit the end */
			if (!state)
				state = TAILQ_FIRST(&state_list);
		} while (i < sc->sc_maxcount * PFSYNC_BULKPACKETS &&
		    state != sc->sc_bulk_terminator);

	if (!state || state == sc->sc_bulk_terminator) {
		/* we're done */
		pfsync_send_bus(sc, PFSYNC_BUS_END);
		sc->sc_ureq_received = 0;
		sc->sc_bulk_send_next = NULL;
		sc->sc_bulk_terminator = NULL;
		timeout_del(&sc->sc_bulk_tmo);
		if (pf_status.debug >= PF_DEBUG_MISC)
			printf("pfsync: bulk update complete\n");
	} else {
		/* look again for more in a bit */
		timeout_add(&sc->sc_bulk_tmo, 1);
		sc->sc_bulk_send_next = state;
	}
	if (sc->sc_mbuf != NULL)
		pfsync_sendout(sc);
	splx(s);
}

void
pfsync_bulkfail(void *v)
{
	struct pfsync_softc *sc = v;
	int s, error;

	if (sc->sc_bulk_tries++ < PFSYNC_MAX_BULKTRIES) {
		/* Try again in a bit */
		timeout_add(&sc->sc_bulkfail_tmo, 5 * hz);
		s = splnet();
		error = pfsync_request_update(NULL, NULL);
		if (error == ENOMEM) {
			if (pf_status.debug >= PF_DEBUG_MISC)
				printf("pfsync: cannot allocate mbufs for "
				    "bulk update\n");
		} else
			pfsync_sendout(sc);
		splx(s);
	} else {
		/* Pretend like the transfer was ok */
		sc->sc_ureq_sent = 0;
		sc->sc_bulk_tries = 0;
#if NCARP > 0
		if (!pfsync_sync_ok)
			carp_group_demote_adj(&sc->sc_if, -1);
#endif
		pfsync_sync_ok = 1;
		if (pf_status.debug >= PF_DEBUG_MISC)
			printf("pfsync: failed to receive "
			    "bulk update status\n");
		timeout_del(&sc->sc_bulkfail_tmo);
	}
}

/* This must be called in splnet() */
int
pfsync_sendout(struct pfsync_softc *sc)
{
#if NBPFILTER > 0
	struct ifnet *ifp = &sc->sc_if;
#endif
	struct mbuf *m;

	timeout_del(&sc->sc_tmo);

	if (sc->sc_mbuf == NULL)
		return (0);
	m = sc->sc_mbuf;
	sc->sc_mbuf = NULL;
	sc->sc_statep.s = NULL;

#if NBPFILTER > 0
	if (ifp->if_bpf)
		bpf_mtap(ifp->if_bpf, m, BPF_DIRECTION_OUT);
#endif

	if (sc->sc_mbuf_net) {
		m_freem(m);
		m = sc->sc_mbuf_net;
		sc->sc_mbuf_net = NULL;
		sc->sc_statep_net.s = NULL;
	}

	return pfsync_sendout_mbuf(sc, m);
}

int
pfsync_tdb_sendout(struct pfsync_softc *sc)
{
#if NBPFILTER > 0
	struct ifnet *ifp = &sc->sc_if;
#endif
	struct mbuf *m;

	timeout_del(&sc->sc_tdb_tmo);

	if (sc->sc_mbuf_tdb == NULL)
		return (0);
	m = sc->sc_mbuf_tdb;
	sc->sc_mbuf_tdb = NULL;
	sc->sc_statep_tdb.t = NULL;

#if NBPFILTER > 0
	if (ifp->if_bpf)
		bpf_mtap(ifp->if_bpf, m, BPF_DIRECTION_OUT);
#endif

	return pfsync_sendout_mbuf(sc, m);
}

int
pfsync_sendout_mbuf(struct pfsync_softc *sc, struct mbuf *m)
{
	struct sockaddr sa;
	struct ip *ip;

	if (sc->sc_sync_ifp ||
	    sc->sc_sync_peer.s_addr != INADDR_PFSYNC_GROUP) {
		M_PREPEND(m, sizeof(struct ip), M_DONTWAIT);
		if (m == NULL) {
			pfsyncstats.pfsyncs_onomem++;
			return (0);
		}
		ip = mtod(m, struct ip *);
		ip->ip_v = IPVERSION;
		ip->ip_hl = sizeof(*ip) >> 2;
		ip->ip_tos = IPTOS_LOWDELAY;
		ip->ip_len = htons(m->m_pkthdr.len);
		ip->ip_id = htons(ip_randomid());
		ip->ip_off = htons(IP_DF);
		ip->ip_ttl = PFSYNC_DFLTTL;
		ip->ip_p = IPPROTO_PFSYNC;
		ip->ip_sum = 0;

		bzero(&sa, sizeof(sa));
		ip->ip_src.s_addr = INADDR_ANY;

		if (sc->sc_sendaddr.s_addr == INADDR_PFSYNC_GROUP)
			m->m_flags |= M_MCAST;
		ip->ip_dst = sc->sc_sendaddr;
		sc->sc_sendaddr.s_addr = sc->sc_sync_peer.s_addr;

		pfsyncstats.pfsyncs_opackets++;

		if (ip_output(m, NULL, NULL, IP_RAWOUTPUT, &sc->sc_imo, NULL))
			pfsyncstats.pfsyncs_oerrors++;
	} else
		m_freem(m);

	return (0);
}

/* Update an in-kernel tdb. Silently fail if no tdb is found. */
void
pfsync_update_net_tdb(struct pfsync_tdb *pt)
{
	struct tdb		*tdb;
	int			 s;

	/* check for invalid values */
	if (ntohl(pt->spi) <= SPI_RESERVED_MAX ||
	    (pt->dst.sa.sa_family != AF_INET &&
	     pt->dst.sa.sa_family != AF_INET6))
		goto bad;

	s = spltdb();
	tdb = gettdb(pt->spi, &pt->dst, pt->sproto);
	if (tdb) {
		pt->rpl = ntohl(pt->rpl);
		pt->cur_bytes = betoh64(pt->cur_bytes);

		/* Neither replay nor byte counter should ever decrease. */
		if (pt->rpl < tdb->tdb_rpl ||
		    pt->cur_bytes < tdb->tdb_cur_bytes) {
			splx(s);
			goto bad;
		}

		tdb->tdb_rpl = pt->rpl;
		tdb->tdb_cur_bytes = pt->cur_bytes;
	}
	splx(s);
	return;

 bad:
	if (pf_status.debug >= PF_DEBUG_MISC)
		printf("pfsync_insert: PFSYNC_ACT_TDB_UPD: "
		    "invalid value\n");
	pfsyncstats.pfsyncs_badstate++;
	return;
}

/* One of our local tdbs have been updated, need to sync rpl with others */
int
pfsync_update_tdb(struct tdb *tdb, int output)
{
	struct ifnet *ifp = NULL;
	struct pfsync_softc *sc = pfsyncif;
	struct pfsync_header *h;
	struct pfsync_tdb *pt = NULL;
	int s, i, ret;

	if (sc == NULL)
		return (0);

	ifp = &sc->sc_if;
	if (ifp->if_bpf == NULL && sc->sc_sync_ifp == NULL &&
	    sc->sc_sync_peer.s_addr == INADDR_PFSYNC_GROUP) {
		/* Don't leave any stale pfsync packets hanging around. */
		if (sc->sc_mbuf_tdb != NULL) {
			m_freem(sc->sc_mbuf_tdb);
			sc->sc_mbuf_tdb = NULL;
			sc->sc_statep_tdb.t = NULL;
		}
		return (0);
	}

	s = splnet();
	if (sc->sc_mbuf_tdb == NULL) {
		if ((sc->sc_mbuf_tdb = pfsync_get_mbuf(sc, PFSYNC_ACT_TDB_UPD,
		    (void *)&sc->sc_statep_tdb.t)) == NULL) {
			splx(s);
			return (ENOMEM);
		}
		h = mtod(sc->sc_mbuf_tdb, struct pfsync_header *);
	} else {
		h = mtod(sc->sc_mbuf_tdb, struct pfsync_header *);
		if (h->action != PFSYNC_ACT_TDB_UPD) {
			/*
			 * XXX will never happen as long as there's
			 * only one "TDB action".
			 */
			pfsync_tdb_sendout(sc);
			sc->sc_mbuf_tdb = pfsync_get_mbuf(sc,
			    PFSYNC_ACT_TDB_UPD, (void *)&sc->sc_statep_tdb.t);
			if (sc->sc_mbuf_tdb == NULL) {
				splx(s);
				return (ENOMEM);
			}
			h = mtod(sc->sc_mbuf_tdb, struct pfsync_header *);
		} else if (sc->sc_maxupdates) {
			/*
			 * If it's an update, look in the packet to see if
			 * we already have an update for the state.
			 */
			struct pfsync_tdb *u =
			    (void *)((char *)h + PFSYNC_HDRLEN);

			for (i = 0; !pt && i < h->count; i++) {
				if (tdb->tdb_spi == u->spi &&
				    tdb->tdb_sproto == u->sproto &&
			            !bcmp(&tdb->tdb_dst, &u->dst,
				    SA_LEN(&u->dst.sa))) {
					pt = u;
					pt->updates++;
				}
				u++;
			}
		}
	}

	if (pt == NULL) {
		/* not a "duplicate" update */
		pt = sc->sc_statep_tdb.t++;
		sc->sc_mbuf_tdb->m_pkthdr.len =
		    sc->sc_mbuf_tdb->m_len += sizeof(struct pfsync_tdb);
		h->count++;
		bzero(pt, sizeof(*pt));

		pt->spi = tdb->tdb_spi;
		memcpy(&pt->dst, &tdb->tdb_dst, sizeof pt->dst);
		pt->sproto = tdb->tdb_sproto;
	}

	/*
	 * When a failover happens, the master's rpl is probably above
	 * what we see here (we may be up to a second late), so
	 * increase it a bit for outbound tdbs to manage most such
	 * situations.
	 *
	 * For now, just add an offset that is likely to be larger
	 * than the number of packets we can see in one second. The RFC
	 * just says the next packet must have a higher seq value.
	 *
	 * XXX What is a good algorithm for this? We could use
	 * a rate-determined increase, but to know it, we would have
	 * to extend struct tdb.
	 * XXX pt->rpl can wrap over MAXINT, but if so the real tdb
	 * will soon be replaced anyway. For now, just don't handle
	 * this edge case.
	 */
#define RPL_INCR 16384
	pt->rpl = htonl(tdb->tdb_rpl + (output ? RPL_INCR : 0));
	pt->cur_bytes = htobe64(tdb->tdb_cur_bytes);

	if (h->count == sc->sc_maxcount ||
	    (sc->sc_maxupdates && (pt->updates >= sc->sc_maxupdates)))
		ret = pfsync_tdb_sendout(sc);

	splx(s);
	return (ret);
}