IA_PRF_RTEXISTOK is no longer needed, in_{add,scrub}prefix() does more
[dragonfly.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  * $FreeBSD: src/sys/netinet/ip_carp.c,v 1.48 2007/02/02 09:39:09 glebius Exp $
28  * $DragonFly: src/sys/netinet/ip_carp.c,v 1.10 2008/07/27 10:06:57 sephe Exp $
29  */
30
31 #include "opt_carp.h"
32 #include "opt_inet.h"
33 #include "opt_inet6.h"
34
35 #include <sys/param.h>
36 #include <sys/systm.h>
37 #include <sys/kernel.h>
38 #include <sys/in_cksum.h>
39 #include <sys/limits.h>
40 #include <sys/malloc.h>
41 #include <sys/mbuf.h>
42 #include <sys/time.h>
43 #include <sys/proc.h>
44 #include <sys/sockio.h>
45 #include <sys/socket.h>
46 #include <sys/sysctl.h>
47 #include <sys/syslog.h>
48
49 #include <machine/stdarg.h>
50 #include <crypto/sha1.h>
51
52 #include <net/bpf.h>
53 #include <net/ethernet.h>
54 #include <net/if.h>
55 #include <net/if_dl.h>
56 #include <net/if_types.h>
57 #include <net/route.h>
58 #include <net/if_clone.h>
59
60 #ifdef INET
61 #include <netinet/in.h>
62 #include <netinet/in_var.h>
63 #include <netinet/in_systm.h>
64 #include <netinet/ip.h>
65 #include <netinet/ip_var.h>
66 #include <netinet/if_ether.h>
67 #endif
68
69 #ifdef INET6
70 #include <netinet/icmp6.h>
71 #include <netinet/ip6.h>
72 #include <netinet6/ip6_var.h>
73 #include <netinet6/scope6_var.h>
74 #include <netinet6/nd6.h>
75 #endif
76
77 #include <netinet/ip_carp.h>
78
79 #define CARP_IFNAME             "carp"
80 #define CARP_IS_RUNNING(ifp)    \
81         (((ifp)->if_flags & (IFF_UP | IFF_RUNNING)) == (IFF_UP | IFF_RUNNING))
82
83 struct carp_vhaddr {
84         uint32_t                vha_flags;      /* CARP_VHAF_ */
85         const struct in_ifaddr  *vha_ia;        /* carp address */
86         const struct in_ifaddr  *vha_iaback;    /* backing address */
87         TAILQ_ENTRY(carp_vhaddr) vha_link;
88 };
89 TAILQ_HEAD(carp_vhaddr_list, carp_vhaddr);
90
91 struct carp_softc {
92         struct ifnet             sc_if;
93         struct ifnet            *sc_carpdev;    /* parent interface */
94         struct carp_vhaddr_list  sc_vha_list;   /* virtual addr list */
95
96         const struct in_ifaddr  *sc_ia;         /* primary iface address v4 */
97         struct ip_moptions       sc_imo;
98
99 #ifdef INET6
100         struct in6_ifaddr       *sc_ia6;        /* primary iface address v6 */
101         struct ip6_moptions      sc_im6o;
102 #endif /* INET6 */
103         TAILQ_ENTRY(carp_softc)  sc_list;
104
105         enum { INIT = 0, BACKUP, MASTER }
106                                  sc_state;
107         int                      sc_dead;
108
109         int                      sc_suppress;
110
111         int                      sc_sendad_errors;
112 #define CARP_SENDAD_MAX_ERRORS  3
113         int                      sc_sendad_success;
114 #define CARP_SENDAD_MIN_SUCCESS 3
115
116         int                      sc_vhid;
117         int                      sc_advskew;
118         int                      sc_naddrs;     /* actually used IPv4 vha */
119         int                      sc_naddrs6;
120         int                      sc_advbase;    /* seconds */
121         int                      sc_init_counter;
122         uint64_t                 sc_counter;
123
124         /* authentication */
125 #define CARP_HMAC_PAD   64
126         unsigned char            sc_key[CARP_KEY_LEN];
127         unsigned char            sc_pad[CARP_HMAC_PAD];
128         SHA1_CTX                 sc_sha1;
129
130         struct callout           sc_ad_tmo;     /* advertisement timeout */
131         struct callout           sc_md_tmo;     /* master down timeout */
132         struct callout           sc_md6_tmo;    /* master down timeout */
133
134         LIST_ENTRY(carp_softc)   sc_next;       /* Interface clue */
135 };
136
137 struct carp_if {
138         TAILQ_HEAD(, carp_softc) vhif_vrs;
139 };
140
141 enum    { CARP_COUNT_MASTER, CARP_COUNT_RUNNING };
142
143 SYSCTL_DECL(_net_inet_carp);
144
145 static int carp_opts[CARPCTL_MAXID] = { 0, 1, 0, 1, 0, 0 }; /* XXX for now */
146 SYSCTL_INT(_net_inet_carp, CARPCTL_ALLOW, allow, CTLFLAG_RW,
147     &carp_opts[CARPCTL_ALLOW], 0, "Accept incoming CARP packets");
148 SYSCTL_INT(_net_inet_carp, CARPCTL_PREEMPT, preempt, CTLFLAG_RW,
149     &carp_opts[CARPCTL_PREEMPT], 0, "high-priority backup preemption mode");
150 SYSCTL_INT(_net_inet_carp, CARPCTL_LOG, log, CTLFLAG_RW,
151     &carp_opts[CARPCTL_LOG], 0, "log bad carp packets");
152 SYSCTL_INT(_net_inet_carp, CARPCTL_ARPBALANCE, arpbalance, CTLFLAG_RW,
153     &carp_opts[CARPCTL_ARPBALANCE], 0, "balance arp responses");
154
155 static int carp_suppress_preempt = 0;
156 SYSCTL_INT(_net_inet_carp, OID_AUTO, suppress_preempt, CTLFLAG_RD,
157     &carp_suppress_preempt, 0, "Preemption is suppressed");
158
159 static struct carpstats carpstats;
160 SYSCTL_STRUCT(_net_inet_carp, CARPCTL_STATS, stats, CTLFLAG_RW,
161     &carpstats, carpstats,
162     "CARP statistics (struct carpstats, netinet/ip_carp.h)");
163
164 #define CARP_LOG(...)   do {                            \
165         if (carp_opts[CARPCTL_LOG] > 0)                 \
166                 log(LOG_INFO, __VA_ARGS__);             \
167 } while (0)
168
169 #define CARP_DEBUG(...) do {                            \
170         if (carp_opts[CARPCTL_LOG] > 1)                 \
171                 log(LOG_DEBUG, __VA_ARGS__);            \
172 } while (0)
173
174 static void     carp_hmac_prepare(struct carp_softc *);
175 static void     carp_hmac_generate(struct carp_softc *, uint32_t *,
176                     unsigned char *);
177 static int      carp_hmac_verify(struct carp_softc *, uint32_t *,
178                     unsigned char *);
179 static void     carp_setroute(struct carp_softc *, int);
180 static void     carp_input_c(struct mbuf *, struct carp_header *, sa_family_t);
181 static int      carp_clone_create(struct if_clone *, int);
182 static void     carp_clone_destroy(struct ifnet *);
183 static void     carp_detach(struct carp_softc *, int);
184 static int      carp_prepare_ad(struct mbuf *, struct carp_softc *,
185                     struct carp_header *);
186 static void     carp_send_ad_all(void);
187 static void     carp_send_ad_timeout(void *);
188 static void     carp_send_ad(struct carp_softc *);
189 static void     carp_send_arp(struct carp_softc *);
190 static void     carp_master_down_timeout(void *);
191 static void     carp_master_down(struct carp_softc *);
192 static int      carp_ioctl(struct ifnet *, u_long, caddr_t, struct ucred *);
193 static int      carp_looutput(struct ifnet *, struct mbuf *, struct sockaddr *,
194                     struct rtentry *);
195 static void     carp_start(struct ifnet *);
196 static void     carp_setrun(struct carp_softc *, sa_family_t);
197 static void     carp_set_state(struct carp_softc *, int);
198
199 static void     carp_multicast_cleanup(struct carp_softc *);
200 static void     carp_add_addr(struct carp_softc *, struct ifaddr *);
201 static void     carp_del_addr(struct carp_softc *, struct ifaddr *);
202 static void     carp_config_addr(struct carp_softc *, struct ifaddr *);
203 static void     carp_link_addrs(struct carp_softc *, struct ifnet *,
204                     struct ifaddr *);
205 static void     carp_unlink_addrs(struct carp_softc *, struct ifnet *,
206                     struct ifaddr *);
207
208 static int      carp_get_vhaddr(struct carp_softc *, struct ifdrv *);
209 static int      carp_config_vhaddr(struct carp_softc *, struct carp_vhaddr *);
210 static int      carp_activate_vhaddr(struct carp_softc *, struct carp_vhaddr *,
211                     struct ifnet *, const struct in_ifaddr *, int);
212 static void     carp_deactivate_vhaddr(struct carp_softc *,
213                     struct carp_vhaddr *);
214
215 static void     carp_sc_state(struct carp_softc *);
216 #ifdef INET6
217 static void     carp_send_na(struct carp_softc *);
218 static int      carp_set_addr6(struct carp_softc *, struct sockaddr_in6 *);
219 static int      carp_del_addr6(struct carp_softc *, struct sockaddr_in6 *);
220 static void     carp_multicast6_cleanup(struct carp_softc *);
221 #endif
222 static void     carp_stop(struct carp_softc *, int);
223 static void     carp_reset(struct carp_softc *, int);
224
225 static void     carp_ifaddr(void *, struct ifnet *, enum ifaddr_event,
226                             struct ifaddr *);
227 static void     carp_ifdetach(void *, struct ifnet *);
228
229 static MALLOC_DEFINE(M_CARP, "CARP", "CARP interfaces");
230
231 static LIST_HEAD(, carp_softc) carpif_list;
232
233 static struct if_clone carp_cloner =
234 IF_CLONE_INITIALIZER(CARP_IFNAME, carp_clone_create, carp_clone_destroy,
235                      0, IF_MAXUNIT);
236
237 static eventhandler_tag carp_ifdetach_event;
238 static eventhandler_tag carp_ifaddr_event;
239
240 static __inline void
241 carp_insert_vhaddr(struct carp_softc *sc, struct carp_vhaddr *vha_new)
242 {
243         struct carp_vhaddr *vha;
244         u_long new_addr, addr;
245
246         KKASSERT((vha_new->vha_flags & CARP_VHAF_ONLIST) == 0);
247
248         /*
249          * Virtual address list is sorted; smaller one first
250          */
251         new_addr = ntohl(vha_new->vha_ia->ia_addr.sin_addr.s_addr);
252
253         TAILQ_FOREACH(vha, &sc->sc_vha_list, vha_link) {
254                 addr = ntohl(vha->vha_ia->ia_addr.sin_addr.s_addr);
255
256                 if (addr > new_addr)
257                         break;
258         }
259         if (vha == NULL)
260                 TAILQ_INSERT_TAIL(&sc->sc_vha_list, vha_new, vha_link);
261         else
262                 TAILQ_INSERT_BEFORE(vha, vha_new, vha_link);
263         vha_new->vha_flags |= CARP_VHAF_ONLIST;
264 }
265
266 static __inline void
267 carp_remove_vhaddr(struct carp_softc *sc, struct carp_vhaddr *vha)
268 {
269         KKASSERT(vha->vha_flags & CARP_VHAF_ONLIST);
270         vha->vha_flags &= ~CARP_VHAF_ONLIST;
271         TAILQ_REMOVE(&sc->sc_vha_list, vha, vha_link);
272 }
273
274 static void
275 carp_hmac_prepare(struct carp_softc *sc)
276 {
277         uint8_t version = CARP_VERSION, type = CARP_ADVERTISEMENT;
278         uint8_t vhid = sc->sc_vhid & 0xff;
279         struct ifaddr_container *ifac;
280         int i;
281 #ifdef INET6
282         struct in6_addr in6;
283 #endif
284 #ifdef INET
285         struct carp_vhaddr *vha;
286 #endif
287
288         /* XXX: possible race here */
289
290         /* compute ipad from key */
291         bzero(sc->sc_pad, sizeof(sc->sc_pad));
292         bcopy(sc->sc_key, sc->sc_pad, sizeof(sc->sc_key));
293         for (i = 0; i < sizeof(sc->sc_pad); i++)
294                 sc->sc_pad[i] ^= 0x36;
295
296         /* precompute first part of inner hash */
297         SHA1Init(&sc->sc_sha1);
298         SHA1Update(&sc->sc_sha1, sc->sc_pad, sizeof(sc->sc_pad));
299         SHA1Update(&sc->sc_sha1, (void *)&version, sizeof(version));
300         SHA1Update(&sc->sc_sha1, (void *)&type, sizeof(type));
301         SHA1Update(&sc->sc_sha1, (void *)&vhid, sizeof(vhid));
302 #ifdef INET
303         TAILQ_FOREACH(vha, &sc->sc_vha_list, vha_link) {
304                 SHA1Update(&sc->sc_sha1,
305                     (const uint8_t *)&vha->vha_ia->ia_addr.sin_addr,
306                     sizeof(struct in_addr));
307         }
308 #endif /* INET */
309 #ifdef INET6
310         TAILQ_FOREACH(ifac, &sc->sc_if.if_addrheads[mycpuid], ifa_link) {
311                 struct ifaddr *ifa = ifac->ifa;
312
313                 if (ifa->ifa_addr->sa_family == AF_INET6) {
314                         in6 = ifatoia6(ifa)->ia_addr.sin6_addr;
315                         in6_clearscope(&in6);
316                         SHA1Update(&sc->sc_sha1, (void *)&in6, sizeof(in6));
317                 }
318         }
319 #endif /* INET6 */
320
321         /* convert ipad to opad */
322         for (i = 0; i < sizeof(sc->sc_pad); i++)
323                 sc->sc_pad[i] ^= 0x36 ^ 0x5c;
324 }
325
326 static void
327 carp_hmac_generate(struct carp_softc *sc, uint32_t counter[2],
328     unsigned char md[20])
329 {
330         SHA1_CTX sha1ctx;
331
332         /* fetch first half of inner hash */
333         bcopy(&sc->sc_sha1, &sha1ctx, sizeof(sha1ctx));
334
335         SHA1Update(&sha1ctx, (void *)counter, sizeof(sc->sc_counter));
336         SHA1Final(md, &sha1ctx);
337
338         /* outer hash */
339         SHA1Init(&sha1ctx);
340         SHA1Update(&sha1ctx, sc->sc_pad, sizeof(sc->sc_pad));
341         SHA1Update(&sha1ctx, md, 20);
342         SHA1Final(md, &sha1ctx);
343 }
344
345 static int
346 carp_hmac_verify(struct carp_softc *sc, uint32_t counter[2],
347     unsigned char md[20])
348 {
349         unsigned char md2[20];
350
351         carp_hmac_generate(sc, counter, md2);
352         return (bcmp(md, md2, sizeof(md2)));
353 }
354
355 static void
356 carp_setroute(struct carp_softc *sc, int cmd)
357 {
358 #ifdef INET6
359         struct ifaddr_container *ifac;
360
361         crit_enter();
362         TAILQ_FOREACH(ifac, &sc->sc_if.if_addrheads[mycpuid], ifa_link) {
363                 struct ifaddr *ifa = ifac->ifa;
364
365                 if (ifa->ifa_addr->sa_family == AF_INET6) {
366                         if (cmd == RTM_ADD)
367                                 in6_ifaddloop(ifa);
368                         else
369                                 in6_ifremloop(ifa);
370                 }
371         }
372         crit_exit();
373 #endif /* INET6 */
374 }
375
376 static int
377 carp_clone_create(struct if_clone *ifc, int unit)
378 {
379         struct carp_softc *sc;
380         struct ifnet *ifp;
381
382         sc = kmalloc(sizeof(*sc), M_CARP, M_WAITOK | M_ZERO);
383         ifp = &sc->sc_if;
384
385         sc->sc_suppress = 0;
386         sc->sc_advbase = CARP_DFLTINTV;
387         sc->sc_vhid = -1;       /* required setting */
388         sc->sc_advskew = 0;
389         sc->sc_init_counter = 1;
390         sc->sc_naddrs = 0;
391         sc->sc_naddrs6 = 0;
392
393         TAILQ_INIT(&sc->sc_vha_list);
394
395 #ifdef INET6
396         sc->sc_im6o.im6o_multicast_hlim = CARP_DFLTTL;
397 #endif
398
399         callout_init(&sc->sc_ad_tmo);
400         callout_init(&sc->sc_md_tmo);
401         callout_init(&sc->sc_md6_tmo);
402
403         ifp->if_softc = sc;
404         if_initname(ifp, CARP_IFNAME, unit);    
405         ifp->if_mtu = ETHERMTU;
406         ifp->if_flags = IFF_LOOPBACK;
407         ifp->if_ioctl = carp_ioctl;
408         ifp->if_output = carp_looutput;
409         ifp->if_start = carp_start;
410         ifp->if_type = IFT_CARP;
411         ifp->if_snd.ifq_maxlen = ifqmaxlen;
412         ifp->if_hdrlen = 0;
413         if_attach(ifp, NULL);
414         bpfattach(ifp, DLT_NULL, sizeof(u_int));
415
416         crit_enter();
417         LIST_INSERT_HEAD(&carpif_list, sc, sc_next);
418         crit_exit();
419
420         return (0);
421 }
422
423 static void
424 carp_clone_destroy(struct ifnet *ifp)
425 {
426         struct carp_softc *sc = ifp->if_softc;
427
428         sc->sc_dead = 1;
429         carp_detach(sc, 1);
430
431         crit_enter();
432         LIST_REMOVE(sc, sc_next);
433         crit_exit();
434         bpfdetach(ifp);
435         if_detach(ifp);
436
437         KASSERT(sc->sc_naddrs == 0, ("certain inet address is still active\n"));
438         kfree(sc, M_CARP);
439 }
440
441 static void
442 carp_detach(struct carp_softc *sc, int detach)
443 {
444         struct carp_if *cif;
445
446         carp_reset(sc, detach);
447
448         carp_multicast_cleanup(sc);
449 #ifdef INET6
450         carp_multicast6_cleanup(sc);
451 #endif
452
453         if (!sc->sc_dead && detach) {
454                 struct carp_vhaddr *vha;
455
456                 TAILQ_FOREACH(vha, &sc->sc_vha_list, vha_link)
457                         carp_deactivate_vhaddr(sc, vha);
458                 KKASSERT(sc->sc_naddrs == 0);
459         }
460
461         if (sc->sc_carpdev != NULL) {
462                 cif = sc->sc_carpdev->if_carp;
463                 TAILQ_REMOVE(&cif->vhif_vrs, sc, sc_list);
464                 if (TAILQ_EMPTY(&cif->vhif_vrs)) {
465                         ifpromisc(sc->sc_carpdev, 0);
466                         sc->sc_carpdev->if_carp = NULL;
467                         kfree(cif, M_CARP);
468                 }
469                 sc->sc_carpdev = NULL;
470                 sc->sc_ia = NULL;
471         }
472 }
473
474 /* Detach an interface from the carp. */
475 static void
476 carp_ifdetach(void *arg __unused, struct ifnet *ifp)
477 {
478         struct carp_if *cif = ifp->if_carp;
479         struct carp_softc *sc;
480
481         while (ifp->if_carp &&
482                (sc = TAILQ_FIRST(&cif->vhif_vrs)) != NULL)
483                 carp_detach(sc, 1);
484 }
485
486 /*
487  * process input packet.
488  * we have rearranged checks order compared to the rfc,
489  * but it seems more efficient this way or not possible otherwise.
490  */
491 void
492 carp_input(struct mbuf *m, ...)
493 {
494         struct ip *ip = mtod(m, struct ip *);
495         struct carp_header *ch;
496         int len, iphlen;
497         __va_list ap;
498
499         __va_start(ap, m);
500         iphlen = __va_arg(ap, int);
501         __va_end(ap);
502
503         carpstats.carps_ipackets++;
504
505         if (!carp_opts[CARPCTL_ALLOW]) {
506                 m_freem(m);
507                 return;
508         }
509
510         /* Check if received on a valid carp interface */
511         if (m->m_pkthdr.rcvif->if_carp == NULL) {
512                 carpstats.carps_badif++;
513                 CARP_LOG("carp_input: packet received on non-carp "
514                     "interface: %s\n",
515                     m->m_pkthdr.rcvif->if_xname);
516                 m_freem(m);
517                 return;
518         }
519
520         /* Verify that the IP TTL is CARP_DFLTTL. */
521         if (ip->ip_ttl != CARP_DFLTTL) {
522                 carpstats.carps_badttl++;
523                 CARP_LOG("carp_input: received ttl %d != %d on %s\n",
524                     ip->ip_ttl, CARP_DFLTTL,
525                     m->m_pkthdr.rcvif->if_xname);
526                 m_freem(m);
527                 return;
528         }
529
530         /* Minimal CARP packet size */
531         len = iphlen + sizeof(*ch);
532
533         /*
534          * Verify that the received packet length is
535          * not less than the CARP header
536          */
537         if (m->m_pkthdr.len < len) {
538                 carpstats.carps_badlen++;
539                 CARP_LOG("packet too short %d on %s\n", m->m_pkthdr.len,
540                          m->m_pkthdr.rcvif->if_xname);
541                 m_freem(m);
542                 return;
543         }
544
545         /* Make sure that CARP header is contiguous */
546         if (len > m->m_len) {
547                 m = m_pullup(m, len);
548                 if (m == NULL) {
549                         carpstats.carps_hdrops++;
550                         CARP_LOG("carp_input: m_pullup failed\n");
551                         return;
552                 }
553                 ip = mtod(m, struct ip *);
554         }
555         ch = (struct carp_header *)((uint8_t *)ip + iphlen);
556
557         /* Verify the CARP checksum */
558         if (in_cksum_skip(m, len, iphlen)) {
559                 carpstats.carps_badsum++;
560                 CARP_LOG("carp_input: checksum failed on %s\n",
561                     m->m_pkthdr.rcvif->if_xname);
562                 m_freem(m);
563                 return;
564         }
565         carp_input_c(m, ch, AF_INET);
566 }
567
568 #ifdef INET6
569 int
570 carp6_input(struct mbuf **mp, int *offp, int proto)
571 {
572         struct mbuf *m = *mp;
573         struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
574         struct carp_header *ch;
575         u_int len;
576
577         carpstats.carps_ipackets6++;
578
579         if (!carp_opts[CARPCTL_ALLOW]) {
580                 m_freem(m);
581                 return (IPPROTO_DONE);
582         }
583
584         /* check if received on a valid carp interface */
585         if (m->m_pkthdr.rcvif->if_carp == NULL) {
586                 carpstats.carps_badif++;
587                 CARP_LOG("carp6_input: packet received on non-carp "
588                     "interface: %s\n",
589                     m->m_pkthdr.rcvif->if_xname);
590                 m_freem(m);
591                 return (IPPROTO_DONE);
592         }
593
594         /* verify that the IP TTL is 255 */
595         if (ip6->ip6_hlim != CARP_DFLTTL) {
596                 carpstats.carps_badttl++;
597                 CARP_LOG("carp6_input: received ttl %d != 255 on %s\n",
598                     ip6->ip6_hlim,
599                     m->m_pkthdr.rcvif->if_xname);
600                 m_freem(m);
601                 return (IPPROTO_DONE);
602         }
603
604         /* verify that we have a complete carp packet */
605         len = m->m_len;
606         IP6_EXTHDR_GET(ch, struct carp_header *, m, *offp, sizeof(*ch));
607         if (ch == NULL) {
608                 carpstats.carps_badlen++;
609                 CARP_LOG("carp6_input: packet size %u too small\n", len);
610                 return (IPPROTO_DONE);
611         }
612
613         /* verify the CARP checksum */
614         if (in_cksum_range(m, 0, *offp, sizeof(*ch))) {
615                 carpstats.carps_badsum++;
616                 CARP_LOG("carp6_input: checksum failed, on %s\n",
617                     m->m_pkthdr.rcvif->if_xname);
618                 m_freem(m);
619                 return (IPPROTO_DONE);
620         }
621
622         carp_input_c(m, ch, AF_INET6);
623         return (IPPROTO_DONE);
624 }
625 #endif /* INET6 */
626
627 static void
628 carp_input_c(struct mbuf *m, struct carp_header *ch, sa_family_t af)
629 {
630         struct ifnet *ifp = m->m_pkthdr.rcvif;
631         struct ifnet *cifp;
632         struct carp_softc *sc;
633         uint64_t tmp_counter;
634         struct timeval sc_tv, ch_tv;
635
636         /* verify that the VHID is valid on the receiving interface */
637         TAILQ_FOREACH(sc, &((struct carp_if *)ifp->if_carp)->vhif_vrs, sc_list)
638                 if (sc->sc_vhid == ch->carp_vhid)
639                         break;
640
641         if (!sc || !CARP_IS_RUNNING(&sc->sc_if)) {
642                 carpstats.carps_badvhid++;
643                 m_freem(m);
644                 return;
645         }
646         cifp = &sc->sc_if;
647
648         getmicrotime(&cifp->if_lastchange);
649         cifp->if_ipackets++;
650         cifp->if_ibytes += m->m_pkthdr.len;
651
652         if (cifp->if_bpf) {
653                 struct ip *ip = mtod(m, struct ip *);
654
655                 /* BPF wants net byte order */
656                 ip->ip_len = htons(ip->ip_len + (ip->ip_hl << 2));
657                 ip->ip_off = htons(ip->ip_off);
658                 bpf_mtap(cifp->if_bpf, m);
659         }
660
661         /* verify the CARP version. */
662         if (ch->carp_version != CARP_VERSION) {
663                 carpstats.carps_badver++;
664                 cifp->if_ierrors++;
665                 CARP_LOG("%s; invalid version %d\n", cifp->if_xname,
666                          ch->carp_version);
667                 m_freem(m);
668                 return;
669         }
670
671         /* verify the hash */
672         if (carp_hmac_verify(sc, ch->carp_counter, ch->carp_md)) {
673                 carpstats.carps_badauth++;
674                 cifp->if_ierrors++;
675                 CARP_LOG("%s: incorrect hash\n", cifp->if_xname);
676                 m_freem(m);
677                 return;
678         }
679
680         tmp_counter = ntohl(ch->carp_counter[0]);
681         tmp_counter = tmp_counter<<32;
682         tmp_counter += ntohl(ch->carp_counter[1]);
683
684         /* XXX Replay protection goes here */
685
686         sc->sc_init_counter = 0;
687         sc->sc_counter = tmp_counter;
688
689         sc_tv.tv_sec = sc->sc_advbase;
690         if (carp_suppress_preempt && sc->sc_advskew <  240)
691                 sc_tv.tv_usec = 240 * 1000000 / 256;
692         else
693                 sc_tv.tv_usec = sc->sc_advskew * 1000000 / 256;
694         ch_tv.tv_sec = ch->carp_advbase;
695         ch_tv.tv_usec = ch->carp_advskew * 1000000 / 256;
696
697         switch (sc->sc_state) {
698         case INIT:
699                 break;
700
701         case MASTER:
702                 /*
703                  * If we receive an advertisement from a master who's going to
704                  * be more frequent than us, go into BACKUP state.
705                  */
706                 if (timevalcmp(&sc_tv, &ch_tv, >) ||
707                     timevalcmp(&sc_tv, &ch_tv, ==)) {
708                         callout_stop(&sc->sc_ad_tmo);
709                         CARP_DEBUG("%s: MASTER -> BACKUP "
710                            "(more frequent advertisement received)\n",
711                            cifp->if_xname);
712                         carp_set_state(sc, BACKUP);
713                         carp_setrun(sc, 0);
714                         carp_setroute(sc, RTM_DELETE);
715                 }
716                 break;
717
718         case BACKUP:
719                 /*
720                  * If we're pre-empting masters who advertise slower than us,
721                  * and this one claims to be slower, treat him as down.
722                  */
723                 if (carp_opts[CARPCTL_PREEMPT] &&
724                     timevalcmp(&sc_tv, &ch_tv, <)) {
725                         CARP_DEBUG("%s: BACKUP -> MASTER "
726                             "(preempting a slower master)\n", cifp->if_xname);
727                         carp_master_down(sc);
728                         break;
729                 }
730
731                 /*
732                  *  If the master is going to advertise at such a low frequency
733                  *  that he's guaranteed to time out, we'd might as well just
734                  *  treat him as timed out now.
735                  */
736                 sc_tv.tv_sec = sc->sc_advbase * 3;
737                 if (timevalcmp(&sc_tv, &ch_tv, <)) {
738                         CARP_DEBUG("%s: BACKUP -> MASTER (master timed out)\n",
739                                    cifp->if_xname);
740                         carp_master_down(sc);
741                         break;
742                 }
743
744                 /*
745                  * Otherwise, we reset the counter and wait for the next
746                  * advertisement.
747                  */
748                 carp_setrun(sc, af);
749                 break;
750         }
751         m_freem(m);
752 }
753
754 static int
755 carp_prepare_ad(struct mbuf *m, struct carp_softc *sc, struct carp_header *ch)
756 {
757         struct ifnet *cifp = &sc->sc_if;
758         struct m_tag *mtag;
759
760         if (sc->sc_init_counter) {
761                 /* this could also be seconds since unix epoch */
762                 sc->sc_counter = karc4random();
763                 sc->sc_counter = sc->sc_counter << 32;
764                 sc->sc_counter += karc4random();
765         } else {
766                 sc->sc_counter++;
767         }
768
769         ch->carp_counter[0] = htonl((sc->sc_counter >> 32) & 0xffffffff);
770         ch->carp_counter[1] = htonl(sc->sc_counter & 0xffffffff);
771
772         carp_hmac_generate(sc, ch->carp_counter, ch->carp_md);
773
774         /* Tag packet for carp_output */
775         mtag = m_tag_get(PACKET_TAG_CARP, sizeof(struct ifnet *), MB_DONTWAIT);
776         if (mtag == NULL) {
777                 m_freem(m);
778                 cifp->if_oerrors++;
779                 return ENOMEM;
780         }
781         bcopy(&cifp, (caddr_t)(mtag + 1), sizeof(struct ifnet *));
782         m_tag_prepend(m, mtag);
783
784         return 0;
785 }
786
787 static void
788 carp_send_ad_all(void)
789 {
790         struct carp_softc *sc;
791
792         LIST_FOREACH(sc, &carpif_list, sc_next) {
793                 if (sc->sc_carpdev == NULL)
794                         continue;
795
796                 if (CARP_IS_RUNNING(&sc->sc_if) && sc->sc_state == MASTER)
797                         carp_send_ad(sc);
798         }
799 }
800
801 static void
802 carp_send_ad_timeout(void *xsc)
803 {
804         carp_send_ad(xsc);
805 }
806
807 static void
808 carp_send_ad(struct carp_softc *sc)
809 {
810         struct ifnet *cifp = &sc->sc_if;
811         struct carp_header ch;
812         struct timeval tv;
813         struct carp_header *ch_ptr;
814         struct mbuf *m;
815         int len, advbase, advskew;
816
817         if (!CARP_IS_RUNNING(cifp)) {
818                 /* Bow out */
819                 advbase = 255;
820                 advskew = 255;
821         } else {
822                 advbase = sc->sc_advbase;
823                 if (!carp_suppress_preempt || sc->sc_advskew > 240)
824                         advskew = sc->sc_advskew;
825                 else
826                         advskew = 240;
827                 tv.tv_sec = advbase;
828                 tv.tv_usec = advskew * 1000000 / 256;
829         }
830
831         ch.carp_version = CARP_VERSION;
832         ch.carp_type = CARP_ADVERTISEMENT;
833         ch.carp_vhid = sc->sc_vhid;
834         ch.carp_advbase = advbase;
835         ch.carp_advskew = advskew;
836         ch.carp_authlen = 7;    /* XXX DEFINE */
837         ch.carp_pad1 = 0;       /* must be zero */
838         ch.carp_cksum = 0;
839
840 #ifdef INET
841         if (sc->sc_ia != NULL) {
842                 struct ip *ip;
843
844                 MGETHDR(m, MB_DONTWAIT, MT_HEADER);
845                 if (m == NULL) {
846                         cifp->if_oerrors++;
847                         carpstats.carps_onomem++;
848                         /* XXX maybe less ? */
849                         if (advbase != 255 || advskew != 255)
850                                 callout_reset(&sc->sc_ad_tmo, tvtohz_high(&tv),
851                                     carp_send_ad_timeout, sc);
852                         return;
853                 }
854                 len = sizeof(*ip) + sizeof(ch);
855                 m->m_pkthdr.len = len;
856                 m->m_pkthdr.rcvif = NULL;
857                 m->m_len = len;
858                 MH_ALIGN(m, m->m_len);
859                 m->m_flags |= M_MCAST;
860                 ip = mtod(m, struct ip *);
861                 ip->ip_v = IPVERSION;
862                 ip->ip_hl = sizeof(*ip) >> 2;
863                 ip->ip_tos = IPTOS_LOWDELAY;
864                 ip->ip_len = len;
865                 ip->ip_id = ip_newid();
866                 ip->ip_off = IP_DF;
867                 ip->ip_ttl = CARP_DFLTTL;
868                 ip->ip_p = IPPROTO_CARP;
869                 ip->ip_sum = 0;
870                 ip->ip_src = sc->sc_ia->ia_addr.sin_addr;
871                 ip->ip_dst.s_addr = htonl(INADDR_CARP_GROUP);
872
873                 ch_ptr = (struct carp_header *)(&ip[1]);
874                 bcopy(&ch, ch_ptr, sizeof(ch));
875                 if (carp_prepare_ad(m, sc, ch_ptr))
876                         return;
877                 ch_ptr->carp_cksum = in_cksum_skip(m, len, sizeof(*ip));
878
879                 getmicrotime(&cifp->if_lastchange);
880                 cifp->if_opackets++;
881                 cifp->if_obytes += len;
882                 carpstats.carps_opackets++;
883
884                 if (ip_output(m, NULL, NULL, IP_RAWOUTPUT, &sc->sc_imo, NULL)) {
885                         cifp->if_oerrors++;
886                         if (sc->sc_sendad_errors < INT_MAX)
887                                 sc->sc_sendad_errors++;
888                         if (sc->sc_sendad_errors == CARP_SENDAD_MAX_ERRORS) {
889                                 carp_suppress_preempt++;
890                                 if (carp_suppress_preempt == 1) {
891                                         carp_send_ad_all();
892                                 }
893                         }
894                         sc->sc_sendad_success = 0;
895                 } else {
896                         if (sc->sc_sendad_errors >= CARP_SENDAD_MAX_ERRORS) {
897                                 if (++sc->sc_sendad_success >=
898                                     CARP_SENDAD_MIN_SUCCESS) {
899                                         carp_suppress_preempt--;
900                                         sc->sc_sendad_errors = 0;
901                                 }
902                         } else {
903                                 sc->sc_sendad_errors = 0;
904                         }
905                 }
906         }
907 #endif /* INET */
908 #ifdef INET6
909         if (sc->sc_ia6) {
910                 struct ip6_hdr *ip6;
911
912                 MGETHDR(m, MB_DONTWAIT, MT_HEADER);
913                 if (m == NULL) {
914                         cifp->if_oerrors++;
915                         carpstats.carps_onomem++;
916                         /* XXX maybe less ? */
917                         if (advbase != 255 || advskew != 255)
918                                 callout_reset(&sc->sc_ad_tmo, tvtohz_high(&tv),
919                                     carp_send_ad_timeout, sc);
920                         return;
921                 }
922                 len = sizeof(*ip6) + sizeof(ch);
923                 m->m_pkthdr.len = len;
924                 m->m_pkthdr.rcvif = NULL;
925                 m->m_len = len;
926                 MH_ALIGN(m, m->m_len);
927                 m->m_flags |= M_MCAST;
928                 ip6 = mtod(m, struct ip6_hdr *);
929                 bzero(ip6, sizeof(*ip6));
930                 ip6->ip6_vfc |= IPV6_VERSION;
931                 ip6->ip6_hlim = CARP_DFLTTL;
932                 ip6->ip6_nxt = IPPROTO_CARP;
933                 bcopy(&sc->sc_ia6->ia_addr.sin6_addr, &ip6->ip6_src,
934                     sizeof(struct in6_addr));
935                 /* set the multicast destination */
936
937                 ip6->ip6_dst.s6_addr16[0] = htons(0xff02);
938                 ip6->ip6_dst.s6_addr8[15] = 0x12;
939                 if (in6_setscope(&ip6->ip6_dst, sc->sc_carpdev, NULL) != 0) {
940                         cifp->if_oerrors++;
941                         m_freem(m);
942                         CARP_LOG("%s: in6_setscope failed\n", __func__);
943                         return;
944                 }
945
946                 ch_ptr = (struct carp_header *)(&ip6[1]);
947                 bcopy(&ch, ch_ptr, sizeof(ch));
948                 if (carp_prepare_ad(m, sc, ch_ptr))
949                         return;
950                 ch_ptr->carp_cksum = in_cksum_skip(m, len, sizeof(*ip6));
951
952                 getmicrotime(&cifp->if_lastchange);
953                 cifp->if_opackets++;
954                 cifp->if_obytes += len;
955                 carpstats.carps_opackets6++;
956
957                 if (ip6_output(m, NULL, NULL, 0, &sc->sc_im6o, NULL, NULL)) {
958                         cifp->if_oerrors++;
959                         if (sc->sc_sendad_errors < INT_MAX)
960                                 sc->sc_sendad_errors++;
961                         if (sc->sc_sendad_errors == CARP_SENDAD_MAX_ERRORS) {
962                                 carp_suppress_preempt++;
963                                 if (carp_suppress_preempt == 1) {
964                                         carp_send_ad_all();
965                                 }
966                         }
967                         sc->sc_sendad_success = 0;
968                 } else {
969                         if (sc->sc_sendad_errors >= CARP_SENDAD_MAX_ERRORS) {
970                                 if (++sc->sc_sendad_success >=
971                                     CARP_SENDAD_MIN_SUCCESS) {
972                                         carp_suppress_preempt--;
973                                         sc->sc_sendad_errors = 0;
974                                 }
975                         } else {
976                                 sc->sc_sendad_errors = 0;
977                         }
978                 }
979         }
980 #endif /* INET6 */
981
982         if (advbase != 255 || advskew != 255)
983                 callout_reset(&sc->sc_ad_tmo, tvtohz_high(&tv),
984                     carp_send_ad_timeout, sc);
985 }
986
987 /*
988  * Broadcast a gratuitous ARP request containing
989  * the virtual router MAC address for each IP address
990  * associated with the virtual router.
991  */
992 static void
993 carp_send_arp(struct carp_softc *sc)
994 {
995         const struct carp_vhaddr *vha;
996
997         TAILQ_FOREACH(vha, &sc->sc_vha_list, vha_link) {
998                 if (vha->vha_iaback == NULL)
999                         continue;
1000
1001                 arp_iainit(sc->sc_carpdev, &vha->vha_ia->ia_addr.sin_addr,
1002                            IF_LLADDR(&sc->sc_if));
1003         }
1004 }
1005
1006 #ifdef INET6
1007 static void
1008 carp_send_na(struct carp_softc *sc)
1009 {
1010         struct ifaddr_container *ifac;
1011         struct in6_addr *in6;
1012         static struct in6_addr mcast = IN6ADDR_LINKLOCAL_ALLNODES_INIT;
1013
1014         TAILQ_FOREACH(ifac, &sc->sc_if.if_addrheads[mycpuid], ifa_link) {
1015                 struct ifaddr *ifa = ifac->ifa;
1016
1017                 if (ifa->ifa_addr->sa_family != AF_INET6)
1018                         continue;
1019
1020                 in6 = &ifatoia6(ifa)->ia_addr.sin6_addr;
1021                 nd6_na_output(sc->sc_carpdev, &mcast, in6,
1022                     ND_NA_FLAG_OVERRIDE, 1, NULL);
1023                 DELAY(1000);    /* XXX */
1024         }
1025 }
1026 #endif /* INET6 */
1027
1028 static __inline const struct carp_vhaddr *
1029 carp_find_addr(const struct carp_softc *sc, const struct in_addr *addr)
1030 {
1031         struct carp_vhaddr *vha;
1032
1033         TAILQ_FOREACH(vha, &sc->sc_vha_list, vha_link) {
1034                 if (vha->vha_iaback == NULL)
1035                         continue;
1036
1037                 if (vha->vha_ia->ia_addr.sin_addr.s_addr == addr->s_addr)
1038                         return vha;
1039         }
1040         return NULL;
1041 }
1042
1043 static int
1044 carp_iamatch_balance(const struct carp_if *cif, const struct in_addr *itaddr,
1045                      const struct in_addr *isaddr, uint8_t **enaddr)
1046 {
1047         const struct carp_softc *vh;
1048         int index, count = 0;
1049
1050         /*
1051          * XXX proof of concept implementation.
1052          * We use the source ip to decide which virtual host should
1053          * handle the request. If we're master of that virtual host,
1054          * then we respond, otherwise, just drop the arp packet on
1055          * the floor.
1056          */
1057
1058         TAILQ_FOREACH(vh, &cif->vhif_vrs, sc_list) {
1059                 if (!CARP_IS_RUNNING(&vh->sc_if))
1060                         continue;
1061
1062                 if (carp_find_addr(vh, itaddr) != NULL)
1063                         count++;
1064         }
1065         if (count == 0)
1066                 return 0;
1067
1068         /* this should be a hash, like pf_hash() */
1069         index = ntohl(isaddr->s_addr) % count;
1070         count = 0;
1071
1072         TAILQ_FOREACH(vh, &cif->vhif_vrs, sc_list) {
1073                 if (!CARP_IS_RUNNING(&vh->sc_if))
1074                         continue;
1075
1076                 if (carp_find_addr(vh, itaddr) == NULL)
1077                         continue;
1078
1079                 if (count == index) {
1080                         if (vh->sc_state == MASTER) {
1081                                 *enaddr = IF_LLADDR(&vh->sc_if);
1082                                 return 1;
1083                         } else {
1084                                 return 0;
1085                         }
1086                 }
1087                 count++;
1088         }
1089         return 0;
1090 }
1091
1092 int
1093 carp_iamatch(const void *v, const struct in_addr *itaddr,
1094              const struct in_addr *isaddr, uint8_t **enaddr)
1095 {
1096         const struct carp_if *cif = v;
1097         const struct carp_softc *vh;
1098
1099         if (carp_opts[CARPCTL_ARPBALANCE])
1100                 return carp_iamatch_balance(cif, itaddr, isaddr, enaddr);
1101
1102         TAILQ_FOREACH(vh, &cif->vhif_vrs, sc_list) {
1103                 if (!CARP_IS_RUNNING(&vh->sc_if) || vh->sc_state != MASTER)
1104                         continue;
1105
1106                 if (carp_find_addr(vh, itaddr) != NULL) {
1107                         *enaddr = IF_LLADDR(&vh->sc_if);
1108                         return 1;
1109                 }
1110         }
1111         return 0;
1112 }
1113
1114 #ifdef INET6
1115 struct ifaddr *
1116 carp_iamatch6(void *v, struct in6_addr *taddr)
1117 {
1118         struct carp_if *cif = v;
1119         struct carp_softc *vh;
1120
1121         TAILQ_FOREACH(vh, &cif->vhif_vrs, sc_list) {
1122                 struct ifaddr_container *ifac;
1123
1124                 TAILQ_FOREACH(ifac, &vh->sc_if.if_addrheads[mycpuid],
1125                               ifa_link) {
1126                         struct ifaddr *ifa = ifac->ifa;
1127
1128                         if (IN6_ARE_ADDR_EQUAL(taddr,
1129                             &ifatoia6(ifa)->ia_addr.sin6_addr) &&
1130                             CARP_IS_RUNNING(&vh->sc_if) &&
1131                             vh->sc_state == MASTER) {
1132                                 return (ifa);
1133                         }
1134                 }
1135         }
1136         return (NULL);
1137 }
1138
1139 void *
1140 carp_macmatch6(void *v, struct mbuf *m, const struct in6_addr *taddr)
1141 {
1142         struct m_tag *mtag;
1143         struct carp_if *cif = v;
1144         struct carp_softc *sc;
1145
1146         TAILQ_FOREACH(sc, &cif->vhif_vrs, sc_list) {
1147                 struct ifaddr_container *ifac;
1148
1149                 TAILQ_FOREACH(ifac, &sc->sc_if.if_addrheads[mycpuid],
1150                               ifa_link) {
1151                         struct ifaddr *ifa = ifac->ifa;
1152
1153                         if (IN6_ARE_ADDR_EQUAL(taddr,
1154                             &ifatoia6(ifa)->ia_addr.sin6_addr) &&
1155                             CARP_IS_RUNNING(&sc->sc_if)) {
1156                                 struct ifnet *ifp = &sc->sc_if;
1157
1158                                 mtag = m_tag_get(PACKET_TAG_CARP,
1159                                     sizeof(struct ifnet *), MB_DONTWAIT);
1160                                 if (mtag == NULL) {
1161                                         /* better a bit than nothing */
1162                                         return (IF_LLADDR(ifp));
1163                                 }
1164                                 bcopy(&ifp, (caddr_t)(mtag + 1),
1165                                     sizeof(struct ifnet *));
1166                                 m_tag_prepend(m, mtag);
1167
1168                                 return (IF_LLADDR(ifp));
1169                         }
1170                 }
1171         }
1172         return (NULL);
1173 }
1174 #endif
1175
1176 int
1177 carp_forus(const void *v, const void *dhost)
1178 {
1179         const struct carp_if *cif = v;
1180         const struct carp_softc *vh;
1181         const uint8_t *ena = dhost;
1182
1183         if (ena[0] || ena[1] || ena[2] != 0x5e || ena[3] || ena[4] != 1)
1184                 return 0;
1185
1186         TAILQ_FOREACH(vh, &cif->vhif_vrs, sc_list) {
1187                 const struct ifnet *cifp = &vh->sc_if;
1188
1189                 if (CARP_IS_RUNNING(cifp) && vh->sc_state == MASTER &&
1190                     !bcmp(dhost, IF_LLADDR(cifp), ETHER_ADDR_LEN))
1191                         return 1;
1192         }
1193         return 0;
1194 }
1195
1196 static void
1197 carp_master_down_timeout(void *xsc)
1198 {
1199         struct carp_softc *sc = xsc;
1200
1201         CARP_DEBUG("%s: BACKUP -> MASTER (master timed out)\n",
1202                    sc->sc_if.if_xname);
1203         carp_master_down(sc);
1204 }
1205
1206 static void
1207 carp_master_down(struct carp_softc *sc)
1208 {
1209         switch (sc->sc_state) {
1210         case INIT:
1211                 kprintf("%s: master_down event in INIT state\n",
1212                         sc->sc_if.if_xname);
1213                 break;
1214
1215         case MASTER:
1216                 break;
1217
1218         case BACKUP:
1219                 carp_set_state(sc, MASTER);
1220                 carp_send_ad(sc);
1221                 carp_send_arp(sc);
1222 #ifdef INET6
1223                 carp_send_na(sc);
1224 #endif /* INET6 */
1225                 carp_setrun(sc, 0);
1226                 carp_setroute(sc, RTM_ADD);
1227                 break;
1228         }
1229 }
1230
1231 /*
1232  * When in backup state, af indicates whether to reset the master down timer
1233  * for v4 or v6. If it's set to zero, reset the ones which are already pending.
1234  */
1235 static void
1236 carp_setrun(struct carp_softc *sc, sa_family_t af)
1237 {
1238         struct ifnet *cifp = &sc->sc_if;
1239         struct timeval tv;
1240
1241         if (sc->sc_carpdev == NULL) {
1242                 carp_set_state(sc, INIT);
1243                 return;
1244         }
1245
1246         if ((cifp->if_flags & IFF_RUNNING) && sc->sc_vhid > 0 &&
1247             (sc->sc_naddrs || sc->sc_naddrs6)) {
1248                 /* Nothing */
1249         } else {
1250                 carp_setroute(sc, RTM_DELETE);
1251                 return;
1252         }
1253
1254         switch (sc->sc_state) {
1255         case INIT:
1256                 if (carp_opts[CARPCTL_PREEMPT] && !carp_suppress_preempt) {
1257                         carp_send_ad(sc);
1258                         carp_send_arp(sc);
1259 #ifdef INET6
1260                         carp_send_na(sc);
1261 #endif /* INET6 */
1262                         CARP_DEBUG("%s: INIT -> MASTER (preempting)\n",
1263                                    cifp->if_xname);
1264                         carp_set_state(sc, MASTER);
1265                         carp_setroute(sc, RTM_ADD);
1266                 } else {
1267                         CARP_DEBUG("%s: INIT -> BACKUP\n", cifp->if_xname);
1268                         carp_set_state(sc, BACKUP);
1269                         carp_setroute(sc, RTM_DELETE);
1270                         carp_setrun(sc, 0);
1271                 }
1272                 break;
1273
1274         case BACKUP:
1275                 callout_stop(&sc->sc_ad_tmo);
1276                 tv.tv_sec = 3 * sc->sc_advbase;
1277                 tv.tv_usec = sc->sc_advskew * 1000000 / 256;
1278                 switch (af) {
1279 #ifdef INET
1280                 case AF_INET:
1281                         callout_reset(&sc->sc_md_tmo, tvtohz_high(&tv),
1282                             carp_master_down_timeout, sc);
1283                         break;
1284 #endif /* INET */
1285 #ifdef INET6
1286                 case AF_INET6:
1287                         callout_reset(&sc->sc_md6_tmo, tvtohz_high(&tv),
1288                             carp_master_down_timeout, sc);
1289                         break;
1290 #endif /* INET6 */
1291                 default:
1292                         if (sc->sc_naddrs)
1293                                 callout_reset(&sc->sc_md_tmo, tvtohz_high(&tv),
1294                                     carp_master_down_timeout, sc);
1295                         if (sc->sc_naddrs6)
1296                                 callout_reset(&sc->sc_md6_tmo, tvtohz_high(&tv),
1297                                     carp_master_down_timeout, sc);
1298                         break;
1299                 }
1300                 break;
1301
1302         case MASTER:
1303                 tv.tv_sec = sc->sc_advbase;
1304                 tv.tv_usec = sc->sc_advskew * 1000000 / 256;
1305                 callout_reset(&sc->sc_ad_tmo, tvtohz_high(&tv),
1306                     carp_send_ad_timeout, sc);
1307                 break;
1308         }
1309 }
1310
1311 static void
1312 carp_multicast_cleanup(struct carp_softc *sc)
1313 {
1314         struct ip_moptions *imo = &sc->sc_imo;
1315
1316         if (imo->imo_num_memberships == 0)
1317                 return;
1318         KKASSERT(imo->imo_num_memberships == 1);
1319
1320         in_delmulti(imo->imo_membership[0]);
1321         imo->imo_membership[0] = NULL;
1322         imo->imo_num_memberships = 0;
1323         imo->imo_multicast_ifp = NULL;
1324 }
1325
1326 #ifdef INET6
1327 static void
1328 carp_multicast6_cleanup(struct carp_softc *sc)
1329 {
1330         struct ip6_moptions *im6o = &sc->sc_im6o;
1331
1332         while (!LIST_EMPTY(&im6o->im6o_memberships)) {
1333                 struct in6_multi_mship *imm =
1334                     LIST_FIRST(&im6o->im6o_memberships);
1335
1336                 LIST_REMOVE(imm, i6mm_chain);
1337                 in6_leavegroup(imm);
1338         }
1339         im6o->im6o_multicast_ifp = NULL;
1340 }
1341 #endif
1342
1343 static int
1344 carp_get_vhaddr(struct carp_softc *sc, struct ifdrv *ifd)
1345 {
1346         const struct carp_vhaddr *vha;
1347         struct ifcarpvhaddr *carpa, *carpa0;
1348         int count, len, error;
1349
1350         count = 0;
1351         TAILQ_FOREACH(vha, &sc->sc_vha_list, vha_link)
1352                 ++count;
1353
1354         if (ifd->ifd_len == 0) {
1355                 ifd->ifd_len = count * sizeof(*carpa);
1356                 return 0;
1357         } else if (count == 0 || ifd->ifd_len < sizeof(*carpa)) {
1358                 ifd->ifd_len = 0;
1359                 return 0;
1360         }
1361         len = min(ifd->ifd_len, sizeof(*carpa) * count);
1362         KKASSERT(len >= sizeof(*carpa));
1363
1364         carpa0 = carpa = kmalloc(len, M_TEMP, M_WAITOK | M_NULLOK | M_ZERO);
1365         if (carpa == NULL)
1366                 return ENOMEM;
1367
1368         count = 0;
1369         TAILQ_FOREACH(vha, &sc->sc_vha_list, vha_link) {
1370                 if (len < sizeof(*carpa))
1371                         break;
1372
1373                 carpa->carpa_flags = vha->vha_flags;
1374                 carpa->carpa_addr.sin_family = AF_INET;
1375                 carpa->carpa_addr.sin_addr = vha->vha_ia->ia_addr.sin_addr;
1376
1377                 carpa->carpa_baddr.sin_family = AF_INET;
1378                 if (vha->vha_iaback == NULL) {
1379                         carpa->carpa_baddr.sin_addr.s_addr = INADDR_ANY;
1380                 } else {
1381                         carpa->carpa_baddr.sin_addr =
1382                         vha->vha_iaback->ia_addr.sin_addr;
1383                 }
1384
1385                 ++carpa;
1386                 ++count;
1387                 len -= sizeof(*carpa);
1388         }
1389         ifd->ifd_len = sizeof(*carpa) * count;
1390         KKASSERT(ifd->ifd_len > 0);
1391
1392         error = copyout(carpa0, ifd->ifd_data, ifd->ifd_len);
1393         kfree(carpa0, M_TEMP);
1394         return error;
1395 }
1396
1397 static int
1398 carp_config_vhaddr(struct carp_softc *sc, struct carp_vhaddr *vha)
1399 {
1400         struct ifnet *ifp;
1401         struct in_ifaddr *ia_if;
1402         struct in_ifaddr_container *iac;
1403         const struct sockaddr_in *sin;
1404         u_long iaddr;
1405         int own;
1406
1407         KKASSERT(vha->vha_ia != NULL);
1408
1409         sin = &vha->vha_ia->ia_addr;
1410         iaddr = ntohl(sin->sin_addr.s_addr);
1411
1412         ia_if = NULL;
1413         own = 0;
1414         TAILQ_FOREACH(iac, &in_ifaddrheads[mycpuid], ia_link) {
1415                 struct in_ifaddr *ia = iac->ia;
1416
1417                 if ((ia->ia_flags & IFA_ROUTE) == 0)
1418                         continue;
1419
1420                 if (ia->ia_ifp->if_type == IFT_CARP)
1421                         continue;
1422
1423                 /* and, yeah, we need a multicast-capable iface too */
1424                 if ((ia->ia_ifp->if_flags & IFF_MULTICAST) == 0)
1425                         continue;
1426
1427                 if ((iaddr & ia->ia_subnetmask) == ia->ia_subnet) {
1428                         if (sin->sin_addr.s_addr ==
1429                             ia->ia_addr.sin_addr.s_addr)
1430                                 own = 1;
1431                         if (ia_if == NULL)
1432                                 ia_if = ia;
1433                         else if (sc->sc_carpdev != NULL &&
1434                                  sc->sc_carpdev == ia->ia_ifp)
1435                                 ia_if = ia;
1436                 }
1437         }
1438
1439         carp_deactivate_vhaddr(sc, vha);
1440         if (!ia_if)
1441                 return ENOENT;
1442
1443         ifp = ia_if->ia_ifp;
1444
1445         /* XXX Don't allow parent iface to be changed */
1446         if (sc->sc_carpdev != NULL && sc->sc_carpdev != ifp)
1447                 return EEXIST;
1448
1449         return carp_activate_vhaddr(sc, vha, ifp, ia_if, own);
1450 }
1451
1452 static void
1453 carp_add_addr(struct carp_softc *sc, struct ifaddr *carp_ifa)
1454 {
1455         struct carp_vhaddr *vha_new;
1456         struct in_ifaddr *carp_ia;
1457 #ifdef INVARIANTS
1458         struct carp_vhaddr *vha;
1459 #endif
1460
1461         KKASSERT(carp_ifa->ifa_addr->sa_family == AF_INET);
1462         carp_ia = ifatoia(carp_ifa);
1463
1464 #ifdef INVARIANTS
1465         TAILQ_FOREACH(vha, &sc->sc_vha_list, vha_link)
1466                 KKASSERT(vha->vha_ia != NULL && vha->vha_ia != carp_ia);
1467 #endif
1468
1469         vha_new = kmalloc(sizeof(*vha_new), M_CARP, M_WAITOK | M_ZERO);
1470         vha_new->vha_ia = carp_ia;
1471         carp_insert_vhaddr(sc, vha_new);
1472
1473         if (carp_config_vhaddr(sc, vha_new) != 0) {
1474                 /*
1475                  * If the above configuration fails, it may only mean
1476                  * that the new address is problematic.  However, the
1477                  * carp(4) interface may already have several working
1478                  * addresses.  Since the expected behaviour of
1479                  * SIOC[AS]IFADDR is to put the NIC into working state,
1480                  * we try starting the state machine manually here with
1481                  * the hope that the carp(4)'s previously working
1482                  * addresses still could be brought up.
1483                  */
1484                 carp_hmac_prepare(sc);
1485                 carp_set_state(sc, INIT);
1486                 carp_setrun(sc, 0);
1487         }
1488 }
1489
1490 static void
1491 carp_del_addr(struct carp_softc *sc, struct ifaddr *carp_ifa)
1492 {
1493         struct carp_vhaddr *vha;
1494         struct in_ifaddr *carp_ia;
1495
1496         KKASSERT(carp_ifa->ifa_addr->sa_family == AF_INET);
1497         carp_ia = ifatoia(carp_ifa);
1498
1499         TAILQ_FOREACH(vha, &sc->sc_vha_list, vha_link) {
1500                 KKASSERT(vha->vha_ia != NULL);
1501                 if (vha->vha_ia == carp_ia)
1502                         break;
1503         }
1504         KASSERT(vha != NULL, ("no corresponding vhaddr %p\n", carp_ifa));
1505
1506         /*
1507          * Remove the vhaddr from the list before deactivating
1508          * the vhaddr, so that the HMAC could be correctly
1509          * updated in carp_deactivate_vhaddr()
1510          */
1511         carp_remove_vhaddr(sc, vha);
1512
1513         carp_deactivate_vhaddr(sc, vha);
1514         kfree(vha, M_CARP);
1515 }
1516
1517 static void
1518 carp_config_addr(struct carp_softc *sc, struct ifaddr *carp_ifa)
1519 {
1520         struct carp_vhaddr *vha;
1521         struct in_ifaddr *carp_ia;
1522
1523         KKASSERT(carp_ifa->ifa_addr->sa_family == AF_INET);
1524         carp_ia = ifatoia(carp_ifa);
1525
1526         TAILQ_FOREACH(vha, &sc->sc_vha_list, vha_link) {
1527                 KKASSERT(vha->vha_ia != NULL);
1528                 if (vha->vha_ia == carp_ia)
1529                         break;
1530         }
1531         KASSERT(vha != NULL, ("no corresponding vhaddr %p\n", carp_ifa));
1532
1533         /* Remove then reinsert, to keep the vhaddr list sorted */
1534         carp_remove_vhaddr(sc, vha);
1535         carp_insert_vhaddr(sc, vha);
1536
1537         if (carp_config_vhaddr(sc, vha) != 0) {
1538                 /* See the comment in carp_add_addr() */
1539                 carp_hmac_prepare(sc);
1540                 carp_set_state(sc, INIT);
1541                 carp_setrun(sc, 0);
1542         }
1543 }
1544
1545 #ifdef INET6
1546 static int
1547 carp_set_addr6(struct carp_softc *sc, struct sockaddr_in6 *sin6)
1548 {
1549         struct ifnet *ifp;
1550         struct carp_if *cif;
1551         struct in6_ifaddr *ia, *ia_if;
1552         struct ip6_moptions *im6o = &sc->sc_im6o;
1553         struct in6_multi_mship *imm;
1554         struct in6_addr in6;
1555         int own, error;
1556
1557         if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr)) {
1558                 carp_setrun(sc, 0);
1559                 return (0);
1560         }
1561
1562         /* we have to do it by hands to check we won't match on us */
1563         ia_if = NULL; own = 0;
1564         for (ia = in6_ifaddr; ia; ia = ia->ia_next) {
1565                 int i;
1566
1567                 for (i = 0; i < 4; i++) {
1568                         if ((sin6->sin6_addr.s6_addr32[i] &
1569                             ia->ia_prefixmask.sin6_addr.s6_addr32[i]) !=
1570                             (ia->ia_addr.sin6_addr.s6_addr32[i] &
1571                             ia->ia_prefixmask.sin6_addr.s6_addr32[i]))
1572                                 break;
1573                 }
1574                 /* and, yeah, we need a multicast-capable iface too */
1575                 if (ia->ia_ifp != &sc->sc_if &&
1576                     (ia->ia_ifp->if_flags & IFF_MULTICAST) &&
1577                     (i == 4)) {
1578                         if (!ia_if)
1579                                 ia_if = ia;
1580                         if (IN6_ARE_ADDR_EQUAL(&sin6->sin6_addr,
1581                             &ia->ia_addr.sin6_addr))
1582                                 own++;
1583                 }
1584         }
1585
1586         if (!ia_if)
1587                 return (EADDRNOTAVAIL);
1588         ia = ia_if;
1589         ifp = ia->ia_ifp;
1590
1591         if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0 ||
1592             (im6o->im6o_multicast_ifp && im6o->im6o_multicast_ifp != ifp))
1593                 return (EADDRNOTAVAIL);
1594
1595         if (!sc->sc_naddrs6) {
1596                 im6o->im6o_multicast_ifp = ifp;
1597
1598                 /* join CARP multicast address */
1599                 bzero(&in6, sizeof(in6));
1600                 in6.s6_addr16[0] = htons(0xff02);
1601                 in6.s6_addr8[15] = 0x12;
1602                 if (in6_setscope(&in6, ifp, NULL) != 0)
1603                         goto cleanup;
1604                 if ((imm = in6_joingroup(ifp, &in6, &error)) == NULL)
1605                         goto cleanup;
1606                 LIST_INSERT_HEAD(&im6o->im6o_memberships, imm, i6mm_chain);
1607
1608                 /* join solicited multicast address */
1609                 bzero(&in6, sizeof(in6));
1610                 in6.s6_addr16[0] = htons(0xff02);
1611                 in6.s6_addr32[1] = 0;
1612                 in6.s6_addr32[2] = htonl(1);
1613                 in6.s6_addr32[3] = sin6->sin6_addr.s6_addr32[3];
1614                 in6.s6_addr8[12] = 0xff;
1615                 if (in6_setscope(&in6, ifp, NULL) != 0)
1616                         goto cleanup;
1617                 if ((imm = in6_joingroup(ifp, &in6, &error)) == NULL)
1618                         goto cleanup;
1619                 LIST_INSERT_HEAD(&im6o->im6o_memberships, imm, i6mm_chain);
1620         }
1621
1622         if (!ifp->if_carp) {
1623                 cif = kmalloc(sizeof(*cif), M_CARP, M_WAITOK | M_ZERO);
1624
1625                 if ((error = ifpromisc(ifp, 1))) {
1626                         kfree(cif, M_CARP);
1627                         goto cleanup;
1628                 }
1629
1630                 TAILQ_INIT(&cif->vhif_vrs);
1631                 ifp->if_carp = cif;
1632         } else {
1633                 struct carp_softc *vr;
1634
1635                 cif = ifp->if_carp;
1636                 TAILQ_FOREACH(vr, &cif->vhif_vrs, sc_list) {
1637                         if (vr != sc && vr->sc_vhid == sc->sc_vhid) {
1638                                 error = EINVAL;
1639                                 goto cleanup;
1640                         }
1641                 }
1642         }
1643         sc->sc_ia6 = ia;
1644         sc->sc_carpdev = ifp;
1645
1646         { /* XXX prevent endless loop if already in queue */
1647         struct carp_softc *vr, *after = NULL;
1648         int myself = 0;
1649         cif = ifp->if_carp;
1650
1651         TAILQ_FOREACH(vr, &cif->vhif_vrs, sc_list) {
1652                 if (vr == sc)
1653                         myself = 1;
1654                 if (vr->sc_vhid < sc->sc_vhid)
1655                         after = vr;
1656         }
1657
1658         if (!myself) {
1659                 /* We're trying to keep things in order */
1660                 if (after == NULL)
1661                         TAILQ_INSERT_TAIL(&cif->vhif_vrs, sc, sc_list);
1662                 else
1663                         TAILQ_INSERT_AFTER(&cif->vhif_vrs, after, sc, sc_list);
1664         }
1665         }
1666
1667         sc->sc_naddrs6++;
1668         if (own)
1669                 sc->sc_advskew = 0;
1670         carp_sc_state(sc);
1671         carp_setrun(sc, 0);
1672
1673         return (0);
1674
1675 cleanup:
1676         /* clean up multicast memberships */
1677         if (!sc->sc_naddrs6) {
1678                 while (!LIST_EMPTY(&im6o->im6o_memberships)) {
1679                         imm = LIST_FIRST(&im6o->im6o_memberships);
1680                         LIST_REMOVE(imm, i6mm_chain);
1681                         in6_leavegroup(imm);
1682                 }
1683         }
1684         return (error);
1685 }
1686
1687 static int
1688 carp_del_addr6(struct carp_softc *sc, struct sockaddr_in6 *sin6)
1689 {
1690         int error = 0;
1691
1692         if (!--sc->sc_naddrs6) {
1693                 struct carp_if *cif = sc->sc_carpdev->if_carp;
1694                 struct ip6_moptions *im6o = &sc->sc_im6o;
1695
1696                 callout_stop(&sc->sc_ad_tmo);
1697                 sc->sc_vhid = -1;
1698                 while (!LIST_EMPTY(&im6o->im6o_memberships)) {
1699                         struct in6_multi_mship *imm =
1700                             LIST_FIRST(&im6o->im6o_memberships);
1701
1702                         LIST_REMOVE(imm, i6mm_chain);
1703                         in6_leavegroup(imm);
1704                 }
1705                 im6o->im6o_multicast_ifp = NULL;
1706                 TAILQ_REMOVE(&cif->vhif_vrs, sc, sc_list);
1707                 if (TAILQ_EMPTY(&cif->vhif_vrs)) {
1708                         sc->sc_carpdev->if_carp = NULL;
1709                         kfree(cif, M_IFADDR);
1710                 }
1711         }
1712         return (error);
1713 }
1714 #endif /* INET6 */
1715
1716 static int
1717 carp_ioctl(struct ifnet *ifp, u_long cmd, caddr_t addr, struct ucred *cr)
1718 {
1719         struct carp_softc *sc = ifp->if_softc, *vr;
1720         struct carpreq carpr;
1721         struct ifaddr *ifa;
1722         struct ifreq *ifr;
1723         struct ifaliasreq *ifra;
1724         struct ifdrv *ifd;
1725         char devname[IFNAMSIZ];
1726         int error = 0;
1727
1728         ifa = (struct ifaddr *)addr;
1729         ifra = (struct ifaliasreq *)addr;
1730         ifr = (struct ifreq *)addr;
1731         ifd = (struct ifdrv *)addr;
1732
1733         switch (cmd) {
1734         case SIOCSIFADDR:
1735                 switch (ifa->ifa_addr->sa_family) {
1736 #ifdef INET
1737                 case AF_INET:
1738                         ifp->if_flags |= IFF_UP | IFF_RUNNING;
1739                         break;
1740 #endif /* INET */
1741 #ifdef INET6
1742                 case AF_INET6:
1743                         ifp->if_flags |= IFF_UP | IFF_RUNNING;
1744                         error = carp_set_addr6(sc, satosin6(ifa->ifa_addr));
1745                         break;
1746 #endif /* INET6 */
1747                 default:
1748                         error = EAFNOSUPPORT;
1749                         break;
1750                 }
1751                 break;
1752
1753         case SIOCAIFADDR:
1754                 switch (ifa->ifa_addr->sa_family) {
1755 #ifdef INET
1756                 case AF_INET:
1757                         panic("SIOCAIFADDR should never be seen\n");
1758 #endif /* INET */
1759 #ifdef INET6
1760                 case AF_INET6:
1761                         ifp->if_flags |= IFF_UP | IFF_RUNNING;
1762                         error = carp_set_addr6(sc, satosin6(&ifra->ifra_addr));
1763                         break;
1764 #endif /* INET6 */
1765                 default:
1766                         error = EAFNOSUPPORT;
1767                         break;
1768                 }
1769                 break;
1770
1771         case SIOCDIFADDR:
1772                 switch (ifa->ifa_addr->sa_family) {
1773 #ifdef INET
1774                 case AF_INET:
1775                         panic("SIOCDIFADDR should never be seen\n");
1776 #endif /* INET */
1777 #ifdef INET6
1778                 case AF_INET6:
1779                         error = carp_del_addr6(sc, satosin6(&ifra->ifra_addr));
1780                         break;
1781 #endif /* INET6 */
1782                 default:
1783                         error = EAFNOSUPPORT;
1784                         break;
1785                 }
1786                 break;
1787
1788         case SIOCSIFFLAGS:
1789                 if (ifp->if_flags & IFF_UP) {
1790                         if ((ifp->if_flags & IFF_RUNNING) == 0) {
1791                                 ifp->if_flags |= IFF_RUNNING;
1792                                 carp_set_state(sc, INIT);
1793                                 carp_setrun(sc, 0);
1794                         }
1795                 } else if (ifp->if_flags & IFF_RUNNING) {
1796                         carp_stop(sc, 0);
1797                 }
1798                 break;
1799
1800         case SIOCSVH:
1801                 error = suser_cred(cr, NULL_CRED_OKAY);
1802                 if (error)
1803                         break;
1804                 error = copyin(ifr->ifr_data, &carpr, sizeof(carpr));
1805                 if (error)
1806                         break;
1807
1808                 error = 1;
1809                 if ((ifp->if_flags & IFF_RUNNING) &&
1810                     sc->sc_state != INIT && carpr.carpr_state != sc->sc_state) {
1811                         switch (carpr.carpr_state) {
1812                         case BACKUP:
1813                                 callout_stop(&sc->sc_ad_tmo);
1814                                 carp_set_state(sc, BACKUP);
1815                                 carp_setrun(sc, 0);
1816                                 carp_setroute(sc, RTM_DELETE);
1817                                 break;
1818
1819                         case MASTER:
1820                                 carp_master_down(sc);
1821                                 break;
1822
1823                         default:
1824                                 break;
1825                         }
1826                 }
1827                 if (carpr.carpr_vhid > 0) {
1828                         if (carpr.carpr_vhid > 255) {
1829                                 error = EINVAL;
1830                                 break;
1831                         }
1832                         if (sc->sc_carpdev) {
1833                                 struct carp_if *cif = sc->sc_carpdev->if_carp;
1834
1835                                 TAILQ_FOREACH(vr, &cif->vhif_vrs, sc_list) {
1836                                         if (vr != sc &&
1837                                             vr->sc_vhid == carpr.carpr_vhid)
1838                                                 return EEXIST;
1839                                 }
1840                         }
1841                         sc->sc_vhid = carpr.carpr_vhid;
1842                         IF_LLADDR(ifp)[0] = 0;
1843                         IF_LLADDR(ifp)[1] = 0;
1844                         IF_LLADDR(ifp)[2] = 0x5e;
1845                         IF_LLADDR(ifp)[3] = 0;
1846                         IF_LLADDR(ifp)[4] = 1;
1847                         IF_LLADDR(ifp)[5] = sc->sc_vhid;
1848                         error--;
1849                 }
1850                 if (carpr.carpr_advbase > 0 || carpr.carpr_advskew > 0) {
1851                         if (carpr.carpr_advskew >= 255) {
1852                                 error = EINVAL;
1853                                 break;
1854                         }
1855                         if (carpr.carpr_advbase > 255) {
1856                                 error = EINVAL;
1857                                 break;
1858                         }
1859                         sc->sc_advbase = carpr.carpr_advbase;
1860                         sc->sc_advskew = carpr.carpr_advskew;
1861                         error--;
1862                 }
1863                 bcopy(carpr.carpr_key, sc->sc_key, sizeof(sc->sc_key));
1864                 if (error > 0) {
1865                         error = EINVAL;
1866                 } else {
1867                         error = 0;
1868                         carp_setrun(sc, 0);
1869                 }
1870                 break;
1871
1872         case SIOCGVH:
1873                 bzero(&carpr, sizeof(carpr));
1874                 carpr.carpr_state = sc->sc_state;
1875                 carpr.carpr_vhid = sc->sc_vhid;
1876                 carpr.carpr_advbase = sc->sc_advbase;
1877                 carpr.carpr_advskew = sc->sc_advskew;
1878
1879                 error = suser_cred(cr, NULL_CRED_OKAY);
1880                 if (error == 0) {
1881                         bcopy(sc->sc_key, carpr.carpr_key,
1882                               sizeof(carpr.carpr_key));
1883                 }
1884
1885                 error = copyout(&carpr, ifr->ifr_data, sizeof(carpr));
1886                 break;
1887
1888         case SIOCGDRVSPEC:
1889                 switch (ifd->ifd_cmd) {
1890                 case CARPGDEVNAME:
1891                         if (ifd->ifd_len != sizeof(devname))
1892                                 error = EINVAL;
1893                         break;
1894
1895                 case CARPGVHADDR:
1896                         break;
1897
1898                 default:
1899                         error = EINVAL;
1900                         break;
1901                 }
1902                 if (error)
1903                         break;
1904
1905                 switch (ifd->ifd_cmd) {
1906                 case CARPGVHADDR:
1907                         error = carp_get_vhaddr(sc, ifd);
1908                         break;
1909
1910                 case CARPGDEVNAME:
1911                         bzero(devname, sizeof(devname));
1912                         if (sc->sc_carpdev != NULL) {
1913                                 strlcpy(devname, sc->sc_carpdev->if_xname,
1914                                         sizeof(devname));
1915                         }
1916                         error = copyout(devname, ifd->ifd_data,
1917                                         sizeof(devname));
1918                         break;
1919                 }
1920                 break;
1921
1922         default:
1923                 error = EINVAL;
1924                 break;
1925         }
1926         carp_hmac_prepare(sc);
1927         return error;
1928 }
1929
1930 /*
1931  * XXX: this is looutput. We should eventually use it from there.
1932  */
1933 static int
1934 carp_looutput(struct ifnet *ifp, struct mbuf *m, struct sockaddr *dst,
1935     struct rtentry *rt)
1936 {
1937         uint32_t af;
1938
1939         M_ASSERTPKTHDR(m); /* check if we have the packet header */
1940
1941         if (rt && rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
1942                 m_freem(m);
1943                 return (rt->rt_flags & RTF_BLACKHOLE ? 0 :
1944                         rt->rt_flags & RTF_HOST ? EHOSTUNREACH : ENETUNREACH);
1945         }
1946
1947         ifp->if_opackets++;
1948         ifp->if_obytes += m->m_pkthdr.len;
1949
1950         /* BPF writes need to be handled specially. */
1951         if (dst->sa_family == AF_UNSPEC) {
1952                 bcopy(dst->sa_data, &af, sizeof(af));
1953                 dst->sa_family = af;
1954         }
1955
1956 #if 1   /* XXX */
1957         switch (dst->sa_family) {
1958         case AF_INET:
1959         case AF_INET6:
1960         case AF_IPX:
1961         case AF_APPLETALK:
1962                 break;
1963
1964         default:
1965                 m_freem(m);
1966                 return (EAFNOSUPPORT);
1967         }
1968 #endif
1969         return (if_simloop(ifp, m, dst->sa_family, 0));
1970 }
1971
1972 /*
1973  * Start output on carp interface. This function should never be called.
1974  */
1975 static void
1976 carp_start(struct ifnet *ifp)
1977 {
1978 #ifdef DEBUG
1979         kprintf("%s: start called\n", ifp->if_xname);
1980 #endif
1981 }
1982
1983 int
1984 carp_output(struct ifnet *ifp, struct mbuf *m, struct sockaddr *sa,
1985     struct rtentry *rt)
1986 {
1987         struct m_tag *mtag;
1988         struct carp_softc *sc;
1989         struct ifnet *carp_ifp;
1990         struct ether_header *eh;
1991
1992         if (!sa)
1993                 return (0);
1994
1995         switch (sa->sa_family) {
1996 #ifdef INET
1997         case AF_INET:
1998                 break;
1999 #endif /* INET */
2000 #ifdef INET6
2001         case AF_INET6:
2002                 break;
2003 #endif /* INET6 */
2004         default:
2005                 return (0);
2006         }
2007
2008         mtag = m_tag_find(m, PACKET_TAG_CARP, NULL);
2009         if (mtag == NULL)
2010                 return (0);
2011
2012         bcopy(mtag + 1, &carp_ifp, sizeof(struct ifnet *));
2013         sc = carp_ifp->if_softc;
2014
2015         /* Set the source MAC address to Virtual Router MAC Address */
2016         switch (ifp->if_type) {
2017         case IFT_ETHER:
2018         case IFT_L2VLAN:
2019                 eh = mtod(m, struct ether_header *);
2020                 eh->ether_shost[0] = 0;
2021                 eh->ether_shost[1] = 0;
2022                 eh->ether_shost[2] = 0x5e;
2023                 eh->ether_shost[3] = 0;
2024                 eh->ether_shost[4] = 1;
2025                 eh->ether_shost[5] = sc->sc_vhid;
2026                 break;
2027
2028         default:
2029                 if_printf(ifp, "carp is not supported for this "
2030                           "interface type\n");
2031                 return (EOPNOTSUPP);
2032         }
2033         return (0);
2034 }
2035
2036 static void
2037 carp_set_state(struct carp_softc *sc, int state)
2038 {
2039         struct ifnet *cifp = &sc->sc_if;
2040
2041         if (sc->sc_state == state)
2042                 return;
2043         sc->sc_state = state;
2044
2045         switch (sc->sc_state) {
2046         case BACKUP:
2047                 cifp->if_link_state = LINK_STATE_DOWN;
2048                 break;
2049
2050         case MASTER:
2051                 cifp->if_link_state = LINK_STATE_UP;
2052                 break;
2053
2054         default:
2055                 cifp->if_link_state = LINK_STATE_UNKNOWN;
2056                 break;
2057         }
2058         rt_ifmsg(cifp);
2059 }
2060
2061 void
2062 carp_carpdev_state(void *v)
2063 {
2064         struct carp_if *cif = v;
2065         struct carp_softc *sc;
2066
2067         TAILQ_FOREACH(sc, &cif->vhif_vrs, sc_list)
2068                 carp_sc_state(sc);
2069 }
2070
2071 static void
2072 carp_sc_state(struct carp_softc *sc)
2073 {
2074         if (!(sc->sc_carpdev->if_flags & IFF_UP)) {
2075                 callout_stop(&sc->sc_ad_tmo);
2076                 callout_stop(&sc->sc_md_tmo);
2077                 callout_stop(&sc->sc_md6_tmo);
2078                 carp_set_state(sc, INIT);
2079                 carp_setrun(sc, 0);
2080                 if (!sc->sc_suppress) {
2081                         carp_suppress_preempt++;
2082                         if (carp_suppress_preempt == 1)
2083                                 carp_send_ad_all();
2084                 }
2085                 sc->sc_suppress = 1;
2086         } else {
2087                 carp_set_state(sc, INIT);
2088                 carp_setrun(sc, 0);
2089                 if (sc->sc_suppress)
2090                         carp_suppress_preempt--;
2091                 sc->sc_suppress = 0;
2092         }
2093 }
2094
2095 static void
2096 carp_stop(struct carp_softc *sc, int detach)
2097 {
2098         sc->sc_if.if_flags &= ~IFF_RUNNING;
2099
2100         callout_stop(&sc->sc_ad_tmo);
2101         callout_stop(&sc->sc_md_tmo);
2102         callout_stop(&sc->sc_md6_tmo);
2103
2104         if (!detach && sc->sc_state == MASTER)
2105                 carp_send_ad(sc);
2106
2107         if (sc->sc_suppress)
2108                 carp_suppress_preempt--;
2109         sc->sc_suppress = 0;
2110
2111         if (sc->sc_sendad_errors >= CARP_SENDAD_MAX_ERRORS)
2112                 carp_suppress_preempt--;
2113         sc->sc_sendad_errors = 0;
2114         sc->sc_sendad_success = 0;
2115
2116         carp_set_state(sc, INIT);
2117         carp_setrun(sc, 0);
2118 }
2119
2120 static void
2121 carp_reset(struct carp_softc *sc, int detach)
2122 {
2123         struct ifnet *cifp = &sc->sc_if;
2124
2125         carp_stop(sc, detach);
2126         if (!sc->sc_dead && (cifp->if_flags & IFF_UP))
2127                 cifp->if_flags |= IFF_RUNNING;
2128 }
2129
2130 static int
2131 carp_activate_vhaddr(struct carp_softc *sc, struct carp_vhaddr *vha,
2132                      struct ifnet *ifp, const struct in_ifaddr *ia_if, int own)
2133 {
2134         struct ip_moptions *imo = &sc->sc_imo;
2135         struct carp_if *cif;
2136         struct carp_softc *vr, *after = NULL;
2137         int onlist, error;
2138 #ifdef INVARIANTS
2139         int assert_onlist;
2140 #endif
2141
2142         KKASSERT(vha->vha_ia != NULL);
2143
2144         KASSERT(ia_if != NULL, ("NULL backing address\n"));
2145         KASSERT(vha->vha_iaback == NULL, ("%p is already activated\n", vha));
2146         KASSERT((vha->vha_flags & CARP_VHAF_OWNER) == 0,
2147                 ("inactive vhaddr %p is the address owner\n", vha));
2148
2149         KASSERT(sc->sc_carpdev == NULL || sc->sc_carpdev == ifp,
2150                 ("%s is already on %s\n", sc->sc_if.if_xname,
2151                  sc->sc_carpdev->if_xname));
2152
2153         KASSERT(imo->imo_multicast_ifp == NULL ||
2154                 imo->imo_multicast_ifp == ifp,
2155                 ("%s didn't leave mcast group on %s\n",
2156                  sc->sc_if.if_xname, imo->imo_multicast_ifp->if_xname));
2157
2158         if (imo->imo_num_memberships == 0) {
2159                 struct in_addr addr;
2160
2161                 addr.s_addr = htonl(INADDR_CARP_GROUP);
2162                 if ((imo->imo_membership[0] = in_addmulti(&addr, ifp)) == NULL)
2163                         return ENOBUFS;
2164                 imo->imo_num_memberships++;
2165                 imo->imo_multicast_ifp = ifp;
2166                 imo->imo_multicast_ttl = CARP_DFLTTL;
2167                 imo->imo_multicast_loop = 0;
2168         }
2169
2170         if (!ifp->if_carp) {
2171                 KASSERT(sc->sc_carpdev == NULL,
2172                         ("%s is already on %s\n", sc->sc_if.if_xname,
2173                          sc->sc_carpdev->if_xname));
2174
2175                 cif = kmalloc(sizeof(*cif), M_CARP, M_WAITOK | M_ZERO);
2176
2177                 error = ifpromisc(ifp, 1);
2178                 if (error) {
2179                         kfree(cif, M_CARP);
2180                         goto cleanup;
2181                 }
2182
2183                 TAILQ_INIT(&cif->vhif_vrs);
2184                 ifp->if_carp = cif;
2185         } else {
2186                 cif = ifp->if_carp;
2187                 TAILQ_FOREACH(vr, &cif->vhif_vrs, sc_list) {
2188                         if (vr != sc && vr->sc_vhid == sc->sc_vhid) {
2189                                 error = EINVAL;
2190                                 goto cleanup;
2191                         }
2192                 }
2193         }
2194
2195 #ifdef INVARIANTS
2196         if (sc->sc_carpdev != NULL)
2197                 assert_onlist = 1;
2198         else
2199                 assert_onlist = 0;
2200 #endif
2201         sc->sc_ia = ia_if;
2202         sc->sc_carpdev = ifp;
2203
2204         cif = ifp->if_carp;
2205         onlist = 0;
2206         TAILQ_FOREACH(vr, &cif->vhif_vrs, sc_list) {
2207                 if (vr == sc)
2208                         onlist = 1;
2209                 if (vr->sc_vhid < sc->sc_vhid)
2210                         after = vr;
2211         }
2212
2213 #ifdef INVARIANTS
2214         if (assert_onlist) {
2215                 KASSERT(onlist, ("%s is not on %s carp list\n",
2216                         sc->sc_if.if_xname, ifp->if_xname));
2217         } else {
2218                 KASSERT(!onlist, ("%s is already on %s carp list\n",
2219                         sc->sc_if.if_xname, ifp->if_xname));
2220         }
2221 #endif
2222
2223         if (!onlist) {
2224                 /* We're trying to keep things in order */
2225                 if (after == NULL)
2226                         TAILQ_INSERT_TAIL(&cif->vhif_vrs, sc, sc_list);
2227                 else
2228                         TAILQ_INSERT_AFTER(&cif->vhif_vrs, after, sc, sc_list);
2229         }
2230
2231         vha->vha_iaback = ia_if;
2232         sc->sc_naddrs++;
2233
2234         if (own) {
2235                 vha->vha_flags |= CARP_VHAF_OWNER;
2236
2237                 /* XXX save user configured advskew? */
2238                 sc->sc_advskew = 0;
2239         }
2240
2241         carp_hmac_prepare(sc);
2242         carp_set_state(sc, INIT);
2243         carp_setrun(sc, 0);
2244         return 0;
2245 cleanup:
2246         carp_multicast_cleanup(sc);
2247         return error;
2248 }
2249
2250 static void
2251 carp_deactivate_vhaddr(struct carp_softc *sc, struct carp_vhaddr *vha)
2252 {
2253         KKASSERT(vha->vha_ia != NULL);
2254
2255         carp_hmac_prepare(sc);
2256
2257         if (vha->vha_iaback == NULL) {
2258                 KASSERT((vha->vha_flags & CARP_VHAF_OWNER) == 0,
2259                         ("inactive vhaddr %p is the address owner\n", vha));
2260                 return;
2261         }
2262
2263         vha->vha_flags &= ~CARP_VHAF_OWNER;
2264
2265         KKASSERT(sc->sc_naddrs > 0);
2266         vha->vha_iaback = NULL;
2267         sc->sc_naddrs--;
2268         if (!sc->sc_naddrs) {
2269                 if (sc->sc_naddrs6) {
2270                         carp_multicast_cleanup(sc);
2271                         sc->sc_ia = NULL;
2272                 } else {
2273                         carp_detach(sc, 0);
2274                 }
2275         }
2276 }
2277
2278 static void
2279 carp_link_addrs(struct carp_softc *sc, struct ifnet *ifp, struct ifaddr *ifa_if)
2280 {
2281         struct carp_vhaddr *vha;
2282         struct in_ifaddr *ia_if;
2283
2284         KKASSERT(ifa_if->ifa_addr->sa_family == AF_INET);
2285         ia_if = ifatoia(ifa_if);
2286
2287         if ((ia_if->ia_flags & IFA_ROUTE) == 0)
2288                 return;
2289
2290         /*
2291          * Test each inactive vhaddr against the newly added address.
2292          * If the newly added address could be the backing address,
2293          * then activate the matching vhaddr.
2294          */
2295         TAILQ_FOREACH(vha, &sc->sc_vha_list, vha_link) {
2296                 const struct in_ifaddr *ia;
2297                 u_long iaddr;
2298                 int own;
2299
2300                 if (vha->vha_iaback != NULL)
2301                         continue;
2302
2303                 ia = vha->vha_ia;
2304                 iaddr = ntohl(ia->ia_addr.sin_addr.s_addr);
2305
2306                 if ((iaddr & ia_if->ia_subnetmask) != ia_if->ia_subnet)
2307                         continue;
2308
2309                 own = 0;
2310                 if (ia->ia_addr.sin_addr.s_addr ==
2311                     ia_if->ia_addr.sin_addr.s_addr)
2312                         own = 1;
2313
2314                 carp_activate_vhaddr(sc, vha, ifp, ia_if, own);
2315         }
2316 }
2317
2318 static void
2319 carp_unlink_addrs(struct carp_softc *sc, struct ifnet *ifp,
2320                   struct ifaddr *ifa_if)
2321 {
2322         struct carp_vhaddr *vha;
2323         struct in_ifaddr *ia_if;
2324
2325         KKASSERT(ifa_if->ifa_addr->sa_family == AF_INET);
2326         ia_if = ifatoia(ifa_if);
2327
2328         /*
2329          * Ad src address is deleted; set it to NULL.
2330          * Following loop will try pick up a new ad src address
2331          * if one of the vhaddr could retain its backing address.
2332          */
2333         if (sc->sc_ia == ia_if)
2334                 sc->sc_ia = NULL;
2335
2336         /*
2337          * Test each active vhaddr against the deleted address.
2338          * If the deleted address is vhaddr address's backing
2339          * address, then deactivate the vhaddr.
2340          */
2341         TAILQ_FOREACH(vha, &sc->sc_vha_list, vha_link) {
2342                 if (vha->vha_iaback == NULL)
2343                         continue;
2344
2345                 if (vha->vha_iaback == ia_if)
2346                         carp_deactivate_vhaddr(sc, vha);
2347                 else if (sc->sc_ia == NULL)
2348                         sc->sc_ia = vha->vha_iaback;
2349         }
2350 }
2351
2352 static void
2353 carp_update_addrs(struct carp_softc *sc)
2354 {
2355         struct carp_vhaddr *vha;
2356
2357         KKASSERT(sc->sc_carpdev == NULL);
2358
2359         TAILQ_FOREACH(vha, &sc->sc_vha_list, vha_link)
2360                 carp_config_vhaddr(sc, vha);
2361 }
2362
2363 static void
2364 carp_ifaddr(void *arg __unused, struct ifnet *ifp,
2365             enum ifaddr_event event, struct ifaddr *ifa)
2366 {
2367         struct carp_softc *sc;
2368
2369         if (ifa->ifa_addr->sa_family != AF_INET)
2370                 return;
2371
2372         if (ifp->if_type == IFT_CARP) {
2373                 /*
2374                  * Address is changed on carp(4) interface
2375                  */
2376                 switch (event) {
2377                 case IFADDR_EVENT_ADD:
2378                         carp_add_addr(ifp->if_softc, ifa);
2379                         break;
2380
2381                 case IFADDR_EVENT_CHANGE:
2382                         carp_config_addr(ifp->if_softc, ifa);
2383                         break;
2384
2385                 case IFADDR_EVENT_DELETE:
2386                         carp_del_addr(ifp->if_softc, ifa);
2387                         break;
2388                 }
2389                 return;
2390         }
2391
2392         /*
2393          * Address is changed on non-carp(4) interface
2394          */
2395         if ((ifp->if_flags & IFF_MULTICAST) == 0)
2396                 return;
2397
2398         crit_enter();
2399         LIST_FOREACH(sc, &carpif_list, sc_next) {
2400                 if (sc->sc_carpdev != NULL && sc->sc_carpdev != ifp) {
2401                         /* Not the parent iface; skip */
2402                         continue;
2403                 }
2404
2405                 switch (event) {
2406                 case IFADDR_EVENT_ADD:
2407                         carp_link_addrs(sc, ifp, ifa);
2408                         break;
2409
2410                 case IFADDR_EVENT_DELETE:
2411                         if (sc->sc_carpdev != NULL) {
2412                                 carp_unlink_addrs(sc, ifp, ifa);
2413                                 if (sc->sc_carpdev == NULL)
2414                                         carp_update_addrs(sc);
2415                         } else {
2416                                 /*
2417                                  * The carp(4) interface didn't have a
2418                                  * parent iface, so it is not possible
2419                                  * that it will contain any address to
2420                                  * be unlinked.
2421                                  */
2422                         }
2423                         break;
2424
2425                 case IFADDR_EVENT_CHANGE:
2426                         if (sc->sc_carpdev == NULL) {
2427                                 /*
2428                                  * The carp(4) interface didn't have a
2429                                  * parent iface, so it is not possible
2430                                  * that it will contain any address to
2431                                  * be updated.
2432                                  */
2433                                 carp_link_addrs(sc, ifp, ifa);
2434                         } else {
2435                                 /*
2436                                  * First try breaking tie with the old
2437                                  * address.  Then see whether we could
2438                                  * link certain vhaddr to the new address.
2439                                  * If that fails, i.e. carpdev is NULL,
2440                                  * we try a global update.
2441                                  *
2442                                  * NOTE: The above order is critical.
2443                                  */
2444                                 carp_unlink_addrs(sc, ifp, ifa);
2445                                 carp_link_addrs(sc, ifp, ifa);
2446                                 if (sc->sc_carpdev == NULL)
2447                                         carp_update_addrs(sc);
2448                         }
2449                         break;
2450                 }
2451         }
2452         crit_exit();
2453 }
2454
2455 static int
2456 carp_modevent(module_t mod, int type, void *data)
2457 {
2458         switch (type) {
2459         case MOD_LOAD:
2460                 LIST_INIT(&carpif_list);
2461                 carp_ifdetach_event =
2462                 EVENTHANDLER_REGISTER(ifnet_detach_event, carp_ifdetach, NULL,
2463                                       EVENTHANDLER_PRI_ANY);
2464                 carp_ifaddr_event =
2465                 EVENTHANDLER_REGISTER(ifaddr_event, carp_ifaddr, NULL,
2466                                       EVENTHANDLER_PRI_ANY);
2467                 if_clone_attach(&carp_cloner);
2468                 break;
2469
2470         case MOD_UNLOAD:
2471                 EVENTHANDLER_DEREGISTER(ifnet_detach_event,
2472                                         carp_ifdetach_event);
2473                 EVENTHANDLER_DEREGISTER(ifaddr_event,
2474                                         carp_ifaddr_event);
2475                 if_clone_detach(&carp_cloner);
2476                 break;
2477
2478         default:
2479                 return (EINVAL);
2480         }
2481         return (0);
2482 }
2483
2484 static moduledata_t carp_mod = {
2485         "carp",
2486         carp_modevent,
2487         0
2488 };
2489 DECLARE_MODULE(carp, carp_mod, SI_SUB_PSEUDO, SI_ORDER_ANY);