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