]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/netinet/ip_divert.c
Autogenerate hardware notes for the uath(4) driver.
[FreeBSD/FreeBSD.git] / sys / netinet / ip_divert.c
1 /*-
2  * Copyright (c) 1982, 1986, 1988, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 4. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
32
33 #if !defined(KLD_MODULE)
34 #include "opt_inet.h"
35 #include "opt_ipfw.h"
36 #include "opt_mac.h"
37 #include "opt_sctp.h"
38 #ifndef INET
39 #error "IPDIVERT requires INET."
40 #endif
41 #ifndef IPFIREWALL
42 #error "IPDIVERT requires IPFIREWALL"
43 #endif
44 #endif
45
46 #include <sys/param.h>
47 #include <sys/kernel.h>
48 #include <sys/lock.h>
49 #include <sys/malloc.h>
50 #include <sys/mbuf.h>
51 #include <sys/module.h>
52 #include <sys/kernel.h>
53 #include <sys/priv.h>
54 #include <sys/proc.h>
55 #include <sys/protosw.h>
56 #include <sys/rwlock.h>
57 #include <sys/signalvar.h>
58 #include <sys/socket.h>
59 #include <sys/socketvar.h>
60 #include <sys/sx.h>
61 #include <sys/sysctl.h>
62 #include <sys/systm.h>
63 #include <sys/vimage.h>
64
65 #include <vm/uma.h>
66
67 #include <net/if.h>
68 #include <net/netisr.h> 
69 #include <net/route.h>
70
71 #include <netinet/in.h>
72 #include <netinet/in_pcb.h>
73 #include <netinet/in_systm.h>
74 #include <netinet/in_var.h>
75 #include <netinet/ip.h>
76 #include <netinet/ip_divert.h>
77 #include <netinet/ip_var.h>
78 #include <netinet/ip_fw.h>
79 #include <netinet/vinet.h>
80 #ifdef SCTP
81 #include <netinet/sctp_crc32.h>
82 #endif
83
84 #include <security/mac/mac_framework.h>
85
86 /*
87  * Divert sockets
88  */
89
90 /*
91  * Allocate enough space to hold a full IP packet
92  */
93 #define DIVSNDQ         (65536 + 100)
94 #define DIVRCVQ         (65536 + 100)
95
96 /*
97  * Divert sockets work in conjunction with ipfw, see the divert(4)
98  * manpage for features.
99  * Internally, packets selected by ipfw in ip_input() or ip_output(),
100  * and never diverted before, are passed to the input queue of the
101  * divert socket with a given 'divert_port' number (as specified in
102  * the matching ipfw rule), and they are tagged with a 16 bit cookie
103  * (representing the rule number of the matching ipfw rule), which
104  * is passed to process reading from the socket.
105  *
106  * Packets written to the divert socket are again tagged with a cookie
107  * (usually the same as above) and a destination address.
108  * If the destination address is INADDR_ANY then the packet is
109  * treated as outgoing and sent to ip_output(), otherwise it is
110  * treated as incoming and sent to ip_input().
111  * In both cases, the packet is tagged with the cookie.
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  * ipfw processing will start at the rule number after the one
116  * written in the cookie (so, tagging a packet with a cookie of 0
117  * will cause it to be effectively considered as a standard packet).
118  */
119
120 /* Internal variables. */
121 #ifdef VIMAGE_GLOBALS
122 static struct inpcbhead divcb;
123 static struct inpcbinfo divcbinfo;
124 #endif
125
126 static u_long   div_sendspace = DIVSNDQ;        /* XXX sysctl ? */
127 static u_long   div_recvspace = DIVRCVQ;        /* XXX sysctl ? */
128
129 /*
130  * Initialize divert connection block queue.
131  */
132 static void
133 div_zone_change(void *tag)
134 {
135
136         uma_zone_set_max(V_divcbinfo.ipi_zone, maxsockets);
137 }
138
139 static int
140 div_inpcb_init(void *mem, int size, int flags)
141 {
142         struct inpcb *inp = mem;
143
144         INP_LOCK_INIT(inp, "inp", "divinp");
145         return (0);
146 }
147
148 static void
149 div_inpcb_fini(void *mem, int size)
150 {
151         struct inpcb *inp = mem;
152
153         INP_LOCK_DESTROY(inp);
154 }
155
156 void
157 div_init(void)
158 {
159         INIT_VNET_INET(curvnet);
160
161         INP_INFO_LOCK_INIT(&V_divcbinfo, "div");
162         LIST_INIT(&V_divcb);
163         V_divcbinfo.ipi_listhead = &V_divcb;
164         /*
165          * XXX We don't use the hash list for divert IP, but it's easier
166          * to allocate a one entry hash list than it is to check all
167          * over the place for hashbase == NULL.
168          */
169         V_divcbinfo.ipi_hashbase = hashinit(1, M_PCB, &V_divcbinfo.ipi_hashmask);
170         V_divcbinfo.ipi_porthashbase = hashinit(1, M_PCB,
171             &V_divcbinfo.ipi_porthashmask);
172         V_divcbinfo.ipi_zone = uma_zcreate("divcb", sizeof(struct inpcb),
173             NULL, NULL, div_inpcb_init, div_inpcb_fini, UMA_ALIGN_PTR,
174             UMA_ZONE_NOFREE);
175         uma_zone_set_max(V_divcbinfo.ipi_zone, maxsockets);
176         EVENTHANDLER_REGISTER(maxsockets_change, div_zone_change,
177                 NULL, EVENTHANDLER_PRI_ANY);
178 }
179
180 /*
181  * IPPROTO_DIVERT is not in the real IP protocol number space; this
182  * function should never be called.  Just in case, drop any packets.
183  */
184 void
185 div_input(struct mbuf *m, int off)
186 {
187         INIT_VNET_INET(curvnet);
188
189         V_ipstat.ips_noproto++;
190         m_freem(m);
191 }
192
193 /*
194  * Divert a packet by passing it up to the divert socket at port 'port'.
195  *
196  * Setup generic address and protocol structures for div_input routine,
197  * then pass them along with mbuf chain.
198  */
199 static void
200 divert_packet(struct mbuf *m, int incoming)
201 {
202         INIT_VNET_INET(curvnet);
203         struct ip *ip;
204         struct inpcb *inp;
205         struct socket *sa;
206         u_int16_t nport;
207         struct sockaddr_in divsrc;
208         struct m_tag *mtag;
209
210         mtag = m_tag_find(m, PACKET_TAG_DIVERT, NULL);
211         if (mtag == NULL) {
212                 printf("%s: no divert tag\n", __func__);
213                 m_freem(m);
214                 return;
215         }
216         /* Assure header */
217         if (m->m_len < sizeof(struct ip) &&
218             (m = m_pullup(m, sizeof(struct ip))) == 0)
219                 return;
220         ip = mtod(m, struct ip *);
221
222         /* Delayed checksums are currently not compatible with divert. */
223         if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
224                 ip->ip_len = ntohs(ip->ip_len);
225                 in_delayed_cksum(m);
226                 m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
227                 ip->ip_len = htons(ip->ip_len);
228         }
229 #ifdef SCTP
230         if (m->m_pkthdr.csum_flags & CSUM_SCTP) {
231                 ip->ip_len = ntohs(ip->ip_len);
232                 sctp_delayed_cksum(m);
233                 m->m_pkthdr.csum_flags &= ~CSUM_SCTP;
234                 ip->ip_len = htons(ip->ip_len);
235         }
236 #endif
237         /*
238          * Record receive interface address, if any.
239          * But only for incoming packets.
240          */
241         bzero(&divsrc, sizeof(divsrc));
242         divsrc.sin_len = sizeof(divsrc);
243         divsrc.sin_family = AF_INET;
244         divsrc.sin_port = divert_cookie(mtag);  /* record matching rule */
245         if (incoming) {
246                 struct ifaddr *ifa;
247
248                 /* Sanity check */
249                 M_ASSERTPKTHDR(m);
250
251                 /* Find IP address for receive interface */
252                 TAILQ_FOREACH(ifa, &m->m_pkthdr.rcvif->if_addrhead, ifa_link) {
253                         if (ifa->ifa_addr->sa_family != AF_INET)
254                                 continue;
255                         divsrc.sin_addr =
256                             ((struct sockaddr_in *) ifa->ifa_addr)->sin_addr;
257                         break;
258                 }
259         }
260         /*
261          * Record the incoming interface name whenever we have one.
262          */
263         if (m->m_pkthdr.rcvif) {
264                 /*
265                  * Hide the actual interface name in there in the 
266                  * sin_zero array. XXX This needs to be moved to a
267                  * different sockaddr type for divert, e.g.
268                  * sockaddr_div with multiple fields like 
269                  * sockaddr_dl. Presently we have only 7 bytes
270                  * but that will do for now as most interfaces
271                  * are 4 or less + 2 or less bytes for unit.
272                  * There is probably a faster way of doing this,
273                  * possibly taking it from the sockaddr_dl on the iface.
274                  * This solves the problem of a P2P link and a LAN interface
275                  * having the same address, which can result in the wrong
276                  * interface being assigned to the packet when fed back
277                  * into the divert socket. Theoretically if the daemon saves
278                  * and re-uses the sockaddr_in as suggested in the man pages,
279                  * this iface name will come along for the ride.
280                  * (see div_output for the other half of this.)
281                  */ 
282                 strlcpy(divsrc.sin_zero, m->m_pkthdr.rcvif->if_xname,
283                     sizeof(divsrc.sin_zero));
284         }
285
286         /* Put packet on socket queue, if any */
287         sa = NULL;
288         nport = htons((u_int16_t)divert_info(mtag));
289         INP_INFO_RLOCK(&V_divcbinfo);
290         LIST_FOREACH(inp, &V_divcb, inp_list) {
291                 /* XXX why does only one socket match? */
292                 if (inp->inp_lport == nport) {
293                         INP_RLOCK(inp);
294                         sa = inp->inp_socket;
295                         SOCKBUF_LOCK(&sa->so_rcv);
296                         if (sbappendaddr_locked(&sa->so_rcv,
297                             (struct sockaddr *)&divsrc, m,
298                             (struct mbuf *)0) == 0) {
299                                 SOCKBUF_UNLOCK(&sa->so_rcv);
300                                 sa = NULL;      /* force mbuf reclaim below */
301                         } else
302                                 sorwakeup_locked(sa);
303                         INP_RUNLOCK(inp);
304                         break;
305                 }
306         }
307         INP_INFO_RUNLOCK(&V_divcbinfo);
308         if (sa == NULL) {
309                 m_freem(m);
310                 V_ipstat.ips_noproto++;
311                 V_ipstat.ips_delivered--;
312         }
313 }
314
315 /*
316  * Deliver packet back into the IP processing machinery.
317  *
318  * If no address specified, or address is 0.0.0.0, send to ip_output();
319  * otherwise, send to ip_input() and mark as having been received on
320  * the interface with that address.
321  */
322 static int
323 div_output(struct socket *so, struct mbuf *m, struct sockaddr_in *sin,
324     struct mbuf *control)
325 {
326         INIT_VNET_INET(curvnet);
327         struct m_tag *mtag;
328         struct divert_tag *dt;
329         int error = 0;
330         struct mbuf *options;
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         if (control)
341                 m_freem(control);               /* XXX */
342
343         if ((mtag = m_tag_find(m, PACKET_TAG_DIVERT, NULL)) == NULL) {
344                 mtag = m_tag_get(PACKET_TAG_DIVERT, sizeof(struct divert_tag),
345                     M_NOWAIT | M_ZERO);
346                 if (mtag == NULL) {
347                         error = ENOBUFS;
348                         goto cantsend;
349                 }
350                 dt = (struct divert_tag *)(mtag+1);
351                 m_tag_prepend(m, mtag);
352         } else
353                 dt = (struct divert_tag *)(mtag+1);
354
355         /* Loopback avoidance and state recovery */
356         if (sin) {
357                 int i;
358
359                 dt->cookie = sin->sin_port;
360                 /*
361                  * Find receive interface with the given name, stuffed
362                  * (if it exists) in the sin_zero[] field.
363                  * The name is user supplied data so don't trust its size
364                  * or that it is zero terminated.
365                  */
366                 for (i = 0; i < sizeof(sin->sin_zero) && sin->sin_zero[i]; i++)
367                         ;
368                 if ( i > 0 && i < sizeof(sin->sin_zero))
369                         m->m_pkthdr.rcvif = ifunit(sin->sin_zero);
370         }
371
372         /* Reinject packet into the system as incoming or outgoing */
373         if (!sin || sin->sin_addr.s_addr == 0) {
374                 struct ip *const ip = mtod(m, struct ip *);
375                 struct inpcb *inp;
376
377                 dt->info |= IP_FW_DIVERT_OUTPUT_FLAG;
378                 INP_INFO_WLOCK(&V_divcbinfo);
379                 inp = sotoinpcb(so);
380                 INP_RLOCK(inp);
381                 /*
382                  * Don't allow both user specified and setsockopt options,
383                  * and don't allow packet length sizes that will crash
384                  */
385                 if (((ip->ip_hl != (sizeof (*ip) >> 2)) && inp->inp_options) ||
386                      ((u_short)ntohs(ip->ip_len) > m->m_pkthdr.len)) {
387                         error = EINVAL;
388                         INP_RUNLOCK(inp);
389                         INP_INFO_WUNLOCK(&V_divcbinfo);
390                         m_freem(m);
391                 } else {
392                         /* Convert fields to host order for ip_output() */
393                         ip->ip_len = ntohs(ip->ip_len);
394                         ip->ip_off = ntohs(ip->ip_off);
395
396                         /* Send packet to output processing */
397                         V_ipstat.ips_rawout++;                  /* XXX */
398
399 #ifdef MAC
400                         mac_inpcb_create_mbuf(inp, m);
401 #endif
402                         /*
403                          * Get ready to inject the packet into ip_output().
404                          * Just in case socket options were specified on the
405                          * divert socket, we duplicate them.  This is done
406                          * to avoid having to hold the PCB locks over the call
407                          * to ip_output(), as doing this results in a number of
408                          * lock ordering complexities.
409                          *
410                          * Note that we set the multicast options argument for
411                          * ip_output() to NULL since it should be invariant that
412                          * they are not present.
413                          */
414                         KASSERT(inp->inp_moptions == NULL,
415                             ("multicast options set on a divert socket"));
416                         options = NULL;
417                         /*
418                          * XXXCSJP: It is unclear to me whether or not it makes
419                          * sense for divert sockets to have options.  However,
420                          * for now we will duplicate them with the INP locks
421                          * held so we can use them in ip_output() without
422                          * requring a reference to the pcb.
423                          */
424                         if (inp->inp_options != NULL) {
425                                 options = m_dup(inp->inp_options, M_DONTWAIT);
426                                 if (options == NULL)
427                                         error = ENOBUFS;
428                         }
429                         INP_RUNLOCK(inp);
430                         INP_INFO_WUNLOCK(&V_divcbinfo);
431                         if (error == ENOBUFS) {
432                                 m_freem(m);
433                                 return (error);
434                         }
435                         error = ip_output(m, options, NULL,
436                             ((so->so_options & SO_DONTROUTE) ?
437                             IP_ROUTETOIF : 0) | IP_ALLOWBROADCAST |
438                             IP_RAWOUTPUT, NULL, NULL);
439                         if (options != NULL)
440                                 m_freem(options);
441                 }
442         } else {
443                 dt->info |= IP_FW_DIVERT_LOOPBACK_FLAG;
444                 if (m->m_pkthdr.rcvif == NULL) {
445                         /*
446                          * No luck with the name, check by IP address.
447                          * Clear the port and the ifname to make sure
448                          * there are no distractions for ifa_ifwithaddr.
449                          */
450                         struct  ifaddr *ifa;
451
452                         bzero(sin->sin_zero, sizeof(sin->sin_zero));
453                         sin->sin_port = 0;
454                         ifa = ifa_ifwithaddr((struct sockaddr *) sin);
455                         if (ifa == NULL) {
456                                 error = EADDRNOTAVAIL;
457                                 goto cantsend;
458                         }
459                         m->m_pkthdr.rcvif = ifa->ifa_ifp;
460                 }
461 #ifdef MAC
462                 SOCK_LOCK(so);
463                 mac_socket_create_mbuf(so, m);
464                 SOCK_UNLOCK(so);
465 #endif
466                 /* Send packet to input processing via netisr */
467                 netisr_queue(NETISR_IP, m);
468         }
469
470         return error;
471
472 cantsend:
473         m_freem(m);
474         return error;
475 }
476
477 static int
478 div_attach(struct socket *so, int proto, struct thread *td)
479 {
480         INIT_VNET_INET(so->so_vnet);
481         struct inpcb *inp;
482         int error;
483
484         inp  = sotoinpcb(so);
485         KASSERT(inp == NULL, ("div_attach: inp != NULL"));
486         if (td != NULL) {
487                 error = priv_check(td, PRIV_NETINET_DIVERT);
488                 if (error)
489                         return (error);
490         }
491         error = soreserve(so, div_sendspace, div_recvspace);
492         if (error)
493                 return error;
494         INP_INFO_WLOCK(&V_divcbinfo);
495         error = in_pcballoc(so, &V_divcbinfo);
496         if (error) {
497                 INP_INFO_WUNLOCK(&V_divcbinfo);
498                 return error;
499         }
500         inp = (struct inpcb *)so->so_pcb;
501         INP_INFO_WUNLOCK(&V_divcbinfo);
502         inp->inp_ip_p = proto;
503         inp->inp_vflag |= INP_IPV4;
504         inp->inp_flags |= INP_HDRINCL;
505         INP_WUNLOCK(inp);
506         return 0;
507 }
508
509 static void
510 div_detach(struct socket *so)
511 {
512         INIT_VNET_INET(so->so_vnet);
513         struct inpcb *inp;
514
515         inp = sotoinpcb(so);
516         KASSERT(inp != NULL, ("div_detach: inp == NULL"));
517         INP_INFO_WLOCK(&V_divcbinfo);
518         INP_WLOCK(inp);
519         in_pcbdetach(inp);
520         in_pcbfree(inp);
521         INP_INFO_WUNLOCK(&V_divcbinfo);
522 }
523
524 static int
525 div_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
526 {
527         INIT_VNET_INET(so->so_vnet);
528         struct inpcb *inp;
529         int error;
530
531         inp = sotoinpcb(so);
532         KASSERT(inp != NULL, ("div_bind: inp == NULL"));
533         /* in_pcbbind assumes that nam is a sockaddr_in
534          * and in_pcbbind requires a valid address. Since divert
535          * sockets don't we need to make sure the address is
536          * filled in properly.
537          * XXX -- divert should not be abusing in_pcbind
538          * and should probably have its own family.
539          */
540         if (nam->sa_family != AF_INET)
541                 return EAFNOSUPPORT;
542         ((struct sockaddr_in *)nam)->sin_addr.s_addr = INADDR_ANY;
543         INP_INFO_WLOCK(&V_divcbinfo);
544         INP_WLOCK(inp);
545         error = in_pcbbind(inp, nam, td->td_ucred);
546         INP_WUNLOCK(inp);
547         INP_INFO_WUNLOCK(&V_divcbinfo);
548         return error;
549 }
550
551 static int
552 div_shutdown(struct socket *so)
553 {
554         struct inpcb *inp;
555
556         inp = sotoinpcb(so);
557         KASSERT(inp != NULL, ("div_shutdown: inp == NULL"));
558         INP_WLOCK(inp);
559         socantsendmore(so);
560         INP_WUNLOCK(inp);
561         return 0;
562 }
563
564 static int
565 div_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
566     struct mbuf *control, struct thread *td)
567 {
568         INIT_VNET_INET(so->so_vnet);
569
570         /* Packet must have a header (but that's about it) */
571         if (m->m_len < sizeof (struct ip) &&
572             (m = m_pullup(m, sizeof (struct ip))) == 0) {
573                 V_ipstat.ips_toosmall++;
574                 m_freem(m);
575                 return EINVAL;
576         }
577
578         /* Send packet */
579         return div_output(so, m, (struct sockaddr_in *)nam, control);
580 }
581
582 void
583 div_ctlinput(int cmd, struct sockaddr *sa, void *vip)
584 {
585         struct in_addr faddr;
586
587         faddr = ((struct sockaddr_in *)sa)->sin_addr;
588         if (sa->sa_family != AF_INET || faddr.s_addr == INADDR_ANY)
589                 return;
590         if (PRC_IS_REDIRECT(cmd))
591                 return;
592 }
593
594 static int
595 div_pcblist(SYSCTL_HANDLER_ARGS)
596 {
597         INIT_VNET_INET(curvnet);
598         int error, i, n;
599         struct inpcb *inp, **inp_list;
600         inp_gen_t gencnt;
601         struct xinpgen xig;
602
603         /*
604          * The process of preparing the TCB list is too time-consuming and
605          * resource-intensive to repeat twice on every request.
606          */
607         if (req->oldptr == 0) {
608                 n = V_divcbinfo.ipi_count;
609                 req->oldidx = 2 * (sizeof xig)
610                         + (n + n/8) * sizeof(struct xinpcb);
611                 return 0;
612         }
613
614         if (req->newptr != 0)
615                 return EPERM;
616
617         /*
618          * OK, now we're committed to doing something.
619          */
620         INP_INFO_RLOCK(&V_divcbinfo);
621         gencnt = V_divcbinfo.ipi_gencnt;
622         n = V_divcbinfo.ipi_count;
623         INP_INFO_RUNLOCK(&V_divcbinfo);
624
625         error = sysctl_wire_old_buffer(req,
626             2 * sizeof(xig) + n*sizeof(struct xinpcb));
627         if (error != 0)
628                 return (error);
629
630         xig.xig_len = sizeof xig;
631         xig.xig_count = n;
632         xig.xig_gen = gencnt;
633         xig.xig_sogen = so_gencnt;
634         error = SYSCTL_OUT(req, &xig, sizeof xig);
635         if (error)
636                 return error;
637
638         inp_list = malloc(n * sizeof *inp_list, M_TEMP, M_WAITOK);
639         if (inp_list == 0)
640                 return ENOMEM;
641         
642         INP_INFO_RLOCK(&V_divcbinfo);
643         for (inp = LIST_FIRST(V_divcbinfo.ipi_listhead), i = 0; inp && i < n;
644              inp = LIST_NEXT(inp, inp_list)) {
645                 INP_RLOCK(inp);
646                 if (inp->inp_gencnt <= gencnt &&
647                     cr_canseeinpcb(req->td->td_ucred, inp) == 0)
648                         inp_list[i++] = inp;
649                 INP_RUNLOCK(inp);
650         }
651         INP_INFO_RUNLOCK(&V_divcbinfo);
652         n = i;
653
654         error = 0;
655         for (i = 0; i < n; i++) {
656                 inp = inp_list[i];
657                 INP_RLOCK(inp);
658                 if (inp->inp_gencnt <= gencnt) {
659                         struct xinpcb xi;
660                         bzero(&xi, sizeof(xi));
661                         xi.xi_len = sizeof xi;
662                         /* XXX should avoid extra copy */
663                         bcopy(inp, &xi.xi_inp, sizeof *inp);
664                         if (inp->inp_socket)
665                                 sotoxsocket(inp->inp_socket, &xi.xi_socket);
666                         INP_RUNLOCK(inp);
667                         error = SYSCTL_OUT(req, &xi, sizeof xi);
668                 } else
669                         INP_RUNLOCK(inp);
670         }
671         if (!error) {
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                 INP_INFO_RLOCK(&V_divcbinfo);
680                 xig.xig_gen = V_divcbinfo.ipi_gencnt;
681                 xig.xig_sogen = so_gencnt;
682                 xig.xig_count = V_divcbinfo.ipi_count;
683                 INP_INFO_RUNLOCK(&V_divcbinfo);
684                 error = SYSCTL_OUT(req, &xig, sizeof xig);
685         }
686         free(inp_list, M_TEMP);
687         return error;
688 }
689
690 #ifdef SYSCTL_NODE
691 SYSCTL_NODE(_net_inet, IPPROTO_DIVERT, divert, CTLFLAG_RW, 0, "IPDIVERT");
692 SYSCTL_PROC(_net_inet_divert, OID_AUTO, pcblist, CTLFLAG_RD, 0, 0,
693             div_pcblist, "S,xinpcb", "List of active divert sockets");
694 #endif
695
696 struct pr_usrreqs div_usrreqs = {
697         .pru_attach =           div_attach,
698         .pru_bind =             div_bind,
699         .pru_control =          in_control,
700         .pru_detach =           div_detach,
701         .pru_peeraddr =         in_getpeeraddr,
702         .pru_send =             div_send,
703         .pru_shutdown =         div_shutdown,
704         .pru_sockaddr =         in_getsockaddr,
705         .pru_sosetlabel =       in_pcbsosetlabel
706 };
707
708 struct protosw div_protosw = {
709         .pr_type =              SOCK_RAW,
710         .pr_protocol =          IPPROTO_DIVERT,
711         .pr_flags =             PR_ATOMIC|PR_ADDR,
712         .pr_input =             div_input,
713         .pr_ctlinput =          div_ctlinput,
714         .pr_ctloutput =         ip_ctloutput,
715         .pr_init =              div_init,
716         .pr_usrreqs =           &div_usrreqs
717 };
718
719 static int
720 div_modevent(module_t mod, int type, void *unused)
721 {
722         int err = 0;
723         int n;
724
725         switch (type) {
726         case MOD_LOAD:
727                 /*
728                  * Protocol will be initialized by pf_proto_register().
729                  * We don't have to register ip_protox because we are not
730                  * a true IP protocol that goes over the wire.
731                  */
732                 err = pf_proto_register(PF_INET, &div_protosw);
733                 ip_divert_ptr = divert_packet;
734                 break;
735         case MOD_QUIESCE:
736                 /*
737                  * IPDIVERT may normally not be unloaded because of the
738                  * potential race conditions.  Tell kldunload we can't be
739                  * unloaded unless the unload is forced.
740                  */
741                 err = EPERM;
742                 break;
743         case MOD_UNLOAD:
744                 /*
745                  * Forced unload.
746                  *
747                  * Module ipdivert can only be unloaded if no sockets are
748                  * connected.  Maybe this can be changed later to forcefully
749                  * disconnect any open sockets.
750                  *
751                  * XXXRW: Note that there is a slight race here, as a new
752                  * socket open request could be spinning on the lock and then
753                  * we destroy the lock.
754                  */
755                 INP_INFO_WLOCK(&V_divcbinfo);
756                 n = V_divcbinfo.ipi_count;
757                 if (n != 0) {
758                         err = EBUSY;
759                         INP_INFO_WUNLOCK(&V_divcbinfo);
760                         break;
761                 }
762                 ip_divert_ptr = NULL;
763                 err = pf_proto_unregister(PF_INET, IPPROTO_DIVERT, SOCK_RAW);
764                 INP_INFO_WUNLOCK(&V_divcbinfo);
765                 INP_INFO_LOCK_DESTROY(&V_divcbinfo);
766                 uma_zdestroy(V_divcbinfo.ipi_zone);
767                 break;
768         default:
769                 err = EOPNOTSUPP;
770                 break;
771         }
772         return err;
773 }
774
775 static moduledata_t ipdivertmod = {
776         "ipdivert",
777         div_modevent,
778         0
779 };
780
781 DECLARE_MODULE(ipdivert, ipdivertmod, SI_SUB_PROTO_IFATTACHDOMAIN, SI_ORDER_ANY);
782 MODULE_DEPEND(dummynet, ipfw, 2, 2, 2);
783 MODULE_VERSION(ipdivert, 1);