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