]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/netinet/ip_divert.c
Merge llvm-project release/15.x llvmorg-15.0.7-0-g8dfdcc7b7bf6
[FreeBSD/FreeBSD.git] / sys / netinet / ip_divert.c
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1982, 1986, 1988, 1993
5  *      The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
34
35 #include "opt_inet.h"
36 #include "opt_inet6.h"
37 #include "opt_sctp.h"
38
39 #include <sys/param.h>
40 #include <sys/eventhandler.h>
41 #include <sys/kernel.h>
42 #include <sys/lock.h>
43 #include <sys/malloc.h>
44 #include <sys/mbuf.h>
45 #include <sys/module.h>
46 #include <sys/kernel.h>
47 #include <sys/priv.h>
48 #include <sys/proc.h>
49 #include <sys/domain.h>
50 #include <sys/protosw.h>
51 #include <sys/socket.h>
52 #include <sys/socketvar.h>
53 #include <sys/sysctl.h>
54 #include <net/vnet.h>
55
56 #include <net/if.h>
57 #include <net/if_var.h>
58 #include <net/if_private.h>
59 #include <net/netisr.h>
60
61 #include <netinet/in.h>
62 #include <netinet/in_pcb.h>
63 #include <netinet/in_systm.h>
64 #include <netinet/in_var.h>
65 #include <netinet/ip.h>
66 #include <netinet/ip_var.h>
67 #include <netinet/ip_divert.h>
68 #ifdef INET6
69 #include <netinet/ip6.h>
70 #include <netinet6/ip6_var.h>
71 #endif
72 #if defined(SCTP) || defined(SCTP_SUPPORT)
73 #include <netinet/sctp_crc32.h>
74 #endif
75
76 #include <security/mac/mac_framework.h>
77 /*
78  * Divert sockets
79  */
80
81 /*
82  * Allocate enough space to hold a full IP packet
83  */
84 #define DIVSNDQ         (65536 + 100)
85 #define DIVRCVQ         (65536 + 100)
86
87 /*
88  * Usually a system has very few divert ports.  Previous implementation
89  * used a linked list.
90  */
91 #define DIVHASHSIZE     (1 << 3)        /* 8 entries, one cache line. */
92 #define DIVHASH(port)   (port % DIVHASHSIZE)
93 #define DCBHASH(dcb)    ((dcb)->dcb_port % DIVHASHSIZE)
94
95 /*
96  * Divert sockets work in conjunction with ipfw or other packet filters,
97  * see the divert(4) manpage for features.
98  * Packets are selected by the packet filter and tagged with an
99  * MTAG_IPFW_RULE tag carrying the 'divert port' number (as set by
100  * the packet filter) and information on the matching filter rule for
101  * subsequent reinjection. The divert_port is used to put the packet
102  * on the corresponding divert socket, while the rule number is passed
103  * up (at least partially) as the sin_port in the struct sockaddr.
104  *
105  * Packets written to the divert socket carry in sin_addr a
106  * destination address, and in sin_port the number of the filter rule
107  * after which to continue processing.
108  * If the destination address is INADDR_ANY, the packet is treated as
109  * as outgoing and sent to ip_output(); otherwise it is treated as
110  * incoming and sent to ip_input().
111  * Further, sin_zero carries some information on the interface,
112  * which can be used in the reinject -- see comments in the code.
113  *
114  * On reinjection, processing in ip_input() and ip_output()
115  * will be exactly the same as for the original packet, except that
116  * packet filter processing will start at the rule number after the one
117  * written in the sin_port (ipfw does not allow a rule #0, so sin_port=0
118  * will apply the entire ruleset to the packet).
119  */
120 static SYSCTL_NODE(_net_inet, OID_AUTO, divert, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
121     "divert(4)");
122
123 VNET_PCPUSTAT_DEFINE_STATIC(struct divstat, divstat);
124 VNET_PCPUSTAT_SYSINIT(divstat);
125 #ifdef VIMAGE
126 VNET_PCPUSTAT_SYSUNINIT(divstat);
127 #endif
128 SYSCTL_VNET_PCPUSTAT(_net_inet_divert, OID_AUTO, stats, struct divstat,
129     divstat, "divert(4) socket statistics");
130 #define DIVSTAT_INC(name)       \
131     VNET_PCPUSTAT_ADD(struct divstat, divstat, div_ ## name, 1)
132
133 static u_long   div_sendspace = DIVSNDQ;        /* XXX sysctl ? */
134 static u_long   div_recvspace = DIVRCVQ;        /* XXX sysctl ? */
135
136 static int div_output_inbound(int fmaily, struct socket *so, struct mbuf *m,
137     struct sockaddr_in *sin);
138 static int div_output_outbound(int family, struct socket *so, struct mbuf *m);
139
140 struct divcb {
141         union {
142                 SLIST_ENTRY(divcb)      dcb_next;
143                 intptr_t                dcb_bound;
144 #define DCB_UNBOUND     ((intptr_t)-1)
145         };
146         struct socket           *dcb_socket;
147         uint16_t                 dcb_port;
148         uint64_t                 dcb_gencnt;
149         struct epoch_context     dcb_epochctx;
150 };
151
152 SLIST_HEAD(divhashhead, divcb);
153
154 VNET_DEFINE_STATIC(struct divhashhead, divhash[DIVHASHSIZE]) = {};
155 #define V_divhash       VNET(divhash)
156 VNET_DEFINE_STATIC(uint64_t, dcb_count) = 0;
157 #define V_dcb_count     VNET(dcb_count)
158 VNET_DEFINE_STATIC(uint64_t, dcb_gencnt) = 0;
159 #define V_dcb_gencnt    VNET(dcb_gencnt)
160
161 static struct mtx divert_mtx;
162 MTX_SYSINIT(divert, &divert_mtx, "divert(4) socket pcb lists", MTX_DEF);
163 #define DIVERT_LOCK()   mtx_lock(&divert_mtx)
164 #define DIVERT_UNLOCK() mtx_unlock(&divert_mtx)
165
166 /*
167  * Divert a packet by passing it up to the divert socket at port 'port'.
168  */
169 static void
170 divert_packet(struct mbuf *m, bool incoming)
171 {
172         struct divcb *dcb;
173         u_int16_t nport;
174         struct sockaddr_in divsrc;
175         struct m_tag *mtag;
176
177         NET_EPOCH_ASSERT();
178
179         mtag = m_tag_locate(m, MTAG_IPFW_RULE, 0, NULL);
180         if (mtag == NULL) {
181                 m_freem(m);
182                 return;
183         }
184         /* Assure header */
185         if (m->m_len < sizeof(struct ip) &&
186             (m = m_pullup(m, sizeof(struct ip))) == NULL)
187                 return;
188 #ifdef INET
189         /* Delayed checksums are currently not compatible with divert. */
190         if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
191                 in_delayed_cksum(m);
192                 m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
193         }
194 #if defined(SCTP) || defined(SCTP_SUPPORT)
195         if (m->m_pkthdr.csum_flags & CSUM_SCTP) {
196                 struct ip *ip;
197
198                 ip = mtod(m, struct ip *);
199                 sctp_delayed_cksum(m, (uint32_t)(ip->ip_hl << 2));
200                 m->m_pkthdr.csum_flags &= ~CSUM_SCTP;
201         }
202 #endif
203 #endif
204 #ifdef INET6
205         if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA_IPV6) {
206                 in6_delayed_cksum(m, m->m_pkthdr.len -
207                     sizeof(struct ip6_hdr), sizeof(struct ip6_hdr));
208                 m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA_IPV6;
209         }
210 #if defined(SCTP) || defined(SCTP_SUPPORT)
211         if (m->m_pkthdr.csum_flags & CSUM_SCTP_IPV6) {
212                 sctp_delayed_cksum(m, sizeof(struct ip6_hdr));
213                 m->m_pkthdr.csum_flags &= ~CSUM_SCTP_IPV6;
214         }
215 #endif
216 #endif /* INET6 */
217         bzero(&divsrc, sizeof(divsrc));
218         divsrc.sin_len = sizeof(divsrc);
219         divsrc.sin_family = AF_INET;
220         /* record matching rule, in host format */
221         divsrc.sin_port = ((struct ipfw_rule_ref *)(mtag+1))->rulenum;
222         /*
223          * Record receive interface address, if any.
224          * But only for incoming packets.
225          */
226         if (incoming) {
227                 struct ifaddr *ifa;
228                 struct ifnet *ifp;
229
230                 /* Sanity check */
231                 M_ASSERTPKTHDR(m);
232
233                 /* Find IP address for receive interface */
234                 ifp = m->m_pkthdr.rcvif;
235                 CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
236                         if (ifa->ifa_addr->sa_family != AF_INET)
237                                 continue;
238                         divsrc.sin_addr =
239                             ((struct sockaddr_in *) ifa->ifa_addr)->sin_addr;
240                         break;
241                 }
242         }
243         /*
244          * Record the incoming interface name whenever we have one.
245          */
246         if (m->m_pkthdr.rcvif) {
247                 /*
248                  * Hide the actual interface name in there in the
249                  * sin_zero array. XXX This needs to be moved to a
250                  * different sockaddr type for divert, e.g.
251                  * sockaddr_div with multiple fields like
252                  * sockaddr_dl. Presently we have only 7 bytes
253                  * but that will do for now as most interfaces
254                  * are 4 or less + 2 or less bytes for unit.
255                  * There is probably a faster way of doing this,
256                  * possibly taking it from the sockaddr_dl on the iface.
257                  * This solves the problem of a P2P link and a LAN interface
258                  * having the same address, which can result in the wrong
259                  * interface being assigned to the packet when fed back
260                  * into the divert socket. Theoretically if the daemon saves
261                  * and re-uses the sockaddr_in as suggested in the man pages,
262                  * this iface name will come along for the ride.
263                  * (see div_output for the other half of this.)
264                  */
265                 strlcpy(divsrc.sin_zero, m->m_pkthdr.rcvif->if_xname,
266                     sizeof(divsrc.sin_zero));
267         }
268
269         /* Put packet on socket queue, if any */
270         nport = htons((uint16_t)(((struct ipfw_rule_ref *)(mtag+1))->info));
271         SLIST_FOREACH(dcb, &V_divhash[DIVHASH(nport)], dcb_next)
272                 if (dcb->dcb_port == nport)
273                         break;
274
275         if (dcb != NULL) {
276                 struct socket *sa = dcb->dcb_socket;
277
278                 SOCKBUF_LOCK(&sa->so_rcv);
279                 if (sbappendaddr_locked(&sa->so_rcv,
280                     (struct sockaddr *)&divsrc, m, NULL) == 0) {
281                         soroverflow_locked(sa);
282                         m_freem(m);
283                 } else {
284                         sorwakeup_locked(sa);
285                         DIVSTAT_INC(diverted);
286                 }
287         } else {
288                 DIVSTAT_INC(noport);
289                 m_freem(m);
290         }
291 }
292
293 /*
294  * Deliver packet back into the IP processing machinery.
295  *
296  * If no address specified, or address is 0.0.0.0, send to ip_output();
297  * otherwise, send to ip_input() and mark as having been received on
298  * the interface with that address.
299  */
300 static int
301 div_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
302     struct mbuf *control, struct thread *td)
303 {
304         struct epoch_tracker et;
305         struct sockaddr_in *sin = (struct sockaddr_in *)nam;
306         const struct ip *ip;
307         struct m_tag *mtag;
308         struct ipfw_rule_ref *dt;
309         int error, family;
310
311         if (control)
312                 m_freem(control);
313
314         /* Packet must have a header (but that's about it) */
315         if (m->m_len < sizeof (struct ip) &&
316             (m = m_pullup(m, sizeof (struct ip))) == NULL) {
317                 m_freem(m);
318                 return (EINVAL);
319         }
320
321         if (sin != NULL) {
322                 if (sin->sin_family != AF_INET) {
323                         m_freem(m);
324                         return (EAFNOSUPPORT);
325                 }
326                 if (sin->sin_len != sizeof(*sin)) {
327                         m_freem(m);
328                         return (EINVAL);
329                 }
330         }
331
332         /*
333          * An mbuf may hasn't come from userland, but we pretend
334          * that it has.
335          */
336         m->m_pkthdr.rcvif = NULL;
337         m->m_nextpkt = NULL;
338         M_SETFIB(m, so->so_fibnum);
339
340         mtag = m_tag_locate(m, MTAG_IPFW_RULE, 0, NULL);
341         if (mtag == NULL) {
342                 /* this should be normal */
343                 mtag = m_tag_alloc(MTAG_IPFW_RULE, 0,
344                     sizeof(struct ipfw_rule_ref), M_NOWAIT | M_ZERO);
345                 if (mtag == NULL) {
346                         m_freem(m);
347                         return (ENOBUFS);
348                 }
349                 m_tag_prepend(m, mtag);
350         }
351         dt = (struct ipfw_rule_ref *)(mtag+1);
352
353         /* Loopback avoidance and state recovery */
354         if (sin) {
355                 int i;
356
357                 /* set the starting point. We provide a non-zero slot,
358                  * but a non_matching chain_id to skip that info and use
359                  * the rulenum/rule_id.
360                  */
361                 dt->slot = 1; /* dummy, chain_id is invalid */
362                 dt->chain_id = 0;
363                 dt->rulenum = sin->sin_port+1; /* host format ? */
364                 dt->rule_id = 0;
365                 /* XXX: broken for IPv6 */
366                 /*
367                  * Find receive interface with the given name, stuffed
368                  * (if it exists) in the sin_zero[] field.
369                  * The name is user supplied data so don't trust its size
370                  * or that it is zero terminated.
371                  */
372                 for (i = 0; i < sizeof(sin->sin_zero) && sin->sin_zero[i]; i++)
373                         ;
374                 if ( i > 0 && i < sizeof(sin->sin_zero))
375                         m->m_pkthdr.rcvif = ifunit(sin->sin_zero);
376         }
377
378         ip = mtod(m, struct ip *);
379         switch (ip->ip_v) {
380 #ifdef INET
381         case IPVERSION:
382                 family = AF_INET;
383                 break;
384 #endif
385 #ifdef INET6
386         case IPV6_VERSION >> 4:
387                 family = AF_INET6;
388                 break;
389 #endif
390         default:
391                 m_freem(m);
392                 return (EAFNOSUPPORT);
393         }
394
395         /* Reinject packet into the system as incoming or outgoing */
396         NET_EPOCH_ENTER(et);
397         if (!sin || sin->sin_addr.s_addr == 0) {
398                 dt->info |= IPFW_IS_DIVERT | IPFW_INFO_OUT;
399                 error = div_output_outbound(family, so, m);
400         } else {
401                 dt->info |= IPFW_IS_DIVERT | IPFW_INFO_IN;
402                 error = div_output_inbound(family, so, m, sin);
403         }
404         NET_EPOCH_EXIT(et);
405
406         return (error);
407 }
408
409 /*
410  * Sends mbuf @m to the wire via ip[6]_output().
411  *
412  * Returns 0 on success or an errno value on failure.  @m is always consumed.
413  */
414 static int
415 div_output_outbound(int family, struct socket *so, struct mbuf *m)
416 {
417         int error;
418
419         switch (family) {
420 #ifdef INET
421         case AF_INET:
422             {
423                 struct ip *const ip = mtod(m, struct ip *);
424
425                 /* Don't allow packet length sizes that will crash. */
426                 if (((u_short)ntohs(ip->ip_len) > m->m_pkthdr.len)) {
427                         m_freem(m);
428                         return (EINVAL);
429                 }
430                 break;
431             }
432 #endif
433 #ifdef INET6
434         case AF_INET6:
435             {
436                 struct ip6_hdr *const ip6 = mtod(m, struct ip6_hdr *);
437
438                 /* Don't allow packet length sizes that will crash */
439                 if (((u_short)ntohs(ip6->ip6_plen) > m->m_pkthdr.len)) {
440                         m_freem(m);
441                         return (EINVAL);
442                 }
443                 break;
444             }
445 #endif
446         }
447
448 #ifdef MAC
449         mac_socket_create_mbuf(so, m);
450 #endif
451
452         error = 0;
453         switch (family) {
454 #ifdef INET
455         case AF_INET:
456                 error = ip_output(m, NULL, NULL,
457                     ((so->so_options & SO_DONTROUTE) ? IP_ROUTETOIF : 0)
458                     | IP_ALLOWBROADCAST | IP_RAWOUTPUT, NULL, NULL);
459                 break;
460 #endif
461 #ifdef INET6
462         case AF_INET6:
463                 error = ip6_output(m, NULL, NULL, 0, NULL, NULL, NULL);
464                 break;
465 #endif
466         }
467         if (error == 0)
468                 DIVSTAT_INC(outbound);
469
470         return (error);
471 }
472
473 /*
474  * Schedules mbuf @m for local processing via IPv4/IPv6 netisr queue.
475  *
476  * Returns 0 on success or an errno value on failure.  @m is always consumed.
477  */
478 static int
479 div_output_inbound(int family, struct socket *so, struct mbuf *m,
480     struct sockaddr_in *sin)
481 {
482         struct ifaddr *ifa;
483
484         if (m->m_pkthdr.rcvif == NULL) {
485                 /*
486                  * No luck with the name, check by IP address.
487                  * Clear the port and the ifname to make sure
488                  * there are no distractions for ifa_ifwithaddr.
489                  */
490
491                 /* XXX: broken for IPv6 */
492                 bzero(sin->sin_zero, sizeof(sin->sin_zero));
493                 sin->sin_port = 0;
494                 ifa = ifa_ifwithaddr((struct sockaddr *) sin);
495                 if (ifa == NULL) {
496                         m_freem(m);
497                         return (EADDRNOTAVAIL);
498                 }
499                 m->m_pkthdr.rcvif = ifa->ifa_ifp;
500         }
501 #ifdef MAC
502         mac_socket_create_mbuf(so, m);
503 #endif
504         /* Send packet to input processing via netisr */
505         switch (family) {
506 #ifdef INET
507         case AF_INET:
508             {
509                 const struct ip *ip;
510
511                 ip = mtod(m, struct ip *);
512                 /*
513                  * Restore M_BCAST flag when destination address is
514                  * broadcast. It is expected by ip_tryforward().
515                  */
516                 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)))
517                         m->m_flags |= M_MCAST;
518                 else if (in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
519                         m->m_flags |= M_BCAST;
520                 netisr_queue_src(NETISR_IP, (uintptr_t)so, m);
521                 DIVSTAT_INC(inbound);
522                 break;
523             }
524 #endif
525 #ifdef INET6
526         case AF_INET6:
527                 netisr_queue_src(NETISR_IPV6, (uintptr_t)so, m);
528                 DIVSTAT_INC(inbound);
529                 break;
530 #endif
531         default:
532                 m_freem(m);
533                 return (EINVAL);
534         }
535
536         return (0);
537 }
538
539 static int
540 div_attach(struct socket *so, int proto, struct thread *td)
541 {
542         struct divcb *dcb;
543         int error;
544
545         if (td != NULL) {
546                 error = priv_check(td, PRIV_NETINET_DIVERT);
547                 if (error)
548                         return (error);
549         }
550         error = soreserve(so, div_sendspace, div_recvspace);
551         if (error)
552                 return error;
553         dcb = malloc(sizeof(*dcb), M_PCB, M_WAITOK);
554         dcb->dcb_bound = DCB_UNBOUND;
555         dcb->dcb_socket = so;
556         DIVERT_LOCK();
557         V_dcb_count++;
558         dcb->dcb_gencnt = ++V_dcb_gencnt;
559         DIVERT_UNLOCK();
560         so->so_pcb = dcb;
561
562         return (0);
563 }
564
565 static void
566 div_free(epoch_context_t ctx)
567 {
568         struct divcb *dcb = __containerof(ctx, struct divcb, dcb_epochctx);
569
570         free(dcb, M_PCB);
571 }
572
573 static void
574 div_detach(struct socket *so)
575 {
576         struct divcb *dcb = so->so_pcb;
577
578         so->so_pcb = NULL;
579         DIVERT_LOCK();
580         if (dcb->dcb_bound != DCB_UNBOUND)
581                 SLIST_REMOVE(&V_divhash[DCBHASH(dcb)], dcb, divcb, dcb_next);
582         V_dcb_count--;
583         V_dcb_gencnt++;
584         DIVERT_UNLOCK();
585         NET_EPOCH_CALL(div_free, &dcb->dcb_epochctx);
586 }
587
588 static int
589 div_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
590 {
591         struct divcb *dcb;
592         uint16_t port;
593
594         if (nam->sa_family != AF_INET)
595                 return EAFNOSUPPORT;
596         if (nam->sa_len != sizeof(struct sockaddr_in))
597                 return EINVAL;
598         port = ((struct sockaddr_in *)nam)->sin_port;
599         DIVERT_LOCK();
600         SLIST_FOREACH(dcb, &V_divhash[DIVHASH(port)], dcb_next)
601                 if (dcb->dcb_port == port) {
602                         DIVERT_UNLOCK();
603                         return (EADDRINUSE);
604                 }
605         dcb = so->so_pcb;
606         if (dcb->dcb_bound != DCB_UNBOUND)
607                 SLIST_REMOVE(&V_divhash[DCBHASH(dcb)], dcb, divcb, dcb_next);
608         dcb->dcb_port = port;
609         SLIST_INSERT_HEAD(&V_divhash[DIVHASH(port)], dcb, dcb_next);
610         DIVERT_UNLOCK();
611
612         return (0);
613 }
614
615 static int
616 div_shutdown(struct socket *so)
617 {
618
619         socantsendmore(so);
620         return 0;
621 }
622
623 static int
624 div_pcblist(SYSCTL_HANDLER_ARGS)
625 {
626         struct xinpgen xig;
627         struct divcb *dcb;
628         int error;
629
630         if (req->newptr != 0)
631                 return EPERM;
632
633         if (req->oldptr == 0) {
634                 u_int n;
635
636                 n = V_dcb_count;
637                 n += imax(n / 8, 10);
638                 req->oldidx = 2 * (sizeof xig) + n * sizeof(struct xinpcb);
639                 return 0;
640         }
641
642         if ((error = sysctl_wire_old_buffer(req, 0)) != 0)
643                 return (error);
644
645         bzero(&xig, sizeof(xig));
646         xig.xig_len = sizeof xig;
647         xig.xig_count = V_dcb_count;
648         xig.xig_gen = V_dcb_gencnt;
649         xig.xig_sogen = so_gencnt;
650         error = SYSCTL_OUT(req, &xig, sizeof xig);
651         if (error)
652                 return error;
653
654         DIVERT_LOCK();
655         for (int i = 0; i < DIVHASHSIZE; i++)
656                 SLIST_FOREACH(dcb, &V_divhash[i], dcb_next) {
657                         if (dcb->dcb_gencnt <= xig.xig_gen) {
658                                 struct xinpcb xi;
659
660                                 bzero(&xi, sizeof(xi));
661                                 xi.xi_len = sizeof(struct xinpcb);
662                                 sotoxsocket(dcb->dcb_socket, &xi.xi_socket);
663                                 xi.inp_gencnt = dcb->dcb_gencnt;
664                                 xi.inp_vflag = INP_IPV4; /* XXX: netstat(1) */
665                                 xi.inp_inc.inc_ie.ie_lport = dcb->dcb_port;
666                                 error = SYSCTL_OUT(req, &xi, sizeof xi);
667                                 if (error)
668                                         goto errout;
669                         }
670                 }
671
672         /*
673          * Give the user an updated idea of our state.
674          * If the generation differs from what we told
675          * her before, she knows that something happened
676          * while we were processing this request, and it
677          * might be necessary to retry.
678          */
679         xig.xig_gen = V_dcb_gencnt;
680         xig.xig_sogen = so_gencnt;
681         xig.xig_count = V_dcb_count;
682         error = SYSCTL_OUT(req, &xig, sizeof xig);
683
684 errout:
685         DIVERT_UNLOCK();
686
687         return (error);
688 }
689 SYSCTL_PROC(_net_inet_divert, OID_AUTO, pcblist,
690     CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, 0, div_pcblist,
691     "S,xinpcb", "List of active divert sockets");
692
693 static struct protosw div_protosw = {
694         .pr_type =              SOCK_RAW,
695         .pr_flags =             PR_ATOMIC|PR_ADDR,
696         .pr_attach =            div_attach,
697         .pr_bind =              div_bind,
698         .pr_detach =            div_detach,
699         .pr_send =              div_send,
700         .pr_shutdown =          div_shutdown,
701 };
702
703 static struct domain divertdomain = {
704         .dom_family =   PF_DIVERT,
705         .dom_name =     "divert",
706         .dom_nprotosw = 1,
707         .dom_protosw =  { &div_protosw },
708 };
709
710 static int
711 div_modevent(module_t mod, int type, void *unused)
712 {
713         int err = 0;
714
715         switch (type) {
716         case MOD_LOAD:
717                 domain_add(&divertdomain);
718                 ip_divert_ptr = divert_packet;
719                 break;
720         case MOD_QUIESCE:
721                 /*
722                  * IPDIVERT may normally not be unloaded because of the
723                  * potential race conditions.  Tell kldunload we can't be
724                  * unloaded unless the unload is forced.
725                  */
726                 err = EPERM;
727                 break;
728         case MOD_UNLOAD:
729                 /*
730                  * Forced unload.
731                  *
732                  * Module ipdivert can only be unloaded if no sockets are
733                  * connected.  Maybe this can be changed later to forcefully
734                  * disconnect any open sockets.
735                  *
736                  * XXXRW: Note that there is a slight race here, as a new
737                  * socket open request could be spinning on the lock and then
738                  * we destroy the lock.
739                  *
740                  * XXXGL: One more reason this code is incorrect is that it
741                  * checks only the current vnet.
742                  */
743                 DIVERT_LOCK();
744                 if (V_dcb_count != 0) {
745                         DIVERT_UNLOCK();
746                         err = EBUSY;
747                         break;
748                 }
749                 DIVERT_UNLOCK();
750                 ip_divert_ptr = NULL;
751                 domain_remove(&divertdomain);
752                 break;
753         default:
754                 err = EOPNOTSUPP;
755                 break;
756         }
757         return err;
758 }
759
760 static moduledata_t ipdivertmod = {
761         "ipdivert",
762         div_modevent,
763         0
764 };
765
766 DECLARE_MODULE(ipdivert, ipdivertmod, SI_SUB_PROTO_FIREWALL, SI_ORDER_ANY);
767 MODULE_VERSION(ipdivert, 1);