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