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