xref: /netbsd-src/sys/netinet/ip_carp.c (revision 7788a0781fe6ff2cce37368b4578a7ade0850cb1)
1 /*	$NetBSD: ip_carp.c,v 1.50 2012/08/20 16:01:37 christos 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.50 2012/08/20 16:01:37 christos 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 		sc->sc_if.if_capabilities = ifp->if_capabilities &
1556 		             (IFCAP_TSOv4 | IFCAP_TSOv6 |
1557                              IFCAP_CSUM_IPv4_Tx|IFCAP_CSUM_IPv4_Rx|
1558                              IFCAP_CSUM_TCPv4_Tx|IFCAP_CSUM_TCPv4_Rx|
1559                              IFCAP_CSUM_UDPv4_Tx|IFCAP_CSUM_UDPv4_Rx|
1560                              IFCAP_CSUM_TCPv6_Tx|IFCAP_CSUM_TCPv6_Rx|
1561                              IFCAP_CSUM_UDPv6_Tx|IFCAP_CSUM_UDPv6_Rx);
1562 
1563 		cif = (struct carp_if *)ifp->if_carp;
1564 		TAILQ_FOREACH(vr, &cif->vhif_vrs, sc_list) {
1565 			if (vr == sc)
1566 				myself = 1;
1567 			if (vr->sc_vhid < sc->sc_vhid)
1568 				after = vr;
1569 		}
1570 
1571 		if (!myself) {
1572 			/* We're trying to keep things in order */
1573 			if (after == NULL) {
1574 				TAILQ_INSERT_TAIL(&cif->vhif_vrs, sc, sc_list);
1575 			} else {
1576 				TAILQ_INSERT_AFTER(&cif->vhif_vrs, after,
1577 				    sc, sc_list);
1578 			}
1579 			cif->vhif_nvrs++;
1580 		}
1581 		if (sc->sc_naddrs || sc->sc_naddrs6)
1582 			sc->sc_if.if_flags |= IFF_UP;
1583 		carp_set_enaddr(sc);
1584 		s = splnet();
1585 		/* XXX linkstatehooks establish */
1586 		carp_carpdev_state(ifp);
1587 		splx(s);
1588 	} else {
1589 		carpdetach(sc);
1590 		sc->sc_if.if_flags &= ~(IFF_UP|IFF_RUNNING);
1591 	}
1592 	return (0);
1593 }
1594 
1595 void
1596 carp_set_enaddr(struct carp_softc *sc)
1597 {
1598 	uint8_t enaddr[ETHER_ADDR_LEN];
1599 	if (sc->sc_carpdev && sc->sc_carpdev->if_type == IFT_ISO88025) {
1600 		enaddr[0] = 3;
1601 		enaddr[1] = 0;
1602 		enaddr[2] = 0x40 >> (sc->sc_vhid - 1);
1603 		enaddr[3] = 0x40000 >> (sc->sc_vhid - 1);
1604 		enaddr[4] = 0;
1605 		enaddr[5] = 0;
1606 	} else {
1607 		enaddr[0] = 0;
1608 		enaddr[1] = 0;
1609 		enaddr[2] = 0x5e;
1610 		enaddr[3] = 0;
1611 		enaddr[4] = 1;
1612 		enaddr[5] = sc->sc_vhid;
1613 	}
1614 	if_set_sadl(&sc->sc_if, enaddr, sizeof(enaddr), false);
1615 }
1616 
1617 void
1618 carp_addr_updated(void *v)
1619 {
1620 	struct carp_softc *sc = (struct carp_softc *) v;
1621 	struct ifaddr *ifa;
1622 	int new_naddrs = 0, new_naddrs6 = 0;
1623 
1624 	IFADDR_FOREACH(ifa, &sc->sc_if) {
1625 		if (ifa->ifa_addr->sa_family == AF_INET)
1626 			new_naddrs++;
1627 		else if (ifa->ifa_addr->sa_family == AF_INET6)
1628 			new_naddrs6++;
1629 	}
1630 
1631 	/* Handle a callback after SIOCDIFADDR */
1632 	if (new_naddrs < sc->sc_naddrs || new_naddrs6 < sc->sc_naddrs6) {
1633 		struct in_addr mc_addr;
1634 		struct in_multi *inm;
1635 
1636 		sc->sc_naddrs = new_naddrs;
1637 		sc->sc_naddrs6 = new_naddrs6;
1638 
1639 		/* Re-establish multicast membership removed by in_control */
1640 		mc_addr.s_addr = INADDR_CARP_GROUP;
1641 		IN_LOOKUP_MULTI(mc_addr, &sc->sc_if, inm);
1642 		if (inm == NULL) {
1643 			memset(&sc->sc_imo, 0, sizeof(sc->sc_imo));
1644 
1645 			if (sc->sc_carpdev != NULL && sc->sc_naddrs > 0)
1646 				carp_join_multicast(sc);
1647 		}
1648 
1649 		if (sc->sc_naddrs == 0 && sc->sc_naddrs6 == 0) {
1650 			sc->sc_if.if_flags &= ~IFF_UP;
1651 			carp_set_state(sc, INIT);
1652 		} else
1653 			carp_hmac_prepare(sc);
1654 	}
1655 
1656 	carp_setrun(sc, 0);
1657 }
1658 
1659 int
1660 carp_set_addr(struct carp_softc *sc, struct sockaddr_in *sin)
1661 {
1662 	struct ifnet *ifp = sc->sc_carpdev;
1663 	struct in_ifaddr *ia, *ia_if;
1664 	int error = 0;
1665 
1666 	if (sin->sin_addr.s_addr == 0) {
1667 		if (!(sc->sc_if.if_flags & IFF_UP))
1668 			carp_set_state(sc, INIT);
1669 		if (sc->sc_naddrs)
1670 			sc->sc_if.if_flags |= IFF_UP;
1671 		carp_setrun(sc, 0);
1672 		return (0);
1673 	}
1674 
1675 	/* we have to do this by hand to ensure we don't match on ourselves */
1676 	ia_if = NULL;
1677 	for (ia = TAILQ_FIRST(&in_ifaddrhead); ia;
1678 	    ia = TAILQ_NEXT(ia, ia_list)) {
1679 
1680 		/* and, yeah, we need a multicast-capable iface too */
1681 		if (ia->ia_ifp != &sc->sc_if &&
1682 		    ia->ia_ifp->if_type != IFT_CARP &&
1683 		    (ia->ia_ifp->if_flags & IFF_MULTICAST) &&
1684 		    (sin->sin_addr.s_addr & ia->ia_subnetmask) ==
1685 		    ia->ia_subnet) {
1686 			if (!ia_if)
1687 				ia_if = ia;
1688 		}
1689 	}
1690 
1691 	if (ia_if) {
1692 		ia = ia_if;
1693 		if (ifp) {
1694 			if (ifp != ia->ia_ifp)
1695 				return (EADDRNOTAVAIL);
1696 		} else {
1697 			ifp = ia->ia_ifp;
1698 		}
1699 	}
1700 
1701 	if ((error = carp_set_ifp(sc, ifp)))
1702 		return (error);
1703 
1704 	if (sc->sc_carpdev == NULL)
1705 		return (EADDRNOTAVAIL);
1706 
1707 	if (sc->sc_naddrs == 0 && (error = carp_join_multicast(sc)) != 0)
1708 		return (error);
1709 
1710 	sc->sc_naddrs++;
1711 	if (sc->sc_carpdev != NULL)
1712 		sc->sc_if.if_flags |= IFF_UP;
1713 
1714 	carp_set_state(sc, INIT);
1715 	carp_setrun(sc, 0);
1716 
1717 	/*
1718 	 * Hook if_addrhooks so that we get a callback after in_ifinit has run,
1719 	 * to correct any inappropriate routes that it inserted.
1720 	 */
1721 	if (sc->ah_cookie == 0) {
1722 		/* XXX link address hook */
1723 	}
1724 
1725 	return (0);
1726 }
1727 
1728 int
1729 carp_join_multicast(struct carp_softc *sc)
1730 {
1731 	struct ip_moptions *imo = &sc->sc_imo, tmpimo;
1732 	struct in_addr addr;
1733 
1734 	memset(&tmpimo, 0, sizeof(tmpimo));
1735 	addr.s_addr = INADDR_CARP_GROUP;
1736 	if ((tmpimo.imo_membership[0] =
1737 	    in_addmulti(&addr, &sc->sc_if)) == NULL) {
1738 		return (ENOBUFS);
1739 	}
1740 
1741 	imo->imo_membership[0] = tmpimo.imo_membership[0];
1742 	imo->imo_num_memberships = 1;
1743 	imo->imo_multicast_ifp = &sc->sc_if;
1744 	imo->imo_multicast_ttl = CARP_DFLTTL;
1745 	imo->imo_multicast_loop = 0;
1746 	return (0);
1747 }
1748 
1749 
1750 #ifdef INET6
1751 int
1752 carp_set_addr6(struct carp_softc *sc, struct sockaddr_in6 *sin6)
1753 {
1754 	struct ifnet *ifp = sc->sc_carpdev;
1755 	struct in6_ifaddr *ia, *ia_if;
1756 	int error = 0;
1757 
1758 	if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr)) {
1759 		if (!(sc->sc_if.if_flags & IFF_UP))
1760 			carp_set_state(sc, INIT);
1761 		if (sc->sc_naddrs6)
1762 			sc->sc_if.if_flags |= IFF_UP;
1763 		carp_setrun(sc, 0);
1764 		return (0);
1765 	}
1766 
1767 	/* we have to do this by hand to ensure we don't match on ourselves */
1768 	ia_if = NULL;
1769 	for (ia = in6_ifaddr; ia; ia = ia->ia_next) {
1770 		int i;
1771 
1772 		for (i = 0; i < 4; i++) {
1773 			if ((sin6->sin6_addr.s6_addr32[i] &
1774 			    ia->ia_prefixmask.sin6_addr.s6_addr32[i]) !=
1775 			    (ia->ia_addr.sin6_addr.s6_addr32[i] &
1776 			    ia->ia_prefixmask.sin6_addr.s6_addr32[i]))
1777 				break;
1778 		}
1779 		/* and, yeah, we need a multicast-capable iface too */
1780 		if (ia->ia_ifp != &sc->sc_if &&
1781 		    ia->ia_ifp->if_type != IFT_CARP &&
1782 		    (ia->ia_ifp->if_flags & IFF_MULTICAST) &&
1783 		    (i == 4)) {
1784 			if (!ia_if)
1785 				ia_if = ia;
1786 		}
1787 	}
1788 
1789 	if (ia_if) {
1790 		ia = ia_if;
1791 		if (sc->sc_carpdev) {
1792 			if (sc->sc_carpdev != ia->ia_ifp)
1793 				return (EADDRNOTAVAIL);
1794 		} else {
1795 			ifp = ia->ia_ifp;
1796 		}
1797 	}
1798 
1799 	if ((error = carp_set_ifp(sc, ifp)))
1800 		return (error);
1801 
1802 	if (sc->sc_carpdev == NULL)
1803 		return (EADDRNOTAVAIL);
1804 
1805 	if (sc->sc_naddrs6 == 0 && (error = carp_join_multicast6(sc)) != 0)
1806 		return (error);
1807 
1808 	sc->sc_naddrs6++;
1809 	if (sc->sc_carpdev != NULL)
1810 		sc->sc_if.if_flags |= IFF_UP;
1811 	carp_set_state(sc, INIT);
1812 	carp_setrun(sc, 0);
1813 
1814 	return (0);
1815 }
1816 
1817 int
1818 carp_join_multicast6(struct carp_softc *sc)
1819 {
1820 	struct in6_multi_mship *imm, *imm2;
1821 	struct ip6_moptions *im6o = &sc->sc_im6o;
1822 	struct sockaddr_in6 addr6;
1823 	int error;
1824 
1825 	/* Join IPv6 CARP multicast group */
1826 	memset(&addr6, 0, sizeof(addr6));
1827 	addr6.sin6_family = AF_INET6;
1828 	addr6.sin6_len = sizeof(addr6);
1829 	addr6.sin6_addr.s6_addr16[0] = htons(0xff02);
1830 	addr6.sin6_addr.s6_addr16[1] = htons(sc->sc_if.if_index);
1831 	addr6.sin6_addr.s6_addr8[15] = 0x12;
1832 	if ((imm = in6_joingroup(&sc->sc_if,
1833 	    &addr6.sin6_addr, &error, 0)) == NULL) {
1834 		return (error);
1835 	}
1836 	/* join solicited multicast address */
1837 	memset(&addr6.sin6_addr, 0, sizeof(addr6.sin6_addr));
1838 	addr6.sin6_addr.s6_addr16[0] = htons(0xff02);
1839 	addr6.sin6_addr.s6_addr16[1] = htons(sc->sc_if.if_index);
1840 	addr6.sin6_addr.s6_addr32[1] = 0;
1841 	addr6.sin6_addr.s6_addr32[2] = htonl(1);
1842 	addr6.sin6_addr.s6_addr32[3] = 0;
1843 	addr6.sin6_addr.s6_addr8[12] = 0xff;
1844 	if ((imm2 = in6_joingroup(&sc->sc_if,
1845 	    &addr6.sin6_addr, &error, 0)) == NULL) {
1846 		in6_leavegroup(imm);
1847 		return (error);
1848 	}
1849 
1850 	/* apply v6 multicast membership */
1851 	im6o->im6o_multicast_ifp = &sc->sc_if;
1852 	if (imm)
1853 		LIST_INSERT_HEAD(&im6o->im6o_memberships, imm,
1854 		    i6mm_chain);
1855 	if (imm2)
1856 		LIST_INSERT_HEAD(&im6o->im6o_memberships, imm2,
1857 		    i6mm_chain);
1858 
1859 	return (0);
1860 }
1861 
1862 #endif /* INET6 */
1863 
1864 int
1865 carp_ioctl(struct ifnet *ifp, u_long cmd, void *data)
1866 {
1867 	struct lwp *l = curlwp;		/* XXX */
1868 	struct carp_softc *sc = ifp->if_softc, *vr;
1869 	struct carpreq carpr;
1870 	struct ifaddr *ifa;
1871 	struct ifreq *ifr;
1872 	struct ifnet *cdev = NULL;
1873 	int error = 0;
1874 
1875 	ifa = (struct ifaddr *)data;
1876 	ifr = (struct ifreq *)data;
1877 
1878 	switch (cmd) {
1879 	case SIOCINITIFADDR:
1880 		switch (ifa->ifa_addr->sa_family) {
1881 #ifdef INET
1882 		case AF_INET:
1883 			sc->sc_if.if_flags |= IFF_UP;
1884 			memcpy(ifa->ifa_dstaddr, ifa->ifa_addr,
1885 			    sizeof(struct sockaddr));
1886 			error = carp_set_addr(sc, satosin(ifa->ifa_addr));
1887 			break;
1888 #endif /* INET */
1889 #ifdef INET6
1890 		case AF_INET6:
1891 			sc->sc_if.if_flags|= IFF_UP;
1892 			error = carp_set_addr6(sc, satosin6(ifa->ifa_addr));
1893 			break;
1894 #endif /* INET6 */
1895 		default:
1896 			error = EAFNOSUPPORT;
1897 			break;
1898 		}
1899 		break;
1900 
1901 	case SIOCSIFFLAGS:
1902 		if ((error = ifioctl_common(ifp, cmd, data)) != 0)
1903 			break;
1904 		if (sc->sc_state != INIT && !(ifr->ifr_flags & IFF_UP)) {
1905 			callout_stop(&sc->sc_ad_tmo);
1906 			callout_stop(&sc->sc_md_tmo);
1907 			callout_stop(&sc->sc_md6_tmo);
1908 			if (sc->sc_state == MASTER) {
1909 				/* we need the interface up to bow out */
1910 				sc->sc_if.if_flags |= IFF_UP;
1911 				sc->sc_bow_out = 1;
1912 				carp_send_ad(sc);
1913 			}
1914 			sc->sc_if.if_flags &= ~IFF_UP;
1915 			carp_set_state(sc, INIT);
1916 			carp_setrun(sc, 0);
1917 		} else if (sc->sc_state == INIT && (ifr->ifr_flags & IFF_UP)) {
1918 			sc->sc_if.if_flags |= IFF_UP;
1919 			carp_setrun(sc, 0);
1920 		}
1921 		break;
1922 
1923 	case SIOCSVH:
1924 		if (l == NULL)
1925 			break;
1926 		if ((error = kauth_authorize_network(l->l_cred,
1927 		    KAUTH_NETWORK_INTERFACE,
1928 		    KAUTH_REQ_NETWORK_INTERFACE_SETPRIV, ifp, (void *)cmd,
1929 		    NULL)) != 0)
1930 			break;
1931 		if ((error = copyin(ifr->ifr_data, &carpr, sizeof carpr)))
1932 			break;
1933 		error = 1;
1934 		if (carpr.carpr_carpdev[0] != '\0' &&
1935 		    (cdev = ifunit(carpr.carpr_carpdev)) == NULL)
1936 			return (EINVAL);
1937 		if ((error = carp_set_ifp(sc, cdev)))
1938 			return (error);
1939 		if (sc->sc_state != INIT && carpr.carpr_state != sc->sc_state) {
1940 			switch (carpr.carpr_state) {
1941 			case BACKUP:
1942 				callout_stop(&sc->sc_ad_tmo);
1943 				carp_set_state(sc, BACKUP);
1944 				carp_setrun(sc, 0);
1945 				carp_setroute(sc, RTM_DELETE);
1946 				break;
1947 			case MASTER:
1948 				carp_master_down(sc);
1949 				break;
1950 			default:
1951 				break;
1952 			}
1953 		}
1954 		if (carpr.carpr_vhid > 0) {
1955 			if (carpr.carpr_vhid > 255) {
1956 				error = EINVAL;
1957 				break;
1958 			}
1959 			if (sc->sc_carpdev) {
1960 				struct carp_if *cif;
1961 				cif = (struct carp_if *)sc->sc_carpdev->if_carp;
1962 				TAILQ_FOREACH(vr, &cif->vhif_vrs, sc_list)
1963 					if (vr != sc &&
1964 					    vr->sc_vhid == carpr.carpr_vhid)
1965 						return (EINVAL);
1966 			}
1967 			sc->sc_vhid = carpr.carpr_vhid;
1968 			carp_set_enaddr(sc);
1969 			carp_set_state(sc, INIT);
1970 			error--;
1971 		}
1972 		if (carpr.carpr_advbase > 0 || carpr.carpr_advskew > 0) {
1973 			if (carpr.carpr_advskew > 254) {
1974 				error = EINVAL;
1975 				break;
1976 			}
1977 			if (carpr.carpr_advbase > 255) {
1978 				error = EINVAL;
1979 				break;
1980 			}
1981 			sc->sc_advbase = carpr.carpr_advbase;
1982 			sc->sc_advskew = carpr.carpr_advskew;
1983 			error--;
1984 		}
1985 		memcpy(sc->sc_key, carpr.carpr_key, sizeof(sc->sc_key));
1986 		if (error > 0)
1987 			error = EINVAL;
1988 		else {
1989 			error = 0;
1990 			carp_setrun(sc, 0);
1991 		}
1992 		break;
1993 
1994 	case SIOCGVH:
1995 		memset(&carpr, 0, sizeof(carpr));
1996 		if (sc->sc_carpdev != NULL)
1997 			strlcpy(carpr.carpr_carpdev, sc->sc_carpdev->if_xname,
1998 			    IFNAMSIZ);
1999 		carpr.carpr_state = sc->sc_state;
2000 		carpr.carpr_vhid = sc->sc_vhid;
2001 		carpr.carpr_advbase = sc->sc_advbase;
2002 		carpr.carpr_advskew = sc->sc_advskew;
2003 
2004 		if ((l != NULL) && (error = kauth_authorize_network(l->l_cred,
2005 		    KAUTH_NETWORK_INTERFACE,
2006 		    KAUTH_REQ_NETWORK_INTERFACE_SETPRIV, ifp, (void *)cmd,
2007 		    NULL)) == 0)
2008 			memcpy(carpr.carpr_key, sc->sc_key,
2009 			    sizeof(carpr.carpr_key));
2010 		error = copyout(&carpr, ifr->ifr_data, sizeof(carpr));
2011 		break;
2012 
2013 	case SIOCADDMULTI:
2014 		error = carp_ether_addmulti(sc, ifr);
2015 		break;
2016 
2017 	case SIOCDELMULTI:
2018 		error = carp_ether_delmulti(sc, ifr);
2019 		break;
2020 
2021 	case SIOCSIFCAP:
2022 		if ((error = ifioctl_common(ifp, cmd, data)) == ENETRESET)
2023 			error = 0;
2024 		break;
2025 
2026 	default:
2027 		error = ether_ioctl(ifp, cmd, data);
2028 	}
2029 
2030 	carp_hmac_prepare(sc);
2031 	return (error);
2032 }
2033 
2034 
2035 /*
2036  * Start output on carp interface. This function should never be called.
2037  */
2038 void
2039 carp_start(struct ifnet *ifp)
2040 {
2041 #ifdef DEBUG
2042 	printf("%s: start called\n", ifp->if_xname);
2043 #endif
2044 }
2045 
2046 int
2047 carp_output(struct ifnet *ifp, struct mbuf *m, const struct sockaddr *sa,
2048     struct rtentry *rt)
2049 {
2050 	struct carp_softc *sc = ((struct carp_softc *)ifp->if_softc);
2051 
2052 	if (sc->sc_carpdev != NULL && sc->sc_state == MASTER) {
2053 		return (sc->sc_carpdev->if_output(ifp, m, sa, rt));
2054 	} else {
2055 		m_freem(m);
2056 		return (ENETUNREACH);
2057 	}
2058 }
2059 
2060 void
2061 carp_set_state(struct carp_softc *sc, int state)
2062 {
2063 	static const char *carp_states[] = { CARP_STATES };
2064 	if (sc->sc_state == state)
2065 		return;
2066 
2067 	CARP_LOG(sc, ("state transition from: %s -> to: %s", carp_states[sc->sc_state], carp_states[state]));
2068 
2069 	sc->sc_state = state;
2070 	switch (state) {
2071 	case BACKUP:
2072 		sc->sc_if.if_link_state = LINK_STATE_DOWN;
2073 		break;
2074 	case MASTER:
2075 		sc->sc_if.if_link_state = LINK_STATE_UP;
2076 		break;
2077 	default:
2078 		sc->sc_if.if_link_state = LINK_STATE_UNKNOWN;
2079 		break;
2080 	}
2081 	rt_ifmsg(&sc->sc_if);
2082 }
2083 
2084 void
2085 carp_carpdev_state(void *v)
2086 {
2087 	struct carp_if *cif;
2088 	struct carp_softc *sc;
2089 	struct ifnet *ifp = v;
2090 
2091 	if (ifp->if_type == IFT_CARP)
2092 		return;
2093 
2094 	cif = (struct carp_if *)ifp->if_carp;
2095 
2096 	TAILQ_FOREACH(sc, &cif->vhif_vrs, sc_list) {
2097 		int suppressed = sc->sc_suppress;
2098 
2099 		if (sc->sc_carpdev->if_link_state == LINK_STATE_DOWN ||
2100 		    !(sc->sc_carpdev->if_flags & IFF_UP)) {
2101 			sc->sc_if.if_flags &= ~IFF_RUNNING;
2102 			callout_stop(&sc->sc_ad_tmo);
2103 			callout_stop(&sc->sc_md_tmo);
2104 			callout_stop(&sc->sc_md6_tmo);
2105 			carp_set_state(sc, INIT);
2106 			sc->sc_suppress = 1;
2107 			carp_setrun(sc, 0);
2108 			if (!suppressed) {
2109 				carp_suppress_preempt++;
2110 				if (carp_suppress_preempt == 1)
2111 					carp_send_ad_all();
2112 			}
2113 		} else {
2114 			carp_set_state(sc, INIT);
2115 			sc->sc_suppress = 0;
2116 			carp_setrun(sc, 0);
2117 			if (suppressed)
2118 				carp_suppress_preempt--;
2119 		}
2120 	}
2121 }
2122 
2123 int
2124 carp_ether_addmulti(struct carp_softc *sc, struct ifreq *ifr)
2125 {
2126 	const struct sockaddr *sa = ifreq_getaddr(SIOCADDMULTI, ifr);
2127 	struct ifnet *ifp;
2128 	struct carp_mc_entry *mc;
2129 	u_int8_t addrlo[ETHER_ADDR_LEN], addrhi[ETHER_ADDR_LEN];
2130 	int error;
2131 
2132 	ifp = sc->sc_carpdev;
2133 	if (ifp == NULL)
2134 		return (EINVAL);
2135 
2136 	error = ether_addmulti(sa, &sc->sc_ac);
2137 	if (error != ENETRESET)
2138 		return (error);
2139 
2140 	/*
2141 	 * This is new multicast address.  We have to tell parent
2142 	 * about it.  Also, remember this multicast address so that
2143 	 * we can delete them on unconfigure.
2144 	 */
2145 	mc = malloc(sizeof(struct carp_mc_entry), M_DEVBUF, M_NOWAIT);
2146 	if (mc == NULL) {
2147 		error = ENOMEM;
2148 		goto alloc_failed;
2149 	}
2150 
2151 	/*
2152 	 * As ether_addmulti() returns ENETRESET, following two
2153 	 * statement shouldn't fail.
2154 	 */
2155 	(void)ether_multiaddr(sa, addrlo, addrhi);
2156 	ETHER_LOOKUP_MULTI(addrlo, addrhi, &sc->sc_ac, mc->mc_enm);
2157 	memcpy(&mc->mc_addr, sa, sa->sa_len);
2158 	LIST_INSERT_HEAD(&sc->carp_mc_listhead, mc, mc_entries);
2159 
2160 	error = if_mcast_op(ifp, SIOCADDMULTI, sa);
2161 	if (error != 0)
2162 		goto ioctl_failed;
2163 
2164 	return (error);
2165 
2166  ioctl_failed:
2167 	LIST_REMOVE(mc, mc_entries);
2168 	free(mc, M_DEVBUF);
2169  alloc_failed:
2170 	(void)ether_delmulti(sa, &sc->sc_ac);
2171 
2172 	return (error);
2173 }
2174 
2175 int
2176 carp_ether_delmulti(struct carp_softc *sc, struct ifreq *ifr)
2177 {
2178 	const struct sockaddr *sa = ifreq_getaddr(SIOCDELMULTI, ifr);
2179 	struct ifnet *ifp;
2180 	struct ether_multi *enm;
2181 	struct carp_mc_entry *mc;
2182 	u_int8_t addrlo[ETHER_ADDR_LEN], addrhi[ETHER_ADDR_LEN];
2183 	int error;
2184 
2185 	ifp = sc->sc_carpdev;
2186 	if (ifp == NULL)
2187 		return (EINVAL);
2188 
2189 	/*
2190 	 * Find a key to lookup carp_mc_entry.  We have to do this
2191 	 * before calling ether_delmulti for obvious reason.
2192 	 */
2193 	if ((error = ether_multiaddr(sa, addrlo, addrhi)) != 0)
2194 		return (error);
2195 	ETHER_LOOKUP_MULTI(addrlo, addrhi, &sc->sc_ac, enm);
2196 	if (enm == NULL)
2197 		return (EINVAL);
2198 
2199 	LIST_FOREACH(mc, &sc->carp_mc_listhead, mc_entries)
2200 		if (mc->mc_enm == enm)
2201 			break;
2202 
2203 	/* We won't delete entries we didn't add */
2204 	if (mc == NULL)
2205 		return (EINVAL);
2206 
2207 	error = ether_delmulti(sa, &sc->sc_ac);
2208 	if (error != ENETRESET)
2209 		return (error);
2210 
2211 	/* We no longer use this multicast address.  Tell parent so. */
2212 	error = if_mcast_op(ifp, SIOCDELMULTI, sa);
2213 	if (error == 0) {
2214 		/* And forget about this address. */
2215 		LIST_REMOVE(mc, mc_entries);
2216 		free(mc, M_DEVBUF);
2217 	} else
2218 		(void)ether_addmulti(sa, &sc->sc_ac);
2219 	return (error);
2220 }
2221 
2222 /*
2223  * Delete any multicast address we have asked to add from parent
2224  * interface.  Called when the carp is being unconfigured.
2225  */
2226 void
2227 carp_ether_purgemulti(struct carp_softc *sc)
2228 {
2229 	struct ifnet *ifp = sc->sc_carpdev;		/* Parent. */
2230 	struct carp_mc_entry *mc;
2231 
2232 	if (ifp == NULL)
2233 		return;
2234 
2235 	while ((mc = LIST_FIRST(&sc->carp_mc_listhead)) != NULL) {
2236 		(void)if_mcast_op(ifp, SIOCDELMULTI, sstosa(&mc->mc_addr));
2237 		LIST_REMOVE(mc, mc_entries);
2238 		free(mc, M_DEVBUF);
2239 	}
2240 }
2241 
2242 static int
2243 sysctl_net_inet_carp_stats(SYSCTLFN_ARGS)
2244 {
2245 
2246 	return (NETSTAT_SYSCTL(carpstat_percpu, CARP_NSTATS));
2247 }
2248 
2249 void
2250 carp_init(void)
2251 {
2252 
2253 	sysctl_net_inet_carp_setup(NULL);
2254 }
2255 
2256 static void
2257 sysctl_net_inet_carp_setup(struct sysctllog **clog)
2258 {
2259 
2260 	sysctl_createv(clog, 0, NULL, NULL,
2261 		       CTLFLAG_PERMANENT,
2262 		       CTLTYPE_NODE, "net", NULL,
2263 		       NULL, 0, NULL, 0,
2264 		       CTL_NET, CTL_EOL);
2265 	sysctl_createv(clog, 0, NULL, NULL,
2266 		       CTLFLAG_PERMANENT,
2267 		       CTLTYPE_NODE, "inet", NULL,
2268 		       NULL, 0, NULL, 0,
2269 		       CTL_NET, PF_INET, CTL_EOL);
2270 	sysctl_createv(clog, 0, NULL, NULL,
2271 		       CTLFLAG_PERMANENT,
2272 		       CTLTYPE_NODE, "carp",
2273 		       SYSCTL_DESCR("CARP related settings"),
2274 		       NULL, 0, NULL, 0,
2275 		       CTL_NET, PF_INET, IPPROTO_CARP, CTL_EOL);
2276 
2277 	sysctl_createv(clog, 0, NULL, NULL,
2278 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
2279 		       CTLTYPE_INT, "preempt",
2280 		       SYSCTL_DESCR("Enable CARP Preempt"),
2281 		       NULL, 0, &carp_opts[CARPCTL_PREEMPT], 0,
2282 		       CTL_NET, PF_INET, IPPROTO_CARP,
2283 		       CTL_CREATE, CTL_EOL);
2284 	sysctl_createv(clog, 0, NULL, NULL,
2285 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
2286 		       CTLTYPE_INT, "arpbalance",
2287 		       SYSCTL_DESCR("Enable ARP balancing"),
2288 		       NULL, 0, &carp_opts[CARPCTL_ARPBALANCE], 0,
2289 		       CTL_NET, PF_INET, IPPROTO_CARP,
2290 		       CTL_CREATE, CTL_EOL);
2291 	sysctl_createv(clog, 0, NULL, NULL,
2292 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
2293 		       CTLTYPE_INT, "allow",
2294 		       SYSCTL_DESCR("Enable CARP"),
2295 		       NULL, 0, &carp_opts[CARPCTL_ALLOW], 0,
2296 		       CTL_NET, PF_INET, IPPROTO_CARP,
2297 		       CTL_CREATE, CTL_EOL);
2298 	sysctl_createv(clog, 0, NULL, NULL,
2299 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
2300 		       CTLTYPE_INT, "log",
2301 		       SYSCTL_DESCR("CARP logging"),
2302 		       NULL, 0, &carp_opts[CARPCTL_LOG], 0,
2303 		       CTL_NET, PF_INET, IPPROTO_CARP,
2304 		       CTL_CREATE, CTL_EOL);
2305 	sysctl_createv(clog, 0, NULL, NULL,
2306 		       CTLFLAG_PERMANENT,
2307 		       CTLTYPE_STRUCT, "stats",
2308 		       SYSCTL_DESCR("CARP statistics"),
2309 		       sysctl_net_inet_carp_stats, 0, NULL, 0,
2310 		       CTL_NET, PF_INET, IPPROTO_CARP, CARPCTL_STATS,
2311 		       CTL_EOL);
2312 }
2313