ip_output.c revision 112591
1296077Sadrian/*
2296077Sadrian * Copyright (c) 1982, 1986, 1988, 1990, 1993
3296077Sadrian *	The Regents of the University of California.  All rights reserved.
4296077Sadrian *
5296077Sadrian * Redistribution and use in source and binary forms, with or without
6296077Sadrian * modification, are permitted provided that the following conditions
7296077Sadrian * are met:
8296077Sadrian * 1. Redistributions of source code must retain the above copyright
9296077Sadrian *    notice, this list of conditions and the following disclaimer.
10296077Sadrian * 2. Redistributions in binary form must reproduce the above copyright
11296077Sadrian *    notice, this list of conditions and the following disclaimer in the
12296077Sadrian *    documentation and/or other materials provided with the distribution.
13296077Sadrian * 3. All advertising materials mentioning features or use of this software
14296077Sadrian *    must display the following acknowledgement:
15296077Sadrian *	This product includes software developed by the University of
16296077Sadrian *	California, Berkeley and its contributors.
17296077Sadrian * 4. Neither the name of the University nor the names of its contributors
18296077Sadrian *    may be used to endorse or promote products derived from this software
19296077Sadrian *    without specific prior written permission.
20296077Sadrian *
21296077Sadrian * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22296077Sadrian * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23296077Sadrian * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24296077Sadrian * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25296077Sadrian * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26296077Sadrian * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27296077Sadrian * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28296077Sadrian * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29296077Sadrian * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30296077Sadrian * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31296077Sadrian * SUCH DAMAGE.
32296077Sadrian *
33296077Sadrian *	@(#)ip_output.c	8.3 (Berkeley) 1/21/94
34296077Sadrian * $FreeBSD: head/sys/netinet/ip_output.c 112591 2003-03-25 05:45:05Z silby $
35296077Sadrian */
36296077Sadrian
37296077Sadrian#include "opt_ipfw.h"
38296077Sadrian#include "opt_ipdn.h"
39296077Sadrian#include "opt_ipdivert.h"
40296077Sadrian#include "opt_ipfilter.h"
41296077Sadrian#include "opt_ipsec.h"
42296077Sadrian#include "opt_mac.h"
43296077Sadrian#include "opt_pfil_hooks.h"
44296077Sadrian#include "opt_random_ip_id.h"
45296077Sadrian#include "opt_mbuf_frag_test.h"
46296077Sadrian
47296077Sadrian#include <sys/param.h>
48296077Sadrian#include <sys/systm.h>
49296077Sadrian#include <sys/kernel.h>
50296077Sadrian#include <sys/mac.h>
51296077Sadrian#include <sys/malloc.h>
52296077Sadrian#include <sys/mbuf.h>
53296077Sadrian#include <sys/protosw.h>
54296077Sadrian#include <sys/socket.h>
55296077Sadrian#include <sys/socketvar.h>
56296077Sadrian#include <sys/sysctl.h>
57296077Sadrian
58296077Sadrian#include <net/if.h>
59296077Sadrian#include <net/route.h>
60296077Sadrian
61296077Sadrian#include <netinet/in.h>
62296077Sadrian#include <netinet/in_systm.h>
63296077Sadrian#include <netinet/ip.h>
64296077Sadrian#include <netinet/in_pcb.h>
65296077Sadrian#include <netinet/in_var.h>
66296077Sadrian#include <netinet/ip_var.h>
67296077Sadrian
68296077Sadrian#include <machine/in_cksum.h>
69296077Sadrian
70296077Sadrianstatic MALLOC_DEFINE(M_IPMOPTS, "ip_moptions", "internet multicast options");
71296077Sadrian
72296077Sadrian#ifdef IPSEC
73296077Sadrian#include <netinet6/ipsec.h>
74296077Sadrian#include <netkey/key.h>
75296077Sadrian#ifdef IPSEC_DEBUG
76296077Sadrian#include <netkey/key_debug.h>
77296077Sadrian#else
78296077Sadrian#define	KEYDEBUG(lev,arg)
79296077Sadrian#endif
80296077Sadrian#endif /*IPSEC*/
81296077Sadrian
82296077Sadrian#ifdef FAST_IPSEC
83296077Sadrian#include <netipsec/ipsec.h>
84296077Sadrian#include <netipsec/xform.h>
85296077Sadrian#include <netipsec/key.h>
86296077Sadrian#endif /*FAST_IPSEC*/
87296077Sadrian
88296077Sadrian#include <netinet/ip_fw.h>
89296077Sadrian#include <netinet/ip_dummynet.h>
90296077Sadrian
91296077Sadrian#define print_ip(x, a, y)	 printf("%s %d.%d.%d.%d%s",\
92296077Sadrian				x, (ntohl(a.s_addr)>>24)&0xFF,\
93296077Sadrian				  (ntohl(a.s_addr)>>16)&0xFF,\
94296077Sadrian				  (ntohl(a.s_addr)>>8)&0xFF,\
95296077Sadrian				  (ntohl(a.s_addr))&0xFF, y);
96296077Sadrian
97296077Sadrianu_short ip_id;
98296077Sadrian
99296077Sadrian#ifdef MBUF_FRAG_TEST
100296077Sadrianint mbuf_frag_size = 0;
101296077SadrianSYSCTL_INT(_net_inet_ip, OID_AUTO, mbuf_frag_size, CTLFLAG_RW,
102296077Sadrian	&mbuf_frag_size, 0, "Fragment outgoing mbufs to this size");
103296077Sadrian#endif
104296077Sadrian
105296077Sadrianstatic struct mbuf *ip_insertoptions(struct mbuf *, struct mbuf *, int *);
106296077Sadrianstatic struct ifnet *ip_multicast_if(struct in_addr *, int *);
107296077Sadrianstatic void	ip_mloopback
108296077Sadrian	(struct ifnet *, struct mbuf *, struct sockaddr_in *, int);
109296077Sadrianstatic int	ip_getmoptions
110296077Sadrian	(struct sockopt *, struct ip_moptions *);
111296077Sadrianstatic int	ip_pcbopts(int, struct mbuf **, struct mbuf *);
112296077Sadrianstatic int	ip_setmoptions
113296077Sadrian	(struct sockopt *, struct ip_moptions **);
114296077Sadrian
115296077Sadrianint	ip_optcopy(struct ip *, struct ip *);
116296077Sadrian
117296077Sadrian
118296077Sadrianextern	struct protosw inetsw[];
119296077Sadrian
120296077Sadrian/*
121296077Sadrian * IP output.  The packet in mbuf chain m contains a skeletal IP
122296077Sadrian * header (with len, off, ttl, proto, tos, src, dst).
123296077Sadrian * The mbuf chain containing the packet will be freed.
124296077Sadrian * The mbuf opt, if present, will not be freed.
125296077Sadrian */
126296077Sadrianint
127296077Sadrianip_output(m0, opt, ro, flags, imo, inp)
128296077Sadrian	struct mbuf *m0;
129296077Sadrian	struct mbuf *opt;
130296077Sadrian	struct route *ro;
131296077Sadrian	int flags;
132296077Sadrian	struct ip_moptions *imo;
133296077Sadrian	struct inpcb *inp;
134296077Sadrian{
135296077Sadrian	struct ip *ip, *mhip;
136296077Sadrian	struct ifnet *ifp = NULL;	/* keep compiler happy */
137296077Sadrian	struct mbuf *m;
138296077Sadrian	int hlen = sizeof (struct ip);
139296077Sadrian	int len, off, error = 0;
140296077Sadrian	struct sockaddr_in *dst = NULL;	/* keep compiler happy */
141296077Sadrian	struct in_ifaddr *ia = NULL;
142296077Sadrian	int isbroadcast, sw_csum;
143296077Sadrian	struct in_addr pkt_dst;
144296077Sadrian#ifdef IPSEC
145296077Sadrian	struct route iproute;
146296077Sadrian	struct secpolicy *sp = NULL;
147296077Sadrian#endif
148296077Sadrian#ifdef FAST_IPSEC
149296077Sadrian	struct route iproute;
150296077Sadrian	struct m_tag *mtag;
151296077Sadrian	struct secpolicy *sp = NULL;
152296077Sadrian	struct tdb_ident *tdbi;
153296077Sadrian	int s;
154296077Sadrian#endif /* FAST_IPSEC */
155296077Sadrian	struct ip_fw_args args;
156296077Sadrian	int src_was_INADDR_ANY = 0;	/* as the name says... */
157296077Sadrian#ifdef PFIL_HOOKS
158296077Sadrian	struct packet_filter_hook *pfh;
159296077Sadrian	struct mbuf *m1;
160296077Sadrian	int rv;
161296077Sadrian#endif /* PFIL_HOOKS */
162296077Sadrian
163296077Sadrian	args.eh = NULL;
164296077Sadrian	args.rule = NULL;
165296077Sadrian	args.next_hop = NULL;
166296077Sadrian	args.divert_rule = 0;			/* divert cookie */
167296077Sadrian
168296077Sadrian	/* Grab info from MT_TAG mbufs prepended to the chain. */
169296077Sadrian	for (; m0 && m0->m_type == MT_TAG; m0 = m0->m_next) {
170296077Sadrian		switch(m0->_m_tag_id) {
171296077Sadrian		default:
172296077Sadrian			printf("ip_output: unrecognised MT_TAG tag %d\n",
173296077Sadrian			    m0->_m_tag_id);
174296077Sadrian			break;
175296077Sadrian
176296077Sadrian		case PACKET_TAG_DUMMYNET:
177296077Sadrian			/*
178296077Sadrian			 * the packet was already tagged, so part of the
179296077Sadrian			 * processing was already done, and we need to go down.
180296077Sadrian			 * Get parameters from the header.
181296077Sadrian			 */
182296077Sadrian			args.rule = ((struct dn_pkt *)m0)->rule;
183296077Sadrian			opt = NULL ;
184296077Sadrian			ro = & ( ((struct dn_pkt *)m0)->ro ) ;
185296077Sadrian			imo = NULL ;
186296077Sadrian			dst = ((struct dn_pkt *)m0)->dn_dst ;
187296077Sadrian			ifp = ((struct dn_pkt *)m0)->ifp ;
188296077Sadrian			flags = ((struct dn_pkt *)m0)->flags ;
189296077Sadrian			break;
190296077Sadrian
191296077Sadrian		case PACKET_TAG_DIVERT:
192296077Sadrian			args.divert_rule = (intptr_t)m0->m_data & 0xffff;
193296077Sadrian			break;
194296077Sadrian
195296077Sadrian		case PACKET_TAG_IPFORWARD:
196296077Sadrian			args.next_hop = (struct sockaddr_in *)m0->m_data;
197296077Sadrian			break;
198296077Sadrian		}
199296077Sadrian	}
200296077Sadrian	m = m0;
201296077Sadrian
202296077Sadrian	KASSERT(!m || (m->m_flags & M_PKTHDR) != 0, ("ip_output: no HDR"));
203296077Sadrian#ifndef FAST_IPSEC
204296077Sadrian	KASSERT(ro != NULL, ("ip_output: no route, proto %d",
205296077Sadrian	    mtod(m, struct ip *)->ip_p));
206296077Sadrian#endif
207296077Sadrian
208296077Sadrian	if (args.rule != NULL) {	/* dummynet already saw us */
209296077Sadrian		ip = mtod(m, struct ip *);
210296077Sadrian		hlen = ip->ip_hl << 2 ;
211296077Sadrian		if (ro->ro_rt)
212296077Sadrian			ia = ifatoia(ro->ro_rt->rt_ifa);
213296077Sadrian		goto sendit;
214296077Sadrian	}
215296077Sadrian
216296077Sadrian	if (opt) {
217296077Sadrian		len = 0;
218296077Sadrian		m = ip_insertoptions(m, opt, &len);
219296077Sadrian		if (len != 0)
220296077Sadrian			hlen = len;
221296077Sadrian	}
222296077Sadrian	ip = mtod(m, struct ip *);
223296077Sadrian	pkt_dst = args.next_hop ? args.next_hop->sin_addr : ip->ip_dst;
224296077Sadrian
225296077Sadrian	/*
226296077Sadrian	 * Fill in IP header.
227296077Sadrian	 */
228296077Sadrian	if ((flags & (IP_FORWARDING|IP_RAWOUTPUT)) == 0) {
229296077Sadrian		ip->ip_v = IPVERSION;
230296077Sadrian		ip->ip_hl = hlen >> 2;
231296077Sadrian		ip->ip_off &= IP_DF;
232296077Sadrian#ifdef RANDOM_IP_ID
233296077Sadrian		ip->ip_id = ip_randomid();
234296077Sadrian#else
235296077Sadrian		ip->ip_id = htons(ip_id++);
236296077Sadrian#endif
237296077Sadrian		ipstat.ips_localout++;
238296077Sadrian	} else {
239296077Sadrian		hlen = ip->ip_hl << 2;
240296077Sadrian	}
241296077Sadrian
242296077Sadrian#ifdef FAST_IPSEC
243296077Sadrian	if (ro == NULL) {
244296077Sadrian		ro = &iproute;
245296077Sadrian		bzero(ro, sizeof (*ro));
246296077Sadrian	}
247296077Sadrian#endif /* FAST_IPSEC */
248296077Sadrian	dst = (struct sockaddr_in *)&ro->ro_dst;
249296077Sadrian	/*
250296077Sadrian	 * If there is a cached route,
251296077Sadrian	 * check that it is to the same destination
252296077Sadrian	 * and is still up.  If not, free it and try again.
253296077Sadrian	 * The address family should also be checked in case of sharing the
254296077Sadrian	 * cache with IPv6.
255296077Sadrian	 */
256296077Sadrian	if (ro->ro_rt && ((ro->ro_rt->rt_flags & RTF_UP) == 0 ||
257296077Sadrian			  dst->sin_family != AF_INET ||
258296077Sadrian			  dst->sin_addr.s_addr != pkt_dst.s_addr)) {
259296077Sadrian		RTFREE(ro->ro_rt);
260296077Sadrian		ro->ro_rt = (struct rtentry *)0;
261296077Sadrian	}
262296077Sadrian	if (ro->ro_rt == 0) {
263296077Sadrian		bzero(dst, sizeof(*dst));
264296077Sadrian		dst->sin_family = AF_INET;
265296077Sadrian		dst->sin_len = sizeof(*dst);
266296077Sadrian		dst->sin_addr = pkt_dst;
267296077Sadrian	}
268296077Sadrian	/*
269296077Sadrian	 * If routing to interface only,
270296077Sadrian	 * short circuit routing lookup.
271296077Sadrian	 */
272296077Sadrian	if (flags & IP_ROUTETOIF) {
273296077Sadrian		if ((ia = ifatoia(ifa_ifwithdstaddr(sintosa(dst)))) == 0 &&
274296077Sadrian		    (ia = ifatoia(ifa_ifwithnet(sintosa(dst)))) == 0) {
275296077Sadrian			ipstat.ips_noroute++;
276296077Sadrian			error = ENETUNREACH;
277296077Sadrian			goto bad;
278296077Sadrian		}
279296077Sadrian		ifp = ia->ia_ifp;
280296077Sadrian		ip->ip_ttl = 1;
281296077Sadrian		isbroadcast = in_broadcast(dst->sin_addr, ifp);
282296077Sadrian	} else if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) &&
283296077Sadrian	    imo != NULL && imo->imo_multicast_ifp != NULL) {
284296077Sadrian		/*
285296077Sadrian		 * Bypass the normal routing lookup for multicast
286296077Sadrian		 * packets if the interface is specified.
287296077Sadrian		 */
288296077Sadrian		ifp = imo->imo_multicast_ifp;
289296077Sadrian		IFP_TO_IA(ifp, ia);
290296077Sadrian		isbroadcast = 0;	/* fool gcc */
291296077Sadrian	} else {
292296077Sadrian		/*
293296077Sadrian		 * If this is the case, we probably don't want to allocate
294296077Sadrian		 * a protocol-cloned route since we didn't get one from the
295296077Sadrian		 * ULP.  This lets TCP do its thing, while not burdening
296296077Sadrian		 * forwarding or ICMP with the overhead of cloning a route.
297296077Sadrian		 * Of course, we still want to do any cloning requested by
298296077Sadrian		 * the link layer, as this is probably required in all cases
299296077Sadrian		 * for correct operation (as it is for ARP).
300296077Sadrian		 */
301296077Sadrian		if (ro->ro_rt == 0)
302296077Sadrian			rtalloc_ign(ro, RTF_PRCLONING);
303296077Sadrian		if (ro->ro_rt == 0) {
304296077Sadrian			ipstat.ips_noroute++;
305296077Sadrian			error = EHOSTUNREACH;
306296077Sadrian			goto bad;
307296077Sadrian		}
308296077Sadrian		ia = ifatoia(ro->ro_rt->rt_ifa);
309296077Sadrian		ifp = ro->ro_rt->rt_ifp;
310296077Sadrian		ro->ro_rt->rt_use++;
311296077Sadrian		if (ro->ro_rt->rt_flags & RTF_GATEWAY)
312296077Sadrian			dst = (struct sockaddr_in *)ro->ro_rt->rt_gateway;
313296077Sadrian		if (ro->ro_rt->rt_flags & RTF_HOST)
314296077Sadrian			isbroadcast = (ro->ro_rt->rt_flags & RTF_BROADCAST);
315296077Sadrian		else
316296077Sadrian			isbroadcast = in_broadcast(dst->sin_addr, ifp);
317296077Sadrian	}
318296077Sadrian	if (IN_MULTICAST(ntohl(pkt_dst.s_addr))) {
319296077Sadrian		struct in_multi *inm;
320296077Sadrian
321296077Sadrian		m->m_flags |= M_MCAST;
322296077Sadrian		/*
323296077Sadrian		 * IP destination address is multicast.  Make sure "dst"
324296077Sadrian		 * still points to the address in "ro".  (It may have been
325296077Sadrian		 * changed to point to a gateway address, above.)
326296077Sadrian		 */
327296077Sadrian		dst = (struct sockaddr_in *)&ro->ro_dst;
328296077Sadrian		/*
329296077Sadrian		 * See if the caller provided any multicast options
330296077Sadrian		 */
331296077Sadrian		if (imo != NULL) {
332296077Sadrian			ip->ip_ttl = imo->imo_multicast_ttl;
333296077Sadrian			if (imo->imo_multicast_vif != -1)
334296077Sadrian				ip->ip_src.s_addr =
335296077Sadrian				    ip_mcast_src ?
336296077Sadrian				    ip_mcast_src(imo->imo_multicast_vif) :
337296077Sadrian				    INADDR_ANY;
338296077Sadrian		} else
339296077Sadrian			ip->ip_ttl = IP_DEFAULT_MULTICAST_TTL;
340296077Sadrian		/*
341296077Sadrian		 * Confirm that the outgoing interface supports multicast.
342296077Sadrian		 */
343296077Sadrian		if ((imo == NULL) || (imo->imo_multicast_vif == -1)) {
344296077Sadrian			if ((ifp->if_flags & IFF_MULTICAST) == 0) {
345296077Sadrian				ipstat.ips_noroute++;
346296077Sadrian				error = ENETUNREACH;
347296077Sadrian				goto bad;
348296077Sadrian			}
349296077Sadrian		}
350296077Sadrian		/*
351296077Sadrian		 * If source address not specified yet, use address
352296077Sadrian		 * of outgoing interface.
353296077Sadrian		 */
354296077Sadrian		if (ip->ip_src.s_addr == INADDR_ANY) {
355296077Sadrian			/* Interface may have no addresses. */
356296077Sadrian			if (ia != NULL)
357296077Sadrian				ip->ip_src = IA_SIN(ia)->sin_addr;
358296077Sadrian		}
359296077Sadrian
360296077Sadrian		if (ip_mrouter && (flags & IP_FORWARDING) == 0) {
361296077Sadrian			/*
362296077Sadrian			 * XXX
363296077Sadrian			 * delayed checksums are not currently
364296077Sadrian			 * compatible with IP multicast routing
365296077Sadrian			 */
366296077Sadrian			if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
367296077Sadrian				in_delayed_cksum(m);
368296077Sadrian				m->m_pkthdr.csum_flags &=
369296077Sadrian					~CSUM_DELAY_DATA;
370296077Sadrian			}
371296077Sadrian		}
372296077Sadrian		IN_LOOKUP_MULTI(pkt_dst, ifp, inm);
373296077Sadrian		if (inm != NULL &&
374296077Sadrian		   (imo == NULL || imo->imo_multicast_loop)) {
375296077Sadrian			/*
376296077Sadrian			 * If we belong to the destination multicast group
377296077Sadrian			 * on the outgoing interface, and the caller did not
378296077Sadrian			 * forbid loopback, loop back a copy.
379296077Sadrian			 */
380296077Sadrian			ip_mloopback(ifp, m, dst, hlen);
381296077Sadrian		}
382296077Sadrian		else {
383296077Sadrian			/*
384296077Sadrian			 * If we are acting as a multicast router, perform
385296077Sadrian			 * multicast forwarding as if the packet had just
386296077Sadrian			 * arrived on the interface to which we are about
387296077Sadrian			 * to send.  The multicast forwarding function
388296077Sadrian			 * recursively calls this function, using the
389296077Sadrian			 * IP_FORWARDING flag to prevent infinite recursion.
390296077Sadrian			 *
391296077Sadrian			 * Multicasts that are looped back by ip_mloopback(),
392296077Sadrian			 * above, will be forwarded by the ip_input() routine,
393296077Sadrian			 * if necessary.
394296077Sadrian			 */
395296077Sadrian			if (ip_mrouter && (flags & IP_FORWARDING) == 0) {
396296077Sadrian				/*
397296077Sadrian				 * If rsvp daemon is not running, do not
398296077Sadrian				 * set ip_moptions. This ensures that the packet
399296077Sadrian				 * is multicast and not just sent down one link
400296077Sadrian				 * as prescribed by rsvpd.
401296077Sadrian				 */
402296077Sadrian				if (!rsvp_on)
403296077Sadrian					imo = NULL;
404296077Sadrian				if (ip_mforward &&
405296077Sadrian				    ip_mforward(ip, ifp, m, imo) != 0) {
406296077Sadrian					m_freem(m);
407296077Sadrian					goto done;
408296077Sadrian				}
409296077Sadrian			}
410296077Sadrian		}
411296077Sadrian
412296077Sadrian		/*
413296077Sadrian		 * Multicasts with a time-to-live of zero may be looped-
414296077Sadrian		 * back, above, but must not be transmitted on a network.
415296077Sadrian		 * Also, multicasts addressed to the loopback interface
416296077Sadrian		 * are not sent -- the above call to ip_mloopback() will
417296077Sadrian		 * loop back a copy if this host actually belongs to the
418296077Sadrian		 * destination group on the loopback interface.
419296077Sadrian		 */
420296077Sadrian		if (ip->ip_ttl == 0 || ifp->if_flags & IFF_LOOPBACK) {
421296077Sadrian			m_freem(m);
422296077Sadrian			goto done;
423296077Sadrian		}
424296077Sadrian
425296077Sadrian		goto sendit;
426296077Sadrian	}
427296077Sadrian#ifndef notdef
428296077Sadrian	/*
429296077Sadrian	 * If the source address is not specified yet, use the address
430296077Sadrian	 * of the outoing interface. In case, keep note we did that, so
431296077Sadrian	 * if the the firewall changes the next-hop causing the output
432296077Sadrian	 * interface to change, we can fix that.
433296077Sadrian	 */
434296077Sadrian	if (ip->ip_src.s_addr == INADDR_ANY) {
435296077Sadrian		/* Interface may have no addresses. */
436296077Sadrian		if (ia != NULL) {
437296077Sadrian			ip->ip_src = IA_SIN(ia)->sin_addr;
438296077Sadrian			src_was_INADDR_ANY = 1;
439296077Sadrian		}
440296077Sadrian	}
441296077Sadrian#endif /* notdef */
442296077Sadrian	/*
443296077Sadrian	 * Verify that we have any chance at all of being able to queue
444296077Sadrian	 *      the packet or packet fragments
445296077Sadrian	 */
446296077Sadrian	if ((ifp->if_snd.ifq_len + ip->ip_len / ifp->if_mtu + 1) >=
447296077Sadrian		ifp->if_snd.ifq_maxlen) {
448296077Sadrian			error = ENOBUFS;
449296077Sadrian			ipstat.ips_odropped++;
450296077Sadrian			goto bad;
451296077Sadrian	}
452296077Sadrian
453296077Sadrian	/*
454296077Sadrian	 * Look for broadcast address and
455296077Sadrian	 * verify user is allowed to send
456296077Sadrian	 * such a packet.
457296077Sadrian	 */
458296077Sadrian	if (isbroadcast) {
459296077Sadrian		if ((ifp->if_flags & IFF_BROADCAST) == 0) {
460296077Sadrian			error = EADDRNOTAVAIL;
461296077Sadrian			goto bad;
462296077Sadrian		}
463296077Sadrian		if ((flags & IP_ALLOWBROADCAST) == 0) {
464296077Sadrian			error = EACCES;
465296077Sadrian			goto bad;
466296077Sadrian		}
467296077Sadrian		/* don't allow broadcast messages to be fragmented */
468296077Sadrian		if ((u_short)ip->ip_len > ifp->if_mtu) {
469296077Sadrian			error = EMSGSIZE;
470296077Sadrian			goto bad;
471296077Sadrian		}
472296077Sadrian		m->m_flags |= M_BCAST;
473296077Sadrian	} else {
474296077Sadrian		m->m_flags &= ~M_BCAST;
475296077Sadrian	}
476296077Sadrian
477296077Sadriansendit:
478296077Sadrian#ifdef IPSEC
479296077Sadrian	/* get SP for this packet */
480296077Sadrian	if (inp == NULL)
481296077Sadrian		sp = ipsec4_getpolicybyaddr(m, IPSEC_DIR_OUTBOUND, flags, &error);
482296077Sadrian	else
483296077Sadrian		sp = ipsec4_getpolicybypcb(m, IPSEC_DIR_OUTBOUND, inp, &error);
484296077Sadrian
485296077Sadrian	if (sp == NULL) {
486296077Sadrian		ipsecstat.out_inval++;
487296077Sadrian		goto bad;
488296077Sadrian	}
489296077Sadrian
490296077Sadrian	error = 0;
491296077Sadrian
492296077Sadrian	/* check policy */
493296077Sadrian	switch (sp->policy) {
494296077Sadrian	case IPSEC_POLICY_DISCARD:
495296077Sadrian		/*
496296077Sadrian		 * This packet is just discarded.
497296077Sadrian		 */
498296077Sadrian		ipsecstat.out_polvio++;
499296077Sadrian		goto bad;
500296077Sadrian
501296077Sadrian	case IPSEC_POLICY_BYPASS:
502296077Sadrian	case IPSEC_POLICY_NONE:
503296077Sadrian		/* no need to do IPsec. */
504296077Sadrian		goto skip_ipsec;
505296077Sadrian
506296077Sadrian	case IPSEC_POLICY_IPSEC:
507296077Sadrian		if (sp->req == NULL) {
508296077Sadrian			/* acquire a policy */
509296077Sadrian			error = key_spdacquire(sp);
510296077Sadrian			goto bad;
511296077Sadrian		}
512296077Sadrian		break;
513296077Sadrian
514296077Sadrian	case IPSEC_POLICY_ENTRUST:
515296077Sadrian	default:
516296077Sadrian		printf("ip_output: Invalid policy found. %d\n", sp->policy);
517296077Sadrian	}
518296077Sadrian    {
519296077Sadrian	struct ipsec_output_state state;
520296077Sadrian	bzero(&state, sizeof(state));
521296077Sadrian	state.m = m;
522296077Sadrian	if (flags & IP_ROUTETOIF) {
523296077Sadrian		state.ro = &iproute;
524296077Sadrian		bzero(&iproute, sizeof(iproute));
525296077Sadrian	} else
526296077Sadrian		state.ro = ro;
527296077Sadrian	state.dst = (struct sockaddr *)dst;
528296077Sadrian
529296077Sadrian	ip->ip_sum = 0;
530296077Sadrian
531296077Sadrian	/*
532296077Sadrian	 * XXX
533296077Sadrian	 * delayed checksums are not currently compatible with IPsec
534296077Sadrian	 */
535296077Sadrian	if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
536296077Sadrian		in_delayed_cksum(m);
537296077Sadrian		m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
538296077Sadrian	}
539296077Sadrian
540296077Sadrian	ip->ip_len = htons(ip->ip_len);
541296077Sadrian	ip->ip_off = htons(ip->ip_off);
542296077Sadrian
543296077Sadrian	error = ipsec4_output(&state, sp, flags);
544296077Sadrian
545296077Sadrian	m = state.m;
546296077Sadrian	if (flags & IP_ROUTETOIF) {
547296077Sadrian		/*
548296077Sadrian		 * if we have tunnel mode SA, we may need to ignore
549296077Sadrian		 * IP_ROUTETOIF.
550296077Sadrian		 */
551296077Sadrian		if (state.ro != &iproute || state.ro->ro_rt != NULL) {
552296077Sadrian			flags &= ~IP_ROUTETOIF;
553296077Sadrian			ro = state.ro;
554296077Sadrian		}
555296077Sadrian	} else
556296077Sadrian		ro = state.ro;
557296077Sadrian	dst = (struct sockaddr_in *)state.dst;
558296077Sadrian	if (error) {
559296077Sadrian		/* mbuf is already reclaimed in ipsec4_output. */
560296077Sadrian		m0 = NULL;
561296077Sadrian		switch (error) {
562296077Sadrian		case EHOSTUNREACH:
563296077Sadrian		case ENETUNREACH:
564296077Sadrian		case EMSGSIZE:
565296077Sadrian		case ENOBUFS:
566296077Sadrian		case ENOMEM:
567296077Sadrian			break;
568296077Sadrian		default:
569296077Sadrian			printf("ip4_output (ipsec): error code %d\n", error);
570297793Spfg			/*fall through*/
571296077Sadrian		case ENOENT:
572296077Sadrian			/* don't show these error codes to the user */
573296077Sadrian			error = 0;
574296077Sadrian			break;
575296077Sadrian		}
576296077Sadrian		goto bad;
577296077Sadrian	}
578296077Sadrian    }
579296077Sadrian
580296077Sadrian	/* be sure to update variables that are affected by ipsec4_output() */
581296077Sadrian	ip = mtod(m, struct ip *);
582296077Sadrian	hlen = ip->ip_hl << 2;
583296077Sadrian	if (ro->ro_rt == NULL) {
584296077Sadrian		if ((flags & IP_ROUTETOIF) == 0) {
585296077Sadrian			printf("ip_output: "
586296077Sadrian				"can't update route after IPsec processing\n");
587296077Sadrian			error = EHOSTUNREACH;	/*XXX*/
588296077Sadrian			goto bad;
589296077Sadrian		}
590296077Sadrian	} else {
591296077Sadrian		ia = ifatoia(ro->ro_rt->rt_ifa);
592296077Sadrian		ifp = ro->ro_rt->rt_ifp;
593296077Sadrian	}
594296077Sadrian
595296077Sadrian	/* make it flipped, again. */
596296077Sadrian	ip->ip_len = ntohs(ip->ip_len);
597296077Sadrian	ip->ip_off = ntohs(ip->ip_off);
598296077Sadrianskip_ipsec:
599296077Sadrian#endif /*IPSEC*/
600296077Sadrian#ifdef FAST_IPSEC
601296077Sadrian	/*
602296077Sadrian	 * Check the security policy (SP) for the packet and, if
603296077Sadrian	 * required, do IPsec-related processing.  There are two
604296077Sadrian	 * cases here; the first time a packet is sent through
605296077Sadrian	 * it will be untagged and handled by ipsec4_checkpolicy.
606296077Sadrian	 * If the packet is resubmitted to ip_output (e.g. after
607296077Sadrian	 * AH, ESP, etc. processing), there will be a tag to bypass
608296077Sadrian	 * the lookup and related policy checking.
609296077Sadrian	 */
610296077Sadrian	mtag = m_tag_find(m, PACKET_TAG_IPSEC_PENDING_TDB, NULL);
611296077Sadrian	s = splnet();
612296077Sadrian	if (mtag != NULL) {
613296077Sadrian		tdbi = (struct tdb_ident *)(mtag + 1);
614296077Sadrian		sp = ipsec_getpolicy(tdbi, IPSEC_DIR_OUTBOUND);
615296077Sadrian		if (sp == NULL)
616296077Sadrian			error = -EINVAL;	/* force silent drop */
617296077Sadrian		m_tag_delete(m, mtag);
618296077Sadrian	} else {
619296077Sadrian		sp = ipsec4_checkpolicy(m, IPSEC_DIR_OUTBOUND, flags,
620296077Sadrian					&error, inp);
621296077Sadrian	}
622296077Sadrian	/*
623296077Sadrian	 * There are four return cases:
624296077Sadrian	 *    sp != NULL	 	    apply IPsec policy
625296077Sadrian	 *    sp == NULL, error == 0	    no IPsec handling needed
626296077Sadrian	 *    sp == NULL, error == -EINVAL  discard packet w/o error
627296077Sadrian	 *    sp == NULL, error != 0	    discard packet, report error
628297793Spfg	 */
629296077Sadrian	if (sp != NULL) {
630296077Sadrian		/* Loop detection, check if ipsec processing already done */
631296077Sadrian		KASSERT(sp->req != NULL, ("ip_output: no ipsec request"));
632296077Sadrian		for (mtag = m_tag_first(m); mtag != NULL;
633296077Sadrian		     mtag = m_tag_next(m, mtag)) {
634296077Sadrian			if (mtag->m_tag_cookie != MTAG_ABI_COMPAT)
635296077Sadrian				continue;
636296077Sadrian			if (mtag->m_tag_id != PACKET_TAG_IPSEC_OUT_DONE &&
637296077Sadrian			    mtag->m_tag_id != PACKET_TAG_IPSEC_OUT_CRYPTO_NEEDED)
638296077Sadrian				continue;
639296077Sadrian			/*
640296077Sadrian			 * Check if policy has an SA associated with it.
641296077Sadrian			 * This can happen when an SP has yet to acquire
642296077Sadrian			 * an SA; e.g. on first reference.  If it occurs,
643296077Sadrian			 * then we let ipsec4_process_packet do its thing.
644296077Sadrian			 */
645296077Sadrian			if (sp->req->sav == NULL)
646296077Sadrian				break;
647296077Sadrian			tdbi = (struct tdb_ident *)(mtag + 1);
648296077Sadrian			if (tdbi->spi == sp->req->sav->spi &&
649296077Sadrian			    tdbi->proto == sp->req->sav->sah->saidx.proto &&
650296077Sadrian			    bcmp(&tdbi->dst, &sp->req->sav->sah->saidx.dst,
651296077Sadrian				 sizeof (union sockaddr_union)) == 0) {
652296077Sadrian				/*
653296077Sadrian				 * No IPsec processing is needed, free
654296077Sadrian				 * reference to SP.
655296077Sadrian				 *
656296077Sadrian				 * NB: null pointer to avoid free at
657296077Sadrian				 *     done: below.
658296077Sadrian				 */
659296077Sadrian				KEY_FREESP(&sp), sp = NULL;
660296077Sadrian				splx(s);
661296077Sadrian				goto spd_done;
662296077Sadrian			}
663296077Sadrian		}
664296077Sadrian
665296077Sadrian		/*
666296077Sadrian		 * Do delayed checksums now because we send before
667296077Sadrian		 * this is done in the normal processing path.
668296077Sadrian		 */
669296077Sadrian		if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
670296077Sadrian			in_delayed_cksum(m);
671296077Sadrian			m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
672296077Sadrian		}
673296077Sadrian
674296077Sadrian		ip->ip_len = htons(ip->ip_len);
675296077Sadrian		ip->ip_off = htons(ip->ip_off);
676296077Sadrian
677296077Sadrian		/* NB: callee frees mbuf */
678296077Sadrian		error = ipsec4_process_packet(m, sp->req, flags, 0);
679296077Sadrian		/*
680296077Sadrian		 * Preserve KAME behaviour: ENOENT can be returned
681296077Sadrian		 * when an SA acquire is in progress.  Don't propagate
682296077Sadrian		 * this to user-level; it confuses applications.
683296077Sadrian		 *
684296077Sadrian		 * XXX this will go away when the SADB is redone.
685296077Sadrian		 */
686296077Sadrian		if (error == ENOENT)
687296077Sadrian			error = 0;
688296077Sadrian		splx(s);
689296077Sadrian		goto done;
690296077Sadrian	} else {
691296077Sadrian		splx(s);
692296077Sadrian
693296077Sadrian		if (error != 0) {
694296077Sadrian			/*
695296077Sadrian			 * Hack: -EINVAL is used to signal that a packet
696296077Sadrian			 * should be silently discarded.  This is typically
697296077Sadrian			 * because we asked key management for an SA and
698296077Sadrian			 * it was delayed (e.g. kicked up to IKE).
699296077Sadrian			 */
700296077Sadrian			if (error == -EINVAL)
701296077Sadrian				error = 0;
702296077Sadrian			goto bad;
703296077Sadrian		} else {
704296077Sadrian			/* No IPsec processing for this packet. */
705296077Sadrian		}
706296077Sadrian#ifdef notyet
707296077Sadrian		/*
708296077Sadrian		 * If deferred crypto processing is needed, check that
709296077Sadrian		 * the interface supports it.
710296077Sadrian		 */
711296077Sadrian		mtag = m_tag_find(m, PACKET_TAG_IPSEC_OUT_CRYPTO_NEEDED, NULL);
712296077Sadrian		if (mtag != NULL && (ifp->if_capenable & IFCAP_IPSEC) == 0) {
713296077Sadrian			/* notify IPsec to do its own crypto */
714296077Sadrian			ipsp_skipcrypto_unmark((struct tdb_ident *)(mtag + 1));
715296077Sadrian			error = EHOSTUNREACH;
716296077Sadrian			goto bad;
717296077Sadrian		}
718296077Sadrian#endif
719296077Sadrian	}
720296077Sadrianspd_done:
721296077Sadrian#endif /* FAST_IPSEC */
722296077Sadrian
723296077Sadrian	/*
724296077Sadrian	 * IpHack's section.
725296077Sadrian	 * - Xlate: translate packet's addr/port (NAT).
726296077Sadrian	 * - Firewall: deny/allow/etc.
727296077Sadrian	 * - Wrap: fake packet's addr/port <unimpl.>
728296077Sadrian	 * - Encapsulate: put it in another IP and send out. <unimp.>
729296077Sadrian	 */
730296077Sadrian#ifdef PFIL_HOOKS
731296077Sadrian	/*
732296077Sadrian	 * Run through list of hooks for output packets.
733296077Sadrian	 */
734296077Sadrian	m1 = m;
735296077Sadrian	pfh = pfil_hook_get(PFIL_OUT, &inetsw[ip_protox[IPPROTO_IP]].pr_pfh);
736296077Sadrian	for (; pfh; pfh = TAILQ_NEXT(pfh, pfil_link))
737296077Sadrian		if (pfh->pfil_func) {
738296077Sadrian			rv = pfh->pfil_func(ip, hlen, ifp, 1, &m1);
739296077Sadrian			if (rv) {
740296077Sadrian				error = EHOSTUNREACH;
741296077Sadrian				goto done;
742296077Sadrian			}
743296077Sadrian			m = m1;
744296077Sadrian			if (m == NULL)
745296077Sadrian				goto done;
746296077Sadrian			ip = mtod(m, struct ip *);
747296077Sadrian		}
748296077Sadrian#endif /* PFIL_HOOKS */
749296077Sadrian
750296077Sadrian	/*
751296077Sadrian	 * Check with the firewall...
752296077Sadrian	 * but not if we are already being fwd'd from a firewall.
753296077Sadrian	 */
754296077Sadrian	if (fw_enable && IPFW_LOADED && !args.next_hop) {
755296077Sadrian		struct sockaddr_in *old = dst;
756296077Sadrian
757296077Sadrian		args.m = m;
758296077Sadrian		args.next_hop = dst;
759296077Sadrian		args.oif = ifp;
760296077Sadrian		off = ip_fw_chk_ptr(&args);
761296077Sadrian		m = args.m;
762296077Sadrian		dst = args.next_hop;
763296077Sadrian
764296077Sadrian                /*
765296077Sadrian		 * On return we must do the following:
766296077Sadrian		 * m == NULL	-> drop the pkt (old interface, deprecated)
767296077Sadrian		 * (off & IP_FW_PORT_DENY_FLAG)	-> drop the pkt (new interface)
768296077Sadrian		 * 1<=off<= 0xffff		-> DIVERT
769296077Sadrian		 * (off & IP_FW_PORT_DYNT_FLAG)	-> send to a DUMMYNET pipe
770296077Sadrian		 * (off & IP_FW_PORT_TEE_FLAG)	-> TEE the packet
771296077Sadrian		 * dst != old			-> IPFIREWALL_FORWARD
772296077Sadrian		 * off==0, dst==old		-> accept
773296077Sadrian		 * If some of the above modules are not compiled in, then
774296077Sadrian		 * we should't have to check the corresponding condition
775296077Sadrian		 * (because the ipfw control socket should not accept
776296077Sadrian		 * unsupported rules), but better play safe and drop
777296077Sadrian		 * packets in case of doubt.
778296077Sadrian		 */
779296077Sadrian		if ( (off & IP_FW_PORT_DENY_FLAG) || m == NULL) {
780296077Sadrian			if (m)
781296077Sadrian				m_freem(m);
782296077Sadrian			error = EACCES;
783296077Sadrian			goto done;
784296077Sadrian		}
785296077Sadrian		ip = mtod(m, struct ip *);
786296077Sadrian		if (off == 0 && dst == old)		/* common case */
787296077Sadrian			goto pass;
788296077Sadrian                if (DUMMYNET_LOADED && (off & IP_FW_PORT_DYNT_FLAG) != 0) {
789296077Sadrian			/*
790296077Sadrian			 * pass the pkt to dummynet. Need to include
791296077Sadrian			 * pipe number, m, ifp, ro, dst because these are
792296077Sadrian			 * not recomputed in the next pass.
793296077Sadrian			 * All other parameters have been already used and
794296077Sadrian			 * so they are not needed anymore.
795296077Sadrian			 * XXX note: if the ifp or ro entry are deleted
796296077Sadrian			 * while a pkt is in dummynet, we are in trouble!
797296077Sadrian			 */
798296077Sadrian			args.ro = ro;
799296077Sadrian			args.dst = dst;
800296077Sadrian			args.flags = flags;
801296077Sadrian
802296077Sadrian			error = ip_dn_io_ptr(m, off & 0xffff, DN_TO_IP_OUT,
803296077Sadrian				&args);
804296077Sadrian			goto done;
805296077Sadrian		}
806296077Sadrian#ifdef IPDIVERT
807296077Sadrian		if (off != 0 && (off & IP_FW_PORT_DYNT_FLAG) == 0) {
808296077Sadrian			struct mbuf *clone = NULL;
809296077Sadrian
810296077Sadrian			/* Clone packet if we're doing a 'tee' */
811296077Sadrian			if ((off & IP_FW_PORT_TEE_FLAG) != 0)
812296077Sadrian				clone = m_dup(m, M_DONTWAIT);
813296077Sadrian
814296077Sadrian			/*
815296077Sadrian			 * XXX
816296077Sadrian			 * delayed checksums are not currently compatible
817296077Sadrian			 * with divert sockets.
818296077Sadrian			 */
819296077Sadrian			if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
820296077Sadrian				in_delayed_cksum(m);
821296077Sadrian				m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
822296077Sadrian			}
823296077Sadrian
824296077Sadrian			/* Restore packet header fields to original values */
825296077Sadrian			ip->ip_len = htons(ip->ip_len);
826296077Sadrian			ip->ip_off = htons(ip->ip_off);
827296077Sadrian
828296077Sadrian			/* Deliver packet to divert input routine */
829296077Sadrian			divert_packet(m, 0, off & 0xffff, args.divert_rule);
830296077Sadrian
831296077Sadrian			/* If 'tee', continue with original packet */
832296077Sadrian			if (clone != NULL) {
833296077Sadrian				m = clone;
834296077Sadrian				ip = mtod(m, struct ip *);
835296077Sadrian				goto pass;
836296077Sadrian			}
837296077Sadrian			goto done;
838296077Sadrian		}
839296077Sadrian#endif
840296077Sadrian
841296077Sadrian		/* IPFIREWALL_FORWARD */
842296077Sadrian		/*
843296077Sadrian		 * Check dst to make sure it is directly reachable on the
844296077Sadrian		 * interface we previously thought it was.
845296077Sadrian		 * If it isn't (which may be likely in some situations) we have
846296077Sadrian		 * to re-route it (ie, find a route for the next-hop and the
847296077Sadrian		 * associated interface) and set them here. This is nested
848296077Sadrian		 * forwarding which in most cases is undesirable, except where
849296077Sadrian		 * such control is nigh impossible. So we do it here.
850296077Sadrian		 * And I'm babbling.
851296077Sadrian		 */
852296077Sadrian		if (off == 0 && old != dst) { /* FORWARD, dst has changed */
853296077Sadrian#if 0
854296077Sadrian			/*
855296077Sadrian			 * XXX To improve readability, this block should be
856296077Sadrian			 * changed into a function call as below:
857296077Sadrian			 */
858296077Sadrian			error = ip_ipforward(&m, &dst, &ifp);
859296077Sadrian			if (error)
860296077Sadrian				goto bad;
861296077Sadrian			if (m == NULL) /* ip_input consumed the mbuf */
862296077Sadrian				goto done;
863296077Sadrian#else
864296077Sadrian			struct in_ifaddr *ia;
865296077Sadrian
866296077Sadrian			/*
867296077Sadrian			 * XXX sro_fwd below is static, and a pointer
868296077Sadrian			 * to it gets passed to routines downstream.
869296077Sadrian			 * This could have surprisingly bad results in
870296077Sadrian			 * practice, because its content is overwritten
871296077Sadrian			 * by subsequent packets.
872296077Sadrian			 */
873296077Sadrian			/* There must be a better way to do this next line... */
874296077Sadrian			static struct route sro_fwd;
875296077Sadrian			struct route *ro_fwd = &sro_fwd;
876296077Sadrian
877296077Sadrian#if 0
878296077Sadrian			print_ip("IPFIREWALL_FORWARD: New dst ip: ",
879296077Sadrian			    dst->sin_addr, "\n");
880296077Sadrian#endif
881299314Sadrian
882299314Sadrian			/*
883299314Sadrian			 * We need to figure out if we have been forwarded
884299314Sadrian			 * to a local socket. If so, then we should somehow
885299314Sadrian			 * "loop back" to ip_input, and get directed to the
886299314Sadrian			 * PCB as if we had received this packet. This is
887299314Sadrian			 * because it may be dificult to identify the packets
888299314Sadrian			 * you want to forward until they are being output
889299314Sadrian			 * and have selected an interface. (e.g. locally
890299314Sadrian			 * initiated packets) If we used the loopback inteface,
891299314Sadrian			 * we would not be able to control what happens
892299314Sadrian			 * as the packet runs through ip_input() as
893299314Sadrian			 * it is done through an ISR.
894299314Sadrian			 */
895299314Sadrian			LIST_FOREACH(ia,
896299314Sadrian			    INADDR_HASH(dst->sin_addr.s_addr), ia_hash) {
897299314Sadrian				/*
898299314Sadrian				 * If the addr to forward to is one
899299314Sadrian				 * of ours, we pretend to
900299314Sadrian				 * be the destination for this packet.
901296077Sadrian				 */
902296077Sadrian				if (IA_SIN(ia)->sin_addr.s_addr ==
903296077Sadrian						 dst->sin_addr.s_addr)
904296077Sadrian					break;
905296077Sadrian			}
906296077Sadrian			if (ia) {	/* tell ip_input "dont filter" */
907296077Sadrian				struct m_hdr tag;
908296077Sadrian
909296077Sadrian				tag.mh_type = MT_TAG;
910296077Sadrian				tag.mh_flags = PACKET_TAG_IPFORWARD;
911296077Sadrian				tag.mh_data = (caddr_t)args.next_hop;
912296077Sadrian				tag.mh_next = m;
913296077Sadrian
914296077Sadrian				if (m->m_pkthdr.rcvif == NULL)
915296077Sadrian					m->m_pkthdr.rcvif = ifunit("lo0");
916296077Sadrian				if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
917					m->m_pkthdr.csum_flags |=
918					    CSUM_DATA_VALID | CSUM_PSEUDO_HDR;
919					m0->m_pkthdr.csum_data = 0xffff;
920				}
921				m->m_pkthdr.csum_flags |=
922				    CSUM_IP_CHECKED | CSUM_IP_VALID;
923				ip->ip_len = htons(ip->ip_len);
924				ip->ip_off = htons(ip->ip_off);
925				ip_input((struct mbuf *)&tag);
926				goto done;
927			}
928			/* Some of the logic for this was
929			 * nicked from above.
930			 *
931			 * This rewrites the cached route in a local PCB.
932			 * Is this what we want to do?
933			 */
934			bcopy(dst, &ro_fwd->ro_dst, sizeof(*dst));
935
936			ro_fwd->ro_rt = 0;
937			rtalloc_ign(ro_fwd, RTF_PRCLONING);
938
939			if (ro_fwd->ro_rt == 0) {
940				ipstat.ips_noroute++;
941				error = EHOSTUNREACH;
942				goto bad;
943			}
944
945			ia = ifatoia(ro_fwd->ro_rt->rt_ifa);
946			ifp = ro_fwd->ro_rt->rt_ifp;
947			ro_fwd->ro_rt->rt_use++;
948			if (ro_fwd->ro_rt->rt_flags & RTF_GATEWAY)
949				dst = (struct sockaddr_in *)
950					ro_fwd->ro_rt->rt_gateway;
951			if (ro_fwd->ro_rt->rt_flags & RTF_HOST)
952				isbroadcast =
953				    (ro_fwd->ro_rt->rt_flags & RTF_BROADCAST);
954			else
955				isbroadcast = in_broadcast(dst->sin_addr, ifp);
956			if (ro->ro_rt)
957				RTFREE(ro->ro_rt);
958			ro->ro_rt = ro_fwd->ro_rt;
959			dst = (struct sockaddr_in *)&ro_fwd->ro_dst;
960
961#endif	/* ... block to be put into a function */
962			/*
963			 * If we added a default src ip earlier,
964			 * which would have been gotten from the-then
965			 * interface, do it again, from the new one.
966			 */
967			if (src_was_INADDR_ANY)
968				ip->ip_src = IA_SIN(ia)->sin_addr;
969			goto pass ;
970		}
971
972                /*
973                 * if we get here, none of the above matches, and
974                 * we have to drop the pkt
975                 */
976		m_freem(m);
977                error = EACCES; /* not sure this is the right error msg */
978                goto done;
979	}
980
981pass:
982	/* 127/8 must not appear on wire - RFC1122. */
983	if ((ntohl(ip->ip_dst.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET ||
984	    (ntohl(ip->ip_src.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET) {
985		if ((ifp->if_flags & IFF_LOOPBACK) == 0) {
986			ipstat.ips_badaddr++;
987			error = EADDRNOTAVAIL;
988			goto bad;
989		}
990	}
991
992	m->m_pkthdr.csum_flags |= CSUM_IP;
993	sw_csum = m->m_pkthdr.csum_flags & ~ifp->if_hwassist;
994	if (sw_csum & CSUM_DELAY_DATA) {
995		in_delayed_cksum(m);
996		sw_csum &= ~CSUM_DELAY_DATA;
997	}
998	m->m_pkthdr.csum_flags &= ifp->if_hwassist;
999
1000	/*
1001	 * If small enough for interface, or the interface will take
1002	 * care of the fragmentation for us, can just send directly.
1003	 */
1004	if ((u_short)ip->ip_len <= ifp->if_mtu ||
1005	    ifp->if_hwassist & CSUM_FRAGMENT) {
1006		ip->ip_len = htons(ip->ip_len);
1007		ip->ip_off = htons(ip->ip_off);
1008		ip->ip_sum = 0;
1009		if (sw_csum & CSUM_DELAY_IP)
1010			ip->ip_sum = in_cksum(m, hlen);
1011
1012		/* Record statistics for this interface address. */
1013		if (!(flags & IP_FORWARDING) && ia) {
1014			ia->ia_ifa.if_opackets++;
1015			ia->ia_ifa.if_obytes += m->m_pkthdr.len;
1016		}
1017
1018#ifdef IPSEC
1019		/* clean ipsec history once it goes out of the node */
1020		ipsec_delaux(m);
1021#endif
1022
1023#ifdef MBUF_FRAG_TEST
1024		if (mbuf_frag_size) {
1025			struct mbuf *m1, *m2;
1026			int length;
1027
1028			length = m->m_len;
1029
1030			while (1) {
1031				length -= mbuf_frag_size;
1032					if (length < 1)
1033						break;
1034				m1 = m_split(m, length, M_DONTWAIT);
1035				m2 = m;
1036				while (1) {
1037					if (m2->m_next == NULL)
1038						break;
1039					m2 = m2->m_next;
1040				}
1041			m2->m_next = m1;
1042			}
1043		}
1044#endif
1045		error = (*ifp->if_output)(ifp, m,
1046				(struct sockaddr *)dst, ro->ro_rt);
1047		goto done;
1048	}
1049	/*
1050	 * Too large for interface; fragment if possible.
1051	 * Must be able to put at least 8 bytes per fragment.
1052	 */
1053	if (ip->ip_off & IP_DF) {
1054		error = EMSGSIZE;
1055		/*
1056		 * This case can happen if the user changed the MTU
1057		 * of an interface after enabling IP on it.  Because
1058		 * most netifs don't keep track of routes pointing to
1059		 * them, there is no way for one to update all its
1060		 * routes when the MTU is changed.
1061		 */
1062		if ((ro->ro_rt->rt_flags & (RTF_UP | RTF_HOST))
1063		    && !(ro->ro_rt->rt_rmx.rmx_locks & RTV_MTU)
1064		    && (ro->ro_rt->rt_rmx.rmx_mtu > ifp->if_mtu)) {
1065			ro->ro_rt->rt_rmx.rmx_mtu = ifp->if_mtu;
1066		}
1067		ipstat.ips_cantfrag++;
1068		goto bad;
1069	}
1070	len = (ifp->if_mtu - hlen) &~ 7;
1071	if (len < 8) {
1072		error = EMSGSIZE;
1073		goto bad;
1074	}
1075
1076	/*
1077	 * if the interface will not calculate checksums on
1078	 * fragmented packets, then do it here.
1079	 */
1080	if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA &&
1081	    (ifp->if_hwassist & CSUM_IP_FRAGS) == 0) {
1082		in_delayed_cksum(m);
1083		m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
1084	}
1085
1086	if (len > PAGE_SIZE) {
1087		/*
1088		 * Fragement large datagrams such that each segment
1089		 * contains a multiple of PAGE_SIZE amount of data,
1090		 * plus headers. This enables a receiver to perform
1091		 * page-flipping zero-copy optimizations.
1092		 */
1093
1094		int newlen;
1095		struct mbuf *mtmp;
1096
1097		for (mtmp = m, off = 0;
1098		     mtmp && ((off + mtmp->m_len) <= ifp->if_mtu);
1099		     mtmp = mtmp->m_next) {
1100			off += mtmp->m_len;
1101		}
1102		/*
1103		 * firstlen (off - hlen) must be aligned on an
1104		 * 8-byte boundary
1105		 */
1106		if (off < hlen)
1107			goto smart_frag_failure;
1108		off = ((off - hlen) & ~7) + hlen;
1109		newlen = (~PAGE_MASK) & ifp->if_mtu;
1110		if ((newlen + sizeof (struct ip)) > ifp->if_mtu) {
1111			/* we failed, go back the default */
1112smart_frag_failure:
1113			newlen = len;
1114			off = hlen + len;
1115		}
1116
1117/*		printf("ipfrag: len = %d, hlen = %d, mhlen = %d, newlen = %d, off = %d\n",
1118		len, hlen, sizeof (struct ip), newlen, off);*/
1119
1120		len = newlen;
1121
1122	} else {
1123		off = hlen + len;
1124	}
1125
1126
1127
1128    {
1129	int mhlen, firstlen = off - hlen;
1130	struct mbuf **mnext = &m->m_nextpkt;
1131	int nfrags = 1;
1132
1133	/*
1134	 * Loop through length of segment after first fragment,
1135	 * make new header and copy data of each part and link onto chain.
1136	 */
1137	m0 = m;
1138	mhlen = sizeof (struct ip);
1139	for (; off < (u_short)ip->ip_len; off += len) {
1140		MGETHDR(m, M_DONTWAIT, MT_HEADER);
1141		if (m == 0) {
1142			error = ENOBUFS;
1143			ipstat.ips_odropped++;
1144			goto sendorfree;
1145		}
1146		m->m_flags |= (m0->m_flags & M_MCAST) | M_FRAG;
1147		m->m_data += max_linkhdr;
1148		mhip = mtod(m, struct ip *);
1149		*mhip = *ip;
1150		if (hlen > sizeof (struct ip)) {
1151			mhlen = ip_optcopy(ip, mhip) + sizeof (struct ip);
1152			mhip->ip_v = IPVERSION;
1153			mhip->ip_hl = mhlen >> 2;
1154		}
1155		m->m_len = mhlen;
1156		mhip->ip_off = ((off - hlen) >> 3) + ip->ip_off;
1157		if (off + len >= (u_short)ip->ip_len)
1158			len = (u_short)ip->ip_len - off;
1159		else
1160			mhip->ip_off |= IP_MF;
1161		mhip->ip_len = htons((u_short)(len + mhlen));
1162		m->m_next = m_copy(m0, off, len);
1163		if (m->m_next == 0) {
1164			(void) m_free(m);
1165			error = ENOBUFS;	/* ??? */
1166			ipstat.ips_odropped++;
1167			goto sendorfree;
1168		}
1169		m->m_pkthdr.len = mhlen + len;
1170		m->m_pkthdr.rcvif = (struct ifnet *)0;
1171#ifdef MAC
1172		mac_create_fragment(m0, m);
1173#endif
1174		m->m_pkthdr.csum_flags = m0->m_pkthdr.csum_flags;
1175		mhip->ip_off = htons(mhip->ip_off);
1176		mhip->ip_sum = 0;
1177		if (sw_csum & CSUM_DELAY_IP)
1178			mhip->ip_sum = in_cksum(m, mhlen);
1179		*mnext = m;
1180		mnext = &m->m_nextpkt;
1181		nfrags++;
1182	}
1183	ipstat.ips_ofragments += nfrags;
1184
1185	/* set first/last markers for fragment chain */
1186	m->m_flags |= M_LASTFRAG;
1187	m0->m_flags |= M_FIRSTFRAG | M_FRAG;
1188	m0->m_pkthdr.csum_data = nfrags;
1189
1190	/*
1191	 * Update first fragment by trimming what's been copied out
1192	 * and updating header, then send each fragment (in order).
1193	 */
1194	m = m0;
1195	m_adj(m, hlen + firstlen - (u_short)ip->ip_len);
1196	m->m_pkthdr.len = hlen + firstlen;
1197	ip->ip_len = htons((u_short)m->m_pkthdr.len);
1198	ip->ip_off |= IP_MF;
1199	ip->ip_off = htons(ip->ip_off);
1200	ip->ip_sum = 0;
1201	if (sw_csum & CSUM_DELAY_IP)
1202		ip->ip_sum = in_cksum(m, hlen);
1203sendorfree:
1204	for (m = m0; m; m = m0) {
1205		m0 = m->m_nextpkt;
1206		m->m_nextpkt = 0;
1207#ifdef IPSEC
1208		/* clean ipsec history once it goes out of the node */
1209		ipsec_delaux(m);
1210#endif
1211		if (error == 0) {
1212			/* Record statistics for this interface address. */
1213			if (ia != NULL) {
1214				ia->ia_ifa.if_opackets++;
1215				ia->ia_ifa.if_obytes += m->m_pkthdr.len;
1216			}
1217
1218			error = (*ifp->if_output)(ifp, m,
1219			    (struct sockaddr *)dst, ro->ro_rt);
1220		} else
1221			m_freem(m);
1222	}
1223
1224	if (error == 0)
1225		ipstat.ips_fragmented++;
1226    }
1227done:
1228#ifdef IPSEC
1229	if (ro == &iproute && ro->ro_rt) {
1230		RTFREE(ro->ro_rt);
1231		ro->ro_rt = NULL;
1232	}
1233	if (sp != NULL) {
1234		KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1235			printf("DP ip_output call free SP:%p\n", sp));
1236		key_freesp(sp);
1237	}
1238#endif /* IPSEC */
1239#ifdef FAST_IPSEC
1240	if (ro == &iproute && ro->ro_rt) {
1241		RTFREE(ro->ro_rt);
1242		ro->ro_rt = NULL;
1243	}
1244	if (sp != NULL)
1245		KEY_FREESP(&sp);
1246#endif /* FAST_IPSEC */
1247	return (error);
1248bad:
1249	m_freem(m);
1250	goto done;
1251}
1252
1253void
1254in_delayed_cksum(struct mbuf *m)
1255{
1256	struct ip *ip;
1257	u_short csum, offset;
1258
1259	ip = mtod(m, struct ip *);
1260	offset = ip->ip_hl << 2 ;
1261	csum = in_cksum_skip(m, ip->ip_len, offset);
1262	if (m->m_pkthdr.csum_flags & CSUM_UDP && csum == 0)
1263		csum = 0xffff;
1264	offset += m->m_pkthdr.csum_data;	/* checksum offset */
1265
1266	if (offset + sizeof(u_short) > m->m_len) {
1267		printf("delayed m_pullup, m->len: %d  off: %d  p: %d\n",
1268		    m->m_len, offset, ip->ip_p);
1269		/*
1270		 * XXX
1271		 * this shouldn't happen, but if it does, the
1272		 * correct behavior may be to insert the checksum
1273		 * in the existing chain instead of rearranging it.
1274		 */
1275		m = m_pullup(m, offset + sizeof(u_short));
1276	}
1277	*(u_short *)(m->m_data + offset) = csum;
1278}
1279
1280/*
1281 * Insert IP options into preformed packet.
1282 * Adjust IP destination as required for IP source routing,
1283 * as indicated by a non-zero in_addr at the start of the options.
1284 *
1285 * XXX This routine assumes that the packet has no options in place.
1286 */
1287static struct mbuf *
1288ip_insertoptions(m, opt, phlen)
1289	register struct mbuf *m;
1290	struct mbuf *opt;
1291	int *phlen;
1292{
1293	register struct ipoption *p = mtod(opt, struct ipoption *);
1294	struct mbuf *n;
1295	register struct ip *ip = mtod(m, struct ip *);
1296	unsigned optlen;
1297
1298	optlen = opt->m_len - sizeof(p->ipopt_dst);
1299	if (optlen + (u_short)ip->ip_len > IP_MAXPACKET) {
1300		*phlen = 0;
1301		return (m);		/* XXX should fail */
1302	}
1303	if (p->ipopt_dst.s_addr)
1304		ip->ip_dst = p->ipopt_dst;
1305	if (m->m_flags & M_EXT || m->m_data - optlen < m->m_pktdat) {
1306		MGETHDR(n, M_DONTWAIT, MT_HEADER);
1307		if (n == 0) {
1308			*phlen = 0;
1309			return (m);
1310		}
1311		n->m_pkthdr.rcvif = (struct ifnet *)0;
1312#ifdef MAC
1313		mac_create_mbuf_from_mbuf(m, n);
1314#endif
1315		n->m_pkthdr.len = m->m_pkthdr.len + optlen;
1316		m->m_len -= sizeof(struct ip);
1317		m->m_data += sizeof(struct ip);
1318		n->m_next = m;
1319		m = n;
1320		m->m_len = optlen + sizeof(struct ip);
1321		m->m_data += max_linkhdr;
1322		(void)memcpy(mtod(m, void *), ip, sizeof(struct ip));
1323	} else {
1324		m->m_data -= optlen;
1325		m->m_len += optlen;
1326		m->m_pkthdr.len += optlen;
1327		ovbcopy((caddr_t)ip, mtod(m, caddr_t), sizeof(struct ip));
1328	}
1329	ip = mtod(m, struct ip *);
1330	bcopy(p->ipopt_list, ip + 1, optlen);
1331	*phlen = sizeof(struct ip) + optlen;
1332	ip->ip_v = IPVERSION;
1333	ip->ip_hl = *phlen >> 2;
1334	ip->ip_len += optlen;
1335	return (m);
1336}
1337
1338/*
1339 * Copy options from ip to jp,
1340 * omitting those not copied during fragmentation.
1341 */
1342int
1343ip_optcopy(ip, jp)
1344	struct ip *ip, *jp;
1345{
1346	register u_char *cp, *dp;
1347	int opt, optlen, cnt;
1348
1349	cp = (u_char *)(ip + 1);
1350	dp = (u_char *)(jp + 1);
1351	cnt = (ip->ip_hl << 2) - sizeof (struct ip);
1352	for (; cnt > 0; cnt -= optlen, cp += optlen) {
1353		opt = cp[0];
1354		if (opt == IPOPT_EOL)
1355			break;
1356		if (opt == IPOPT_NOP) {
1357			/* Preserve for IP mcast tunnel's LSRR alignment. */
1358			*dp++ = IPOPT_NOP;
1359			optlen = 1;
1360			continue;
1361		}
1362
1363		KASSERT(cnt >= IPOPT_OLEN + sizeof(*cp),
1364		    ("ip_optcopy: malformed ipv4 option"));
1365		optlen = cp[IPOPT_OLEN];
1366		KASSERT(optlen >= IPOPT_OLEN + sizeof(*cp) && optlen <= cnt,
1367		    ("ip_optcopy: malformed ipv4 option"));
1368
1369		/* bogus lengths should have been caught by ip_dooptions */
1370		if (optlen > cnt)
1371			optlen = cnt;
1372		if (IPOPT_COPIED(opt)) {
1373			bcopy(cp, dp, optlen);
1374			dp += optlen;
1375		}
1376	}
1377	for (optlen = dp - (u_char *)(jp+1); optlen & 0x3; optlen++)
1378		*dp++ = IPOPT_EOL;
1379	return (optlen);
1380}
1381
1382/*
1383 * IP socket option processing.
1384 */
1385int
1386ip_ctloutput(so, sopt)
1387	struct socket *so;
1388	struct sockopt *sopt;
1389{
1390	struct	inpcb *inp = sotoinpcb(so);
1391	int	error, optval;
1392
1393	error = optval = 0;
1394	if (sopt->sopt_level != IPPROTO_IP) {
1395		return (EINVAL);
1396	}
1397
1398	switch (sopt->sopt_dir) {
1399	case SOPT_SET:
1400		switch (sopt->sopt_name) {
1401		case IP_OPTIONS:
1402#ifdef notyet
1403		case IP_RETOPTS:
1404#endif
1405		{
1406			struct mbuf *m;
1407			if (sopt->sopt_valsize > MLEN) {
1408				error = EMSGSIZE;
1409				break;
1410			}
1411			MGET(m, sopt->sopt_td ? M_TRYWAIT : M_DONTWAIT, MT_HEADER);
1412			if (m == 0) {
1413				error = ENOBUFS;
1414				break;
1415			}
1416			m->m_len = sopt->sopt_valsize;
1417			error = sooptcopyin(sopt, mtod(m, char *), m->m_len,
1418					    m->m_len);
1419
1420			return (ip_pcbopts(sopt->sopt_name, &inp->inp_options,
1421					   m));
1422		}
1423
1424		case IP_TOS:
1425		case IP_TTL:
1426		case IP_RECVOPTS:
1427		case IP_RECVRETOPTS:
1428		case IP_RECVDSTADDR:
1429		case IP_RECVIF:
1430		case IP_FAITH:
1431			error = sooptcopyin(sopt, &optval, sizeof optval,
1432					    sizeof optval);
1433			if (error)
1434				break;
1435
1436			switch (sopt->sopt_name) {
1437			case IP_TOS:
1438				inp->inp_ip_tos = optval;
1439				break;
1440
1441			case IP_TTL:
1442				inp->inp_ip_ttl = optval;
1443				break;
1444#define	OPTSET(bit) \
1445	if (optval) \
1446		inp->inp_flags |= bit; \
1447	else \
1448		inp->inp_flags &= ~bit;
1449
1450			case IP_RECVOPTS:
1451				OPTSET(INP_RECVOPTS);
1452				break;
1453
1454			case IP_RECVRETOPTS:
1455				OPTSET(INP_RECVRETOPTS);
1456				break;
1457
1458			case IP_RECVDSTADDR:
1459				OPTSET(INP_RECVDSTADDR);
1460				break;
1461
1462			case IP_RECVIF:
1463				OPTSET(INP_RECVIF);
1464				break;
1465
1466			case IP_FAITH:
1467				OPTSET(INP_FAITH);
1468				break;
1469			}
1470			break;
1471#undef OPTSET
1472
1473		case IP_MULTICAST_IF:
1474		case IP_MULTICAST_VIF:
1475		case IP_MULTICAST_TTL:
1476		case IP_MULTICAST_LOOP:
1477		case IP_ADD_MEMBERSHIP:
1478		case IP_DROP_MEMBERSHIP:
1479			error = ip_setmoptions(sopt, &inp->inp_moptions);
1480			break;
1481
1482		case IP_PORTRANGE:
1483			error = sooptcopyin(sopt, &optval, sizeof optval,
1484					    sizeof optval);
1485			if (error)
1486				break;
1487
1488			switch (optval) {
1489			case IP_PORTRANGE_DEFAULT:
1490				inp->inp_flags &= ~(INP_LOWPORT);
1491				inp->inp_flags &= ~(INP_HIGHPORT);
1492				break;
1493
1494			case IP_PORTRANGE_HIGH:
1495				inp->inp_flags &= ~(INP_LOWPORT);
1496				inp->inp_flags |= INP_HIGHPORT;
1497				break;
1498
1499			case IP_PORTRANGE_LOW:
1500				inp->inp_flags &= ~(INP_HIGHPORT);
1501				inp->inp_flags |= INP_LOWPORT;
1502				break;
1503
1504			default:
1505				error = EINVAL;
1506				break;
1507			}
1508			break;
1509
1510#if defined(IPSEC) || defined(FAST_IPSEC)
1511		case IP_IPSEC_POLICY:
1512		{
1513			caddr_t req;
1514			size_t len = 0;
1515			int priv;
1516			struct mbuf *m;
1517			int optname;
1518
1519			if ((error = soopt_getm(sopt, &m)) != 0) /* XXX */
1520				break;
1521			if ((error = soopt_mcopyin(sopt, m)) != 0) /* XXX */
1522				break;
1523			priv = (sopt->sopt_td != NULL &&
1524				suser(sopt->sopt_td) != 0) ? 0 : 1;
1525			req = mtod(m, caddr_t);
1526			len = m->m_len;
1527			optname = sopt->sopt_name;
1528			error = ipsec4_set_policy(inp, optname, req, len, priv);
1529			m_freem(m);
1530			break;
1531		}
1532#endif /*IPSEC*/
1533
1534		default:
1535			error = ENOPROTOOPT;
1536			break;
1537		}
1538		break;
1539
1540	case SOPT_GET:
1541		switch (sopt->sopt_name) {
1542		case IP_OPTIONS:
1543		case IP_RETOPTS:
1544			if (inp->inp_options)
1545				error = sooptcopyout(sopt,
1546						     mtod(inp->inp_options,
1547							  char *),
1548						     inp->inp_options->m_len);
1549			else
1550				sopt->sopt_valsize = 0;
1551			break;
1552
1553		case IP_TOS:
1554		case IP_TTL:
1555		case IP_RECVOPTS:
1556		case IP_RECVRETOPTS:
1557		case IP_RECVDSTADDR:
1558		case IP_RECVIF:
1559		case IP_PORTRANGE:
1560		case IP_FAITH:
1561			switch (sopt->sopt_name) {
1562
1563			case IP_TOS:
1564				optval = inp->inp_ip_tos;
1565				break;
1566
1567			case IP_TTL:
1568				optval = inp->inp_ip_ttl;
1569				break;
1570
1571#define	OPTBIT(bit)	(inp->inp_flags & bit ? 1 : 0)
1572
1573			case IP_RECVOPTS:
1574				optval = OPTBIT(INP_RECVOPTS);
1575				break;
1576
1577			case IP_RECVRETOPTS:
1578				optval = OPTBIT(INP_RECVRETOPTS);
1579				break;
1580
1581			case IP_RECVDSTADDR:
1582				optval = OPTBIT(INP_RECVDSTADDR);
1583				break;
1584
1585			case IP_RECVIF:
1586				optval = OPTBIT(INP_RECVIF);
1587				break;
1588
1589			case IP_PORTRANGE:
1590				if (inp->inp_flags & INP_HIGHPORT)
1591					optval = IP_PORTRANGE_HIGH;
1592				else if (inp->inp_flags & INP_LOWPORT)
1593					optval = IP_PORTRANGE_LOW;
1594				else
1595					optval = 0;
1596				break;
1597
1598			case IP_FAITH:
1599				optval = OPTBIT(INP_FAITH);
1600				break;
1601			}
1602			error = sooptcopyout(sopt, &optval, sizeof optval);
1603			break;
1604
1605		case IP_MULTICAST_IF:
1606		case IP_MULTICAST_VIF:
1607		case IP_MULTICAST_TTL:
1608		case IP_MULTICAST_LOOP:
1609		case IP_ADD_MEMBERSHIP:
1610		case IP_DROP_MEMBERSHIP:
1611			error = ip_getmoptions(sopt, inp->inp_moptions);
1612			break;
1613
1614#if defined(IPSEC) || defined(FAST_IPSEC)
1615		case IP_IPSEC_POLICY:
1616		{
1617			struct mbuf *m = NULL;
1618			caddr_t req = NULL;
1619			size_t len = 0;
1620
1621			if (m != 0) {
1622				req = mtod(m, caddr_t);
1623				len = m->m_len;
1624			}
1625			error = ipsec4_get_policy(sotoinpcb(so), req, len, &m);
1626			if (error == 0)
1627				error = soopt_mcopyout(sopt, m); /* XXX */
1628			if (error == 0)
1629				m_freem(m);
1630			break;
1631		}
1632#endif /*IPSEC*/
1633
1634		default:
1635			error = ENOPROTOOPT;
1636			break;
1637		}
1638		break;
1639	}
1640	return (error);
1641}
1642
1643/*
1644 * Set up IP options in pcb for insertion in output packets.
1645 * Store in mbuf with pointer in pcbopt, adding pseudo-option
1646 * with destination address if source routed.
1647 */
1648static int
1649ip_pcbopts(optname, pcbopt, m)
1650	int optname;
1651	struct mbuf **pcbopt;
1652	register struct mbuf *m;
1653{
1654	register int cnt, optlen;
1655	register u_char *cp;
1656	u_char opt;
1657
1658	/* turn off any old options */
1659	if (*pcbopt)
1660		(void)m_free(*pcbopt);
1661	*pcbopt = 0;
1662	if (m == (struct mbuf *)0 || m->m_len == 0) {
1663		/*
1664		 * Only turning off any previous options.
1665		 */
1666		if (m)
1667			(void)m_free(m);
1668		return (0);
1669	}
1670
1671	if (m->m_len % sizeof(int32_t))
1672		goto bad;
1673	/*
1674	 * IP first-hop destination address will be stored before
1675	 * actual options; move other options back
1676	 * and clear it when none present.
1677	 */
1678	if (m->m_data + m->m_len + sizeof(struct in_addr) >= &m->m_dat[MLEN])
1679		goto bad;
1680	cnt = m->m_len;
1681	m->m_len += sizeof(struct in_addr);
1682	cp = mtod(m, u_char *) + sizeof(struct in_addr);
1683	ovbcopy(mtod(m, caddr_t), (caddr_t)cp, (unsigned)cnt);
1684	bzero(mtod(m, caddr_t), sizeof(struct in_addr));
1685
1686	for (; cnt > 0; cnt -= optlen, cp += optlen) {
1687		opt = cp[IPOPT_OPTVAL];
1688		if (opt == IPOPT_EOL)
1689			break;
1690		if (opt == IPOPT_NOP)
1691			optlen = 1;
1692		else {
1693			if (cnt < IPOPT_OLEN + sizeof(*cp))
1694				goto bad;
1695			optlen = cp[IPOPT_OLEN];
1696			if (optlen < IPOPT_OLEN + sizeof(*cp) || optlen > cnt)
1697				goto bad;
1698		}
1699		switch (opt) {
1700
1701		default:
1702			break;
1703
1704		case IPOPT_LSRR:
1705		case IPOPT_SSRR:
1706			/*
1707			 * user process specifies route as:
1708			 *	->A->B->C->D
1709			 * D must be our final destination (but we can't
1710			 * check that since we may not have connected yet).
1711			 * A is first hop destination, which doesn't appear in
1712			 * actual IP option, but is stored before the options.
1713			 */
1714			if (optlen < IPOPT_MINOFF - 1 + sizeof(struct in_addr))
1715				goto bad;
1716			m->m_len -= sizeof(struct in_addr);
1717			cnt -= sizeof(struct in_addr);
1718			optlen -= sizeof(struct in_addr);
1719			cp[IPOPT_OLEN] = optlen;
1720			/*
1721			 * Move first hop before start of options.
1722			 */
1723			bcopy((caddr_t)&cp[IPOPT_OFFSET+1], mtod(m, caddr_t),
1724			    sizeof(struct in_addr));
1725			/*
1726			 * Then copy rest of options back
1727			 * to close up the deleted entry.
1728			 */
1729			ovbcopy((caddr_t)(&cp[IPOPT_OFFSET+1] +
1730			    sizeof(struct in_addr)),
1731			    (caddr_t)&cp[IPOPT_OFFSET+1],
1732			    (unsigned)cnt + sizeof(struct in_addr));
1733			break;
1734		}
1735	}
1736	if (m->m_len > MAX_IPOPTLEN + sizeof(struct in_addr))
1737		goto bad;
1738	*pcbopt = m;
1739	return (0);
1740
1741bad:
1742	(void)m_free(m);
1743	return (EINVAL);
1744}
1745
1746/*
1747 * XXX
1748 * The whole multicast option thing needs to be re-thought.
1749 * Several of these options are equally applicable to non-multicast
1750 * transmission, and one (IP_MULTICAST_TTL) totally duplicates a
1751 * standard option (IP_TTL).
1752 */
1753
1754/*
1755 * following RFC1724 section 3.3, 0.0.0.0/8 is interpreted as interface index.
1756 */
1757static struct ifnet *
1758ip_multicast_if(a, ifindexp)
1759	struct in_addr *a;
1760	int *ifindexp;
1761{
1762	int ifindex;
1763	struct ifnet *ifp;
1764
1765	if (ifindexp)
1766		*ifindexp = 0;
1767	if (ntohl(a->s_addr) >> 24 == 0) {
1768		ifindex = ntohl(a->s_addr) & 0xffffff;
1769		if (ifindex < 0 || if_index < ifindex)
1770			return NULL;
1771		ifp = ifnet_byindex(ifindex);
1772		if (ifindexp)
1773			*ifindexp = ifindex;
1774	} else {
1775		INADDR_TO_IFP(*a, ifp);
1776	}
1777	return ifp;
1778}
1779
1780/*
1781 * Set the IP multicast options in response to user setsockopt().
1782 */
1783static int
1784ip_setmoptions(sopt, imop)
1785	struct sockopt *sopt;
1786	struct ip_moptions **imop;
1787{
1788	int error = 0;
1789	int i;
1790	struct in_addr addr;
1791	struct ip_mreq mreq;
1792	struct ifnet *ifp;
1793	struct ip_moptions *imo = *imop;
1794	struct route ro;
1795	struct sockaddr_in *dst;
1796	int ifindex;
1797	int s;
1798
1799	if (imo == NULL) {
1800		/*
1801		 * No multicast option buffer attached to the pcb;
1802		 * allocate one and initialize to default values.
1803		 */
1804		imo = (struct ip_moptions*)malloc(sizeof(*imo), M_IPMOPTS,
1805		    M_WAITOK);
1806
1807		if (imo == NULL)
1808			return (ENOBUFS);
1809		*imop = imo;
1810		imo->imo_multicast_ifp = NULL;
1811		imo->imo_multicast_addr.s_addr = INADDR_ANY;
1812		imo->imo_multicast_vif = -1;
1813		imo->imo_multicast_ttl = IP_DEFAULT_MULTICAST_TTL;
1814		imo->imo_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
1815		imo->imo_num_memberships = 0;
1816	}
1817
1818	switch (sopt->sopt_name) {
1819	/* store an index number for the vif you wanna use in the send */
1820	case IP_MULTICAST_VIF:
1821		if (legal_vif_num == 0) {
1822			error = EOPNOTSUPP;
1823			break;
1824		}
1825		error = sooptcopyin(sopt, &i, sizeof i, sizeof i);
1826		if (error)
1827			break;
1828		if (!legal_vif_num(i) && (i != -1)) {
1829			error = EINVAL;
1830			break;
1831		}
1832		imo->imo_multicast_vif = i;
1833		break;
1834
1835	case IP_MULTICAST_IF:
1836		/*
1837		 * Select the interface for outgoing multicast packets.
1838		 */
1839		error = sooptcopyin(sopt, &addr, sizeof addr, sizeof addr);
1840		if (error)
1841			break;
1842		/*
1843		 * INADDR_ANY is used to remove a previous selection.
1844		 * When no interface is selected, a default one is
1845		 * chosen every time a multicast packet is sent.
1846		 */
1847		if (addr.s_addr == INADDR_ANY) {
1848			imo->imo_multicast_ifp = NULL;
1849			break;
1850		}
1851		/*
1852		 * The selected interface is identified by its local
1853		 * IP address.  Find the interface and confirm that
1854		 * it supports multicasting.
1855		 */
1856		s = splimp();
1857		ifp = ip_multicast_if(&addr, &ifindex);
1858		if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0) {
1859			splx(s);
1860			error = EADDRNOTAVAIL;
1861			break;
1862		}
1863		imo->imo_multicast_ifp = ifp;
1864		if (ifindex)
1865			imo->imo_multicast_addr = addr;
1866		else
1867			imo->imo_multicast_addr.s_addr = INADDR_ANY;
1868		splx(s);
1869		break;
1870
1871	case IP_MULTICAST_TTL:
1872		/*
1873		 * Set the IP time-to-live for outgoing multicast packets.
1874		 * The original multicast API required a char argument,
1875		 * which is inconsistent with the rest of the socket API.
1876		 * We allow either a char or an int.
1877		 */
1878		if (sopt->sopt_valsize == 1) {
1879			u_char ttl;
1880			error = sooptcopyin(sopt, &ttl, 1, 1);
1881			if (error)
1882				break;
1883			imo->imo_multicast_ttl = ttl;
1884		} else {
1885			u_int ttl;
1886			error = sooptcopyin(sopt, &ttl, sizeof ttl,
1887					    sizeof ttl);
1888			if (error)
1889				break;
1890			if (ttl > 255)
1891				error = EINVAL;
1892			else
1893				imo->imo_multicast_ttl = ttl;
1894		}
1895		break;
1896
1897	case IP_MULTICAST_LOOP:
1898		/*
1899		 * Set the loopback flag for outgoing multicast packets.
1900		 * Must be zero or one.  The original multicast API required a
1901		 * char argument, which is inconsistent with the rest
1902		 * of the socket API.  We allow either a char or an int.
1903		 */
1904		if (sopt->sopt_valsize == 1) {
1905			u_char loop;
1906			error = sooptcopyin(sopt, &loop, 1, 1);
1907			if (error)
1908				break;
1909			imo->imo_multicast_loop = !!loop;
1910		} else {
1911			u_int loop;
1912			error = sooptcopyin(sopt, &loop, sizeof loop,
1913					    sizeof loop);
1914			if (error)
1915				break;
1916			imo->imo_multicast_loop = !!loop;
1917		}
1918		break;
1919
1920	case IP_ADD_MEMBERSHIP:
1921		/*
1922		 * Add a multicast group membership.
1923		 * Group must be a valid IP multicast address.
1924		 */
1925		error = sooptcopyin(sopt, &mreq, sizeof mreq, sizeof mreq);
1926		if (error)
1927			break;
1928
1929		if (!IN_MULTICAST(ntohl(mreq.imr_multiaddr.s_addr))) {
1930			error = EINVAL;
1931			break;
1932		}
1933		s = splimp();
1934		/*
1935		 * If no interface address was provided, use the interface of
1936		 * the route to the given multicast address.
1937		 */
1938		if (mreq.imr_interface.s_addr == INADDR_ANY) {
1939			bzero((caddr_t)&ro, sizeof(ro));
1940			dst = (struct sockaddr_in *)&ro.ro_dst;
1941			dst->sin_len = sizeof(*dst);
1942			dst->sin_family = AF_INET;
1943			dst->sin_addr = mreq.imr_multiaddr;
1944			rtalloc(&ro);
1945			if (ro.ro_rt == NULL) {
1946				error = EADDRNOTAVAIL;
1947				splx(s);
1948				break;
1949			}
1950			ifp = ro.ro_rt->rt_ifp;
1951			rtfree(ro.ro_rt);
1952		}
1953		else {
1954			ifp = ip_multicast_if(&mreq.imr_interface, NULL);
1955		}
1956
1957		/*
1958		 * See if we found an interface, and confirm that it
1959		 * supports multicast.
1960		 */
1961		if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0) {
1962			error = EADDRNOTAVAIL;
1963			splx(s);
1964			break;
1965		}
1966		/*
1967		 * See if the membership already exists or if all the
1968		 * membership slots are full.
1969		 */
1970		for (i = 0; i < imo->imo_num_memberships; ++i) {
1971			if (imo->imo_membership[i]->inm_ifp == ifp &&
1972			    imo->imo_membership[i]->inm_addr.s_addr
1973						== mreq.imr_multiaddr.s_addr)
1974				break;
1975		}
1976		if (i < imo->imo_num_memberships) {
1977			error = EADDRINUSE;
1978			splx(s);
1979			break;
1980		}
1981		if (i == IP_MAX_MEMBERSHIPS) {
1982			error = ETOOMANYREFS;
1983			splx(s);
1984			break;
1985		}
1986		/*
1987		 * Everything looks good; add a new record to the multicast
1988		 * address list for the given interface.
1989		 */
1990		if ((imo->imo_membership[i] =
1991		    in_addmulti(&mreq.imr_multiaddr, ifp)) == NULL) {
1992			error = ENOBUFS;
1993			splx(s);
1994			break;
1995		}
1996		++imo->imo_num_memberships;
1997		splx(s);
1998		break;
1999
2000	case IP_DROP_MEMBERSHIP:
2001		/*
2002		 * Drop a multicast group membership.
2003		 * Group must be a valid IP multicast address.
2004		 */
2005		error = sooptcopyin(sopt, &mreq, sizeof mreq, sizeof mreq);
2006		if (error)
2007			break;
2008
2009		if (!IN_MULTICAST(ntohl(mreq.imr_multiaddr.s_addr))) {
2010			error = EINVAL;
2011			break;
2012		}
2013
2014		s = splimp();
2015		/*
2016		 * If an interface address was specified, get a pointer
2017		 * to its ifnet structure.
2018		 */
2019		if (mreq.imr_interface.s_addr == INADDR_ANY)
2020			ifp = NULL;
2021		else {
2022			ifp = ip_multicast_if(&mreq.imr_interface, NULL);
2023			if (ifp == NULL) {
2024				error = EADDRNOTAVAIL;
2025				splx(s);
2026				break;
2027			}
2028		}
2029		/*
2030		 * Find the membership in the membership array.
2031		 */
2032		for (i = 0; i < imo->imo_num_memberships; ++i) {
2033			if ((ifp == NULL ||
2034			     imo->imo_membership[i]->inm_ifp == ifp) &&
2035			     imo->imo_membership[i]->inm_addr.s_addr ==
2036			     mreq.imr_multiaddr.s_addr)
2037				break;
2038		}
2039		if (i == imo->imo_num_memberships) {
2040			error = EADDRNOTAVAIL;
2041			splx(s);
2042			break;
2043		}
2044		/*
2045		 * Give up the multicast address record to which the
2046		 * membership points.
2047		 */
2048		in_delmulti(imo->imo_membership[i]);
2049		/*
2050		 * Remove the gap in the membership array.
2051		 */
2052		for (++i; i < imo->imo_num_memberships; ++i)
2053			imo->imo_membership[i-1] = imo->imo_membership[i];
2054		--imo->imo_num_memberships;
2055		splx(s);
2056		break;
2057
2058	default:
2059		error = EOPNOTSUPP;
2060		break;
2061	}
2062
2063	/*
2064	 * If all options have default values, no need to keep the mbuf.
2065	 */
2066	if (imo->imo_multicast_ifp == NULL &&
2067	    imo->imo_multicast_vif == -1 &&
2068	    imo->imo_multicast_ttl == IP_DEFAULT_MULTICAST_TTL &&
2069	    imo->imo_multicast_loop == IP_DEFAULT_MULTICAST_LOOP &&
2070	    imo->imo_num_memberships == 0) {
2071		free(*imop, M_IPMOPTS);
2072		*imop = NULL;
2073	}
2074
2075	return (error);
2076}
2077
2078/*
2079 * Return the IP multicast options in response to user getsockopt().
2080 */
2081static int
2082ip_getmoptions(sopt, imo)
2083	struct sockopt *sopt;
2084	register struct ip_moptions *imo;
2085{
2086	struct in_addr addr;
2087	struct in_ifaddr *ia;
2088	int error, optval;
2089	u_char coptval;
2090
2091	error = 0;
2092	switch (sopt->sopt_name) {
2093	case IP_MULTICAST_VIF:
2094		if (imo != NULL)
2095			optval = imo->imo_multicast_vif;
2096		else
2097			optval = -1;
2098		error = sooptcopyout(sopt, &optval, sizeof optval);
2099		break;
2100
2101	case IP_MULTICAST_IF:
2102		if (imo == NULL || imo->imo_multicast_ifp == NULL)
2103			addr.s_addr = INADDR_ANY;
2104		else if (imo->imo_multicast_addr.s_addr) {
2105			/* return the value user has set */
2106			addr = imo->imo_multicast_addr;
2107		} else {
2108			IFP_TO_IA(imo->imo_multicast_ifp, ia);
2109			addr.s_addr = (ia == NULL) ? INADDR_ANY
2110				: IA_SIN(ia)->sin_addr.s_addr;
2111		}
2112		error = sooptcopyout(sopt, &addr, sizeof addr);
2113		break;
2114
2115	case IP_MULTICAST_TTL:
2116		if (imo == 0)
2117			optval = coptval = IP_DEFAULT_MULTICAST_TTL;
2118		else
2119			optval = coptval = imo->imo_multicast_ttl;
2120		if (sopt->sopt_valsize == 1)
2121			error = sooptcopyout(sopt, &coptval, 1);
2122		else
2123			error = sooptcopyout(sopt, &optval, sizeof optval);
2124		break;
2125
2126	case IP_MULTICAST_LOOP:
2127		if (imo == 0)
2128			optval = coptval = IP_DEFAULT_MULTICAST_LOOP;
2129		else
2130			optval = coptval = imo->imo_multicast_loop;
2131		if (sopt->sopt_valsize == 1)
2132			error = sooptcopyout(sopt, &coptval, 1);
2133		else
2134			error = sooptcopyout(sopt, &optval, sizeof optval);
2135		break;
2136
2137	default:
2138		error = ENOPROTOOPT;
2139		break;
2140	}
2141	return (error);
2142}
2143
2144/*
2145 * Discard the IP multicast options.
2146 */
2147void
2148ip_freemoptions(imo)
2149	register struct ip_moptions *imo;
2150{
2151	register int i;
2152
2153	if (imo != NULL) {
2154		for (i = 0; i < imo->imo_num_memberships; ++i)
2155			in_delmulti(imo->imo_membership[i]);
2156		free(imo, M_IPMOPTS);
2157	}
2158}
2159
2160/*
2161 * Routine called from ip_output() to loop back a copy of an IP multicast
2162 * packet to the input queue of a specified interface.  Note that this
2163 * calls the output routine of the loopback "driver", but with an interface
2164 * pointer that might NOT be a loopback interface -- evil, but easier than
2165 * replicating that code here.
2166 */
2167static void
2168ip_mloopback(ifp, m, dst, hlen)
2169	struct ifnet *ifp;
2170	register struct mbuf *m;
2171	register struct sockaddr_in *dst;
2172	int hlen;
2173{
2174	register struct ip *ip;
2175	struct mbuf *copym;
2176
2177	copym = m_copy(m, 0, M_COPYALL);
2178	if (copym != NULL && (copym->m_flags & M_EXT || copym->m_len < hlen))
2179		copym = m_pullup(copym, hlen);
2180	if (copym != NULL) {
2181		/*
2182		 * We don't bother to fragment if the IP length is greater
2183		 * than the interface's MTU.  Can this possibly matter?
2184		 */
2185		ip = mtod(copym, struct ip *);
2186		ip->ip_len = htons(ip->ip_len);
2187		ip->ip_off = htons(ip->ip_off);
2188		ip->ip_sum = 0;
2189		ip->ip_sum = in_cksum(copym, hlen);
2190		/*
2191		 * NB:
2192		 * It's not clear whether there are any lingering
2193		 * reentrancy problems in other areas which might
2194		 * be exposed by using ip_input directly (in
2195		 * particular, everything which modifies the packet
2196		 * in-place).  Yet another option is using the
2197		 * protosw directly to deliver the looped back
2198		 * packet.  For the moment, we'll err on the side
2199		 * of safety by using if_simloop().
2200		 */
2201#if 1 /* XXX */
2202		if (dst->sin_family != AF_INET) {
2203			printf("ip_mloopback: bad address family %d\n",
2204						dst->sin_family);
2205			dst->sin_family = AF_INET;
2206		}
2207#endif
2208
2209#ifdef notdef
2210		copym->m_pkthdr.rcvif = ifp;
2211		ip_input(copym);
2212#else
2213		/* if the checksum hasn't been computed, mark it as valid */
2214		if (copym->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
2215			copym->m_pkthdr.csum_flags |=
2216			    CSUM_DATA_VALID | CSUM_PSEUDO_HDR;
2217			copym->m_pkthdr.csum_data = 0xffff;
2218		}
2219		if_simloop(ifp, copym, dst->sin_family, 0);
2220#endif
2221	}
2222}
2223