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