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