xref: /netbsd-src/sys/netinet/ip_carp.c (revision b757af438b42b93f8c6571f026d8b8ef3eaf5fc9)
1 /*	$NetBSD: ip_carp.c,v 1.48 2012/03/27 17:48:17 bouyer Exp $	*/
2 /*	$OpenBSD: ip_carp.c,v 1.113 2005/11/04 08:11:54 mcbride Exp $	*/
3 
4 /*
5  * Copyright (c) 2002 Michael Shalayeff. All rights reserved.
6  * Copyright (c) 2003 Ryan McBride. All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20  * IN NO EVENT SHALL THE AUTHOR OR HIS RELATIVES BE LIABLE FOR ANY DIRECT,
21  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
22  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
23  * SERVICES; LOSS OF MIND, USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
25  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
26  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
27  * THE POSSIBILITY OF SUCH DAMAGE.
28  */
29 
30 #include "opt_inet.h"
31 
32 #include <sys/cdefs.h>
33 __KERNEL_RCSID(0, "$NetBSD: ip_carp.c,v 1.48 2012/03/27 17:48:17 bouyer Exp $");
34 
35 /*
36  * TODO:
37  *	- iface reconfigure
38  *	- support for hardware checksum calculations;
39  *
40  */
41 
42 #include <sys/param.h>
43 #include <sys/proc.h>
44 #include <sys/mbuf.h>
45 #include <sys/socket.h>
46 #include <sys/socketvar.h>
47 #include <sys/callout.h>
48 #include <sys/ioctl.h>
49 #include <sys/errno.h>
50 #include <sys/device.h>
51 #include <sys/time.h>
52 #include <sys/kernel.h>
53 #include <sys/kauth.h>
54 #include <sys/sysctl.h>
55 #include <sys/ucred.h>
56 #include <sys/syslog.h>
57 #include <sys/acct.h>
58 #include <sys/cprng.h>
59 
60 #include <sys/cpu.h>
61 
62 #include <net/if.h>
63 #include <net/pfil.h>
64 #include <net/if_types.h>
65 #include <net/if_ether.h>
66 #include <net/route.h>
67 #include <net/netisr.h>
68 #include <net/net_stats.h>
69 #include <netinet/if_inarp.h>
70 
71 #if NFDDI > 0
72 #include <net/if_fddi.h>
73 #endif
74 #if NTOKEN > 0
75 #include <net/if_token.h>
76 #endif
77 
78 #ifdef INET
79 #include <netinet/in.h>
80 #include <netinet/in_systm.h>
81 #include <netinet/in_var.h>
82 #include <netinet/ip.h>
83 #include <netinet/ip_var.h>
84 
85 #include <net/if_dl.h>
86 #endif
87 
88 #ifdef INET6
89 #include <netinet/icmp6.h>
90 #include <netinet/ip6.h>
91 #include <netinet6/ip6_var.h>
92 #include <netinet6/nd6.h>
93 #include <netinet6/scope6_var.h>
94 #endif
95 
96 #include <net/bpf.h>
97 
98 #include <sys/sha1.h>
99 
100 #include <netinet/ip_carp.h>
101 
102 struct carp_mc_entry {
103 	LIST_ENTRY(carp_mc_entry)	mc_entries;
104 	union {
105 		struct ether_multi	*mcu_enm;
106 	} mc_u;
107 	struct sockaddr_storage		mc_addr;
108 };
109 #define	mc_enm	mc_u.mcu_enm
110 
111 struct carp_softc {
112 	struct ethercom sc_ac;
113 #define	sc_if		sc_ac.ec_if
114 #define	sc_carpdev	sc_ac.ec_if.if_carpdev
115 	int ah_cookie;
116 	int lh_cookie;
117 	struct ip_moptions sc_imo;
118 #ifdef INET6
119 	struct ip6_moptions sc_im6o;
120 #endif /* INET6 */
121 	TAILQ_ENTRY(carp_softc) sc_list;
122 
123 	enum { INIT = 0, BACKUP, MASTER }	sc_state;
124 
125 	int sc_suppress;
126 	int sc_bow_out;
127 
128 	int sc_sendad_errors;
129 #define CARP_SENDAD_MAX_ERRORS	3
130 	int sc_sendad_success;
131 #define CARP_SENDAD_MIN_SUCCESS 3
132 
133 	int sc_vhid;
134 	int sc_advskew;
135 	int sc_naddrs;
136 	int sc_naddrs6;
137 	int sc_advbase;		/* seconds */
138 	int sc_init_counter;
139 	u_int64_t sc_counter;
140 
141 	/* authentication */
142 #define CARP_HMAC_PAD	64
143 	unsigned char sc_key[CARP_KEY_LEN];
144 	unsigned char sc_pad[CARP_HMAC_PAD];
145 	SHA1_CTX sc_sha1;
146 	u_int32_t sc_hashkey[2];
147 
148 	struct callout sc_ad_tmo;	/* advertisement timeout */
149 	struct callout sc_md_tmo;	/* master down timeout */
150 	struct callout sc_md6_tmo;	/* master down timeout */
151 
152 	LIST_HEAD(__carp_mchead, carp_mc_entry)	carp_mc_listhead;
153 };
154 
155 int carp_suppress_preempt = 0;
156 int carp_opts[CARPCTL_MAXID] = { 0, 1, 0, 0, 0 };	/* XXX for now */
157 
158 static percpu_t *carpstat_percpu;
159 
160 #define	CARP_STATINC(x)		_NET_STATINC(carpstat_percpu, x)
161 
162 struct carp_if {
163 	TAILQ_HEAD(, carp_softc) vhif_vrs;
164 	int vhif_nvrs;
165 
166 	struct ifnet *vhif_ifp;
167 };
168 
169 #define	CARP_LOG(sc, s)							\
170 	if (carp_opts[CARPCTL_LOG]) {					\
171 		if (sc)							\
172 			log(LOG_INFO, "%s: ",				\
173 			    (sc)->sc_if.if_xname);			\
174 		else							\
175 			log(LOG_INFO, "carp: ");			\
176 		addlog s;						\
177 		addlog("\n");						\
178 	}
179 
180 void	carp_hmac_prepare(struct carp_softc *);
181 void	carp_hmac_generate(struct carp_softc *, u_int32_t *,
182 	    unsigned char *);
183 int	carp_hmac_verify(struct carp_softc *, u_int32_t *,
184 	    unsigned char *);
185 void	carp_setroute(struct carp_softc *, int);
186 void	carp_proto_input_c(struct mbuf *, struct carp_header *, sa_family_t);
187 void	carpattach(int);
188 void	carpdetach(struct carp_softc *);
189 int	carp_prepare_ad(struct mbuf *, struct carp_softc *,
190 	    struct carp_header *);
191 void	carp_send_ad_all(void);
192 void	carp_send_ad(void *);
193 void	carp_send_arp(struct carp_softc *);
194 void	carp_master_down(void *);
195 int	carp_ioctl(struct ifnet *, u_long, void *);
196 void	carp_start(struct ifnet *);
197 void	carp_setrun(struct carp_softc *, sa_family_t);
198 void	carp_set_state(struct carp_softc *, int);
199 int	carp_addrcount(struct carp_if *, struct in_ifaddr *, int);
200 enum	{ CARP_COUNT_MASTER, CARP_COUNT_RUNNING };
201 
202 void	carp_multicast_cleanup(struct carp_softc *);
203 int	carp_set_ifp(struct carp_softc *, struct ifnet *);
204 void	carp_set_enaddr(struct carp_softc *);
205 void	carp_addr_updated(void *);
206 u_int32_t	carp_hash(struct carp_softc *, u_char *);
207 int	carp_set_addr(struct carp_softc *, struct sockaddr_in *);
208 int	carp_join_multicast(struct carp_softc *);
209 #ifdef INET6
210 void	carp_send_na(struct carp_softc *);
211 int	carp_set_addr6(struct carp_softc *, struct sockaddr_in6 *);
212 int	carp_join_multicast6(struct carp_softc *);
213 #endif
214 int	carp_clone_create(struct if_clone *, int);
215 int	carp_clone_destroy(struct ifnet *);
216 int	carp_ether_addmulti(struct carp_softc *, struct ifreq *);
217 int	carp_ether_delmulti(struct carp_softc *, struct ifreq *);
218 void	carp_ether_purgemulti(struct carp_softc *);
219 
220 static void sysctl_net_inet_carp_setup(struct sysctllog **);
221 
222 struct if_clone carp_cloner =
223     IF_CLONE_INITIALIZER("carp", carp_clone_create, carp_clone_destroy);
224 
225 static __inline u_int16_t
226 carp_cksum(struct mbuf *m, int len)
227 {
228 	return (in_cksum(m, len));
229 }
230 
231 void
232 carp_hmac_prepare(struct carp_softc *sc)
233 {
234 	u_int8_t carp_version = CARP_VERSION, type = CARP_ADVERTISEMENT;
235 	u_int8_t vhid = sc->sc_vhid & 0xff;
236 	SHA1_CTX sha1ctx;
237 	u_int32_t kmd[5];
238 	struct ifaddr *ifa;
239 	int i, found;
240 	struct in_addr last, cur, in;
241 #ifdef INET6
242 	struct in6_addr last6, cur6, in6;
243 #endif /* INET6 */
244 
245 	/* compute ipad from key */
246 	memset(sc->sc_pad, 0, sizeof(sc->sc_pad));
247 	memcpy(sc->sc_pad, sc->sc_key, sizeof(sc->sc_key));
248 	for (i = 0; i < sizeof(sc->sc_pad); i++)
249 		sc->sc_pad[i] ^= 0x36;
250 
251 	/* precompute first part of inner hash */
252 	SHA1Init(&sc->sc_sha1);
253 	SHA1Update(&sc->sc_sha1, sc->sc_pad, sizeof(sc->sc_pad));
254 	SHA1Update(&sc->sc_sha1, (void *)&carp_version, sizeof(carp_version));
255 	SHA1Update(&sc->sc_sha1, (void *)&type, sizeof(type));
256 
257 	/* generate a key for the arpbalance hash, before the vhid is hashed */
258 	memcpy(&sha1ctx, &sc->sc_sha1, sizeof(sha1ctx));
259 	SHA1Final((unsigned char *)kmd, &sha1ctx);
260 	sc->sc_hashkey[0] = kmd[0] ^ kmd[1];
261 	sc->sc_hashkey[1] = kmd[2] ^ kmd[3];
262 
263 	/* the rest of the precomputation */
264 	SHA1Update(&sc->sc_sha1, (void *)&vhid, sizeof(vhid));
265 
266 	/* Hash the addresses from smallest to largest, not interface order */
267 #ifdef INET
268 	cur.s_addr = 0;
269 	do {
270 		found = 0;
271 		last = cur;
272 		cur.s_addr = 0xffffffff;
273 		IFADDR_FOREACH(ifa, &sc->sc_if) {
274 			in.s_addr = ifatoia(ifa)->ia_addr.sin_addr.s_addr;
275 			if (ifa->ifa_addr->sa_family == AF_INET &&
276 			    ntohl(in.s_addr) > ntohl(last.s_addr) &&
277 			    ntohl(in.s_addr) < ntohl(cur.s_addr)) {
278 				cur.s_addr = in.s_addr;
279 				found++;
280 			}
281 		}
282 		if (found)
283 			SHA1Update(&sc->sc_sha1, (void *)&cur, sizeof(cur));
284 	} while (found);
285 #endif /* INET */
286 
287 #ifdef INET6
288 	memset(&cur6, 0x00, sizeof(cur6));
289 	do {
290 		found = 0;
291 		last6 = cur6;
292 		memset(&cur6, 0xff, sizeof(cur6));
293 		IFADDR_FOREACH(ifa, &sc->sc_if) {
294 			in6 = ifatoia6(ifa)->ia_addr.sin6_addr;
295 			if (IN6_IS_ADDR_LINKLOCAL(&in6))
296 				in6.s6_addr16[1] = 0;
297 			if (ifa->ifa_addr->sa_family == AF_INET6 &&
298 			    memcmp(&in6, &last6, sizeof(in6)) > 0 &&
299 			    memcmp(&in6, &cur6, sizeof(in6)) < 0) {
300 				cur6 = in6;
301 				found++;
302 			}
303 		}
304 		if (found)
305 			SHA1Update(&sc->sc_sha1, (void *)&cur6, sizeof(cur6));
306 	} while (found);
307 #endif /* INET6 */
308 
309 	/* convert ipad to opad */
310 	for (i = 0; i < sizeof(sc->sc_pad); i++)
311 		sc->sc_pad[i] ^= 0x36 ^ 0x5c;
312 }
313 
314 void
315 carp_hmac_generate(struct carp_softc *sc, u_int32_t counter[2],
316     unsigned char md[20])
317 {
318 	SHA1_CTX sha1ctx;
319 
320 	/* fetch first half of inner hash */
321 	memcpy(&sha1ctx, &sc->sc_sha1, sizeof(sha1ctx));
322 
323 	SHA1Update(&sha1ctx, (void *)counter, sizeof(sc->sc_counter));
324 	SHA1Final(md, &sha1ctx);
325 
326 	/* outer hash */
327 	SHA1Init(&sha1ctx);
328 	SHA1Update(&sha1ctx, sc->sc_pad, sizeof(sc->sc_pad));
329 	SHA1Update(&sha1ctx, md, 20);
330 	SHA1Final(md, &sha1ctx);
331 }
332 
333 int
334 carp_hmac_verify(struct carp_softc *sc, u_int32_t counter[2],
335     unsigned char md[20])
336 {
337 	unsigned char md2[20];
338 
339 	carp_hmac_generate(sc, counter, md2);
340 
341 	return (memcmp(md, md2, sizeof(md2)));
342 }
343 
344 void
345 carp_setroute(struct carp_softc *sc, int cmd)
346 {
347 	struct ifaddr *ifa;
348 	int s;
349 
350 	s = splsoftnet();
351 	IFADDR_FOREACH(ifa, &sc->sc_if) {
352 		switch (ifa->ifa_addr->sa_family) {
353 		case AF_INET: {
354 			int count = 0;
355 			struct rtentry *rt;
356 			int hr_otherif, nr_ourif;
357 
358 			/*
359 			 * Avoid screwing with the routes if there are other
360 			 * carp interfaces which are master and have the same
361 			 * address.
362 			 */
363 			if (sc->sc_carpdev != NULL &&
364 			    sc->sc_carpdev->if_carp != NULL) {
365 				count = carp_addrcount(
366 				    (struct carp_if *)sc->sc_carpdev->if_carp,
367 				    ifatoia(ifa), CARP_COUNT_MASTER);
368 				if ((cmd == RTM_ADD && count != 1) ||
369 				    (cmd == RTM_DELETE && count != 0))
370 					continue;
371 			}
372 
373 			/* Remove the existing host route, if any */
374 			rtrequest(RTM_DELETE, ifa->ifa_addr,
375 			    ifa->ifa_addr, ifa->ifa_netmask,
376 			    RTF_HOST, NULL);
377 
378 			rt = NULL;
379 			(void)rtrequest(RTM_GET, ifa->ifa_addr, ifa->ifa_addr,
380 			    ifa->ifa_netmask, RTF_HOST, &rt);
381 			hr_otherif = (rt && rt->rt_ifp != &sc->sc_if &&
382 			    rt->rt_flags & (RTF_CLONING|RTF_CLONED));
383 			if (rt != NULL) {
384 				RTFREE(rt);
385 				rt = NULL;
386 			}
387 
388 			/* Check for a network route on our interface */
389 
390 			rt = NULL;
391 			(void)rtrequest(RTM_GET, ifa->ifa_addr, ifa->ifa_addr,
392 			    ifa->ifa_netmask, 0, &rt);
393 			nr_ourif = (rt && rt->rt_ifp == &sc->sc_if);
394 
395 			switch (cmd) {
396 			case RTM_ADD:
397 				if (hr_otherif) {
398 					ifa->ifa_rtrequest = NULL;
399 					ifa->ifa_flags &= ~RTF_CLONING;
400 
401 					rtrequest(RTM_ADD, ifa->ifa_addr,
402 					    ifa->ifa_addr, ifa->ifa_netmask,
403 					    RTF_UP | RTF_HOST, NULL);
404 				}
405 				if (!hr_otherif || nr_ourif || !rt) {
406 					if (nr_ourif && !(rt->rt_flags &
407 					    RTF_CLONING))
408 						rtrequest(RTM_DELETE,
409 						    ifa->ifa_addr,
410 						    ifa->ifa_addr,
411 						    ifa->ifa_netmask, 0, NULL);
412 
413 					ifa->ifa_rtrequest = arp_rtrequest;
414 					ifa->ifa_flags |= RTF_CLONING;
415 
416 					if (rtrequest(RTM_ADD, ifa->ifa_addr,
417 					    ifa->ifa_addr, ifa->ifa_netmask, 0,
418 					    NULL) == 0)
419 						ifa->ifa_flags |= IFA_ROUTE;
420 				}
421 				break;
422 			case RTM_DELETE:
423 				break;
424 			default:
425 				break;
426 			}
427 			if (rt != NULL) {
428 				RTFREE(rt);
429 				rt = NULL;
430 			}
431 			break;
432 		}
433 
434 #ifdef INET6
435 		case AF_INET6:
436 			if (cmd == RTM_ADD)
437 				in6_ifaddloop(ifa);
438 			else
439 				in6_ifremloop(ifa);
440 			break;
441 #endif /* INET6 */
442 		default:
443 			break;
444 		}
445 	}
446 	splx(s);
447 }
448 
449 /*
450  * process input packet.
451  * we have rearranged checks order compared to the rfc,
452  * but it seems more efficient this way or not possible otherwise.
453  */
454 void
455 carp_proto_input(struct mbuf *m, ...)
456 {
457 	struct ip *ip = mtod(m, struct ip *);
458 	struct carp_softc *sc = NULL;
459 	struct carp_header *ch;
460 	int iplen, len, hlen;
461 	va_list ap;
462 
463 	va_start(ap, m);
464 	hlen = va_arg(ap, int);
465 	va_end(ap);
466 
467 	CARP_STATINC(CARP_STAT_IPACKETS);
468 
469 	if (!carp_opts[CARPCTL_ALLOW]) {
470 		m_freem(m);
471 		return;
472 	}
473 
474 	/* check if received on a valid carp interface */
475 	if (m->m_pkthdr.rcvif->if_type != IFT_CARP) {
476 		CARP_STATINC(CARP_STAT_BADIF);
477 		CARP_LOG(sc, ("packet received on non-carp interface: %s",
478 		    m->m_pkthdr.rcvif->if_xname));
479 		m_freem(m);
480 		return;
481 	}
482 
483 	/* verify that the IP TTL is 255.  */
484 	if (ip->ip_ttl != CARP_DFLTTL) {
485 		CARP_STATINC(CARP_STAT_BADTTL);
486 		CARP_LOG(sc, ("received ttl %d != %d on %s", ip->ip_ttl,
487 		    CARP_DFLTTL, m->m_pkthdr.rcvif->if_xname));
488 		m_freem(m);
489 		return;
490 	}
491 
492 	/*
493 	 * verify that the received packet length is
494 	 * equal to the CARP header
495 	 */
496 	iplen = ip->ip_hl << 2;
497 	len = iplen + sizeof(*ch);
498 	if (len > m->m_pkthdr.len) {
499 		CARP_STATINC(CARP_STAT_BADLEN);
500 		CARP_LOG(sc, ("packet too short %d on %s", m->m_pkthdr.len,
501 		    m->m_pkthdr.rcvif->if_xname));
502 		m_freem(m);
503 		return;
504 	}
505 
506 	if ((m = m_pullup(m, len)) == NULL) {
507 		CARP_STATINC(CARP_STAT_HDROPS);
508 		return;
509 	}
510 	ip = mtod(m, struct ip *);
511 	ch = (struct carp_header *)((char *)ip + iplen);
512 	/* verify the CARP checksum */
513 	m->m_data += iplen;
514 	if (carp_cksum(m, len - iplen)) {
515 		CARP_STATINC(CARP_STAT_BADSUM);
516 		CARP_LOG(sc, ("checksum failed on %s",
517 		    m->m_pkthdr.rcvif->if_xname));
518 		m_freem(m);
519 		return;
520 	}
521 	m->m_data -= iplen;
522 
523 	carp_proto_input_c(m, ch, AF_INET);
524 }
525 
526 #ifdef INET6
527 int
528 carp6_proto_input(struct mbuf **mp, int *offp, int proto)
529 {
530 	struct mbuf *m = *mp;
531 	struct carp_softc *sc = NULL;
532 	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
533 	struct carp_header *ch;
534 	u_int len;
535 
536 	CARP_STATINC(CARP_STAT_IPACKETS6);
537 
538 	if (!carp_opts[CARPCTL_ALLOW]) {
539 		m_freem(m);
540 		return (IPPROTO_DONE);
541 	}
542 
543 	/* check if received on a valid carp interface */
544 	if (m->m_pkthdr.rcvif->if_type != IFT_CARP) {
545 		CARP_STATINC(CARP_STAT_BADIF);
546 		CARP_LOG(sc, ("packet received on non-carp interface: %s",
547 		    m->m_pkthdr.rcvif->if_xname));
548 		m_freem(m);
549 		return (IPPROTO_DONE);
550 	}
551 
552 	/* verify that the IP TTL is 255 */
553 	if (ip6->ip6_hlim != CARP_DFLTTL) {
554 		CARP_STATINC(CARP_STAT_BADTTL);
555 		CARP_LOG(sc, ("received ttl %d != %d on %s", ip6->ip6_hlim,
556 		    CARP_DFLTTL, m->m_pkthdr.rcvif->if_xname));
557 		m_freem(m);
558 		return (IPPROTO_DONE);
559 	}
560 
561 	/* verify that we have a complete carp packet */
562 	len = m->m_len;
563 	IP6_EXTHDR_GET(ch, struct carp_header *, m, *offp, sizeof(*ch));
564 	if (ch == NULL) {
565 		CARP_STATINC(CARP_STAT_BADLEN);
566 		CARP_LOG(sc, ("packet size %u too small", len));
567 		return (IPPROTO_DONE);
568 	}
569 
570 
571 	/* verify the CARP checksum */
572 	m->m_data += *offp;
573 	if (carp_cksum(m, sizeof(*ch))) {
574 		CARP_STATINC(CARP_STAT_BADSUM);
575 		CARP_LOG(sc, ("checksum failed, on %s",
576 		    m->m_pkthdr.rcvif->if_xname));
577 		m_freem(m);
578 		return (IPPROTO_DONE);
579 	}
580 	m->m_data -= *offp;
581 
582 	carp_proto_input_c(m, ch, AF_INET6);
583 	return (IPPROTO_DONE);
584 }
585 #endif /* INET6 */
586 
587 void
588 carp_proto_input_c(struct mbuf *m, struct carp_header *ch, sa_family_t af)
589 {
590 	struct carp_softc *sc;
591 	u_int64_t tmp_counter;
592 	struct timeval sc_tv, ch_tv;
593 
594 	TAILQ_FOREACH(sc, &((struct carp_if *)
595 	    m->m_pkthdr.rcvif->if_carpdev->if_carp)->vhif_vrs, sc_list)
596 		if (sc->sc_vhid == ch->carp_vhid)
597 			break;
598 
599 	if (!sc || (sc->sc_if.if_flags & (IFF_UP|IFF_RUNNING)) !=
600 	    (IFF_UP|IFF_RUNNING)) {
601 		CARP_STATINC(CARP_STAT_BADVHID);
602 		m_freem(m);
603 		return;
604 	}
605 
606 	/*
607 	 * Check if our own advertisement was duplicated
608 	 * from a non simplex interface.
609 	 * XXX If there is no address on our physical interface
610 	 * there is no way to distinguish our ads from the ones
611 	 * another carp host might have sent us.
612 	 */
613 	if ((sc->sc_carpdev->if_flags & IFF_SIMPLEX) == 0) {
614 		struct sockaddr sa;
615 		struct ifaddr *ifa;
616 
617 		memset(&sa, 0, sizeof(sa));
618 		sa.sa_family = af;
619 		ifa = ifaof_ifpforaddr(&sa, sc->sc_carpdev);
620 
621 		if (ifa && af == AF_INET) {
622 			struct ip *ip = mtod(m, struct ip *);
623 			if (ip->ip_src.s_addr ==
624 					ifatoia(ifa)->ia_addr.sin_addr.s_addr) {
625 				m_freem(m);
626 				return;
627 			}
628 		}
629 #ifdef INET6
630 		if (ifa && af == AF_INET6) {
631 			struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
632 			struct in6_addr in6_src, in6_found;
633 
634 			in6_src = ip6->ip6_src;
635 			in6_found = ifatoia6(ifa)->ia_addr.sin6_addr;
636 			if (IN6_IS_ADDR_LINKLOCAL(&in6_src))
637 				in6_src.s6_addr16[1] = 0;
638 			if (IN6_IS_ADDR_LINKLOCAL(&in6_found))
639 				in6_found.s6_addr16[1] = 0;
640 			if (IN6_ARE_ADDR_EQUAL(&in6_src, &in6_found)) {
641 				m_freem(m);
642 				return;
643 			}
644 		}
645 #endif /* INET6 */
646 	}
647 
648 	nanotime(&sc->sc_if.if_lastchange);
649 	sc->sc_if.if_ipackets++;
650 	sc->sc_if.if_ibytes += m->m_pkthdr.len;
651 
652 	/* verify the CARP version. */
653 	if (ch->carp_version != CARP_VERSION) {
654 		CARP_STATINC(CARP_STAT_BADVER);
655 		sc->sc_if.if_ierrors++;
656 		CARP_LOG(sc, ("invalid version %d != %d",
657 		    ch->carp_version, CARP_VERSION));
658 		m_freem(m);
659 		return;
660 	}
661 
662 	/* verify the hash */
663 	if (carp_hmac_verify(sc, ch->carp_counter, ch->carp_md)) {
664 		CARP_STATINC(CARP_STAT_BADAUTH);
665 		sc->sc_if.if_ierrors++;
666 		CARP_LOG(sc, ("incorrect hash"));
667 		m_freem(m);
668 		return;
669 	}
670 
671 	tmp_counter = ntohl(ch->carp_counter[0]);
672 	tmp_counter = tmp_counter<<32;
673 	tmp_counter += ntohl(ch->carp_counter[1]);
674 
675 	/* XXX Replay protection goes here */
676 
677 	sc->sc_init_counter = 0;
678 	sc->sc_counter = tmp_counter;
679 
680 
681 	sc_tv.tv_sec = sc->sc_advbase;
682 	if (carp_suppress_preempt && sc->sc_advskew <  240)
683 		sc_tv.tv_usec = 240 * 1000000 / 256;
684 	else
685 		sc_tv.tv_usec = sc->sc_advskew * 1000000 / 256;
686 	ch_tv.tv_sec = ch->carp_advbase;
687 	ch_tv.tv_usec = ch->carp_advskew * 1000000 / 256;
688 
689 	switch (sc->sc_state) {
690 	case INIT:
691 		break;
692 	case MASTER:
693 		/*
694 		 * If we receive an advertisement from a backup who's going to
695 		 * be more frequent than us, go into BACKUP state.
696 		 */
697 		if (timercmp(&sc_tv, &ch_tv, >) ||
698 		    timercmp(&sc_tv, &ch_tv, ==)) {
699 			callout_stop(&sc->sc_ad_tmo);
700 			CARP_LOG(sc, ("MASTER -> BACKUP (more frequent advertisement received)"));
701 			carp_set_state(sc, BACKUP);
702 			carp_setrun(sc, 0);
703 			carp_setroute(sc, RTM_DELETE);
704 		}
705 		break;
706 	case BACKUP:
707 		/*
708 		 * If we're pre-empting masters who advertise slower than us,
709 		 * and this one claims to be slower, treat him as down.
710 		 */
711 		if (carp_opts[CARPCTL_PREEMPT] && timercmp(&sc_tv, &ch_tv, <)) {
712 			CARP_LOG(sc, ("BACKUP -> MASTER (preempting a slower master)"));
713 			carp_master_down(sc);
714 			break;
715 		}
716 
717 		/*
718 		 *  If the master is going to advertise at such a low frequency
719 		 *  that he's guaranteed to time out, we'd might as well just
720 		 *  treat him as timed out now.
721 		 */
722 		sc_tv.tv_sec = sc->sc_advbase * 3;
723 		if (timercmp(&sc_tv, &ch_tv, <)) {
724 			CARP_LOG(sc, ("BACKUP -> MASTER (master timed out)"));
725 			carp_master_down(sc);
726 			break;
727 		}
728 
729 		/*
730 		 * Otherwise, we reset the counter and wait for the next
731 		 * advertisement.
732 		 */
733 		carp_setrun(sc, af);
734 		break;
735 	}
736 
737 	m_freem(m);
738 	return;
739 }
740 
741 /*
742  * Interface side of the CARP implementation.
743  */
744 
745 /* ARGSUSED */
746 void
747 carpattach(int n)
748 {
749 	if_clone_attach(&carp_cloner);
750 
751 	carpstat_percpu = percpu_alloc(sizeof(uint64_t) * CARP_NSTATS);
752 }
753 
754 int
755 carp_clone_create(struct if_clone *ifc, int unit)
756 {
757 	extern int ifqmaxlen;
758 	struct carp_softc *sc;
759 	struct ifnet *ifp;
760 
761 	sc = malloc(sizeof(*sc), M_DEVBUF, M_NOWAIT|M_ZERO);
762 	if (!sc)
763 		return (ENOMEM);
764 
765 	sc->sc_suppress = 0;
766 	sc->sc_advbase = CARP_DFLTINTV;
767 	sc->sc_vhid = -1;	/* required setting */
768 	sc->sc_advskew = 0;
769 	sc->sc_init_counter = 1;
770 	sc->sc_naddrs = sc->sc_naddrs6 = 0;
771 #ifdef INET6
772 	sc->sc_im6o.im6o_multicast_hlim = CARP_DFLTTL;
773 #endif /* INET6 */
774 
775 	callout_init(&sc->sc_ad_tmo, 0);
776 	callout_init(&sc->sc_md_tmo, 0);
777 	callout_init(&sc->sc_md6_tmo, 0);
778 
779 	callout_setfunc(&sc->sc_ad_tmo, carp_send_ad, sc);
780 	callout_setfunc(&sc->sc_md_tmo, carp_master_down, sc);
781 	callout_setfunc(&sc->sc_md6_tmo, carp_master_down, sc);
782 
783 	LIST_INIT(&sc->carp_mc_listhead);
784 	ifp = &sc->sc_if;
785 	ifp->if_softc = sc;
786 	snprintf(ifp->if_xname, sizeof ifp->if_xname, "%s%d", ifc->ifc_name,
787 	    unit);
788 	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
789 	ifp->if_ioctl = carp_ioctl;
790 	ifp->if_start = carp_start;
791 	ifp->if_output = carp_output;
792 	ifp->if_type = IFT_CARP;
793 	ifp->if_addrlen = ETHER_ADDR_LEN;
794 	ifp->if_hdrlen = ETHER_HDR_LEN;
795 	ifp->if_mtu = ETHERMTU;
796 	IFQ_SET_MAXLEN(&ifp->if_snd, ifqmaxlen);
797 	IFQ_SET_READY(&ifp->if_snd);
798 	if_attach(ifp);
799 
800 	if_alloc_sadl(ifp);
801 	ifp->if_broadcastaddr = etherbroadcastaddr;
802 	carp_set_enaddr(sc);
803 	LIST_INIT(&sc->sc_ac.ec_multiaddrs);
804 	bpf_attach(ifp, DLT_EN10MB, ETHER_HDR_LEN);
805 	return (0);
806 }
807 
808 int
809 carp_clone_destroy(struct ifnet *ifp)
810 {
811 	struct carp_softc *sc = ifp->if_softc;
812 
813 	carpdetach(ifp->if_softc);
814 	ether_ifdetach(ifp);
815 	if_detach(ifp);
816 	callout_destroy(&sc->sc_ad_tmo);
817 	callout_destroy(&sc->sc_md_tmo);
818 	callout_destroy(&sc->sc_md6_tmo);
819 	free(ifp->if_softc, M_DEVBUF);
820 
821 	return (0);
822 }
823 
824 void
825 carpdetach(struct carp_softc *sc)
826 {
827 	struct carp_if *cif;
828 	int s;
829 
830 	callout_stop(&sc->sc_ad_tmo);
831 	callout_stop(&sc->sc_md_tmo);
832 	callout_stop(&sc->sc_md6_tmo);
833 
834 	if (sc->sc_suppress)
835 		carp_suppress_preempt--;
836 	sc->sc_suppress = 0;
837 
838 	if (sc->sc_sendad_errors >= CARP_SENDAD_MAX_ERRORS)
839 		carp_suppress_preempt--;
840 	sc->sc_sendad_errors = 0;
841 
842 	carp_set_state(sc, INIT);
843 	sc->sc_if.if_flags &= ~IFF_UP;
844 	carp_setrun(sc, 0);
845 	carp_multicast_cleanup(sc);
846 
847 	s = splnet();
848 	if (sc->sc_carpdev != NULL) {
849 		/* XXX linkstatehook removal */
850 		cif = (struct carp_if *)sc->sc_carpdev->if_carp;
851 		TAILQ_REMOVE(&cif->vhif_vrs, sc, sc_list);
852 		if (!--cif->vhif_nvrs) {
853 			ifpromisc(sc->sc_carpdev, 0);
854 			sc->sc_carpdev->if_carp = NULL;
855 			free(cif, M_IFADDR);
856 		}
857 	}
858 	sc->sc_carpdev = NULL;
859 	splx(s);
860 }
861 
862 /* Detach an interface from the carp. */
863 void
864 carp_ifdetach(struct ifnet *ifp)
865 {
866 	struct carp_softc *sc, *nextsc;
867 	struct carp_if *cif = (struct carp_if *)ifp->if_carp;
868 
869 	for (sc = TAILQ_FIRST(&cif->vhif_vrs); sc; sc = nextsc) {
870 		nextsc = TAILQ_NEXT(sc, sc_list);
871 		carpdetach(sc);
872 	}
873 }
874 
875 int
876 carp_prepare_ad(struct mbuf *m, struct carp_softc *sc,
877     struct carp_header *ch)
878 {
879 	if (sc->sc_init_counter) {
880 		/* this could also be seconds since unix epoch */
881 		sc->sc_counter = cprng_fast64();
882 	} else
883 		sc->sc_counter++;
884 
885 	ch->carp_counter[0] = htonl((sc->sc_counter>>32)&0xffffffff);
886 	ch->carp_counter[1] = htonl(sc->sc_counter&0xffffffff);
887 
888 	carp_hmac_generate(sc, ch->carp_counter, ch->carp_md);
889 
890 	return (0);
891 }
892 
893 void
894 carp_send_ad_all(void)
895 {
896 	struct ifnet *ifp;
897 	struct carp_if *cif;
898 	struct carp_softc *vh;
899 
900 	TAILQ_FOREACH(ifp, &ifnet, if_list) {
901 		if (ifp->if_carp == NULL || ifp->if_type == IFT_CARP)
902 			continue;
903 
904 		cif = (struct carp_if *)ifp->if_carp;
905 		TAILQ_FOREACH(vh, &cif->vhif_vrs, sc_list) {
906 			if ((vh->sc_if.if_flags & (IFF_UP|IFF_RUNNING)) ==
907 			    (IFF_UP|IFF_RUNNING) && vh->sc_state == MASTER)
908 				carp_send_ad(vh);
909 		}
910 	}
911 }
912 
913 
914 void
915 carp_send_ad(void *v)
916 {
917 	struct carp_header ch;
918 	struct timeval tv;
919 	struct carp_softc *sc = v;
920 	struct carp_header *ch_ptr;
921 	struct mbuf *m;
922 	int error, len, advbase, advskew, s;
923 	struct ifaddr *ifa;
924 	struct sockaddr sa;
925 
926 	s = splsoftnet();
927 
928 	advbase = advskew = 0; /* Sssssh compiler */
929 	if (sc->sc_carpdev == NULL) {
930 		sc->sc_if.if_oerrors++;
931 		goto retry_later;
932 	}
933 
934 	/* bow out if we've gone to backup (the carp interface is going down) */
935 	if (sc->sc_bow_out) {
936 		sc->sc_bow_out = 0;
937 		advbase = 255;
938 		advskew = 255;
939 	} else {
940 		advbase = sc->sc_advbase;
941 		if (!carp_suppress_preempt || sc->sc_advskew > 240)
942 			advskew = sc->sc_advskew;
943 		else
944 			advskew = 240;
945 		tv.tv_sec = advbase;
946 		tv.tv_usec = advskew * 1000000 / 256;
947 	}
948 
949 	ch.carp_version = CARP_VERSION;
950 	ch.carp_type = CARP_ADVERTISEMENT;
951 	ch.carp_vhid = sc->sc_vhid;
952 	ch.carp_advbase = advbase;
953 	ch.carp_advskew = advskew;
954 	ch.carp_authlen = 7;	/* XXX DEFINE */
955 	ch.carp_pad1 = 0;	/* must be zero */
956 	ch.carp_cksum = 0;
957 
958 
959 #ifdef INET
960 	if (sc->sc_naddrs) {
961 		struct ip *ip;
962 
963 		MGETHDR(m, M_DONTWAIT, MT_HEADER);
964 		if (m == NULL) {
965 			sc->sc_if.if_oerrors++;
966 			CARP_STATINC(CARP_STAT_ONOMEM);
967 			/* XXX maybe less ? */
968 			goto retry_later;
969 		}
970 		len = sizeof(*ip) + sizeof(ch);
971 		m->m_pkthdr.len = len;
972 		m->m_pkthdr.rcvif = NULL;
973 		m->m_len = len;
974 		MH_ALIGN(m, m->m_len);
975 		m->m_flags |= M_MCAST;
976 		ip = mtod(m, struct ip *);
977 		ip->ip_v = IPVERSION;
978 		ip->ip_hl = sizeof(*ip) >> 2;
979 		ip->ip_tos = IPTOS_LOWDELAY;
980 		ip->ip_len = htons(len);
981 		ip->ip_id = 0;	/* no need for id, we don't support fragments */
982 		ip->ip_off = htons(IP_DF);
983 		ip->ip_ttl = CARP_DFLTTL;
984 		ip->ip_p = IPPROTO_CARP;
985 		ip->ip_sum = 0;
986 
987 		memset(&sa, 0, sizeof(sa));
988 		sa.sa_family = AF_INET;
989 		ifa = ifaof_ifpforaddr(&sa, sc->sc_carpdev);
990 		if (ifa == NULL)
991 			ip->ip_src.s_addr = 0;
992 		else
993 			ip->ip_src.s_addr =
994 			    ifatoia(ifa)->ia_addr.sin_addr.s_addr;
995 		ip->ip_dst.s_addr = INADDR_CARP_GROUP;
996 
997 		ch_ptr = (struct carp_header *)(&ip[1]);
998 		memcpy(ch_ptr, &ch, sizeof(ch));
999 		if (carp_prepare_ad(m, sc, ch_ptr))
1000 			goto retry_later;
1001 
1002 		m->m_data += sizeof(*ip);
1003 		ch_ptr->carp_cksum = carp_cksum(m, len - sizeof(*ip));
1004 		m->m_data -= sizeof(*ip);
1005 
1006 		nanotime(&sc->sc_if.if_lastchange);
1007 		sc->sc_if.if_opackets++;
1008 		sc->sc_if.if_obytes += len;
1009 		CARP_STATINC(CARP_STAT_OPACKETS);
1010 
1011 		error = ip_output(m, NULL, NULL, IP_RAWOUTPUT, &sc->sc_imo,
1012 		    NULL);
1013 		if (error) {
1014 			if (error == ENOBUFS)
1015 				CARP_STATINC(CARP_STAT_ONOMEM);
1016 			else
1017 				CARP_LOG(sc, ("ip_output failed: %d", error));
1018 			sc->sc_if.if_oerrors++;
1019 			if (sc->sc_sendad_errors < INT_MAX)
1020 				sc->sc_sendad_errors++;
1021 			if (sc->sc_sendad_errors == CARP_SENDAD_MAX_ERRORS) {
1022 				carp_suppress_preempt++;
1023 				if (carp_suppress_preempt == 1)
1024 					carp_send_ad_all();
1025 			}
1026 			sc->sc_sendad_success = 0;
1027 		} else {
1028 			if (sc->sc_sendad_errors >= CARP_SENDAD_MAX_ERRORS) {
1029 				if (++sc->sc_sendad_success >=
1030 				    CARP_SENDAD_MIN_SUCCESS) {
1031 					carp_suppress_preempt--;
1032 					sc->sc_sendad_errors = 0;
1033 				}
1034 			} else
1035 				sc->sc_sendad_errors = 0;
1036 		}
1037 	}
1038 #endif /* INET */
1039 #ifdef INET6
1040 	if (sc->sc_naddrs6) {
1041 		struct ip6_hdr *ip6;
1042 
1043 		MGETHDR(m, M_DONTWAIT, MT_HEADER);
1044 		if (m == NULL) {
1045 			sc->sc_if.if_oerrors++;
1046 			CARP_STATINC(CARP_STAT_ONOMEM);
1047 			/* XXX maybe less ? */
1048 			goto retry_later;
1049 		}
1050 		len = sizeof(*ip6) + sizeof(ch);
1051 		m->m_pkthdr.len = len;
1052 		m->m_pkthdr.rcvif = NULL;
1053 		m->m_len = len;
1054 		MH_ALIGN(m, m->m_len);
1055 		m->m_flags |= M_MCAST;
1056 		ip6 = mtod(m, struct ip6_hdr *);
1057 		memset(ip6, 0, sizeof(*ip6));
1058 		ip6->ip6_vfc |= IPV6_VERSION;
1059 		ip6->ip6_hlim = CARP_DFLTTL;
1060 		ip6->ip6_nxt = IPPROTO_CARP;
1061 
1062 		/* set the source address */
1063 		memset(&sa, 0, sizeof(sa));
1064 		sa.sa_family = AF_INET6;
1065 		ifa = ifaof_ifpforaddr(&sa, sc->sc_carpdev);
1066 		if (ifa == NULL)	/* This should never happen with IPv6 */
1067 			memset(&ip6->ip6_src, 0, sizeof(struct in6_addr));
1068 		else
1069 			bcopy(ifatoia6(ifa)->ia_addr.sin6_addr.s6_addr,
1070 			    &ip6->ip6_src, sizeof(struct in6_addr));
1071 		/* set the multicast destination */
1072 
1073 		ip6->ip6_dst.s6_addr16[0] = htons(0xff02);
1074 		ip6->ip6_dst.s6_addr8[15] = 0x12;
1075 		if (in6_setscope(&ip6->ip6_dst, sc->sc_carpdev, NULL) != 0) {
1076 			sc->sc_if.if_oerrors++;
1077 			m_freem(m);
1078 			CARP_LOG(sc, ("in6_setscope failed"));
1079 			goto retry_later;
1080 		}
1081 
1082 		ch_ptr = (struct carp_header *)(&ip6[1]);
1083 		memcpy(ch_ptr, &ch, sizeof(ch));
1084 		if (carp_prepare_ad(m, sc, ch_ptr))
1085 			goto retry_later;
1086 
1087 		m->m_data += sizeof(*ip6);
1088 		ch_ptr->carp_cksum = carp_cksum(m, len - sizeof(*ip6));
1089 		m->m_data -= sizeof(*ip6);
1090 
1091 		nanotime(&sc->sc_if.if_lastchange);
1092 		sc->sc_if.if_opackets++;
1093 		sc->sc_if.if_obytes += len;
1094 		CARP_STATINC(CARP_STAT_OPACKETS6);
1095 
1096 		error = ip6_output(m, NULL, NULL, 0, &sc->sc_im6o, NULL, NULL);
1097 		if (error) {
1098 			if (error == ENOBUFS)
1099 				CARP_STATINC(CARP_STAT_ONOMEM);
1100 			else
1101 				CARP_LOG(sc, ("ip6_output failed: %d", error));
1102 			sc->sc_if.if_oerrors++;
1103 			if (sc->sc_sendad_errors < INT_MAX)
1104 				sc->sc_sendad_errors++;
1105 			if (sc->sc_sendad_errors == CARP_SENDAD_MAX_ERRORS) {
1106 				carp_suppress_preempt++;
1107 				if (carp_suppress_preempt == 1)
1108 					carp_send_ad_all();
1109 			}
1110 			sc->sc_sendad_success = 0;
1111 		} else {
1112 			if (sc->sc_sendad_errors >= CARP_SENDAD_MAX_ERRORS) {
1113 				if (++sc->sc_sendad_success >=
1114 				    CARP_SENDAD_MIN_SUCCESS) {
1115 					carp_suppress_preempt--;
1116 					sc->sc_sendad_errors = 0;
1117 				}
1118 			} else
1119 				sc->sc_sendad_errors = 0;
1120 		}
1121 	}
1122 #endif /* INET6 */
1123 
1124 retry_later:
1125 	splx(s);
1126 	if (advbase != 255 || advskew != 255)
1127 		callout_schedule(&sc->sc_ad_tmo, tvtohz(&tv));
1128 }
1129 
1130 /*
1131  * Broadcast a gratuitous ARP request containing
1132  * the virtual router MAC address for each IP address
1133  * associated with the virtual router.
1134  */
1135 void
1136 carp_send_arp(struct carp_softc *sc)
1137 {
1138 	struct ifaddr *ifa;
1139 	struct in_addr *in;
1140 	int s = splsoftnet();
1141 
1142 	IFADDR_FOREACH(ifa, &sc->sc_if) {
1143 
1144 		if (ifa->ifa_addr->sa_family != AF_INET)
1145 			continue;
1146 
1147 		in = &ifatoia(ifa)->ia_addr.sin_addr;
1148 		arprequest(sc->sc_carpdev, in, in, CLLADDR(sc->sc_if.if_sadl));
1149 	}
1150 	splx(s);
1151 }
1152 
1153 #ifdef INET6
1154 void
1155 carp_send_na(struct carp_softc *sc)
1156 {
1157 	struct ifaddr *ifa;
1158 	struct in6_addr *in6;
1159 	static struct in6_addr mcast = IN6ADDR_LINKLOCAL_ALLNODES_INIT;
1160 	int s = splsoftnet();
1161 
1162 	IFADDR_FOREACH(ifa, &sc->sc_if) {
1163 
1164 		if (ifa->ifa_addr->sa_family != AF_INET6)
1165 			continue;
1166 
1167 		in6 = &ifatoia6(ifa)->ia_addr.sin6_addr;
1168 		nd6_na_output(sc->sc_carpdev, &mcast, in6,
1169 		    ND_NA_FLAG_OVERRIDE, 1, NULL);
1170 	}
1171 	splx(s);
1172 }
1173 #endif /* INET6 */
1174 
1175 /*
1176  * Based on bridge_hash() in if_bridge.c
1177  */
1178 #define	mix(a,b,c) \
1179 	do {						\
1180 		a -= b; a -= c; a ^= (c >> 13);		\
1181 		b -= c; b -= a; b ^= (a << 8);		\
1182 		c -= a; c -= b; c ^= (b >> 13);		\
1183 		a -= b; a -= c; a ^= (c >> 12);		\
1184 		b -= c; b -= a; b ^= (a << 16);		\
1185 		c -= a; c -= b; c ^= (b >> 5);		\
1186 		a -= b; a -= c; a ^= (c >> 3);		\
1187 		b -= c; b -= a; b ^= (a << 10);		\
1188 		c -= a; c -= b; c ^= (b >> 15);		\
1189 	} while (0)
1190 
1191 u_int32_t
1192 carp_hash(struct carp_softc *sc, u_char *src)
1193 {
1194 	u_int32_t a = 0x9e3779b9, b = sc->sc_hashkey[0], c = sc->sc_hashkey[1];
1195 
1196 	c += sc->sc_key[3] << 24;
1197 	c += sc->sc_key[2] << 16;
1198 	c += sc->sc_key[1] << 8;
1199 	c += sc->sc_key[0];
1200 	b += src[5] << 8;
1201 	b += src[4];
1202 	a += src[3] << 24;
1203 	a += src[2] << 16;
1204 	a += src[1] << 8;
1205 	a += src[0];
1206 
1207 	mix(a, b, c);
1208 	return (c);
1209 }
1210 
1211 int
1212 carp_addrcount(struct carp_if *cif, struct in_ifaddr *ia, int type)
1213 {
1214 	struct carp_softc *vh;
1215 	struct ifaddr *ifa;
1216 	int count = 0;
1217 
1218 	TAILQ_FOREACH(vh, &cif->vhif_vrs, sc_list) {
1219 		if ((type == CARP_COUNT_RUNNING &&
1220 		    (vh->sc_if.if_flags & (IFF_UP|IFF_RUNNING)) ==
1221 		    (IFF_UP|IFF_RUNNING)) ||
1222 		    (type == CARP_COUNT_MASTER && vh->sc_state == MASTER)) {
1223 			IFADDR_FOREACH(ifa, &vh->sc_if) {
1224 				if (ifa->ifa_addr->sa_family == AF_INET &&
1225 				    ia->ia_addr.sin_addr.s_addr ==
1226 				    ifatoia(ifa)->ia_addr.sin_addr.s_addr)
1227 					count++;
1228 			}
1229 		}
1230 	}
1231 	return (count);
1232 }
1233 
1234 int
1235 carp_iamatch(struct in_ifaddr *ia, u_char *src,
1236     u_int32_t *count, u_int32_t index)
1237 {
1238 	struct carp_softc *sc = ia->ia_ifp->if_softc;
1239 
1240 	if (carp_opts[CARPCTL_ARPBALANCE]) {
1241 		/*
1242 		 * We use the source ip to decide which virtual host should
1243 		 * handle the request. If we're master of that virtual host,
1244 		 * then we respond, otherwise, just drop the arp packet on
1245 		 * the floor.
1246 		 */
1247 
1248 		/* Count the elegible carp interfaces with this address */
1249 		if (*count == 0)
1250 			*count = carp_addrcount(
1251 			    (struct carp_if *)ia->ia_ifp->if_carpdev->if_carp,
1252 			    ia, CARP_COUNT_RUNNING);
1253 
1254 		/* This should never happen, but... */
1255 		if (*count == 0)
1256 			return (0);
1257 
1258 		if (carp_hash(sc, src) % *count == index - 1 &&
1259 		    sc->sc_state == MASTER) {
1260 			return (1);
1261 		}
1262 	} else {
1263 		if (sc->sc_state == MASTER)
1264 			return (1);
1265 	}
1266 
1267 	return (0);
1268 }
1269 
1270 #ifdef INET6
1271 struct ifaddr *
1272 carp_iamatch6(void *v, struct in6_addr *taddr)
1273 {
1274 	struct carp_if *cif = v;
1275 	struct carp_softc *vh;
1276 	struct ifaddr *ifa;
1277 
1278 	TAILQ_FOREACH(vh, &cif->vhif_vrs, sc_list) {
1279 		IFADDR_FOREACH(ifa, &vh->sc_if) {
1280 			if (IN6_ARE_ADDR_EQUAL(taddr,
1281 			    &ifatoia6(ifa)->ia_addr.sin6_addr) &&
1282 			    ((vh->sc_if.if_flags & (IFF_UP|IFF_RUNNING)) ==
1283 			    (IFF_UP|IFF_RUNNING)) && vh->sc_state == MASTER)
1284 				return (ifa);
1285 		}
1286 	}
1287 
1288 	return (NULL);
1289 }
1290 #endif /* INET6 */
1291 
1292 struct ifnet *
1293 carp_ourether(void *v, struct ether_header *eh, u_char iftype, int src)
1294 {
1295 	struct carp_if *cif = (struct carp_if *)v;
1296 	struct carp_softc *vh;
1297 	u_int8_t *ena;
1298 
1299 	if (src)
1300 		ena = (u_int8_t *)&eh->ether_shost;
1301 	else
1302 		ena = (u_int8_t *)&eh->ether_dhost;
1303 
1304 	switch (iftype) {
1305 	case IFT_ETHER:
1306 	case IFT_FDDI:
1307 		if (ena[0] || ena[1] || ena[2] != 0x5e || ena[3] || ena[4] != 1)
1308 			return (NULL);
1309 		break;
1310 	case IFT_ISO88025:
1311 		if (ena[0] != 3 || ena[1] || ena[4] || ena[5])
1312 			return (NULL);
1313 		break;
1314 	default:
1315 		return (NULL);
1316 		break;
1317 	}
1318 
1319 	TAILQ_FOREACH(vh, &cif->vhif_vrs, sc_list)
1320 		if ((vh->sc_if.if_flags & (IFF_UP|IFF_RUNNING)) ==
1321 		    (IFF_UP|IFF_RUNNING) && vh->sc_state == MASTER &&
1322 		    !memcmp(ena, CLLADDR(vh->sc_if.if_sadl),
1323 		    ETHER_ADDR_LEN)) {
1324 			return (&vh->sc_if);
1325 		    }
1326 
1327 	return (NULL);
1328 }
1329 
1330 int
1331 carp_input(struct mbuf *m, u_int8_t *shost, u_int8_t *dhost, u_int16_t etype)
1332 {
1333 	struct ether_header eh;
1334 	struct carp_if *cif = (struct carp_if *)m->m_pkthdr.rcvif->if_carp;
1335 	struct ifnet *ifp;
1336 
1337 	memcpy(&eh.ether_shost, shost, sizeof(eh.ether_shost));
1338 	memcpy(&eh.ether_dhost, dhost, sizeof(eh.ether_dhost));
1339 	eh.ether_type = etype;
1340 
1341 	if (m->m_flags & (M_BCAST|M_MCAST)) {
1342 		struct carp_softc *vh;
1343 		struct mbuf *m0;
1344 
1345 		/*
1346 		 * XXX Should really check the list of multicast addresses
1347 		 * for each CARP interface _before_ copying.
1348 		 */
1349 		TAILQ_FOREACH(vh, &cif->vhif_vrs, sc_list) {
1350 			m0 = m_copym(m, 0, M_COPYALL, M_DONTWAIT);
1351 			if (m0 == NULL)
1352 				continue;
1353 			m0->m_pkthdr.rcvif = &vh->sc_if;
1354 			ether_input(&vh->sc_if, m0);
1355 		}
1356 		return (1);
1357 	}
1358 
1359 	ifp = carp_ourether(cif, &eh, m->m_pkthdr.rcvif->if_type, 0);
1360 	if (ifp == NULL) {
1361 		return (1);
1362 	}
1363 
1364 	m->m_pkthdr.rcvif = ifp;
1365 
1366 	bpf_mtap(ifp, m);
1367 	ifp->if_ipackets++;
1368 	ether_input(ifp, m);
1369 	return (0);
1370 }
1371 
1372 void
1373 carp_master_down(void *v)
1374 {
1375 	struct carp_softc *sc = v;
1376 
1377 	switch (sc->sc_state) {
1378 	case INIT:
1379 		printf("%s: master_down event in INIT state\n",
1380 		    sc->sc_if.if_xname);
1381 		break;
1382 	case MASTER:
1383 		break;
1384 	case BACKUP:
1385 		CARP_LOG(sc, ("INIT -> MASTER (preempting)"));
1386 		carp_set_state(sc, MASTER);
1387 		carp_send_ad(sc);
1388 		carp_send_arp(sc);
1389 #ifdef INET6
1390 		carp_send_na(sc);
1391 #endif /* INET6 */
1392 		carp_setrun(sc, 0);
1393 		carp_setroute(sc, RTM_ADD);
1394 		break;
1395 	}
1396 }
1397 
1398 /*
1399  * When in backup state, af indicates whether to reset the master down timer
1400  * for v4 or v6. If it's set to zero, reset the ones which are already pending.
1401  */
1402 void
1403 carp_setrun(struct carp_softc *sc, sa_family_t af)
1404 {
1405 	struct timeval tv;
1406 
1407 	if (sc->sc_carpdev == NULL) {
1408 		sc->sc_if.if_flags &= ~IFF_RUNNING;
1409 		carp_set_state(sc, INIT);
1410 		return;
1411 	}
1412 
1413 	if (sc->sc_if.if_flags & IFF_UP && sc->sc_vhid > 0 &&
1414 	    (sc->sc_naddrs || sc->sc_naddrs6) && !sc->sc_suppress) {
1415 		sc->sc_if.if_flags |= IFF_RUNNING;
1416 	} else {
1417 		sc->sc_if.if_flags &= ~IFF_RUNNING;
1418 		carp_setroute(sc, RTM_DELETE);
1419 		return;
1420 	}
1421 
1422 	switch (sc->sc_state) {
1423 	case INIT:
1424 		carp_set_state(sc, BACKUP);
1425 		carp_setroute(sc, RTM_DELETE);
1426 		carp_setrun(sc, 0);
1427 		break;
1428 	case BACKUP:
1429 		callout_stop(&sc->sc_ad_tmo);
1430 		tv.tv_sec = 3 * sc->sc_advbase;
1431 		tv.tv_usec = sc->sc_advskew * 1000000 / 256;
1432 		switch (af) {
1433 #ifdef INET
1434 		case AF_INET:
1435 			callout_schedule(&sc->sc_md_tmo, tvtohz(&tv));
1436 			break;
1437 #endif /* INET */
1438 #ifdef INET6
1439 		case AF_INET6:
1440 			callout_schedule(&sc->sc_md6_tmo, tvtohz(&tv));
1441 			break;
1442 #endif /* INET6 */
1443 		default:
1444 			if (sc->sc_naddrs)
1445 				callout_schedule(&sc->sc_md_tmo, tvtohz(&tv));
1446 			if (sc->sc_naddrs6)
1447 				callout_schedule(&sc->sc_md6_tmo, tvtohz(&tv));
1448 			break;
1449 		}
1450 		break;
1451 	case MASTER:
1452 		tv.tv_sec = sc->sc_advbase;
1453 		tv.tv_usec = sc->sc_advskew * 1000000 / 256;
1454 		callout_schedule(&sc->sc_ad_tmo, tvtohz(&tv));
1455 		break;
1456 	}
1457 }
1458 
1459 void
1460 carp_multicast_cleanup(struct carp_softc *sc)
1461 {
1462 	struct ip_moptions *imo = &sc->sc_imo;
1463 #ifdef INET6
1464 	struct ip6_moptions *im6o = &sc->sc_im6o;
1465 #endif
1466 	u_int16_t n = imo->imo_num_memberships;
1467 
1468 	/* Clean up our own multicast memberships */
1469 	while (n-- > 0) {
1470 		if (imo->imo_membership[n] != NULL) {
1471 			in_delmulti(imo->imo_membership[n]);
1472 			imo->imo_membership[n] = NULL;
1473 		}
1474 	}
1475 	imo->imo_num_memberships = 0;
1476 	imo->imo_multicast_ifp = NULL;
1477 
1478 #ifdef INET6
1479 	while (!LIST_EMPTY(&im6o->im6o_memberships)) {
1480 		struct in6_multi_mship *imm =
1481 		    LIST_FIRST(&im6o->im6o_memberships);
1482 
1483 		LIST_REMOVE(imm, i6mm_chain);
1484 		in6_leavegroup(imm);
1485 	}
1486 	im6o->im6o_multicast_ifp = NULL;
1487 #endif
1488 
1489 	/* And any other multicast memberships */
1490 	carp_ether_purgemulti(sc);
1491 }
1492 
1493 int
1494 carp_set_ifp(struct carp_softc *sc, struct ifnet *ifp)
1495 {
1496 	struct carp_if *cif, *ncif = NULL;
1497 	struct carp_softc *vr, *after = NULL;
1498 	int myself = 0, error = 0;
1499 	int s;
1500 
1501 	if (ifp == sc->sc_carpdev)
1502 		return (0);
1503 
1504 	if (ifp != NULL) {
1505 		if ((ifp->if_flags & IFF_MULTICAST) == 0)
1506 			return (EADDRNOTAVAIL);
1507 
1508 		if (ifp->if_type == IFT_CARP)
1509 			return (EINVAL);
1510 
1511 		if (ifp->if_carp == NULL) {
1512 			ncif = malloc(sizeof(*cif), M_IFADDR, M_NOWAIT);
1513 			if (ncif == NULL)
1514 				return (ENOBUFS);
1515 			if ((error = ifpromisc(ifp, 1))) {
1516 				free(ncif, M_IFADDR);
1517 				return (error);
1518 			}
1519 
1520 			ncif->vhif_ifp = ifp;
1521 			TAILQ_INIT(&ncif->vhif_vrs);
1522 		} else {
1523 			cif = (struct carp_if *)ifp->if_carp;
1524 			TAILQ_FOREACH(vr, &cif->vhif_vrs, sc_list)
1525 				if (vr != sc && vr->sc_vhid == sc->sc_vhid)
1526 					return (EINVAL);
1527 		}
1528 
1529 		/* detach from old interface */
1530 		if (sc->sc_carpdev != NULL)
1531 			carpdetach(sc);
1532 
1533 		/* join multicast groups */
1534 		if (sc->sc_naddrs < 0 &&
1535 		    (error = carp_join_multicast(sc)) != 0) {
1536 			if (ncif != NULL)
1537 				free(ncif, M_IFADDR);
1538 			return (error);
1539 		}
1540 
1541 #ifdef INET6
1542 		if (sc->sc_naddrs6 < 0 &&
1543 		    (error = carp_join_multicast6(sc)) != 0) {
1544 			if (ncif != NULL)
1545 				free(ncif, M_IFADDR);
1546 			carp_multicast_cleanup(sc);
1547 			return (error);
1548 		}
1549 #endif
1550 
1551 		/* attach carp interface to physical interface */
1552 		if (ncif != NULL)
1553 			ifp->if_carp = (void *)ncif;
1554 		sc->sc_carpdev = ifp;
1555 		cif = (struct carp_if *)ifp->if_carp;
1556 		TAILQ_FOREACH(vr, &cif->vhif_vrs, sc_list) {
1557 			if (vr == sc)
1558 				myself = 1;
1559 			if (vr->sc_vhid < sc->sc_vhid)
1560 				after = vr;
1561 		}
1562 
1563 		if (!myself) {
1564 			/* We're trying to keep things in order */
1565 			if (after == NULL) {
1566 				TAILQ_INSERT_TAIL(&cif->vhif_vrs, sc, sc_list);
1567 			} else {
1568 				TAILQ_INSERT_AFTER(&cif->vhif_vrs, after,
1569 				    sc, sc_list);
1570 			}
1571 			cif->vhif_nvrs++;
1572 		}
1573 		if (sc->sc_naddrs || sc->sc_naddrs6)
1574 			sc->sc_if.if_flags |= IFF_UP;
1575 		carp_set_enaddr(sc);
1576 		s = splnet();
1577 		/* XXX linkstatehooks establish */
1578 		carp_carpdev_state(ifp);
1579 		splx(s);
1580 	} else {
1581 		carpdetach(sc);
1582 		sc->sc_if.if_flags &= ~(IFF_UP|IFF_RUNNING);
1583 	}
1584 	return (0);
1585 }
1586 
1587 void
1588 carp_set_enaddr(struct carp_softc *sc)
1589 {
1590 	uint8_t enaddr[ETHER_ADDR_LEN];
1591 	if (sc->sc_carpdev && sc->sc_carpdev->if_type == IFT_ISO88025) {
1592 		enaddr[0] = 3;
1593 		enaddr[1] = 0;
1594 		enaddr[2] = 0x40 >> (sc->sc_vhid - 1);
1595 		enaddr[3] = 0x40000 >> (sc->sc_vhid - 1);
1596 		enaddr[4] = 0;
1597 		enaddr[5] = 0;
1598 	} else {
1599 		enaddr[0] = 0;
1600 		enaddr[1] = 0;
1601 		enaddr[2] = 0x5e;
1602 		enaddr[3] = 0;
1603 		enaddr[4] = 1;
1604 		enaddr[5] = sc->sc_vhid;
1605 	}
1606 	if_set_sadl(&sc->sc_if, enaddr, sizeof(enaddr), false);
1607 }
1608 
1609 void
1610 carp_addr_updated(void *v)
1611 {
1612 	struct carp_softc *sc = (struct carp_softc *) v;
1613 	struct ifaddr *ifa;
1614 	int new_naddrs = 0, new_naddrs6 = 0;
1615 
1616 	IFADDR_FOREACH(ifa, &sc->sc_if) {
1617 		if (ifa->ifa_addr->sa_family == AF_INET)
1618 			new_naddrs++;
1619 		else if (ifa->ifa_addr->sa_family == AF_INET6)
1620 			new_naddrs6++;
1621 	}
1622 
1623 	/* Handle a callback after SIOCDIFADDR */
1624 	if (new_naddrs < sc->sc_naddrs || new_naddrs6 < sc->sc_naddrs6) {
1625 		struct in_addr mc_addr;
1626 		struct in_multi *inm;
1627 
1628 		sc->sc_naddrs = new_naddrs;
1629 		sc->sc_naddrs6 = new_naddrs6;
1630 
1631 		/* Re-establish multicast membership removed by in_control */
1632 		mc_addr.s_addr = INADDR_CARP_GROUP;
1633 		IN_LOOKUP_MULTI(mc_addr, &sc->sc_if, inm);
1634 		if (inm == NULL) {
1635 			memset(&sc->sc_imo, 0, sizeof(sc->sc_imo));
1636 
1637 			if (sc->sc_carpdev != NULL && sc->sc_naddrs > 0)
1638 				carp_join_multicast(sc);
1639 		}
1640 
1641 		if (sc->sc_naddrs == 0 && sc->sc_naddrs6 == 0) {
1642 			sc->sc_if.if_flags &= ~IFF_UP;
1643 			carp_set_state(sc, INIT);
1644 		} else
1645 			carp_hmac_prepare(sc);
1646 	}
1647 
1648 	carp_setrun(sc, 0);
1649 }
1650 
1651 int
1652 carp_set_addr(struct carp_softc *sc, struct sockaddr_in *sin)
1653 {
1654 	struct ifnet *ifp = sc->sc_carpdev;
1655 	struct in_ifaddr *ia, *ia_if;
1656 	int error = 0;
1657 
1658 	if (sin->sin_addr.s_addr == 0) {
1659 		if (!(sc->sc_if.if_flags & IFF_UP))
1660 			carp_set_state(sc, INIT);
1661 		if (sc->sc_naddrs)
1662 			sc->sc_if.if_flags |= IFF_UP;
1663 		carp_setrun(sc, 0);
1664 		return (0);
1665 	}
1666 
1667 	/* we have to do this by hand to ensure we don't match on ourselves */
1668 	ia_if = NULL;
1669 	for (ia = TAILQ_FIRST(&in_ifaddrhead); ia;
1670 	    ia = TAILQ_NEXT(ia, ia_list)) {
1671 
1672 		/* and, yeah, we need a multicast-capable iface too */
1673 		if (ia->ia_ifp != &sc->sc_if &&
1674 		    ia->ia_ifp->if_type != IFT_CARP &&
1675 		    (ia->ia_ifp->if_flags & IFF_MULTICAST) &&
1676 		    (sin->sin_addr.s_addr & ia->ia_subnetmask) ==
1677 		    ia->ia_subnet) {
1678 			if (!ia_if)
1679 				ia_if = ia;
1680 		}
1681 	}
1682 
1683 	if (ia_if) {
1684 		ia = ia_if;
1685 		if (ifp) {
1686 			if (ifp != ia->ia_ifp)
1687 				return (EADDRNOTAVAIL);
1688 		} else {
1689 			ifp = ia->ia_ifp;
1690 		}
1691 	}
1692 
1693 	if ((error = carp_set_ifp(sc, ifp)))
1694 		return (error);
1695 
1696 	if (sc->sc_carpdev == NULL)
1697 		return (EADDRNOTAVAIL);
1698 
1699 	if (sc->sc_naddrs == 0 && (error = carp_join_multicast(sc)) != 0)
1700 		return (error);
1701 
1702 	sc->sc_naddrs++;
1703 	if (sc->sc_carpdev != NULL)
1704 		sc->sc_if.if_flags |= IFF_UP;
1705 
1706 	carp_set_state(sc, INIT);
1707 	carp_setrun(sc, 0);
1708 
1709 	/*
1710 	 * Hook if_addrhooks so that we get a callback after in_ifinit has run,
1711 	 * to correct any inappropriate routes that it inserted.
1712 	 */
1713 	if (sc->ah_cookie == 0) {
1714 		/* XXX link address hook */
1715 	}
1716 
1717 	return (0);
1718 }
1719 
1720 int
1721 carp_join_multicast(struct carp_softc *sc)
1722 {
1723 	struct ip_moptions *imo = &sc->sc_imo, tmpimo;
1724 	struct in_addr addr;
1725 
1726 	memset(&tmpimo, 0, sizeof(tmpimo));
1727 	addr.s_addr = INADDR_CARP_GROUP;
1728 	if ((tmpimo.imo_membership[0] =
1729 	    in_addmulti(&addr, &sc->sc_if)) == NULL) {
1730 		return (ENOBUFS);
1731 	}
1732 
1733 	imo->imo_membership[0] = tmpimo.imo_membership[0];
1734 	imo->imo_num_memberships = 1;
1735 	imo->imo_multicast_ifp = &sc->sc_if;
1736 	imo->imo_multicast_ttl = CARP_DFLTTL;
1737 	imo->imo_multicast_loop = 0;
1738 	return (0);
1739 }
1740 
1741 
1742 #ifdef INET6
1743 int
1744 carp_set_addr6(struct carp_softc *sc, struct sockaddr_in6 *sin6)
1745 {
1746 	struct ifnet *ifp = sc->sc_carpdev;
1747 	struct in6_ifaddr *ia, *ia_if;
1748 	int error = 0;
1749 
1750 	if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr)) {
1751 		if (!(sc->sc_if.if_flags & IFF_UP))
1752 			carp_set_state(sc, INIT);
1753 		if (sc->sc_naddrs6)
1754 			sc->sc_if.if_flags |= IFF_UP;
1755 		carp_setrun(sc, 0);
1756 		return (0);
1757 	}
1758 
1759 	/* we have to do this by hand to ensure we don't match on ourselves */
1760 	ia_if = NULL;
1761 	for (ia = in6_ifaddr; ia; ia = ia->ia_next) {
1762 		int i;
1763 
1764 		for (i = 0; i < 4; i++) {
1765 			if ((sin6->sin6_addr.s6_addr32[i] &
1766 			    ia->ia_prefixmask.sin6_addr.s6_addr32[i]) !=
1767 			    (ia->ia_addr.sin6_addr.s6_addr32[i] &
1768 			    ia->ia_prefixmask.sin6_addr.s6_addr32[i]))
1769 				break;
1770 		}
1771 		/* and, yeah, we need a multicast-capable iface too */
1772 		if (ia->ia_ifp != &sc->sc_if &&
1773 		    ia->ia_ifp->if_type != IFT_CARP &&
1774 		    (ia->ia_ifp->if_flags & IFF_MULTICAST) &&
1775 		    (i == 4)) {
1776 			if (!ia_if)
1777 				ia_if = ia;
1778 		}
1779 	}
1780 
1781 	if (ia_if) {
1782 		ia = ia_if;
1783 		if (sc->sc_carpdev) {
1784 			if (sc->sc_carpdev != ia->ia_ifp)
1785 				return (EADDRNOTAVAIL);
1786 		} else {
1787 			ifp = ia->ia_ifp;
1788 		}
1789 	}
1790 
1791 	if ((error = carp_set_ifp(sc, ifp)))
1792 		return (error);
1793 
1794 	if (sc->sc_carpdev == NULL)
1795 		return (EADDRNOTAVAIL);
1796 
1797 	if (sc->sc_naddrs6 == 0 && (error = carp_join_multicast6(sc)) != 0)
1798 		return (error);
1799 
1800 	sc->sc_naddrs6++;
1801 	if (sc->sc_carpdev != NULL)
1802 		sc->sc_if.if_flags |= IFF_UP;
1803 	carp_set_state(sc, INIT);
1804 	carp_setrun(sc, 0);
1805 
1806 	return (0);
1807 }
1808 
1809 int
1810 carp_join_multicast6(struct carp_softc *sc)
1811 {
1812 	struct in6_multi_mship *imm, *imm2;
1813 	struct ip6_moptions *im6o = &sc->sc_im6o;
1814 	struct sockaddr_in6 addr6;
1815 	int error;
1816 
1817 	/* Join IPv6 CARP multicast group */
1818 	memset(&addr6, 0, sizeof(addr6));
1819 	addr6.sin6_family = AF_INET6;
1820 	addr6.sin6_len = sizeof(addr6);
1821 	addr6.sin6_addr.s6_addr16[0] = htons(0xff02);
1822 	addr6.sin6_addr.s6_addr16[1] = htons(sc->sc_if.if_index);
1823 	addr6.sin6_addr.s6_addr8[15] = 0x12;
1824 	if ((imm = in6_joingroup(&sc->sc_if,
1825 	    &addr6.sin6_addr, &error, 0)) == NULL) {
1826 		return (error);
1827 	}
1828 	/* join solicited multicast address */
1829 	memset(&addr6.sin6_addr, 0, sizeof(addr6.sin6_addr));
1830 	addr6.sin6_addr.s6_addr16[0] = htons(0xff02);
1831 	addr6.sin6_addr.s6_addr16[1] = htons(sc->sc_if.if_index);
1832 	addr6.sin6_addr.s6_addr32[1] = 0;
1833 	addr6.sin6_addr.s6_addr32[2] = htonl(1);
1834 	addr6.sin6_addr.s6_addr32[3] = 0;
1835 	addr6.sin6_addr.s6_addr8[12] = 0xff;
1836 	if ((imm2 = in6_joingroup(&sc->sc_if,
1837 	    &addr6.sin6_addr, &error, 0)) == NULL) {
1838 		in6_leavegroup(imm);
1839 		return (error);
1840 	}
1841 
1842 	/* apply v6 multicast membership */
1843 	im6o->im6o_multicast_ifp = &sc->sc_if;
1844 	if (imm)
1845 		LIST_INSERT_HEAD(&im6o->im6o_memberships, imm,
1846 		    i6mm_chain);
1847 	if (imm2)
1848 		LIST_INSERT_HEAD(&im6o->im6o_memberships, imm2,
1849 		    i6mm_chain);
1850 
1851 	return (0);
1852 }
1853 
1854 #endif /* INET6 */
1855 
1856 int
1857 carp_ioctl(struct ifnet *ifp, u_long cmd, void *data)
1858 {
1859 	struct lwp *l = curlwp;		/* XXX */
1860 	struct carp_softc *sc = ifp->if_softc, *vr;
1861 	struct carpreq carpr;
1862 	struct ifaddr *ifa;
1863 	struct ifreq *ifr;
1864 	struct ifnet *cdev = NULL;
1865 	int error = 0;
1866 
1867 	ifa = (struct ifaddr *)data;
1868 	ifr = (struct ifreq *)data;
1869 
1870 	switch (cmd) {
1871 	case SIOCINITIFADDR:
1872 		switch (ifa->ifa_addr->sa_family) {
1873 #ifdef INET
1874 		case AF_INET:
1875 			sc->sc_if.if_flags |= IFF_UP;
1876 			memcpy(ifa->ifa_dstaddr, ifa->ifa_addr,
1877 			    sizeof(struct sockaddr));
1878 			error = carp_set_addr(sc, satosin(ifa->ifa_addr));
1879 			break;
1880 #endif /* INET */
1881 #ifdef INET6
1882 		case AF_INET6:
1883 			sc->sc_if.if_flags|= IFF_UP;
1884 			error = carp_set_addr6(sc, satosin6(ifa->ifa_addr));
1885 			break;
1886 #endif /* INET6 */
1887 		default:
1888 			error = EAFNOSUPPORT;
1889 			break;
1890 		}
1891 		break;
1892 
1893 	case SIOCSIFFLAGS:
1894 		if ((error = ifioctl_common(ifp, cmd, data)) != 0)
1895 			break;
1896 		if (sc->sc_state != INIT && !(ifr->ifr_flags & IFF_UP)) {
1897 			callout_stop(&sc->sc_ad_tmo);
1898 			callout_stop(&sc->sc_md_tmo);
1899 			callout_stop(&sc->sc_md6_tmo);
1900 			if (sc->sc_state == MASTER) {
1901 				/* we need the interface up to bow out */
1902 				sc->sc_if.if_flags |= IFF_UP;
1903 				sc->sc_bow_out = 1;
1904 				carp_send_ad(sc);
1905 			}
1906 			sc->sc_if.if_flags &= ~IFF_UP;
1907 			carp_set_state(sc, INIT);
1908 			carp_setrun(sc, 0);
1909 		} else if (sc->sc_state == INIT && (ifr->ifr_flags & IFF_UP)) {
1910 			sc->sc_if.if_flags |= IFF_UP;
1911 			carp_setrun(sc, 0);
1912 		}
1913 		break;
1914 
1915 	case SIOCSVH:
1916 		if (l == NULL)
1917 			break;
1918 		if ((error = kauth_authorize_network(l->l_cred,
1919 		    KAUTH_NETWORK_INTERFACE,
1920 		    KAUTH_REQ_NETWORK_INTERFACE_SETPRIV, ifp, (void *)cmd,
1921 		    NULL)) != 0)
1922 			break;
1923 		if ((error = copyin(ifr->ifr_data, &carpr, sizeof carpr)))
1924 			break;
1925 		error = 1;
1926 		if (carpr.carpr_carpdev[0] != '\0' &&
1927 		    (cdev = ifunit(carpr.carpr_carpdev)) == NULL)
1928 			return (EINVAL);
1929 		if ((error = carp_set_ifp(sc, cdev)))
1930 			return (error);
1931 		if (sc->sc_state != INIT && carpr.carpr_state != sc->sc_state) {
1932 			switch (carpr.carpr_state) {
1933 			case BACKUP:
1934 				callout_stop(&sc->sc_ad_tmo);
1935 				carp_set_state(sc, BACKUP);
1936 				carp_setrun(sc, 0);
1937 				carp_setroute(sc, RTM_DELETE);
1938 				break;
1939 			case MASTER:
1940 				carp_master_down(sc);
1941 				break;
1942 			default:
1943 				break;
1944 			}
1945 		}
1946 		if (carpr.carpr_vhid > 0) {
1947 			if (carpr.carpr_vhid > 255) {
1948 				error = EINVAL;
1949 				break;
1950 			}
1951 			if (sc->sc_carpdev) {
1952 				struct carp_if *cif;
1953 				cif = (struct carp_if *)sc->sc_carpdev->if_carp;
1954 				TAILQ_FOREACH(vr, &cif->vhif_vrs, sc_list)
1955 					if (vr != sc &&
1956 					    vr->sc_vhid == carpr.carpr_vhid)
1957 						return (EINVAL);
1958 			}
1959 			sc->sc_vhid = carpr.carpr_vhid;
1960 			carp_set_enaddr(sc);
1961 			carp_set_state(sc, INIT);
1962 			error--;
1963 		}
1964 		if (carpr.carpr_advbase > 0 || carpr.carpr_advskew > 0) {
1965 			if (carpr.carpr_advskew > 254) {
1966 				error = EINVAL;
1967 				break;
1968 			}
1969 			if (carpr.carpr_advbase > 255) {
1970 				error = EINVAL;
1971 				break;
1972 			}
1973 			sc->sc_advbase = carpr.carpr_advbase;
1974 			sc->sc_advskew = carpr.carpr_advskew;
1975 			error--;
1976 		}
1977 		memcpy(sc->sc_key, carpr.carpr_key, sizeof(sc->sc_key));
1978 		if (error > 0)
1979 			error = EINVAL;
1980 		else {
1981 			error = 0;
1982 			carp_setrun(sc, 0);
1983 		}
1984 		break;
1985 
1986 	case SIOCGVH:
1987 		memset(&carpr, 0, sizeof(carpr));
1988 		if (sc->sc_carpdev != NULL)
1989 			strlcpy(carpr.carpr_carpdev, sc->sc_carpdev->if_xname,
1990 			    IFNAMSIZ);
1991 		carpr.carpr_state = sc->sc_state;
1992 		carpr.carpr_vhid = sc->sc_vhid;
1993 		carpr.carpr_advbase = sc->sc_advbase;
1994 		carpr.carpr_advskew = sc->sc_advskew;
1995 
1996 		if ((l != NULL) && (error = kauth_authorize_network(l->l_cred,
1997 		    KAUTH_NETWORK_INTERFACE,
1998 		    KAUTH_REQ_NETWORK_INTERFACE_SETPRIV, ifp, (void *)cmd,
1999 		    NULL)) == 0)
2000 			memcpy(carpr.carpr_key, sc->sc_key,
2001 			    sizeof(carpr.carpr_key));
2002 		error = copyout(&carpr, ifr->ifr_data, sizeof(carpr));
2003 		break;
2004 
2005 	case SIOCADDMULTI:
2006 		error = carp_ether_addmulti(sc, ifr);
2007 		break;
2008 
2009 	case SIOCDELMULTI:
2010 		error = carp_ether_delmulti(sc, ifr);
2011 		break;
2012 
2013 	default:
2014 		error = ether_ioctl(ifp, cmd, data);
2015 	}
2016 
2017 	carp_hmac_prepare(sc);
2018 	return (error);
2019 }
2020 
2021 
2022 /*
2023  * Start output on carp interface. This function should never be called.
2024  */
2025 void
2026 carp_start(struct ifnet *ifp)
2027 {
2028 #ifdef DEBUG
2029 	printf("%s: start called\n", ifp->if_xname);
2030 #endif
2031 }
2032 
2033 int
2034 carp_output(struct ifnet *ifp, struct mbuf *m, const struct sockaddr *sa,
2035     struct rtentry *rt)
2036 {
2037 	struct carp_softc *sc = ((struct carp_softc *)ifp->if_softc);
2038 
2039 	if (sc->sc_carpdev != NULL && sc->sc_state == MASTER) {
2040 		return (sc->sc_carpdev->if_output(ifp, m, sa, rt));
2041 	} else {
2042 		m_freem(m);
2043 		return (ENETUNREACH);
2044 	}
2045 }
2046 
2047 void
2048 carp_set_state(struct carp_softc *sc, int state)
2049 {
2050 	static const char *carp_states[] = { CARP_STATES };
2051 	if (sc->sc_state == state)
2052 		return;
2053 
2054 	CARP_LOG(sc, ("state transition from: %s -> to: %s", carp_states[sc->sc_state], carp_states[state]));
2055 
2056 	sc->sc_state = state;
2057 	switch (state) {
2058 	case BACKUP:
2059 		sc->sc_if.if_link_state = LINK_STATE_DOWN;
2060 		break;
2061 	case MASTER:
2062 		sc->sc_if.if_link_state = LINK_STATE_UP;
2063 		break;
2064 	default:
2065 		sc->sc_if.if_link_state = LINK_STATE_UNKNOWN;
2066 		break;
2067 	}
2068 	rt_ifmsg(&sc->sc_if);
2069 }
2070 
2071 void
2072 carp_carpdev_state(void *v)
2073 {
2074 	struct carp_if *cif;
2075 	struct carp_softc *sc;
2076 	struct ifnet *ifp = v;
2077 
2078 	if (ifp->if_type == IFT_CARP)
2079 		return;
2080 
2081 	cif = (struct carp_if *)ifp->if_carp;
2082 
2083 	TAILQ_FOREACH(sc, &cif->vhif_vrs, sc_list) {
2084 		int suppressed = sc->sc_suppress;
2085 
2086 		if (sc->sc_carpdev->if_link_state == LINK_STATE_DOWN ||
2087 		    !(sc->sc_carpdev->if_flags & IFF_UP)) {
2088 			sc->sc_if.if_flags &= ~IFF_RUNNING;
2089 			callout_stop(&sc->sc_ad_tmo);
2090 			callout_stop(&sc->sc_md_tmo);
2091 			callout_stop(&sc->sc_md6_tmo);
2092 			carp_set_state(sc, INIT);
2093 			sc->sc_suppress = 1;
2094 			carp_setrun(sc, 0);
2095 			if (!suppressed) {
2096 				carp_suppress_preempt++;
2097 				if (carp_suppress_preempt == 1)
2098 					carp_send_ad_all();
2099 			}
2100 		} else {
2101 			carp_set_state(sc, INIT);
2102 			sc->sc_suppress = 0;
2103 			carp_setrun(sc, 0);
2104 			if (suppressed)
2105 				carp_suppress_preempt--;
2106 		}
2107 	}
2108 }
2109 
2110 int
2111 carp_ether_addmulti(struct carp_softc *sc, struct ifreq *ifr)
2112 {
2113 	const struct sockaddr *sa = ifreq_getaddr(SIOCADDMULTI, ifr);
2114 	struct ifnet *ifp;
2115 	struct carp_mc_entry *mc;
2116 	u_int8_t addrlo[ETHER_ADDR_LEN], addrhi[ETHER_ADDR_LEN];
2117 	int error;
2118 
2119 	ifp = sc->sc_carpdev;
2120 	if (ifp == NULL)
2121 		return (EINVAL);
2122 
2123 	error = ether_addmulti(sa, &sc->sc_ac);
2124 	if (error != ENETRESET)
2125 		return (error);
2126 
2127 	/*
2128 	 * This is new multicast address.  We have to tell parent
2129 	 * about it.  Also, remember this multicast address so that
2130 	 * we can delete them on unconfigure.
2131 	 */
2132 	mc = malloc(sizeof(struct carp_mc_entry), M_DEVBUF, M_NOWAIT);
2133 	if (mc == NULL) {
2134 		error = ENOMEM;
2135 		goto alloc_failed;
2136 	}
2137 
2138 	/*
2139 	 * As ether_addmulti() returns ENETRESET, following two
2140 	 * statement shouldn't fail.
2141 	 */
2142 	(void)ether_multiaddr(sa, addrlo, addrhi);
2143 	ETHER_LOOKUP_MULTI(addrlo, addrhi, &sc->sc_ac, mc->mc_enm);
2144 	memcpy(&mc->mc_addr, sa, sa->sa_len);
2145 	LIST_INSERT_HEAD(&sc->carp_mc_listhead, mc, mc_entries);
2146 
2147 	error = if_mcast_op(ifp, SIOCADDMULTI, sa);
2148 	if (error != 0)
2149 		goto ioctl_failed;
2150 
2151 	return (error);
2152 
2153  ioctl_failed:
2154 	LIST_REMOVE(mc, mc_entries);
2155 	free(mc, M_DEVBUF);
2156  alloc_failed:
2157 	(void)ether_delmulti(sa, &sc->sc_ac);
2158 
2159 	return (error);
2160 }
2161 
2162 int
2163 carp_ether_delmulti(struct carp_softc *sc, struct ifreq *ifr)
2164 {
2165 	const struct sockaddr *sa = ifreq_getaddr(SIOCDELMULTI, ifr);
2166 	struct ifnet *ifp;
2167 	struct ether_multi *enm;
2168 	struct carp_mc_entry *mc;
2169 	u_int8_t addrlo[ETHER_ADDR_LEN], addrhi[ETHER_ADDR_LEN];
2170 	int error;
2171 
2172 	ifp = sc->sc_carpdev;
2173 	if (ifp == NULL)
2174 		return (EINVAL);
2175 
2176 	/*
2177 	 * Find a key to lookup carp_mc_entry.  We have to do this
2178 	 * before calling ether_delmulti for obvious reason.
2179 	 */
2180 	if ((error = ether_multiaddr(sa, addrlo, addrhi)) != 0)
2181 		return (error);
2182 	ETHER_LOOKUP_MULTI(addrlo, addrhi, &sc->sc_ac, enm);
2183 	if (enm == NULL)
2184 		return (EINVAL);
2185 
2186 	LIST_FOREACH(mc, &sc->carp_mc_listhead, mc_entries)
2187 		if (mc->mc_enm == enm)
2188 			break;
2189 
2190 	/* We won't delete entries we didn't add */
2191 	if (mc == NULL)
2192 		return (EINVAL);
2193 
2194 	error = ether_delmulti(sa, &sc->sc_ac);
2195 	if (error != ENETRESET)
2196 		return (error);
2197 
2198 	/* We no longer use this multicast address.  Tell parent so. */
2199 	error = if_mcast_op(ifp, SIOCDELMULTI, sa);
2200 	if (error == 0) {
2201 		/* And forget about this address. */
2202 		LIST_REMOVE(mc, mc_entries);
2203 		free(mc, M_DEVBUF);
2204 	} else
2205 		(void)ether_addmulti(sa, &sc->sc_ac);
2206 	return (error);
2207 }
2208 
2209 /*
2210  * Delete any multicast address we have asked to add from parent
2211  * interface.  Called when the carp is being unconfigured.
2212  */
2213 void
2214 carp_ether_purgemulti(struct carp_softc *sc)
2215 {
2216 	struct ifnet *ifp = sc->sc_carpdev;		/* Parent. */
2217 	struct carp_mc_entry *mc;
2218 
2219 	if (ifp == NULL)
2220 		return;
2221 
2222 	while ((mc = LIST_FIRST(&sc->carp_mc_listhead)) != NULL) {
2223 		(void)if_mcast_op(ifp, SIOCDELMULTI, sstosa(&mc->mc_addr));
2224 		LIST_REMOVE(mc, mc_entries);
2225 		free(mc, M_DEVBUF);
2226 	}
2227 }
2228 
2229 static int
2230 sysctl_net_inet_carp_stats(SYSCTLFN_ARGS)
2231 {
2232 
2233 	return (NETSTAT_SYSCTL(carpstat_percpu, CARP_NSTATS));
2234 }
2235 
2236 void
2237 carp_init(void)
2238 {
2239 
2240 	sysctl_net_inet_carp_setup(NULL);
2241 }
2242 
2243 static void
2244 sysctl_net_inet_carp_setup(struct sysctllog **clog)
2245 {
2246 
2247 	sysctl_createv(clog, 0, NULL, NULL,
2248 		       CTLFLAG_PERMANENT,
2249 		       CTLTYPE_NODE, "net", NULL,
2250 		       NULL, 0, NULL, 0,
2251 		       CTL_NET, CTL_EOL);
2252 	sysctl_createv(clog, 0, NULL, NULL,
2253 		       CTLFLAG_PERMANENT,
2254 		       CTLTYPE_NODE, "inet", NULL,
2255 		       NULL, 0, NULL, 0,
2256 		       CTL_NET, PF_INET, CTL_EOL);
2257 	sysctl_createv(clog, 0, NULL, NULL,
2258 		       CTLFLAG_PERMANENT,
2259 		       CTLTYPE_NODE, "carp",
2260 		       SYSCTL_DESCR("CARP related settings"),
2261 		       NULL, 0, NULL, 0,
2262 		       CTL_NET, PF_INET, IPPROTO_CARP, CTL_EOL);
2263 
2264 	sysctl_createv(clog, 0, NULL, NULL,
2265 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
2266 		       CTLTYPE_INT, "preempt",
2267 		       SYSCTL_DESCR("Enable CARP Preempt"),
2268 		       NULL, 0, &carp_opts[CARPCTL_PREEMPT], 0,
2269 		       CTL_NET, PF_INET, IPPROTO_CARP,
2270 		       CTL_CREATE, CTL_EOL);
2271 	sysctl_createv(clog, 0, NULL, NULL,
2272 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
2273 		       CTLTYPE_INT, "arpbalance",
2274 		       SYSCTL_DESCR("Enable ARP balancing"),
2275 		       NULL, 0, &carp_opts[CARPCTL_ARPBALANCE], 0,
2276 		       CTL_NET, PF_INET, IPPROTO_CARP,
2277 		       CTL_CREATE, CTL_EOL);
2278 	sysctl_createv(clog, 0, NULL, NULL,
2279 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
2280 		       CTLTYPE_INT, "allow",
2281 		       SYSCTL_DESCR("Enable CARP"),
2282 		       NULL, 0, &carp_opts[CARPCTL_ALLOW], 0,
2283 		       CTL_NET, PF_INET, IPPROTO_CARP,
2284 		       CTL_CREATE, CTL_EOL);
2285 	sysctl_createv(clog, 0, NULL, NULL,
2286 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
2287 		       CTLTYPE_INT, "log",
2288 		       SYSCTL_DESCR("CARP logging"),
2289 		       NULL, 0, &carp_opts[CARPCTL_LOG], 0,
2290 		       CTL_NET, PF_INET, IPPROTO_CARP,
2291 		       CTL_CREATE, CTL_EOL);
2292 	sysctl_createv(clog, 0, NULL, NULL,
2293 		       CTLFLAG_PERMANENT,
2294 		       CTLTYPE_STRUCT, "stats",
2295 		       SYSCTL_DESCR("CARP statistics"),
2296 		       sysctl_net_inet_carp_stats, 0, NULL, 0,
2297 		       CTL_NET, PF_INET, IPPROTO_CARP, CARPCTL_STATS,
2298 		       CTL_EOL);
2299 }
2300