xref: /freebsd/sys/netinet/ip_divert.c (revision 2e3507c25e42292b45a5482e116d278f5515d04d)
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 #include "opt_inet.h"
34 #include "opt_inet6.h"
35 #include "opt_sctp.h"
36 
37 #include <sys/param.h>
38 #include <sys/eventhandler.h>
39 #include <sys/kernel.h>
40 #include <sys/lock.h>
41 #include <sys/malloc.h>
42 #include <sys/mbuf.h>
43 #include <sys/module.h>
44 #include <sys/kernel.h>
45 #include <sys/priv.h>
46 #include <sys/proc.h>
47 #include <sys/domain.h>
48 #include <sys/protosw.h>
49 #include <sys/socket.h>
50 #include <sys/socketvar.h>
51 #include <sys/sysctl.h>
52 #include <net/vnet.h>
53 
54 #include <net/if.h>
55 #include <net/if_var.h>
56 #include <net/if_private.h>
57 #include <net/netisr.h>
58 
59 #include <netinet/in.h>
60 #include <netinet/in_pcb.h>
61 #include <netinet/in_systm.h>
62 #include <netinet/in_var.h>
63 #include <netinet/ip.h>
64 #include <netinet/ip_var.h>
65 #include <netinet/ip_divert.h>
66 #ifdef INET6
67 #include <netinet/ip6.h>
68 #include <netinet6/ip6_var.h>
69 #endif
70 #if defined(SCTP) || defined(SCTP_SUPPORT)
71 #include <netinet/sctp_crc32.h>
72 #endif
73 
74 #include <security/mac/mac_framework.h>
75 /*
76  * Divert sockets
77  */
78 
79 /*
80  * Allocate enough space to hold a full IP packet
81  */
82 #define	DIVSNDQ		(65536 + 100)
83 #define	DIVRCVQ		(65536 + 100)
84 
85 /*
86  * Usually a system has very few divert ports.  Previous implementation
87  * used a linked list.
88  */
89 #define	DIVHASHSIZE	(1 << 3)	/* 8 entries, one cache line. */
90 #define	DIVHASH(port)	(port % DIVHASHSIZE)
91 #define	DCBHASH(dcb)	((dcb)->dcb_port % DIVHASHSIZE)
92 
93 /*
94  * Divert sockets work in conjunction with ipfw or other packet filters,
95  * see the divert(4) manpage for features.
96  * Packets are selected by the packet filter and tagged with an
97  * MTAG_IPFW_RULE tag carrying the 'divert port' number (as set by
98  * the packet filter) and information on the matching filter rule for
99  * subsequent reinjection. The divert_port is used to put the packet
100  * on the corresponding divert socket, while the rule number is passed
101  * up (at least partially) as the sin_port in the struct sockaddr.
102  *
103  * Packets written to the divert socket carry in sin_addr a
104  * destination address, and in sin_port the number of the filter rule
105  * after which to continue processing.
106  * If the destination address is INADDR_ANY, the packet is treated as
107  * as outgoing and sent to ip_output(); otherwise it is treated as
108  * incoming and sent to ip_input().
109  * Further, sin_zero carries some information on the interface,
110  * which can be used in the reinject -- see comments in the code.
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  * packet filter processing will start at the rule number after the one
115  * written in the sin_port (ipfw does not allow a rule #0, so sin_port=0
116  * will apply the entire ruleset to the packet).
117  */
118 static SYSCTL_NODE(_net_inet, OID_AUTO, divert, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
119     "divert(4)");
120 
121 VNET_PCPUSTAT_DEFINE_STATIC(struct divstat, divstat);
122 VNET_PCPUSTAT_SYSINIT(divstat);
123 #ifdef VIMAGE
124 VNET_PCPUSTAT_SYSUNINIT(divstat);
125 #endif
126 SYSCTL_VNET_PCPUSTAT(_net_inet_divert, OID_AUTO, stats, struct divstat,
127     divstat, "divert(4) socket statistics");
128 #define	DIVSTAT_INC(name)	\
129     VNET_PCPUSTAT_ADD(struct divstat, divstat, div_ ## name, 1)
130 
131 static u_long	div_sendspace = DIVSNDQ;	/* XXX sysctl ? */
132 static u_long	div_recvspace = DIVRCVQ;	/* XXX sysctl ? */
133 
134 static int div_output_inbound(int fmaily, struct socket *so, struct mbuf *m,
135     struct sockaddr_in *sin);
136 static int div_output_outbound(int family, struct socket *so, struct mbuf *m);
137 
138 struct divcb {
139 	union {
140 		SLIST_ENTRY(divcb)	dcb_next;
141 		intptr_t		dcb_bound;
142 #define	DCB_UNBOUND	((intptr_t)-1)
143 	};
144 	struct socket		*dcb_socket;
145 	uint16_t		 dcb_port;
146 	uint64_t		 dcb_gencnt;
147 	struct epoch_context	 dcb_epochctx;
148 };
149 
150 SLIST_HEAD(divhashhead, divcb);
151 
152 VNET_DEFINE_STATIC(struct divhashhead, divhash[DIVHASHSIZE]) = {};
153 #define	V_divhash	VNET(divhash)
154 VNET_DEFINE_STATIC(uint64_t, dcb_count) = 0;
155 #define	V_dcb_count	VNET(dcb_count)
156 VNET_DEFINE_STATIC(uint64_t, dcb_gencnt) = 0;
157 #define	V_dcb_gencnt	VNET(dcb_gencnt)
158 
159 static struct mtx divert_mtx;
160 MTX_SYSINIT(divert, &divert_mtx, "divert(4) socket pcb lists", MTX_DEF);
161 #define	DIVERT_LOCK()	mtx_lock(&divert_mtx)
162 #define	DIVERT_UNLOCK()	mtx_unlock(&divert_mtx)
163 
164 /*
165  * Divert a packet by passing it up to the divert socket at port 'port'.
166  */
167 static void
168 divert_packet(struct mbuf *m, bool incoming)
169 {
170 	struct divcb *dcb;
171 	u_int16_t nport;
172 	struct sockaddr_in divsrc;
173 	struct m_tag *mtag;
174 	uint16_t cookie;
175 
176 	NET_EPOCH_ASSERT();
177 
178 	mtag = m_tag_locate(m, MTAG_IPFW_RULE, 0, NULL);
179 	if (mtag != NULL) {
180 		cookie = ((struct ipfw_rule_ref *)(mtag+1))->rulenum;
181 		nport = htons((uint16_t)
182 		    (((struct ipfw_rule_ref *)(mtag+1))->info));
183 	} else if ((mtag = m_tag_locate(m, MTAG_PF_DIVERT, 0, NULL)) != NULL) {
184 		cookie = ((struct pf_divert_mtag *)(mtag+1))->idir;
185 		nport = htons(((struct pf_divert_mtag *)(mtag+1))->port);
186 	} else {
187 		m_freem(m);
188 		return;
189 	}
190 	/* Assure header */
191 	if (m->m_len < sizeof(struct ip) &&
192 	    (m = m_pullup(m, sizeof(struct ip))) == NULL)
193 		return;
194 #ifdef INET
195 	/* Delayed checksums are currently not compatible with divert. */
196 	if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
197 		in_delayed_cksum(m);
198 		m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
199 	}
200 #if defined(SCTP) || defined(SCTP_SUPPORT)
201 	if (m->m_pkthdr.csum_flags & CSUM_SCTP) {
202 		struct ip *ip;
203 
204 		ip = mtod(m, struct ip *);
205 		sctp_delayed_cksum(m, (uint32_t)(ip->ip_hl << 2));
206 		m->m_pkthdr.csum_flags &= ~CSUM_SCTP;
207 	}
208 #endif
209 #endif
210 #ifdef INET6
211 	if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA_IPV6) {
212 		in6_delayed_cksum(m, m->m_pkthdr.len -
213 		    sizeof(struct ip6_hdr), sizeof(struct ip6_hdr));
214 		m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA_IPV6;
215 	}
216 #if defined(SCTP) || defined(SCTP_SUPPORT)
217 	if (m->m_pkthdr.csum_flags & CSUM_SCTP_IPV6) {
218 		sctp_delayed_cksum(m, sizeof(struct ip6_hdr));
219 		m->m_pkthdr.csum_flags &= ~CSUM_SCTP_IPV6;
220 	}
221 #endif
222 #endif /* INET6 */
223 	bzero(&divsrc, sizeof(divsrc));
224 	divsrc.sin_len = sizeof(divsrc);
225 	divsrc.sin_family = AF_INET;
226 	/* record matching rule, in host format */
227 	divsrc.sin_port = cookie;
228 	/*
229 	 * Record receive interface address, if any.
230 	 * But only for incoming packets.
231 	 */
232 	if (incoming) {
233 		struct ifaddr *ifa;
234 		struct ifnet *ifp;
235 
236 		/* Sanity check */
237 		M_ASSERTPKTHDR(m);
238 
239 		/* Find IP address for receive interface */
240 		ifp = m->m_pkthdr.rcvif;
241 		CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
242 			if (ifa->ifa_addr->sa_family != AF_INET)
243 				continue;
244 			divsrc.sin_addr =
245 			    ((struct sockaddr_in *) ifa->ifa_addr)->sin_addr;
246 			break;
247 		}
248 	}
249 	/*
250 	 * Record the incoming interface name whenever we have one.
251 	 */
252 	if (m->m_pkthdr.rcvif) {
253 		/*
254 		 * Hide the actual interface name in there in the
255 		 * sin_zero array. XXX This needs to be moved to a
256 		 * different sockaddr type for divert, e.g.
257 		 * sockaddr_div with multiple fields like
258 		 * sockaddr_dl. Presently we have only 7 bytes
259 		 * but that will do for now as most interfaces
260 		 * are 4 or less + 2 or less bytes for unit.
261 		 * There is probably a faster way of doing this,
262 		 * possibly taking it from the sockaddr_dl on the iface.
263 		 * This solves the problem of a P2P link and a LAN interface
264 		 * having the same address, which can result in the wrong
265 		 * interface being assigned to the packet when fed back
266 		 * into the divert socket. Theoretically if the daemon saves
267 		 * and re-uses the sockaddr_in as suggested in the man pages,
268 		 * this iface name will come along for the ride.
269 		 * (see div_output for the other half of this.)
270 		 */
271 		strlcpy(divsrc.sin_zero, m->m_pkthdr.rcvif->if_xname,
272 		    sizeof(divsrc.sin_zero));
273 	}
274 
275 	/* Put packet on socket queue, if any */
276 	SLIST_FOREACH(dcb, &V_divhash[DIVHASH(nport)], dcb_next)
277 		if (dcb->dcb_port == nport)
278 			break;
279 
280 	if (dcb != NULL) {
281 		struct socket *sa = dcb->dcb_socket;
282 
283 		SOCKBUF_LOCK(&sa->so_rcv);
284 		if (sbappendaddr_locked(&sa->so_rcv,
285 		    (struct sockaddr *)&divsrc, m, NULL) == 0) {
286 			soroverflow_locked(sa);
287 			m_freem(m);
288 		} else {
289 			sorwakeup_locked(sa);
290 			DIVSTAT_INC(diverted);
291 		}
292 	} else {
293 		DIVSTAT_INC(noport);
294 		m_freem(m);
295 	}
296 }
297 
298 /*
299  * Deliver packet back into the IP processing machinery.
300  *
301  * If no address specified, or address is 0.0.0.0, send to ip_output();
302  * otherwise, send to ip_input() and mark as having been received on
303  * the interface with that address.
304  */
305 static int
306 div_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
307     struct mbuf *control, struct thread *td)
308 {
309 	struct epoch_tracker et;
310 	struct sockaddr_in *sin = (struct sockaddr_in *)nam;
311 	const struct ip *ip;
312 	struct m_tag *mtag;
313 	struct ipfw_rule_ref *dt;
314 	struct pf_divert_mtag *pfdt;
315 	int error, family;
316 
317 	if (control)
318 		m_freem(control);
319 
320 	/* Packet must have a header (but that's about it) */
321 	if (m->m_len < sizeof (struct ip) &&
322 	    (m = m_pullup(m, sizeof (struct ip))) == NULL) {
323 		m_freem(m);
324 		return (EINVAL);
325 	}
326 
327 	if (sin != NULL) {
328 		if (sin->sin_family != AF_INET) {
329 			m_freem(m);
330 			return (EAFNOSUPPORT);
331 		}
332 		if (sin->sin_len != sizeof(*sin)) {
333 			m_freem(m);
334 			return (EINVAL);
335 		}
336 	}
337 
338 	/*
339 	 * An mbuf may hasn't come from userland, but we pretend
340 	 * that it has.
341 	 */
342 	m->m_pkthdr.rcvif = NULL;
343 	m->m_nextpkt = NULL;
344 	M_SETFIB(m, so->so_fibnum);
345 
346 	mtag = m_tag_locate(m, MTAG_IPFW_RULE, 0, NULL);
347 	if (mtag == NULL) {
348 		/* this should be normal */
349 		mtag = m_tag_alloc(MTAG_IPFW_RULE, 0,
350 		    sizeof(struct ipfw_rule_ref), M_NOWAIT | M_ZERO);
351 		if (mtag == NULL) {
352 			m_freem(m);
353 			return (ENOBUFS);
354 		}
355 		m_tag_prepend(m, mtag);
356 	}
357 	dt = (struct ipfw_rule_ref *)(mtag+1);
358 
359 	/* Loopback avoidance and state recovery */
360 	if (sin) {
361 		int i;
362 
363 		/* set the starting point. We provide a non-zero slot,
364 		 * but a non_matching chain_id to skip that info and use
365 		 * the rulenum/rule_id.
366 		 */
367 		dt->slot = 1; /* dummy, chain_id is invalid */
368 		dt->chain_id = 0;
369 		dt->rulenum = sin->sin_port+1; /* host format ? */
370 		dt->rule_id = 0;
371 		/* XXX: broken for IPv6 */
372 		/*
373 		 * Find receive interface with the given name, stuffed
374 		 * (if it exists) in the sin_zero[] field.
375 		 * The name is user supplied data so don't trust its size
376 		 * or that it is zero terminated.
377 		 */
378 		for (i = 0; i < sizeof(sin->sin_zero) && sin->sin_zero[i]; i++)
379 			;
380 		if ( i > 0 && i < sizeof(sin->sin_zero))
381 			m->m_pkthdr.rcvif = ifunit(sin->sin_zero);
382 	}
383 
384 	ip = mtod(m, struct ip *);
385 	switch (ip->ip_v) {
386 #ifdef INET
387 	case IPVERSION:
388 		family = AF_INET;
389 		break;
390 #endif
391 #ifdef INET6
392 	case IPV6_VERSION >> 4:
393 		family = AF_INET6;
394 		break;
395 #endif
396 	default:
397 		m_freem(m);
398 		return (EAFNOSUPPORT);
399 	}
400 
401 	mtag = m_tag_locate(m, MTAG_PF_DIVERT, 0, NULL);
402 	if (mtag == NULL) {
403 		/* this should be normal */
404 		mtag = m_tag_alloc(MTAG_PF_DIVERT, 0,
405 		    sizeof(struct pf_divert_mtag), M_NOWAIT | M_ZERO);
406 		if (mtag == NULL) {
407 			m_freem(m);
408 			return (ENOBUFS);
409 		}
410 		m_tag_prepend(m, mtag);
411 	}
412 	pfdt = (struct pf_divert_mtag *)(mtag+1);
413 	if (sin)
414 		pfdt->idir = sin->sin_port;
415 
416 	/* Reinject packet into the system as incoming or outgoing */
417 	NET_EPOCH_ENTER(et);
418 	if (!sin || sin->sin_addr.s_addr == 0) {
419 		dt->info |= IPFW_IS_DIVERT | IPFW_INFO_OUT;
420 		pfdt->ndir = PF_DIVERT_MTAG_DIR_OUT;
421 		error = div_output_outbound(family, so, m);
422 	} else {
423 		dt->info |= IPFW_IS_DIVERT | IPFW_INFO_IN;
424 		pfdt->ndir = PF_DIVERT_MTAG_DIR_IN;
425 		error = div_output_inbound(family, so, m, sin);
426 	}
427 	NET_EPOCH_EXIT(et);
428 
429 	return (error);
430 }
431 
432 /*
433  * Sends mbuf @m to the wire via ip[6]_output().
434  *
435  * Returns 0 on success or an errno value on failure.  @m is always consumed.
436  */
437 static int
438 div_output_outbound(int family, struct socket *so, struct mbuf *m)
439 {
440 	int error;
441 
442 	switch (family) {
443 #ifdef INET
444 	case AF_INET:
445 	    {
446 		struct ip *const ip = mtod(m, struct ip *);
447 
448 		/* Don't allow packet length sizes that will crash. */
449 		if (((u_short)ntohs(ip->ip_len) > m->m_pkthdr.len)) {
450 			m_freem(m);
451 			return (EINVAL);
452 		}
453 		break;
454 	    }
455 #endif
456 #ifdef INET6
457 	case AF_INET6:
458 	    {
459 		struct ip6_hdr *const ip6 = mtod(m, struct ip6_hdr *);
460 
461 		/* Don't allow packet length sizes that will crash */
462 		if (((u_short)ntohs(ip6->ip6_plen) > m->m_pkthdr.len)) {
463 			m_freem(m);
464 			return (EINVAL);
465 		}
466 		break;
467 	    }
468 #endif
469 	}
470 
471 #ifdef MAC
472 	mac_socket_create_mbuf(so, m);
473 #endif
474 
475 	error = 0;
476 	switch (family) {
477 #ifdef INET
478 	case AF_INET:
479 		error = ip_output(m, NULL, NULL,
480 		    ((so->so_options & SO_DONTROUTE) ? IP_ROUTETOIF : 0)
481 		    | IP_ALLOWBROADCAST | IP_RAWOUTPUT, NULL, NULL);
482 		break;
483 #endif
484 #ifdef INET6
485 	case AF_INET6:
486 		error = ip6_output(m, NULL, NULL, 0, NULL, NULL, NULL);
487 		break;
488 #endif
489 	}
490 	if (error == 0)
491 		DIVSTAT_INC(outbound);
492 
493 	return (error);
494 }
495 
496 /*
497  * Schedules mbuf @m for local processing via IPv4/IPv6 netisr queue.
498  *
499  * Returns 0 on success or an errno value on failure.  @m is always consumed.
500  */
501 static int
502 div_output_inbound(int family, struct socket *so, struct mbuf *m,
503     struct sockaddr_in *sin)
504 {
505 	struct ifaddr *ifa;
506 
507 	if (m->m_pkthdr.rcvif == NULL) {
508 		/*
509 		 * No luck with the name, check by IP address.
510 		 * Clear the port and the ifname to make sure
511 		 * there are no distractions for ifa_ifwithaddr.
512 		 */
513 
514 		/* XXX: broken for IPv6 */
515 		bzero(sin->sin_zero, sizeof(sin->sin_zero));
516 		sin->sin_port = 0;
517 		ifa = ifa_ifwithaddr((struct sockaddr *) sin);
518 		if (ifa == NULL) {
519 			m_freem(m);
520 			return (EADDRNOTAVAIL);
521 		}
522 		m->m_pkthdr.rcvif = ifa->ifa_ifp;
523 	}
524 #ifdef MAC
525 	mac_socket_create_mbuf(so, m);
526 #endif
527 	/* Send packet to input processing via netisr */
528 	switch (family) {
529 #ifdef INET
530 	case AF_INET:
531 	    {
532 		const struct ip *ip;
533 
534 		ip = mtod(m, struct ip *);
535 		/*
536 		 * Restore M_BCAST flag when destination address is
537 		 * broadcast. It is expected by ip_tryforward().
538 		 */
539 		if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)))
540 			m->m_flags |= M_MCAST;
541 		else if (in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
542 			m->m_flags |= M_BCAST;
543 		netisr_queue_src(NETISR_IP, (uintptr_t)so, m);
544 		DIVSTAT_INC(inbound);
545 		break;
546 	    }
547 #endif
548 #ifdef INET6
549 	case AF_INET6:
550 		netisr_queue_src(NETISR_IPV6, (uintptr_t)so, m);
551 		DIVSTAT_INC(inbound);
552 		break;
553 #endif
554 	default:
555 		m_freem(m);
556 		return (EINVAL);
557 	}
558 
559 	return (0);
560 }
561 
562 static int
563 div_attach(struct socket *so, int proto, struct thread *td)
564 {
565 	struct divcb *dcb;
566 	int error;
567 
568 	if (td != NULL) {
569 		error = priv_check(td, PRIV_NETINET_DIVERT);
570 		if (error)
571 			return (error);
572 	}
573 	error = soreserve(so, div_sendspace, div_recvspace);
574 	if (error)
575 		return error;
576 	dcb = malloc(sizeof(*dcb), M_PCB, M_WAITOK);
577 	dcb->dcb_bound = DCB_UNBOUND;
578 	dcb->dcb_socket = so;
579 	DIVERT_LOCK();
580 	V_dcb_count++;
581 	dcb->dcb_gencnt = ++V_dcb_gencnt;
582 	DIVERT_UNLOCK();
583 	so->so_pcb = dcb;
584 
585 	return (0);
586 }
587 
588 static void
589 div_free(epoch_context_t ctx)
590 {
591 	struct divcb *dcb = __containerof(ctx, struct divcb, dcb_epochctx);
592 
593 	free(dcb, M_PCB);
594 }
595 
596 static void
597 div_detach(struct socket *so)
598 {
599 	struct divcb *dcb = so->so_pcb;
600 
601 	so->so_pcb = NULL;
602 	DIVERT_LOCK();
603 	if (dcb->dcb_bound != DCB_UNBOUND)
604 		SLIST_REMOVE(&V_divhash[DCBHASH(dcb)], dcb, divcb, dcb_next);
605 	V_dcb_count--;
606 	V_dcb_gencnt++;
607 	DIVERT_UNLOCK();
608 	NET_EPOCH_CALL(div_free, &dcb->dcb_epochctx);
609 }
610 
611 static int
612 div_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
613 {
614 	struct divcb *dcb;
615 	uint16_t port;
616 
617 	if (nam->sa_family != AF_INET)
618 		return EAFNOSUPPORT;
619 	if (nam->sa_len != sizeof(struct sockaddr_in))
620 		return EINVAL;
621 	port = ((struct sockaddr_in *)nam)->sin_port;
622 	DIVERT_LOCK();
623 	SLIST_FOREACH(dcb, &V_divhash[DIVHASH(port)], dcb_next)
624 		if (dcb->dcb_port == port) {
625 			DIVERT_UNLOCK();
626 			return (EADDRINUSE);
627 		}
628 	dcb = so->so_pcb;
629 	if (dcb->dcb_bound != DCB_UNBOUND)
630 		SLIST_REMOVE(&V_divhash[DCBHASH(dcb)], dcb, divcb, dcb_next);
631 	dcb->dcb_port = port;
632 	SLIST_INSERT_HEAD(&V_divhash[DIVHASH(port)], dcb, dcb_next);
633 	DIVERT_UNLOCK();
634 
635 	return (0);
636 }
637 
638 static int
639 div_shutdown(struct socket *so)
640 {
641 
642 	socantsendmore(so);
643 	return 0;
644 }
645 
646 static int
647 div_pcblist(SYSCTL_HANDLER_ARGS)
648 {
649 	struct xinpgen xig;
650 	struct divcb *dcb;
651 	int error;
652 
653 	if (req->newptr != 0)
654 		return EPERM;
655 
656 	if (req->oldptr == 0) {
657 		u_int n;
658 
659 		n = V_dcb_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_dcb_count;
671 	xig.xig_gen = V_dcb_gencnt;
672 	xig.xig_sogen = so_gencnt;
673 	error = SYSCTL_OUT(req, &xig, sizeof xig);
674 	if (error)
675 		return error;
676 
677 	DIVERT_LOCK();
678 	for (int i = 0; i < DIVHASHSIZE; i++)
679 		SLIST_FOREACH(dcb, &V_divhash[i], dcb_next) {
680 			if (dcb->dcb_gencnt <= xig.xig_gen) {
681 				struct xinpcb xi;
682 
683 				bzero(&xi, sizeof(xi));
684 				xi.xi_len = sizeof(struct xinpcb);
685 				sotoxsocket(dcb->dcb_socket, &xi.xi_socket);
686 				xi.inp_gencnt = dcb->dcb_gencnt;
687 				xi.inp_vflag = INP_IPV4; /* XXX: netstat(1) */
688 				xi.inp_inc.inc_ie.ie_lport = dcb->dcb_port;
689 				error = SYSCTL_OUT(req, &xi, sizeof xi);
690 				if (error)
691 					goto errout;
692 			}
693 		}
694 
695 	/*
696 	 * Give the user an updated idea of our state.
697 	 * If the generation differs from what we told
698 	 * her before, she knows that something happened
699 	 * while we were processing this request, and it
700 	 * might be necessary to retry.
701 	 */
702 	xig.xig_gen = V_dcb_gencnt;
703 	xig.xig_sogen = so_gencnt;
704 	xig.xig_count = V_dcb_count;
705 	error = SYSCTL_OUT(req, &xig, sizeof xig);
706 
707 errout:
708 	DIVERT_UNLOCK();
709 
710 	return (error);
711 }
712 SYSCTL_PROC(_net_inet_divert, OID_AUTO, pcblist,
713     CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, 0, div_pcblist,
714     "S,xinpcb", "List of active divert sockets");
715 
716 static struct protosw div_protosw = {
717 	.pr_type =		SOCK_RAW,
718 	.pr_flags =		PR_ATOMIC|PR_ADDR,
719 	.pr_attach =		div_attach,
720 	.pr_bind =		div_bind,
721 	.pr_detach =		div_detach,
722 	.pr_send =		div_send,
723 	.pr_shutdown =		div_shutdown,
724 };
725 
726 static struct domain divertdomain = {
727 	.dom_family =	PF_DIVERT,
728 	.dom_name =	"divert",
729 	.dom_nprotosw =	1,
730 	.dom_protosw =	{ &div_protosw },
731 };
732 
733 static int
734 div_modevent(module_t mod, int type, void *unused)
735 {
736 	int err = 0;
737 
738 	switch (type) {
739 	case MOD_LOAD:
740 		domain_add(&divertdomain);
741 		ip_divert_ptr = divert_packet;
742 		break;
743 	case MOD_QUIESCE:
744 		/*
745 		 * IPDIVERT may normally not be unloaded because of the
746 		 * potential race conditions.  Tell kldunload we can't be
747 		 * unloaded unless the unload is forced.
748 		 */
749 		err = EPERM;
750 		break;
751 	case MOD_UNLOAD:
752 		/*
753 		 * Forced unload.
754 		 *
755 		 * Module ipdivert can only be unloaded if no sockets are
756 		 * connected.  Maybe this can be changed later to forcefully
757 		 * disconnect any open sockets.
758 		 *
759 		 * XXXRW: Note that there is a slight race here, as a new
760 		 * socket open request could be spinning on the lock and then
761 		 * we destroy the lock.
762 		 *
763 		 * XXXGL: One more reason this code is incorrect is that it
764 		 * checks only the current vnet.
765 		 */
766 		DIVERT_LOCK();
767 		if (V_dcb_count != 0) {
768 			DIVERT_UNLOCK();
769 			err = EBUSY;
770 			break;
771 		}
772 		DIVERT_UNLOCK();
773 		ip_divert_ptr = NULL;
774 		domain_remove(&divertdomain);
775 		break;
776 	default:
777 		err = EOPNOTSUPP;
778 		break;
779 	}
780 	return err;
781 }
782 
783 static moduledata_t ipdivertmod = {
784         "ipdivert",
785         div_modevent,
786         0
787 };
788 
789 DECLARE_MODULE(ipdivert, ipdivertmod, SI_SUB_PROTO_FIREWALL, SI_ORDER_ANY);
790 MODULE_VERSION(ipdivert, 1);
791