ip_divert.c revision 36707
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 * 3. All advertising materials mentioning features or use of this software
14 *    must display the following acknowledgement:
15 *	This product includes software developed by the University of
16 *	California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 *    may be used to endorse or promote products derived from this software
19 *    without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 *
33 *	$Id: ip_divert.c,v 1.27 1998/06/05 22:39:52 julian Exp $
34 */
35
36#include "opt_inet.h"
37#include "opt_ipfw.h"
38
39#ifndef INET
40#error "IPDIVERT requires INET."
41#endif
42
43#include <sys/param.h>
44#include <sys/malloc.h>
45#include <sys/mbuf.h>
46#include <sys/socket.h>
47#include <sys/protosw.h>
48#include <sys/socketvar.h>
49#include <sys/systm.h>
50#include <sys/proc.h>
51
52#include <vm/vm_zone.h>
53
54#include <net/if.h>
55#include <net/route.h>
56
57#include <netinet/in.h>
58#include <netinet/in_systm.h>
59#include <netinet/ip.h>
60#include <netinet/in_pcb.h>
61#include <netinet/in_var.h>
62#include <netinet/ip_var.h>
63
64/*
65 * Divert sockets
66 */
67
68/*
69 * Allocate enough space to hold a full IP packet
70 */
71#define	DIVSNDQ		(65536 + 100)
72#define	DIVRCVQ		(65536 + 100)
73
74/* Global variables */
75
76/*
77 * ip_input() and ip_output() set this secret value before calling us to
78 * let us know which divert port to divert a packet to; this is done so
79 * we can use the existing prototype for struct protosw's pr_input().
80 * This is stored in host order.
81 */
82u_short ip_divert_port;
83
84/*
85 * #ifdef IPFW_DIVERT_OLDRESTART
86 * We set this value to a non-zero port number when we want the call to
87 * ip_fw_chk() in ip_input() or ip_output() to ignore ``divert <port>''
88 * chain entries. This is stored in host order.
89 * #else
90 * A 16 bit cookie is passed to the user process.
91 * The user process can send it back to help the caller know something
92 * about where the packet came from.
93 *
94 * If IPFW is the caller then the cookie is the rule that sent
95 * us here. On reinjection is is the rule after which processing
96 * should continue. Leaving it the same will make processing start
97 * at the rule number after that which sent it here. Setting it to
98 * 0 will restart processing at the beginning.
99 * #endif
100 */
101u_short ip_divert_cookie;
102
103/* Internal variables */
104
105static struct inpcbhead divcb;
106static struct inpcbinfo divcbinfo;
107
108static u_long	div_sendspace = DIVSNDQ;	/* XXX sysctl ? */
109static u_long	div_recvspace = DIVRCVQ;	/* XXX sysctl ? */
110
111/* Optimization: have this preinitialized */
112static struct sockaddr_in divsrc = { sizeof(divsrc), AF_INET };
113
114/* Internal functions */
115
116static int div_output(struct socket *so,
117		struct mbuf *m, struct sockaddr *addr, struct mbuf *control);
118
119/*
120 * Initialize divert connection block queue.
121 */
122void
123div_init(void)
124{
125	LIST_INIT(&divcb);
126	divcbinfo.listhead = &divcb;
127	/*
128	 * XXX We don't use the hash list for divert IP, but it's easier
129	 * to allocate a one entry hash list than it is to check all
130	 * over the place for hashbase == NULL.
131	 */
132	divcbinfo.hashbase = hashinit(1, M_PCB, &divcbinfo.hashmask);
133	divcbinfo.porthashbase = hashinit(1, M_PCB, &divcbinfo.porthashmask);
134	divcbinfo.ipi_zone = zinit("divcb", sizeof(struct inpcb),
135				   maxsockets, ZONE_INTERRUPT, 0);
136}
137
138/*
139 * Setup generic address and protocol structures
140 * for div_input routine, then pass them along with
141 * mbuf chain. ip->ip_len is assumed to have had
142 * the header length (hlen) subtracted out already.
143 * We tell whether the packet was incoming or outgoing
144 * by seeing if hlen == 0, which is a hack.
145 */
146void
147div_input(struct mbuf *m, int hlen)
148{
149	struct ip *ip;
150	struct inpcb *inp;
151	struct socket *sa;
152
153	/* Sanity check */
154	if (ip_divert_port == 0)
155		panic("div_input: port is 0");
156
157	/* Assure header */
158	if (m->m_len < sizeof(struct ip) &&
159	    (m = m_pullup(m, sizeof(struct ip))) == 0) {
160		return;
161	}
162	ip = mtod(m, struct ip *);
163
164	/* Record divert port */
165#ifdef IPFW_DIVERT_OLDRESTART
166	divsrc.sin_port = htons(ip_divert_port);
167#else
168	divsrc.sin_port = ip_divert_cookie;
169	ip_divert_cookie = 0;
170#endif /* IPFW_DIVERT_OLDRESTART */
171
172	/* Restore packet header fields */
173	ip->ip_len += hlen;
174	HTONS(ip->ip_len);
175	HTONS(ip->ip_off);
176
177	/* Record receive interface address, if any */
178	divsrc.sin_addr.s_addr = 0;
179	if (hlen) {
180		struct ifaddr *ifa;
181		char	name[32];
182
183#ifdef DIAGNOSTIC
184		/* Sanity check */
185		if (!(m->m_flags & M_PKTHDR))
186			panic("div_input: no pkt hdr");
187#endif
188
189		/* More fields affected by ip_input() */
190		HTONS(ip->ip_id);
191
192		/* Find IP address for receive interface */
193		for (ifa = m->m_pkthdr.rcvif->if_addrhead.tqh_first;
194		    ifa != NULL; ifa = ifa->ifa_link.tqe_next) {
195			if (ifa->ifa_addr == NULL)
196				continue;
197			if (ifa->ifa_addr->sa_family != AF_INET)
198				continue;
199			divsrc.sin_addr =
200			    ((struct sockaddr_in *) ifa->ifa_addr)->sin_addr;
201			break;
202		}
203		/*
204		 * Hide the actual interface name in there in the
205		 * sin_zero array. XXX This needs to be moved to a
206		 * different sockaddr type for divert, e.g.
207		 * sockaddr_div with multiple fields like
208		 * sockaddr_dl. Presently we have only 7 bytes
209		 * but that will do for now as most interfaces
210		 * are 4 or less + 2 or less bytes for unit.
211		 * There is probably a faster way of doing this,
212		 * possibly taking it from the sockaddr_dl on the iface.
213		 * This solves the problem of a P2P link and a LAN interface
214		 * having the same address, which can result in the wrong
215		 * interface being assigned to the packet when fed back
216		 * into the divert socket. Theoretically if the daemon saves
217		 * and re-uses the sockaddr_in as suggested in the man pages,
218		 * this iface name will come along for the ride.
219		 * (see div_output for the other half of this.)
220		 */
221		sprintf(name, "%s%d",
222			m->m_pkthdr.rcvif->if_name, m->m_pkthdr.rcvif->if_unit);
223		strncpy(divsrc.sin_zero, name, 7);
224	}
225
226	/* Put packet on socket queue, if any */
227	sa = NULL;
228	for (inp = divcb.lh_first; inp != NULL; inp = inp->inp_list.le_next) {
229		if (inp->inp_lport == htons(ip_divert_port))
230			sa = inp->inp_socket;
231	}
232	if (sa) {
233		if (sbappendaddr(&sa->so_rcv, (struct sockaddr *)&divsrc,
234				m, (struct mbuf *)0) == 0)
235			m_freem(m);
236		else
237			sorwakeup(sa);
238	} else {
239		m_freem(m);
240		ipstat.ips_noproto++;
241		ipstat.ips_delivered--;
242        }
243}
244
245/*
246 * Deliver packet back into the IP processing machinery.
247 *
248 * If no address specified, or address is 0.0.0.0, send to ip_output();
249 * otherwise, send to ip_input() and mark as having been received on
250 * the interface with that address.
251 *
252 * If no address specified, or dest port is 0, allow packet to divert
253 * back to this socket; otherwise, don't.
254 */
255static int
256div_output(so, m, addr, control)
257	struct socket *so;
258	register struct mbuf *m;
259	struct sockaddr *addr;
260	struct mbuf *control;
261{
262	register struct inpcb *const inp = sotoinpcb(so);
263	register struct ip *const ip = mtod(m, struct ip *);
264	struct sockaddr_in *sin = (struct sockaddr_in *)addr;
265	int error = 0;
266
267	if (control)
268		m_freem(control);		/* XXX */
269
270	/* Loopback avoidance */
271	if (sin) {
272#ifdef IPFW_DIVERT_OLDRESTART
273		ip_divert_cookie = ntohs(sin->sin_port);
274#else
275		ip_divert_cookie = sin->sin_port;
276#endif /* IPFW_DIVERT_OLDRESTART */
277	} else {
278		ip_divert_cookie = 0;
279	}
280
281	/* Reinject packet into the system as incoming or outgoing */
282	if (!sin || sin->sin_addr.s_addr == 0) {
283		/* Don't allow both user specified and setsockopt options,
284		   and don't allow packet length sizes that will crash */
285		if (((ip->ip_hl != (sizeof (*ip) >> 2)) && inp->inp_options) ||
286		     ((u_short)ntohs(ip->ip_len) > m->m_pkthdr.len)) {
287			error = EINVAL;
288			goto cantsend;
289		}
290
291		/* Convert fields to host order for ip_output() */
292		NTOHS(ip->ip_len);
293		NTOHS(ip->ip_off);
294
295		/* Send packet to output processing */
296		ipstat.ips_rawout++;			/* XXX */
297		error = ip_output(m, inp->inp_options, &inp->inp_route,
298			(so->so_options & SO_DONTROUTE) |
299			IP_ALLOWBROADCAST | IP_RAWOUTPUT, inp->inp_moptions);
300	} else {
301		struct	ifnet *ifp = NULL;
302		struct	ifaddr *ifa;
303		int	len = 0;
304		char	*c = sin->sin_zero;
305
306		sin->sin_port = 0;
307
308		/*
309		 * Find receive interface with the given name or IP address.
310		 * The name is user supplied data so don't trust it's size or
311		 * that it is zero terminated. The name has priority.
312		 * We are presently assuming that the sockaddr_in
313		 * has not been replaced by a sockaddr_div, so we limit it
314		 * to 16 bytes in total. the name is stuffed (if it exists)
315		 * in the sin_zero[] field.
316		 */
317		while (*c++ && (len++ < sizeof(sin->sin_zero)));
318		if ((len > 0) && (len < sizeof(sin->sin_zero)))
319			ifp = ifunit(sin->sin_zero);
320
321		/* If no luck with the name. check by IP address.  */
322		if (ifp) {
323			m->m_pkthdr.rcvif = ifp;
324		} else {
325			if (!(ifa = ifa_ifwithaddr((struct sockaddr *) sin))) {
326				error = EADDRNOTAVAIL;
327				goto cantsend;
328			}
329			m->m_pkthdr.rcvif = ifa->ifa_ifp;
330		}
331
332		/* Send packet to input processing */
333		ip_input(m);
334	}
335
336	/* Reset for next time (and other packets) */
337	ip_divert_cookie = 0;
338	return error;
339
340cantsend:
341	ip_divert_cookie = 0;
342	m_freem(m);
343	return error;
344}
345
346static int
347div_attach(struct socket *so, int proto, struct proc *p)
348{
349	struct inpcb *inp;
350	int error, s;
351
352	inp  = sotoinpcb(so);
353	if (inp)
354		panic("div_attach");
355	if (p && (error = suser(p->p_ucred, &p->p_acflag)) != 0)
356		return error;
357
358	s = splnet();
359	error = in_pcballoc(so, &divcbinfo, p);
360	splx(s);
361	if (error)
362		return error;
363	error = soreserve(so, div_sendspace, div_recvspace);
364	if (error)
365		return error;
366	inp = (struct inpcb *)so->so_pcb;
367	inp->inp_ip_p = proto;
368	inp->inp_flags |= INP_HDRINCL;
369	/* The socket is always "connected" because
370	   we always know "where" to send the packet */
371	so->so_state |= SS_ISCONNECTED;
372	return 0;
373}
374
375static int
376div_detach(struct socket *so)
377{
378	struct inpcb *inp;
379
380	inp = sotoinpcb(so);
381	if (inp == 0)
382		panic("div_detach");
383	in_pcbdetach(inp);
384	return 0;
385}
386
387static int
388div_abort(struct socket *so)
389{
390	soisdisconnected(so);
391	return div_detach(so);
392}
393
394static int
395div_disconnect(struct socket *so)
396{
397	if ((so->so_state & SS_ISCONNECTED) == 0)
398		return ENOTCONN;
399	return div_abort(so);
400}
401
402static int
403div_bind(struct socket *so, struct sockaddr *nam, struct proc *p)
404{
405	struct inpcb *inp;
406	int s;
407	int error;
408
409	s = splnet();
410	inp = sotoinpcb(so);
411	error = in_pcbbind(inp, nam, p);
412	splx(s);
413	return 0;
414}
415
416static int
417div_shutdown(struct socket *so)
418{
419	socantsendmore(so);
420	return 0;
421}
422
423static int
424div_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
425	 struct mbuf *control, struct proc *p)
426{
427	/* Packet must have a header (but that's about it) */
428	if (m->m_len < sizeof (struct ip) ||
429	    (m = m_pullup(m, sizeof (struct ip))) == 0) {
430		ipstat.ips_toosmall++;
431		m_freem(m);
432		return EINVAL;
433	}
434
435	/* Send packet */
436	return div_output(so, m, nam, control);
437}
438
439struct pr_usrreqs div_usrreqs = {
440	div_abort, pru_accept_notsupp, div_attach, div_bind,
441	pru_connect_notsupp, pru_connect2_notsupp, in_control, div_detach,
442	div_disconnect, pru_listen_notsupp, in_setpeeraddr, pru_rcvd_notsupp,
443	pru_rcvoob_notsupp, div_send, pru_sense_null, div_shutdown,
444	in_setsockaddr, sosend, soreceive, sopoll
445};
446