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