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