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