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