]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/netinet/ip_carp.c
vtnet: don't leak pfil(9) data on detach
[FreeBSD/FreeBSD.git] / sys / netinet / ip_carp.c
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2002 Michael Shalayeff.
5  * Copyright (c) 2003 Ryan McBride.
6  * Copyright (c) 2011 Gleb Smirnoff <glebius@FreeBSD.org>
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21  * IN NO EVENT SHALL THE AUTHOR OR HIS RELATIVES BE LIABLE FOR ANY DIRECT,
22  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
24  * SERVICES; LOSS OF MIND, USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
26  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
27  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
28  * THE POSSIBILITY OF SUCH DAMAGE.
29  */
30
31 #include <sys/cdefs.h>
32 #include "opt_bpf.h"
33 #include "opt_inet.h"
34 #include "opt_inet6.h"
35
36 #include <sys/param.h>
37 #include <sys/systm.h>
38 #include <sys/devctl.h>
39 #include <sys/jail.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/priv.h>
46 #include <sys/proc.h>
47 #include <sys/protosw.h>
48 #include <sys/socket.h>
49 #include <sys/sockio.h>
50 #include <sys/sysctl.h>
51 #include <sys/syslog.h>
52 #include <sys/taskqueue.h>
53 #include <sys/counter.h>
54
55 #include <net/ethernet.h>
56 #include <net/if.h>
57 #include <net/if_var.h>
58 #include <net/if_dl.h>
59 #include <net/if_llatbl.h>
60 #include <net/if_types.h>
61 #include <net/route.h>
62 #include <net/vnet.h>
63
64 #if defined(INET) || defined(INET6)
65 #include <netinet/in.h>
66 #include <netinet/in_var.h>
67 #include <netinet/ip_carp.h>
68 #include <netinet/ip.h>
69 #include <machine/in_cksum.h>
70 #endif
71 #ifdef INET
72 #include <netinet/ip_var.h>
73 #include <netinet/if_ether.h>
74 #endif
75
76 #ifdef INET6
77 #include <netinet/icmp6.h>
78 #include <netinet/ip6.h>
79 #include <netinet6/in6_var.h>
80 #include <netinet6/ip6_var.h>
81 #include <netinet6/scope6_var.h>
82 #include <netinet6/nd6.h>
83 #endif
84
85 #include <crypto/sha1.h>
86
87 static MALLOC_DEFINE(M_CARP, "CARP", "CARP addresses");
88
89 struct carp_softc {
90         struct ifnet            *sc_carpdev;    /* Pointer to parent ifnet. */
91         struct ifaddr           **sc_ifas;      /* Our ifaddrs. */
92         struct sockaddr_dl      sc_addr;        /* Our link level address. */
93         struct callout          sc_ad_tmo;      /* Advertising timeout. */
94 #ifdef INET
95         struct callout          sc_md_tmo;      /* Master down timeout. */
96 #endif
97 #ifdef INET6
98         struct callout          sc_md6_tmo;     /* XXX: Master down timeout. */
99 #endif
100         struct mtx              sc_mtx;
101
102         int                     sc_vhid;
103         int                     sc_advskew;
104         int                     sc_advbase;
105
106         int                     sc_naddrs;
107         int                     sc_naddrs6;
108         int                     sc_ifasiz;
109         enum { INIT = 0, BACKUP, MASTER }       sc_state;
110         int                     sc_suppress;
111         int                     sc_sendad_errors;
112 #define CARP_SENDAD_MAX_ERRORS  3
113         int                     sc_sendad_success;
114 #define CARP_SENDAD_MIN_SUCCESS 3
115
116         int                     sc_init_counter;
117         uint64_t                sc_counter;
118
119         /* authentication */
120 #define CARP_HMAC_PAD   64
121         unsigned char sc_key[CARP_KEY_LEN];
122         unsigned char sc_pad[CARP_HMAC_PAD];
123         SHA1_CTX sc_sha1;
124
125         TAILQ_ENTRY(carp_softc) sc_list;        /* On the carp_if list. */
126         LIST_ENTRY(carp_softc)  sc_next;        /* On the global list. */
127 };
128
129 struct carp_if {
130 #ifdef INET
131         int     cif_naddrs;
132 #endif
133 #ifdef INET6
134         int     cif_naddrs6;
135 #endif
136         TAILQ_HEAD(, carp_softc) cif_vrs;
137 #ifdef INET
138         struct ip_moptions       cif_imo;
139 #endif
140 #ifdef INET6
141         struct ip6_moptions      cif_im6o;
142 #endif
143         struct ifnet    *cif_ifp;
144         struct mtx      cif_mtx;
145         uint32_t        cif_flags;
146 #define CIF_PROMISC     0x00000001
147 };
148
149 #define CARP_INET       0
150 #define CARP_INET6      1
151 static int proto_reg[] = {-1, -1};
152
153 /*
154  * Brief design of carp(4).
155  *
156  * Any carp-capable ifnet may have a list of carp softcs hanging off
157  * its ifp->if_carp pointer. Each softc represents one unique virtual
158  * host id, or vhid. The softc has a back pointer to the ifnet. All
159  * softcs are joined in a global list, which has quite limited use.
160  *
161  * Any interface address that takes part in CARP negotiation has a
162  * pointer to the softc of its vhid, ifa->ifa_carp. That could be either
163  * AF_INET or AF_INET6 address.
164  *
165  * Although, one can get the softc's backpointer to ifnet and traverse
166  * through its ifp->if_addrhead queue to find all interface addresses
167  * involved in CARP, we keep a growable array of ifaddr pointers. This
168  * allows us to avoid grabbing the IF_ADDR_LOCK() in many traversals that
169  * do calls into the network stack, thus avoiding LORs.
170  *
171  * Locking:
172  *
173  * Each softc has a lock sc_mtx. It is used to synchronise carp_input_c(),
174  * callout-driven events and ioctl()s.
175  *
176  * To traverse the list of softcs on an ifnet we use CIF_LOCK() or carp_sx.
177  * To traverse the global list we use the mutex carp_mtx.
178  *
179  * Known issues with locking:
180  *
181  * - Sending ad, we put the pointer to the softc in an mtag, and no reference
182  *   counting is done on the softc.
183  * - On module unload we may race (?) with packet processing thread
184  *   dereferencing our function pointers.
185  */
186
187 /* Accept incoming CARP packets. */
188 VNET_DEFINE_STATIC(int, carp_allow) = 1;
189 #define V_carp_allow    VNET(carp_allow)
190
191 /* Set DSCP in outgoing CARP packets. */
192 VNET_DEFINE_STATIC(int, carp_dscp) = 56;
193 #define V_carp_dscp     VNET(carp_dscp)
194
195 /* Preempt slower nodes. */
196 VNET_DEFINE_STATIC(int, carp_preempt) = 0;
197 #define V_carp_preempt  VNET(carp_preempt)
198
199 /* Log level. */
200 VNET_DEFINE_STATIC(int, carp_log) = 1;
201 #define V_carp_log      VNET(carp_log)
202
203 /* Global advskew demotion. */
204 VNET_DEFINE_STATIC(int, carp_demotion) = 0;
205 #define V_carp_demotion VNET(carp_demotion)
206
207 /* Send error demotion factor. */
208 VNET_DEFINE_STATIC(int, carp_senderr_adj) = CARP_MAXSKEW;
209 #define V_carp_senderr_adj      VNET(carp_senderr_adj)
210
211 /* Iface down demotion factor. */
212 VNET_DEFINE_STATIC(int, carp_ifdown_adj) = CARP_MAXSKEW;
213 #define V_carp_ifdown_adj       VNET(carp_ifdown_adj)
214
215 static int carp_allow_sysctl(SYSCTL_HANDLER_ARGS);
216 static int carp_dscp_sysctl(SYSCTL_HANDLER_ARGS);
217 static int carp_demote_adj_sysctl(SYSCTL_HANDLER_ARGS);
218
219 SYSCTL_NODE(_net_inet, IPPROTO_CARP, carp, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
220     "CARP");
221 SYSCTL_PROC(_net_inet_carp, OID_AUTO, allow,
222     CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RWTUN | CTLFLAG_MPSAFE,
223     &VNET_NAME(carp_allow), 0, carp_allow_sysctl, "I",
224     "Accept incoming CARP packets");
225 SYSCTL_PROC(_net_inet_carp, OID_AUTO, dscp,
226     CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
227     0, 0, carp_dscp_sysctl, "I",
228     "DSCP value for carp packets");
229 SYSCTL_INT(_net_inet_carp, OID_AUTO, preempt, CTLFLAG_VNET | CTLFLAG_RW,
230     &VNET_NAME(carp_preempt), 0, "High-priority backup preemption mode");
231 SYSCTL_INT(_net_inet_carp, OID_AUTO, log, CTLFLAG_VNET | CTLFLAG_RW,
232     &VNET_NAME(carp_log), 0, "CARP log level");
233 SYSCTL_PROC(_net_inet_carp, OID_AUTO, demotion,
234     CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
235     0, 0, carp_demote_adj_sysctl, "I",
236     "Adjust demotion factor (skew of advskew)");
237 SYSCTL_INT(_net_inet_carp, OID_AUTO, senderr_demotion_factor,
238     CTLFLAG_VNET | CTLFLAG_RW,
239     &VNET_NAME(carp_senderr_adj), 0, "Send error demotion factor adjustment");
240 SYSCTL_INT(_net_inet_carp, OID_AUTO, ifdown_demotion_factor,
241     CTLFLAG_VNET | CTLFLAG_RW,
242     &VNET_NAME(carp_ifdown_adj), 0,
243     "Interface down demotion factor adjustment");
244
245 VNET_PCPUSTAT_DEFINE(struct carpstats, carpstats);
246 VNET_PCPUSTAT_SYSINIT(carpstats);
247 VNET_PCPUSTAT_SYSUNINIT(carpstats);
248
249 #define CARPSTATS_ADD(name, val)        \
250     counter_u64_add(VNET(carpstats)[offsetof(struct carpstats, name) / \
251         sizeof(uint64_t)], (val))
252 #define CARPSTATS_INC(name)             CARPSTATS_ADD(name, 1)
253
254 SYSCTL_VNET_PCPUSTAT(_net_inet_carp, OID_AUTO, stats, struct carpstats,
255     carpstats, "CARP statistics (struct carpstats, netinet/ip_carp.h)");
256
257 #define CARP_LOCK_INIT(sc)      mtx_init(&(sc)->sc_mtx, "carp_softc",   \
258         NULL, MTX_DEF)
259 #define CARP_LOCK_DESTROY(sc)   mtx_destroy(&(sc)->sc_mtx)
260 #define CARP_LOCK_ASSERT(sc)    mtx_assert(&(sc)->sc_mtx, MA_OWNED)
261 #define CARP_LOCK(sc)           mtx_lock(&(sc)->sc_mtx)
262 #define CARP_UNLOCK(sc)         mtx_unlock(&(sc)->sc_mtx)
263 #define CIF_LOCK_INIT(cif)      mtx_init(&(cif)->cif_mtx, "carp_if",   \
264         NULL, MTX_DEF)
265 #define CIF_LOCK_DESTROY(cif)   mtx_destroy(&(cif)->cif_mtx)
266 #define CIF_LOCK_ASSERT(cif)    mtx_assert(&(cif)->cif_mtx, MA_OWNED)
267 #define CIF_LOCK(cif)           mtx_lock(&(cif)->cif_mtx)
268 #define CIF_UNLOCK(cif)         mtx_unlock(&(cif)->cif_mtx)
269 #define CIF_FREE(cif)   do {                            \
270                 CIF_LOCK(cif);                          \
271                 if (TAILQ_EMPTY(&(cif)->cif_vrs))       \
272                         carp_free_if(cif);              \
273                 else                                    \
274                         CIF_UNLOCK(cif);                \
275 } while (0)
276
277 #define CARP_LOG(...)   do {                            \
278         if (V_carp_log > 0)                             \
279                 log(LOG_INFO, "carp: " __VA_ARGS__);    \
280 } while (0)
281
282 #define CARP_DEBUG(...) do {                            \
283         if (V_carp_log > 1)                             \
284                 log(LOG_DEBUG, __VA_ARGS__);            \
285 } while (0)
286
287 #define IFNET_FOREACH_IFA(ifp, ifa)                                     \
288         CK_STAILQ_FOREACH((ifa), &(ifp)->if_addrhead, ifa_link) \
289                 if ((ifa)->ifa_carp != NULL)
290
291 #define CARP_FOREACH_IFA(sc, ifa)                                       \
292         CARP_LOCK_ASSERT(sc);                                           \
293         for (int _i = 0;                                                \
294                 _i < (sc)->sc_naddrs + (sc)->sc_naddrs6 &&              \
295                 ((ifa) = sc->sc_ifas[_i]) != NULL;                      \
296                 ++_i)
297
298 #define IFNET_FOREACH_CARP(ifp, sc)                                     \
299         KASSERT(mtx_owned(&ifp->if_carp->cif_mtx) ||                    \
300             sx_xlocked(&carp_sx), ("cif_vrs not locked"));              \
301         TAILQ_FOREACH((sc), &(ifp)->if_carp->cif_vrs, sc_list)
302
303 #define DEMOTE_ADVSKEW(sc)                                      \
304     (((sc)->sc_advskew + V_carp_demotion > CARP_MAXSKEW) ?      \
305     CARP_MAXSKEW :                                              \
306         (((sc)->sc_advskew + V_carp_demotion < 0) ?             \
307         0 : ((sc)->sc_advskew + V_carp_demotion)))
308
309 static void     carp_input_c(struct mbuf *, struct carp_header *, sa_family_t);
310 static struct carp_softc
311                 *carp_alloc(struct ifnet *);
312 static void     carp_destroy(struct carp_softc *);
313 static struct carp_if
314                 *carp_alloc_if(struct ifnet *);
315 static void     carp_free_if(struct carp_if *);
316 static void     carp_set_state(struct carp_softc *, int, const char* reason);
317 static void     carp_sc_state(struct carp_softc *);
318 static void     carp_setrun(struct carp_softc *, sa_family_t);
319 static void     carp_master_down(void *);
320 static void     carp_master_down_locked(struct carp_softc *,
321                     const char* reason);
322 static void     carp_send_ad(void *);
323 static void     carp_send_ad_locked(struct carp_softc *);
324 static void     carp_addroute(struct carp_softc *);
325 static void     carp_ifa_addroute(struct ifaddr *);
326 static void     carp_delroute(struct carp_softc *);
327 static void     carp_ifa_delroute(struct ifaddr *);
328 static void     carp_send_ad_all(void *, int);
329 static void     carp_demote_adj(int, char *);
330
331 static LIST_HEAD(, carp_softc) carp_list;
332 static struct mtx carp_mtx;
333 static struct sx carp_sx;
334 static struct task carp_sendall_task =
335     TASK_INITIALIZER(0, carp_send_ad_all, NULL);
336
337 static void
338 carp_hmac_prepare(struct carp_softc *sc)
339 {
340         uint8_t version = CARP_VERSION, type = CARP_ADVERTISEMENT;
341         uint8_t vhid = sc->sc_vhid & 0xff;
342         struct ifaddr *ifa;
343         int i, found;
344 #ifdef INET
345         struct in_addr last, cur, in;
346 #endif
347 #ifdef INET6
348         struct in6_addr last6, cur6, in6;
349 #endif
350
351         CARP_LOCK_ASSERT(sc);
352
353         /* Compute ipad from key. */
354         bzero(sc->sc_pad, sizeof(sc->sc_pad));
355         bcopy(sc->sc_key, sc->sc_pad, sizeof(sc->sc_key));
356         for (i = 0; i < sizeof(sc->sc_pad); i++)
357                 sc->sc_pad[i] ^= 0x36;
358
359         /* Precompute first part of inner hash. */
360         SHA1Init(&sc->sc_sha1);
361         SHA1Update(&sc->sc_sha1, sc->sc_pad, sizeof(sc->sc_pad));
362         SHA1Update(&sc->sc_sha1, (void *)&version, sizeof(version));
363         SHA1Update(&sc->sc_sha1, (void *)&type, sizeof(type));
364         SHA1Update(&sc->sc_sha1, (void *)&vhid, sizeof(vhid));
365 #ifdef INET
366         cur.s_addr = 0;
367         do {
368                 found = 0;
369                 last = cur;
370                 cur.s_addr = 0xffffffff;
371                 CARP_FOREACH_IFA(sc, ifa) {
372                         in.s_addr = ifatoia(ifa)->ia_addr.sin_addr.s_addr;
373                         if (ifa->ifa_addr->sa_family == AF_INET &&
374                             ntohl(in.s_addr) > ntohl(last.s_addr) &&
375                             ntohl(in.s_addr) < ntohl(cur.s_addr)) {
376                                 cur.s_addr = in.s_addr;
377                                 found++;
378                         }
379                 }
380                 if (found)
381                         SHA1Update(&sc->sc_sha1, (void *)&cur, sizeof(cur));
382         } while (found);
383 #endif /* INET */
384 #ifdef INET6
385         memset(&cur6, 0, sizeof(cur6));
386         do {
387                 found = 0;
388                 last6 = cur6;
389                 memset(&cur6, 0xff, sizeof(cur6));
390                 CARP_FOREACH_IFA(sc, ifa) {
391                         in6 = ifatoia6(ifa)->ia_addr.sin6_addr;
392                         if (IN6_IS_SCOPE_EMBED(&in6))
393                                 in6.s6_addr16[1] = 0;
394                         if (ifa->ifa_addr->sa_family == AF_INET6 &&
395                             memcmp(&in6, &last6, sizeof(in6)) > 0 &&
396                             memcmp(&in6, &cur6, sizeof(in6)) < 0) {
397                                 cur6 = in6;
398                                 found++;
399                         }
400                 }
401                 if (found)
402                         SHA1Update(&sc->sc_sha1, (void *)&cur6, sizeof(cur6));
403         } while (found);
404 #endif /* INET6 */
405
406         /* convert ipad to opad */
407         for (i = 0; i < sizeof(sc->sc_pad); i++)
408                 sc->sc_pad[i] ^= 0x36 ^ 0x5c;
409 }
410
411 static void
412 carp_hmac_generate(struct carp_softc *sc, uint32_t counter[2],
413     unsigned char md[20])
414 {
415         SHA1_CTX sha1ctx;
416
417         CARP_LOCK_ASSERT(sc);
418
419         /* fetch first half of inner hash */
420         bcopy(&sc->sc_sha1, &sha1ctx, sizeof(sha1ctx));
421
422         SHA1Update(&sha1ctx, (void *)counter, sizeof(sc->sc_counter));
423         SHA1Final(md, &sha1ctx);
424
425         /* outer hash */
426         SHA1Init(&sha1ctx);
427         SHA1Update(&sha1ctx, sc->sc_pad, sizeof(sc->sc_pad));
428         SHA1Update(&sha1ctx, md, 20);
429         SHA1Final(md, &sha1ctx);
430 }
431
432 static int
433 carp_hmac_verify(struct carp_softc *sc, uint32_t counter[2],
434     unsigned char md[20])
435 {
436         unsigned char md2[20];
437
438         CARP_LOCK_ASSERT(sc);
439
440         carp_hmac_generate(sc, counter, md2);
441
442         return (bcmp(md, md2, sizeof(md2)));
443 }
444
445 /*
446  * process input packet.
447  * we have rearranged checks order compared to the rfc,
448  * but it seems more efficient this way or not possible otherwise.
449  */
450 #ifdef INET
451 int
452 carp_input(struct mbuf **mp, int *offp, int proto)
453 {
454         struct mbuf *m = *mp;
455         struct ip *ip = mtod(m, struct ip *);
456         struct carp_header *ch;
457         int iplen, len;
458
459         iplen = *offp;
460         *mp = NULL;
461
462         CARPSTATS_INC(carps_ipackets);
463
464         if (!V_carp_allow) {
465                 m_freem(m);
466                 return (IPPROTO_DONE);
467         }
468
469         /* verify that the IP TTL is 255.  */
470         if (ip->ip_ttl != CARP_DFLTTL) {
471                 CARPSTATS_INC(carps_badttl);
472                 CARP_DEBUG("%s: received ttl %d != 255 on %s\n", __func__,
473                     ip->ip_ttl,
474                     m->m_pkthdr.rcvif->if_xname);
475                 m_freem(m);
476                 return (IPPROTO_DONE);
477         }
478
479         iplen = ip->ip_hl << 2;
480
481         if (m->m_pkthdr.len < iplen + sizeof(*ch)) {
482                 CARPSTATS_INC(carps_badlen);
483                 CARP_DEBUG("%s: received len %zd < sizeof(struct carp_header) "
484                     "on %s\n", __func__, m->m_len - sizeof(struct ip),
485                     m->m_pkthdr.rcvif->if_xname);
486                 m_freem(m);
487                 return (IPPROTO_DONE);
488         }
489
490         if (iplen + sizeof(*ch) < m->m_len) {
491                 if ((m = m_pullup(m, iplen + sizeof(*ch))) == NULL) {
492                         CARPSTATS_INC(carps_hdrops);
493                         CARP_DEBUG("%s: pullup failed\n", __func__);
494                         return (IPPROTO_DONE);
495                 }
496                 ip = mtod(m, struct ip *);
497         }
498         ch = (struct carp_header *)((char *)ip + iplen);
499
500         /*
501          * verify that the received packet length is
502          * equal to the CARP header
503          */
504         len = iplen + sizeof(*ch);
505         if (len > m->m_pkthdr.len) {
506                 CARPSTATS_INC(carps_badlen);
507                 CARP_DEBUG("%s: packet too short %d on %s\n", __func__,
508                     m->m_pkthdr.len,
509                     m->m_pkthdr.rcvif->if_xname);
510                 m_freem(m);
511                 return (IPPROTO_DONE);
512         }
513
514         if ((m = m_pullup(m, len)) == NULL) {
515                 CARPSTATS_INC(carps_hdrops);
516                 return (IPPROTO_DONE);
517         }
518         ip = mtod(m, struct ip *);
519         ch = (struct carp_header *)((char *)ip + iplen);
520
521         /* verify the CARP checksum */
522         m->m_data += iplen;
523         if (in_cksum(m, len - iplen)) {
524                 CARPSTATS_INC(carps_badsum);
525                 CARP_DEBUG("%s: checksum failed on %s\n", __func__,
526                     m->m_pkthdr.rcvif->if_xname);
527                 m_freem(m);
528                 return (IPPROTO_DONE);
529         }
530         m->m_data -= iplen;
531
532         carp_input_c(m, ch, AF_INET);
533         return (IPPROTO_DONE);
534 }
535 #endif
536
537 #ifdef INET6
538 int
539 carp6_input(struct mbuf **mp, int *offp, int proto)
540 {
541         struct mbuf *m = *mp;
542         struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
543         struct carp_header *ch;
544         u_int len;
545
546         CARPSTATS_INC(carps_ipackets6);
547
548         if (!V_carp_allow) {
549                 m_freem(m);
550                 return (IPPROTO_DONE);
551         }
552
553         /* check if received on a valid carp interface */
554         if (m->m_pkthdr.rcvif->if_carp == NULL) {
555                 CARPSTATS_INC(carps_badif);
556                 CARP_DEBUG("%s: packet received on non-carp interface: %s\n",
557                     __func__, m->m_pkthdr.rcvif->if_xname);
558                 m_freem(m);
559                 return (IPPROTO_DONE);
560         }
561
562         /* verify that the IP TTL is 255 */
563         if (ip6->ip6_hlim != CARP_DFLTTL) {
564                 CARPSTATS_INC(carps_badttl);
565                 CARP_DEBUG("%s: received ttl %d != 255 on %s\n", __func__,
566                     ip6->ip6_hlim, m->m_pkthdr.rcvif->if_xname);
567                 m_freem(m);
568                 return (IPPROTO_DONE);
569         }
570
571         /* verify that we have a complete carp packet */
572         if (m->m_len < *offp + sizeof(*ch)) {
573                 len = m->m_len;
574                 m = m_pullup(m, *offp + sizeof(*ch));
575                 if (m == NULL) {
576                         CARPSTATS_INC(carps_badlen);
577                         CARP_DEBUG("%s: packet size %u too small\n", __func__, len);
578                         return (IPPROTO_DONE);
579                 }
580         }
581         ch = (struct carp_header *)(mtod(m, char *) + *offp);
582
583         /* verify the CARP checksum */
584         m->m_data += *offp;
585         if (in_cksum(m, sizeof(*ch))) {
586                 CARPSTATS_INC(carps_badsum);
587                 CARP_DEBUG("%s: checksum failed, on %s\n", __func__,
588                     m->m_pkthdr.rcvif->if_xname);
589                 m_freem(m);
590                 return (IPPROTO_DONE);
591         }
592         m->m_data -= *offp;
593
594         carp_input_c(m, ch, AF_INET6);
595         return (IPPROTO_DONE);
596 }
597 #endif /* INET6 */
598
599 /*
600  * This routine should not be necessary at all, but some switches
601  * (VMWare ESX vswitches) can echo our own packets back at us,
602  * and we must ignore them or they will cause us to drop out of
603  * MASTER mode.
604  *
605  * We cannot catch all cases of network loops.  Instead, what we
606  * do here is catch any packet that arrives with a carp header
607  * with a VHID of 0, that comes from an address that is our own.
608  * These packets are by definition "from us" (even if they are from
609  * a misconfigured host that is pretending to be us).
610  *
611  * The VHID test is outside this mini-function.
612  */
613 static int
614 carp_source_is_self(struct mbuf *m, struct ifaddr *ifa, sa_family_t af)
615 {
616 #ifdef INET
617         struct ip *ip4;
618         struct in_addr in4;
619 #endif
620 #ifdef INET6
621         struct ip6_hdr *ip6;
622         struct in6_addr in6;
623 #endif
624
625         switch (af) {
626 #ifdef INET
627         case AF_INET:
628                 ip4 = mtod(m, struct ip *);
629                 in4 = ifatoia(ifa)->ia_addr.sin_addr;
630                 return (in4.s_addr == ip4->ip_src.s_addr);
631 #endif
632 #ifdef INET6
633         case AF_INET6:
634                 ip6 = mtod(m, struct ip6_hdr *);
635                 in6 = ifatoia6(ifa)->ia_addr.sin6_addr;
636                 return (memcmp(&in6, &ip6->ip6_src, sizeof(in6)) == 0);
637 #endif
638         default:
639                 break;
640         }
641         return (0);
642 }
643
644 static void
645 carp_input_c(struct mbuf *m, struct carp_header *ch, sa_family_t af)
646 {
647         struct ifnet *ifp = m->m_pkthdr.rcvif;
648         struct ifaddr *ifa, *match;
649         struct carp_softc *sc;
650         uint64_t tmp_counter;
651         struct timeval sc_tv, ch_tv;
652         int error;
653
654         NET_EPOCH_ASSERT();
655
656         /*
657          * Verify that the VHID is valid on the receiving interface.
658          *
659          * There should be just one match.  If there are none
660          * the VHID is not valid and we drop the packet.  If
661          * there are multiple VHID matches, take just the first
662          * one, for compatibility with previous code.  While we're
663          * scanning, check for obvious loops in the network topology
664          * (these should never happen, and as noted above, we may
665          * miss real loops; this is just a double-check).
666          */
667         error = 0;
668         match = NULL;
669         IFNET_FOREACH_IFA(ifp, ifa) {
670                 if (match == NULL && ifa->ifa_carp != NULL &&
671                     ifa->ifa_addr->sa_family == af &&
672                     ifa->ifa_carp->sc_vhid == ch->carp_vhid)
673                         match = ifa;
674                 if (ch->carp_vhid == 0 && carp_source_is_self(m, ifa, af))
675                         error = ELOOP;
676         }
677         ifa = error ? NULL : match;
678         if (ifa != NULL)
679                 ifa_ref(ifa);
680
681         if (ifa == NULL) {
682                 if (error == ELOOP) {
683                         CARP_DEBUG("dropping looped packet on interface %s\n",
684                             ifp->if_xname);
685                         CARPSTATS_INC(carps_badif);     /* ??? */
686                 } else {
687                         CARPSTATS_INC(carps_badvhid);
688                 }
689                 m_freem(m);
690                 return;
691         }
692
693         /* verify the CARP version. */
694         if (ch->carp_version != CARP_VERSION) {
695                 CARPSTATS_INC(carps_badver);
696                 CARP_DEBUG("%s: invalid version %d\n", ifp->if_xname,
697                     ch->carp_version);
698                 ifa_free(ifa);
699                 m_freem(m);
700                 return;
701         }
702
703         sc = ifa->ifa_carp;
704         CARP_LOCK(sc);
705         ifa_free(ifa);
706
707         if (carp_hmac_verify(sc, ch->carp_counter, ch->carp_md)) {
708                 CARPSTATS_INC(carps_badauth);
709                 CARP_DEBUG("%s: incorrect hash for VHID %u@%s\n", __func__,
710                     sc->sc_vhid, ifp->if_xname);
711                 goto out;
712         }
713
714         tmp_counter = ntohl(ch->carp_counter[0]);
715         tmp_counter = tmp_counter<<32;
716         tmp_counter += ntohl(ch->carp_counter[1]);
717
718         /* XXX Replay protection goes here */
719
720         sc->sc_init_counter = 0;
721         sc->sc_counter = tmp_counter;
722
723         sc_tv.tv_sec = sc->sc_advbase;
724         sc_tv.tv_usec = DEMOTE_ADVSKEW(sc) * 1000000 / 256;
725         ch_tv.tv_sec = ch->carp_advbase;
726         ch_tv.tv_usec = ch->carp_advskew * 1000000 / 256;
727
728         switch (sc->sc_state) {
729         case INIT:
730                 break;
731         case MASTER:
732                 /*
733                  * If we receive an advertisement from a master who's going to
734                  * be more frequent than us, go into BACKUP state.
735                  */
736                 if (timevalcmp(&sc_tv, &ch_tv, >) ||
737                     timevalcmp(&sc_tv, &ch_tv, ==)) {
738                         callout_stop(&sc->sc_ad_tmo);
739                         carp_set_state(sc, BACKUP,
740                             "more frequent advertisement received");
741                         carp_setrun(sc, 0);
742                         carp_delroute(sc);
743                 }
744                 break;
745         case BACKUP:
746                 /*
747                  * If we're pre-empting masters who advertise slower than us,
748                  * and this one claims to be slower, treat him as down.
749                  */
750                 if (V_carp_preempt && timevalcmp(&sc_tv, &ch_tv, <)) {
751                         carp_master_down_locked(sc,
752                             "preempting a slower master");
753                         break;
754                 }
755
756                 /*
757                  *  If the master is going to advertise at such a low frequency
758                  *  that he's guaranteed to time out, we'd might as well just
759                  *  treat him as timed out now.
760                  */
761                 sc_tv.tv_sec = sc->sc_advbase * 3;
762                 if (timevalcmp(&sc_tv, &ch_tv, <)) {
763                         carp_master_down_locked(sc, "master will time out");
764                         break;
765                 }
766
767                 /*
768                  * Otherwise, we reset the counter and wait for the next
769                  * advertisement.
770                  */
771                 carp_setrun(sc, af);
772                 break;
773         }
774
775 out:
776         CARP_UNLOCK(sc);
777         m_freem(m);
778 }
779
780 static int
781 carp_prepare_ad(struct mbuf *m, struct carp_softc *sc, struct carp_header *ch)
782 {
783         struct m_tag *mtag;
784
785         if (sc->sc_init_counter) {
786                 /* this could also be seconds since unix epoch */
787                 sc->sc_counter = arc4random();
788                 sc->sc_counter = sc->sc_counter << 32;
789                 sc->sc_counter += arc4random();
790         } else
791                 sc->sc_counter++;
792
793         ch->carp_counter[0] = htonl((sc->sc_counter>>32)&0xffffffff);
794         ch->carp_counter[1] = htonl(sc->sc_counter&0xffffffff);
795
796         carp_hmac_generate(sc, ch->carp_counter, ch->carp_md);
797
798         /* Tag packet for carp_output */
799         if ((mtag = m_tag_get(PACKET_TAG_CARP, sizeof(struct carp_softc *),
800             M_NOWAIT)) == NULL) {
801                 m_freem(m);
802                 CARPSTATS_INC(carps_onomem);
803                 return (ENOMEM);
804         }
805         bcopy(&sc, mtag + 1, sizeof(sc));
806         m_tag_prepend(m, mtag);
807
808         return (0);
809 }
810
811 /*
812  * To avoid LORs and possible recursions this function shouldn't
813  * be called directly, but scheduled via taskqueue.
814  */
815 static void
816 carp_send_ad_all(void *ctx __unused, int pending __unused)
817 {
818         struct carp_softc *sc;
819         struct epoch_tracker et;
820
821         NET_EPOCH_ENTER(et);
822         mtx_lock(&carp_mtx);
823         LIST_FOREACH(sc, &carp_list, sc_next)
824                 if (sc->sc_state == MASTER) {
825                         CARP_LOCK(sc);
826                         CURVNET_SET(sc->sc_carpdev->if_vnet);
827                         carp_send_ad_locked(sc);
828                         CURVNET_RESTORE();
829                         CARP_UNLOCK(sc);
830                 }
831         mtx_unlock(&carp_mtx);
832         NET_EPOCH_EXIT(et);
833 }
834
835 /* Send a periodic advertisement, executed in callout context. */
836 static void
837 carp_send_ad(void *v)
838 {
839         struct carp_softc *sc = v;
840         struct epoch_tracker et;
841
842         NET_EPOCH_ENTER(et);
843         CARP_LOCK_ASSERT(sc);
844         CURVNET_SET(sc->sc_carpdev->if_vnet);
845         carp_send_ad_locked(sc);
846         CURVNET_RESTORE();
847         CARP_UNLOCK(sc);
848         NET_EPOCH_EXIT(et);
849 }
850
851 static void
852 carp_send_ad_error(struct carp_softc *sc, int error)
853 {
854
855         /*
856          * We track errors and successfull sends with this logic:
857          * - Any error resets success counter to 0.
858          * - MAX_ERRORS triggers demotion.
859          * - MIN_SUCCESS successes resets error counter to 0.
860          * - MIN_SUCCESS reverts demotion, if it was triggered before.
861          */
862         if (error) {
863                 if (sc->sc_sendad_errors < INT_MAX)
864                         sc->sc_sendad_errors++;
865                 if (sc->sc_sendad_errors == CARP_SENDAD_MAX_ERRORS) {
866                         static const char fmt[] = "send error %d on %s";
867                         char msg[sizeof(fmt) + IFNAMSIZ];
868
869                         sprintf(msg, fmt, error, sc->sc_carpdev->if_xname);
870                         carp_demote_adj(V_carp_senderr_adj, msg);
871                 }
872                 sc->sc_sendad_success = 0;
873         } else if (sc->sc_sendad_errors > 0) {
874                 if (++sc->sc_sendad_success >= CARP_SENDAD_MIN_SUCCESS) {
875                         if (sc->sc_sendad_errors >= CARP_SENDAD_MAX_ERRORS) {
876                                 static const char fmt[] = "send ok on %s";
877                                 char msg[sizeof(fmt) + IFNAMSIZ];
878
879                                 sprintf(msg, fmt, sc->sc_carpdev->if_xname);
880                                 carp_demote_adj(-V_carp_senderr_adj, msg);
881                         }
882                         sc->sc_sendad_errors = 0;
883                 }
884         }
885 }
886
887 /*
888  * Pick the best ifaddr on the given ifp for sending CARP
889  * advertisements.
890  *
891  * "Best" here is defined by ifa_preferred().  This function is much
892  * much like ifaof_ifpforaddr() except that we just use ifa_preferred().
893  *
894  * (This could be simplified to return the actual address, except that
895  * it has a different format in AF_INET and AF_INET6.)
896  */
897 static struct ifaddr *
898 carp_best_ifa(int af, struct ifnet *ifp)
899 {
900         struct ifaddr *ifa, *best;
901
902         NET_EPOCH_ASSERT();
903
904         if (af >= AF_MAX)
905                 return (NULL);
906         best = NULL;
907         CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
908                 if (ifa->ifa_addr->sa_family == af &&
909                     (best == NULL || ifa_preferred(best, ifa)))
910                         best = ifa;
911         }
912         if (best != NULL)
913                 ifa_ref(best);
914         return (best);
915 }
916
917 static void
918 carp_send_ad_locked(struct carp_softc *sc)
919 {
920         struct carp_header ch;
921         struct timeval tv;
922         struct ifaddr *ifa;
923         struct carp_header *ch_ptr;
924         struct mbuf *m;
925         int len, advskew;
926
927         NET_EPOCH_ASSERT();
928         CARP_LOCK_ASSERT(sc);
929
930         advskew = DEMOTE_ADVSKEW(sc);
931         tv.tv_sec = sc->sc_advbase;
932         tv.tv_usec = advskew * 1000000 / 256;
933
934         ch.carp_version = CARP_VERSION;
935         ch.carp_type = CARP_ADVERTISEMENT;
936         ch.carp_vhid = sc->sc_vhid;
937         ch.carp_advbase = sc->sc_advbase;
938         ch.carp_advskew = advskew;
939         ch.carp_authlen = 7;    /* XXX DEFINE */
940         ch.carp_pad1 = 0;       /* must be zero */
941         ch.carp_cksum = 0;
942
943         /* XXXGL: OpenBSD picks first ifaddr with needed family. */
944
945 #ifdef INET
946         if (sc->sc_naddrs) {
947                 struct ip *ip;
948
949                 m = m_gethdr(M_NOWAIT, MT_DATA);
950                 if (m == NULL) {
951                         CARPSTATS_INC(carps_onomem);
952                         goto resched;
953                 }
954                 len = sizeof(*ip) + sizeof(ch);
955                 m->m_pkthdr.len = len;
956                 m->m_pkthdr.rcvif = NULL;
957                 m->m_len = len;
958                 M_ALIGN(m, m->m_len);
959                 m->m_flags |= M_MCAST;
960                 ip = mtod(m, struct ip *);
961                 ip->ip_v = IPVERSION;
962                 ip->ip_hl = sizeof(*ip) >> 2;
963                 ip->ip_tos = V_carp_dscp << IPTOS_DSCP_OFFSET;
964                 ip->ip_len = htons(len);
965                 ip->ip_off = htons(IP_DF);
966                 ip->ip_ttl = CARP_DFLTTL;
967                 ip->ip_p = IPPROTO_CARP;
968                 ip->ip_sum = 0;
969                 ip_fillid(ip);
970
971                 ifa = carp_best_ifa(AF_INET, sc->sc_carpdev);
972                 if (ifa != NULL) {
973                         ip->ip_src.s_addr =
974                             ifatoia(ifa)->ia_addr.sin_addr.s_addr;
975                         ifa_free(ifa);
976                 } else
977                         ip->ip_src.s_addr = 0;
978                 ip->ip_dst.s_addr = htonl(INADDR_CARP_GROUP);
979
980                 ch_ptr = (struct carp_header *)(&ip[1]);
981                 bcopy(&ch, ch_ptr, sizeof(ch));
982                 if (carp_prepare_ad(m, sc, ch_ptr))
983                         goto resched;
984
985                 m->m_data += sizeof(*ip);
986                 ch_ptr->carp_cksum = in_cksum(m, len - sizeof(*ip));
987                 m->m_data -= sizeof(*ip);
988
989                 CARPSTATS_INC(carps_opackets);
990
991                 carp_send_ad_error(sc, ip_output(m, NULL, NULL, IP_RAWOUTPUT,
992                     &sc->sc_carpdev->if_carp->cif_imo, NULL));
993         }
994 #endif /* INET */
995 #ifdef INET6
996         if (sc->sc_naddrs6) {
997                 struct ip6_hdr *ip6;
998
999                 m = m_gethdr(M_NOWAIT, MT_DATA);
1000                 if (m == NULL) {
1001                         CARPSTATS_INC(carps_onomem);
1002                         goto resched;
1003                 }
1004                 len = sizeof(*ip6) + sizeof(ch);
1005                 m->m_pkthdr.len = len;
1006                 m->m_pkthdr.rcvif = NULL;
1007                 m->m_len = len;
1008                 M_ALIGN(m, m->m_len);
1009                 m->m_flags |= M_MCAST;
1010                 ip6 = mtod(m, struct ip6_hdr *);
1011                 bzero(ip6, sizeof(*ip6));
1012                 ip6->ip6_vfc |= IPV6_VERSION;
1013                 /* Traffic class isn't defined in ip6 struct instead
1014                  * it gets offset into flowid field */
1015                 ip6->ip6_flow |= htonl(V_carp_dscp << (IPV6_FLOWLABEL_LEN +
1016                     IPTOS_DSCP_OFFSET));
1017                 ip6->ip6_hlim = CARP_DFLTTL;
1018                 ip6->ip6_nxt = IPPROTO_CARP;
1019
1020                 /* set the source address */
1021                 ifa = carp_best_ifa(AF_INET6, sc->sc_carpdev);
1022                 if (ifa != NULL) {
1023                         bcopy(IFA_IN6(ifa), &ip6->ip6_src,
1024                             sizeof(struct in6_addr));
1025                         ifa_free(ifa);
1026                 } else
1027                         /* This should never happen with IPv6. */
1028                         bzero(&ip6->ip6_src, sizeof(struct in6_addr));
1029
1030                 /* Set the multicast destination. */
1031                 ip6->ip6_dst.s6_addr16[0] = htons(0xff02);
1032                 ip6->ip6_dst.s6_addr8[15] = 0x12;
1033                 if (in6_setscope(&ip6->ip6_dst, sc->sc_carpdev, NULL) != 0) {
1034                         m_freem(m);
1035                         CARP_DEBUG("%s: in6_setscope failed\n", __func__);
1036                         goto resched;
1037                 }
1038
1039                 ch_ptr = (struct carp_header *)(&ip6[1]);
1040                 bcopy(&ch, ch_ptr, sizeof(ch));
1041                 if (carp_prepare_ad(m, sc, ch_ptr))
1042                         goto resched;
1043
1044                 m->m_data += sizeof(*ip6);
1045                 ch_ptr->carp_cksum = in_cksum(m, len - sizeof(*ip6));
1046                 m->m_data -= sizeof(*ip6);
1047
1048                 CARPSTATS_INC(carps_opackets6);
1049
1050                 carp_send_ad_error(sc, ip6_output(m, NULL, NULL, 0,
1051                     &sc->sc_carpdev->if_carp->cif_im6o, NULL, NULL));
1052         }
1053 #endif /* INET6 */
1054
1055 resched:
1056         callout_reset(&sc->sc_ad_tmo, tvtohz(&tv), carp_send_ad, sc);
1057 }
1058
1059 static void
1060 carp_addroute(struct carp_softc *sc)
1061 {
1062         struct ifaddr *ifa;
1063
1064         CARP_FOREACH_IFA(sc, ifa)
1065                 carp_ifa_addroute(ifa);
1066 }
1067
1068 static void
1069 carp_ifa_addroute(struct ifaddr *ifa)
1070 {
1071
1072         switch (ifa->ifa_addr->sa_family) {
1073 #ifdef INET
1074         case AF_INET:
1075                 in_addprefix(ifatoia(ifa));
1076                 ifa_add_loopback_route(ifa,
1077                     (struct sockaddr *)&ifatoia(ifa)->ia_addr);
1078                 break;
1079 #endif
1080 #ifdef INET6
1081         case AF_INET6:
1082                 ifa_add_loopback_route(ifa,
1083                     (struct sockaddr *)&ifatoia6(ifa)->ia_addr);
1084                 nd6_add_ifa_lle(ifatoia6(ifa));
1085                 break;
1086 #endif
1087         }
1088 }
1089
1090 static void
1091 carp_delroute(struct carp_softc *sc)
1092 {
1093         struct ifaddr *ifa;
1094
1095         CARP_FOREACH_IFA(sc, ifa)
1096                 carp_ifa_delroute(ifa);
1097 }
1098
1099 static void
1100 carp_ifa_delroute(struct ifaddr *ifa)
1101 {
1102
1103         switch (ifa->ifa_addr->sa_family) {
1104 #ifdef INET
1105         case AF_INET:
1106                 ifa_del_loopback_route(ifa,
1107                     (struct sockaddr *)&ifatoia(ifa)->ia_addr);
1108                 in_scrubprefix(ifatoia(ifa), LLE_STATIC);
1109                 break;
1110 #endif
1111 #ifdef INET6
1112         case AF_INET6:
1113                 ifa_del_loopback_route(ifa,
1114                     (struct sockaddr *)&ifatoia6(ifa)->ia_addr);
1115                 nd6_rem_ifa_lle(ifatoia6(ifa), 1);
1116                 break;
1117 #endif
1118         }
1119 }
1120
1121 int
1122 carp_master(struct ifaddr *ifa)
1123 {
1124         struct carp_softc *sc = ifa->ifa_carp;
1125
1126         return (sc->sc_state == MASTER);
1127 }
1128
1129 #ifdef INET
1130 /*
1131  * Broadcast a gratuitous ARP request containing
1132  * the virtual router MAC address for each IP address
1133  * associated with the virtual router.
1134  */
1135 static void
1136 carp_send_arp(struct carp_softc *sc)
1137 {
1138         struct ifaddr *ifa;
1139         struct in_addr addr;
1140
1141         NET_EPOCH_ASSERT();
1142
1143         CARP_FOREACH_IFA(sc, ifa) {
1144                 if (ifa->ifa_addr->sa_family != AF_INET)
1145                         continue;
1146                 addr = ((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
1147                 arp_announce_ifaddr(sc->sc_carpdev, addr, LLADDR(&sc->sc_addr));
1148         }
1149 }
1150
1151 int
1152 carp_iamatch(struct ifaddr *ifa, uint8_t **enaddr)
1153 {
1154         struct carp_softc *sc = ifa->ifa_carp;
1155
1156         if (sc->sc_state == MASTER) {
1157                 *enaddr = LLADDR(&sc->sc_addr);
1158                 return (1);
1159         }
1160
1161         return (0);
1162 }
1163 #endif
1164
1165 #ifdef INET6
1166 static void
1167 carp_send_na(struct carp_softc *sc)
1168 {
1169         static struct in6_addr mcast = IN6ADDR_LINKLOCAL_ALLNODES_INIT;
1170         struct ifaddr *ifa;
1171         struct in6_addr *in6;
1172
1173         CARP_FOREACH_IFA(sc, ifa) {
1174                 if (ifa->ifa_addr->sa_family != AF_INET6)
1175                         continue;
1176
1177                 in6 = IFA_IN6(ifa);
1178                 nd6_na_output(sc->sc_carpdev, &mcast, in6,
1179                     ND_NA_FLAG_OVERRIDE, 1, NULL);
1180                 DELAY(1000);    /* XXX */
1181         }
1182 }
1183
1184 /*
1185  * Returns ifa in case it's a carp address and it is MASTER, or if the address
1186  * matches and is not a carp address.  Returns NULL otherwise.
1187  */
1188 struct ifaddr *
1189 carp_iamatch6(struct ifnet *ifp, struct in6_addr *taddr)
1190 {
1191         struct ifaddr *ifa;
1192
1193         NET_EPOCH_ASSERT();
1194
1195         ifa = NULL;
1196         CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1197                 if (ifa->ifa_addr->sa_family != AF_INET6)
1198                         continue;
1199                 if (!IN6_ARE_ADDR_EQUAL(taddr, IFA_IN6(ifa)))
1200                         continue;
1201                 if (ifa->ifa_carp && ifa->ifa_carp->sc_state != MASTER)
1202                         ifa = NULL;
1203                 else
1204                         ifa_ref(ifa);
1205                 break;
1206         }
1207
1208         return (ifa);
1209 }
1210
1211 char *
1212 carp_macmatch6(struct ifnet *ifp, struct mbuf *m, const struct in6_addr *taddr)
1213 {
1214         struct ifaddr *ifa;
1215
1216         NET_EPOCH_ASSERT();
1217
1218         IFNET_FOREACH_IFA(ifp, ifa)
1219                 if (ifa->ifa_addr->sa_family == AF_INET6 &&
1220                     IN6_ARE_ADDR_EQUAL(taddr, IFA_IN6(ifa))) {
1221                         struct carp_softc *sc = ifa->ifa_carp;
1222                         struct m_tag *mtag;
1223
1224                         mtag = m_tag_get(PACKET_TAG_CARP,
1225                             sizeof(struct carp_softc *), M_NOWAIT);
1226                         if (mtag == NULL)
1227                                 /* Better a bit than nothing. */
1228                                 return (LLADDR(&sc->sc_addr));
1229
1230                         bcopy(&sc, mtag + 1, sizeof(sc));
1231                         m_tag_prepend(m, mtag);
1232
1233                         return (LLADDR(&sc->sc_addr));
1234                 }
1235
1236         return (NULL);
1237 }
1238 #endif /* INET6 */
1239
1240 int
1241 carp_forus(struct ifnet *ifp, u_char *dhost)
1242 {
1243         struct carp_softc *sc;
1244         uint8_t *ena = dhost;
1245
1246         if (ena[0] || ena[1] || ena[2] != 0x5e || ena[3] || ena[4] != 1)
1247                 return (0);
1248
1249         CIF_LOCK(ifp->if_carp);
1250         IFNET_FOREACH_CARP(ifp, sc) {
1251                 /*
1252                  * CARP_LOCK() is not here, since would protect nothing, but
1253                  * cause deadlock with if_bridge, calling this under its lock.
1254                  */
1255                 if (sc->sc_state == MASTER && !bcmp(dhost, LLADDR(&sc->sc_addr),
1256                     ETHER_ADDR_LEN)) {
1257                         CIF_UNLOCK(ifp->if_carp);
1258                         return (1);
1259                 }
1260         }
1261         CIF_UNLOCK(ifp->if_carp);
1262
1263         return (0);
1264 }
1265
1266 /* Master down timeout event, executed in callout context. */
1267 static void
1268 carp_master_down(void *v)
1269 {
1270         struct carp_softc *sc = v;
1271         struct epoch_tracker et;
1272
1273         NET_EPOCH_ENTER(et);
1274         CARP_LOCK_ASSERT(sc);
1275
1276         CURVNET_SET(sc->sc_carpdev->if_vnet);
1277         if (sc->sc_state == BACKUP) {
1278                 carp_master_down_locked(sc, "master timed out");
1279         }
1280         CURVNET_RESTORE();
1281
1282         CARP_UNLOCK(sc);
1283         NET_EPOCH_EXIT(et);
1284 }
1285
1286 static void
1287 carp_master_down_locked(struct carp_softc *sc, const char *reason)
1288 {
1289
1290         NET_EPOCH_ASSERT();
1291         CARP_LOCK_ASSERT(sc);
1292
1293         switch (sc->sc_state) {
1294         case BACKUP:
1295                 carp_set_state(sc, MASTER, reason);
1296                 carp_send_ad_locked(sc);
1297 #ifdef INET
1298                 carp_send_arp(sc);
1299 #endif
1300 #ifdef INET6
1301                 carp_send_na(sc);
1302 #endif
1303                 carp_setrun(sc, 0);
1304                 carp_addroute(sc);
1305                 break;
1306         case INIT:
1307         case MASTER:
1308 #ifdef INVARIANTS
1309                 panic("carp: VHID %u@%s: master_down event in %s state\n",
1310                     sc->sc_vhid,
1311                     sc->sc_carpdev->if_xname,
1312                     sc->sc_state ? "MASTER" : "INIT");
1313 #endif
1314                 break;
1315         }
1316 }
1317
1318 /*
1319  * When in backup state, af indicates whether to reset the master down timer
1320  * for v4 or v6. If it's set to zero, reset the ones which are already pending.
1321  */
1322 static void
1323 carp_setrun(struct carp_softc *sc, sa_family_t af)
1324 {
1325         struct timeval tv;
1326
1327         CARP_LOCK_ASSERT(sc);
1328
1329         if ((sc->sc_carpdev->if_flags & IFF_UP) == 0 ||
1330             sc->sc_carpdev->if_link_state != LINK_STATE_UP ||
1331             (sc->sc_naddrs == 0 && sc->sc_naddrs6 == 0) ||
1332             !V_carp_allow)
1333                 return;
1334
1335         switch (sc->sc_state) {
1336         case INIT:
1337                 carp_set_state(sc, BACKUP, "initialization complete");
1338                 carp_setrun(sc, 0);
1339                 break;
1340         case BACKUP:
1341                 callout_stop(&sc->sc_ad_tmo);
1342                 tv.tv_sec = 3 * sc->sc_advbase;
1343                 tv.tv_usec = sc->sc_advskew * 1000000 / 256;
1344                 switch (af) {
1345 #ifdef INET
1346                 case AF_INET:
1347                         callout_reset(&sc->sc_md_tmo, tvtohz(&tv),
1348                             carp_master_down, sc);
1349                         break;
1350 #endif
1351 #ifdef INET6
1352                 case AF_INET6:
1353                         callout_reset(&sc->sc_md6_tmo, tvtohz(&tv),
1354                             carp_master_down, sc);
1355                         break;
1356 #endif
1357                 default:
1358 #ifdef INET
1359                         if (sc->sc_naddrs)
1360                                 callout_reset(&sc->sc_md_tmo, tvtohz(&tv),
1361                                     carp_master_down, sc);
1362 #endif
1363 #ifdef INET6
1364                         if (sc->sc_naddrs6)
1365                                 callout_reset(&sc->sc_md6_tmo, tvtohz(&tv),
1366                                     carp_master_down, sc);
1367 #endif
1368                         break;
1369                 }
1370                 break;
1371         case MASTER:
1372                 tv.tv_sec = sc->sc_advbase;
1373                 tv.tv_usec = sc->sc_advskew * 1000000 / 256;
1374                 callout_reset(&sc->sc_ad_tmo, tvtohz(&tv),
1375                     carp_send_ad, sc);
1376                 break;
1377         }
1378 }
1379
1380 /*
1381  * Setup multicast structures.
1382  */
1383 static int
1384 carp_multicast_setup(struct carp_if *cif, sa_family_t sa)
1385 {
1386         struct ifnet *ifp = cif->cif_ifp;
1387         int error = 0;
1388
1389         switch (sa) {
1390 #ifdef INET
1391         case AF_INET:
1392             {
1393                 struct ip_moptions *imo = &cif->cif_imo;
1394                 struct in_mfilter *imf;
1395                 struct in_addr addr;
1396
1397                 if (ip_mfilter_first(&imo->imo_head) != NULL)
1398                         return (0);
1399
1400                 imf = ip_mfilter_alloc(M_WAITOK, 0, 0);
1401                 ip_mfilter_init(&imo->imo_head);
1402                 imo->imo_multicast_vif = -1;
1403
1404                 addr.s_addr = htonl(INADDR_CARP_GROUP);
1405                 if ((error = in_joingroup(ifp, &addr, NULL,
1406                     &imf->imf_inm)) != 0) {
1407                         ip_mfilter_free(imf);
1408                         break;
1409                 }
1410
1411                 ip_mfilter_insert(&imo->imo_head, imf);
1412                 imo->imo_multicast_ifp = ifp;
1413                 imo->imo_multicast_ttl = CARP_DFLTTL;
1414                 imo->imo_multicast_loop = 0;
1415                 break;
1416            }
1417 #endif
1418 #ifdef INET6
1419         case AF_INET6:
1420             {
1421                 struct ip6_moptions *im6o = &cif->cif_im6o;
1422                 struct in6_mfilter *im6f[2];
1423                 struct in6_addr in6;
1424
1425                 if (ip6_mfilter_first(&im6o->im6o_head))
1426                         return (0);
1427
1428                 im6f[0] = ip6_mfilter_alloc(M_WAITOK, 0, 0);
1429                 im6f[1] = ip6_mfilter_alloc(M_WAITOK, 0, 0);
1430
1431                 ip6_mfilter_init(&im6o->im6o_head);
1432                 im6o->im6o_multicast_hlim = CARP_DFLTTL;
1433                 im6o->im6o_multicast_ifp = ifp;
1434
1435                 /* Join IPv6 CARP multicast group. */
1436                 bzero(&in6, sizeof(in6));
1437                 in6.s6_addr16[0] = htons(0xff02);
1438                 in6.s6_addr8[15] = 0x12;
1439                 if ((error = in6_setscope(&in6, ifp, NULL)) != 0) {
1440                         ip6_mfilter_free(im6f[0]);
1441                         ip6_mfilter_free(im6f[1]);
1442                         break;
1443                 }
1444                 if ((error = in6_joingroup(ifp, &in6, NULL, &im6f[0]->im6f_in6m, 0)) != 0) {
1445                         ip6_mfilter_free(im6f[0]);
1446                         ip6_mfilter_free(im6f[1]);
1447                         break;
1448                 }
1449
1450                 /* Join solicited multicast address. */
1451                 bzero(&in6, sizeof(in6));
1452                 in6.s6_addr16[0] = htons(0xff02);
1453                 in6.s6_addr32[1] = 0;
1454                 in6.s6_addr32[2] = htonl(1);
1455                 in6.s6_addr32[3] = 0;
1456                 in6.s6_addr8[12] = 0xff;
1457
1458                 if ((error = in6_setscope(&in6, ifp, NULL)) != 0) {
1459                         ip6_mfilter_free(im6f[0]);
1460                         ip6_mfilter_free(im6f[1]);
1461                         break;
1462                 }
1463
1464                 if ((error = in6_joingroup(ifp, &in6, NULL, &im6f[1]->im6f_in6m, 0)) != 0) {
1465                         in6_leavegroup(im6f[0]->im6f_in6m, NULL);
1466                         ip6_mfilter_free(im6f[0]);
1467                         ip6_mfilter_free(im6f[1]);
1468                         break;
1469                 }
1470                 ip6_mfilter_insert(&im6o->im6o_head, im6f[0]);
1471                 ip6_mfilter_insert(&im6o->im6o_head, im6f[1]);
1472                 break;
1473             }
1474 #endif
1475         }
1476
1477         return (error);
1478 }
1479
1480 /*
1481  * Free multicast structures.
1482  */
1483 static void
1484 carp_multicast_cleanup(struct carp_if *cif, sa_family_t sa)
1485 {
1486 #ifdef INET
1487         struct ip_moptions *imo = &cif->cif_imo;
1488         struct in_mfilter *imf;
1489 #endif
1490 #ifdef INET6
1491         struct ip6_moptions *im6o = &cif->cif_im6o;
1492         struct in6_mfilter *im6f;
1493 #endif
1494         sx_assert(&carp_sx, SA_XLOCKED);
1495
1496         switch (sa) {
1497 #ifdef INET
1498         case AF_INET:
1499                 if (cif->cif_naddrs != 0)
1500                         break;
1501
1502                 while ((imf = ip_mfilter_first(&imo->imo_head)) != NULL) {
1503                         ip_mfilter_remove(&imo->imo_head, imf);
1504                         in_leavegroup(imf->imf_inm, NULL);
1505                         ip_mfilter_free(imf);
1506                 }
1507                 break;
1508 #endif
1509 #ifdef INET6
1510         case AF_INET6:
1511                 if (cif->cif_naddrs6 != 0)
1512                         break;
1513
1514                 while ((im6f = ip6_mfilter_first(&im6o->im6o_head)) != NULL) {
1515                         ip6_mfilter_remove(&im6o->im6o_head, im6f);
1516                         in6_leavegroup(im6f->im6f_in6m, NULL);
1517                         ip6_mfilter_free(im6f);
1518                 }
1519                 break;
1520 #endif
1521         }
1522 }
1523
1524 int
1525 carp_output(struct ifnet *ifp, struct mbuf *m, const struct sockaddr *sa)
1526 {
1527         struct m_tag *mtag;
1528         struct carp_softc *sc;
1529
1530         if (!sa)
1531                 return (0);
1532
1533         switch (sa->sa_family) {
1534 #ifdef INET
1535         case AF_INET:
1536                 break;
1537 #endif
1538 #ifdef INET6
1539         case AF_INET6:
1540                 break;
1541 #endif
1542         default:
1543                 return (0);
1544         }
1545
1546         mtag = m_tag_find(m, PACKET_TAG_CARP, NULL);
1547         if (mtag == NULL)
1548                 return (0);
1549
1550         bcopy(mtag + 1, &sc, sizeof(sc));
1551
1552         /* Set the source MAC address to the Virtual Router MAC Address. */
1553         switch (ifp->if_type) {
1554         case IFT_ETHER:
1555         case IFT_BRIDGE:
1556         case IFT_L2VLAN: {
1557                         struct ether_header *eh;
1558
1559                         eh = mtod(m, struct ether_header *);
1560                         eh->ether_shost[0] = 0;
1561                         eh->ether_shost[1] = 0;
1562                         eh->ether_shost[2] = 0x5e;
1563                         eh->ether_shost[3] = 0;
1564                         eh->ether_shost[4] = 1;
1565                         eh->ether_shost[5] = sc->sc_vhid;
1566                 }
1567                 break;
1568         default:
1569                 printf("%s: carp is not supported for the %d interface type\n",
1570                     ifp->if_xname, ifp->if_type);
1571                 return (EOPNOTSUPP);
1572         }
1573
1574         return (0);
1575 }
1576
1577 static struct carp_softc*
1578 carp_alloc(struct ifnet *ifp)
1579 {
1580         struct carp_softc *sc;
1581         struct carp_if *cif;
1582
1583         sx_assert(&carp_sx, SA_XLOCKED);
1584
1585         if ((cif = ifp->if_carp) == NULL)
1586                 cif = carp_alloc_if(ifp);
1587
1588         sc = malloc(sizeof(*sc), M_CARP, M_WAITOK|M_ZERO);
1589
1590         sc->sc_advbase = CARP_DFLTINTV;
1591         sc->sc_vhid = -1;       /* required setting */
1592         sc->sc_init_counter = 1;
1593         sc->sc_state = INIT;
1594
1595         sc->sc_ifasiz = sizeof(struct ifaddr *);
1596         sc->sc_ifas = malloc(sc->sc_ifasiz, M_CARP, M_WAITOK|M_ZERO);
1597         sc->sc_carpdev = ifp;
1598
1599         CARP_LOCK_INIT(sc);
1600 #ifdef INET
1601         callout_init_mtx(&sc->sc_md_tmo, &sc->sc_mtx, CALLOUT_RETURNUNLOCKED);
1602 #endif
1603 #ifdef INET6
1604         callout_init_mtx(&sc->sc_md6_tmo, &sc->sc_mtx, CALLOUT_RETURNUNLOCKED);
1605 #endif
1606         callout_init_mtx(&sc->sc_ad_tmo, &sc->sc_mtx, CALLOUT_RETURNUNLOCKED);
1607
1608         CIF_LOCK(cif);
1609         TAILQ_INSERT_TAIL(&cif->cif_vrs, sc, sc_list);
1610         CIF_UNLOCK(cif);
1611
1612         mtx_lock(&carp_mtx);
1613         LIST_INSERT_HEAD(&carp_list, sc, sc_next);
1614         mtx_unlock(&carp_mtx);
1615
1616         return (sc);
1617 }
1618
1619 static void
1620 carp_grow_ifas(struct carp_softc *sc)
1621 {
1622         struct ifaddr **new;
1623
1624         new = malloc(sc->sc_ifasiz * 2, M_CARP, M_WAITOK | M_ZERO);
1625         CARP_LOCK(sc);
1626         bcopy(sc->sc_ifas, new, sc->sc_ifasiz);
1627         free(sc->sc_ifas, M_CARP);
1628         sc->sc_ifas = new;
1629         sc->sc_ifasiz *= 2;
1630         CARP_UNLOCK(sc);
1631 }
1632
1633 static void
1634 carp_destroy(struct carp_softc *sc)
1635 {
1636         struct ifnet *ifp = sc->sc_carpdev;
1637         struct carp_if *cif = ifp->if_carp;
1638
1639         sx_assert(&carp_sx, SA_XLOCKED);
1640
1641         if (sc->sc_suppress)
1642                 carp_demote_adj(-V_carp_ifdown_adj, "vhid removed");
1643         CARP_UNLOCK(sc);
1644
1645         CIF_LOCK(cif);
1646         TAILQ_REMOVE(&cif->cif_vrs, sc, sc_list);
1647         CIF_UNLOCK(cif);
1648
1649         mtx_lock(&carp_mtx);
1650         LIST_REMOVE(sc, sc_next);
1651         mtx_unlock(&carp_mtx);
1652
1653         callout_drain(&sc->sc_ad_tmo);
1654 #ifdef INET
1655         callout_drain(&sc->sc_md_tmo);
1656 #endif
1657 #ifdef INET6
1658         callout_drain(&sc->sc_md6_tmo);
1659 #endif
1660         CARP_LOCK_DESTROY(sc);
1661
1662         free(sc->sc_ifas, M_CARP);
1663         free(sc, M_CARP);
1664 }
1665
1666 static struct carp_if*
1667 carp_alloc_if(struct ifnet *ifp)
1668 {
1669         struct carp_if *cif;
1670         int error;
1671
1672         cif = malloc(sizeof(*cif), M_CARP, M_WAITOK|M_ZERO);
1673
1674         if ((error = ifpromisc(ifp, 1)) != 0)
1675                 printf("%s: ifpromisc(%s) failed: %d\n",
1676                     __func__, ifp->if_xname, error);
1677         else
1678                 cif->cif_flags |= CIF_PROMISC;
1679
1680         CIF_LOCK_INIT(cif);
1681         cif->cif_ifp = ifp;
1682         TAILQ_INIT(&cif->cif_vrs);
1683
1684         IF_ADDR_WLOCK(ifp);
1685         ifp->if_carp = cif;
1686         if_ref(ifp);
1687         IF_ADDR_WUNLOCK(ifp);
1688
1689         return (cif);
1690 }
1691
1692 static void
1693 carp_free_if(struct carp_if *cif)
1694 {
1695         struct ifnet *ifp = cif->cif_ifp;
1696
1697         CIF_LOCK_ASSERT(cif);
1698         KASSERT(TAILQ_EMPTY(&cif->cif_vrs), ("%s: softc list not empty",
1699             __func__));
1700
1701         IF_ADDR_WLOCK(ifp);
1702         ifp->if_carp = NULL;
1703         IF_ADDR_WUNLOCK(ifp);
1704
1705         CIF_LOCK_DESTROY(cif);
1706
1707         if (cif->cif_flags & CIF_PROMISC)
1708                 ifpromisc(ifp, 0);
1709         if_rele(ifp);
1710
1711         free(cif, M_CARP);
1712 }
1713
1714 static void
1715 carp_carprcp(struct carpreq *carpr, struct carp_softc *sc, int priv)
1716 {
1717
1718         CARP_LOCK(sc);
1719         carpr->carpr_state = sc->sc_state;
1720         carpr->carpr_vhid = sc->sc_vhid;
1721         carpr->carpr_advbase = sc->sc_advbase;
1722         carpr->carpr_advskew = sc->sc_advskew;
1723         if (priv)
1724                 bcopy(sc->sc_key, carpr->carpr_key, sizeof(carpr->carpr_key));
1725         else
1726                 bzero(carpr->carpr_key, sizeof(carpr->carpr_key));
1727         CARP_UNLOCK(sc);
1728 }
1729
1730 int
1731 carp_ioctl(struct ifreq *ifr, u_long cmd, struct thread *td)
1732 {
1733         struct epoch_tracker et;
1734         struct carpreq carpr;
1735         struct ifnet *ifp;
1736         struct carp_softc *sc = NULL;
1737         int error = 0, locked = 0;
1738
1739         if ((error = copyin(ifr_data_get_ptr(ifr), &carpr, sizeof carpr)))
1740                 return (error);
1741
1742         ifp = ifunit_ref(ifr->ifr_name);
1743         if (ifp == NULL)
1744                 return (ENXIO);
1745
1746         switch (ifp->if_type) {
1747         case IFT_ETHER:
1748         case IFT_L2VLAN:
1749         case IFT_BRIDGE:
1750                 break;
1751         default:
1752                 error = EOPNOTSUPP;
1753                 goto out;
1754         }
1755
1756         if ((ifp->if_flags & IFF_MULTICAST) == 0) {
1757                 error = EADDRNOTAVAIL;
1758                 goto out;
1759         }
1760
1761         sx_xlock(&carp_sx);
1762         switch (cmd) {
1763         case SIOCSVH:
1764                 if ((error = priv_check(td, PRIV_NETINET_CARP)))
1765                         break;
1766                 if (carpr.carpr_vhid <= 0 || carpr.carpr_vhid > CARP_MAXVHID ||
1767                     carpr.carpr_advbase < 0 || carpr.carpr_advskew < 0) {
1768                         error = EINVAL;
1769                         break;
1770                 }
1771
1772                 if (ifp->if_carp) {
1773                         IFNET_FOREACH_CARP(ifp, sc)
1774                                 if (sc->sc_vhid == carpr.carpr_vhid)
1775                                         break;
1776                 }
1777                 if (sc == NULL) {
1778                         sc = carp_alloc(ifp);
1779                         CARP_LOCK(sc);
1780                         sc->sc_vhid = carpr.carpr_vhid;
1781                         LLADDR(&sc->sc_addr)[0] = 0;
1782                         LLADDR(&sc->sc_addr)[1] = 0;
1783                         LLADDR(&sc->sc_addr)[2] = 0x5e;
1784                         LLADDR(&sc->sc_addr)[3] = 0;
1785                         LLADDR(&sc->sc_addr)[4] = 1;
1786                         LLADDR(&sc->sc_addr)[5] = sc->sc_vhid;
1787                 } else
1788                         CARP_LOCK(sc);
1789                 locked = 1;
1790                 if (carpr.carpr_advbase > 0) {
1791                         if (carpr.carpr_advbase > 255 ||
1792                             carpr.carpr_advbase < CARP_DFLTINTV) {
1793                                 error = EINVAL;
1794                                 break;
1795                         }
1796                         sc->sc_advbase = carpr.carpr_advbase;
1797                 }
1798                 if (carpr.carpr_advskew >= 255) {
1799                         error = EINVAL;
1800                         break;
1801                 }
1802                 sc->sc_advskew = carpr.carpr_advskew;
1803                 if (carpr.carpr_key[0] != '\0') {
1804                         bcopy(carpr.carpr_key, sc->sc_key, sizeof(sc->sc_key));
1805                         carp_hmac_prepare(sc);
1806                 }
1807                 if (sc->sc_state != INIT &&
1808                     carpr.carpr_state != sc->sc_state) {
1809                         switch (carpr.carpr_state) {
1810                         case BACKUP:
1811                                 callout_stop(&sc->sc_ad_tmo);
1812                                 carp_set_state(sc, BACKUP,
1813                                     "user requested via ifconfig");
1814                                 carp_setrun(sc, 0);
1815                                 carp_delroute(sc);
1816                                 break;
1817                         case MASTER:
1818                                 NET_EPOCH_ENTER(et);
1819                                 carp_master_down_locked(sc,
1820                                     "user requested via ifconfig");
1821                                 NET_EPOCH_EXIT(et);
1822                                 break;
1823                         default:
1824                                 break;
1825                         }
1826                 }
1827                 break;
1828
1829         case SIOCGVH:
1830             {
1831                 int priveleged;
1832
1833                 if (carpr.carpr_vhid < 0 || carpr.carpr_vhid > CARP_MAXVHID) {
1834                         error = EINVAL;
1835                         break;
1836                 }
1837                 if (carpr.carpr_count < 1) {
1838                         error = EMSGSIZE;
1839                         break;
1840                 }
1841                 if (ifp->if_carp == NULL) {
1842                         error = ENOENT;
1843                         break;
1844                 }
1845
1846                 priveleged = (priv_check(td, PRIV_NETINET_CARP) == 0);
1847                 if (carpr.carpr_vhid != 0) {
1848                         IFNET_FOREACH_CARP(ifp, sc)
1849                                 if (sc->sc_vhid == carpr.carpr_vhid)
1850                                         break;
1851                         if (sc == NULL) {
1852                                 error = ENOENT;
1853                                 break;
1854                         }
1855                         carp_carprcp(&carpr, sc, priveleged);
1856                         error = copyout(&carpr, ifr_data_get_ptr(ifr),
1857                             sizeof(carpr));
1858                 } else  {
1859                         int i, count;
1860
1861                         count = 0;
1862                         IFNET_FOREACH_CARP(ifp, sc)
1863                                 count++;
1864
1865                         if (count > carpr.carpr_count) {
1866                                 CIF_UNLOCK(ifp->if_carp);
1867                                 error = EMSGSIZE;
1868                                 break;
1869                         }
1870
1871                         i = 0;
1872                         IFNET_FOREACH_CARP(ifp, sc) {
1873                                 carp_carprcp(&carpr, sc, priveleged);
1874                                 carpr.carpr_count = count;
1875                                 error = copyout(&carpr,
1876                                     (char *)ifr_data_get_ptr(ifr) +
1877                                     (i * sizeof(carpr)), sizeof(carpr));
1878                                 if (error) {
1879                                         CIF_UNLOCK(ifp->if_carp);
1880                                         break;
1881                                 }
1882                                 i++;
1883                         }
1884                 }
1885                 break;
1886             }
1887         default:
1888                 error = EINVAL;
1889         }
1890         sx_xunlock(&carp_sx);
1891
1892 out:
1893         if (locked)
1894                 CARP_UNLOCK(sc);
1895         if_rele(ifp);
1896
1897         return (error);
1898 }
1899
1900 static int
1901 carp_get_vhid(struct ifaddr *ifa)
1902 {
1903
1904         if (ifa == NULL || ifa->ifa_carp == NULL)
1905                 return (0);
1906
1907         return (ifa->ifa_carp->sc_vhid);
1908 }
1909
1910 int
1911 carp_attach(struct ifaddr *ifa, int vhid)
1912 {
1913         struct ifnet *ifp = ifa->ifa_ifp;
1914         struct carp_if *cif = ifp->if_carp;
1915         struct carp_softc *sc;
1916         int index, error;
1917
1918         KASSERT(ifa->ifa_carp == NULL, ("%s: ifa %p attached", __func__, ifa));
1919
1920         switch (ifa->ifa_addr->sa_family) {
1921 #ifdef INET
1922         case AF_INET:
1923 #endif
1924 #ifdef INET6
1925         case AF_INET6:
1926 #endif
1927                 break;
1928         default:
1929                 return (EPROTOTYPE);
1930         }
1931
1932         sx_xlock(&carp_sx);
1933         if (ifp->if_carp == NULL) {
1934                 sx_xunlock(&carp_sx);
1935                 return (ENOPROTOOPT);
1936         }
1937
1938         IFNET_FOREACH_CARP(ifp, sc)
1939                 if (sc->sc_vhid == vhid)
1940                         break;
1941         if (sc == NULL) {
1942                 sx_xunlock(&carp_sx);
1943                 return (ENOENT);
1944         }
1945
1946         error = carp_multicast_setup(cif, ifa->ifa_addr->sa_family);
1947         if (error) {
1948                 CIF_FREE(cif);
1949                 sx_xunlock(&carp_sx);
1950                 return (error);
1951         }
1952
1953         index = sc->sc_naddrs + sc->sc_naddrs6 + 1;
1954         if (index > sc->sc_ifasiz / sizeof(struct ifaddr *))
1955                 carp_grow_ifas(sc);
1956
1957         switch (ifa->ifa_addr->sa_family) {
1958 #ifdef INET
1959         case AF_INET:
1960                 cif->cif_naddrs++;
1961                 sc->sc_naddrs++;
1962                 break;
1963 #endif
1964 #ifdef INET6
1965         case AF_INET6:
1966                 cif->cif_naddrs6++;
1967                 sc->sc_naddrs6++;
1968                 break;
1969 #endif
1970         }
1971
1972         ifa_ref(ifa);
1973
1974         CARP_LOCK(sc);
1975         sc->sc_ifas[index - 1] = ifa;
1976         ifa->ifa_carp = sc;
1977         carp_hmac_prepare(sc);
1978         carp_sc_state(sc);
1979         CARP_UNLOCK(sc);
1980
1981         sx_xunlock(&carp_sx);
1982
1983         return (0);
1984 }
1985
1986 void
1987 carp_detach(struct ifaddr *ifa, bool keep_cif)
1988 {
1989         struct ifnet *ifp = ifa->ifa_ifp;
1990         struct carp_if *cif = ifp->if_carp;
1991         struct carp_softc *sc = ifa->ifa_carp;
1992         int i, index;
1993
1994         KASSERT(sc != NULL, ("%s: %p not attached", __func__, ifa));
1995
1996         sx_xlock(&carp_sx);
1997
1998         CARP_LOCK(sc);
1999         /* Shift array. */
2000         index = sc->sc_naddrs + sc->sc_naddrs6;
2001         for (i = 0; i < index; i++)
2002                 if (sc->sc_ifas[i] == ifa)
2003                         break;
2004         KASSERT(i < index, ("%s: %p no backref", __func__, ifa));
2005         for (; i < index - 1; i++)
2006                 sc->sc_ifas[i] = sc->sc_ifas[i+1];
2007         sc->sc_ifas[index - 1] = NULL;
2008
2009         switch (ifa->ifa_addr->sa_family) {
2010 #ifdef INET
2011         case AF_INET:
2012                 cif->cif_naddrs--;
2013                 sc->sc_naddrs--;
2014                 break;
2015 #endif
2016 #ifdef INET6
2017         case AF_INET6:
2018                 cif->cif_naddrs6--;
2019                 sc->sc_naddrs6--;
2020                 break;
2021 #endif
2022         }
2023
2024         carp_ifa_delroute(ifa);
2025         carp_multicast_cleanup(cif, ifa->ifa_addr->sa_family);
2026
2027         ifa->ifa_carp = NULL;
2028         ifa_free(ifa);
2029
2030         carp_hmac_prepare(sc);
2031         carp_sc_state(sc);
2032
2033         if (!keep_cif && sc->sc_naddrs == 0 && sc->sc_naddrs6 == 0)
2034                 carp_destroy(sc);
2035         else
2036                 CARP_UNLOCK(sc);
2037
2038         if (!keep_cif)
2039                 CIF_FREE(cif);
2040
2041         sx_xunlock(&carp_sx);
2042 }
2043
2044 static void
2045 carp_set_state(struct carp_softc *sc, int state, const char *reason)
2046 {
2047
2048         CARP_LOCK_ASSERT(sc);
2049
2050         if (sc->sc_state != state) {
2051                 const char *carp_states[] = { CARP_STATES };
2052                 char subsys[IFNAMSIZ+5];
2053
2054                 snprintf(subsys, IFNAMSIZ+5, "%u@%s", sc->sc_vhid,
2055                     sc->sc_carpdev->if_xname);
2056
2057                 CARP_LOG("%s: %s -> %s (%s)\n", subsys,
2058                     carp_states[sc->sc_state], carp_states[state], reason);
2059
2060                 sc->sc_state = state;
2061
2062                 devctl_notify("CARP", subsys, carp_states[state], NULL);
2063         }
2064 }
2065
2066 static void
2067 carp_linkstate(struct ifnet *ifp)
2068 {
2069         struct carp_softc *sc;
2070
2071         CIF_LOCK(ifp->if_carp);
2072         IFNET_FOREACH_CARP(ifp, sc) {
2073                 CARP_LOCK(sc);
2074                 carp_sc_state(sc);
2075                 CARP_UNLOCK(sc);
2076         }
2077         CIF_UNLOCK(ifp->if_carp);
2078 }
2079
2080 static void
2081 carp_sc_state(struct carp_softc *sc)
2082 {
2083
2084         CARP_LOCK_ASSERT(sc);
2085
2086         if (sc->sc_carpdev->if_link_state != LINK_STATE_UP ||
2087             !(sc->sc_carpdev->if_flags & IFF_UP) ||
2088             !V_carp_allow) {
2089                 callout_stop(&sc->sc_ad_tmo);
2090 #ifdef INET
2091                 callout_stop(&sc->sc_md_tmo);
2092 #endif
2093 #ifdef INET6
2094                 callout_stop(&sc->sc_md6_tmo);
2095 #endif
2096                 carp_set_state(sc, INIT, "hardware interface down");
2097                 carp_setrun(sc, 0);
2098                 carp_delroute(sc);
2099                 if (!sc->sc_suppress)
2100                         carp_demote_adj(V_carp_ifdown_adj, "interface down");
2101                 sc->sc_suppress = 1;
2102         } else {
2103                 carp_set_state(sc, INIT, "hardware interface up");
2104                 carp_setrun(sc, 0);
2105                 if (sc->sc_suppress)
2106                         carp_demote_adj(-V_carp_ifdown_adj, "interface up");
2107                 sc->sc_suppress = 0;
2108         }
2109 }
2110
2111 static void
2112 carp_demote_adj(int adj, char *reason)
2113 {
2114         atomic_add_int(&V_carp_demotion, adj);
2115         CARP_LOG("demoted by %d to %d (%s)\n", adj, V_carp_demotion, reason);
2116         taskqueue_enqueue(taskqueue_swi, &carp_sendall_task);
2117 }
2118
2119 static int
2120 carp_allow_sysctl(SYSCTL_HANDLER_ARGS)
2121 {
2122         int new, error;
2123         struct carp_softc *sc;
2124
2125         new = V_carp_allow;
2126         error = sysctl_handle_int(oidp, &new, 0, req);
2127         if (error || !req->newptr)
2128                 return (error);
2129
2130         if (V_carp_allow != new) {
2131                 V_carp_allow = new;
2132
2133                 mtx_lock(&carp_mtx);
2134                 LIST_FOREACH(sc, &carp_list, sc_next) {
2135                         CARP_LOCK(sc);
2136                         if (curvnet == sc->sc_carpdev->if_vnet)
2137                                 carp_sc_state(sc);
2138                         CARP_UNLOCK(sc);
2139                 }
2140                 mtx_unlock(&carp_mtx);
2141         }
2142
2143         return (0);
2144 }
2145
2146 static int
2147 carp_dscp_sysctl(SYSCTL_HANDLER_ARGS)
2148 {
2149         int new, error;
2150
2151         new = V_carp_dscp;
2152         error = sysctl_handle_int(oidp, &new, 0, req);
2153         if (error || !req->newptr)
2154                 return (error);
2155
2156         if (new < 0 || new > 63)
2157                 return (EINVAL);
2158
2159         V_carp_dscp = new;
2160
2161         return (0);
2162 }
2163
2164 static int
2165 carp_demote_adj_sysctl(SYSCTL_HANDLER_ARGS)
2166 {
2167         int new, error;
2168
2169         new = V_carp_demotion;
2170         error = sysctl_handle_int(oidp, &new, 0, req);
2171         if (error || !req->newptr)
2172                 return (error);
2173
2174         carp_demote_adj(new, "sysctl");
2175
2176         return (0);
2177 }
2178
2179 #ifdef INET
2180 extern  struct domain inetdomain;
2181 static struct protosw in_carp_protosw = {
2182         .pr_type =              SOCK_RAW,
2183         .pr_domain =            &inetdomain,
2184         .pr_protocol =          IPPROTO_CARP,
2185         .pr_flags =             PR_ATOMIC|PR_ADDR,
2186         .pr_input =             carp_input,
2187         .pr_output =            rip_output,
2188         .pr_ctloutput =         rip_ctloutput,
2189         .pr_usrreqs =           &rip_usrreqs
2190 };
2191 #endif
2192
2193 #ifdef INET6
2194 extern  struct domain inet6domain;
2195 static struct protosw in6_carp_protosw = {
2196         .pr_type =              SOCK_RAW,
2197         .pr_domain =            &inet6domain,
2198         .pr_protocol =          IPPROTO_CARP,
2199         .pr_flags =             PR_ATOMIC|PR_ADDR,
2200         .pr_input =             carp6_input,
2201         .pr_output =            rip6_output,
2202         .pr_ctloutput =         rip6_ctloutput,
2203         .pr_usrreqs =           &rip6_usrreqs
2204 };
2205 #endif
2206
2207 static void
2208 carp_mod_cleanup(void)
2209 {
2210
2211 #ifdef INET
2212         if (proto_reg[CARP_INET] == 0) {
2213                 (void)ipproto_unregister(IPPROTO_CARP);
2214                 pf_proto_unregister(PF_INET, IPPROTO_CARP, SOCK_RAW);
2215                 proto_reg[CARP_INET] = -1;
2216         }
2217         carp_iamatch_p = NULL;
2218 #endif
2219 #ifdef INET6
2220         if (proto_reg[CARP_INET6] == 0) {
2221                 (void)ip6proto_unregister(IPPROTO_CARP);
2222                 pf_proto_unregister(PF_INET6, IPPROTO_CARP, SOCK_RAW);
2223                 proto_reg[CARP_INET6] = -1;
2224         }
2225         carp_iamatch6_p = NULL;
2226         carp_macmatch6_p = NULL;
2227 #endif
2228         carp_ioctl_p = NULL;
2229         carp_attach_p = NULL;
2230         carp_detach_p = NULL;
2231         carp_get_vhid_p = NULL;
2232         carp_linkstate_p = NULL;
2233         carp_forus_p = NULL;
2234         carp_output_p = NULL;
2235         carp_demote_adj_p = NULL;
2236         carp_master_p = NULL;
2237         mtx_unlock(&carp_mtx);
2238         taskqueue_drain(taskqueue_swi, &carp_sendall_task);
2239         mtx_destroy(&carp_mtx);
2240         sx_destroy(&carp_sx);
2241 }
2242
2243 static void
2244 ipcarp_sysinit(void)
2245 {
2246
2247         /* Load allow as tunable so to postpone carp start after module load */
2248         TUNABLE_INT_FETCH("net.inet.carp.allow", &V_carp_allow);
2249 }
2250 VNET_SYSINIT(ip_carp, SI_SUB_PROTO_DOMAIN, SI_ORDER_ANY, ipcarp_sysinit, NULL);
2251
2252 static int
2253 carp_mod_load(void)
2254 {
2255         int err;
2256
2257         mtx_init(&carp_mtx, "carp_mtx", NULL, MTX_DEF);
2258         sx_init(&carp_sx, "carp_sx");
2259         LIST_INIT(&carp_list);
2260         carp_get_vhid_p = carp_get_vhid;
2261         carp_forus_p = carp_forus;
2262         carp_output_p = carp_output;
2263         carp_linkstate_p = carp_linkstate;
2264         carp_ioctl_p = carp_ioctl;
2265         carp_attach_p = carp_attach;
2266         carp_detach_p = carp_detach;
2267         carp_demote_adj_p = carp_demote_adj;
2268         carp_master_p = carp_master;
2269 #ifdef INET6
2270         carp_iamatch6_p = carp_iamatch6;
2271         carp_macmatch6_p = carp_macmatch6;
2272         proto_reg[CARP_INET6] = pf_proto_register(PF_INET6,
2273             (struct protosw *)&in6_carp_protosw);
2274         if (proto_reg[CARP_INET6]) {
2275                 printf("carp: error %d attaching to PF_INET6\n",
2276                     proto_reg[CARP_INET6]);
2277                 carp_mod_cleanup();
2278                 return (proto_reg[CARP_INET6]);
2279         }
2280         err = ip6proto_register(IPPROTO_CARP);
2281         if (err) {
2282                 printf("carp: error %d registering with INET6\n", err);
2283                 carp_mod_cleanup();
2284                 return (err);
2285         }
2286 #endif
2287 #ifdef INET
2288         carp_iamatch_p = carp_iamatch;
2289         proto_reg[CARP_INET] = pf_proto_register(PF_INET, &in_carp_protosw);
2290         if (proto_reg[CARP_INET]) {
2291                 printf("carp: error %d attaching to PF_INET\n",
2292                     proto_reg[CARP_INET]);
2293                 carp_mod_cleanup();
2294                 return (proto_reg[CARP_INET]);
2295         }
2296         err = ipproto_register(IPPROTO_CARP);
2297         if (err) {
2298                 printf("carp: error %d registering with INET\n", err);
2299                 carp_mod_cleanup();
2300                 return (err);
2301         }
2302 #endif
2303         return (0);
2304 }
2305
2306 static int
2307 carp_modevent(module_t mod, int type, void *data)
2308 {
2309         switch (type) {
2310         case MOD_LOAD:
2311                 return carp_mod_load();
2312                 /* NOTREACHED */
2313         case MOD_UNLOAD:
2314                 mtx_lock(&carp_mtx);
2315                 if (LIST_EMPTY(&carp_list))
2316                         carp_mod_cleanup();
2317                 else {
2318                         mtx_unlock(&carp_mtx);
2319                         return (EBUSY);
2320                 }
2321                 break;
2322
2323         default:
2324                 return (EINVAL);
2325         }
2326
2327         return (0);
2328 }
2329
2330 static moduledata_t carp_mod = {
2331         "carp",
2332         carp_modevent,
2333         0
2334 };
2335
2336 DECLARE_MODULE(carp, carp_mod, SI_SUB_PROTO_DOMAIN, SI_ORDER_ANY);