]> CyberLeo.Net >> Repos - FreeBSD/releng/7.2.git/blob - sys/netinet/ip_mroute.c
Create releng/7.2 from stable/7 in preparation for 7.2-RELEASE.
[FreeBSD/releng/7.2.git] / sys / netinet / ip_mroute.c
1 /*-
2  * Copyright (c) 1989 Stephen Deering
3  * Copyright (c) 1992, 1993
4  *      The Regents of the University of California.  All rights reserved.
5  *
6  * This code is derived from software contributed to Berkeley by
7  * Stephen Deering of Stanford University.
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  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  *      @(#)ip_mroute.c 8.2 (Berkeley) 11/15/93
34  */
35
36 /*
37  * IP multicast forwarding procedures
38  *
39  * Written by David Waitzman, BBN Labs, August 1988.
40  * Modified by Steve Deering, Stanford, February 1989.
41  * Modified by Mark J. Steiglitz, Stanford, May, 1991
42  * Modified by Van Jacobson, LBL, January 1993
43  * Modified by Ajit Thyagarajan, PARC, August 1993
44  * Modified by Bill Fenner, PARC, April 1995
45  * Modified by Ahmed Helmy, SGI, June 1996
46  * Modified by George Edmond Eddy (Rusty), ISI, February 1998
47  * Modified by Pavlin Radoslavov, USC/ISI, May 1998, August 1999, October 2000
48  * Modified by Hitoshi Asaeda, WIDE, August 2000
49  * Modified by Pavlin Radoslavov, ICSI, October 2002
50  *
51  * MROUTING Revision: 3.5
52  * and PIM-SMv2 and PIM-DM support, advanced API support,
53  * bandwidth metering and signaling
54  */
55
56 #include <sys/cdefs.h>
57 __FBSDID("$FreeBSD$");
58
59 #include "opt_inet.h"
60 #include "opt_inet6.h"
61 #include "opt_mac.h"
62 #include "opt_mrouting.h"
63
64 #define _PIM_VT 1
65
66 #include <sys/param.h>
67 #include <sys/kernel.h>
68 #include <sys/lock.h>
69 #include <sys/malloc.h>
70 #include <sys/mbuf.h>
71 #include <sys/module.h>
72 #include <sys/priv.h>
73 #include <sys/protosw.h>
74 #include <sys/signalvar.h>
75 #include <sys/socket.h>
76 #include <sys/socketvar.h>
77 #include <sys/sockio.h>
78 #include <sys/sx.h>
79 #include <sys/sysctl.h>
80 #include <sys/syslog.h>
81 #include <sys/systm.h>
82 #include <sys/time.h>
83 #include <net/if.h>
84 #include <net/netisr.h>
85 #include <net/route.h>
86 #include <netinet/in.h>
87 #include <netinet/igmp.h>
88 #include <netinet/in_systm.h>
89 #include <netinet/in_var.h>
90 #include <netinet/ip.h>
91 #include <netinet/ip_encap.h>
92 #include <netinet/ip_mroute.h>
93 #include <netinet/ip_var.h>
94 #include <netinet/ip_options.h>
95 #include <netinet/pim.h>
96 #include <netinet/pim_var.h>
97 #include <netinet/udp.h>
98 #ifdef INET6
99 #include <netinet/ip6.h>
100 #include <netinet6/in6_var.h>
101 #include <netinet6/ip6_mroute.h>
102 #include <netinet6/ip6_var.h>
103 #endif
104 #include <machine/in_cksum.h>
105
106 #include <security/mac/mac_framework.h>
107
108 /*
109  * Control debugging code for rsvp and multicast routing code.
110  * Can only set them with the debugger.
111  */
112 static u_int    rsvpdebug;              /* non-zero enables debugging   */
113
114 static u_int    mrtdebug;               /* any set of the flags below   */
115 #define         DEBUG_MFC       0x02
116 #define         DEBUG_FORWARD   0x04
117 #define         DEBUG_EXPIRE    0x08
118 #define         DEBUG_XMIT      0x10
119 #define         DEBUG_PIM       0x20
120
121 #define         VIFI_INVALID    ((vifi_t) -1)
122
123 #define M_HASCL(m)      ((m)->m_flags & M_EXT)
124
125 static MALLOC_DEFINE(M_MRTABLE, "mroutetbl", "multicast routing tables");
126
127 /*
128  * Locking.  We use two locks: one for the virtual interface table and
129  * one for the forwarding table.  These locks may be nested in which case
130  * the VIF lock must always be taken first.  Note that each lock is used
131  * to cover not only the specific data structure but also related data
132  * structures.  It may be better to add more fine-grained locking later;
133  * it's not clear how performance-critical this code is.
134  *
135  * XXX: This module could particularly benefit from being cleaned
136  *      up to use the <sys/queue.h> macros.
137  *
138  */
139
140 static struct mrtstat   mrtstat;
141 SYSCTL_STRUCT(_net_inet_ip, OID_AUTO, mrtstat, CTLFLAG_RW,
142     &mrtstat, mrtstat,
143     "Multicast Routing Statistics (struct mrtstat, netinet/ip_mroute.h)");
144
145 static struct mfc       *mfctable[MFCTBLSIZ];
146 SYSCTL_OPAQUE(_net_inet_ip, OID_AUTO, mfctable, CTLFLAG_RD,
147     &mfctable, sizeof(mfctable), "S,*mfc[MFCTBLSIZ]",
148     "Multicast Forwarding Table (struct *mfc[MFCTBLSIZ], netinet/ip_mroute.h)");
149
150 static struct mtx mrouter_mtx;
151 #define MROUTER_LOCK()          mtx_lock(&mrouter_mtx)
152 #define MROUTER_UNLOCK()        mtx_unlock(&mrouter_mtx)
153 #define MROUTER_LOCK_ASSERT()   mtx_assert(&mrouter_mtx, MA_OWNED)
154 #define MROUTER_LOCK_INIT()     \
155         mtx_init(&mrouter_mtx, "IPv4 multicast forwarding", NULL, MTX_DEF)
156 #define MROUTER_LOCK_DESTROY()  mtx_destroy(&mrouter_mtx)
157
158 static struct mtx mfc_mtx;
159 #define MFC_LOCK()      mtx_lock(&mfc_mtx)
160 #define MFC_UNLOCK()    mtx_unlock(&mfc_mtx)
161 #define MFC_LOCK_ASSERT()       mtx_assert(&mfc_mtx, MA_OWNED)
162 #define MFC_LOCK_INIT() mtx_init(&mfc_mtx, "mroute mfc table", NULL, MTX_DEF)
163 #define MFC_LOCK_DESTROY()      mtx_destroy(&mfc_mtx)
164
165 static struct vif       viftable[MAXVIFS];
166 SYSCTL_OPAQUE(_net_inet_ip, OID_AUTO, viftable, CTLFLAG_RD,
167     &viftable, sizeof(viftable), "S,vif[MAXVIFS]",
168     "Multicast Virtual Interfaces (struct vif[MAXVIFS], netinet/ip_mroute.h)");
169
170 static struct mtx vif_mtx;
171 #define VIF_LOCK()      mtx_lock(&vif_mtx)
172 #define VIF_UNLOCK()    mtx_unlock(&vif_mtx)
173 #define VIF_LOCK_ASSERT()       mtx_assert(&vif_mtx, MA_OWNED)
174 #define VIF_LOCK_INIT() mtx_init(&vif_mtx, "mroute vif table", NULL, MTX_DEF)
175 #define VIF_LOCK_DESTROY()      mtx_destroy(&vif_mtx)
176
177 static u_char           nexpire[MFCTBLSIZ];
178
179 static eventhandler_tag if_detach_event_tag = NULL;
180
181 static struct callout expire_upcalls_ch;
182
183 #define         EXPIRE_TIMEOUT  (hz / 4)        /* 4x / second          */
184 #define         UPCALL_EXPIRE   6               /* number of timeouts   */
185
186 #define ENCAP_TTL 64
187
188 /*
189  * Bandwidth meter variables and constants
190  */
191 static MALLOC_DEFINE(M_BWMETER, "bwmeter", "multicast upcall bw meters");
192 /*
193  * Pending timeouts are stored in a hash table, the key being the
194  * expiration time. Periodically, the entries are analysed and processed.
195  */
196 #define BW_METER_BUCKETS        1024
197 static struct bw_meter *bw_meter_timers[BW_METER_BUCKETS];
198 static struct callout bw_meter_ch;
199 #define BW_METER_PERIOD (hz)            /* periodical handling of bw meters */
200
201 /*
202  * Pending upcalls are stored in a vector which is flushed when
203  * full, or periodically
204  */
205 static struct bw_upcall bw_upcalls[BW_UPCALLS_MAX];
206 static u_int    bw_upcalls_n; /* # of pending upcalls */
207 static struct callout bw_upcalls_ch;
208 #define BW_UPCALLS_PERIOD (hz)          /* periodical flush of bw upcalls */
209
210 static struct pimstat pimstat;
211
212 SYSCTL_NODE(_net_inet, IPPROTO_PIM, pim, CTLFLAG_RW, 0, "PIM");
213 SYSCTL_STRUCT(_net_inet_pim, PIMCTL_STATS, stats, CTLFLAG_RD,
214     &pimstat, pimstat,
215     "PIM Statistics (struct pimstat, netinet/pim_var.h)");
216
217 static u_long   pim_squelch_wholepkt = 0;
218 SYSCTL_ULONG(_net_inet_pim, OID_AUTO, squelch_wholepkt, CTLFLAG_RW,
219     &pim_squelch_wholepkt, 0,
220     "Disable IGMP_WHOLEPKT notifications if rendezvous point is unspecified");
221
222 extern  struct domain inetdomain;
223 struct protosw in_pim_protosw = {
224         .pr_type =              SOCK_RAW,
225         .pr_domain =            &inetdomain,
226         .pr_protocol =          IPPROTO_PIM,
227         .pr_flags =             PR_ATOMIC|PR_ADDR|PR_LASTHDR,
228         .pr_input =             pim_input,
229         .pr_output =            (pr_output_t*)rip_output,
230         .pr_ctloutput =         rip_ctloutput,
231         .pr_usrreqs =           &rip_usrreqs
232 };
233 static const struct encaptab *pim_encap_cookie;
234
235 #ifdef INET6
236 /* ip6_mroute.c glue */
237 extern struct in6_protosw in6_pim_protosw;
238 static const struct encaptab *pim6_encap_cookie;
239
240 extern int X_ip6_mrouter_set(struct socket *, struct sockopt *);
241 extern int X_ip6_mrouter_get(struct socket *, struct sockopt *);
242 extern int X_ip6_mrouter_done(void);
243 extern int X_ip6_mforward(struct ip6_hdr *, struct ifnet *, struct mbuf *);
244 extern int X_mrt6_ioctl(int, caddr_t);
245 #endif
246
247 static int pim_encapcheck(const struct mbuf *, int, int, void *);
248
249 /*
250  * Note: the PIM Register encapsulation adds the following in front of a
251  * data packet:
252  *
253  * struct pim_encap_hdr {
254  *    struct ip ip;
255  *    struct pim_encap_pimhdr  pim;
256  * }
257  *
258  */
259
260 struct pim_encap_pimhdr {
261         struct pim pim;
262         uint32_t   flags;
263 };
264
265 static struct ip pim_encap_iphdr = {
266 #if BYTE_ORDER == LITTLE_ENDIAN
267         sizeof(struct ip) >> 2,
268         IPVERSION,
269 #else
270         IPVERSION,
271         sizeof(struct ip) >> 2,
272 #endif
273         0,                      /* tos */
274         sizeof(struct ip),      /* total length */
275         0,                      /* id */
276         0,                      /* frag offset */
277         ENCAP_TTL,
278         IPPROTO_PIM,
279         0,                      /* checksum */
280 };
281
282 static struct pim_encap_pimhdr pim_encap_pimhdr = {
283     {
284         PIM_MAKE_VT(PIM_VERSION, PIM_REGISTER), /* PIM vers and message type */
285         0,                      /* reserved */
286         0,                      /* checksum */
287     },
288     0                           /* flags */
289 };
290
291 static struct ifnet multicast_register_if;
292 static vifi_t reg_vif_num = VIFI_INVALID;
293
294 /*
295  * Private variables.
296  */
297 static vifi_t      numvifs;
298
299 static u_long   X_ip_mcast_src(int vifi);
300 static int      X_ip_mforward(struct ip *ip, struct ifnet *ifp,
301                         struct mbuf *m, struct ip_moptions *imo);
302 static int      X_ip_mrouter_done(void);
303 static int      X_ip_mrouter_get(struct socket *so, struct sockopt *m);
304 static int      X_ip_mrouter_set(struct socket *so, struct sockopt *m);
305 static int      X_legal_vif_num(int vif);
306 static int      X_mrt_ioctl(int cmd, caddr_t data, int fibnum);
307
308 static int get_sg_cnt(struct sioc_sg_req *);
309 static int get_vif_cnt(struct sioc_vif_req *);
310 static void if_detached_event(void *arg __unused, struct ifnet *);
311 static int ip_mrouter_init(struct socket *, int);
312 static int add_vif(struct vifctl *);
313 static int del_vif_locked(vifi_t);
314 static int del_vif(vifi_t);
315 static int add_mfc(struct mfcctl2 *);
316 static int del_mfc(struct mfcctl2 *);
317 static int set_api_config(uint32_t *); /* chose API capabilities */
318 static int socket_send(struct socket *, struct mbuf *, struct sockaddr_in *);
319 static int set_assert(int);
320 static void expire_upcalls(void *);
321 static int ip_mdq(struct mbuf *, struct ifnet *, struct mfc *, vifi_t);
322 static void phyint_send(struct ip *, struct vif *, struct mbuf *);
323 static void send_packet(struct vif *, struct mbuf *);
324
325 /*
326  * Bandwidth monitoring
327  */
328 static void free_bw_list(struct bw_meter *list);
329 static int add_bw_upcall(struct bw_upcall *);
330 static int del_bw_upcall(struct bw_upcall *);
331 static void bw_meter_receive_packet(struct bw_meter *x, int plen,
332                 struct timeval *nowp);
333 static void bw_meter_prepare_upcall(struct bw_meter *x, struct timeval *nowp);
334 static void bw_upcalls_send(void);
335 static void schedule_bw_meter(struct bw_meter *x, struct timeval *nowp);
336 static void unschedule_bw_meter(struct bw_meter *x);
337 static void bw_meter_process(void);
338 static void expire_bw_upcalls_send(void *);
339 static void expire_bw_meter_process(void *);
340
341 static int pim_register_send(struct ip *, struct vif *,
342                 struct mbuf *, struct mfc *);
343 static int pim_register_send_rp(struct ip *, struct vif *,
344                 struct mbuf *, struct mfc *);
345 static int pim_register_send_upcall(struct ip *, struct vif *,
346                 struct mbuf *, struct mfc *);
347 static struct mbuf *pim_register_prepare(struct ip *, struct mbuf *);
348
349 /*
350  * whether or not special PIM assert processing is enabled.
351  */
352 static int pim_assert;
353 /*
354  * Rate limit for assert notification messages, in usec
355  */
356 #define ASSERT_MSG_TIME         3000000
357
358 /*
359  * Kernel multicast routing API capabilities and setup.
360  * If more API capabilities are added to the kernel, they should be
361  * recorded in `mrt_api_support'.
362  */
363 static const uint32_t mrt_api_support = (MRT_MFC_FLAGS_DISABLE_WRONGVIF |
364                                          MRT_MFC_FLAGS_BORDER_VIF |
365                                          MRT_MFC_RP |
366                                          MRT_MFC_BW_UPCALL);
367 static uint32_t mrt_api_config = 0;
368
369 /*
370  * Hash function for a source, group entry
371  */
372 #define MFCHASH(a, g) MFCHASHMOD(((a) >> 20) ^ ((a) >> 10) ^ (a) ^ \
373                         ((g) >> 20) ^ ((g) >> 10) ^ (g))
374
375 /*
376  * Find a route for a given origin IP address and Multicast group address
377  * Statistics are updated by the caller if needed
378  * (mrtstat.mrts_mfc_lookups and mrtstat.mrts_mfc_misses)
379  */
380 static struct mfc *
381 mfc_find(in_addr_t o, in_addr_t g)
382 {
383     struct mfc *rt;
384
385     MFC_LOCK_ASSERT();
386
387     for (rt = mfctable[MFCHASH(o,g)]; rt; rt = rt->mfc_next)
388         if ((rt->mfc_origin.s_addr == o) &&
389                 (rt->mfc_mcastgrp.s_addr == g) && (rt->mfc_stall == NULL))
390             break;
391     return rt;
392 }
393
394 /*
395  * Macros to compute elapsed time efficiently
396  * Borrowed from Van Jacobson's scheduling code
397  */
398 #define TV_DELTA(a, b, delta) {                                 \
399         int xxs;                                                \
400         delta = (a).tv_usec - (b).tv_usec;                      \
401         if ((xxs = (a).tv_sec - (b).tv_sec)) {                  \
402                 switch (xxs) {                                  \
403                 case 2:                                         \
404                       delta += 1000000;                         \
405                       /* FALLTHROUGH */                         \
406                 case 1:                                         \
407                       delta += 1000000;                         \
408                       break;                                    \
409                 default:                                        \
410                       delta += (1000000 * xxs);                 \
411                 }                                               \
412         }                                                       \
413 }
414
415 #define TV_LT(a, b) (((a).tv_usec < (b).tv_usec && \
416               (a).tv_sec <= (b).tv_sec) || (a).tv_sec < (b).tv_sec)
417
418 /*
419  * Handle MRT setsockopt commands to modify the multicast routing tables.
420  */
421 static int
422 X_ip_mrouter_set(struct socket *so, struct sockopt *sopt)
423 {
424     int error, optval;
425     vifi_t      vifi;
426     struct      vifctl vifc;
427     struct      mfcctl2 mfc;
428     struct      bw_upcall bw_upcall;
429     uint32_t    i;
430
431     if (so != ip_mrouter && sopt->sopt_name != MRT_INIT)
432         return EPERM;
433
434     error = 0;
435     switch (sopt->sopt_name) {
436     case MRT_INIT:
437         error = sooptcopyin(sopt, &optval, sizeof optval, sizeof optval);
438         if (error)
439             break;
440         error = ip_mrouter_init(so, optval);
441         break;
442
443     case MRT_DONE:
444         error = ip_mrouter_done();
445         break;
446
447     case MRT_ADD_VIF:
448         error = sooptcopyin(sopt, &vifc, sizeof vifc, sizeof vifc);
449         if (error)
450             break;
451         error = add_vif(&vifc);
452         break;
453
454     case MRT_DEL_VIF:
455         error = sooptcopyin(sopt, &vifi, sizeof vifi, sizeof vifi);
456         if (error)
457             break;
458         error = del_vif(vifi);
459         break;
460
461     case MRT_ADD_MFC:
462     case MRT_DEL_MFC:
463         /*
464          * select data size depending on API version.
465          */
466         if (sopt->sopt_name == MRT_ADD_MFC &&
467                 mrt_api_config & MRT_API_FLAGS_ALL) {
468             error = sooptcopyin(sopt, &mfc, sizeof(struct mfcctl2),
469                                 sizeof(struct mfcctl2));
470         } else {
471             error = sooptcopyin(sopt, &mfc, sizeof(struct mfcctl),
472                                 sizeof(struct mfcctl));
473             bzero((caddr_t)&mfc + sizeof(struct mfcctl),
474                         sizeof(mfc) - sizeof(struct mfcctl));
475         }
476         if (error)
477             break;
478         if (sopt->sopt_name == MRT_ADD_MFC)
479             error = add_mfc(&mfc);
480         else
481             error = del_mfc(&mfc);
482         break;
483
484     case MRT_ASSERT:
485         error = sooptcopyin(sopt, &optval, sizeof optval, sizeof optval);
486         if (error)
487             break;
488         set_assert(optval);
489         break;
490
491     case MRT_API_CONFIG:
492         error = sooptcopyin(sopt, &i, sizeof i, sizeof i);
493         if (!error)
494             error = set_api_config(&i);
495         if (!error)
496             error = sooptcopyout(sopt, &i, sizeof i);
497         break;
498
499     case MRT_ADD_BW_UPCALL:
500     case MRT_DEL_BW_UPCALL:
501         error = sooptcopyin(sopt, &bw_upcall, sizeof bw_upcall,
502                                 sizeof bw_upcall);
503         if (error)
504             break;
505         if (sopt->sopt_name == MRT_ADD_BW_UPCALL)
506             error = add_bw_upcall(&bw_upcall);
507         else
508             error = del_bw_upcall(&bw_upcall);
509         break;
510
511     default:
512         error = EOPNOTSUPP;
513         break;
514     }
515     return error;
516 }
517
518 /*
519  * Handle MRT getsockopt commands
520  */
521 static int
522 X_ip_mrouter_get(struct socket *so, struct sockopt *sopt)
523 {
524     int error;
525     static int version = 0x0305; /* !!! why is this here? XXX */
526
527     switch (sopt->sopt_name) {
528     case MRT_VERSION:
529         error = sooptcopyout(sopt, &version, sizeof version);
530         break;
531
532     case MRT_ASSERT:
533         error = sooptcopyout(sopt, &pim_assert, sizeof pim_assert);
534         break;
535
536     case MRT_API_SUPPORT:
537         error = sooptcopyout(sopt, &mrt_api_support, sizeof mrt_api_support);
538         break;
539
540     case MRT_API_CONFIG:
541         error = sooptcopyout(sopt, &mrt_api_config, sizeof mrt_api_config);
542         break;
543
544     default:
545         error = EOPNOTSUPP;
546         break;
547     }
548     return error;
549 }
550
551 /*
552  * Handle ioctl commands to obtain information from the cache
553  */
554 static int
555 X_mrt_ioctl(int cmd, caddr_t data, int fibnum)
556 {
557     int error = 0;
558
559     /*
560      * Currently the only function calling this ioctl routine is rtioctl().
561      * Typically, only root can create the raw socket in order to execute
562      * this ioctl method, however the request might be coming from a prison
563      */
564     error = priv_check(curthread, PRIV_NETINET_MROUTE);
565     if (error)
566         return (error);
567     switch (cmd) {
568     case (SIOCGETVIFCNT):
569         error = get_vif_cnt((struct sioc_vif_req *)data);
570         break;
571
572     case (SIOCGETSGCNT):
573         error = get_sg_cnt((struct sioc_sg_req *)data);
574         break;
575
576     default:
577         error = EINVAL;
578         break;
579     }
580     return error;
581 }
582
583 /*
584  * returns the packet, byte, rpf-failure count for the source group provided
585  */
586 static int
587 get_sg_cnt(struct sioc_sg_req *req)
588 {
589     struct mfc *rt;
590
591     MFC_LOCK();
592     rt = mfc_find(req->src.s_addr, req->grp.s_addr);
593     if (rt == NULL) {
594         MFC_UNLOCK();
595         req->pktcnt = req->bytecnt = req->wrong_if = 0xffffffff;
596         return EADDRNOTAVAIL;
597     }
598     req->pktcnt = rt->mfc_pkt_cnt;
599     req->bytecnt = rt->mfc_byte_cnt;
600     req->wrong_if = rt->mfc_wrong_if;
601     MFC_UNLOCK();
602     return 0;
603 }
604
605 /*
606  * returns the input and output packet and byte counts on the vif provided
607  */
608 static int
609 get_vif_cnt(struct sioc_vif_req *req)
610 {
611     vifi_t vifi = req->vifi;
612
613     VIF_LOCK();
614     if (vifi >= numvifs) {
615         VIF_UNLOCK();
616         return EINVAL;
617     }
618
619     req->icount = viftable[vifi].v_pkt_in;
620     req->ocount = viftable[vifi].v_pkt_out;
621     req->ibytes = viftable[vifi].v_bytes_in;
622     req->obytes = viftable[vifi].v_bytes_out;
623     VIF_UNLOCK();
624
625     return 0;
626 }
627
628 static void
629 ip_mrouter_reset(void)
630 {
631     bzero((caddr_t)mfctable, sizeof(mfctable));
632     bzero((caddr_t)nexpire, sizeof(nexpire));
633
634     pim_assert = 0;
635     mrt_api_config = 0;
636
637     callout_init(&expire_upcalls_ch, CALLOUT_MPSAFE);
638
639     bw_upcalls_n = 0;
640     bzero((caddr_t)bw_meter_timers, sizeof(bw_meter_timers));
641     callout_init(&bw_upcalls_ch, CALLOUT_MPSAFE);
642     callout_init(&bw_meter_ch, CALLOUT_MPSAFE);
643 }
644
645 static void
646 if_detached_event(void *arg __unused, struct ifnet *ifp)
647 {
648     vifi_t vifi;
649     int i;
650     struct mfc *mfc;
651     struct mfc *nmfc;
652     struct mfc **ppmfc; /* Pointer to previous node's next-pointer */
653     struct rtdetq *pq;
654     struct rtdetq *npq;
655
656     MROUTER_LOCK();
657     if (ip_mrouter == NULL) {
658         MROUTER_UNLOCK();
659     }
660
661     /*
662      * Tear down multicast forwarder state associated with this ifnet.
663      * 1. Walk the vif list, matching vifs against this ifnet.
664      * 2. Walk the multicast forwarding cache (mfc) looking for
665      *    inner matches with this vif's index.
666      * 3. Free any pending mbufs for this mfc.
667      * 4. Free the associated mfc entry and state associated with this vif.
668      *    Be very careful about unlinking from a singly-linked list whose
669      *    "head node" is a pointer in a simple array.
670      * 5. Free vif state. This should disable ALLMULTI on the interface.
671      */
672     VIF_LOCK();
673     MFC_LOCK();
674     for (vifi = 0; vifi < numvifs; vifi++) {
675         if (viftable[vifi].v_ifp != ifp)
676                 continue;
677         for (i = 0; i < MFCTBLSIZ; i++) {
678             ppmfc = &mfctable[i];
679             for (mfc = mfctable[i]; mfc != NULL; ) {
680                 nmfc = mfc->mfc_next;
681                 if (mfc->mfc_parent == vifi) {
682                     for (pq = mfc->mfc_stall; pq != NULL; ) {
683                         npq = pq->next;
684                         m_freem(pq->m);
685                         free(pq, M_MRTABLE);
686                         pq = npq;
687                     }
688                     free_bw_list(mfc->mfc_bw_meter);
689                     free(mfc, M_MRTABLE);
690                     *ppmfc = nmfc;
691                 } else {
692                     ppmfc = &mfc->mfc_next;
693                 }
694                 mfc = nmfc;
695             }
696         }
697         del_vif_locked(vifi);
698     }
699     MFC_UNLOCK();
700     VIF_UNLOCK();
701
702     MROUTER_UNLOCK();
703 }
704                         
705 /*
706  * Enable multicast routing
707  */
708 static int
709 ip_mrouter_init(struct socket *so, int version)
710 {
711     if (mrtdebug)
712         log(LOG_DEBUG, "ip_mrouter_init: so_type = %d, pr_protocol = %d\n",
713             so->so_type, so->so_proto->pr_protocol);
714
715     if (so->so_type != SOCK_RAW || so->so_proto->pr_protocol != IPPROTO_IGMP)
716         return EOPNOTSUPP;
717
718     if (version != 1)
719         return ENOPROTOOPT;
720
721     MROUTER_LOCK();
722
723     if (ip_mrouter != NULL) {
724         MROUTER_UNLOCK();
725         return EADDRINUSE;
726     }
727
728     if_detach_event_tag = EVENTHANDLER_REGISTER(ifnet_departure_event, 
729         if_detached_event, NULL, EVENTHANDLER_PRI_ANY);
730     if (if_detach_event_tag == NULL) {
731         MROUTER_UNLOCK();
732         return (ENOMEM);
733     }
734
735     callout_reset(&expire_upcalls_ch, EXPIRE_TIMEOUT, expire_upcalls, NULL);
736
737     callout_reset(&bw_upcalls_ch, BW_UPCALLS_PERIOD,
738         expire_bw_upcalls_send, NULL);
739     callout_reset(&bw_meter_ch, BW_METER_PERIOD, expire_bw_meter_process, NULL);
740
741     ip_mrouter = so;
742
743     MROUTER_UNLOCK();
744
745     if (mrtdebug)
746         log(LOG_DEBUG, "ip_mrouter_init\n");
747
748     return 0;
749 }
750
751 /*
752  * Disable multicast routing
753  */
754 static int
755 X_ip_mrouter_done(void)
756 {
757     vifi_t vifi;
758     int i;
759     struct ifnet *ifp;
760     struct ifreq ifr;
761     struct mfc *rt;
762     struct rtdetq *rte;
763
764     MROUTER_LOCK();
765
766     if (ip_mrouter == NULL) {
767         MROUTER_UNLOCK();
768         return EINVAL;
769     }
770
771     /*
772      * Detach/disable hooks to the reset of the system.
773      */
774     ip_mrouter = NULL;
775     mrt_api_config = 0;
776
777     VIF_LOCK();
778     /*
779      * For each phyint in use, disable promiscuous reception of all IP
780      * multicasts.
781      */
782     for (vifi = 0; vifi < numvifs; vifi++) {
783         if (viftable[vifi].v_lcl_addr.s_addr != 0 &&
784                 !(viftable[vifi].v_flags & (VIFF_TUNNEL | VIFF_REGISTER))) {
785             struct sockaddr_in *so = (struct sockaddr_in *)&(ifr.ifr_addr);
786
787             so->sin_len = sizeof(struct sockaddr_in);
788             so->sin_family = AF_INET;
789             so->sin_addr.s_addr = INADDR_ANY;
790             ifp = viftable[vifi].v_ifp;
791             if_allmulti(ifp, 0);
792         }
793     }
794     bzero((caddr_t)viftable, sizeof(viftable));
795     numvifs = 0;
796     pim_assert = 0;
797     VIF_UNLOCK();
798     EVENTHANDLER_DEREGISTER(ifnet_departure_event, if_detach_event_tag);
799
800     /*
801      * Free all multicast forwarding cache entries.
802      */
803     callout_stop(&expire_upcalls_ch);
804     callout_stop(&bw_upcalls_ch);
805     callout_stop(&bw_meter_ch);
806
807     MFC_LOCK();
808     for (i = 0; i < MFCTBLSIZ; i++) {
809         for (rt = mfctable[i]; rt != NULL; ) {
810             struct mfc *nr = rt->mfc_next;
811
812             for (rte = rt->mfc_stall; rte != NULL; ) {
813                 struct rtdetq *n = rte->next;
814
815                 m_freem(rte->m);
816                 free(rte, M_MRTABLE);
817                 rte = n;
818             }
819             free_bw_list(rt->mfc_bw_meter);
820             free(rt, M_MRTABLE);
821             rt = nr;
822         }
823     }
824     bzero((caddr_t)mfctable, sizeof(mfctable));
825     bzero((caddr_t)nexpire, sizeof(nexpire));
826     bw_upcalls_n = 0;
827     bzero(bw_meter_timers, sizeof(bw_meter_timers));
828     MFC_UNLOCK();
829
830     reg_vif_num = VIFI_INVALID;
831
832     MROUTER_UNLOCK();
833
834     if (mrtdebug)
835         log(LOG_DEBUG, "ip_mrouter_done\n");
836
837     return 0;
838 }
839
840 /*
841  * Set PIM assert processing global
842  */
843 static int
844 set_assert(int i)
845 {
846     if ((i != 1) && (i != 0))
847         return EINVAL;
848
849     pim_assert = i;
850
851     return 0;
852 }
853
854 /*
855  * Configure API capabilities
856  */
857 int
858 set_api_config(uint32_t *apival)
859 {
860     int i;
861
862     /*
863      * We can set the API capabilities only if it is the first operation
864      * after MRT_INIT. I.e.:
865      *  - there are no vifs installed
866      *  - pim_assert is not enabled
867      *  - the MFC table is empty
868      */
869     if (numvifs > 0) {
870         *apival = 0;
871         return EPERM;
872     }
873     if (pim_assert) {
874         *apival = 0;
875         return EPERM;
876     }
877     for (i = 0; i < MFCTBLSIZ; i++) {
878         if (mfctable[i] != NULL) {
879             *apival = 0;
880             return EPERM;
881         }
882     }
883
884     mrt_api_config = *apival & mrt_api_support;
885     *apival = mrt_api_config;
886
887     return 0;
888 }
889
890 /*
891  * Add a vif to the vif table
892  */
893 static int
894 add_vif(struct vifctl *vifcp)
895 {
896     struct vif *vifp = viftable + vifcp->vifc_vifi;
897     struct sockaddr_in sin = {sizeof sin, AF_INET};
898     struct ifaddr *ifa;
899     struct ifnet *ifp;
900     int error;
901
902     VIF_LOCK();
903     if (vifcp->vifc_vifi >= MAXVIFS) {
904         VIF_UNLOCK();
905         return EINVAL;
906     }
907     /* rate limiting is no longer supported by this code */
908     if (vifcp->vifc_rate_limit != 0) {
909         log(LOG_ERR, "rate limiting is no longer supported\n");
910         VIF_UNLOCK();
911         return EINVAL;
912     }
913     if (vifp->v_lcl_addr.s_addr != INADDR_ANY) {
914         VIF_UNLOCK();
915         return EADDRINUSE;
916     }
917     if (vifcp->vifc_lcl_addr.s_addr == INADDR_ANY) {
918         VIF_UNLOCK();
919         return EADDRNOTAVAIL;
920     }
921
922     /* Find the interface with an address in AF_INET family */
923     if (vifcp->vifc_flags & VIFF_REGISTER) {
924         /*
925          * XXX: Because VIFF_REGISTER does not really need a valid
926          * local interface (e.g. it could be 127.0.0.2), we don't
927          * check its address.
928          */
929         ifp = NULL;
930     } else {
931         sin.sin_addr = vifcp->vifc_lcl_addr;
932         ifa = ifa_ifwithaddr((struct sockaddr *)&sin);
933         if (ifa == NULL) {
934             VIF_UNLOCK();
935             return EADDRNOTAVAIL;
936         }
937         ifp = ifa->ifa_ifp;
938     }
939
940     if ((vifcp->vifc_flags & VIFF_TUNNEL) != 0) {
941         log(LOG_ERR, "tunnels are no longer supported\n");
942         VIF_UNLOCK();
943         return EOPNOTSUPP;
944     } else if (vifcp->vifc_flags & VIFF_REGISTER) {
945         ifp = &multicast_register_if;
946         if (mrtdebug)
947             log(LOG_DEBUG, "Adding a register vif, ifp: %p\n",
948                     (void *)&multicast_register_if);
949         if (reg_vif_num == VIFI_INVALID) {
950             if_initname(&multicast_register_if, "register_vif", 0);
951             multicast_register_if.if_flags = IFF_LOOPBACK;
952             reg_vif_num = vifcp->vifc_vifi;
953         }
954     } else {            /* Make sure the interface supports multicast */
955         if ((ifp->if_flags & IFF_MULTICAST) == 0) {
956             VIF_UNLOCK();
957             return EOPNOTSUPP;
958         }
959
960         /* Enable promiscuous reception of all IP multicasts from the if */
961         error = if_allmulti(ifp, 1);
962         if (error) {
963             VIF_UNLOCK();
964             return error;
965         }
966     }
967
968     vifp->v_flags     = vifcp->vifc_flags;
969     vifp->v_threshold = vifcp->vifc_threshold;
970     vifp->v_lcl_addr  = vifcp->vifc_lcl_addr;
971     vifp->v_rmt_addr  = vifcp->vifc_rmt_addr;
972     vifp->v_ifp       = ifp;
973     vifp->v_rsvp_on   = 0;
974     vifp->v_rsvpd     = NULL;
975     /* initialize per vif pkt counters */
976     vifp->v_pkt_in    = 0;
977     vifp->v_pkt_out   = 0;
978     vifp->v_bytes_in  = 0;
979     vifp->v_bytes_out = 0;
980     bzero(&vifp->v_route, sizeof(vifp->v_route));
981
982     /* Adjust numvifs up if the vifi is higher than numvifs */
983     if (numvifs <= vifcp->vifc_vifi) numvifs = vifcp->vifc_vifi + 1;
984
985     VIF_UNLOCK();
986
987     if (mrtdebug)
988         log(LOG_DEBUG, "add_vif #%d, lcladdr %lx, %s %lx, thresh %x\n",
989             vifcp->vifc_vifi,
990             (u_long)ntohl(vifcp->vifc_lcl_addr.s_addr),
991             (vifcp->vifc_flags & VIFF_TUNNEL) ? "rmtaddr" : "mask",
992             (u_long)ntohl(vifcp->vifc_rmt_addr.s_addr),
993             vifcp->vifc_threshold);
994
995     return 0;
996 }
997
998 /*
999  * Delete a vif from the vif table
1000  */
1001 static int
1002 del_vif_locked(vifi_t vifi)
1003 {
1004     struct vif *vifp;
1005
1006     VIF_LOCK_ASSERT();
1007
1008     if (vifi >= numvifs) {
1009         return EINVAL;
1010     }
1011     vifp = &viftable[vifi];
1012     if (vifp->v_lcl_addr.s_addr == INADDR_ANY) {
1013         return EADDRNOTAVAIL;
1014     }
1015
1016     if (!(vifp->v_flags & (VIFF_TUNNEL | VIFF_REGISTER)))
1017         if_allmulti(vifp->v_ifp, 0);
1018
1019     if (vifp->v_flags & VIFF_REGISTER)
1020         reg_vif_num = VIFI_INVALID;
1021
1022     bzero((caddr_t)vifp, sizeof (*vifp));
1023
1024     if (mrtdebug)
1025         log(LOG_DEBUG, "del_vif %d, numvifs %d\n", vifi, numvifs);
1026
1027     /* Adjust numvifs down */
1028     for (vifi = numvifs; vifi > 0; vifi--)
1029         if (viftable[vifi-1].v_lcl_addr.s_addr != INADDR_ANY)
1030             break;
1031     numvifs = vifi;
1032
1033     return 0;
1034 }
1035
1036 static int
1037 del_vif(vifi_t vifi)
1038 {
1039     int cc;
1040
1041     VIF_LOCK();
1042     cc = del_vif_locked(vifi);
1043     VIF_UNLOCK();
1044
1045     return cc;
1046 }
1047
1048 /*
1049  * update an mfc entry without resetting counters and S,G addresses.
1050  */
1051 static void
1052 update_mfc_params(struct mfc *rt, struct mfcctl2 *mfccp)
1053 {
1054     int i;
1055
1056     rt->mfc_parent = mfccp->mfcc_parent;
1057     for (i = 0; i < numvifs; i++) {
1058         rt->mfc_ttls[i] = mfccp->mfcc_ttls[i];
1059         rt->mfc_flags[i] = mfccp->mfcc_flags[i] & mrt_api_config &
1060             MRT_MFC_FLAGS_ALL;
1061     }
1062     /* set the RP address */
1063     if (mrt_api_config & MRT_MFC_RP)
1064         rt->mfc_rp = mfccp->mfcc_rp;
1065     else
1066         rt->mfc_rp.s_addr = INADDR_ANY;
1067 }
1068
1069 /*
1070  * fully initialize an mfc entry from the parameter.
1071  */
1072 static void
1073 init_mfc_params(struct mfc *rt, struct mfcctl2 *mfccp)
1074 {
1075     rt->mfc_origin     = mfccp->mfcc_origin;
1076     rt->mfc_mcastgrp   = mfccp->mfcc_mcastgrp;
1077
1078     update_mfc_params(rt, mfccp);
1079
1080     /* initialize pkt counters per src-grp */
1081     rt->mfc_pkt_cnt    = 0;
1082     rt->mfc_byte_cnt   = 0;
1083     rt->mfc_wrong_if   = 0;
1084     rt->mfc_last_assert.tv_sec = rt->mfc_last_assert.tv_usec = 0;
1085 }
1086
1087
1088 /*
1089  * Add an mfc entry
1090  */
1091 static int
1092 add_mfc(struct mfcctl2 *mfccp)
1093 {
1094     struct mfc *rt;
1095     u_long hash;
1096     struct rtdetq *rte;
1097     u_short nstl;
1098
1099     VIF_LOCK();
1100     MFC_LOCK();
1101
1102     rt = mfc_find(mfccp->mfcc_origin.s_addr, mfccp->mfcc_mcastgrp.s_addr);
1103
1104     /* If an entry already exists, just update the fields */
1105     if (rt) {
1106         if (mrtdebug & DEBUG_MFC)
1107             log(LOG_DEBUG,"add_mfc update o %lx g %lx p %x\n",
1108                 (u_long)ntohl(mfccp->mfcc_origin.s_addr),
1109                 (u_long)ntohl(mfccp->mfcc_mcastgrp.s_addr),
1110                 mfccp->mfcc_parent);
1111
1112         update_mfc_params(rt, mfccp);
1113         MFC_UNLOCK();
1114         VIF_UNLOCK();
1115         return 0;
1116     }
1117
1118     /*
1119      * Find the entry for which the upcall was made and update
1120      */
1121     hash = MFCHASH(mfccp->mfcc_origin.s_addr, mfccp->mfcc_mcastgrp.s_addr);
1122     for (rt = mfctable[hash], nstl = 0; rt; rt = rt->mfc_next) {
1123
1124         if ((rt->mfc_origin.s_addr == mfccp->mfcc_origin.s_addr) &&
1125                 (rt->mfc_mcastgrp.s_addr == mfccp->mfcc_mcastgrp.s_addr) &&
1126                 (rt->mfc_stall != NULL)) {
1127
1128             if (nstl++)
1129                 log(LOG_ERR, "add_mfc %s o %lx g %lx p %x dbx %p\n",
1130                     "multiple kernel entries",
1131                     (u_long)ntohl(mfccp->mfcc_origin.s_addr),
1132                     (u_long)ntohl(mfccp->mfcc_mcastgrp.s_addr),
1133                     mfccp->mfcc_parent, (void *)rt->mfc_stall);
1134
1135             if (mrtdebug & DEBUG_MFC)
1136                 log(LOG_DEBUG,"add_mfc o %lx g %lx p %x dbg %p\n",
1137                     (u_long)ntohl(mfccp->mfcc_origin.s_addr),
1138                     (u_long)ntohl(mfccp->mfcc_mcastgrp.s_addr),
1139                     mfccp->mfcc_parent, (void *)rt->mfc_stall);
1140
1141             init_mfc_params(rt, mfccp);
1142
1143             rt->mfc_expire = 0; /* Don't clean this guy up */
1144             nexpire[hash]--;
1145
1146             /* free packets Qed at the end of this entry */
1147             for (rte = rt->mfc_stall; rte != NULL; ) {
1148                 struct rtdetq *n = rte->next;
1149
1150                 ip_mdq(rte->m, rte->ifp, rt, -1);
1151                 m_freem(rte->m);
1152                 free(rte, M_MRTABLE);
1153                 rte = n;
1154             }
1155             rt->mfc_stall = NULL;
1156         }
1157     }
1158
1159     /*
1160      * It is possible that an entry is being inserted without an upcall
1161      */
1162     if (nstl == 0) {
1163         if (mrtdebug & DEBUG_MFC)
1164             log(LOG_DEBUG,"add_mfc no upcall h %lu o %lx g %lx p %x\n",
1165                 hash, (u_long)ntohl(mfccp->mfcc_origin.s_addr),
1166                 (u_long)ntohl(mfccp->mfcc_mcastgrp.s_addr),
1167                 mfccp->mfcc_parent);
1168
1169         for (rt = mfctable[hash]; rt != NULL; rt = rt->mfc_next) {
1170             if ((rt->mfc_origin.s_addr == mfccp->mfcc_origin.s_addr) &&
1171                     (rt->mfc_mcastgrp.s_addr == mfccp->mfcc_mcastgrp.s_addr)) {
1172                 init_mfc_params(rt, mfccp);
1173                 if (rt->mfc_expire)
1174                     nexpire[hash]--;
1175                 rt->mfc_expire = 0;
1176                 break; /* XXX */
1177             }
1178         }
1179         if (rt == NULL) {               /* no upcall, so make a new entry */
1180             rt = (struct mfc *)malloc(sizeof(*rt), M_MRTABLE, M_NOWAIT);
1181             if (rt == NULL) {
1182                 MFC_UNLOCK();
1183                 VIF_UNLOCK();
1184                 return ENOBUFS;
1185             }
1186
1187             init_mfc_params(rt, mfccp);
1188             rt->mfc_expire     = 0;
1189             rt->mfc_stall      = NULL;
1190
1191             rt->mfc_bw_meter = NULL;
1192             /* insert new entry at head of hash chain */
1193             rt->mfc_next = mfctable[hash];
1194             mfctable[hash] = rt;
1195         }
1196     }
1197     MFC_UNLOCK();
1198     VIF_UNLOCK();
1199     return 0;
1200 }
1201
1202 /*
1203  * Delete an mfc entry
1204  */
1205 static int
1206 del_mfc(struct mfcctl2 *mfccp)
1207 {
1208     struct in_addr      origin;
1209     struct in_addr      mcastgrp;
1210     struct mfc          *rt;
1211     struct mfc          **nptr;
1212     u_long              hash;
1213     struct bw_meter     *list;
1214
1215     origin = mfccp->mfcc_origin;
1216     mcastgrp = mfccp->mfcc_mcastgrp;
1217
1218     if (mrtdebug & DEBUG_MFC)
1219         log(LOG_DEBUG,"del_mfc orig %lx mcastgrp %lx\n",
1220             (u_long)ntohl(origin.s_addr), (u_long)ntohl(mcastgrp.s_addr));
1221
1222     MFC_LOCK();
1223
1224     hash = MFCHASH(origin.s_addr, mcastgrp.s_addr);
1225     for (nptr = &mfctable[hash]; (rt = *nptr) != NULL; nptr = &rt->mfc_next)
1226         if (origin.s_addr == rt->mfc_origin.s_addr &&
1227                 mcastgrp.s_addr == rt->mfc_mcastgrp.s_addr &&
1228                 rt->mfc_stall == NULL)
1229             break;
1230     if (rt == NULL) {
1231         MFC_UNLOCK();
1232         return EADDRNOTAVAIL;
1233     }
1234
1235     *nptr = rt->mfc_next;
1236
1237     /*
1238      * free the bw_meter entries
1239      */
1240     list = rt->mfc_bw_meter;
1241     rt->mfc_bw_meter = NULL;
1242
1243     free(rt, M_MRTABLE);
1244
1245     free_bw_list(list);
1246
1247     MFC_UNLOCK();
1248
1249     return 0;
1250 }
1251
1252 /*
1253  * Send a message to the routing daemon on the multicast routing socket
1254  */
1255 static int
1256 socket_send(struct socket *s, struct mbuf *mm, struct sockaddr_in *src)
1257 {
1258     if (s) {
1259         SOCKBUF_LOCK(&s->so_rcv);
1260         if (sbappendaddr_locked(&s->so_rcv, (struct sockaddr *)src, mm,
1261             NULL) != 0) {
1262             sorwakeup_locked(s);
1263             return 0;
1264         }
1265         SOCKBUF_UNLOCK(&s->so_rcv);
1266     }
1267     m_freem(mm);
1268     return -1;
1269 }
1270
1271 /*
1272  * IP multicast forwarding function. This function assumes that the packet
1273  * pointed to by "ip" has arrived on (or is about to be sent to) the interface
1274  * pointed to by "ifp", and the packet is to be relayed to other networks
1275  * that have members of the packet's destination IP multicast group.
1276  *
1277  * The packet is returned unscathed to the caller, unless it is
1278  * erroneous, in which case a non-zero return value tells the caller to
1279  * discard it.
1280  */
1281
1282 #define TUNNEL_LEN  12  /* # bytes of IP option for tunnel encapsulation  */
1283
1284 static int
1285 X_ip_mforward(struct ip *ip, struct ifnet *ifp, struct mbuf *m,
1286     struct ip_moptions *imo)
1287 {
1288     struct mfc *rt;
1289     int error;
1290     vifi_t vifi;
1291
1292     if (mrtdebug & DEBUG_FORWARD)
1293         log(LOG_DEBUG, "ip_mforward: src %lx, dst %lx, ifp %p\n",
1294             (u_long)ntohl(ip->ip_src.s_addr), (u_long)ntohl(ip->ip_dst.s_addr),
1295             (void *)ifp);
1296
1297     if (ip->ip_hl < (sizeof(struct ip) + TUNNEL_LEN) >> 2 ||
1298                 ((u_char *)(ip + 1))[1] != IPOPT_LSRR ) {
1299         /*
1300          * Packet arrived via a physical interface or
1301          * an encapsulated tunnel or a register_vif.
1302          */
1303     } else {
1304         /*
1305          * Packet arrived through a source-route tunnel.
1306          * Source-route tunnels are no longer supported.
1307          */
1308         static int last_log;
1309         if (last_log != time_uptime) {
1310             last_log = time_uptime;
1311             log(LOG_ERR,
1312                 "ip_mforward: received source-routed packet from %lx\n",
1313                 (u_long)ntohl(ip->ip_src.s_addr));
1314         }
1315         return 1;
1316     }
1317
1318     VIF_LOCK();
1319     MFC_LOCK();
1320     if (imo && ((vifi = imo->imo_multicast_vif) < numvifs)) {
1321         if (ip->ip_ttl < MAXTTL)
1322             ip->ip_ttl++;       /* compensate for -1 in *_send routines */
1323         if (rsvpdebug && ip->ip_p == IPPROTO_RSVP) {
1324             struct vif *vifp = viftable + vifi;
1325
1326             printf("Sending IPPROTO_RSVP from %lx to %lx on vif %d (%s%s)\n",
1327                 (long)ntohl(ip->ip_src.s_addr), (long)ntohl(ip->ip_dst.s_addr),
1328                 vifi,
1329                 (vifp->v_flags & VIFF_TUNNEL) ? "tunnel on " : "",
1330                 vifp->v_ifp->if_xname);
1331         }
1332         error = ip_mdq(m, ifp, NULL, vifi);
1333         MFC_UNLOCK();
1334         VIF_UNLOCK();
1335         return error;
1336     }
1337     if (rsvpdebug && ip->ip_p == IPPROTO_RSVP) {
1338         printf("Warning: IPPROTO_RSVP from %lx to %lx without vif option\n",
1339             (long)ntohl(ip->ip_src.s_addr), (long)ntohl(ip->ip_dst.s_addr));
1340         if (!imo)
1341             printf("In fact, no options were specified at all\n");
1342     }
1343
1344     /*
1345      * Don't forward a packet with time-to-live of zero or one,
1346      * or a packet destined to a local-only group.
1347      */
1348     if (ip->ip_ttl <= 1 || IN_LOCAL_GROUP(ntohl(ip->ip_dst.s_addr))) {
1349         MFC_UNLOCK();
1350         VIF_UNLOCK();
1351         return 0;
1352     }
1353
1354     /*
1355      * Determine forwarding vifs from the forwarding cache table
1356      */
1357     ++mrtstat.mrts_mfc_lookups;
1358     rt = mfc_find(ip->ip_src.s_addr, ip->ip_dst.s_addr);
1359
1360     /* Entry exists, so forward if necessary */
1361     if (rt != NULL) {
1362         error = ip_mdq(m, ifp, rt, -1);
1363         MFC_UNLOCK();
1364         VIF_UNLOCK();
1365         return error;
1366     } else {
1367         /*
1368          * If we don't have a route for packet's origin,
1369          * Make a copy of the packet & send message to routing daemon
1370          */
1371
1372         struct mbuf *mb0;
1373         struct rtdetq *rte;
1374         u_long hash;
1375         int hlen = ip->ip_hl << 2;
1376
1377         ++mrtstat.mrts_mfc_misses;
1378
1379         mrtstat.mrts_no_route++;
1380         if (mrtdebug & (DEBUG_FORWARD | DEBUG_MFC))
1381             log(LOG_DEBUG, "ip_mforward: no rte s %lx g %lx\n",
1382                 (u_long)ntohl(ip->ip_src.s_addr),
1383                 (u_long)ntohl(ip->ip_dst.s_addr));
1384
1385         /*
1386          * Allocate mbufs early so that we don't do extra work if we are
1387          * just going to fail anyway.  Make sure to pullup the header so
1388          * that other people can't step on it.
1389          */
1390         rte = (struct rtdetq *)malloc((sizeof *rte), M_MRTABLE, M_NOWAIT);
1391         if (rte == NULL) {
1392             MFC_UNLOCK();
1393             VIF_UNLOCK();
1394             return ENOBUFS;
1395         }
1396         mb0 = m_copypacket(m, M_DONTWAIT);
1397         if (mb0 && (M_HASCL(mb0) || mb0->m_len < hlen))
1398             mb0 = m_pullup(mb0, hlen);
1399         if (mb0 == NULL) {
1400             free(rte, M_MRTABLE);
1401             MFC_UNLOCK();
1402             VIF_UNLOCK();
1403             return ENOBUFS;
1404         }
1405
1406         /* is there an upcall waiting for this flow ? */
1407         hash = MFCHASH(ip->ip_src.s_addr, ip->ip_dst.s_addr);
1408         for (rt = mfctable[hash]; rt; rt = rt->mfc_next) {
1409             if ((ip->ip_src.s_addr == rt->mfc_origin.s_addr) &&
1410                     (ip->ip_dst.s_addr == rt->mfc_mcastgrp.s_addr) &&
1411                     (rt->mfc_stall != NULL))
1412                 break;
1413         }
1414
1415         if (rt == NULL) {
1416             int i;
1417             struct igmpmsg *im;
1418             struct sockaddr_in k_igmpsrc = { sizeof k_igmpsrc, AF_INET };
1419             struct mbuf *mm;
1420
1421             /*
1422              * Locate the vifi for the incoming interface for this packet.
1423              * If none found, drop packet.
1424              */
1425             for (vifi=0; vifi < numvifs && viftable[vifi].v_ifp != ifp; vifi++)
1426                 ;
1427             if (vifi >= numvifs)        /* vif not found, drop packet */
1428                 goto non_fatal;
1429
1430             /* no upcall, so make a new entry */
1431             rt = (struct mfc *)malloc(sizeof(*rt), M_MRTABLE, M_NOWAIT);
1432             if (rt == NULL)
1433                 goto fail;
1434             /* Make a copy of the header to send to the user level process */
1435             mm = m_copy(mb0, 0, hlen);
1436             if (mm == NULL)
1437                 goto fail1;
1438
1439             /*
1440              * Send message to routing daemon to install
1441              * a route into the kernel table
1442              */
1443
1444             im = mtod(mm, struct igmpmsg *);
1445             im->im_msgtype = IGMPMSG_NOCACHE;
1446             im->im_mbz = 0;
1447             im->im_vif = vifi;
1448
1449             mrtstat.mrts_upcalls++;
1450
1451             k_igmpsrc.sin_addr = ip->ip_src;
1452             if (socket_send(ip_mrouter, mm, &k_igmpsrc) < 0) {
1453                 log(LOG_WARNING, "ip_mforward: ip_mrouter socket queue full\n");
1454                 ++mrtstat.mrts_upq_sockfull;
1455 fail1:
1456                 free(rt, M_MRTABLE);
1457 fail:
1458                 free(rte, M_MRTABLE);
1459                 m_freem(mb0);
1460                 MFC_UNLOCK();
1461                 VIF_UNLOCK();
1462                 return ENOBUFS;
1463             }
1464
1465             /* insert new entry at head of hash chain */
1466             rt->mfc_origin.s_addr     = ip->ip_src.s_addr;
1467             rt->mfc_mcastgrp.s_addr   = ip->ip_dst.s_addr;
1468             rt->mfc_expire            = UPCALL_EXPIRE;
1469             nexpire[hash]++;
1470             for (i = 0; i < numvifs; i++) {
1471                 rt->mfc_ttls[i] = 0;
1472                 rt->mfc_flags[i] = 0;
1473             }
1474             rt->mfc_parent = -1;
1475
1476             rt->mfc_rp.s_addr = INADDR_ANY; /* clear the RP address */
1477
1478             rt->mfc_bw_meter = NULL;
1479
1480             /* link into table */
1481             rt->mfc_next   = mfctable[hash];
1482             mfctable[hash] = rt;
1483             rt->mfc_stall = rte;
1484
1485         } else {
1486             /* determine if q has overflowed */
1487             int npkts = 0;
1488             struct rtdetq **p;
1489
1490             /*
1491              * XXX ouch! we need to append to the list, but we
1492              * only have a pointer to the front, so we have to
1493              * scan the entire list every time.
1494              */
1495             for (p = &rt->mfc_stall; *p != NULL; p = &(*p)->next)
1496                 npkts++;
1497
1498             if (npkts > MAX_UPQ) {
1499                 mrtstat.mrts_upq_ovflw++;
1500 non_fatal:
1501                 free(rte, M_MRTABLE);
1502                 m_freem(mb0);
1503                 MFC_UNLOCK();
1504                 VIF_UNLOCK();
1505                 return 0;
1506             }
1507
1508             /* Add this entry to the end of the queue */
1509             *p = rte;
1510         }
1511
1512         rte->m                  = mb0;
1513         rte->ifp                = ifp;
1514         rte->next               = NULL;
1515
1516         MFC_UNLOCK();
1517         VIF_UNLOCK();
1518
1519         return 0;
1520     }
1521 }
1522
1523 /*
1524  * Clean up the cache entry if upcall is not serviced
1525  */
1526 static void
1527 expire_upcalls(void *unused)
1528 {
1529     struct rtdetq *rte;
1530     struct mfc *mfc, **nptr;
1531     int i;
1532
1533     MFC_LOCK();
1534     for (i = 0; i < MFCTBLSIZ; i++) {
1535         if (nexpire[i] == 0)
1536             continue;
1537         nptr = &mfctable[i];
1538         for (mfc = *nptr; mfc != NULL; mfc = *nptr) {
1539             /*
1540              * Skip real cache entries
1541              * Make sure it wasn't marked to not expire (shouldn't happen)
1542              * If it expires now
1543              */
1544             if (mfc->mfc_stall != NULL && mfc->mfc_expire != 0 &&
1545                     --mfc->mfc_expire == 0) {
1546                 if (mrtdebug & DEBUG_EXPIRE)
1547                     log(LOG_DEBUG, "expire_upcalls: expiring (%lx %lx)\n",
1548                         (u_long)ntohl(mfc->mfc_origin.s_addr),
1549                         (u_long)ntohl(mfc->mfc_mcastgrp.s_addr));
1550                 /*
1551                  * drop all the packets
1552                  * free the mbuf with the pkt, if, timing info
1553                  */
1554                 for (rte = mfc->mfc_stall; rte; ) {
1555                     struct rtdetq *n = rte->next;
1556
1557                     m_freem(rte->m);
1558                     free(rte, M_MRTABLE);
1559                     rte = n;
1560                 }
1561                 ++mrtstat.mrts_cache_cleanups;
1562                 nexpire[i]--;
1563
1564                 /*
1565                  * free the bw_meter entries
1566                  */
1567                 while (mfc->mfc_bw_meter != NULL) {
1568                     struct bw_meter *x = mfc->mfc_bw_meter;
1569
1570                     mfc->mfc_bw_meter = x->bm_mfc_next;
1571                     free(x, M_BWMETER);
1572                 }
1573
1574                 *nptr = mfc->mfc_next;
1575                 free(mfc, M_MRTABLE);
1576             } else {
1577                 nptr = &mfc->mfc_next;
1578             }
1579         }
1580     }
1581     MFC_UNLOCK();
1582
1583     callout_reset(&expire_upcalls_ch, EXPIRE_TIMEOUT, expire_upcalls, NULL);
1584 }
1585
1586 /*
1587  * Packet forwarding routine once entry in the cache is made
1588  */
1589 static int
1590 ip_mdq(struct mbuf *m, struct ifnet *ifp, struct mfc *rt, vifi_t xmt_vif)
1591 {
1592     struct ip  *ip = mtod(m, struct ip *);
1593     vifi_t vifi;
1594     int plen = ip->ip_len;
1595
1596     VIF_LOCK_ASSERT();
1597
1598     /*
1599      * If xmt_vif is not -1, send on only the requested vif.
1600      *
1601      * (since vifi_t is u_short, -1 becomes MAXUSHORT, which > numvifs.)
1602      */
1603     if (xmt_vif < numvifs) {
1604         if (viftable[xmt_vif].v_flags & VIFF_REGISTER)
1605                 pim_register_send(ip, viftable + xmt_vif, m, rt);
1606         else
1607                 phyint_send(ip, viftable + xmt_vif, m);
1608         return 1;
1609     }
1610
1611     /*
1612      * Don't forward if it didn't arrive from the parent vif for its origin.
1613      */
1614     vifi = rt->mfc_parent;
1615     if ((vifi >= numvifs) || (viftable[vifi].v_ifp != ifp)) {
1616         /* came in the wrong interface */
1617         if (mrtdebug & DEBUG_FORWARD)
1618             log(LOG_DEBUG, "wrong if: ifp %p vifi %d vififp %p\n",
1619                 (void *)ifp, vifi, (void *)viftable[vifi].v_ifp);
1620         ++mrtstat.mrts_wrong_if;
1621         ++rt->mfc_wrong_if;
1622         /*
1623          * If we are doing PIM assert processing, send a message
1624          * to the routing daemon.
1625          *
1626          * XXX: A PIM-SM router needs the WRONGVIF detection so it
1627          * can complete the SPT switch, regardless of the type
1628          * of the iif (broadcast media, GRE tunnel, etc).
1629          */
1630         if (pim_assert && (vifi < numvifs) && viftable[vifi].v_ifp) {
1631             struct timeval now;
1632             u_long delta;
1633
1634             if (ifp == &multicast_register_if)
1635                 pimstat.pims_rcv_registers_wrongiif++;
1636
1637             /* Get vifi for the incoming packet */
1638             for (vifi=0; vifi < numvifs && viftable[vifi].v_ifp != ifp; vifi++)
1639                 ;
1640             if (vifi >= numvifs)
1641                 return 0;       /* The iif is not found: ignore the packet. */
1642
1643             if (rt->mfc_flags[vifi] & MRT_MFC_FLAGS_DISABLE_WRONGVIF)
1644                 return 0;       /* WRONGVIF disabled: ignore the packet */
1645
1646             GET_TIME(now);
1647
1648             TV_DELTA(now, rt->mfc_last_assert, delta);
1649
1650             if (delta > ASSERT_MSG_TIME) {
1651                 struct sockaddr_in k_igmpsrc = { sizeof k_igmpsrc, AF_INET };
1652                 struct igmpmsg *im;
1653                 int hlen = ip->ip_hl << 2;
1654                 struct mbuf *mm = m_copy(m, 0, hlen);
1655
1656                 if (mm && (M_HASCL(mm) || mm->m_len < hlen))
1657                     mm = m_pullup(mm, hlen);
1658                 if (mm == NULL)
1659                     return ENOBUFS;
1660
1661                 rt->mfc_last_assert = now;
1662
1663                 im = mtod(mm, struct igmpmsg *);
1664                 im->im_msgtype  = IGMPMSG_WRONGVIF;
1665                 im->im_mbz              = 0;
1666                 im->im_vif              = vifi;
1667
1668                 mrtstat.mrts_upcalls++;
1669
1670                 k_igmpsrc.sin_addr = im->im_src;
1671                 if (socket_send(ip_mrouter, mm, &k_igmpsrc) < 0) {
1672                     log(LOG_WARNING,
1673                         "ip_mforward: ip_mrouter socket queue full\n");
1674                     ++mrtstat.mrts_upq_sockfull;
1675                     return ENOBUFS;
1676                 }
1677             }
1678         }
1679         return 0;
1680     }
1681
1682     /* If I sourced this packet, it counts as output, else it was input. */
1683     if (ip->ip_src.s_addr == viftable[vifi].v_lcl_addr.s_addr) {
1684         viftable[vifi].v_pkt_out++;
1685         viftable[vifi].v_bytes_out += plen;
1686     } else {
1687         viftable[vifi].v_pkt_in++;
1688         viftable[vifi].v_bytes_in += plen;
1689     }
1690     rt->mfc_pkt_cnt++;
1691     rt->mfc_byte_cnt += plen;
1692
1693     /*
1694      * For each vif, decide if a copy of the packet should be forwarded.
1695      * Forward if:
1696      *          - the ttl exceeds the vif's threshold
1697      *          - there are group members downstream on interface
1698      */
1699     for (vifi = 0; vifi < numvifs; vifi++)
1700         if ((rt->mfc_ttls[vifi] > 0) && (ip->ip_ttl > rt->mfc_ttls[vifi])) {
1701             viftable[vifi].v_pkt_out++;
1702             viftable[vifi].v_bytes_out += plen;
1703             if (viftable[vifi].v_flags & VIFF_REGISTER)
1704                 pim_register_send(ip, viftable + vifi, m, rt);
1705             else
1706                 phyint_send(ip, viftable + vifi, m);
1707         }
1708
1709     /*
1710      * Perform upcall-related bw measuring.
1711      */
1712     if (rt->mfc_bw_meter != NULL) {
1713         struct bw_meter *x;
1714         struct timeval now;
1715
1716         GET_TIME(now);
1717         MFC_LOCK_ASSERT();
1718         for (x = rt->mfc_bw_meter; x != NULL; x = x->bm_mfc_next)
1719             bw_meter_receive_packet(x, plen, &now);
1720     }
1721
1722     return 0;
1723 }
1724
1725 /*
1726  * check if a vif number is legal/ok. This is used by ip_output.
1727  */
1728 static int
1729 X_legal_vif_num(int vif)
1730 {
1731     /* XXX unlocked, matter? */
1732     return (vif >= 0 && vif < numvifs);
1733 }
1734
1735 /*
1736  * Return the local address used by this vif
1737  */
1738 static u_long
1739 X_ip_mcast_src(int vifi)
1740 {
1741     /* XXX unlocked, matter? */
1742     if (vifi >= 0 && vifi < numvifs)
1743         return viftable[vifi].v_lcl_addr.s_addr;
1744     else
1745         return INADDR_ANY;
1746 }
1747
1748 static void
1749 phyint_send(struct ip *ip, struct vif *vifp, struct mbuf *m)
1750 {
1751     struct mbuf *mb_copy;
1752     int hlen = ip->ip_hl << 2;
1753
1754     VIF_LOCK_ASSERT();
1755
1756     /*
1757      * Make a new reference to the packet; make sure that
1758      * the IP header is actually copied, not just referenced,
1759      * so that ip_output() only scribbles on the copy.
1760      */
1761     mb_copy = m_copypacket(m, M_DONTWAIT);
1762     if (mb_copy && (M_HASCL(mb_copy) || mb_copy->m_len < hlen))
1763         mb_copy = m_pullup(mb_copy, hlen);
1764     if (mb_copy == NULL)
1765         return;
1766
1767     send_packet(vifp, mb_copy);
1768 }
1769
1770 static void
1771 send_packet(struct vif *vifp, struct mbuf *m)
1772 {
1773         struct ip_moptions imo;
1774         struct in_multi *imm[2];
1775         int error;
1776
1777         VIF_LOCK_ASSERT();
1778
1779         imo.imo_multicast_ifp  = vifp->v_ifp;
1780         imo.imo_multicast_ttl  = mtod(m, struct ip *)->ip_ttl - 1;
1781         imo.imo_multicast_loop = 1;
1782         imo.imo_multicast_vif  = -1;
1783         imo.imo_num_memberships = 0;
1784         imo.imo_max_memberships = 2;
1785         imo.imo_membership  = &imm[0];
1786
1787         /*
1788          * Re-entrancy should not be a problem here, because
1789          * the packets that we send out and are looped back at us
1790          * should get rejected because they appear to come from
1791          * the loopback interface, thus preventing looping.
1792          */
1793         error = ip_output(m, NULL, &vifp->v_route, IP_FORWARDING, &imo, NULL);
1794         if (mrtdebug & DEBUG_XMIT) {
1795             log(LOG_DEBUG, "phyint_send on vif %td err %d\n",
1796                 vifp - viftable, error);
1797         }
1798 }
1799
1800 static int
1801 X_ip_rsvp_vif(struct socket *so, struct sockopt *sopt)
1802 {
1803     int error, vifi;
1804
1805     if (so->so_type != SOCK_RAW || so->so_proto->pr_protocol != IPPROTO_RSVP)
1806         return EOPNOTSUPP;
1807
1808     error = sooptcopyin(sopt, &vifi, sizeof vifi, sizeof vifi);
1809     if (error)
1810         return error;
1811
1812     VIF_LOCK();
1813
1814     if (vifi < 0 || vifi >= numvifs) {  /* Error if vif is invalid */
1815         VIF_UNLOCK();
1816         return EADDRNOTAVAIL;
1817     }
1818
1819     if (sopt->sopt_name == IP_RSVP_VIF_ON) {
1820         /* Check if socket is available. */
1821         if (viftable[vifi].v_rsvpd != NULL) {
1822             VIF_UNLOCK();
1823             return EADDRINUSE;
1824         }
1825
1826         viftable[vifi].v_rsvpd = so;
1827         /* This may seem silly, but we need to be sure we don't over-increment
1828          * the RSVP counter, in case something slips up.
1829          */
1830         if (!viftable[vifi].v_rsvp_on) {
1831             viftable[vifi].v_rsvp_on = 1;
1832             rsvp_on++;
1833         }
1834     } else { /* must be VIF_OFF */
1835         /*
1836          * XXX as an additional consistency check, one could make sure
1837          * that viftable[vifi].v_rsvpd == so, otherwise passing so as
1838          * first parameter is pretty useless.
1839          */
1840         viftable[vifi].v_rsvpd = NULL;
1841         /*
1842          * This may seem silly, but we need to be sure we don't over-decrement
1843          * the RSVP counter, in case something slips up.
1844          */
1845         if (viftable[vifi].v_rsvp_on) {
1846             viftable[vifi].v_rsvp_on = 0;
1847             rsvp_on--;
1848         }
1849     }
1850     VIF_UNLOCK();
1851     return 0;
1852 }
1853
1854 static void
1855 X_ip_rsvp_force_done(struct socket *so)
1856 {
1857     int vifi;
1858
1859     /* Don't bother if it is not the right type of socket. */
1860     if (so->so_type != SOCK_RAW || so->so_proto->pr_protocol != IPPROTO_RSVP)
1861         return;
1862
1863     VIF_LOCK();
1864
1865     /* The socket may be attached to more than one vif...this
1866      * is perfectly legal.
1867      */
1868     for (vifi = 0; vifi < numvifs; vifi++) {
1869         if (viftable[vifi].v_rsvpd == so) {
1870             viftable[vifi].v_rsvpd = NULL;
1871             /* This may seem silly, but we need to be sure we don't
1872              * over-decrement the RSVP counter, in case something slips up.
1873              */
1874             if (viftable[vifi].v_rsvp_on) {
1875                 viftable[vifi].v_rsvp_on = 0;
1876                 rsvp_on--;
1877             }
1878         }
1879     }
1880
1881     VIF_UNLOCK();
1882 }
1883
1884 static void
1885 X_rsvp_input(struct mbuf *m, int off)
1886 {
1887     int vifi;
1888     struct ip *ip = mtod(m, struct ip *);
1889     struct sockaddr_in rsvp_src = { sizeof rsvp_src, AF_INET };
1890     struct ifnet *ifp;
1891
1892     if (rsvpdebug)
1893         printf("rsvp_input: rsvp_on %d\n",rsvp_on);
1894
1895     /* Can still get packets with rsvp_on = 0 if there is a local member
1896      * of the group to which the RSVP packet is addressed.  But in this
1897      * case we want to throw the packet away.
1898      */
1899     if (!rsvp_on) {
1900         m_freem(m);
1901         return;
1902     }
1903
1904     if (rsvpdebug)
1905         printf("rsvp_input: check vifs\n");
1906
1907 #ifdef DIAGNOSTIC
1908     M_ASSERTPKTHDR(m);
1909 #endif
1910
1911     ifp = m->m_pkthdr.rcvif;
1912
1913     VIF_LOCK();
1914     /* Find which vif the packet arrived on. */
1915     for (vifi = 0; vifi < numvifs; vifi++)
1916         if (viftable[vifi].v_ifp == ifp)
1917             break;
1918
1919     if (vifi == numvifs || viftable[vifi].v_rsvpd == NULL) {
1920         /*
1921          * Drop the lock here to avoid holding it across rip_input.
1922          * This could make rsvpdebug printfs wrong.  If you care,
1923          * record the state of stuff before dropping the lock.
1924          */
1925         VIF_UNLOCK();
1926         /*
1927          * If the old-style non-vif-associated socket is set,
1928          * then use it.  Otherwise, drop packet since there
1929          * is no specific socket for this vif.
1930          */
1931         if (ip_rsvpd != NULL) {
1932             if (rsvpdebug)
1933                 printf("rsvp_input: Sending packet up old-style socket\n");
1934             rip_input(m, off);  /* xxx */
1935         } else {
1936             if (rsvpdebug && vifi == numvifs)
1937                 printf("rsvp_input: Can't find vif for packet.\n");
1938             else if (rsvpdebug && viftable[vifi].v_rsvpd == NULL)
1939                 printf("rsvp_input: No socket defined for vif %d\n",vifi);
1940             m_freem(m);
1941         }
1942         return;
1943     }
1944     rsvp_src.sin_addr = ip->ip_src;
1945
1946     if (rsvpdebug && m)
1947         printf("rsvp_input: m->m_len = %d, sbspace() = %ld\n",
1948                m->m_len,sbspace(&(viftable[vifi].v_rsvpd->so_rcv)));
1949
1950     if (socket_send(viftable[vifi].v_rsvpd, m, &rsvp_src) < 0) {
1951         if (rsvpdebug)
1952             printf("rsvp_input: Failed to append to socket\n");
1953     } else {
1954         if (rsvpdebug)
1955             printf("rsvp_input: send packet up\n");
1956     }
1957     VIF_UNLOCK();
1958 }
1959
1960 /*
1961  * Code for bandwidth monitors
1962  */
1963
1964 /*
1965  * Define common interface for timeval-related methods
1966  */
1967 #define BW_TIMEVALCMP(tvp, uvp, cmp) timevalcmp((tvp), (uvp), cmp)
1968 #define BW_TIMEVALDECR(vvp, uvp) timevalsub((vvp), (uvp))
1969 #define BW_TIMEVALADD(vvp, uvp) timevaladd((vvp), (uvp))
1970
1971 static uint32_t
1972 compute_bw_meter_flags(struct bw_upcall *req)
1973 {
1974     uint32_t flags = 0;
1975
1976     if (req->bu_flags & BW_UPCALL_UNIT_PACKETS)
1977         flags |= BW_METER_UNIT_PACKETS;
1978     if (req->bu_flags & BW_UPCALL_UNIT_BYTES)
1979         flags |= BW_METER_UNIT_BYTES;
1980     if (req->bu_flags & BW_UPCALL_GEQ)
1981         flags |= BW_METER_GEQ;
1982     if (req->bu_flags & BW_UPCALL_LEQ)
1983         flags |= BW_METER_LEQ;
1984
1985     return flags;
1986 }
1987
1988 /*
1989  * Add a bw_meter entry
1990  */
1991 static int
1992 add_bw_upcall(struct bw_upcall *req)
1993 {
1994     struct mfc *mfc;
1995     struct timeval delta = { BW_UPCALL_THRESHOLD_INTERVAL_MIN_SEC,
1996                 BW_UPCALL_THRESHOLD_INTERVAL_MIN_USEC };
1997     struct timeval now;
1998     struct bw_meter *x;
1999     uint32_t flags;
2000
2001     if (!(mrt_api_config & MRT_MFC_BW_UPCALL))
2002         return EOPNOTSUPP;
2003
2004     /* Test if the flags are valid */
2005     if (!(req->bu_flags & (BW_UPCALL_UNIT_PACKETS | BW_UPCALL_UNIT_BYTES)))
2006         return EINVAL;
2007     if (!(req->bu_flags & (BW_UPCALL_GEQ | BW_UPCALL_LEQ)))
2008         return EINVAL;
2009     if ((req->bu_flags & (BW_UPCALL_GEQ | BW_UPCALL_LEQ))
2010             == (BW_UPCALL_GEQ | BW_UPCALL_LEQ))
2011         return EINVAL;
2012
2013     /* Test if the threshold time interval is valid */
2014     if (BW_TIMEVALCMP(&req->bu_threshold.b_time, &delta, <))
2015         return EINVAL;
2016
2017     flags = compute_bw_meter_flags(req);
2018
2019     /*
2020      * Find if we have already same bw_meter entry
2021      */
2022     MFC_LOCK();
2023     mfc = mfc_find(req->bu_src.s_addr, req->bu_dst.s_addr);
2024     if (mfc == NULL) {
2025         MFC_UNLOCK();
2026         return EADDRNOTAVAIL;
2027     }
2028     for (x = mfc->mfc_bw_meter; x != NULL; x = x->bm_mfc_next) {
2029         if ((BW_TIMEVALCMP(&x->bm_threshold.b_time,
2030                            &req->bu_threshold.b_time, ==)) &&
2031             (x->bm_threshold.b_packets == req->bu_threshold.b_packets) &&
2032             (x->bm_threshold.b_bytes == req->bu_threshold.b_bytes) &&
2033             (x->bm_flags & BW_METER_USER_FLAGS) == flags)  {
2034             MFC_UNLOCK();
2035             return 0;           /* XXX Already installed */
2036         }
2037     }
2038
2039     /* Allocate the new bw_meter entry */
2040     x = (struct bw_meter *)malloc(sizeof(*x), M_BWMETER, M_NOWAIT);
2041     if (x == NULL) {
2042         MFC_UNLOCK();
2043         return ENOBUFS;
2044     }
2045
2046     /* Set the new bw_meter entry */
2047     x->bm_threshold.b_time = req->bu_threshold.b_time;
2048     GET_TIME(now);
2049     x->bm_start_time = now;
2050     x->bm_threshold.b_packets = req->bu_threshold.b_packets;
2051     x->bm_threshold.b_bytes = req->bu_threshold.b_bytes;
2052     x->bm_measured.b_packets = 0;
2053     x->bm_measured.b_bytes = 0;
2054     x->bm_flags = flags;
2055     x->bm_time_next = NULL;
2056     x->bm_time_hash = BW_METER_BUCKETS;
2057
2058     /* Add the new bw_meter entry to the front of entries for this MFC */
2059     x->bm_mfc = mfc;
2060     x->bm_mfc_next = mfc->mfc_bw_meter;
2061     mfc->mfc_bw_meter = x;
2062     schedule_bw_meter(x, &now);
2063     MFC_UNLOCK();
2064
2065     return 0;
2066 }
2067
2068 static void
2069 free_bw_list(struct bw_meter *list)
2070 {
2071     while (list != NULL) {
2072         struct bw_meter *x = list;
2073
2074         list = list->bm_mfc_next;
2075         unschedule_bw_meter(x);
2076         free(x, M_BWMETER);
2077     }
2078 }
2079
2080 /*
2081  * Delete one or multiple bw_meter entries
2082  */
2083 static int
2084 del_bw_upcall(struct bw_upcall *req)
2085 {
2086     struct mfc *mfc;
2087     struct bw_meter *x;
2088
2089     if (!(mrt_api_config & MRT_MFC_BW_UPCALL))
2090         return EOPNOTSUPP;
2091
2092     MFC_LOCK();
2093     /* Find the corresponding MFC entry */
2094     mfc = mfc_find(req->bu_src.s_addr, req->bu_dst.s_addr);
2095     if (mfc == NULL) {
2096         MFC_UNLOCK();
2097         return EADDRNOTAVAIL;
2098     } else if (req->bu_flags & BW_UPCALL_DELETE_ALL) {
2099         /*
2100          * Delete all bw_meter entries for this mfc
2101          */
2102         struct bw_meter *list;
2103
2104         list = mfc->mfc_bw_meter;
2105         mfc->mfc_bw_meter = NULL;
2106         free_bw_list(list);
2107         MFC_UNLOCK();
2108         return 0;
2109     } else {                    /* Delete a single bw_meter entry */
2110         struct bw_meter *prev;
2111         uint32_t flags = 0;
2112
2113         flags = compute_bw_meter_flags(req);
2114
2115         /* Find the bw_meter entry to delete */
2116         for (prev = NULL, x = mfc->mfc_bw_meter; x != NULL;
2117              prev = x, x = x->bm_mfc_next) {
2118             if ((BW_TIMEVALCMP(&x->bm_threshold.b_time,
2119                                &req->bu_threshold.b_time, ==)) &&
2120                 (x->bm_threshold.b_packets == req->bu_threshold.b_packets) &&
2121                 (x->bm_threshold.b_bytes == req->bu_threshold.b_bytes) &&
2122                 (x->bm_flags & BW_METER_USER_FLAGS) == flags)
2123                 break;
2124         }
2125         if (x != NULL) { /* Delete entry from the list for this MFC */
2126             if (prev != NULL)
2127                 prev->bm_mfc_next = x->bm_mfc_next;     /* remove from middle*/
2128             else
2129                 x->bm_mfc->mfc_bw_meter = x->bm_mfc_next;/* new head of list */
2130
2131             unschedule_bw_meter(x);
2132             MFC_UNLOCK();
2133             /* Free the bw_meter entry */
2134             free(x, M_BWMETER);
2135             return 0;
2136         } else {
2137             MFC_UNLOCK();
2138             return EINVAL;
2139         }
2140     }
2141     /* NOTREACHED */
2142 }
2143
2144 /*
2145  * Perform bandwidth measurement processing that may result in an upcall
2146  */
2147 static void
2148 bw_meter_receive_packet(struct bw_meter *x, int plen, struct timeval *nowp)
2149 {
2150     struct timeval delta;
2151
2152     MFC_LOCK_ASSERT();
2153
2154     delta = *nowp;
2155     BW_TIMEVALDECR(&delta, &x->bm_start_time);
2156
2157     if (x->bm_flags & BW_METER_GEQ) {
2158         /*
2159          * Processing for ">=" type of bw_meter entry
2160          */
2161         if (BW_TIMEVALCMP(&delta, &x->bm_threshold.b_time, >)) {
2162             /* Reset the bw_meter entry */
2163             x->bm_start_time = *nowp;
2164             x->bm_measured.b_packets = 0;
2165             x->bm_measured.b_bytes = 0;
2166             x->bm_flags &= ~BW_METER_UPCALL_DELIVERED;
2167         }
2168
2169         /* Record that a packet is received */
2170         x->bm_measured.b_packets++;
2171         x->bm_measured.b_bytes += plen;
2172
2173         /*
2174          * Test if we should deliver an upcall
2175          */
2176         if (!(x->bm_flags & BW_METER_UPCALL_DELIVERED)) {
2177             if (((x->bm_flags & BW_METER_UNIT_PACKETS) &&
2178                  (x->bm_measured.b_packets >= x->bm_threshold.b_packets)) ||
2179                 ((x->bm_flags & BW_METER_UNIT_BYTES) &&
2180                  (x->bm_measured.b_bytes >= x->bm_threshold.b_bytes))) {
2181                 /* Prepare an upcall for delivery */
2182                 bw_meter_prepare_upcall(x, nowp);
2183                 x->bm_flags |= BW_METER_UPCALL_DELIVERED;
2184             }
2185         }
2186     } else if (x->bm_flags & BW_METER_LEQ) {
2187         /*
2188          * Processing for "<=" type of bw_meter entry
2189          */
2190         if (BW_TIMEVALCMP(&delta, &x->bm_threshold.b_time, >)) {
2191             /*
2192              * We are behind time with the multicast forwarding table
2193              * scanning for "<=" type of bw_meter entries, so test now
2194              * if we should deliver an upcall.
2195              */
2196             if (((x->bm_flags & BW_METER_UNIT_PACKETS) &&
2197                  (x->bm_measured.b_packets <= x->bm_threshold.b_packets)) ||
2198                 ((x->bm_flags & BW_METER_UNIT_BYTES) &&
2199                  (x->bm_measured.b_bytes <= x->bm_threshold.b_bytes))) {
2200                 /* Prepare an upcall for delivery */
2201                 bw_meter_prepare_upcall(x, nowp);
2202             }
2203             /* Reschedule the bw_meter entry */
2204             unschedule_bw_meter(x);
2205             schedule_bw_meter(x, nowp);
2206         }
2207
2208         /* Record that a packet is received */
2209         x->bm_measured.b_packets++;
2210         x->bm_measured.b_bytes += plen;
2211
2212         /*
2213          * Test if we should restart the measuring interval
2214          */
2215         if ((x->bm_flags & BW_METER_UNIT_PACKETS &&
2216              x->bm_measured.b_packets <= x->bm_threshold.b_packets) ||
2217             (x->bm_flags & BW_METER_UNIT_BYTES &&
2218              x->bm_measured.b_bytes <= x->bm_threshold.b_bytes)) {
2219             /* Don't restart the measuring interval */
2220         } else {
2221             /* Do restart the measuring interval */
2222             /*
2223              * XXX: note that we don't unschedule and schedule, because this
2224              * might be too much overhead per packet. Instead, when we process
2225              * all entries for a given timer hash bin, we check whether it is
2226              * really a timeout. If not, we reschedule at that time.
2227              */
2228             x->bm_start_time = *nowp;
2229             x->bm_measured.b_packets = 0;
2230             x->bm_measured.b_bytes = 0;
2231             x->bm_flags &= ~BW_METER_UPCALL_DELIVERED;
2232         }
2233     }
2234 }
2235
2236 /*
2237  * Prepare a bandwidth-related upcall
2238  */
2239 static void
2240 bw_meter_prepare_upcall(struct bw_meter *x, struct timeval *nowp)
2241 {
2242     struct timeval delta;
2243     struct bw_upcall *u;
2244
2245     MFC_LOCK_ASSERT();
2246
2247     /*
2248      * Compute the measured time interval
2249      */
2250     delta = *nowp;
2251     BW_TIMEVALDECR(&delta, &x->bm_start_time);
2252
2253     /*
2254      * If there are too many pending upcalls, deliver them now
2255      */
2256     if (bw_upcalls_n >= BW_UPCALLS_MAX)
2257         bw_upcalls_send();
2258
2259     /*
2260      * Set the bw_upcall entry
2261      */
2262     u = &bw_upcalls[bw_upcalls_n++];
2263     u->bu_src = x->bm_mfc->mfc_origin;
2264     u->bu_dst = x->bm_mfc->mfc_mcastgrp;
2265     u->bu_threshold.b_time = x->bm_threshold.b_time;
2266     u->bu_threshold.b_packets = x->bm_threshold.b_packets;
2267     u->bu_threshold.b_bytes = x->bm_threshold.b_bytes;
2268     u->bu_measured.b_time = delta;
2269     u->bu_measured.b_packets = x->bm_measured.b_packets;
2270     u->bu_measured.b_bytes = x->bm_measured.b_bytes;
2271     u->bu_flags = 0;
2272     if (x->bm_flags & BW_METER_UNIT_PACKETS)
2273         u->bu_flags |= BW_UPCALL_UNIT_PACKETS;
2274     if (x->bm_flags & BW_METER_UNIT_BYTES)
2275         u->bu_flags |= BW_UPCALL_UNIT_BYTES;
2276     if (x->bm_flags & BW_METER_GEQ)
2277         u->bu_flags |= BW_UPCALL_GEQ;
2278     if (x->bm_flags & BW_METER_LEQ)
2279         u->bu_flags |= BW_UPCALL_LEQ;
2280 }
2281
2282 /*
2283  * Send the pending bandwidth-related upcalls
2284  */
2285 static void
2286 bw_upcalls_send(void)
2287 {
2288     struct mbuf *m;
2289     int len = bw_upcalls_n * sizeof(bw_upcalls[0]);
2290     struct sockaddr_in k_igmpsrc = { sizeof k_igmpsrc, AF_INET };
2291     static struct igmpmsg igmpmsg = { 0,                /* unused1 */
2292                                       0,                /* unused2 */
2293                                       IGMPMSG_BW_UPCALL,/* im_msgtype */
2294                                       0,                /* im_mbz  */
2295                                       0,                /* im_vif  */
2296                                       0,                /* unused3 */
2297                                       { 0 },            /* im_src  */
2298                                       { 0 } };          /* im_dst  */
2299
2300     MFC_LOCK_ASSERT();
2301
2302     if (bw_upcalls_n == 0)
2303         return;                 /* No pending upcalls */
2304
2305     bw_upcalls_n = 0;
2306
2307     /*
2308      * Allocate a new mbuf, initialize it with the header and
2309      * the payload for the pending calls.
2310      */
2311     MGETHDR(m, M_DONTWAIT, MT_DATA);
2312     if (m == NULL) {
2313         log(LOG_WARNING, "bw_upcalls_send: cannot allocate mbuf\n");
2314         return;
2315     }
2316
2317     m->m_len = m->m_pkthdr.len = 0;
2318     m_copyback(m, 0, sizeof(struct igmpmsg), (caddr_t)&igmpmsg);
2319     m_copyback(m, sizeof(struct igmpmsg), len, (caddr_t)&bw_upcalls[0]);
2320
2321     /*
2322      * Send the upcalls
2323      * XXX do we need to set the address in k_igmpsrc ?
2324      */
2325     mrtstat.mrts_upcalls++;
2326     if (socket_send(ip_mrouter, m, &k_igmpsrc) < 0) {
2327         log(LOG_WARNING, "bw_upcalls_send: ip_mrouter socket queue full\n");
2328         ++mrtstat.mrts_upq_sockfull;
2329     }
2330 }
2331
2332 /*
2333  * Compute the timeout hash value for the bw_meter entries
2334  */
2335 #define BW_METER_TIMEHASH(bw_meter, hash)                               \
2336     do {                                                                \
2337         struct timeval next_timeval = (bw_meter)->bm_start_time;        \
2338                                                                         \
2339         BW_TIMEVALADD(&next_timeval, &(bw_meter)->bm_threshold.b_time); \
2340         (hash) = next_timeval.tv_sec;                                   \
2341         if (next_timeval.tv_usec)                                       \
2342             (hash)++; /* XXX: make sure we don't timeout early */       \
2343         (hash) %= BW_METER_BUCKETS;                                     \
2344     } while (0)
2345
2346 /*
2347  * Schedule a timer to process periodically bw_meter entry of type "<="
2348  * by linking the entry in the proper hash bucket.
2349  */
2350 static void
2351 schedule_bw_meter(struct bw_meter *x, struct timeval *nowp)
2352 {
2353     int time_hash;
2354
2355     MFC_LOCK_ASSERT();
2356
2357     if (!(x->bm_flags & BW_METER_LEQ))
2358         return;         /* XXX: we schedule timers only for "<=" entries */
2359
2360     /*
2361      * Reset the bw_meter entry
2362      */
2363     x->bm_start_time = *nowp;
2364     x->bm_measured.b_packets = 0;
2365     x->bm_measured.b_bytes = 0;
2366     x->bm_flags &= ~BW_METER_UPCALL_DELIVERED;
2367
2368     /*
2369      * Compute the timeout hash value and insert the entry
2370      */
2371     BW_METER_TIMEHASH(x, time_hash);
2372     x->bm_time_next = bw_meter_timers[time_hash];
2373     bw_meter_timers[time_hash] = x;
2374     x->bm_time_hash = time_hash;
2375 }
2376
2377 /*
2378  * Unschedule the periodic timer that processes bw_meter entry of type "<="
2379  * by removing the entry from the proper hash bucket.
2380  */
2381 static void
2382 unschedule_bw_meter(struct bw_meter *x)
2383 {
2384     int time_hash;
2385     struct bw_meter *prev, *tmp;
2386
2387     MFC_LOCK_ASSERT();
2388
2389     if (!(x->bm_flags & BW_METER_LEQ))
2390         return;         /* XXX: we schedule timers only for "<=" entries */
2391
2392     /*
2393      * Compute the timeout hash value and delete the entry
2394      */
2395     time_hash = x->bm_time_hash;
2396     if (time_hash >= BW_METER_BUCKETS)
2397         return;         /* Entry was not scheduled */
2398
2399     for (prev = NULL, tmp = bw_meter_timers[time_hash];
2400              tmp != NULL; prev = tmp, tmp = tmp->bm_time_next)
2401         if (tmp == x)
2402             break;
2403
2404     if (tmp == NULL)
2405         panic("unschedule_bw_meter: bw_meter entry not found");
2406
2407     if (prev != NULL)
2408         prev->bm_time_next = x->bm_time_next;
2409     else
2410         bw_meter_timers[time_hash] = x->bm_time_next;
2411
2412     x->bm_time_next = NULL;
2413     x->bm_time_hash = BW_METER_BUCKETS;
2414 }
2415
2416
2417 /*
2418  * Process all "<=" type of bw_meter that should be processed now,
2419  * and for each entry prepare an upcall if necessary. Each processed
2420  * entry is rescheduled again for the (periodic) processing.
2421  *
2422  * This is run periodically (once per second normally). On each round,
2423  * all the potentially matching entries are in the hash slot that we are
2424  * looking at.
2425  */
2426 static void
2427 bw_meter_process()
2428 {
2429     static uint32_t last_tv_sec;        /* last time we processed this */
2430
2431     uint32_t loops;
2432     int i;
2433     struct timeval now, process_endtime;
2434
2435     GET_TIME(now);
2436     if (last_tv_sec == now.tv_sec)
2437         return;         /* nothing to do */
2438
2439     loops = now.tv_sec - last_tv_sec;
2440     last_tv_sec = now.tv_sec;
2441     if (loops > BW_METER_BUCKETS)
2442         loops = BW_METER_BUCKETS;
2443
2444     MFC_LOCK();
2445     /*
2446      * Process all bins of bw_meter entries from the one after the last
2447      * processed to the current one. On entry, i points to the last bucket
2448      * visited, so we need to increment i at the beginning of the loop.
2449      */
2450     for (i = (now.tv_sec - loops) % BW_METER_BUCKETS; loops > 0; loops--) {
2451         struct bw_meter *x, *tmp_list;
2452
2453         if (++i >= BW_METER_BUCKETS)
2454             i = 0;
2455
2456         /* Disconnect the list of bw_meter entries from the bin */
2457         tmp_list = bw_meter_timers[i];
2458         bw_meter_timers[i] = NULL;
2459
2460         /* Process the list of bw_meter entries */
2461         while (tmp_list != NULL) {
2462             x = tmp_list;
2463             tmp_list = tmp_list->bm_time_next;
2464
2465             /* Test if the time interval is over */
2466             process_endtime = x->bm_start_time;
2467             BW_TIMEVALADD(&process_endtime, &x->bm_threshold.b_time);
2468             if (BW_TIMEVALCMP(&process_endtime, &now, >)) {
2469                 /* Not yet: reschedule, but don't reset */
2470                 int time_hash;
2471
2472                 BW_METER_TIMEHASH(x, time_hash);
2473                 if (time_hash == i && process_endtime.tv_sec == now.tv_sec) {
2474                     /*
2475                      * XXX: somehow the bin processing is a bit ahead of time.
2476                      * Put the entry in the next bin.
2477                      */
2478                     if (++time_hash >= BW_METER_BUCKETS)
2479                         time_hash = 0;
2480                 }
2481                 x->bm_time_next = bw_meter_timers[time_hash];
2482                 bw_meter_timers[time_hash] = x;
2483                 x->bm_time_hash = time_hash;
2484
2485                 continue;
2486             }
2487
2488             /*
2489              * Test if we should deliver an upcall
2490              */
2491             if (((x->bm_flags & BW_METER_UNIT_PACKETS) &&
2492                  (x->bm_measured.b_packets <= x->bm_threshold.b_packets)) ||
2493                 ((x->bm_flags & BW_METER_UNIT_BYTES) &&
2494                  (x->bm_measured.b_bytes <= x->bm_threshold.b_bytes))) {
2495                 /* Prepare an upcall for delivery */
2496                 bw_meter_prepare_upcall(x, &now);
2497             }
2498
2499             /*
2500              * Reschedule for next processing
2501              */
2502             schedule_bw_meter(x, &now);
2503         }
2504     }
2505
2506     /* Send all upcalls that are pending delivery */
2507     bw_upcalls_send();
2508
2509     MFC_UNLOCK();
2510 }
2511
2512 /*
2513  * A periodic function for sending all upcalls that are pending delivery
2514  */
2515 static void
2516 expire_bw_upcalls_send(void *unused)
2517 {
2518     MFC_LOCK();
2519     bw_upcalls_send();
2520     MFC_UNLOCK();
2521
2522     callout_reset(&bw_upcalls_ch, BW_UPCALLS_PERIOD,
2523         expire_bw_upcalls_send, NULL);
2524 }
2525
2526 /*
2527  * A periodic function for periodic scanning of the multicast forwarding
2528  * table for processing all "<=" bw_meter entries.
2529  */
2530 static void
2531 expire_bw_meter_process(void *unused)
2532 {
2533     if (mrt_api_config & MRT_MFC_BW_UPCALL)
2534         bw_meter_process();
2535
2536     callout_reset(&bw_meter_ch, BW_METER_PERIOD, expire_bw_meter_process, NULL);
2537 }
2538
2539 /*
2540  * End of bandwidth monitoring code
2541  */
2542
2543 /*
2544  * Send the packet up to the user daemon, or eventually do kernel encapsulation
2545  *
2546  */
2547 static int
2548 pim_register_send(struct ip *ip, struct vif *vifp, struct mbuf *m,
2549     struct mfc *rt)
2550 {
2551     struct mbuf *mb_copy, *mm;
2552
2553     if (mrtdebug & DEBUG_PIM)
2554         log(LOG_DEBUG, "pim_register_send: ");
2555
2556     /*
2557      * Do not send IGMP_WHOLEPKT notifications to userland, if the
2558      * rendezvous point was unspecified, and we were told not to.
2559      */
2560     if (pim_squelch_wholepkt != 0 && (mrt_api_config & MRT_MFC_RP) &&
2561         (rt->mfc_rp.s_addr == INADDR_ANY))
2562         return 0;
2563
2564     mb_copy = pim_register_prepare(ip, m);
2565     if (mb_copy == NULL)
2566         return ENOBUFS;
2567
2568     /*
2569      * Send all the fragments. Note that the mbuf for each fragment
2570      * is freed by the sending machinery.
2571      */
2572     for (mm = mb_copy; mm; mm = mb_copy) {
2573         mb_copy = mm->m_nextpkt;
2574         mm->m_nextpkt = 0;
2575         mm = m_pullup(mm, sizeof(struct ip));
2576         if (mm != NULL) {
2577             ip = mtod(mm, struct ip *);
2578             if ((mrt_api_config & MRT_MFC_RP) &&
2579                 (rt->mfc_rp.s_addr != INADDR_ANY)) {
2580                 pim_register_send_rp(ip, vifp, mm, rt);
2581             } else {
2582                 pim_register_send_upcall(ip, vifp, mm, rt);
2583             }
2584         }
2585     }
2586
2587     return 0;
2588 }
2589
2590 /*
2591  * Return a copy of the data packet that is ready for PIM Register
2592  * encapsulation.
2593  * XXX: Note that in the returned copy the IP header is a valid one.
2594  */
2595 static struct mbuf *
2596 pim_register_prepare(struct ip *ip, struct mbuf *m)
2597 {
2598     struct mbuf *mb_copy = NULL;
2599     int mtu;
2600
2601     /* Take care of delayed checksums */
2602     if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
2603         in_delayed_cksum(m);
2604         m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
2605     }
2606
2607     /*
2608      * Copy the old packet & pullup its IP header into the
2609      * new mbuf so we can modify it.
2610      */
2611     mb_copy = m_copypacket(m, M_DONTWAIT);
2612     if (mb_copy == NULL)
2613         return NULL;
2614     mb_copy = m_pullup(mb_copy, ip->ip_hl << 2);
2615     if (mb_copy == NULL)
2616         return NULL;
2617
2618     /* take care of the TTL */
2619     ip = mtod(mb_copy, struct ip *);
2620     --ip->ip_ttl;
2621
2622     /* Compute the MTU after the PIM Register encapsulation */
2623     mtu = 0xffff - sizeof(pim_encap_iphdr) - sizeof(pim_encap_pimhdr);
2624
2625     if (ip->ip_len <= mtu) {
2626         /* Turn the IP header into a valid one */
2627         ip->ip_len = htons(ip->ip_len);
2628         ip->ip_off = htons(ip->ip_off);
2629         ip->ip_sum = 0;
2630         ip->ip_sum = in_cksum(mb_copy, ip->ip_hl << 2);
2631     } else {
2632         /* Fragment the packet */
2633         if (ip_fragment(ip, &mb_copy, mtu, 0, CSUM_DELAY_IP) != 0) {
2634             m_freem(mb_copy);
2635             return NULL;
2636         }
2637     }
2638     return mb_copy;
2639 }
2640
2641 /*
2642  * Send an upcall with the data packet to the user-level process.
2643  */
2644 static int
2645 pim_register_send_upcall(struct ip *ip, struct vif *vifp,
2646     struct mbuf *mb_copy, struct mfc *rt)
2647 {
2648     struct mbuf *mb_first;
2649     int len = ntohs(ip->ip_len);
2650     struct igmpmsg *im;
2651     struct sockaddr_in k_igmpsrc = { sizeof k_igmpsrc, AF_INET };
2652
2653     VIF_LOCK_ASSERT();
2654
2655     /*
2656      * Add a new mbuf with an upcall header
2657      */
2658     MGETHDR(mb_first, M_DONTWAIT, MT_DATA);
2659     if (mb_first == NULL) {
2660         m_freem(mb_copy);
2661         return ENOBUFS;
2662     }
2663     mb_first->m_data += max_linkhdr;
2664     mb_first->m_pkthdr.len = len + sizeof(struct igmpmsg);
2665     mb_first->m_len = sizeof(struct igmpmsg);
2666     mb_first->m_next = mb_copy;
2667
2668     /* Send message to routing daemon */
2669     im = mtod(mb_first, struct igmpmsg *);
2670     im->im_msgtype      = IGMPMSG_WHOLEPKT;
2671     im->im_mbz          = 0;
2672     im->im_vif          = vifp - viftable;
2673     im->im_src          = ip->ip_src;
2674     im->im_dst          = ip->ip_dst;
2675
2676     k_igmpsrc.sin_addr  = ip->ip_src;
2677
2678     mrtstat.mrts_upcalls++;
2679
2680     if (socket_send(ip_mrouter, mb_first, &k_igmpsrc) < 0) {
2681         if (mrtdebug & DEBUG_PIM)
2682             log(LOG_WARNING,
2683                 "mcast: pim_register_send_upcall: ip_mrouter socket queue full");
2684         ++mrtstat.mrts_upq_sockfull;
2685         return ENOBUFS;
2686     }
2687
2688     /* Keep statistics */
2689     pimstat.pims_snd_registers_msgs++;
2690     pimstat.pims_snd_registers_bytes += len;
2691
2692     return 0;
2693 }
2694
2695 /*
2696  * Encapsulate the data packet in PIM Register message and send it to the RP.
2697  */
2698 static int
2699 pim_register_send_rp(struct ip *ip, struct vif *vifp, struct mbuf *mb_copy,
2700     struct mfc *rt)
2701 {
2702     struct mbuf *mb_first;
2703     struct ip *ip_outer;
2704     struct pim_encap_pimhdr *pimhdr;
2705     int len = ntohs(ip->ip_len);
2706     vifi_t vifi = rt->mfc_parent;
2707
2708     VIF_LOCK_ASSERT();
2709
2710     if ((vifi >= numvifs) || (viftable[vifi].v_lcl_addr.s_addr == 0)) {
2711         m_freem(mb_copy);
2712         return EADDRNOTAVAIL;           /* The iif vif is invalid */
2713     }
2714
2715     /*
2716      * Add a new mbuf with the encapsulating header
2717      */
2718     MGETHDR(mb_first, M_DONTWAIT, MT_DATA);
2719     if (mb_first == NULL) {
2720         m_freem(mb_copy);
2721         return ENOBUFS;
2722     }
2723     mb_first->m_data += max_linkhdr;
2724     mb_first->m_len = sizeof(pim_encap_iphdr) + sizeof(pim_encap_pimhdr);
2725     mb_first->m_next = mb_copy;
2726
2727     mb_first->m_pkthdr.len = len + mb_first->m_len;
2728
2729     /*
2730      * Fill in the encapsulating IP and PIM header
2731      */
2732     ip_outer = mtod(mb_first, struct ip *);
2733     *ip_outer = pim_encap_iphdr;
2734     ip_outer->ip_id = ip_newid();
2735     ip_outer->ip_len = len + sizeof(pim_encap_iphdr) + sizeof(pim_encap_pimhdr);
2736     ip_outer->ip_src = viftable[vifi].v_lcl_addr;
2737     ip_outer->ip_dst = rt->mfc_rp;
2738     /*
2739      * Copy the inner header TOS to the outer header, and take care of the
2740      * IP_DF bit.
2741      */
2742     ip_outer->ip_tos = ip->ip_tos;
2743     if (ntohs(ip->ip_off) & IP_DF)
2744         ip_outer->ip_off |= IP_DF;
2745     pimhdr = (struct pim_encap_pimhdr *)((caddr_t)ip_outer
2746                                          + sizeof(pim_encap_iphdr));
2747     *pimhdr = pim_encap_pimhdr;
2748     /* If the iif crosses a border, set the Border-bit */
2749     if (rt->mfc_flags[vifi] & MRT_MFC_FLAGS_BORDER_VIF & mrt_api_config)
2750         pimhdr->flags |= htonl(PIM_BORDER_REGISTER);
2751
2752     mb_first->m_data += sizeof(pim_encap_iphdr);
2753     pimhdr->pim.pim_cksum = in_cksum(mb_first, sizeof(pim_encap_pimhdr));
2754     mb_first->m_data -= sizeof(pim_encap_iphdr);
2755
2756     send_packet(vifp, mb_first);
2757
2758     /* Keep statistics */
2759     pimstat.pims_snd_registers_msgs++;
2760     pimstat.pims_snd_registers_bytes += len;
2761
2762     return 0;
2763 }
2764
2765 /*
2766  * pim_encapcheck() is called by the encap[46]_input() path at runtime to
2767  * determine if a packet is for PIM; allowing PIM to be dynamically loaded
2768  * into the kernel.
2769  */
2770 static int
2771 pim_encapcheck(const struct mbuf *m, int off, int proto, void *arg)
2772 {
2773
2774 #ifdef DIAGNOSTIC
2775     KASSERT(proto == IPPROTO_PIM, ("not for IPPROTO_PIM"));
2776 #endif
2777     if (proto != IPPROTO_PIM)
2778         return 0;       /* not for us; reject the datagram. */
2779
2780     return 64;          /* claim the datagram. */
2781 }
2782
2783 /*
2784  * PIM-SMv2 and PIM-DM messages processing.
2785  * Receives and verifies the PIM control messages, and passes them
2786  * up to the listening socket, using rip_input().
2787  * The only message with special processing is the PIM_REGISTER message
2788  * (used by PIM-SM): the PIM header is stripped off, and the inner packet
2789  * is passed to if_simloop().
2790  */
2791 void
2792 pim_input(struct mbuf *m, int off)
2793 {
2794     struct ip *ip = mtod(m, struct ip *);
2795     struct pim *pim;
2796     int minlen;
2797     int datalen = ip->ip_len;
2798     int ip_tos;
2799     int iphlen = off;
2800
2801     /* Keep statistics */
2802     pimstat.pims_rcv_total_msgs++;
2803     pimstat.pims_rcv_total_bytes += datalen;
2804
2805     /*
2806      * Validate lengths
2807      */
2808     if (datalen < PIM_MINLEN) {
2809         pimstat.pims_rcv_tooshort++;
2810         log(LOG_ERR, "pim_input: packet size too small %d from %lx\n",
2811             datalen, (u_long)ip->ip_src.s_addr);
2812         m_freem(m);
2813         return;
2814     }
2815
2816     /*
2817      * If the packet is at least as big as a REGISTER, go agead
2818      * and grab the PIM REGISTER header size, to avoid another
2819      * possible m_pullup() later.
2820      *
2821      * PIM_MINLEN       == pimhdr + u_int32_t == 4 + 4 = 8
2822      * PIM_REG_MINLEN   == pimhdr + reghdr + encap_iphdr == 4 + 4 + 20 = 28
2823      */
2824     minlen = iphlen + (datalen >= PIM_REG_MINLEN ? PIM_REG_MINLEN : PIM_MINLEN);
2825     /*
2826      * Get the IP and PIM headers in contiguous memory, and
2827      * possibly the PIM REGISTER header.
2828      */
2829     if ((m->m_flags & M_EXT || m->m_len < minlen) &&
2830         (m = m_pullup(m, minlen)) == 0) {
2831         log(LOG_ERR, "pim_input: m_pullup failure\n");
2832         return;
2833     }
2834     /* m_pullup() may have given us a new mbuf so reset ip. */
2835     ip = mtod(m, struct ip *);
2836     ip_tos = ip->ip_tos;
2837
2838     /* adjust mbuf to point to the PIM header */
2839     m->m_data += iphlen;
2840     m->m_len  -= iphlen;
2841     pim = mtod(m, struct pim *);
2842
2843     /*
2844      * Validate checksum. If PIM REGISTER, exclude the data packet.
2845      *
2846      * XXX: some older PIMv2 implementations don't make this distinction,
2847      * so for compatibility reason perform the checksum over part of the
2848      * message, and if error, then over the whole message.
2849      */
2850     if (PIM_VT_T(pim->pim_vt) == PIM_REGISTER && in_cksum(m, PIM_MINLEN) == 0) {
2851         /* do nothing, checksum okay */
2852     } else if (in_cksum(m, datalen)) {
2853         pimstat.pims_rcv_badsum++;
2854         if (mrtdebug & DEBUG_PIM)
2855             log(LOG_DEBUG, "pim_input: invalid checksum");
2856         m_freem(m);
2857         return;
2858     }
2859
2860     /* PIM version check */
2861     if (PIM_VT_V(pim->pim_vt) < PIM_VERSION) {
2862         pimstat.pims_rcv_badversion++;
2863         log(LOG_ERR, "pim_input: incorrect version %d, expecting %d\n",
2864             PIM_VT_V(pim->pim_vt), PIM_VERSION);
2865         m_freem(m);
2866         return;
2867     }
2868
2869     /* restore mbuf back to the outer IP */
2870     m->m_data -= iphlen;
2871     m->m_len  += iphlen;
2872
2873     if (PIM_VT_T(pim->pim_vt) == PIM_REGISTER) {
2874         /*
2875          * Since this is a REGISTER, we'll make a copy of the register
2876          * headers ip + pim + u_int32 + encap_ip, to be passed up to the
2877          * routing daemon.
2878          */
2879         struct sockaddr_in dst = { sizeof(dst), AF_INET };
2880         struct mbuf *mcp;
2881         struct ip *encap_ip;
2882         u_int32_t *reghdr;
2883         struct ifnet *vifp;
2884
2885         VIF_LOCK();
2886         if ((reg_vif_num >= numvifs) || (reg_vif_num == VIFI_INVALID)) {
2887             VIF_UNLOCK();
2888             if (mrtdebug & DEBUG_PIM)
2889                 log(LOG_DEBUG,
2890                     "pim_input: register vif not set: %d\n", reg_vif_num);
2891             m_freem(m);
2892             return;
2893         }
2894         /* XXX need refcnt? */
2895         vifp = viftable[reg_vif_num].v_ifp;
2896         VIF_UNLOCK();
2897
2898         /*
2899          * Validate length
2900          */
2901         if (datalen < PIM_REG_MINLEN) {
2902             pimstat.pims_rcv_tooshort++;
2903             pimstat.pims_rcv_badregisters++;
2904             log(LOG_ERR,
2905                 "pim_input: register packet size too small %d from %lx\n",
2906                 datalen, (u_long)ip->ip_src.s_addr);
2907             m_freem(m);
2908             return;
2909         }
2910
2911         reghdr = (u_int32_t *)(pim + 1);
2912         encap_ip = (struct ip *)(reghdr + 1);
2913
2914         if (mrtdebug & DEBUG_PIM) {
2915             log(LOG_DEBUG,
2916                 "pim_input[register], encap_ip: %lx -> %lx, encap_ip len %d\n",
2917                 (u_long)ntohl(encap_ip->ip_src.s_addr),
2918                 (u_long)ntohl(encap_ip->ip_dst.s_addr),
2919                 ntohs(encap_ip->ip_len));
2920         }
2921
2922         /* verify the version number of the inner packet */
2923         if (encap_ip->ip_v != IPVERSION) {
2924             pimstat.pims_rcv_badregisters++;
2925             if (mrtdebug & DEBUG_PIM) {
2926                 log(LOG_DEBUG, "pim_input: invalid IP version (%d) "
2927                     "of the inner packet\n", encap_ip->ip_v);
2928             }
2929             m_freem(m);
2930             return;
2931         }
2932
2933         /* verify the inner packet is destined to a mcast group */
2934         if (!IN_MULTICAST(ntohl(encap_ip->ip_dst.s_addr))) {
2935             pimstat.pims_rcv_badregisters++;
2936             if (mrtdebug & DEBUG_PIM)
2937                 log(LOG_DEBUG,
2938                     "pim_input: inner packet of register is not "
2939                     "multicast %lx\n",
2940                     (u_long)ntohl(encap_ip->ip_dst.s_addr));
2941             m_freem(m);
2942             return;
2943         }
2944
2945         /* If a NULL_REGISTER, pass it to the daemon */
2946         if ((ntohl(*reghdr) & PIM_NULL_REGISTER))
2947             goto pim_input_to_daemon;
2948
2949         /*
2950          * Copy the TOS from the outer IP header to the inner IP header.
2951          */
2952         if (encap_ip->ip_tos != ip_tos) {
2953             /* Outer TOS -> inner TOS */
2954             encap_ip->ip_tos = ip_tos;
2955             /* Recompute the inner header checksum. Sigh... */
2956
2957             /* adjust mbuf to point to the inner IP header */
2958             m->m_data += (iphlen + PIM_MINLEN);
2959             m->m_len  -= (iphlen + PIM_MINLEN);
2960
2961             encap_ip->ip_sum = 0;
2962             encap_ip->ip_sum = in_cksum(m, encap_ip->ip_hl << 2);
2963
2964             /* restore mbuf to point back to the outer IP header */
2965             m->m_data -= (iphlen + PIM_MINLEN);
2966             m->m_len  += (iphlen + PIM_MINLEN);
2967         }
2968
2969         /*
2970          * Decapsulate the inner IP packet and loopback to forward it
2971          * as a normal multicast packet. Also, make a copy of the
2972          *     outer_iphdr + pimhdr + reghdr + encap_iphdr
2973          * to pass to the daemon later, so it can take the appropriate
2974          * actions (e.g., send back PIM_REGISTER_STOP).
2975          * XXX: here m->m_data points to the outer IP header.
2976          */
2977         mcp = m_copy(m, 0, iphlen + PIM_REG_MINLEN);
2978         if (mcp == NULL) {
2979             log(LOG_ERR,
2980                 "pim_input: pim register: could not copy register head\n");
2981             m_freem(m);
2982             return;
2983         }
2984
2985         /* Keep statistics */
2986         /* XXX: registers_bytes include only the encap. mcast pkt */
2987         pimstat.pims_rcv_registers_msgs++;
2988         pimstat.pims_rcv_registers_bytes += ntohs(encap_ip->ip_len);
2989
2990         /*
2991          * forward the inner ip packet; point m_data at the inner ip.
2992          */
2993         m_adj(m, iphlen + PIM_MINLEN);
2994
2995         if (mrtdebug & DEBUG_PIM) {
2996             log(LOG_DEBUG,
2997                 "pim_input: forwarding decapsulated register: "
2998                 "src %lx, dst %lx, vif %d\n",
2999                 (u_long)ntohl(encap_ip->ip_src.s_addr),
3000                 (u_long)ntohl(encap_ip->ip_dst.s_addr),
3001                 reg_vif_num);
3002         }
3003         /* NB: vifp was collected above; can it change on us? */
3004         if_simloop(vifp, m, dst.sin_family, 0);
3005
3006         /* prepare the register head to send to the mrouting daemon */
3007         m = mcp;
3008     }
3009
3010 pim_input_to_daemon:
3011     /*
3012      * Pass the PIM message up to the daemon; if it is a Register message,
3013      * pass the 'head' only up to the daemon. This includes the
3014      * outer IP header, PIM header, PIM-Register header and the
3015      * inner IP header.
3016      * XXX: the outer IP header pkt size of a Register is not adjust to
3017      * reflect the fact that the inner multicast data is truncated.
3018      */
3019     rip_input(m, iphlen);
3020
3021     return;
3022 }
3023
3024 /*
3025  * XXX: This is common code for dealing with initialization for both
3026  * the IPv4 and IPv6 multicast forwarding paths. It could do with cleanup.
3027  */
3028 static int
3029 ip_mroute_modevent(module_t mod, int type, void *unused)
3030 {
3031     switch (type) {
3032     case MOD_LOAD:
3033         MROUTER_LOCK_INIT();
3034         MFC_LOCK_INIT();
3035         VIF_LOCK_INIT();
3036         ip_mrouter_reset();
3037         TUNABLE_ULONG_FETCH("net.inet.pim.squelch_wholepkt",
3038             &pim_squelch_wholepkt);
3039
3040         pim_encap_cookie = encap_attach_func(AF_INET, IPPROTO_PIM,
3041             pim_encapcheck, &in_pim_protosw, NULL);
3042         if (pim_encap_cookie == NULL) {
3043                 printf("ip_mroute: unable to attach pim encap\n");
3044                 VIF_LOCK_DESTROY();
3045                 MFC_LOCK_DESTROY();
3046                 MROUTER_LOCK_DESTROY();
3047                 return (EINVAL);
3048         }
3049
3050 #ifdef INET6
3051         pim6_encap_cookie = encap_attach_func(AF_INET6, IPPROTO_PIM,
3052             pim_encapcheck, (struct protosw *)&in6_pim_protosw, NULL);
3053         if (pim6_encap_cookie == NULL) {
3054                 printf("ip_mroute: unable to attach pim6 encap\n");
3055                 if (pim_encap_cookie) {
3056                     encap_detach(pim_encap_cookie);
3057                     pim_encap_cookie = NULL;
3058                 }
3059                 VIF_LOCK_DESTROY();
3060                 MFC_LOCK_DESTROY();
3061                 MROUTER_LOCK_DESTROY();
3062                 return (EINVAL);
3063         }
3064 #endif
3065
3066         ip_mcast_src = X_ip_mcast_src;
3067         ip_mforward = X_ip_mforward;
3068         ip_mrouter_done = X_ip_mrouter_done;
3069         ip_mrouter_get = X_ip_mrouter_get;
3070         ip_mrouter_set = X_ip_mrouter_set;
3071
3072 #ifdef INET6
3073         ip6_mforward = X_ip6_mforward;
3074         ip6_mrouter_done = X_ip6_mrouter_done;
3075         ip6_mrouter_get = X_ip6_mrouter_get;
3076         ip6_mrouter_set = X_ip6_mrouter_set;
3077         mrt6_ioctl = X_mrt6_ioctl;
3078 #endif
3079
3080         ip_rsvp_force_done = X_ip_rsvp_force_done;
3081         ip_rsvp_vif = X_ip_rsvp_vif;
3082
3083         legal_vif_num = X_legal_vif_num;
3084         mrt_ioctl = X_mrt_ioctl;
3085         rsvp_input_p = X_rsvp_input;
3086         break;
3087
3088     case MOD_UNLOAD:
3089         /*
3090          * Typically module unload happens after the user-level
3091          * process has shutdown the kernel services (the check
3092          * below insures someone can't just yank the module out
3093          * from under a running process).  But if the module is
3094          * just loaded and then unloaded w/o starting up a user
3095          * process we still need to cleanup.
3096          */
3097         if (ip_mrouter
3098 #ifdef INET6
3099             || ip6_mrouter
3100 #endif
3101         )
3102             return EINVAL;
3103
3104 #ifdef INET6
3105         if (pim6_encap_cookie) {
3106             encap_detach(pim6_encap_cookie);
3107             pim6_encap_cookie = NULL;
3108         }
3109         X_ip6_mrouter_done();
3110         ip6_mforward = NULL;
3111         ip6_mrouter_done = NULL;
3112         ip6_mrouter_get = NULL;
3113         ip6_mrouter_set = NULL;
3114         mrt6_ioctl = NULL;
3115 #endif
3116
3117         if (pim_encap_cookie) {
3118             encap_detach(pim_encap_cookie);
3119             pim_encap_cookie = NULL;
3120         }
3121         X_ip_mrouter_done();
3122         ip_mcast_src = NULL;
3123         ip_mforward = NULL;
3124         ip_mrouter_done = NULL;
3125         ip_mrouter_get = NULL;
3126         ip_mrouter_set = NULL;
3127
3128         ip_rsvp_force_done = NULL;
3129         ip_rsvp_vif = NULL;
3130
3131         legal_vif_num = NULL;
3132         mrt_ioctl = NULL;
3133         rsvp_input_p = NULL;
3134
3135         VIF_LOCK_DESTROY();
3136         MFC_LOCK_DESTROY();
3137         MROUTER_LOCK_DESTROY();
3138         break;
3139
3140     default:
3141         return EOPNOTSUPP;
3142     }
3143     return 0;
3144 }
3145
3146 static moduledata_t ip_mroutemod = {
3147     "ip_mroute",
3148     ip_mroute_modevent,
3149     0
3150 };
3151 DECLARE_MODULE(ip_mroute, ip_mroutemod, SI_SUB_PSEUDO, SI_ORDER_ANY);