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