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