source: rtems-libbsd/freebsd/sys/netinet/ip_carp.c @ 2017a6d

55-freebsd-126-freebsd-12freebsd-9.3
Last change on this file since 2017a6d was 2017a6d, checked in by Sebastian Huber <sebastian.huber@…>, on 04/07/16 at 07:48:12

Directly use <sys/time.h> provided by Newlib

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