summaryrefslogtreecommitdiffstats
path: root/vrrpd/vrrp.c
blob: 658dc098a2f54631eee5a30c85a6c03ba801546b (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
/*
 * VRRP global definitions and state machine.
 * Copyright (C) 2018-2019 Cumulus Networks, Inc.
 * Quentin Young
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation; either version 2 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; see the file COPYING; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
 */
#include <zebra.h>

#include "lib/hash.h"
#include "lib/hook.h"
#include "lib/if.h"
#include "lib/linklist.h"
#include "lib/memory.h"
#include "lib/network.h"
#include "lib/prefix.h"
#include "lib/sockopt.h"
#include "lib/sockunion.h"
#include "lib/vrf.h"
#include "lib/vty.h"

#include "vrrp.h"
#include "vrrp_arp.h"
#include "vrrp_debug.h"
#include "vrrp_memory.h"
#include "vrrp_ndisc.h"
#include "vrrp_packet.h"
#include "vrrp_zebra.h"

#define VRRP_LOGPFX "[CORE] "

/* statics */
struct hash *vrrp_vrouters_hash;
bool vrrp_autoconfig_is_on;
int vrrp_autoconfig_version;

const char *vrrp_state_names[3] = {
	[VRRP_STATE_INITIALIZE] = "Initialize",
	[VRRP_STATE_MASTER] = "Master",
	[VRRP_STATE_BACKUP] = "Backup",
};

const char *vrrp_event_names[2] = {
	[VRRP_EVENT_STARTUP] = "Startup",
	[VRRP_EVENT_SHUTDOWN] = "Shutdown",
};


/* Utility functions ------------------------------------------------------- */

/*
 * Sets an ethaddr to RFC-defined Virtual Router MAC address.
 *
 * mac
 *    ethaddr to set
 *
 * v6
 *    Whether this is a V6 or V4 Virtual Router MAC
 *
 * vrid
 *    Virtual Router Identifier
 */
static void vrrp_mac_set(struct ethaddr *mac, bool v6, uint8_t vrid)
{
	/*
	 * V4: 00-00-5E-00-01-{VRID}
	 * V6: 00-00-5E-00-02-{VRID}
	 */
	mac->octet[0] = 0x00;
	mac->octet[1] = 0x00;
	mac->octet[2] = 0x5E;
	mac->octet[3] = 0x00;
	mac->octet[4] = v6 ? 0x02 : 0x01;
	mac->octet[5] = vrid;
}

/*
 * Recalculates and sets skew_time and master_down_interval based
 * values.
 *
 * r
 *   VRRP Router to operate on
 */
static void vrrp_recalculate_timers(struct vrrp_router *r)
{
	uint16_t skm = (r->vr->version == 3) ? r->master_adver_interval : 1;
	r->skew_time = ((256 - r->vr->priority) * skm) / 256;
	r->master_down_interval = (3 * r->master_adver_interval);
	r->master_down_interval += r->skew_time;
}

/*
 * Determines if a VRRP router is the owner of the specified address.
 *
 * The determining factor for whether an interface is the address owner is
 * simply whether the address is assigned to the VRRP subinterface by someone
 * other than vrrpd.
 *
 * This function should always return the correct answer regardless of
 * master/backup status.
 *
 * vr
 *    Virtual Router
 *
 * Returns:
 *    whether or not vr owns the specified address
 */
static bool vrrp_is_owner(struct interface *ifp, struct ipaddr *addr)
{
	struct prefix p;

	p.family = IS_IPADDR_V4(addr) ? AF_INET : AF_INET6;
	p.prefixlen = IS_IPADDR_V4(addr) ? IPV4_MAX_BITLEN : IPV6_MAX_BITLEN;
	memcpy(&p.u, &addr->ip, sizeof(addr->ip));

	return !!connected_lookup_prefix_exact(ifp, &p);
}

/* Configuration controllers ----------------------------------------------- */

void vrrp_set_priority(struct vrrp_vrouter *vr, uint8_t priority)
{
	vr->priority = priority;
	vr->v4->priority = priority;
	vr->v6->priority = priority;
}

void vrrp_set_advertisement_interval(struct vrrp_vrouter *vr,
				     uint16_t advertisement_interval)
{
	if (vr->advertisement_interval == advertisement_interval)
		return;

	vr->advertisement_interval = advertisement_interval;
	vrrp_recalculate_timers(vr->v4);
	vrrp_recalculate_timers(vr->v6);
}

static bool vrrp_has_ip(struct vrrp_vrouter *vr, struct ipaddr *ip)
{
	struct vrrp_router *r = ip->ipa_type == IPADDR_V4 ? vr->v4 : vr->v6;
	struct listnode *ln;
	struct ipaddr *iter;

	for (ALL_LIST_ELEMENTS_RO(r->addrs, ln, iter))
		if (!memcmp(&iter->ip, &ip->ip, IPADDRSZ(ip)))
			return true;

	return false;
}

int vrrp_add_ip(struct vrrp_router *r, struct ipaddr *ip, bool activate)
{
	int af = (ip->ipa_type == IPADDR_V6) ? AF_INET6 : AF_INET;

	assert(r->family == af);

	if (vrrp_has_ip(r->vr, ip))
		return 0;

	if (!vrrp_is_owner(r->vr->ifp, ip) && r->is_owner) {
		char ipbuf[INET6_ADDRSTRLEN];
		inet_ntop(r->family, &ip->ip, ipbuf, sizeof(ipbuf));
		zlog_err(
			VRRP_LOGPFX VRRP_LOGPFX_VRID
			"This VRRP router is not the address owner of %s, but is the address owner of other addresses; this config is unsupported.",
			r->vr->vrid, ipbuf);
		return -1;
	}

	struct ipaddr *new = XCALLOC(MTYPE_VRRP_IP, sizeof(struct ipaddr));

	*new = *ip;
	listnode_add(r->addrs, new);

	bool do_activate = (activate && r->fsm.state == VRRP_STATE_INITIALIZE);
	int ret = 0;

	if (do_activate) {
		ret = vrrp_event(r, VRRP_EVENT_STARTUP);
		if (ret)
			listnode_delete(r->addrs, new);
	}
	else if (r->fsm.state == VRRP_STATE_MASTER) {
		switch (r->family) {
		case AF_INET:
			vrrp_garp_send(r, &new->ipaddr_v4);
			break;
		case AF_INET6:
			vrrp_ndisc_una_send(r, new);
			break;
		}
	}

	return ret;
}

int vrrp_add_ipv4(struct vrrp_vrouter *vr, struct in_addr v4, bool activate)
{
	struct ipaddr ip;
	ip.ipa_type = IPADDR_V4;
	ip.ipaddr_v4 = v4;
	return vrrp_add_ip(vr->v4, &ip, activate);
}

int vrrp_add_ipv6(struct vrrp_vrouter *vr, struct in6_addr v6, bool activate)
{
	struct ipaddr ip;
	ip.ipa_type = IPADDR_V6;
	ip.ipaddr_v6 = v6;
	return vrrp_add_ip(vr->v6, &ip, activate);
}

int vrrp_del_ip(struct vrrp_router *r, struct ipaddr *ip, bool deactivate)
{
	struct listnode *ln, *nn;
	struct ipaddr *iter;
	int ret = 0;

	if (!vrrp_has_ip(r->vr, ip))
		return 0;

	if (deactivate && r->addrs->count == 1
	    && r->fsm.state != VRRP_STATE_INITIALIZE)
		ret = vrrp_event(r, VRRP_EVENT_SHUTDOWN);

	/*
	 * Don't delete IP if we failed to deactivate, otherwise we'll run into
	 * issues later trying to build a VRRP advertisement with no IPs
	 */
	if (ret == 0) {
		for (ALL_LIST_ELEMENTS(r->addrs, ln, nn, iter))
			if (!memcmp(&iter->ip, &ip->ip, IPADDRSZ(ip)))
				list_delete_node(r->addrs, ln);
	}

	return ret;
}

int vrrp_del_ipv6(struct vrrp_vrouter *vr, struct in6_addr v6, bool deactivate)
{
	struct ipaddr ip;
	ip.ipa_type = IPADDR_V6;
	ip.ipaddr_v6 = v6;
	return vrrp_del_ip(vr->v6, &ip, deactivate);
}

int vrrp_del_ipv4(struct vrrp_vrouter *vr, struct in_addr v4, bool deactivate)
{
	struct ipaddr ip;
	ip.ipa_type = IPADDR_V4;
	ip.ipaddr_v4 = v4;
	return vrrp_del_ip(vr->v4, &ip, deactivate);
}


/* Creation and destruction ------------------------------------------------ */

static void vrrp_router_addr_list_del_cb(void *val)
{
	struct ipaddr *ip = val;
	XFREE(MTYPE_VRRP_IP, ip);
}

/*
 * Search for a suitable macvlan subinterface we can attach to, and if found,
 * attach to it.
 *
 * r
 *    Router to attach to interface
 *
 * Returns:
 *    Whether an interface was successfully attached
 */
static bool vrrp_attach_interface(struct vrrp_router *r)
{
	/* Search for existing interface with computed MAC address */
	struct interface **ifps;
	size_t ifps_cnt = if_lookup_by_hwaddr(
		r->vmac.octet, sizeof(r->vmac.octet), &ifps, VRF_DEFAULT);

	/*
	 * Filter to only those macvlan interfaces whose parent is the base
	 * interface this VRRP router is configured on.
	 *
	 * If there are still multiple interfaces we just select the first one,
	 * as it should be functionally identical to the others.
	 */
	unsigned int candidates = 0;
	struct interface *selection = NULL;
	for (unsigned int i = 0; i < ifps_cnt; i++) {
		if (ifps[i]->link_ifindex != r->vr->ifp->ifindex
		    || !CHECK_FLAG(ifps[i]->flags, IFF_UP))
			ifps[i] = NULL;
		else {
			selection = selection ? selection : ifps[i];
			candidates++;
		}
	}

	if (ifps_cnt)
		XFREE(MTYPE_TMP, ifps);

	char ethstr[ETHER_ADDR_STRLEN];
	prefix_mac2str(&r->vmac, ethstr, sizeof(ethstr));

	assert(!!selection == !!candidates);

	if (candidates == 0)
		zlog_warn(VRRP_LOGPFX VRRP_LOGPFX_VRID
			  "No interface found w/ MAC %s",
			  r->vr->vrid, ethstr);
	else if (candidates > 1)
		zlog_warn(VRRP_LOGPFX VRRP_LOGPFX_VRID
			  "Multiple VRRP interfaces found; using %s",
			  r->vr->vrid, selection->name);
	else
		zlog_info(VRRP_LOGPFX VRRP_LOGPFX_VRID "Selected %s",
			  r->vr->vrid, selection->name);

	r->mvl_ifp = selection;

	return !!r->mvl_ifp;

}

static struct vrrp_router *vrrp_router_create(struct vrrp_vrouter *vr,
					      int family)
{
	struct vrrp_router *r =
		XCALLOC(MTYPE_VRRP_RTR, sizeof(struct vrrp_router));

	r->family = family;
	r->sock_rx = -1;
	r->sock_tx = -1;
	r->vr = vr;
	r->addrs = list_new();
	r->addrs->del = vrrp_router_addr_list_del_cb;
	r->priority = vr->priority;
	r->fsm.state = VRRP_STATE_INITIALIZE;
	vrrp_mac_set(&r->vmac, family == AF_INET6, vr->vrid);

	vrrp_attach_interface(r);

	return r;
}

static void vrrp_router_destroy(struct vrrp_router *r)
{
	if (r->is_active)
		vrrp_event(r, VRRP_EVENT_SHUTDOWN);

	if (r->sock_rx >= 0)
		close(r->sock_rx);
	if (r->sock_tx >= 0)
		close(r->sock_tx);

	/* FIXME: also delete list elements */
	list_delete(&r->addrs);
	XFREE(MTYPE_VRRP_RTR, r);
}

struct vrrp_vrouter *vrrp_vrouter_create(struct interface *ifp, uint8_t vrid,
					 uint8_t version)
{
	struct vrrp_vrouter *vr = vrrp_lookup(ifp, vrid);

	if (vr)
		return vr;

	if (version != 2 && version != 3)
		return NULL;

	vr = XCALLOC(MTYPE_VRRP_RTR, sizeof(struct vrrp_vrouter));

	vr->ifp = ifp;
	vr->version = version;
	vr->vrid = vrid;
	vr->priority = VRRP_DEFAULT_PRIORITY;
	vr->preempt_mode = true;
	vr->accept_mode = false;

	vr->v4 = vrrp_router_create(vr, AF_INET);
	vr->v6 = vrrp_router_create(vr, AF_INET6);

	vrrp_set_advertisement_interval(vr, VRRP_DEFAULT_ADVINT);

	hash_get(vrrp_vrouters_hash, vr, hash_alloc_intern);

	return vr;
}

void vrrp_vrouter_destroy(struct vrrp_vrouter *vr)
{
	vrrp_router_destroy(vr->v4);
	vrrp_router_destroy(vr->v6);
	hash_release(vrrp_vrouters_hash, vr);
	XFREE(MTYPE_VRRP_RTR, vr);
}

struct vrrp_vrouter *vrrp_lookup(struct interface *ifp, uint8_t vrid)
{
	struct vrrp_vrouter vr;
	vr.vrid = vrid;
	vr.ifp = ifp;

	return hash_lookup(vrrp_vrouters_hash, &vr);
}

/* Network ----------------------------------------------------------------- */

/* Forward decls */
static void vrrp_change_state(struct vrrp_router *r, int to);
static int vrrp_adver_timer_expire(struct thread *thread);
static int vrrp_master_down_timer_expire(struct thread *thread);

/*
 * Create and multicast a VRRP ADVERTISEMENT message.
 *
 * r
 *    VRRP Router for which to send ADVERTISEMENT
 */
static void vrrp_send_advertisement(struct vrrp_router *r)
{
	struct vrrp_pkt *pkt;
	ssize_t pktsz;
	struct ipaddr *addrs[r->addrs->count];
	union sockunion dest;

	list_to_array(r->addrs, (void **)addrs, r->addrs->count);

	pktsz = vrrp_pkt_adver_build(&pkt, &r->src, r->vr->version, r->vr->vrid,
				     r->priority, r->vr->advertisement_interval,
				     r->addrs->count, (struct ipaddr **)&addrs);

	if (DEBUG_MODE_CHECK(&vrrp_dbg_pkt, DEBUG_MODE_ALL))
		zlog_hexdump(pkt, (size_t)pktsz);

	const char *group =
		r->family == AF_INET ? VRRP_MCASTV4_GROUP_STR : VRRP_MCASTV6_GROUP_STR;
	str2sockunion(group, &dest);

	ssize_t sent = sendto(r->sock_tx, pkt, (size_t)pktsz, 0, &dest.sa,
			      sockunion_sizeof(&dest));

	XFREE(MTYPE_VRRP_PKT, pkt);

	if (sent < 0) {
		zlog_warn(VRRP_LOGPFX VRRP_LOGPFX_VRID
			  "Failed to send VRRP Advertisement: %s",
			  r->vr->vrid, safe_strerror(errno));
	}
}

/*
 * Receive and parse VRRP advertisement.
 *
 * By the time we get here all fields have been validated for basic correctness
 * and the packet is a valid VRRP packet.
 *
 * However, we have not validated whether the VRID is correct for this virtual
 * router, nor whether the priority is correct (i.e. is not 255 when we are the
 * address owner), nor whether the advertisement interval equals our own
 * configured value (this check is only performed in VRRPv2).
 *
 * r
 *    VRRP Router associated with the socket this advertisement was received on
 *
 * src
 *    Source address of sender
 *
 * pkt
 *    The advertisement they sent
 *
 * pktsize
 *    Size of advertisement
 *
 * Returns:
 *    -1 if advertisement is invalid
 *     0 otherwise
 */
static int vrrp_recv_advertisement(struct vrrp_router *r, struct ipaddr *src,
				   struct vrrp_pkt *pkt, size_t pktsize)
{
	char sipstr[INET6_ADDRSTRLEN];
	ipaddr2str(src, sipstr, sizeof(sipstr));

	char dumpbuf[BUFSIZ];
	vrrp_pkt_adver_dump(dumpbuf, sizeof(dumpbuf), pkt);
	DEBUGD(&vrrp_dbg_proto,
	       VRRP_LOGPFX VRRP_LOGPFX_VRID
	       "Received VRRP Advertisement from %s:\n%s",
	       r->vr->vrid, sipstr, dumpbuf);

	/* Check that VRID matches our configured VRID */
	if (pkt->hdr.vrid != r->vr->vrid) {
		DEBUGD(&vrrp_dbg_proto,
		       VRRP_LOGPFX VRRP_LOGPFX_VRID
		       "%s datagram invalid: Advertisement contains VRID %" PRIu8
		       " which does not match our instance",
		       r->vr->vrid, family2str(r->family), pkt->hdr.vrid);
		return -1;
	}

	/* Verify that we are not the IPvX address owner */
	if (r->is_owner) {
		DEBUGD(&vrrp_dbg_proto,
		       VRRP_LOGPFX VRRP_LOGPFX_VRID
		       "%s datagram invalid: Received advertisement but we are the address owner",
		       r->vr->vrid, family2str(r->family));
		return -1;
	}

	/* If v2, verify that adver time matches ours */
	bool adveq = (pkt->hdr.v2.adver_int
		      == MAX(r->vr->advertisement_interval / 100, 1));
	if (r->vr->version == 2 && !adveq) {
		DEBUGD(&vrrp_dbg_proto,
		       VRRP_LOGPFX VRRP_LOGPFX_VRID
		       "%s datagram invalid: Received advertisement with advertisement interval %" PRIu8
		       " unequal to our configured value %u",
		       r->vr->vrid, family2str(r->family),
		       pkt->hdr.v2.adver_int,
		       MAX(r->vr->advertisement_interval / 100, 1));
		return -1;
	}


	/* Check that # IPs received matches our # configured IPs */
	if (pkt->hdr.naddr != r->addrs->count)
		DEBUGD(&vrrp_dbg_proto,
		       VRRP_LOGPFX VRRP_LOGPFX_VRID
		       "%s datagram has %" PRIu8
		       " addresses, but this VRRP instance has %u",
		       r->vr->vrid, family2str(r->family), pkt->hdr.naddr,
		       r->addrs->count);

	int addrcmp;

	switch (r->fsm.state) {
	case VRRP_STATE_MASTER:
		addrcmp = memcmp(&src->ip, &r->src.ip, IPADDRSZ(src));

		if (pkt->hdr.priority == 0) {
			vrrp_send_advertisement(r);
			THREAD_OFF(r->t_adver_timer);
			thread_add_timer_msec(
				master, vrrp_adver_timer_expire, r,
				r->vr->advertisement_interval * 10,
				&r->t_adver_timer);
		} else if (pkt->hdr.priority > r->priority
			   || ((pkt->hdr.priority == r->priority) && addrcmp > 0)) {
			zlog_info(
				VRRP_LOGPFX VRRP_LOGPFX_VRID
				"Received advertisement from %s w/ priority %" PRIu8
				"; switching to Backup",
				r->vr->vrid, sipstr, pkt->hdr.priority);
			THREAD_OFF(r->t_adver_timer);
			if (r->vr->version == 3) {
				r->master_adver_interval =
					htons(pkt->hdr.v3.adver_int);
			}
			vrrp_recalculate_timers(r);
			THREAD_OFF(r->t_master_down_timer);
			thread_add_timer_msec(master,
					      vrrp_master_down_timer_expire, r,
					      r->master_down_interval * 10,
					      &r->t_master_down_timer);
			vrrp_change_state(r, VRRP_STATE_BACKUP);
		} else {
			/* Discard advertisement */
			DEBUGD(&vrrp_dbg_proto,
			       VRRP_LOGPFX VRRP_LOGPFX_VRID
			       "Discarding advertisement from %s",
			       r->vr->vrid, sipstr);
		}
		break;
	case VRRP_STATE_BACKUP:
		if (pkt->hdr.priority == 0) {
			THREAD_OFF(r->t_master_down_timer);
			thread_add_timer_msec(
				master, vrrp_master_down_timer_expire, r,
				r->skew_time * 10, &r->t_master_down_timer);
		} else if (r->vr->preempt_mode == false
			   || pkt->hdr.priority >= r->priority) {
			if (r->vr->version == 3) {
				r->master_adver_interval =
					ntohs(pkt->hdr.v3.adver_int);
			}
			vrrp_recalculate_timers(r);
			THREAD_OFF(r->t_master_down_timer);
			thread_add_timer_msec(master,
					      vrrp_master_down_timer_expire, r,
					      r->master_down_interval * 10,
					      &r->t_master_down_timer);
		} else if (r->vr->preempt_mode == true
			   && pkt->hdr.priority < r->priority) {
			/* Discard advertisement */
			DEBUGD(&vrrp_dbg_proto,
			       VRRP_LOGPFX VRRP_LOGPFX_VRID
			       "Discarding advertisement from %s",
			       r->vr->vrid, sipstr);
		}
		break;
	case VRRP_STATE_INITIALIZE:
		zlog_err(VRRP_LOGPFX VRRP_LOGPFX_VRID
			 "Received ADVERTISEMENT in state %s; this is a bug",
			 r->vr->vrid, vrrp_state_names[r->fsm.state]);
		break;
	}

	return 0;
}

/*
 * Read and process next IPvX datagram.
 */
static int vrrp_read(struct thread *thread)
{
	struct vrrp_router *r = thread->arg;

	struct vrrp_pkt *pkt;
	ssize_t pktsize;
	ssize_t nbytes;
	bool resched;
	char errbuf[BUFSIZ];
	struct sockaddr_storage sa;
	uint8_t control[64];
	struct ipaddr src = {};

	struct msghdr m;
	struct iovec iov;
	iov.iov_base = r->ibuf;
	iov.iov_len = sizeof(r->ibuf);
	m.msg_name = &sa;
	m.msg_namelen = sizeof(sa);
	m.msg_iov = &iov;
	m.msg_iovlen = 1;
	m.msg_control = control;
	m.msg_controllen = sizeof(control);

	nbytes = recvmsg(r->sock_rx, &m, MSG_DONTWAIT);

	if ((nbytes < 0 && ERRNO_IO_RETRY(errno))) {
		resched = true;
		goto done;
	} else if (nbytes <= 0) {
		vrrp_event(r, VRRP_EVENT_SHUTDOWN);
		resched = false;
		goto done;
	}

	if (DEBUG_MODE_CHECK(&vrrp_dbg_pkt, DEBUG_MODE_ALL)) {
		DEBUGD(&vrrp_dbg_pkt,
		       VRRP_LOGPFX VRRP_LOGPFX_VRID "Received %s datagram: ",
		       r->vr->vrid, family2str(r->family));
		zlog_hexdump(r->ibuf, nbytes);
	}

	pktsize = vrrp_pkt_parse_datagram(r->family, r->vr->version, &m, nbytes,
					  &src, &pkt, errbuf, sizeof(errbuf));

	if (pktsize < 0) {
		DEBUGD(&vrrp_dbg_pkt,
		       VRRP_LOGPFX VRRP_LOGPFX_VRID "%s datagram invalid: %s",
		       r->vr->vrid, family2str(r->family), errbuf);
	} else {
		DEBUGD(&vrrp_dbg_pkt,
		       VRRP_LOGPFX VRRP_LOGPFX_VRID "Packet looks good",
		       r->vr->vrid);
		vrrp_recv_advertisement(r, &src, pkt, pktsize);
	}

	resched = true;

done:
	memset(r->ibuf, 0x00, sizeof(r->ibuf));

	if (resched)
		thread_add_read(master, vrrp_read, r, r->sock_rx, &r->t_read);

	return 0;
}

/*
 * Finds the first connected address of the appropriate family on a VRRP
 * router's interface and binds the Tx socket of the VRRP router to that
 * address.
 *
 * Also sets src field of vrrp_router.
 *
 * r
 *    VRRP router to operate on
 *
 * Returns:
 *     0 on success
 *    -1 on failure
 */
static int vrrp_bind_to_primary_connected(struct vrrp_router *r)
{
	char ipstr[INET6_ADDRSTRLEN];
	struct interface *ifp;

	/*
	 * A slight quirk: the RFC specifies that advertisements under IPv6 must
	 * be transmitted using the link local address of the source interface
	 */
	ifp = r->family == AF_INET ? r->vr->ifp : r->mvl_ifp;

	struct listnode *ln;
	struct connected *c = NULL;
	for (ALL_LIST_ELEMENTS_RO(ifp->connected, ln, c))
		if (c->address->family == r->family)
			break;

	if (c == NULL) {
		zlog_err(VRRP_LOGPFX VRRP_LOGPFX_VRID
			 "Failed to find %s address to bind on %s",
			 r->vr->vrid, family2str(r->family), ifp->name);
		return -1;
	}

	union sockunion su;
	memset(&su, 0x00, sizeof(su));

	switch (r->family) {
	case AF_INET:
		r->src.ipa_type = IPADDR_V4;
		r->src.ipaddr_v4 = c->address->u.prefix4;
		su.sin.sin_family = AF_INET;
		su.sin.sin_addr = c->address->u.prefix4;
		break;
	case AF_INET6:
		r->src.ipa_type = IPADDR_V6;
		r->src.ipaddr_v6 = c->address->u.prefix6;
		su.sin6.sin6_family = AF_INET6;
		su.sin6.sin6_scope_id = ifp->ifindex;
		su.sin6.sin6_addr = c->address->u.prefix6;
		break;
	}

	sockopt_reuseaddr(r->sock_tx);
	if (bind(r->sock_tx, (const struct sockaddr *)&su, sizeof(su)) < 0) {
		zlog_err(
			VRRP_LOGPFX VRRP_LOGPFX_VRID
			"Failed to bind Tx socket to primary IP address %s: %s",
			r->vr->vrid,
			inet_ntop(r->family,
				  (const void *)&c->address->u.prefix, ipstr,
				  sizeof(ipstr)),
			safe_strerror(errno));
		return -1;
	} else {
		DEBUGD(&vrrp_dbg_sock,
		       VRRP_LOGPFX VRRP_LOGPFX_VRID
		       "Bound Tx socket to primary IP address %s",
		       r->vr->vrid,
		       inet_ntop(r->family, (const void *)&c->address->u.prefix,
				 ipstr, sizeof(ipstr)));
	}

	return 0;
}

/*
 * Creates and configures VRRP router sockets.
 *
 * This function:
 * - Creates two sockets, one for Tx, one for Rx
 * - Joins the Rx socket to the appropriate VRRP multicast group
 * - Sets the Tx socket to set the TTL (v4) or Hop Limit (v6) field to 255 for
 *   all transmitted IPvX packets
 * - Requests the kernel to deliver IPv6 header values needed to validate VRRP
 *   packets
 *
 * If any of the above fail, the sockets are closed. The only exception is if
 * the TTL / Hop Limit settings fail; these are logged, but configuration
 * proceeds.
 *
 * The first connected address on the Virtual Router's interface is used as the
 * interface address.
 *
 * r
 *    VRRP Router for which to create listen socket
 *
 * Returns:
 *     0 on success
 *    -1 on failure
 */
static int vrrp_socket(struct vrrp_router *r)
{
	int ret;
	bool failed = false;

	frr_elevate_privs(&vrrp_privs)
	{
		r->sock_rx = socket(r->family, SOCK_RAW, IPPROTO_VRRP);
		r->sock_tx = socket(r->family, SOCK_RAW, IPPROTO_VRRP);
	}

	if (r->sock_rx < 0 || r->sock_tx < 0) {
		const char *rxtx = r->sock_rx < 0 ? "Rx" : "Tx";
		zlog_warn(VRRP_LOGPFX VRRP_LOGPFX_VRID
			  "Can't create %s VRRP %s socket",
			  r->vr->vrid, family2str(r->family), rxtx);
		failed = true;
		goto done;
	}

	/* Configure sockets */
	if (r->family == AF_INET) {
		/* Set Tx socket to always Tx with TTL set to 255 */
		int ttl = 255;
		ret = setsockopt(r->sock_tx, IPPROTO_IP, IP_MULTICAST_TTL, &ttl,
				 sizeof(ttl));
		if (ret < 0) {
			zlog_warn(
				VRRP_LOGPFX VRRP_LOGPFX_VRID
				"Failed to set outgoing multicast TTL count to 255; RFC 5798 compliant implementations will drop our packets",
				r->vr->vrid);
		}

		/* Set Tx socket DSCP byte */
		setsockopt_ipv4_tos(r->sock_tx, IPTOS_PREC_INTERNETCONTROL);

		/* Turn off multicast loop on Tx */
		setsockopt_ipv4_multicast_loop(r->sock_tx, 0);

		/* Bind Rx socket to exact interface */
		vrrp_privs.change(ZPRIVS_RAISE);
		{
			ret = setsockopt(r->sock_rx, SOL_SOCKET,
					 SO_BINDTODEVICE, r->vr->ifp->name,
					 strlen(r->vr->ifp->name));
		}
		vrrp_privs.change(ZPRIVS_LOWER);
		if (ret) {
			zlog_warn(VRRP_LOGPFX VRRP_LOGPFX_VRID
				  "Failed to bind Rx socket to %s: %s",
				  r->vr->vrid, r->vr->ifp->name,
				  safe_strerror(errno));
			failed = true;
			goto done;
		}
		DEBUGD(&vrrp_dbg_sock,
		       VRRP_LOGPFX VRRP_LOGPFX_VRID "Bound Rx socket to %s",
		       r->vr->vrid, r->vr->ifp->name);

		/* Bind Rx socket to v4 multicast address */
		struct sockaddr_in sa = {0};
		sa.sin_family = AF_INET;
		sa.sin_addr.s_addr = htonl(VRRP_MCASTV4_GROUP);
		if (bind(r->sock_rx, (struct sockaddr *)&sa, sizeof(sa))) {
			zlog_err(
				VRRP_LOGPFX VRRP_LOGPFX_VRID
				"Failed to bind Rx socket to VRRP %s multicast group: %s",
				r->vr->vrid, family2str(r->family),
				safe_strerror(errno));
			failed = true;
			goto done;
		}
		DEBUGD(&vrrp_dbg_sock,
		       VRRP_LOGPFX VRRP_LOGPFX_VRID
		       "Bound Rx socket to VRRP %s multicast group",
		       r->vr->vrid, family2str(r->family));

		/* Join Rx socket to VRRP IPv4 multicast group */
		struct connected *c = listhead(r->vr->ifp->connected)->data;
		struct in_addr v4 = c->address->u.prefix4;
		ret = setsockopt_ipv4_multicast(r->sock_rx, IP_ADD_MEMBERSHIP,
						v4, htonl(VRRP_MCASTV4_GROUP),
						r->vr->ifp->ifindex);
		if (ret < 0) {
			zlog_warn(VRRP_LOGPFX VRRP_LOGPFX_VRID
				  "Failed to join VRRP %s multicast group",
				  r->vr->vrid, family2str(r->family));
			failed = true;
			goto done;
		}
		DEBUGD(&vrrp_dbg_sock,
		       VRRP_LOGPFX VRRP_LOGPFX_VRID
		       "Joined %s VRRP multicast group",
		       r->vr->vrid, family2str(r->family));

		/* Set outgoing interface for advertisements */
		struct ip_mreqn mreqn = {};
		mreqn.imr_ifindex = r->mvl_ifp->ifindex;
		ret = setsockopt(r->sock_tx, IPPROTO_IP, IP_MULTICAST_IF,
				 (void *)&mreqn, sizeof(mreqn));
		if (ret < 0) {
			zlog_warn(
				VRRP_LOGPFX VRRP_LOGPFX_VRID
				"Could not set %s as outgoing multicast interface",
				r->vr->vrid, r->mvl_ifp->name);
			failed = true;
			goto done;
		}
		DEBUGD(&vrrp_dbg_sock,
		       VRRP_LOGPFX VRRP_LOGPFX_VRID
		       "Set %s as outgoing multicast interface",
		       r->vr->vrid, r->mvl_ifp->name);
	} else if (r->family == AF_INET6) {
		/* Always transmit IPv6 packets with hop limit set to 255 */
		ret = setsockopt_ipv6_multicast_hops(r->sock_tx, 255);
		if (ret < 0) {
			zlog_warn(
				VRRP_LOGPFX VRRP_LOGPFX_VRID
				"Failed to set outgoing multicast hop count to 255; RFC 5798 compliant implementations will drop our packets",
				r->vr->vrid);
		}

		/* Set Tx socket DSCP byte */
		setsockopt_ipv6_tclass(r->sock_tx, IPTOS_PREC_INTERNETCONTROL);

		/* Request hop limit delivery */
		setsockopt_ipv6_hoplimit(r->sock_rx, 1);
		if (ret < 0) {
			zlog_warn(VRRP_LOGPFX VRRP_LOGPFX_VRID
				  "Failed to request IPv6 Hop Limit delivery",
				  r->vr->vrid);
			failed = true;
			goto done;
		}

		/* Turn off multicast loop on Tx */
		setsockopt_ipv6_multicast_loop(r->sock_tx, 0);

		/* Bind Rx socket to exact interface */
		vrrp_privs.change(ZPRIVS_RAISE);
		{
			ret = setsockopt(r->sock_rx, SOL_SOCKET,
					 SO_BINDTODEVICE, r->vr->ifp->name,
					 strlen(r->vr->ifp->name));
		}
		vrrp_privs.change(ZPRIVS_LOWER);
		if (ret) {
			zlog_warn(VRRP_LOGPFX VRRP_LOGPFX_VRID
				  "Failed to bind Rx socket to %s: %s",
				  r->vr->vrid, r->vr->ifp->name,
				  safe_strerror(errno));
			failed = true;
			goto done;
		}
		DEBUGD(&vrrp_dbg_sock,
		       VRRP_LOGPFX VRRP_LOGPFX_VRID "Bound Rx socket to %s",
		       r->vr->vrid, r->vr->ifp->name);

		/* Bind Rx socket to v6 multicast address */
		struct sockaddr_in6 sa = {0};
		sa.sin6_family = AF_INET6;
		inet_pton(AF_INET6, VRRP_MCASTV6_GROUP_STR, &sa.sin6_addr);
		if (bind(r->sock_rx, (struct sockaddr *)&sa, sizeof(sa))) {
			zlog_err(
				VRRP_LOGPFX VRRP_LOGPFX_VRID
				"Failed to bind Rx socket to VRRP %s multicast group: %s",
				r->vr->vrid, family2str(r->family),
				safe_strerror(errno));
			failed = true;
			goto done;
		}
		DEBUGD(&vrrp_dbg_sock,
		       VRRP_LOGPFX VRRP_LOGPFX_VRID
		       "Bound Rx socket to VRRP %s multicast group",
		       r->vr->vrid, family2str(r->family));

		/* Join VRRP IPv6 multicast group */
		struct ipv6_mreq mreq;
		inet_pton(AF_INET6, VRRP_MCASTV6_GROUP_STR,
			  &mreq.ipv6mr_multiaddr);
		mreq.ipv6mr_interface = r->vr->ifp->ifindex;
		ret = setsockopt(r->sock_rx, IPPROTO_IPV6, IPV6_JOIN_GROUP,
				 &mreq, sizeof(mreq));
		if (ret < 0) {
			zlog_warn(VRRP_LOGPFX VRRP_LOGPFX_VRID
				  "Failed to join VRRP %s multicast group",
				  r->vr->vrid, family2str(r->family));
			failed = true;
			goto done;
		}
		DEBUGD(&vrrp_dbg_sock,
		       VRRP_LOGPFX VRRP_LOGPFX_VRID
		       "Joined %s VRRP multicast group",
		       r->vr->vrid, family2str(r->family));

		/* Set outgoing interface for advertisements */
		ret = setsockopt(r->sock_tx, IPPROTO_IPV6, IPV6_MULTICAST_IF,
				 &r->mvl_ifp->ifindex, sizeof(ifindex_t));
		if (ret < 0) {
			zlog_warn(
				VRRP_LOGPFX VRRP_LOGPFX_VRID
				"Could not set %s as outgoing multicast interface",
				r->vr->vrid, r->mvl_ifp->name);
			failed = true;
			goto done;
		}
		DEBUGD(&vrrp_dbg_sock,
		       VRRP_LOGPFX VRRP_LOGPFX_VRID
		       "Set %s as outgoing multicast interface",
		       r->vr->vrid, r->mvl_ifp->name);
	}

	/* Bind Tx socket to link-local address */
	if (vrrp_bind_to_primary_connected(r) < 0) {
		failed = true;
		goto done;
	}

done:
	ret = 0;
	if (failed) {
		zlog_warn(VRRP_LOGPFX VRRP_LOGPFX_VRID
			  "Failed to initialize VRRP %s router",
			  r->vr->vrid, family2str(r->family));
		if (r->sock_rx >= 0) {
			close(r->sock_rx);
			r->sock_rx = -1;
		}
		if (r->sock_tx >= 0) {
			close(r->sock_tx);
			r->sock_tx = -1;
		}
		ret = -1;
	}

	return ret;
}


/* State machine ----------------------------------------------------------- */

DEFINE_HOOK(vrrp_change_state_hook, (struct vrrp_router * r, int to), (r, to));

/*
 * Handle any necessary actions during state change to MASTER state.
 *
 * r
 *    VRRP Router to operate on
 */
static void vrrp_change_state_master(struct vrrp_router *r)
{
	/* Enable ND Router Advertisements */
	if (r->family == AF_INET6)
		vrrp_zebra_radv_set(r, true);

	vrrp_zclient_send_interface_protodown(r->mvl_ifp, false);
}

/*
 * Handle any necessary actions during state change to BACKUP state.
 *
 * r
 *    Virtual Router to operate on
 */
static void vrrp_change_state_backup(struct vrrp_router *r)
{
	/* Disable ND Router Advertisements */
	if (r->family == AF_INET6)
		vrrp_zebra_radv_set(r, false);

	vrrp_zclient_send_interface_protodown(r->mvl_ifp, true);
}

/*
 * Handle any necessary actions during state change to INITIALIZE state.
 *
 * This is not called for initial startup, only when transitioning from MASTER
 * or BACKUP.
 *
 * r
 *    VRRP Router to operate on
 */
static void vrrp_change_state_initialize(struct vrrp_router *r)
{
	r->vr->advertisement_interval = r->vr->advertisement_interval;
	r->master_adver_interval = 0;
	vrrp_recalculate_timers(r);

	/* Disable ND Router Advertisements */
	if (r->family == AF_INET6)
		vrrp_zebra_radv_set(r, false);
}

void (*vrrp_change_state_handlers[])(struct vrrp_router *vr) = {
	[VRRP_STATE_MASTER] = vrrp_change_state_master,
	[VRRP_STATE_BACKUP] = vrrp_change_state_backup,
	[VRRP_STATE_INITIALIZE] = vrrp_change_state_initialize,
};

/*
 * Change Virtual Router FSM position. Handles transitional actions and calls
 * any subscribers to the state change hook.
 *
 * r
 *    Virtual Router for which to change state
 *
 * to
 *    State to change to
 */
static void vrrp_change_state(struct vrrp_router *r, int to)
{
	if (r->fsm.state == to)
		return;

	/* Call our handlers, then any subscribers */
	vrrp_change_state_handlers[to](r);
	hook_call(vrrp_change_state_hook, r, to);
	zlog_info(VRRP_LOGPFX VRRP_LOGPFX_VRID "%s -> %s", r->vr->vrid,
		  vrrp_state_names[r->fsm.state], vrrp_state_names[to]);
	r->fsm.state = to;
}

/*
 * Called when Adver_Timer expires.
 */
static int vrrp_adver_timer_expire(struct thread *thread)
{
	struct vrrp_router *r = thread->arg;

	DEBUGD(&vrrp_dbg_proto,
	       VRRP_LOGPFX VRRP_LOGPFX_VRID "Adver_Timer expired", r->vr->vrid);

	if (r->fsm.state == VRRP_STATE_MASTER) {
		/* Send an ADVERTISEMENT */
		vrrp_send_advertisement(r);

		/* Reset the Adver_Timer to Advertisement_Interval */
		thread_add_timer_msec(master, vrrp_adver_timer_expire, r,
				      r->vr->advertisement_interval * 10,
				      &r->t_adver_timer);
	} else {
		zlog_err(VRRP_LOGPFX VRRP_LOGPFX_VRID
			 "Adver_Timer expired in state '%s'; this is a bug",
			 r->vr->vrid, vrrp_state_names[r->fsm.state]);
	}

	return 0;
}

/*
 * Called when Master_Down_Timer expires.
 */
static int vrrp_master_down_timer_expire(struct thread *thread)
{
	struct vrrp_router *r = thread->arg;

	zlog_info(VRRP_LOGPFX VRRP_LOGPFX_VRID "Master_Down_Timer expired",
		  r->vr->vrid);

	vrrp_send_advertisement(r);
	if (r->family == AF_INET)
		vrrp_garp_send_all(r);
	if (r->family == AF_INET6)
		vrrp_ndisc_una_send_all(r);
	thread_add_timer_msec(master, vrrp_adver_timer_expire, r,
			      r->vr->advertisement_interval * 10,
			      &r->t_adver_timer);
	vrrp_change_state(r, VRRP_STATE_MASTER);

	return 0;
}

/*
 * Event handler for Startup event.
 *
 * Creates sockets, sends advertisements and ARP requests, starts timers,
 * and transitions the Virtual Router to either Master or Backup states.
 *
 * This function will also initialize the program's global ARP subsystem if it
 * has not yet been initialized.
 *
 * r
 *    VRRP Router on which to apply Startup event
 *
 * Returns:
 *    < 0 if the session socket could not be created, or the state is not
 *        Initialize
 *      0 on success
 */
static int vrrp_startup(struct vrrp_router *r)
{
	/* May only be called when the state is Initialize */
	if (r->fsm.state != VRRP_STATE_INITIALIZE)
		return -1;

	/* Must have a valid macvlan interface available */
	if (r->mvl_ifp == NULL && !vrrp_attach_interface(r)) {
		zlog_warn(VRRP_LOGPFX VRRP_LOGPFX_VRID
			  "No appropriate interface for %s VRRP found",
			  r->vr->vrid, family2str(r->family));
		return -1;
	}

	/* Initialize global gratuitous ARP socket if necessary */
	if (r->family == AF_INET && !vrrp_garp_is_init())
		vrrp_garp_init();
	if (r->family == AF_INET6 && !vrrp_ndisc_is_init())
		vrrp_ndisc_init();

	/* Create socket */
	if (r->sock_rx < 0 || r->sock_tx < 0) {
		int ret = vrrp_socket(r);
		if (ret < 0 || r->sock_tx < 0 || r->sock_rx < 0)
			return ret;
	}

	/* Schedule listener */
	thread_add_read(master, vrrp_read, r, r->sock_rx, &r->t_read);

	/* Configure effective priority */
	struct ipaddr *primary = (struct ipaddr *)listhead(r->addrs)->data;

	char ipbuf[INET6_ADDRSTRLEN];
	inet_ntop(r->family, &primary->ip.addr, ipbuf, sizeof(ipbuf));

	if (vrrp_is_owner(r->vr->ifp, primary)) {
		r->priority = VRRP_PRIO_MASTER;
		vrrp_recalculate_timers(r);

		zlog_info(
			VRRP_LOGPFX VRRP_LOGPFX_VRID
			"%s owns primary Virtual Router IP %s; electing self as Master",
			r->vr->vrid, r->vr->ifp->name, ipbuf);
	}

	if (r->priority == VRRP_PRIO_MASTER) {
		vrrp_send_advertisement(r);

		if (r->family == AF_INET)
			vrrp_garp_send_all(r);
		if (r->family == AF_INET6)
			vrrp_ndisc_una_send_all(r);

		thread_add_timer_msec(master, vrrp_adver_timer_expire, r,
				      r->vr->advertisement_interval * 10,
				      &r->t_adver_timer);
		vrrp_change_state(r, VRRP_STATE_MASTER);
	} else {
		r->master_adver_interval = r->vr->advertisement_interval;
		vrrp_recalculate_timers(r);
		thread_add_timer_msec(master, vrrp_master_down_timer_expire, r,
				      r->master_down_interval * 10,
				      &r->t_master_down_timer);
		vrrp_change_state(r, VRRP_STATE_BACKUP);
	}

	r->is_active = true;

	return 0;
}

/*
 * Shuts down a Virtual Router and transitions it to Initialize.
 *
 * This call must be idempotent; it is safe to call multiple times on the same
 * VRRP Router.
 */
static int vrrp_shutdown(struct vrrp_router *r)
{
	switch (r->fsm.state) {
	case VRRP_STATE_MASTER:
		/* Cancel the Adver_Timer */
		THREAD_OFF(r->t_adver_timer);
		/* Send an ADVERTISEMENT with Priority = 0 */
		uint8_t saved_prio = r->priority;
		r->priority = 0;
		vrrp_send_advertisement(r);
		r->priority = saved_prio;
		break;
	case VRRP_STATE_BACKUP:
		/* Cancel the Master_Down_Timer */
		THREAD_OFF(r->t_master_down_timer);
		break;
	case VRRP_STATE_INITIALIZE:
		DEBUGD(&vrrp_dbg_proto,
		       VRRP_LOGPFX VRRP_LOGPFX_VRID
		       "Received '%s' event in '%s' state; ignoring",
		       r->vr->vrid, vrrp_event_names[VRRP_EVENT_SHUTDOWN],
		       vrrp_state_names[VRRP_STATE_INITIALIZE]);
		break;
	}

	/* Transition to the Initialize state */
	vrrp_change_state(r, VRRP_STATE_INITIALIZE);

	r->is_active = false;

	return 0;
}

static int (*vrrp_event_handlers[])(struct vrrp_router *r) = {
	[VRRP_EVENT_STARTUP] = vrrp_startup,
	[VRRP_EVENT_SHUTDOWN] = vrrp_shutdown,
};

/*
 * Spawn a VRRP FSM event on a VRRP Router.
 *
 * vr
 *    VRRP Router on which to spawn event
 *
 * event
 *    The event to spawn
 *
 * Returns:
 *    -1 on failure
 *     0 otherwise
 */
int vrrp_event(struct vrrp_router *r, int event)
{
	zlog_info(VRRP_LOGPFX VRRP_LOGPFX_VRID "'%s' event", r->vr->vrid,
		  vrrp_event_names[r->fsm.state]);
	return vrrp_event_handlers[event](r);
}


/* Autoconfig -------------------------------------------------------------- */

/*
 * Set the configured addresses for this VRRP instance to exactly the addresses
 * present on its macvlan subinterface(s).
 *
 * vr
 *    VRRP router to act on
 */
static void vrrp_autoconfig_autoaddrupdate(struct vrrp_vrouter *vr)
{
	list_delete_all_node(vr->v4->addrs);
	list_delete_all_node(vr->v6->addrs);

	struct listnode *ln;
	struct connected *c = NULL;

	if (vr->v4->mvl_ifp) {
		DEBUGD(&vrrp_dbg_auto,
		       VRRP_LOGPFX VRRP_LOGPFX_VRID
		       "Setting IPv4 Virtual IP list to match IPv4 addresses on %s",
		       vr->vrid, vr->v4->mvl_ifp->name);
		for (ALL_LIST_ELEMENTS_RO(vr->v4->mvl_ifp->connected, ln, c))
			if (c->address->family == AF_INET)
				vrrp_add_ipv4(vr, c->address->u.prefix4, true);
	}

	if (vr->v6->mvl_ifp) {
		DEBUGD(&vrrp_dbg_auto,
		       VRRP_LOGPFX VRRP_LOGPFX_VRID
		       "Setting IPv6 Virtual IP list to match IPv6 addresses on %s",
		       vr->vrid, vr->v6->mvl_ifp->name);
		for (ALL_LIST_ELEMENTS_RO(vr->v6->mvl_ifp->connected, ln, c))
			if (c->address->family == AF_INET6
			    && !IN6_IS_ADDR_LINKLOCAL(&c->address->u.prefix6))
				vrrp_add_ipv6(vr, c->address->u.prefix6, true);
	}

	if (vr->v4->addrs->count == 0
	    && vr->v4->fsm.state != VRRP_STATE_INITIALIZE) {
		DEBUGD(&vrrp_dbg_auto,
		       VRRP_LOGPFX VRRP_LOGPFX_VRID
		       "IPv4 Virtual IP list is empty; shutting down",
		       vr->vrid);
		vrrp_event(vr->v4, VRRP_EVENT_SHUTDOWN);
	}
	if (vr->v6->addrs->count == 0
	    && vr->v6->fsm.state != VRRP_STATE_INITIALIZE) {
		DEBUGD(&vrrp_dbg_auto,
		       VRRP_LOGPFX VRRP_LOGPFX_VRID
		       "IPv6 Virtual IP list is empty; shutting down",
		       vr->vrid);
		vrrp_event(vr->v6, VRRP_EVENT_SHUTDOWN);
	}
}

static struct vrrp_vrouter *
vrrp_autoconfig_autocreate(struct interface *mvl_ifp)
{
	struct interface *p;
	struct vrrp_vrouter *vr;

	p = if_lookup_by_index(mvl_ifp->link_ifindex, VRF_DEFAULT);

	if (!p)
		return NULL;

	uint8_t vrid = mvl_ifp->hw_addr[5];

	DEBUGD(&vrrp_dbg_auto, VRRP_LOGPFX "Autoconfiguring VRRP on %s",
	       p->name);

	vr = vrrp_vrouter_create(p, vrid, vrrp_autoconfig_version);

	if (!vr) {
		zlog_warn(VRRP_LOGPFX
			  "Failed to autoconfigure VRRP instance %" PRIu8
			  " on %s",
			  vrid, p->name);
		return NULL;
	}

	vrrp_autoconfig_autoaddrupdate(vr);

	vr->autoconf = true;

	return vr;
}

static bool vrrp_ifp_has_vrrp_mac(struct interface *ifp)
{
	struct ethaddr vmac4;
	struct ethaddr vmac6;
	vrrp_mac_set(&vmac4, 0, 0x00);
	vrrp_mac_set(&vmac6, 1, 0x00);

	return !memcmp(ifp->hw_addr, vmac4.octet, sizeof(vmac4.octet) - 1)
	       || !memcmp(ifp->hw_addr, vmac6.octet, sizeof(vmac6.octet) - 1);
}

static struct vrrp_vrouter *vrrp_lookup_by_mvlif(struct interface *mvl_ifp)
{
	struct interface *p;

	if (!mvl_ifp || !mvl_ifp->link_ifindex
	    || !vrrp_ifp_has_vrrp_mac(mvl_ifp))
		return NULL;

	p = if_lookup_by_index(mvl_ifp->link_ifindex, VRF_DEFAULT);
	uint8_t vrid = mvl_ifp->hw_addr[5];

	return vrrp_lookup(p, vrid);
}

int vrrp_autoconfig_if_add(struct interface *ifp)
{
	if (!vrrp_autoconfig_is_on)
		return 0;

	struct vrrp_vrouter *vr;

	if (!ifp || !ifp->link_ifindex || !vrrp_ifp_has_vrrp_mac(ifp))
		return -1;

	vr = vrrp_lookup_by_mvlif(ifp);

	if (!vr)
		vr = vrrp_autoconfig_autocreate(ifp);

	if (!vr)
		return -1;

	if (vr->autoconf == false)
		return 0;
	else {
		vrrp_attach_interface(vr->v4);
		vrrp_attach_interface(vr->v6);
		vrrp_autoconfig_autoaddrupdate(vr);
	}

	return 0;
}

int vrrp_autoconfig_if_del(struct interface *ifp)
{
	if (!vrrp_autoconfig_is_on)
		return 0;

	struct vrrp_vrouter *vr = vrrp_lookup_by_mvlif(ifp);

	if (!vr)
		return 0;

	if (vr && vr->autoconf == false)
		return 0;

	if (vr && vr->v4->mvl_ifp == ifp) {
		if (vr->v4->fsm.state != VRRP_STATE_INITIALIZE) {
			DEBUGD(&vrrp_dbg_auto,
			       VRRP_LOGPFX VRRP_LOGPFX_VRID
			       "Interface %s deleted; shutting down IPv4 VRRP router",
			       vr->vrid, ifp->name);
			vrrp_event(vr->v4, VRRP_EVENT_SHUTDOWN);
		}
		vr->v4->mvl_ifp = NULL;
	}
	if (vr && vr->v6->mvl_ifp == ifp) {
		if (vr->v6->fsm.state != VRRP_STATE_INITIALIZE) {
			DEBUGD(&vrrp_dbg_auto,
			       VRRP_LOGPFX VRRP_LOGPFX_VRID
			       "Interface %s deleted; shutting down IPv6 VRRP router",
			       vr->vrid, ifp->name);
			vrrp_event(vr->v6, VRRP_EVENT_SHUTDOWN);
		}
		vr->v6->mvl_ifp = NULL;
	}

	if (vr->v4->mvl_ifp == NULL && vr->v6->mvl_ifp == NULL) {
		DEBUGD(&vrrp_dbg_auto,
		       VRRP_LOGPFX VRRP_LOGPFX_VRID
		       "All VRRP interfaces for instance deleted; destroying autoconfigured VRRP router",
		       vr->vrid);
		vrrp_vrouter_destroy(vr);
		vr = NULL;
	}

	return 0;
}

int vrrp_autoconfig_if_up(struct interface *ifp)
{
	if (!vrrp_autoconfig_is_on)
		return 0;

	struct vrrp_vrouter *vr = vrrp_lookup_by_mvlif(ifp);

	if (vr && !vr->autoconf)
		return 0;

	if (!vr) {
		vrrp_autoconfig_if_add(ifp);
		return 0;
	}

	vrrp_attach_interface(vr->v4);
	vrrp_attach_interface(vr->v6);
	vrrp_autoconfig_autoaddrupdate(vr);

	return 0;
}

int vrrp_autoconfig_if_down(struct interface *ifp)
{
	if (!vrrp_autoconfig_is_on)
		return 0;

	return 0;
}

int vrrp_autoconfig_if_address_add(struct interface *ifp)
{
	if (!vrrp_autoconfig_is_on)
		return 0;

	struct vrrp_vrouter *vr = vrrp_lookup_by_mvlif(ifp);

	if (vr && vr->autoconf)
		vrrp_autoconfig_autoaddrupdate(vr);

	return 0;
}

int vrrp_autoconfig_if_address_del(struct interface *ifp)
{
	if (!vrrp_autoconfig_is_on)
		return 0;

	struct vrrp_vrouter *vr = vrrp_lookup_by_mvlif(ifp);

	if (vr && vr->autoconf)
		vrrp_autoconfig_autoaddrupdate(vr);

	return 0;
}

int vrrp_autoconfig(void)
{
	if (!vrrp_autoconfig_is_on)
		return 0;

	struct vrf *vrf = vrf_lookup_by_id(VRF_DEFAULT);
	struct interface *ifp;

	FOR_ALL_INTERFACES (vrf, ifp)
		vrrp_autoconfig_if_add(ifp);

	return 0;
}

void vrrp_autoconfig_on(int version)
{
	vrrp_autoconfig_is_on = true;
	vrrp_autoconfig_version = version;

	vrrp_autoconfig();
}

void vrrp_autoconfig_off(void)
{
	vrrp_autoconfig_is_on = false;

	struct list *ll = hash_to_list(vrrp_vrouters_hash);

	struct listnode *ln;
	struct vrrp_vrouter *vr;

	for (ALL_LIST_ELEMENTS_RO(ll, ln, vr))
		if (vr->autoconf)
			vrrp_vrouter_destroy(vr);

	list_delete(&ll);
}

/* Other ------------------------------------------------------------------- */

int vrrp_config_write_interface(struct vty *vty)
{
	struct list *vrs = hash_to_list(vrrp_vrouters_hash);
	struct listnode *ln;
	struct vrrp_vrouter *vr;
	int writes = 0;

	for (ALL_LIST_ELEMENTS_RO(vrs, ln, vr)) {
		vty_frame(vty, "interface %s\n", vr->ifp->name);
		++writes;

		vty_out(vty, " vrrp %" PRIu8 "%s\n", vr->vrid,
			vr->version == 2 ? " version 2" : "");
		++writes;

		if (!vr->preempt_mode && ++writes)
			vty_out(vty, " no vrrp %" PRIu8 " preempt\n", vr->vrid);

		if (vr->accept_mode && ++writes)
			vty_out(vty, " vrrp %" PRIu8 " accept\n", vr->vrid);

		if (vr->advertisement_interval != VRRP_DEFAULT_ADVINT
		    && ++writes)
			vty_out(vty,
				" vrrp %" PRIu8
				" advertisement-interval %" PRIu16 "\n",
				vr->vrid, vr->advertisement_interval);

		if (vr->priority != VRRP_DEFAULT_PRIORITY && ++writes)
			vty_out(vty, " vrrp %" PRIu8 " priority %" PRIu8 "\n",
				vr->vrid, vr->priority);

		ln = NULL;
		struct ipaddr *ip;

		for (ALL_LIST_ELEMENTS_RO(vr->v4->addrs, ln, ip)) {
			char ipbuf[INET6_ADDRSTRLEN];
			ipaddr2str(ip, ipbuf, sizeof(ipbuf));
			vty_out(vty, " vrrp %" PRIu8 " ip %s\n", vr->vrid,
				ipbuf);
			++writes;
		}
		for (ALL_LIST_ELEMENTS_RO(vr->v6->addrs, ln, ip)) {
			char ipbuf[INET6_ADDRSTRLEN];
			ipaddr2str(ip, ipbuf, sizeof(ipbuf));
			vty_out(vty, " vrrp %" PRIu8 " ipv6 %s\n", vr->vrid,
				ipbuf);
			++writes;
		}
	}

	return writes;
}

int vrrp_config_write_global(struct vty *vty)
{
	if (vrrp_autoconfig_is_on)
		vty_out(vty, "vrrp autoconfigure%s\n",
			vrrp_autoconfig_version == 2 ? " version 2" : "");

	return 1;
}

static unsigned int vrrp_hash_key(void *arg)
{
	struct vrrp_vrouter *vr = arg;

	char key[IFNAMSIZ + 64];
	snprintf(key, sizeof(key), "%s@%" PRIu8, vr->ifp->name, vr->vrid);

	return string_hash_make(key);
}

static bool vrrp_hash_cmp(const void *arg1, const void *arg2)
{
	const struct vrrp_vrouter *vr1 = arg1;
	const struct vrrp_vrouter *vr2 = arg2;

	if (vr1->ifp != vr2->ifp)
		return 0;
	if (vr1->vrid != vr2->vrid)
		return 0;

	return 1;
}

void vrrp_init(void)
{
	vrrp_autoconfig_version = 3;
	vrrp_vrouters_hash = hash_create(&vrrp_hash_key, vrrp_hash_cmp,
					 "VRRP virtual router hash");
	vrf_init(NULL, NULL, NULL, NULL, NULL);
}