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