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