xref: /freebsd/sys/netinet/ip_divert.c (revision 8fc80638)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1982, 1986, 1988, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
34 
35 #include "opt_inet.h"
36 #include "opt_inet6.h"
37 #include "opt_sctp.h"
38 #ifndef INET
39 #error "IPDIVERT requires INET"
40 #endif
41 
42 #include <sys/param.h>
43 #include <sys/eventhandler.h>
44 #include <sys/kernel.h>
45 #include <sys/lock.h>
46 #include <sys/malloc.h>
47 #include <sys/mbuf.h>
48 #include <sys/module.h>
49 #include <sys/kernel.h>
50 #include <sys/priv.h>
51 #include <sys/proc.h>
52 #include <sys/protosw.h>
53 #include <sys/socket.h>
54 #include <sys/socketvar.h>
55 #include <sys/sysctl.h>
56 #include <net/vnet.h>
57 
58 #include <net/if.h>
59 #include <net/if_var.h>
60 #include <net/netisr.h>
61 
62 #include <netinet/in.h>
63 #include <netinet/in_pcb.h>
64 #include <netinet/in_systm.h>
65 #include <netinet/in_var.h>
66 #include <netinet/ip.h>
67 #include <netinet/ip_var.h>
68 #ifdef INET6
69 #include <netinet/ip6.h>
70 #include <netinet6/ip6_var.h>
71 #endif
72 #if defined(SCTP) || defined(SCTP_SUPPORT)
73 #include <netinet/sctp_crc32.h>
74 #endif
75 
76 #include <security/mac/mac_framework.h>
77 /*
78  * Divert sockets
79  */
80 
81 /*
82  * Allocate enough space to hold a full IP packet
83  */
84 #define	DIVSNDQ		(65536 + 100)
85 #define	DIVRCVQ		(65536 + 100)
86 
87 /*
88  * Divert sockets work in conjunction with ipfw or other packet filters,
89  * see the divert(4) manpage for features.
90  * Packets are selected by the packet filter and tagged with an
91  * MTAG_IPFW_RULE tag carrying the 'divert port' number (as set by
92  * the packet filter) and information on the matching filter rule for
93  * subsequent reinjection. The divert_port is used to put the packet
94  * on the corresponding divert socket, while the rule number is passed
95  * up (at least partially) as the sin_port in the struct sockaddr.
96  *
97  * Packets written to the divert socket carry in sin_addr a
98  * destination address, and in sin_port the number of the filter rule
99  * after which to continue processing.
100  * If the destination address is INADDR_ANY, the packet is treated as
101  * as outgoing and sent to ip_output(); otherwise it is treated as
102  * incoming and sent to ip_input().
103  * Further, sin_zero carries some information on the interface,
104  * which can be used in the reinject -- see comments in the code.
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  * packet filter processing will start at the rule number after the one
109  * written in the sin_port (ipfw does not allow a rule #0, so sin_port=0
110  * will apply the entire ruleset to the packet).
111  */
112 
113 /* Internal variables. */
114 VNET_DEFINE_STATIC(struct inpcbinfo, divcbinfo);
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 int div_output_inbound(int fmaily, struct socket *so, struct mbuf *m,
121     struct sockaddr_in *sin);
122 static int div_output_outbound(int family, struct socket *so, struct mbuf *m);
123 
124 /*
125  * Initialize divert connection block queue.
126  */
127 INPCBSTORAGE_DEFINE(divcbstor, "divinp", "divcb", "div", "divhash");
128 
129 static void
130 div_init(void *arg __unused)
131 {
132 
133 	/*
134 	 * XXX We don't use the hash list for divert IP, but it's easier to
135 	 * allocate one-entry hash lists than it is to check all over the
136 	 * place for hashbase == NULL.
137 	 */
138 	in_pcbinfo_init(&V_divcbinfo, &divcbstor, 1, 1);
139 }
140 VNET_SYSINIT(div_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_THIRD, div_init, NULL);
141 
142 static void
143 div_destroy(void *unused __unused)
144 {
145 
146 	in_pcbinfo_destroy(&V_divcbinfo);
147 }
148 VNET_SYSUNINIT(divert, SI_SUB_PROTO_DOMAIN, SI_ORDER_THIRD, div_destroy, NULL);
149 
150 static bool
151 div_port_match(const struct inpcb *inp, void *v)
152 {
153 	uint16_t nport = *(uint16_t *)v;
154 
155 	return (inp->inp_lport == nport);
156 }
157 
158 /*
159  * Divert a packet by passing it up to the divert socket at port 'port'.
160  */
161 static void
162 divert_packet(struct mbuf *m, bool incoming)
163 {
164 #if defined(SCTP) || defined(SCTP_SUPPORT)
165 	struct ip *ip;
166 #endif
167 	struct inpcb *inp;
168 	struct socket *sa;
169 	u_int16_t nport;
170 	struct sockaddr_in divsrc;
171 	struct inpcb_iterator inpi = INP_ITERATOR(&V_divcbinfo,
172 	    INPLOOKUP_RLOCKPCB, div_port_match, &nport);
173 	struct m_tag *mtag;
174 
175 	NET_EPOCH_ASSERT();
176 
177 	mtag = m_tag_locate(m, MTAG_IPFW_RULE, 0, NULL);
178 	if (mtag == NULL) {
179 		m_freem(m);
180 		return;
181 	}
182 	/* Assure header */
183 	if (m->m_len < sizeof(struct ip) &&
184 	    (m = m_pullup(m, sizeof(struct ip))) == NULL)
185 		return;
186 
187 	/* Delayed checksums are currently not compatible with divert. */
188 	if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
189 		in_delayed_cksum(m);
190 		m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
191 	}
192 #if defined(SCTP) || defined(SCTP_SUPPORT)
193 	if (m->m_pkthdr.csum_flags & CSUM_SCTP) {
194 		ip = mtod(m, struct ip *);
195 		sctp_delayed_cksum(m, (uint32_t)(ip->ip_hl << 2));
196 		m->m_pkthdr.csum_flags &= ~CSUM_SCTP;
197 	}
198 #endif
199 #ifdef INET6
200 	if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA_IPV6) {
201 		in6_delayed_cksum(m, m->m_pkthdr.len -
202 		    sizeof(struct ip6_hdr), sizeof(struct ip6_hdr));
203 		m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA_IPV6;
204 	}
205 #if defined(SCTP) || defined(SCTP_SUPPORT)
206 	if (m->m_pkthdr.csum_flags & CSUM_SCTP_IPV6) {
207 		sctp_delayed_cksum(m, sizeof(struct ip6_hdr));
208 		m->m_pkthdr.csum_flags &= ~CSUM_SCTP_IPV6;
209 	}
210 #endif
211 #endif /* INET6 */
212 	bzero(&divsrc, sizeof(divsrc));
213 	divsrc.sin_len = sizeof(divsrc);
214 	divsrc.sin_family = AF_INET;
215 	/* record matching rule, in host format */
216 	divsrc.sin_port = ((struct ipfw_rule_ref *)(mtag+1))->rulenum;
217 	/*
218 	 * Record receive interface address, if any.
219 	 * But only for incoming packets.
220 	 */
221 	if (incoming) {
222 		struct ifaddr *ifa;
223 		struct ifnet *ifp;
224 
225 		/* Sanity check */
226 		M_ASSERTPKTHDR(m);
227 
228 		/* Find IP address for receive interface */
229 		ifp = m->m_pkthdr.rcvif;
230 		CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
231 			if (ifa->ifa_addr->sa_family != AF_INET)
232 				continue;
233 			divsrc.sin_addr =
234 			    ((struct sockaddr_in *) ifa->ifa_addr)->sin_addr;
235 			break;
236 		}
237 	}
238 	/*
239 	 * Record the incoming interface name whenever we have one.
240 	 */
241 	if (m->m_pkthdr.rcvif) {
242 		/*
243 		 * Hide the actual interface name in there in the
244 		 * sin_zero array. XXX This needs to be moved to a
245 		 * different sockaddr type for divert, e.g.
246 		 * sockaddr_div with multiple fields like
247 		 * sockaddr_dl. Presently we have only 7 bytes
248 		 * but that will do for now as most interfaces
249 		 * are 4 or less + 2 or less bytes for unit.
250 		 * There is probably a faster way of doing this,
251 		 * possibly taking it from the sockaddr_dl on the iface.
252 		 * This solves the problem of a P2P link and a LAN interface
253 		 * having the same address, which can result in the wrong
254 		 * interface being assigned to the packet when fed back
255 		 * into the divert socket. Theoretically if the daemon saves
256 		 * and re-uses the sockaddr_in as suggested in the man pages,
257 		 * this iface name will come along for the ride.
258 		 * (see div_output for the other half of this.)
259 		 */
260 		strlcpy(divsrc.sin_zero, m->m_pkthdr.rcvif->if_xname,
261 		    sizeof(divsrc.sin_zero));
262 	}
263 
264 	/* Put packet on socket queue, if any */
265 	sa = NULL;
266 	/* nport is inp_next's context. */
267 	nport = htons((u_int16_t)(((struct ipfw_rule_ref *)(mtag+1))->info));
268 	while ((inp = inp_next(&inpi)) != NULL) {
269 		sa = inp->inp_socket;
270 		SOCKBUF_LOCK(&sa->so_rcv);
271 		if (sbappendaddr_locked(&sa->so_rcv,
272 		    (struct sockaddr *)&divsrc, m, NULL) == 0) {
273 			soroverflow_locked(sa);
274 			sa = NULL;	/* force mbuf reclaim below */
275 		} else
276 			sorwakeup_locked(sa);
277 		/* XXX why does only one socket match? */
278 		INP_RUNLOCK(inp);
279 		break;
280 	}
281 	if (sa == NULL) {
282 		m_freem(m);
283 		KMOD_IPSTAT_INC(ips_noproto);
284 		KMOD_IPSTAT_DEC(ips_delivered);
285         }
286 }
287 
288 /*
289  * Deliver packet back into the IP processing machinery.
290  *
291  * If no address specified, or address is 0.0.0.0, send to ip_output();
292  * otherwise, send to ip_input() and mark as having been received on
293  * the interface with that address.
294  */
295 static int
296 div_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
297     struct mbuf *control, struct thread *td)
298 {
299 	struct epoch_tracker et;
300 	struct sockaddr_in *sin = (struct sockaddr_in *)nam;
301 	const struct ip *ip;
302 	struct m_tag *mtag;
303 	struct ipfw_rule_ref *dt;
304 	int error, family;
305 
306 	if (control)
307 		m_freem(control);
308 
309 	/* Packet must have a header (but that's about it) */
310 	if (m->m_len < sizeof (struct ip) &&
311 	    (m = m_pullup(m, sizeof (struct ip))) == NULL) {
312 		KMOD_IPSTAT_INC(ips_toosmall);
313 		m_freem(m);
314 		return (EINVAL);
315 	}
316 
317 	if (sin != NULL) {
318 		if (sin->sin_family != AF_INET) {
319 			m_freem(m);
320 			return (EAFNOSUPPORT);
321 		}
322 		if (sin->sin_len != sizeof(*sin)) {
323 			m_freem(m);
324 			return (EINVAL);
325 		}
326 	}
327 
328 	/*
329 	 * An mbuf may hasn't come from userland, but we pretend
330 	 * that it has.
331 	 */
332 	m->m_pkthdr.rcvif = NULL;
333 	m->m_nextpkt = NULL;
334 	M_SETFIB(m, so->so_fibnum);
335 
336 	mtag = m_tag_locate(m, MTAG_IPFW_RULE, 0, NULL);
337 	if (mtag == NULL) {
338 		/* this should be normal */
339 		mtag = m_tag_alloc(MTAG_IPFW_RULE, 0,
340 		    sizeof(struct ipfw_rule_ref), M_NOWAIT | M_ZERO);
341 		if (mtag == NULL) {
342 			m_freem(m);
343 			return (ENOBUFS);
344 		}
345 		m_tag_prepend(m, mtag);
346 	}
347 	dt = (struct ipfw_rule_ref *)(mtag+1);
348 
349 	/* Loopback avoidance and state recovery */
350 	if (sin) {
351 		int i;
352 
353 		/* set the starting point. We provide a non-zero slot,
354 		 * but a non_matching chain_id to skip that info and use
355 		 * the rulenum/rule_id.
356 		 */
357 		dt->slot = 1; /* dummy, chain_id is invalid */
358 		dt->chain_id = 0;
359 		dt->rulenum = sin->sin_port+1; /* host format ? */
360 		dt->rule_id = 0;
361 		/* XXX: broken for IPv6 */
362 		/*
363 		 * Find receive interface with the given name, stuffed
364 		 * (if it exists) in the sin_zero[] field.
365 		 * The name is user supplied data so don't trust its size
366 		 * or that it is zero terminated.
367 		 */
368 		for (i = 0; i < sizeof(sin->sin_zero) && sin->sin_zero[i]; i++)
369 			;
370 		if ( i > 0 && i < sizeof(sin->sin_zero))
371 			m->m_pkthdr.rcvif = ifunit(sin->sin_zero);
372 	}
373 
374 	ip = mtod(m, struct ip *);
375 	switch (ip->ip_v) {
376 	case IPVERSION:
377 		family = AF_INET;
378 		break;
379 #ifdef INET6
380 	case IPV6_VERSION >> 4:
381 		family = AF_INET6;
382 		break;
383 #endif
384 	default:
385 		m_freem(m);
386 		return (EAFNOSUPPORT);
387 	}
388 
389 	/* Reinject packet into the system as incoming or outgoing */
390 	NET_EPOCH_ENTER(et);
391 	if (!sin || sin->sin_addr.s_addr == 0) {
392 		dt->info |= IPFW_IS_DIVERT | IPFW_INFO_OUT;
393 		error = div_output_outbound(family, so, m);
394 	} else {
395 		dt->info |= IPFW_IS_DIVERT | IPFW_INFO_IN;
396 		error = div_output_inbound(family, so, m, sin);
397 	}
398 	NET_EPOCH_EXIT(et);
399 
400 	return (error);
401 }
402 
403 /*
404  * Sends mbuf @m to the wire via ip[6]_output().
405  *
406  * Returns 0 on success or an errno value on failure.  @m is always consumed.
407  */
408 static int
409 div_output_outbound(int family, struct socket *so, struct mbuf *m)
410 {
411 	struct ip *const ip = mtod(m, struct ip *);
412 	struct mbuf *options;
413 	struct inpcb *inp;
414 	int error;
415 
416 	inp = sotoinpcb(so);
417 	INP_RLOCK(inp);
418 	switch (family) {
419 	case AF_INET:
420 		/*
421 		 * Don't allow both user specified and setsockopt
422 		 * options, and don't allow packet length sizes that
423 		 * will crash.
424 		 */
425 		if ((((ip->ip_hl << 2) != sizeof(struct ip)) &&
426 		    inp->inp_options != NULL) ||
427 		    ((u_short)ntohs(ip->ip_len) > m->m_pkthdr.len)) {
428 			INP_RUNLOCK(inp);
429 			m_freem(m);
430 			return (EINVAL);
431 		}
432 		break;
433 #ifdef INET6
434 	case AF_INET6:
435 	    {
436 		struct ip6_hdr *const ip6 = mtod(m, struct ip6_hdr *);
437 
438 		/* Don't allow packet length sizes that will crash */
439 		if (((u_short)ntohs(ip6->ip6_plen) > m->m_pkthdr.len)) {
440 			INP_RUNLOCK(inp);
441 			m_freem(m);
442 			return (EINVAL);
443 		}
444 		break;
445 	    }
446 #endif
447 	}
448 
449 	/* Send packet to output processing */
450 	KMOD_IPSTAT_INC(ips_rawout);		/* XXX */
451 
452 #ifdef MAC
453 	mac_inpcb_create_mbuf(inp, m);
454 #endif
455 	/*
456 	 * Get ready to inject the packet into ip_output().
457 	 * Just in case socket options were specified on the
458 	 * divert socket, we duplicate them.  This is done
459 	 * to avoid having to hold the PCB locks over the call
460 	 * to ip_output(), as doing this results in a number of
461 	 * lock ordering complexities.
462 	 *
463 	 * Note that we set the multicast options argument for
464 	 * ip_output() to NULL since it should be invariant that
465 	 * they are not present.
466 	 */
467 	KASSERT(inp->inp_moptions == NULL,
468 	    ("multicast options set on a divert socket"));
469 	/*
470 	 * XXXCSJP: It is unclear to me whether or not it makes
471 	 * sense for divert sockets to have options.  However,
472 	 * for now we will duplicate them with the INP locks
473 	 * held so we can use them in ip_output() without
474 	 * requring a reference to the pcb.
475 	 */
476 	options = NULL;
477 	if (inp->inp_options != NULL) {
478 		options = m_dup(inp->inp_options, M_NOWAIT);
479 		if (options == NULL) {
480 			INP_RUNLOCK(inp);
481 			m_freem(m);
482 			return (ENOBUFS);
483 		}
484 	}
485 	INP_RUNLOCK(inp);
486 
487 	error = 0;
488 	switch (family) {
489 	case AF_INET:
490 		error = ip_output(m, options, NULL,
491 		    ((so->so_options & SO_DONTROUTE) ? IP_ROUTETOIF : 0)
492 		    | IP_ALLOWBROADCAST | IP_RAWOUTPUT, NULL, NULL);
493 		break;
494 #ifdef INET6
495 	case AF_INET6:
496 		error = ip6_output(m, NULL, NULL, 0, NULL, NULL, NULL);
497 		break;
498 #endif
499 	}
500 	if (options != NULL)
501 		m_freem(options);
502 
503 	return (error);
504 }
505 
506 /*
507  * Schedules mbuf @m for local processing via IPv4/IPv6 netisr queue.
508  *
509  * Returns 0 on success or an errno value on failure.  @m is always consumed.
510  */
511 static int
512 div_output_inbound(int family, struct socket *so, struct mbuf *m,
513     struct sockaddr_in *sin)
514 {
515 	const struct ip *ip;
516 	struct ifaddr *ifa;
517 
518 	if (m->m_pkthdr.rcvif == NULL) {
519 		/*
520 		 * No luck with the name, check by IP address.
521 		 * Clear the port and the ifname to make sure
522 		 * there are no distractions for ifa_ifwithaddr.
523 		 */
524 
525 		/* XXX: broken for IPv6 */
526 		bzero(sin->sin_zero, sizeof(sin->sin_zero));
527 		sin->sin_port = 0;
528 		ifa = ifa_ifwithaddr((struct sockaddr *) sin);
529 		if (ifa == NULL) {
530 			m_freem(m);
531 			return (EADDRNOTAVAIL);
532 		}
533 		m->m_pkthdr.rcvif = ifa->ifa_ifp;
534 	}
535 #ifdef MAC
536 	mac_socket_create_mbuf(so, m);
537 #endif
538 	/* Send packet to input processing via netisr */
539 	switch (family) {
540 	case AF_INET:
541 		ip = mtod(m, struct ip *);
542 		/*
543 		 * Restore M_BCAST flag when destination address is
544 		 * broadcast. It is expected by ip_tryforward().
545 		 */
546 		if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)))
547 			m->m_flags |= M_MCAST;
548 		else if (in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
549 			m->m_flags |= M_BCAST;
550 		netisr_queue_src(NETISR_IP, (uintptr_t)so, m);
551 		break;
552 #ifdef INET6
553 	case AF_INET6:
554 		netisr_queue_src(NETISR_IPV6, (uintptr_t)so, m);
555 		break;
556 #endif
557 	default:
558 		m_freem(m);
559 		return (EINVAL);
560 	}
561 
562 	return (0);
563 }
564 
565 static int
566 div_attach(struct socket *so, int proto, struct thread *td)
567 {
568 	struct inpcb *inp;
569 	int error;
570 
571 	inp  = sotoinpcb(so);
572 	KASSERT(inp == NULL, ("div_attach: inp != NULL"));
573 	if (td != NULL) {
574 		error = priv_check(td, PRIV_NETINET_DIVERT);
575 		if (error)
576 			return (error);
577 	}
578 	error = soreserve(so, div_sendspace, div_recvspace);
579 	if (error)
580 		return error;
581 	error = in_pcballoc(so, &V_divcbinfo);
582 	if (error)
583 		return error;
584 	inp = (struct inpcb *)so->so_pcb;
585 	inp->inp_ip_p = proto;
586 	inp->inp_flags |= INP_HDRINCL;
587 	INP_WUNLOCK(inp);
588 	return 0;
589 }
590 
591 static void
592 div_detach(struct socket *so)
593 {
594 	struct inpcb *inp;
595 
596 	inp = sotoinpcb(so);
597 	KASSERT(inp != NULL, ("div_detach: inp == NULL"));
598 	INP_WLOCK(inp);
599 	in_pcbdetach(inp);
600 	in_pcbfree(inp);
601 }
602 
603 static int
604 div_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
605 {
606 	struct inpcb *inp;
607 	int error;
608 
609 	inp = sotoinpcb(so);
610 	KASSERT(inp != NULL, ("div_bind: inp == NULL"));
611 	/* in_pcbbind assumes that nam is a sockaddr_in
612 	 * and in_pcbbind requires a valid address. Since divert
613 	 * sockets don't we need to make sure the address is
614 	 * filled in properly.
615 	 * XXX -- divert should not be abusing in_pcbind
616 	 * and should probably have its own family.
617 	 */
618 	if (nam->sa_family != AF_INET)
619 		return EAFNOSUPPORT;
620 	if (nam->sa_len != sizeof(struct sockaddr_in))
621 		return EINVAL;
622 	((struct sockaddr_in *)nam)->sin_addr.s_addr = INADDR_ANY;
623 	INP_WLOCK(inp);
624 	INP_HASH_WLOCK(&V_divcbinfo);
625 	error = in_pcbbind(inp, nam, td->td_ucred);
626 	INP_HASH_WUNLOCK(&V_divcbinfo);
627 	INP_WUNLOCK(inp);
628 	return error;
629 }
630 
631 static int
632 div_shutdown(struct socket *so)
633 {
634 	struct inpcb *inp;
635 
636 	inp = sotoinpcb(so);
637 	KASSERT(inp != NULL, ("div_shutdown: inp == NULL"));
638 	INP_WLOCK(inp);
639 	socantsendmore(so);
640 	INP_WUNLOCK(inp);
641 	return 0;
642 }
643 
644 static int
645 div_pcblist(SYSCTL_HANDLER_ARGS)
646 {
647 	struct inpcb_iterator inpi = INP_ALL_ITERATOR(&V_divcbinfo,
648 	    INPLOOKUP_RLOCKPCB);
649 	struct xinpgen xig;
650 	struct inpcb *inp;
651 	int error;
652 
653 	if (req->newptr != 0)
654 		return EPERM;
655 
656 	if (req->oldptr == 0) {
657 		int n;
658 
659 		n = V_divcbinfo.ipi_count;
660 		n += imax(n / 8, 10);
661 		req->oldidx = 2 * (sizeof xig) + n * sizeof(struct xinpcb);
662 		return 0;
663 	}
664 
665 	if ((error = sysctl_wire_old_buffer(req, 0)) != 0)
666 		return (error);
667 
668 	bzero(&xig, sizeof(xig));
669 	xig.xig_len = sizeof xig;
670 	xig.xig_count = V_divcbinfo.ipi_count;
671 	xig.xig_gen = V_divcbinfo.ipi_gencnt;
672 	xig.xig_sogen = so_gencnt;
673 	error = SYSCTL_OUT(req, &xig, sizeof xig);
674 	if (error)
675 		return error;
676 
677 	while ((inp = inp_next(&inpi)) != NULL) {
678 		if (inp->inp_gencnt <= xig.xig_gen) {
679 			struct xinpcb xi;
680 
681 			in_pcbtoxinpcb(inp, &xi);
682 			error = SYSCTL_OUT(req, &xi, sizeof xi);
683 			if (error) {
684 				INP_RUNLOCK(inp);
685 				break;
686 			}
687 		}
688 	}
689 
690 	if (!error) {
691 		/*
692 		 * Give the user an updated idea of our state.
693 		 * If the generation differs from what we told
694 		 * her before, she knows that something happened
695 		 * while we were processing this request, and it
696 		 * might be necessary to retry.
697 		 */
698 		xig.xig_gen = V_divcbinfo.ipi_gencnt;
699 		xig.xig_sogen = so_gencnt;
700 		xig.xig_count = V_divcbinfo.ipi_count;
701 		error = SYSCTL_OUT(req, &xig, sizeof xig);
702 	}
703 
704 	return (error);
705 }
706 
707 #ifdef SYSCTL_NODE
708 static SYSCTL_NODE(_net_inet, IPPROTO_DIVERT, divert,
709     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
710     "IPDIVERT");
711 SYSCTL_PROC(_net_inet_divert, OID_AUTO, pcblist,
712    CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
713     NULL, 0, div_pcblist, "S,xinpcb",
714     "List of active divert sockets");
715 #endif
716 
717 static struct protosw div_protosw = {
718 	.pr_type =		SOCK_RAW,
719 	.pr_protocol =		IPPROTO_DIVERT,
720 	.pr_flags =		PR_ATOMIC|PR_ADDR,
721 	.pr_attach =		div_attach,
722 	.pr_bind =		div_bind,
723 	.pr_control =		in_control,
724 	.pr_detach =		div_detach,
725 	.pr_peeraddr =		in_getpeeraddr,
726 	.pr_send =		div_send,
727 	.pr_shutdown =		div_shutdown,
728 	.pr_sockaddr =		in_getsockaddr,
729 	.pr_sosetlabel =	in_pcbsosetlabel
730 };
731 
732 static int
733 div_modevent(module_t mod, int type, void *unused)
734 {
735 	int err = 0;
736 
737 	switch (type) {
738 	case MOD_LOAD:
739 		/*
740 		 * Protocol will be initialized by pf_proto_register().
741 		 */
742 		err = protosw_register(&inetdomain, &div_protosw);
743 		if (err != 0)
744 			return (err);
745 		ip_divert_ptr = divert_packet;
746 		break;
747 	case MOD_QUIESCE:
748 		/*
749 		 * IPDIVERT may normally not be unloaded because of the
750 		 * potential race conditions.  Tell kldunload we can't be
751 		 * unloaded unless the unload is forced.
752 		 */
753 		err = EPERM;
754 		break;
755 	case MOD_UNLOAD:
756 		/*
757 		 * Forced unload.
758 		 *
759 		 * Module ipdivert can only be unloaded if no sockets are
760 		 * connected.  Maybe this can be changed later to forcefully
761 		 * disconnect any open sockets.
762 		 *
763 		 * XXXRW: Note that there is a slight race here, as a new
764 		 * socket open request could be spinning on the lock and then
765 		 * we destroy the lock.
766 		 */
767 		INP_INFO_WLOCK(&V_divcbinfo);
768 		if (V_divcbinfo.ipi_count != 0) {
769 			err = EBUSY;
770 			INP_INFO_WUNLOCK(&V_divcbinfo);
771 			break;
772 		}
773 		ip_divert_ptr = NULL;
774 		err = protosw_unregister(&div_protosw);
775 		INP_INFO_WUNLOCK(&V_divcbinfo);
776 #ifndef VIMAGE
777 		div_destroy(NULL);
778 #endif
779 		break;
780 	default:
781 		err = EOPNOTSUPP;
782 		break;
783 	}
784 	return err;
785 }
786 
787 static moduledata_t ipdivertmod = {
788         "ipdivert",
789         div_modevent,
790         0
791 };
792 
793 DECLARE_MODULE(ipdivert, ipdivertmod, SI_SUB_PROTO_FIREWALL, SI_ORDER_ANY);
794 MODULE_DEPEND(ipdivert, ipfw, 3, 3, 3);
795 MODULE_VERSION(ipdivert, 1);
796