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