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