ip_divert.c revision 165634
1206917Smarius/*-
2206917Smarius * Copyright (c) 1982, 1986, 1988, 1993
3206917Smarius *	The Regents of the University of California.  All rights reserved.
4206917Smarius *
5206917Smarius * Redistribution and use in source and binary forms, with or without
6206917Smarius * modification, are permitted provided that the following conditions
7206917Smarius * are met:
8206917Smarius * 1. Redistributions of source code must retain the above copyright
9206917Smarius *    notice, this list of conditions and the following disclaimer.
10206917Smarius * 2. Redistributions in binary form must reproduce the above copyright
11206917Smarius *    notice, this list of conditions and the following disclaimer in the
12206917Smarius *    documentation and/or other materials provided with the distribution.
13206917Smarius * 4. Neither the name of the University nor the names of its contributors
14206917Smarius *    may be used to endorse or promote products derived from this software
15206917Smarius *    without specific prior written permission.
16206917Smarius *
17206917Smarius * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18206917Smarius * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19206917Smarius * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20206917Smarius * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21206917Smarius * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22206917Smarius * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23206917Smarius * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24206917Smarius * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25206917Smarius * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26206917Smarius * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27206917Smarius * SUCH DAMAGE.
28206917Smarius *
29206917Smarius * $FreeBSD: head/sys/netinet/ip_divert.c 165634 2006-12-29 14:58:18Z jhb $
30206917Smarius */
31206917Smarius
32206917Smarius#if !defined(KLD_MODULE)
33206917Smarius#include "opt_inet.h"
34206917Smarius#include "opt_ipfw.h"
35206917Smarius#include "opt_mac.h"
36206917Smarius#ifndef INET
37206917Smarius#error "IPDIVERT requires INET."
38206917Smarius#endif
39206917Smarius#ifndef IPFIREWALL
40206917Smarius#error "IPDIVERT requires IPFIREWALL"
41206917Smarius#endif
42206917Smarius#endif
43206917Smarius
44206917Smarius#include <sys/param.h>
45206917Smarius#include <sys/kernel.h>
46206917Smarius#include <sys/lock.h>
47206917Smarius#include <sys/malloc.h>
48206917Smarius#include <sys/mbuf.h>
49206917Smarius#include <sys/module.h>
50206917Smarius#include <sys/kernel.h>
51206917Smarius#include <sys/priv.h>
52206917Smarius#include <sys/proc.h>
53206917Smarius#include <sys/protosw.h>
54206917Smarius#include <sys/signalvar.h>
55206917Smarius#include <sys/socket.h>
56206917Smarius#include <sys/socketvar.h>
57206917Smarius#include <sys/sx.h>
58206917Smarius#include <sys/sysctl.h>
59206917Smarius#include <sys/systm.h>
60206917Smarius
61206917Smarius#include <vm/uma.h>
62206917Smarius
63206917Smarius#include <net/if.h>
64206917Smarius#include <net/route.h>
65206917Smarius
66206917Smarius#include <netinet/in.h>
67206917Smarius#include <netinet/in_pcb.h>
68206917Smarius#include <netinet/in_systm.h>
69206917Smarius#include <netinet/in_var.h>
70206917Smarius#include <netinet/ip.h>
71206917Smarius#include <netinet/ip_divert.h>
72206917Smarius#include <netinet/ip_var.h>
73206917Smarius#include <netinet/ip_fw.h>
74206917Smarius
75206917Smarius#include <security/mac/mac_framework.h>
76206917Smarius
77206917Smarius/*
78206917Smarius * Divert sockets
79206917Smarius */
80206917Smarius
81206917Smarius/*
82206917Smarius * Allocate enough space to hold a full IP packet
83206917Smarius */
84206917Smarius#define	DIVSNDQ		(65536 + 100)
85206917Smarius#define	DIVRCVQ		(65536 + 100)
86206917Smarius
87206917Smarius/*
88206917Smarius * Divert sockets work in conjunction with ipfw, see the divert(4)
89206917Smarius * manpage for features.
90206917Smarius * Internally, packets selected by ipfw in ip_input() or ip_output(),
91206917Smarius * and never diverted before, are passed to the input queue of the
92206917Smarius * divert socket with a given 'divert_port' number (as specified in
93206917Smarius * the matching ipfw rule), and they are tagged with a 16 bit cookie
94206917Smarius * (representing the rule number of the matching ipfw rule), which
95206917Smarius * is passed to process reading from the socket.
96206917Smarius *
97206917Smarius * Packets written to the divert socket are again tagged with a cookie
98206917Smarius * (usually the same as above) and a destination address.
99206917Smarius * If the destination address is INADDR_ANY then the packet is
100206917Smarius * treated as outgoing and sent to ip_output(), otherwise it is
101206917Smarius * treated as incoming and sent to ip_input().
102206917Smarius * In both cases, the packet is tagged with the cookie.
103206917Smarius *
104206917Smarius * On reinjection, processing in ip_input() and ip_output()
105206917Smarius * will be exactly the same as for the original packet, except that
106206917Smarius * ipfw processing will start at the rule number after the one
107206917Smarius * written in the cookie (so, tagging a packet with a cookie of 0
108206917Smarius * will cause it to be effectively considered as a standard packet).
109206917Smarius */
110206917Smarius
111206917Smarius/* Internal variables. */
112206917Smariusstatic struct inpcbhead divcb;
113206917Smariusstatic struct inpcbinfo divcbinfo;
114206917Smarius
115206917Smariusstatic u_long	div_sendspace = DIVSNDQ;	/* XXX sysctl ? */
116206917Smariusstatic u_long	div_recvspace = DIVRCVQ;	/* XXX sysctl ? */
117206917Smarius
118206917Smarius/*
119206917Smarius * Initialize divert connection block queue.
120206917Smarius */
121206917Smariusstatic void
122206917Smariusdiv_zone_change(void *tag)
123206917Smarius{
124206917Smarius
125206917Smarius	uma_zone_set_max(divcbinfo.ipi_zone, maxsockets);
126206917Smarius}
127206917Smarius
128206917Smariusstatic int
129206917Smariusdiv_inpcb_init(void *mem, int size, int flags)
130206917Smarius{
131206917Smarius	struct inpcb *inp = mem;
132206917Smarius
133206917Smarius	INP_LOCK_INIT(inp, "inp", "divinp");
134206917Smarius	return (0);
135206917Smarius}
136206917Smarius
137206917Smariusstatic void
138206917Smariusdiv_inpcb_fini(void *mem, int size)
139206917Smarius{
140206917Smarius	struct inpcb *inp = mem;
141206917Smarius
142206917Smarius	INP_LOCK_DESTROY(inp);
143206917Smarius}
144206917Smarius
145206917Smariusvoid
146206917Smariusdiv_init(void)
147206917Smarius{
148206917Smarius	INP_INFO_LOCK_INIT(&divcbinfo, "div");
149206917Smarius	LIST_INIT(&divcb);
150206917Smarius	divcbinfo.listhead = &divcb;
151206917Smarius	/*
152206917Smarius	 * XXX We don't use the hash list for divert IP, but it's easier
153206917Smarius	 * to allocate a one entry hash list than it is to check all
154206917Smarius	 * over the place for hashbase == NULL.
155206917Smarius	 */
156206917Smarius	divcbinfo.hashbase = hashinit(1, M_PCB, &divcbinfo.hashmask);
157206917Smarius	divcbinfo.porthashbase = hashinit(1, M_PCB, &divcbinfo.porthashmask);
158206917Smarius	divcbinfo.ipi_zone = uma_zcreate("divcb", sizeof(struct inpcb),
159206917Smarius	    NULL, NULL, div_inpcb_init, div_inpcb_fini, UMA_ALIGN_PTR,
160206917Smarius	    UMA_ZONE_NOFREE);
161206917Smarius	uma_zone_set_max(divcbinfo.ipi_zone, maxsockets);
162206917Smarius	EVENTHANDLER_REGISTER(maxsockets_change, div_zone_change,
163206917Smarius		NULL, EVENTHANDLER_PRI_ANY);
164206917Smarius}
165206917Smarius
166206917Smarius/*
167206917Smarius * IPPROTO_DIVERT is not in the real IP protocol number space; this
168206917Smarius * function should never be called.  Just in case, drop any packets.
169206917Smarius */
170206917Smariusvoid
171206917Smariusdiv_input(struct mbuf *m, int off)
172206917Smarius{
173206917Smarius	ipstat.ips_noproto++;
174206917Smarius	m_freem(m);
175206917Smarius}
176206917Smarius
177206917Smarius/*
178206917Smarius * Divert a packet by passing it up to the divert socket at port 'port'.
179206917Smarius *
180206917Smarius * Setup generic address and protocol structures for div_input routine,
181206917Smarius * then pass them along with mbuf chain.
182206917Smarius */
183206917Smariusstatic void
184divert_packet(struct mbuf *m, int incoming)
185{
186	struct ip *ip;
187	struct inpcb *inp;
188	struct socket *sa;
189	u_int16_t nport;
190	struct sockaddr_in divsrc;
191	struct m_tag *mtag;
192
193	mtag = m_tag_find(m, PACKET_TAG_DIVERT, NULL);
194	if (mtag == NULL) {
195		printf("%s: no divert tag\n", __func__);
196		m_freem(m);
197		return;
198	}
199	/* Assure header */
200	if (m->m_len < sizeof(struct ip) &&
201	    (m = m_pullup(m, sizeof(struct ip))) == 0)
202		return;
203	ip = mtod(m, struct ip *);
204
205	/* Delayed checksums are currently not compatible with divert. */
206	if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
207		ip->ip_len = ntohs(ip->ip_len);
208		in_delayed_cksum(m);
209		m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
210		ip->ip_len = htons(ip->ip_len);
211	}
212
213	/*
214	 * Record receive interface address, if any.
215	 * But only for incoming packets.
216	 */
217	bzero(&divsrc, sizeof(divsrc));
218	divsrc.sin_len = sizeof(divsrc);
219	divsrc.sin_family = AF_INET;
220	divsrc.sin_port = divert_cookie(mtag);	/* record matching rule */
221	if (incoming) {
222		struct ifaddr *ifa;
223
224		/* Sanity check */
225		M_ASSERTPKTHDR(m);
226
227		/* Find IP address for receive interface */
228		TAILQ_FOREACH(ifa, &m->m_pkthdr.rcvif->if_addrhead, ifa_link) {
229			if (ifa->ifa_addr->sa_family != AF_INET)
230				continue;
231			divsrc.sin_addr =
232			    ((struct sockaddr_in *) ifa->ifa_addr)->sin_addr;
233			break;
234		}
235	}
236	/*
237	 * Record the incoming interface name whenever we have one.
238	 */
239	if (m->m_pkthdr.rcvif) {
240		/*
241		 * Hide the actual interface name in there in the
242		 * sin_zero array. XXX This needs to be moved to a
243		 * different sockaddr type for divert, e.g.
244		 * sockaddr_div with multiple fields like
245		 * sockaddr_dl. Presently we have only 7 bytes
246		 * but that will do for now as most interfaces
247		 * are 4 or less + 2 or less bytes for unit.
248		 * There is probably a faster way of doing this,
249		 * possibly taking it from the sockaddr_dl on the iface.
250		 * This solves the problem of a P2P link and a LAN interface
251		 * having the same address, which can result in the wrong
252		 * interface being assigned to the packet when fed back
253		 * into the divert socket. Theoretically if the daemon saves
254		 * and re-uses the sockaddr_in as suggested in the man pages,
255		 * this iface name will come along for the ride.
256		 * (see div_output for the other half of this.)
257		 */
258		strlcpy(divsrc.sin_zero, m->m_pkthdr.rcvif->if_xname,
259		    sizeof(divsrc.sin_zero));
260	}
261
262	/* Put packet on socket queue, if any */
263	sa = NULL;
264	nport = htons((u_int16_t)divert_info(mtag));
265	INP_INFO_RLOCK(&divcbinfo);
266	LIST_FOREACH(inp, &divcb, inp_list) {
267		INP_LOCK(inp);
268		/* XXX why does only one socket match? */
269		if (inp->inp_lport == nport) {
270			sa = inp->inp_socket;
271			SOCKBUF_LOCK(&sa->so_rcv);
272			if (sbappendaddr_locked(&sa->so_rcv,
273			    (struct sockaddr *)&divsrc, m,
274			    (struct mbuf *)0) == 0) {
275				SOCKBUF_UNLOCK(&sa->so_rcv);
276				sa = NULL;	/* force mbuf reclaim below */
277			} else
278				sorwakeup_locked(sa);
279			INP_UNLOCK(inp);
280			break;
281		}
282		INP_UNLOCK(inp);
283	}
284	INP_INFO_RUNLOCK(&divcbinfo);
285	if (sa == NULL) {
286		m_freem(m);
287		ipstat.ips_noproto++;
288		ipstat.ips_delivered--;
289        }
290}
291
292/*
293 * Deliver packet back into the IP processing machinery.
294 *
295 * If no address specified, or address is 0.0.0.0, send to ip_output();
296 * otherwise, send to ip_input() and mark as having been received on
297 * the interface with that address.
298 */
299static int
300div_output(struct socket *so, struct mbuf *m,
301	struct sockaddr_in *sin, struct mbuf *control)
302{
303	struct m_tag *mtag;
304	struct divert_tag *dt;
305	int error = 0;
306
307	/*
308	 * An mbuf may hasn't come from userland, but we pretend
309	 * that it has.
310	 */
311	m->m_pkthdr.rcvif = NULL;
312	m->m_nextpkt = NULL;
313
314	if (control)
315		m_freem(control);		/* XXX */
316
317	if ((mtag = m_tag_find(m, PACKET_TAG_DIVERT, NULL)) == NULL) {
318		mtag = m_tag_get(PACKET_TAG_DIVERT, sizeof(struct divert_tag),
319		    M_NOWAIT | M_ZERO);
320		if (mtag == NULL) {
321			error = ENOBUFS;
322			goto cantsend;
323		}
324		dt = (struct divert_tag *)(mtag+1);
325		m_tag_prepend(m, mtag);
326	} else
327		dt = (struct divert_tag *)(mtag+1);
328
329	/* Loopback avoidance and state recovery */
330	if (sin) {
331		int i;
332
333		dt->cookie = sin->sin_port;
334		/*
335		 * Find receive interface with the given name, stuffed
336		 * (if it exists) in the sin_zero[] field.
337		 * The name is user supplied data so don't trust its size
338		 * or that it is zero terminated.
339		 */
340		for (i = 0; i < sizeof(sin->sin_zero) && sin->sin_zero[i]; i++)
341			;
342		if ( i > 0 && i < sizeof(sin->sin_zero))
343			m->m_pkthdr.rcvif = ifunit(sin->sin_zero);
344	}
345
346	/* Reinject packet into the system as incoming or outgoing */
347	if (!sin || sin->sin_addr.s_addr == 0) {
348		struct ip *const ip = mtod(m, struct ip *);
349		struct inpcb *inp;
350
351		dt->info |= IP_FW_DIVERT_OUTPUT_FLAG;
352		INP_INFO_WLOCK(&divcbinfo);
353		inp = sotoinpcb(so);
354		INP_LOCK(inp);
355		/*
356		 * Don't allow both user specified and setsockopt options,
357		 * and don't allow packet length sizes that will crash
358		 */
359		if (((ip->ip_hl != (sizeof (*ip) >> 2)) && inp->inp_options) ||
360		     ((u_short)ntohs(ip->ip_len) > m->m_pkthdr.len)) {
361			error = EINVAL;
362			m_freem(m);
363		} else {
364			/* Convert fields to host order for ip_output() */
365			ip->ip_len = ntohs(ip->ip_len);
366			ip->ip_off = ntohs(ip->ip_off);
367
368			/* Send packet to output processing */
369			ipstat.ips_rawout++;			/* XXX */
370
371#ifdef MAC
372			mac_create_mbuf_from_inpcb(inp, m);
373#endif
374			error = ip_output(m,
375				    inp->inp_options, NULL,
376				    ((so->so_options & SO_DONTROUTE) ?
377				    IP_ROUTETOIF : 0) |
378				    IP_ALLOWBROADCAST | IP_RAWOUTPUT,
379				    inp->inp_moptions, NULL);
380		}
381		INP_UNLOCK(inp);
382		INP_INFO_WUNLOCK(&divcbinfo);
383	} else {
384		dt->info |= IP_FW_DIVERT_LOOPBACK_FLAG;
385		if (m->m_pkthdr.rcvif == NULL) {
386			/*
387			 * No luck with the name, check by IP address.
388			 * Clear the port and the ifname to make sure
389			 * there are no distractions for ifa_ifwithaddr.
390			 */
391			struct	ifaddr *ifa;
392
393			bzero(sin->sin_zero, sizeof(sin->sin_zero));
394			sin->sin_port = 0;
395			ifa = ifa_ifwithaddr((struct sockaddr *) sin);
396			if (ifa == NULL) {
397				error = EADDRNOTAVAIL;
398				goto cantsend;
399			}
400			m->m_pkthdr.rcvif = ifa->ifa_ifp;
401		}
402#ifdef MAC
403		SOCK_LOCK(so);
404		mac_create_mbuf_from_socket(so, m);
405		SOCK_UNLOCK(so);
406#endif
407		/* Send packet to input processing */
408		ip_input(m);
409	}
410
411	return error;
412
413cantsend:
414	m_freem(m);
415	return error;
416}
417
418static int
419div_attach(struct socket *so, int proto, struct thread *td)
420{
421	struct inpcb *inp;
422	int error;
423
424	inp  = sotoinpcb(so);
425	KASSERT(inp == NULL, ("div_attach: inp != NULL"));
426	if (td != NULL) {
427		error = priv_check(td, PRIV_NETINET_DIVERT);
428		if (error)
429			return (error);
430	}
431	error = soreserve(so, div_sendspace, div_recvspace);
432	if (error)
433		return error;
434	INP_INFO_WLOCK(&divcbinfo);
435	error = in_pcballoc(so, &divcbinfo);
436	if (error) {
437		INP_INFO_WUNLOCK(&divcbinfo);
438		return error;
439	}
440	inp = (struct inpcb *)so->so_pcb;
441	INP_INFO_WUNLOCK(&divcbinfo);
442	inp->inp_ip_p = proto;
443	inp->inp_vflag |= INP_IPV4;
444	inp->inp_flags |= INP_HDRINCL;
445	INP_UNLOCK(inp);
446	return 0;
447}
448
449static void
450div_detach(struct socket *so)
451{
452	struct inpcb *inp;
453
454	inp = sotoinpcb(so);
455	KASSERT(inp != NULL, ("div_detach: inp == NULL"));
456	INP_INFO_WLOCK(&divcbinfo);
457	INP_LOCK(inp);
458	in_pcbdetach(inp);
459	in_pcbfree(inp);
460	INP_INFO_WUNLOCK(&divcbinfo);
461}
462
463static int
464div_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
465{
466	struct inpcb *inp;
467	int error;
468
469	inp = sotoinpcb(so);
470	KASSERT(inp != NULL, ("div_bind: inp == NULL"));
471	/* in_pcbbind assumes that nam is a sockaddr_in
472	 * and in_pcbbind requires a valid address. Since divert
473	 * sockets don't we need to make sure the address is
474	 * filled in properly.
475	 * XXX -- divert should not be abusing in_pcbind
476	 * and should probably have its own family.
477	 */
478	if (nam->sa_family != AF_INET)
479		return EAFNOSUPPORT;
480	((struct sockaddr_in *)nam)->sin_addr.s_addr = INADDR_ANY;
481	INP_INFO_WLOCK(&divcbinfo);
482	INP_LOCK(inp);
483	error = in_pcbbind(inp, nam, td->td_ucred);
484	INP_UNLOCK(inp);
485	INP_INFO_WUNLOCK(&divcbinfo);
486	return error;
487}
488
489static int
490div_shutdown(struct socket *so)
491{
492	struct inpcb *inp;
493
494	inp = sotoinpcb(so);
495	KASSERT(inp != NULL, ("div_shutdown: inp == NULL"));
496	INP_LOCK(inp);
497	socantsendmore(so);
498	INP_UNLOCK(inp);
499	return 0;
500}
501
502static int
503div_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
504	 struct mbuf *control, struct thread *td)
505{
506	/* Packet must have a header (but that's about it) */
507	if (m->m_len < sizeof (struct ip) &&
508	    (m = m_pullup(m, sizeof (struct ip))) == 0) {
509		ipstat.ips_toosmall++;
510		m_freem(m);
511		return EINVAL;
512	}
513
514	/* Send packet */
515	return div_output(so, m, (struct sockaddr_in *)nam, control);
516}
517
518void
519div_ctlinput(int cmd, struct sockaddr *sa, void *vip)
520{
521        struct in_addr faddr;
522
523	faddr = ((struct sockaddr_in *)sa)->sin_addr;
524	if (sa->sa_family != AF_INET || faddr.s_addr == INADDR_ANY)
525        	return;
526	if (PRC_IS_REDIRECT(cmd))
527		return;
528}
529
530static int
531div_pcblist(SYSCTL_HANDLER_ARGS)
532{
533	int error, i, n;
534	struct inpcb *inp, **inp_list;
535	inp_gen_t gencnt;
536	struct xinpgen xig;
537
538	/*
539	 * The process of preparing the TCB list is too time-consuming and
540	 * resource-intensive to repeat twice on every request.
541	 */
542	if (req->oldptr == 0) {
543		n = divcbinfo.ipi_count;
544		req->oldidx = 2 * (sizeof xig)
545			+ (n + n/8) * sizeof(struct xinpcb);
546		return 0;
547	}
548
549	if (req->newptr != 0)
550		return EPERM;
551
552	/*
553	 * OK, now we're committed to doing something.
554	 */
555	INP_INFO_RLOCK(&divcbinfo);
556	gencnt = divcbinfo.ipi_gencnt;
557	n = divcbinfo.ipi_count;
558	INP_INFO_RUNLOCK(&divcbinfo);
559
560	error = sysctl_wire_old_buffer(req,
561	    2 * sizeof(xig) + n*sizeof(struct xinpcb));
562	if (error != 0)
563		return (error);
564
565	xig.xig_len = sizeof xig;
566	xig.xig_count = n;
567	xig.xig_gen = gencnt;
568	xig.xig_sogen = so_gencnt;
569	error = SYSCTL_OUT(req, &xig, sizeof xig);
570	if (error)
571		return error;
572
573	inp_list = malloc(n * sizeof *inp_list, M_TEMP, M_WAITOK);
574	if (inp_list == 0)
575		return ENOMEM;
576
577	INP_INFO_RLOCK(&divcbinfo);
578	for (inp = LIST_FIRST(divcbinfo.listhead), i = 0; inp && i < n;
579	     inp = LIST_NEXT(inp, inp_list)) {
580		INP_LOCK(inp);
581		if (inp->inp_gencnt <= gencnt &&
582		    cr_canseesocket(req->td->td_ucred, inp->inp_socket) == 0)
583			inp_list[i++] = inp;
584		INP_UNLOCK(inp);
585	}
586	INP_INFO_RUNLOCK(&divcbinfo);
587	n = i;
588
589	error = 0;
590	for (i = 0; i < n; i++) {
591		inp = inp_list[i];
592		INP_LOCK(inp);
593		if (inp->inp_gencnt <= gencnt) {
594			struct xinpcb xi;
595			bzero(&xi, sizeof(xi));
596			xi.xi_len = sizeof xi;
597			/* XXX should avoid extra copy */
598			bcopy(inp, &xi.xi_inp, sizeof *inp);
599			if (inp->inp_socket)
600				sotoxsocket(inp->inp_socket, &xi.xi_socket);
601			INP_UNLOCK(inp);
602			error = SYSCTL_OUT(req, &xi, sizeof xi);
603		} else
604			INP_UNLOCK(inp);
605	}
606	if (!error) {
607		/*
608		 * Give the user an updated idea of our state.
609		 * If the generation differs from what we told
610		 * her before, she knows that something happened
611		 * while we were processing this request, and it
612		 * might be necessary to retry.
613		 */
614		INP_INFO_RLOCK(&divcbinfo);
615		xig.xig_gen = divcbinfo.ipi_gencnt;
616		xig.xig_sogen = so_gencnt;
617		xig.xig_count = divcbinfo.ipi_count;
618		INP_INFO_RUNLOCK(&divcbinfo);
619		error = SYSCTL_OUT(req, &xig, sizeof xig);
620	}
621	free(inp_list, M_TEMP);
622	return error;
623}
624
625/*
626 * This is the wrapper function for in_setsockaddr.  We just pass down
627 * the pcbinfo for in_setpeeraddr to lock.
628 */
629static int
630div_sockaddr(struct socket *so, struct sockaddr **nam)
631{
632	return (in_setsockaddr(so, nam, &divcbinfo));
633}
634
635/*
636 * This is the wrapper function for in_setpeeraddr. We just pass down
637 * the pcbinfo for in_setpeeraddr to lock.
638 */
639static int
640div_peeraddr(struct socket *so, struct sockaddr **nam)
641{
642	return (in_setpeeraddr(so, nam, &divcbinfo));
643}
644
645#ifdef SYSCTL_NODE
646SYSCTL_NODE(_net_inet, IPPROTO_DIVERT, divert, CTLFLAG_RW, 0, "IPDIVERT");
647SYSCTL_PROC(_net_inet_divert, OID_AUTO, pcblist, CTLFLAG_RD, 0, 0,
648	    div_pcblist, "S,xinpcb", "List of active divert sockets");
649#endif
650
651struct pr_usrreqs div_usrreqs = {
652	.pru_attach =		div_attach,
653	.pru_bind =		div_bind,
654	.pru_control =		in_control,
655	.pru_detach =		div_detach,
656	.pru_peeraddr =		div_peeraddr,
657	.pru_send =		div_send,
658	.pru_shutdown =		div_shutdown,
659	.pru_sockaddr =		div_sockaddr,
660	.pru_sosetlabel =	in_pcbsosetlabel
661};
662
663struct protosw div_protosw = {
664	.pr_type =		SOCK_RAW,
665	.pr_protocol =		IPPROTO_DIVERT,
666	.pr_flags =		PR_ATOMIC|PR_ADDR,
667	.pr_input =		div_input,
668	.pr_ctlinput =		div_ctlinput,
669	.pr_ctloutput =		ip_ctloutput,
670	.pr_init =		div_init,
671	.pr_usrreqs =		&div_usrreqs
672};
673
674static int
675div_modevent(module_t mod, int type, void *unused)
676{
677	int err = 0;
678	int n;
679
680	switch (type) {
681	case MOD_LOAD:
682		/*
683		 * Protocol will be initialized by pf_proto_register().
684		 * We don't have to register ip_protox because we are not
685		 * a true IP protocol that goes over the wire.
686		 */
687		err = pf_proto_register(PF_INET, &div_protosw);
688		ip_divert_ptr = divert_packet;
689		break;
690	case MOD_QUIESCE:
691		/*
692		 * IPDIVERT may normally not be unloaded because of the
693		 * potential race conditions.  Tell kldunload we can't be
694		 * unloaded unless the unload is forced.
695		 */
696		err = EPERM;
697		break;
698	case MOD_UNLOAD:
699		/*
700		 * Forced unload.
701		 *
702		 * Module ipdivert can only be unloaded if no sockets are
703		 * connected.  Maybe this can be changed later to forcefully
704		 * disconnect any open sockets.
705		 *
706		 * XXXRW: Note that there is a slight race here, as a new
707		 * socket open request could be spinning on the lock and then
708		 * we destroy the lock.
709		 */
710		INP_INFO_WLOCK(&divcbinfo);
711		n = divcbinfo.ipi_count;
712		if (n != 0) {
713			err = EBUSY;
714			INP_INFO_WUNLOCK(&divcbinfo);
715			break;
716		}
717		ip_divert_ptr = NULL;
718		err = pf_proto_unregister(PF_INET, IPPROTO_DIVERT, SOCK_RAW);
719		INP_INFO_WUNLOCK(&divcbinfo);
720		INP_INFO_LOCK_DESTROY(&divcbinfo);
721		uma_zdestroy(divcbinfo.ipi_zone);
722		break;
723	default:
724		err = EOPNOTSUPP;
725		break;
726	}
727	return err;
728}
729
730static moduledata_t ipdivertmod = {
731        "ipdivert",
732        div_modevent,
733        0
734};
735
736DECLARE_MODULE(ipdivert, ipdivertmod, SI_SUB_PROTO_IFATTACHDOMAIN, SI_ORDER_ANY);
737MODULE_DEPEND(dummynet, ipfw, 2, 2, 2);
738MODULE_VERSION(ipdivert, 1);
739