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