ip_output.c revision 108533
1215976Sjmallett/*
2232812Sjmallett * Copyright (c) 1982, 1986, 1988, 1990, 1993
3215976Sjmallett *	The Regents of the University of California.  All rights reserved.
4215976Sjmallett *
5215976Sjmallett * Redistribution and use in source and binary forms, with or without
6215976Sjmallett * modification, are permitted provided that the following conditions
7215976Sjmallett * are met:
8215976Sjmallett * 1. Redistributions of source code must retain the above copyright
9215976Sjmallett *    notice, this list of conditions and the following disclaimer.
10215976Sjmallett * 2. Redistributions in binary form must reproduce the above copyright
11215976Sjmallett *    notice, this list of conditions and the following disclaimer in the
12215976Sjmallett *    documentation and/or other materials provided with the distribution.
13215976Sjmallett * 3. All advertising materials mentioning features or use of this software
14215976Sjmallett *    must display the following acknowledgement:
15215976Sjmallett *	This product includes software developed by the University of
16215976Sjmallett *	California, Berkeley and its contributors.
17215976Sjmallett * 4. Neither the name of the University nor the names of its contributors
18232812Sjmallett *    may be used to endorse or promote products derived from this software
19215976Sjmallett *    without specific prior written permission.
20215976Sjmallett *
21215976Sjmallett * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22215976Sjmallett * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23215976Sjmallett * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24215976Sjmallett * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25215976Sjmallett * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26215976Sjmallett * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27215976Sjmallett * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28215976Sjmallett * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29232812Sjmallett * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30215976Sjmallett * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31215976Sjmallett * SUCH DAMAGE.
32215976Sjmallett *
33215976Sjmallett *	@(#)ip_output.c	8.3 (Berkeley) 1/21/94
34215976Sjmallett * $FreeBSD: head/sys/netinet/ip_output.c 108533 2003-01-01 18:49:04Z schweikh $
35215976Sjmallett */
36215976Sjmallett
37215976Sjmallett#include "opt_ipfw.h"
38215976Sjmallett#include "opt_ipdn.h"
39215976Sjmallett#include "opt_ipdivert.h"
40215976Sjmallett#include "opt_ipfilter.h"
41215976Sjmallett#include "opt_ipsec.h"
42215976Sjmallett#include "opt_mac.h"
43215976Sjmallett#include "opt_pfil_hooks.h"
44215976Sjmallett#include "opt_random_ip_id.h"
45215976Sjmallett
46215976Sjmallett#include <sys/param.h>
47215976Sjmallett#include <sys/systm.h>
48215976Sjmallett#include <sys/kernel.h>
49215976Sjmallett#include <sys/mac.h>
50215976Sjmallett#include <sys/malloc.h>
51215976Sjmallett#include <sys/mbuf.h>
52232812Sjmallett#include <sys/protosw.h>
53232812Sjmallett#include <sys/socket.h>
54215976Sjmallett#include <sys/socketvar.h>
55215976Sjmallett
56215976Sjmallett#include <net/if.h>
57215976Sjmallett#include <net/route.h>
58215976Sjmallett
59215976Sjmallett#include <netinet/in.h>
60215976Sjmallett#include <netinet/in_systm.h>
61215976Sjmallett#include <netinet/ip.h>
62215976Sjmallett#include <netinet/in_pcb.h>
63215976Sjmallett#include <netinet/in_var.h>
64215976Sjmallett#include <netinet/ip_var.h>
65215976Sjmallett
66215976Sjmallett#include <machine/in_cksum.h>
67215976Sjmallett
68215976Sjmallettstatic MALLOC_DEFINE(M_IPMOPTS, "ip_moptions", "internet multicast options");
69215976Sjmallett
70215976Sjmallett#ifdef IPSEC
71215976Sjmallett#include <netinet6/ipsec.h>
72215976Sjmallett#include <netkey/key.h>
73215976Sjmallett#ifdef IPSEC_DEBUG
74215976Sjmallett#include <netkey/key_debug.h>
75215976Sjmallett#else
76215976Sjmallett#define	KEYDEBUG(lev,arg)
77215976Sjmallett#endif
78215976Sjmallett#endif /*IPSEC*/
79215976Sjmallett
80215976Sjmallett#ifdef FAST_IPSEC
81215976Sjmallett#include <netipsec/ipsec.h>
82215976Sjmallett#include <netipsec/xform.h>
83215976Sjmallett#include <netipsec/key.h>
84215976Sjmallett#endif /*FAST_IPSEC*/
85215976Sjmallett
86215976Sjmallett#include <netinet/ip_fw.h>
87215976Sjmallett#include <netinet/ip_dummynet.h>
88215976Sjmallett
89215976Sjmallett#define print_ip(x, a, y)	 printf("%s %d.%d.%d.%d%s",\
90215976Sjmallett				x, (ntohl(a.s_addr)>>24)&0xFF,\
91215976Sjmallett				  (ntohl(a.s_addr)>>16)&0xFF,\
92215976Sjmallett				  (ntohl(a.s_addr)>>8)&0xFF,\
93215976Sjmallett				  (ntohl(a.s_addr))&0xFF, y);
94215976Sjmallett
95215976Sjmallettu_short ip_id;
96215976Sjmallett
97215976Sjmallettstatic struct mbuf *ip_insertoptions(struct mbuf *, struct mbuf *, int *);
98215976Sjmallettstatic struct ifnet *ip_multicast_if(struct in_addr *, int *);
99215976Sjmallettstatic void	ip_mloopback
100215976Sjmallett	(struct ifnet *, struct mbuf *, struct sockaddr_in *, int);
101215976Sjmallettstatic int	ip_getmoptions
102215976Sjmallett	(struct sockopt *, struct ip_moptions *);
103215976Sjmallettstatic int	ip_pcbopts(int, struct mbuf **, struct mbuf *);
104215976Sjmallettstatic int	ip_setmoptions
105215976Sjmallett	(struct sockopt *, struct ip_moptions **);
106215976Sjmallett
107215976Sjmallettint	ip_optcopy(struct ip *, struct ip *);
108215976Sjmallett
109215976Sjmallett
110215976Sjmallettextern	struct protosw inetsw[];
111215976Sjmallett
112215976Sjmallett/*
113215976Sjmallett * IP output.  The packet in mbuf chain m contains a skeletal IP
114215976Sjmallett * header (with len, off, ttl, proto, tos, src, dst).
115215976Sjmallett * The mbuf chain containing the packet will be freed.
116215976Sjmallett * The mbuf opt, if present, will not be freed.
117215976Sjmallett */
118215976Sjmallettint
119215976Sjmallettip_output(m0, opt, ro, flags, imo, inp)
120215976Sjmallett	struct mbuf *m0;
121215976Sjmallett	struct mbuf *opt;
122215976Sjmallett	struct route *ro;
123215976Sjmallett	int flags;
124215976Sjmallett	struct ip_moptions *imo;
125215976Sjmallett	struct inpcb *inp;
126215976Sjmallett{
127215976Sjmallett	struct ip *ip, *mhip;
128215976Sjmallett	struct ifnet *ifp = NULL;	/* keep compiler happy */
129215976Sjmallett	struct mbuf *m;
130215976Sjmallett	int hlen = sizeof (struct ip);
131215976Sjmallett	int len, off, error = 0;
132215976Sjmallett	struct sockaddr_in *dst = NULL;	/* keep compiler happy */
133215976Sjmallett	struct in_ifaddr *ia = NULL;
134215976Sjmallett	int isbroadcast, sw_csum;
135215976Sjmallett	struct in_addr pkt_dst;
136215976Sjmallett#ifdef IPSEC
137215976Sjmallett	struct route iproute;
138215976Sjmallett	struct secpolicy *sp = NULL;
139215976Sjmallett	struct socket *so = inp ? inp->inp_socket : NULL;
140215976Sjmallett#endif
141215976Sjmallett#ifdef FAST_IPSEC
142215976Sjmallett	struct route iproute;
143215976Sjmallett	struct m_tag *mtag;
144215976Sjmallett	struct secpolicy *sp = NULL;
145215976Sjmallett	struct tdb_ident *tdbi;
146215976Sjmallett	int s;
147215976Sjmallett#endif /* FAST_IPSEC */
148215976Sjmallett	struct ip_fw_args args;
149215976Sjmallett	int src_was_INADDR_ANY = 0;	/* as the name says... */
150215976Sjmallett#ifdef PFIL_HOOKS
151215976Sjmallett	struct packet_filter_hook *pfh;
152215976Sjmallett	struct mbuf *m1;
153215976Sjmallett	int rv;
154215976Sjmallett#endif /* PFIL_HOOKS */
155215976Sjmallett
156215976Sjmallett	args.eh = NULL;
157215976Sjmallett	args.rule = NULL;
158215976Sjmallett	args.next_hop = NULL;
159215976Sjmallett	args.divert_rule = 0;			/* divert cookie */
160215976Sjmallett
161215976Sjmallett	/* Grab info from MT_TAG mbufs prepended to the chain. */
162215976Sjmallett	for (; m0 && m0->m_type == MT_TAG; m0 = m0->m_next) {
163215976Sjmallett		switch(m0->_m_tag_id) {
164215976Sjmallett		default:
165215976Sjmallett			printf("ip_output: unrecognised MT_TAG tag %d\n",
166215976Sjmallett			    m0->_m_tag_id);
167215976Sjmallett			break;
168215976Sjmallett
169215976Sjmallett		case PACKET_TAG_DUMMYNET:
170215976Sjmallett			/*
171215976Sjmallett			 * the packet was already tagged, so part of the
172215976Sjmallett			 * processing was already done, and we need to go down.
173215976Sjmallett			 * Get parameters from the header.
174215976Sjmallett			 */
175215976Sjmallett			args.rule = ((struct dn_pkt *)m0)->rule;
176215976Sjmallett			opt = NULL ;
177215976Sjmallett			ro = & ( ((struct dn_pkt *)m0)->ro ) ;
178215976Sjmallett			imo = NULL ;
179215976Sjmallett			dst = ((struct dn_pkt *)m0)->dn_dst ;
180215976Sjmallett			ifp = ((struct dn_pkt *)m0)->ifp ;
181215976Sjmallett			flags = ((struct dn_pkt *)m0)->flags ;
182215976Sjmallett			break;
183215976Sjmallett
184215976Sjmallett		case PACKET_TAG_DIVERT:
185215976Sjmallett			args.divert_rule = (intptr_t)m0->m_data & 0xffff;
186215976Sjmallett			break;
187215976Sjmallett
188215976Sjmallett		case PACKET_TAG_IPFORWARD:
189215976Sjmallett			args.next_hop = (struct sockaddr_in *)m0->m_data;
190215976Sjmallett			break;
191215976Sjmallett		}
192215976Sjmallett	}
193215976Sjmallett	m = m0;
194215976Sjmallett
195215976Sjmallett	KASSERT(!m || (m->m_flags & M_PKTHDR) != 0, ("ip_output: no HDR"));
196215976Sjmallett#ifndef FAST_IPSEC
197215976Sjmallett	KASSERT(ro != NULL, ("ip_output: no route, proto %d",
198215976Sjmallett	    mtod(m, struct ip *)->ip_p));
199215976Sjmallett#endif
200215976Sjmallett
201215976Sjmallett	if (args.rule != NULL) {	/* dummynet already saw us */
202215976Sjmallett		ip = mtod(m, struct ip *);
203215976Sjmallett		hlen = ip->ip_hl << 2 ;
204215976Sjmallett		if (ro->ro_rt)
205215976Sjmallett			ia = ifatoia(ro->ro_rt->rt_ifa);
206215976Sjmallett		goto sendit;
207215976Sjmallett	}
208215976Sjmallett
209215976Sjmallett	if (opt) {
210215976Sjmallett		len = 0;
211215976Sjmallett		m = ip_insertoptions(m, opt, &len);
212215976Sjmallett		if (len != 0)
213215976Sjmallett			hlen = len;
214215976Sjmallett	}
215232812Sjmallett	ip = mtod(m, struct ip *);
216215976Sjmallett	pkt_dst = args.next_hop ? args.next_hop->sin_addr : ip->ip_dst;
217232812Sjmallett
218232812Sjmallett	/*
219215976Sjmallett	 * Fill in IP header.
220215976Sjmallett	 */
221215976Sjmallett	if ((flags & (IP_FORWARDING|IP_RAWOUTPUT)) == 0) {
222215976Sjmallett		ip->ip_v = IPVERSION;
223215976Sjmallett		ip->ip_hl = hlen >> 2;
224215976Sjmallett		ip->ip_off &= IP_DF;
225215976Sjmallett#ifdef RANDOM_IP_ID
226215976Sjmallett		ip->ip_id = ip_randomid();
227215976Sjmallett#else
228215976Sjmallett		ip->ip_id = htons(ip_id++);
229215976Sjmallett#endif
230215976Sjmallett		ipstat.ips_localout++;
231215976Sjmallett	} else {
232215976Sjmallett		hlen = ip->ip_hl << 2;
233215976Sjmallett	}
234215976Sjmallett
235215976Sjmallett#ifdef FAST_IPSEC
236215976Sjmallett	if (ro == NULL) {
237215976Sjmallett		ro = &iproute;
238215976Sjmallett		bzero(ro, sizeof (*ro));
239215976Sjmallett	}
240215976Sjmallett#endif /* FAST_IPSEC */
241215976Sjmallett	dst = (struct sockaddr_in *)&ro->ro_dst;
242215976Sjmallett	/*
243215976Sjmallett	 * If there is a cached route,
244215976Sjmallett	 * check that it is to the same destination
245215976Sjmallett	 * and is still up.  If not, free it and try again.
246215976Sjmallett	 * The address family should also be checked in case of sharing the
247215976Sjmallett	 * cache with IPv6.
248215976Sjmallett	 */
249232812Sjmallett	if (ro->ro_rt && ((ro->ro_rt->rt_flags & RTF_UP) == 0 ||
250215976Sjmallett			  dst->sin_family != AF_INET ||
251232812Sjmallett			  dst->sin_addr.s_addr != pkt_dst.s_addr)) {
252232812Sjmallett		RTFREE(ro->ro_rt);
253215976Sjmallett		ro->ro_rt = (struct rtentry *)0;
254215976Sjmallett	}
255215976Sjmallett	if (ro->ro_rt == 0) {
256215976Sjmallett		bzero(dst, sizeof(*dst));
257215976Sjmallett		dst->sin_family = AF_INET;
258215976Sjmallett		dst->sin_len = sizeof(*dst);
259215976Sjmallett		dst->sin_addr = pkt_dst;
260215976Sjmallett	}
261215976Sjmallett	/*
262215976Sjmallett	 * If routing to interface only,
263215976Sjmallett	 * short circuit routing lookup.
264215976Sjmallett	 */
265215976Sjmallett	if (flags & IP_ROUTETOIF) {
266215976Sjmallett		if ((ia = ifatoia(ifa_ifwithdstaddr(sintosa(dst)))) == 0 &&
267215976Sjmallett		    (ia = ifatoia(ifa_ifwithnet(sintosa(dst)))) == 0) {
268215976Sjmallett			ipstat.ips_noroute++;
269215976Sjmallett			error = ENETUNREACH;
270215976Sjmallett			goto bad;
271215976Sjmallett		}
272215976Sjmallett		ifp = ia->ia_ifp;
273215976Sjmallett		ip->ip_ttl = 1;
274215976Sjmallett		isbroadcast = in_broadcast(dst->sin_addr, ifp);
275232812Sjmallett	} else if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) &&
276215976Sjmallett	    imo != NULL && imo->imo_multicast_ifp != NULL) {
277232812Sjmallett		/*
278232812Sjmallett		 * Bypass the normal routing lookup for multicast
279215976Sjmallett		 * packets if the interface is specified.
280215976Sjmallett		 */
281215976Sjmallett		ifp = imo->imo_multicast_ifp;
282215976Sjmallett		IFP_TO_IA(ifp, ia);
283215976Sjmallett		isbroadcast = 0;	/* fool gcc */
284215976Sjmallett	} else {
285215976Sjmallett		/*
286215976Sjmallett		 * If this is the case, we probably don't want to allocate
287215976Sjmallett		 * a protocol-cloned route since we didn't get one from the
288215976Sjmallett		 * ULP.  This lets TCP do its thing, while not burdening
289215976Sjmallett		 * forwarding or ICMP with the overhead of cloning a route.
290215976Sjmallett		 * Of course, we still want to do any cloning requested by
291215976Sjmallett		 * the link layer, as this is probably required in all cases
292215976Sjmallett		 * for correct operation (as it is for ARP).
293215976Sjmallett		 */
294215976Sjmallett		if (ro->ro_rt == 0)
295215976Sjmallett			rtalloc_ign(ro, RTF_PRCLONING);
296215976Sjmallett		if (ro->ro_rt == 0) {
297215976Sjmallett			ipstat.ips_noroute++;
298215976Sjmallett			error = EHOSTUNREACH;
299215976Sjmallett			goto bad;
300215976Sjmallett		}
301215976Sjmallett		ia = ifatoia(ro->ro_rt->rt_ifa);
302232812Sjmallett		ifp = ro->ro_rt->rt_ifp;
303215976Sjmallett		ro->ro_rt->rt_use++;
304232812Sjmallett		if (ro->ro_rt->rt_flags & RTF_GATEWAY)
305232812Sjmallett			dst = (struct sockaddr_in *)ro->ro_rt->rt_gateway;
306215976Sjmallett		if (ro->ro_rt->rt_flags & RTF_HOST)
307215976Sjmallett			isbroadcast = (ro->ro_rt->rt_flags & RTF_BROADCAST);
308215976Sjmallett		else
309215976Sjmallett			isbroadcast = in_broadcast(dst->sin_addr, ifp);
310215976Sjmallett	}
311215976Sjmallett	if (IN_MULTICAST(ntohl(pkt_dst.s_addr))) {
312215976Sjmallett		struct in_multi *inm;
313215976Sjmallett
314215976Sjmallett		m->m_flags |= M_MCAST;
315215976Sjmallett		/*
316215976Sjmallett		 * IP destination address is multicast.  Make sure "dst"
317215976Sjmallett		 * still points to the address in "ro".  (It may have been
318215976Sjmallett		 * changed to point to a gateway address, above.)
319215976Sjmallett		 */
320215976Sjmallett		dst = (struct sockaddr_in *)&ro->ro_dst;
321215976Sjmallett		/*
322215976Sjmallett		 * See if the caller provided any multicast options
323215976Sjmallett		 */
324215976Sjmallett		if (imo != NULL) {
325215976Sjmallett			ip->ip_ttl = imo->imo_multicast_ttl;
326215976Sjmallett			if (imo->imo_multicast_vif != -1)
327215976Sjmallett				ip->ip_src.s_addr =
328215976Sjmallett				    ip_mcast_src ?
329215976Sjmallett				    ip_mcast_src(imo->imo_multicast_vif) :
330215976Sjmallett				    INADDR_ANY;
331215976Sjmallett		} else
332215976Sjmallett			ip->ip_ttl = IP_DEFAULT_MULTICAST_TTL;
333215976Sjmallett		/*
334215976Sjmallett		 * Confirm that the outgoing interface supports multicast.
335215976Sjmallett		 */
336215976Sjmallett		if ((imo == NULL) || (imo->imo_multicast_vif == -1)) {
337215976Sjmallett			if ((ifp->if_flags & IFF_MULTICAST) == 0) {
338215976Sjmallett				ipstat.ips_noroute++;
339215976Sjmallett				error = ENETUNREACH;
340215976Sjmallett				goto bad;
341215976Sjmallett			}
342215976Sjmallett		}
343215976Sjmallett		/*
344215976Sjmallett		 * If source address not specified yet, use address
345215976Sjmallett		 * of outgoing interface.
346215976Sjmallett		 */
347215976Sjmallett		if (ip->ip_src.s_addr == INADDR_ANY) {
348215976Sjmallett			/* Interface may have no addresses. */
349215976Sjmallett			if (ia != NULL)
350215976Sjmallett				ip->ip_src = IA_SIN(ia)->sin_addr;
351215976Sjmallett		}
352215976Sjmallett
353215976Sjmallett		if (ip_mrouter && (flags & IP_FORWARDING) == 0) {
354215976Sjmallett			/*
355215976Sjmallett			 * XXX
356215976Sjmallett			 * delayed checksums are not currently
357215976Sjmallett			 * compatible with IP multicast routing
358232812Sjmallett			 */
359215976Sjmallett			if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
360232812Sjmallett				in_delayed_cksum(m);
361232812Sjmallett				m->m_pkthdr.csum_flags &=
362215976Sjmallett					~CSUM_DELAY_DATA;
363215976Sjmallett			}
364215976Sjmallett		}
365215976Sjmallett		IN_LOOKUP_MULTI(pkt_dst, ifp, inm);
366215976Sjmallett		if (inm != NULL &&
367215976Sjmallett		   (imo == NULL || imo->imo_multicast_loop)) {
368215976Sjmallett			/*
369215976Sjmallett			 * If we belong to the destination multicast group
370215976Sjmallett			 * on the outgoing interface, and the caller did not
371215976Sjmallett			 * forbid loopback, loop back a copy.
372215976Sjmallett			 */
373215976Sjmallett			ip_mloopback(ifp, m, dst, hlen);
374215976Sjmallett		}
375215976Sjmallett		else {
376215976Sjmallett			/*
377215976Sjmallett			 * If we are acting as a multicast router, perform
378215976Sjmallett			 * multicast forwarding as if the packet had just
379215976Sjmallett			 * arrived on the interface to which we are about
380215976Sjmallett			 * to send.  The multicast forwarding function
381215976Sjmallett			 * recursively calls this function, using the
382215976Sjmallett			 * IP_FORWARDING flag to prevent infinite recursion.
383215976Sjmallett			 *
384232812Sjmallett			 * Multicasts that are looped back by ip_mloopback(),
385215976Sjmallett			 * above, will be forwarded by the ip_input() routine,
386232812Sjmallett			 * if necessary.
387232812Sjmallett			 */
388215976Sjmallett			if (ip_mrouter && (flags & IP_FORWARDING) == 0) {
389215976Sjmallett				/*
390215976Sjmallett				 * If rsvp daemon is not running, do not
391215976Sjmallett				 * set ip_moptions. This ensures that the packet
392215976Sjmallett				 * is multicast and not just sent down one link
393215976Sjmallett				 * as prescribed by rsvpd.
394215976Sjmallett				 */
395215976Sjmallett				if (!rsvp_on)
396215976Sjmallett					imo = NULL;
397215976Sjmallett				if (ip_mforward &&
398215976Sjmallett				    ip_mforward(ip, ifp, m, imo) != 0) {
399215976Sjmallett					m_freem(m);
400215976Sjmallett					goto done;
401215976Sjmallett				}
402215976Sjmallett			}
403215976Sjmallett		}
404215976Sjmallett
405215976Sjmallett		/*
406215976Sjmallett		 * Multicasts with a time-to-live of zero may be looped-
407215976Sjmallett		 * back, above, but must not be transmitted on a network.
408215976Sjmallett		 * Also, multicasts addressed to the loopback interface
409215976Sjmallett		 * are not sent -- the above call to ip_mloopback() will
410215976Sjmallett		 * loop back a copy if this host actually belongs to the
411215976Sjmallett		 * destination group on the loopback interface.
412215976Sjmallett		 */
413215976Sjmallett		if (ip->ip_ttl == 0 || ifp->if_flags & IFF_LOOPBACK) {
414215976Sjmallett			m_freem(m);
415215976Sjmallett			goto done;
416215976Sjmallett		}
417232812Sjmallett
418215976Sjmallett		goto sendit;
419232812Sjmallett	}
420232812Sjmallett#ifndef notdef
421215976Sjmallett	/*
422215976Sjmallett	 * If the source address is not specified yet, use the address
423215976Sjmallett	 * of the outoing interface. In case, keep note we did that, so
424215976Sjmallett	 * if the the firewall changes the next-hop causing the output
425215976Sjmallett	 * interface to change, we can fix that.
426215976Sjmallett	 */
427215976Sjmallett	if (ip->ip_src.s_addr == INADDR_ANY) {
428215976Sjmallett		/* Interface may have no addresses. */
429215976Sjmallett		if (ia != NULL) {
430215976Sjmallett			ip->ip_src = IA_SIN(ia)->sin_addr;
431215976Sjmallett			src_was_INADDR_ANY = 1;
432215976Sjmallett		}
433215976Sjmallett	}
434215976Sjmallett#endif /* notdef */
435215976Sjmallett	/*
436215976Sjmallett	 * Verify that we have any chance at all of being able to queue
437215976Sjmallett	 *      the packet or packet fragments
438215976Sjmallett	 */
439215976Sjmallett	if ((ifp->if_snd.ifq_len + ip->ip_len / ifp->if_mtu + 1) >=
440215976Sjmallett		ifp->if_snd.ifq_maxlen) {
441215976Sjmallett			error = ENOBUFS;
442215976Sjmallett			ipstat.ips_odropped++;
443215976Sjmallett			goto bad;
444215976Sjmallett	}
445215976Sjmallett
446215976Sjmallett	/*
447215976Sjmallett	 * Look for broadcast address and
448215976Sjmallett	 * verify user is allowed to send
449215976Sjmallett	 * such a packet.
450215976Sjmallett	 */
451215976Sjmallett	if (isbroadcast) {
452215976Sjmallett		if ((ifp->if_flags & IFF_BROADCAST) == 0) {
453232812Sjmallett			error = EADDRNOTAVAIL;
454215976Sjmallett			goto bad;
455232812Sjmallett		}
456232812Sjmallett		if ((flags & IP_ALLOWBROADCAST) == 0) {
457215976Sjmallett			error = EACCES;
458215976Sjmallett			goto bad;
459215976Sjmallett		}
460215976Sjmallett		/* don't allow broadcast messages to be fragmented */
461215976Sjmallett		if ((u_short)ip->ip_len > ifp->if_mtu) {
462215976Sjmallett			error = EMSGSIZE;
463215976Sjmallett			goto bad;
464215976Sjmallett		}
465215976Sjmallett		m->m_flags |= M_BCAST;
466215976Sjmallett	} else {
467215976Sjmallett		m->m_flags &= ~M_BCAST;
468215976Sjmallett	}
469215976Sjmallett
470215976Sjmallettsendit:
471215976Sjmallett#ifdef IPSEC
472215976Sjmallett	/* get SP for this packet */
473215976Sjmallett	if (so == NULL)
474215976Sjmallett		sp = ipsec4_getpolicybyaddr(m, IPSEC_DIR_OUTBOUND, flags, &error);
475215976Sjmallett	else
476215976Sjmallett		sp = ipsec4_getpolicybysock(m, IPSEC_DIR_OUTBOUND, so, &error);
477215976Sjmallett
478215976Sjmallett	if (sp == NULL) {
479215976Sjmallett		ipsecstat.out_inval++;
480215976Sjmallett		goto bad;
481215976Sjmallett	}
482215976Sjmallett
483215976Sjmallett	error = 0;
484215976Sjmallett
485215976Sjmallett	/* check policy */
486215976Sjmallett	switch (sp->policy) {
487215976Sjmallett	case IPSEC_POLICY_DISCARD:
488215976Sjmallett		/*
489215976Sjmallett		 * This packet is just discarded.
490232812Sjmallett		 */
491215976Sjmallett		ipsecstat.out_polvio++;
492232812Sjmallett		goto bad;
493232812Sjmallett
494215976Sjmallett	case IPSEC_POLICY_BYPASS:
495215976Sjmallett	case IPSEC_POLICY_NONE:
496215976Sjmallett		/* no need to do IPsec. */
497215976Sjmallett		goto skip_ipsec;
498215976Sjmallett
499215976Sjmallett	case IPSEC_POLICY_IPSEC:
500215976Sjmallett		if (sp->req == NULL) {
501215976Sjmallett			/* acquire a policy */
502215976Sjmallett			error = key_spdacquire(sp);
503215976Sjmallett			goto bad;
504215976Sjmallett		}
505215976Sjmallett		break;
506215976Sjmallett
507215976Sjmallett	case IPSEC_POLICY_ENTRUST:
508215976Sjmallett	default:
509215976Sjmallett		printf("ip_output: Invalid policy found. %d\n", sp->policy);
510215976Sjmallett	}
511215976Sjmallett    {
512215976Sjmallett	struct ipsec_output_state state;
513215976Sjmallett	bzero(&state, sizeof(state));
514215976Sjmallett	state.m = m;
515215976Sjmallett	if (flags & IP_ROUTETOIF) {
516215976Sjmallett		state.ro = &iproute;
517215976Sjmallett		bzero(&iproute, sizeof(iproute));
518215976Sjmallett	} else
519215976Sjmallett		state.ro = ro;
520215976Sjmallett	state.dst = (struct sockaddr *)dst;
521215976Sjmallett
522232812Sjmallett	ip->ip_sum = 0;
523215976Sjmallett
524232812Sjmallett	/*
525232812Sjmallett	 * XXX
526215976Sjmallett	 * delayed checksums are not currently compatible with IPsec
527215976Sjmallett	 */
528215976Sjmallett	if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
529215976Sjmallett		in_delayed_cksum(m);
530215976Sjmallett		m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
531215976Sjmallett	}
532215976Sjmallett
533215976Sjmallett	ip->ip_len = htons(ip->ip_len);
534215976Sjmallett	ip->ip_off = htons(ip->ip_off);
535215976Sjmallett
536215976Sjmallett	error = ipsec4_output(&state, sp, flags);
537215976Sjmallett
538215976Sjmallett	m = state.m;
539215976Sjmallett	if (flags & IP_ROUTETOIF) {
540215976Sjmallett		/*
541215976Sjmallett		 * if we have tunnel mode SA, we may need to ignore
542215976Sjmallett		 * IP_ROUTETOIF.
543215976Sjmallett		 */
544215976Sjmallett		if (state.ro != &iproute || state.ro->ro_rt != NULL) {
545215976Sjmallett			flags &= ~IP_ROUTETOIF;
546215976Sjmallett			ro = state.ro;
547215976Sjmallett		}
548215976Sjmallett	} else
549215976Sjmallett		ro = state.ro;
550215976Sjmallett	dst = (struct sockaddr_in *)state.dst;
551215976Sjmallett	if (error) {
552215976Sjmallett		/* mbuf is already reclaimed in ipsec4_output. */
553215976Sjmallett		m0 = NULL;
554232812Sjmallett		switch (error) {
555215976Sjmallett		case EHOSTUNREACH:
556232812Sjmallett		case ENETUNREACH:
557232812Sjmallett		case EMSGSIZE:
558215976Sjmallett		case ENOBUFS:
559215976Sjmallett		case ENOMEM:
560215976Sjmallett			break;
561215976Sjmallett		default:
562215976Sjmallett			printf("ip4_output (ipsec): error code %d\n", error);
563215976Sjmallett			/*fall through*/
564215976Sjmallett		case ENOENT:
565215976Sjmallett			/* don't show these error codes to the user */
566215976Sjmallett			error = 0;
567215976Sjmallett			break;
568215976Sjmallett		}
569215976Sjmallett		goto bad;
570215976Sjmallett	}
571215976Sjmallett    }
572215976Sjmallett
573215976Sjmallett	/* be sure to update variables that are affected by ipsec4_output() */
574215976Sjmallett	ip = mtod(m, struct ip *);
575215976Sjmallett	hlen = ip->ip_hl << 2;
576215976Sjmallett	if (ro->ro_rt == NULL) {
577215976Sjmallett		if ((flags & IP_ROUTETOIF) == 0) {
578215976Sjmallett			printf("ip_output: "
579215976Sjmallett				"can't update route after IPsec processing\n");
580215976Sjmallett			error = EHOSTUNREACH;	/*XXX*/
581215976Sjmallett			goto bad;
582232812Sjmallett		}
583215976Sjmallett	} else {
584232812Sjmallett		ia = ifatoia(ro->ro_rt->rt_ifa);
585232812Sjmallett		ifp = ro->ro_rt->rt_ifp;
586215976Sjmallett	}
587215976Sjmallett
588215976Sjmallett	/* make it flipped, again. */
589215976Sjmallett	ip->ip_len = ntohs(ip->ip_len);
590215976Sjmallett	ip->ip_off = ntohs(ip->ip_off);
591215976Sjmallettskip_ipsec:
592215976Sjmallett#endif /*IPSEC*/
593215976Sjmallett#ifdef FAST_IPSEC
594215976Sjmallett	/*
595215976Sjmallett	 * Check the security policy (SP) for the packet and, if
596215976Sjmallett	 * required, do IPsec-related processing.  There are two
597215976Sjmallett	 * cases here; the first time a packet is sent through
598215976Sjmallett	 * it will be untagged and handled by ipsec4_checkpolicy.
599215976Sjmallett	 * If the packet is resubmitted to ip_output (e.g. after
600215976Sjmallett	 * AH, ESP, etc. processing), there will be a tag to bypass
601215976Sjmallett	 * the lookup and related policy checking.
602215976Sjmallett	 */
603215976Sjmallett	mtag = m_tag_find(m, PACKET_TAG_IPSEC_PENDING_TDB, NULL);
604215976Sjmallett	s = splnet();
605215976Sjmallett	if (mtag != NULL) {
606215976Sjmallett		tdbi = (struct tdb_ident *)(mtag + 1);
607215976Sjmallett		sp = ipsec_getpolicy(tdbi, IPSEC_DIR_OUTBOUND);
608215976Sjmallett		if (sp == NULL)
609232812Sjmallett			error = -EINVAL;	/* force silent drop */
610215976Sjmallett		m_tag_delete(m, mtag);
611232812Sjmallett	} else {
612232812Sjmallett		sp = ipsec4_checkpolicy(m, IPSEC_DIR_OUTBOUND, flags,
613215976Sjmallett					&error, inp);
614215976Sjmallett	}
615215976Sjmallett	/*
616215976Sjmallett	 * There are four return cases:
617215976Sjmallett	 *    sp != NULL	 	    apply IPsec policy
618215976Sjmallett	 *    sp == NULL, error == 0	    no IPsec handling needed
619215976Sjmallett	 *    sp == NULL, error == -EINVAL  discard packet w/o error
620215976Sjmallett	 *    sp == NULL, error != 0	    discard packet, report error
621215976Sjmallett	 */
622215976Sjmallett	if (sp != NULL) {
623215976Sjmallett		/* Loop detection, check if ipsec processing already done */
624215976Sjmallett		KASSERT(sp->req != NULL, ("ip_output: no ipsec request"));
625215976Sjmallett		for (mtag = m_tag_first(m); mtag != NULL;
626215976Sjmallett		     mtag = m_tag_next(m, mtag)) {
627215976Sjmallett			if (mtag->m_tag_cookie != MTAG_ABI_COMPAT)
628215976Sjmallett				continue;
629215976Sjmallett			if (mtag->m_tag_id != PACKET_TAG_IPSEC_OUT_DONE &&
630215976Sjmallett			    mtag->m_tag_id != PACKET_TAG_IPSEC_OUT_CRYPTO_NEEDED)
631				continue;
632			/*
633			 * Check if policy has an SA associated with it.
634			 * This can happen when an SP has yet to acquire
635			 * an SA; e.g. on first reference.  If it occurs,
636			 * then we let ipsec4_process_packet do its thing.
637			 */
638			if (sp->req->sav == NULL)
639				break;
640			tdbi = (struct tdb_ident *)(mtag + 1);
641			if (tdbi->spi == sp->req->sav->spi &&
642			    tdbi->proto == sp->req->sav->sah->saidx.proto &&
643			    bcmp(&tdbi->dst, &sp->req->sav->sah->saidx.dst,
644				 sizeof (union sockaddr_union)) == 0) {
645				/*
646				 * No IPsec processing is needed, free
647				 * reference to SP.
648				 *
649				 * NB: null pointer to avoid free at
650				 *     done: below.
651				 */
652				KEY_FREESP(&sp), sp = NULL;
653				splx(s);
654				goto spd_done;
655			}
656		}
657
658		/*
659		 * Do delayed checksums now because we send before
660		 * this is done in the normal processing path.
661		 */
662		if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
663			in_delayed_cksum(m);
664			m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
665		}
666
667		ip->ip_len = htons(ip->ip_len);
668		ip->ip_off = htons(ip->ip_off);
669
670		/* NB: callee frees mbuf */
671		error = ipsec4_process_packet(m, sp->req, flags, 0);
672		splx(s);
673		goto done;
674	} else {
675		splx(s);
676
677		if (error != 0) {
678			/*
679			 * Hack: -EINVAL is used to signal that a packet
680			 * should be silently discarded.  This is typically
681			 * because we asked key management for an SA and
682			 * it was delayed (e.g. kicked up to IKE).
683			 */
684			if (error == -EINVAL)
685				error = 0;
686			goto bad;
687		} else {
688			/* No IPsec processing for this packet. */
689		}
690#ifdef notyet
691		/*
692		 * If deferred crypto processing is needed, check that
693		 * the interface supports it.
694		 */
695		mtag = m_tag_find(m, PACKET_TAG_IPSEC_OUT_CRYPTO_NEEDED, NULL);
696		if (mtag != NULL && (ifp->if_capenable & IFCAP_IPSEC) == 0) {
697			/* notify IPsec to do its own crypto */
698			ipsp_skipcrypto_unmark((struct tdb_ident *)(mtag + 1));
699			error = EHOSTUNREACH;
700			goto bad;
701		}
702#endif
703	}
704spd_done:
705#endif /* FAST_IPSEC */
706
707	/*
708	 * IpHack's section.
709	 * - Xlate: translate packet's addr/port (NAT).
710	 * - Firewall: deny/allow/etc.
711	 * - Wrap: fake packet's addr/port <unimpl.>
712	 * - Encapsulate: put it in another IP and send out. <unimp.>
713	 */
714#ifdef PFIL_HOOKS
715	/*
716	 * Run through list of hooks for output packets.
717	 */
718	m1 = m;
719	pfh = pfil_hook_get(PFIL_OUT, &inetsw[ip_protox[IPPROTO_IP]].pr_pfh);
720	for (; pfh; pfh = TAILQ_NEXT(pfh, pfil_link))
721		if (pfh->pfil_func) {
722			rv = pfh->pfil_func(ip, hlen, ifp, 1, &m1);
723			if (rv) {
724				error = EHOSTUNREACH;
725				goto done;
726			}
727			m = m1;
728			if (m == NULL)
729				goto done;
730			ip = mtod(m, struct ip *);
731		}
732#endif /* PFIL_HOOKS */
733
734	/*
735	 * Check with the firewall...
736	 * but not if we are already being fwd'd from a firewall.
737	 */
738	if (fw_enable && IPFW_LOADED && !args.next_hop) {
739		struct sockaddr_in *old = dst;
740
741		args.m = m;
742		args.next_hop = dst;
743		args.oif = ifp;
744		off = ip_fw_chk_ptr(&args);
745		m = args.m;
746		dst = args.next_hop;
747
748                /*
749		 * On return we must do the following:
750		 * m == NULL	-> drop the pkt (old interface, deprecated)
751		 * (off & IP_FW_PORT_DENY_FLAG)	-> drop the pkt (new interface)
752		 * 1<=off<= 0xffff		-> DIVERT
753		 * (off & IP_FW_PORT_DYNT_FLAG)	-> send to a DUMMYNET pipe
754		 * (off & IP_FW_PORT_TEE_FLAG)	-> TEE the packet
755		 * dst != old			-> IPFIREWALL_FORWARD
756		 * off==0, dst==old		-> accept
757		 * If some of the above modules are not compiled in, then
758		 * we should't have to check the corresponding condition
759		 * (because the ipfw control socket should not accept
760		 * unsupported rules), but better play safe and drop
761		 * packets in case of doubt.
762		 */
763		if ( (off & IP_FW_PORT_DENY_FLAG) || m == NULL) {
764			if (m)
765				m_freem(m);
766			error = EACCES;
767			goto done;
768		}
769		ip = mtod(m, struct ip *);
770		if (off == 0 && dst == old)		/* common case */
771			goto pass;
772                if (DUMMYNET_LOADED && (off & IP_FW_PORT_DYNT_FLAG) != 0) {
773			/*
774			 * pass the pkt to dummynet. Need to include
775			 * pipe number, m, ifp, ro, dst because these are
776			 * not recomputed in the next pass.
777			 * All other parameters have been already used and
778			 * so they are not needed anymore.
779			 * XXX note: if the ifp or ro entry are deleted
780			 * while a pkt is in dummynet, we are in trouble!
781			 */
782			args.ro = ro;
783			args.dst = dst;
784			args.flags = flags;
785
786			error = ip_dn_io_ptr(m, off & 0xffff, DN_TO_IP_OUT,
787				&args);
788			goto done;
789		}
790#ifdef IPDIVERT
791		if (off != 0 && (off & IP_FW_PORT_DYNT_FLAG) == 0) {
792			struct mbuf *clone = NULL;
793
794			/* Clone packet if we're doing a 'tee' */
795			if ((off & IP_FW_PORT_TEE_FLAG) != 0)
796				clone = m_dup(m, M_DONTWAIT);
797
798			/*
799			 * XXX
800			 * delayed checksums are not currently compatible
801			 * with divert sockets.
802			 */
803			if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
804				in_delayed_cksum(m);
805				m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
806			}
807
808			/* Restore packet header fields to original values */
809			ip->ip_len = htons(ip->ip_len);
810			ip->ip_off = htons(ip->ip_off);
811
812			/* Deliver packet to divert input routine */
813			divert_packet(m, 0, off & 0xffff, args.divert_rule);
814
815			/* If 'tee', continue with original packet */
816			if (clone != NULL) {
817				m = clone;
818				ip = mtod(m, struct ip *);
819				goto pass;
820			}
821			goto done;
822		}
823#endif
824
825		/* IPFIREWALL_FORWARD */
826		/*
827		 * Check dst to make sure it is directly reachable on the
828		 * interface we previously thought it was.
829		 * If it isn't (which may be likely in some situations) we have
830		 * to re-route it (ie, find a route for the next-hop and the
831		 * associated interface) and set them here. This is nested
832		 * forwarding which in most cases is undesirable, except where
833		 * such control is nigh impossible. So we do it here.
834		 * And I'm babbling.
835		 */
836		if (off == 0 && old != dst) { /* FORWARD, dst has changed */
837#if 0
838			/*
839			 * XXX To improve readability, this block should be
840			 * changed into a function call as below:
841			 */
842			error = ip_ipforward(&m, &dst, &ifp);
843			if (error)
844				goto bad;
845			if (m == NULL) /* ip_input consumed the mbuf */
846				goto done;
847#else
848			struct in_ifaddr *ia;
849
850			/*
851			 * XXX sro_fwd below is static, and a pointer
852			 * to it gets passed to routines downstream.
853			 * This could have surprisingly bad results in
854			 * practice, because its content is overwritten
855			 * by subsequent packets.
856			 */
857			/* There must be a better way to do this next line... */
858			static struct route sro_fwd;
859			struct route *ro_fwd = &sro_fwd;
860
861#if 0
862			print_ip("IPFIREWALL_FORWARD: New dst ip: ",
863			    dst->sin_addr, "\n");
864#endif
865
866			/*
867			 * We need to figure out if we have been forwarded
868			 * to a local socket. If so, then we should somehow
869			 * "loop back" to ip_input, and get directed to the
870			 * PCB as if we had received this packet. This is
871			 * because it may be dificult to identify the packets
872			 * you want to forward until they are being output
873			 * and have selected an interface. (e.g. locally
874			 * initiated packets) If we used the loopback inteface,
875			 * we would not be able to control what happens
876			 * as the packet runs through ip_input() as
877			 * it is done through an ISR.
878			 */
879			LIST_FOREACH(ia,
880			    INADDR_HASH(dst->sin_addr.s_addr), ia_hash) {
881				/*
882				 * If the addr to forward to is one
883				 * of ours, we pretend to
884				 * be the destination for this packet.
885				 */
886				if (IA_SIN(ia)->sin_addr.s_addr ==
887						 dst->sin_addr.s_addr)
888					break;
889			}
890			if (ia) {	/* tell ip_input "dont filter" */
891				struct m_hdr tag;
892
893				tag.mh_type = MT_TAG;
894				tag.mh_flags = PACKET_TAG_IPFORWARD;
895				tag.mh_data = (caddr_t)args.next_hop;
896				tag.mh_next = m;
897
898				if (m->m_pkthdr.rcvif == NULL)
899					m->m_pkthdr.rcvif = ifunit("lo0");
900				if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
901					m->m_pkthdr.csum_flags |=
902					    CSUM_DATA_VALID | CSUM_PSEUDO_HDR;
903					m0->m_pkthdr.csum_data = 0xffff;
904				}
905				m->m_pkthdr.csum_flags |=
906				    CSUM_IP_CHECKED | CSUM_IP_VALID;
907				ip->ip_len = htons(ip->ip_len);
908				ip->ip_off = htons(ip->ip_off);
909				ip_input((struct mbuf *)&tag);
910				goto done;
911			}
912			/* Some of the logic for this was
913			 * nicked from above.
914			 *
915			 * This rewrites the cached route in a local PCB.
916			 * Is this what we want to do?
917			 */
918			bcopy(dst, &ro_fwd->ro_dst, sizeof(*dst));
919
920			ro_fwd->ro_rt = 0;
921			rtalloc_ign(ro_fwd, RTF_PRCLONING);
922
923			if (ro_fwd->ro_rt == 0) {
924				ipstat.ips_noroute++;
925				error = EHOSTUNREACH;
926				goto bad;
927			}
928
929			ia = ifatoia(ro_fwd->ro_rt->rt_ifa);
930			ifp = ro_fwd->ro_rt->rt_ifp;
931			ro_fwd->ro_rt->rt_use++;
932			if (ro_fwd->ro_rt->rt_flags & RTF_GATEWAY)
933				dst = (struct sockaddr_in *)
934					ro_fwd->ro_rt->rt_gateway;
935			if (ro_fwd->ro_rt->rt_flags & RTF_HOST)
936				isbroadcast =
937				    (ro_fwd->ro_rt->rt_flags & RTF_BROADCAST);
938			else
939				isbroadcast = in_broadcast(dst->sin_addr, ifp);
940			if (ro->ro_rt)
941				RTFREE(ro->ro_rt);
942			ro->ro_rt = ro_fwd->ro_rt;
943			dst = (struct sockaddr_in *)&ro_fwd->ro_dst;
944
945#endif	/* ... block to be put into a function */
946			/*
947			 * If we added a default src ip earlier,
948			 * which would have been gotten from the-then
949			 * interface, do it again, from the new one.
950			 */
951			if (src_was_INADDR_ANY)
952				ip->ip_src = IA_SIN(ia)->sin_addr;
953			goto pass ;
954		}
955
956                /*
957                 * if we get here, none of the above matches, and
958                 * we have to drop the pkt
959                 */
960		m_freem(m);
961                error = EACCES; /* not sure this is the right error msg */
962                goto done;
963	}
964
965pass:
966	/* 127/8 must not appear on wire - RFC1122. */
967	if ((ntohl(ip->ip_dst.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET ||
968	    (ntohl(ip->ip_src.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET) {
969		if ((ifp->if_flags & IFF_LOOPBACK) == 0) {
970			ipstat.ips_badaddr++;
971			error = EADDRNOTAVAIL;
972			goto bad;
973		}
974	}
975
976	m->m_pkthdr.csum_flags |= CSUM_IP;
977	sw_csum = m->m_pkthdr.csum_flags & ~ifp->if_hwassist;
978	if (sw_csum & CSUM_DELAY_DATA) {
979		in_delayed_cksum(m);
980		sw_csum &= ~CSUM_DELAY_DATA;
981	}
982	m->m_pkthdr.csum_flags &= ifp->if_hwassist;
983
984	/*
985	 * If small enough for interface, or the interface will take
986	 * care of the fragmentation for us, can just send directly.
987	 */
988	if ((u_short)ip->ip_len <= ifp->if_mtu ||
989	    ifp->if_hwassist & CSUM_FRAGMENT) {
990		ip->ip_len = htons(ip->ip_len);
991		ip->ip_off = htons(ip->ip_off);
992		ip->ip_sum = 0;
993		if (sw_csum & CSUM_DELAY_IP)
994			ip->ip_sum = in_cksum(m, hlen);
995
996		/* Record statistics for this interface address. */
997		if (!(flags & IP_FORWARDING) && ia) {
998			ia->ia_ifa.if_opackets++;
999			ia->ia_ifa.if_obytes += m->m_pkthdr.len;
1000		}
1001
1002#ifdef IPSEC
1003		/* clean ipsec history once it goes out of the node */
1004		ipsec_delaux(m);
1005#endif
1006
1007		error = (*ifp->if_output)(ifp, m,
1008				(struct sockaddr *)dst, ro->ro_rt);
1009		goto done;
1010	}
1011	/*
1012	 * Too large for interface; fragment if possible.
1013	 * Must be able to put at least 8 bytes per fragment.
1014	 */
1015	if (ip->ip_off & IP_DF) {
1016		error = EMSGSIZE;
1017		/*
1018		 * This case can happen if the user changed the MTU
1019		 * of an interface after enabling IP on it.  Because
1020		 * most netifs don't keep track of routes pointing to
1021		 * them, there is no way for one to update all its
1022		 * routes when the MTU is changed.
1023		 */
1024		if ((ro->ro_rt->rt_flags & (RTF_UP | RTF_HOST))
1025		    && !(ro->ro_rt->rt_rmx.rmx_locks & RTV_MTU)
1026		    && (ro->ro_rt->rt_rmx.rmx_mtu > ifp->if_mtu)) {
1027			ro->ro_rt->rt_rmx.rmx_mtu = ifp->if_mtu;
1028		}
1029		ipstat.ips_cantfrag++;
1030		goto bad;
1031	}
1032	len = (ifp->if_mtu - hlen) &~ 7;
1033	if (len < 8) {
1034		error = EMSGSIZE;
1035		goto bad;
1036	}
1037
1038	/*
1039	 * if the interface will not calculate checksums on
1040	 * fragmented packets, then do it here.
1041	 */
1042	if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA &&
1043	    (ifp->if_hwassist & CSUM_IP_FRAGS) == 0) {
1044		in_delayed_cksum(m);
1045		m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
1046	}
1047
1048	if (len > PAGE_SIZE) {
1049		/*
1050		 * Fragement large datagrams such that each segment
1051		 * contains a multiple of PAGE_SIZE amount of data,
1052		 * plus headers. This enables a receiver to perform
1053		 * page-flipping zero-copy optimizations.
1054		 */
1055
1056		int newlen;
1057		struct mbuf *mtmp;
1058
1059		for (mtmp = m, off = 0;
1060		     mtmp && ((off + mtmp->m_len) <= ifp->if_mtu);
1061		     mtmp = mtmp->m_next) {
1062			off += mtmp->m_len;
1063		}
1064		/*
1065		 * firstlen (off - hlen) must be aligned on an
1066		 * 8-byte boundary
1067		 */
1068		if (off < hlen)
1069			goto smart_frag_failure;
1070		off = ((off - hlen) & ~7) + hlen;
1071		newlen = (~PAGE_MASK) & ifp->if_mtu;
1072		if ((newlen + sizeof (struct ip)) > ifp->if_mtu) {
1073			/* we failed, go back the default */
1074smart_frag_failure:
1075			newlen = len;
1076			off = hlen + len;
1077		}
1078
1079/*		printf("ipfrag: len = %d, hlen = %d, mhlen = %d, newlen = %d, off = %d\n",
1080		len, hlen, sizeof (struct ip), newlen, off);*/
1081
1082		len = newlen;
1083
1084	} else {
1085		off = hlen + len;
1086	}
1087
1088
1089
1090    {
1091	int mhlen, firstlen = off - hlen;
1092	struct mbuf **mnext = &m->m_nextpkt;
1093	int nfrags = 1;
1094
1095	/*
1096	 * Loop through length of segment after first fragment,
1097	 * make new header and copy data of each part and link onto chain.
1098	 */
1099	m0 = m;
1100	mhlen = sizeof (struct ip);
1101	for (; off < (u_short)ip->ip_len; off += len) {
1102		MGETHDR(m, M_DONTWAIT, MT_HEADER);
1103		if (m == 0) {
1104			error = ENOBUFS;
1105			ipstat.ips_odropped++;
1106			goto sendorfree;
1107		}
1108		m->m_flags |= (m0->m_flags & M_MCAST) | M_FRAG;
1109		m->m_data += max_linkhdr;
1110		mhip = mtod(m, struct ip *);
1111		*mhip = *ip;
1112		if (hlen > sizeof (struct ip)) {
1113			mhlen = ip_optcopy(ip, mhip) + sizeof (struct ip);
1114			mhip->ip_v = IPVERSION;
1115			mhip->ip_hl = mhlen >> 2;
1116		}
1117		m->m_len = mhlen;
1118		mhip->ip_off = ((off - hlen) >> 3) + ip->ip_off;
1119		if (off + len >= (u_short)ip->ip_len)
1120			len = (u_short)ip->ip_len - off;
1121		else
1122			mhip->ip_off |= IP_MF;
1123		mhip->ip_len = htons((u_short)(len + mhlen));
1124		m->m_next = m_copy(m0, off, len);
1125		if (m->m_next == 0) {
1126			(void) m_free(m);
1127			error = ENOBUFS;	/* ??? */
1128			ipstat.ips_odropped++;
1129			goto sendorfree;
1130		}
1131		m->m_pkthdr.len = mhlen + len;
1132		m->m_pkthdr.rcvif = (struct ifnet *)0;
1133#ifdef MAC
1134		mac_create_fragment(m0, m);
1135#endif
1136		m->m_pkthdr.csum_flags = m0->m_pkthdr.csum_flags;
1137		mhip->ip_off = htons(mhip->ip_off);
1138		mhip->ip_sum = 0;
1139		if (sw_csum & CSUM_DELAY_IP)
1140			mhip->ip_sum = in_cksum(m, mhlen);
1141		*mnext = m;
1142		mnext = &m->m_nextpkt;
1143		nfrags++;
1144	}
1145	ipstat.ips_ofragments += nfrags;
1146
1147	/* set first/last markers for fragment chain */
1148	m->m_flags |= M_LASTFRAG;
1149	m0->m_flags |= M_FIRSTFRAG | M_FRAG;
1150	m0->m_pkthdr.csum_data = nfrags;
1151
1152	/*
1153	 * Update first fragment by trimming what's been copied out
1154	 * and updating header, then send each fragment (in order).
1155	 */
1156	m = m0;
1157	m_adj(m, hlen + firstlen - (u_short)ip->ip_len);
1158	m->m_pkthdr.len = hlen + firstlen;
1159	ip->ip_len = htons((u_short)m->m_pkthdr.len);
1160	ip->ip_off |= IP_MF;
1161	ip->ip_off = htons(ip->ip_off);
1162	ip->ip_sum = 0;
1163	if (sw_csum & CSUM_DELAY_IP)
1164		ip->ip_sum = in_cksum(m, hlen);
1165sendorfree:
1166	for (m = m0; m; m = m0) {
1167		m0 = m->m_nextpkt;
1168		m->m_nextpkt = 0;
1169#ifdef IPSEC
1170		/* clean ipsec history once it goes out of the node */
1171		ipsec_delaux(m);
1172#endif
1173		if (error == 0) {
1174			/* Record statistics for this interface address. */
1175			if (ia != NULL) {
1176				ia->ia_ifa.if_opackets++;
1177				ia->ia_ifa.if_obytes += m->m_pkthdr.len;
1178			}
1179
1180			error = (*ifp->if_output)(ifp, m,
1181			    (struct sockaddr *)dst, ro->ro_rt);
1182		} else
1183			m_freem(m);
1184	}
1185
1186	if (error == 0)
1187		ipstat.ips_fragmented++;
1188    }
1189done:
1190#ifdef IPSEC
1191	if (ro == &iproute && ro->ro_rt) {
1192		RTFREE(ro->ro_rt);
1193		ro->ro_rt = NULL;
1194	}
1195	if (sp != NULL) {
1196		KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1197			printf("DP ip_output call free SP:%p\n", sp));
1198		key_freesp(sp);
1199	}
1200#endif /* IPSEC */
1201#ifdef FAST_IPSEC
1202	if (ro == &iproute && ro->ro_rt) {
1203		RTFREE(ro->ro_rt);
1204		ro->ro_rt = NULL;
1205	}
1206	if (sp != NULL)
1207		KEY_FREESP(&sp);
1208#endif /* FAST_IPSEC */
1209	return (error);
1210bad:
1211	m_freem(m);
1212	goto done;
1213}
1214
1215void
1216in_delayed_cksum(struct mbuf *m)
1217{
1218	struct ip *ip;
1219	u_short csum, offset;
1220
1221	ip = mtod(m, struct ip *);
1222	offset = ip->ip_hl << 2 ;
1223	csum = in_cksum_skip(m, ip->ip_len, offset);
1224	if (m->m_pkthdr.csum_flags & CSUM_UDP && csum == 0)
1225		csum = 0xffff;
1226	offset += m->m_pkthdr.csum_data;	/* checksum offset */
1227
1228	if (offset + sizeof(u_short) > m->m_len) {
1229		printf("delayed m_pullup, m->len: %d  off: %d  p: %d\n",
1230		    m->m_len, offset, ip->ip_p);
1231		/*
1232		 * XXX
1233		 * this shouldn't happen, but if it does, the
1234		 * correct behavior may be to insert the checksum
1235		 * in the existing chain instead of rearranging it.
1236		 */
1237		m = m_pullup(m, offset + sizeof(u_short));
1238	}
1239	*(u_short *)(m->m_data + offset) = csum;
1240}
1241
1242/*
1243 * Insert IP options into preformed packet.
1244 * Adjust IP destination as required for IP source routing,
1245 * as indicated by a non-zero in_addr at the start of the options.
1246 *
1247 * XXX This routine assumes that the packet has no options in place.
1248 */
1249static struct mbuf *
1250ip_insertoptions(m, opt, phlen)
1251	register struct mbuf *m;
1252	struct mbuf *opt;
1253	int *phlen;
1254{
1255	register struct ipoption *p = mtod(opt, struct ipoption *);
1256	struct mbuf *n;
1257	register struct ip *ip = mtod(m, struct ip *);
1258	unsigned optlen;
1259
1260	optlen = opt->m_len - sizeof(p->ipopt_dst);
1261	if (optlen + (u_short)ip->ip_len > IP_MAXPACKET) {
1262		*phlen = 0;
1263		return (m);		/* XXX should fail */
1264	}
1265	if (p->ipopt_dst.s_addr)
1266		ip->ip_dst = p->ipopt_dst;
1267	if (m->m_flags & M_EXT || m->m_data - optlen < m->m_pktdat) {
1268		MGETHDR(n, M_DONTWAIT, MT_HEADER);
1269		if (n == 0) {
1270			*phlen = 0;
1271			return (m);
1272		}
1273		n->m_pkthdr.rcvif = (struct ifnet *)0;
1274#ifdef MAC
1275		mac_create_mbuf_from_mbuf(m, n);
1276#endif
1277		n->m_pkthdr.len = m->m_pkthdr.len + optlen;
1278		m->m_len -= sizeof(struct ip);
1279		m->m_data += sizeof(struct ip);
1280		n->m_next = m;
1281		m = n;
1282		m->m_len = optlen + sizeof(struct ip);
1283		m->m_data += max_linkhdr;
1284		(void)memcpy(mtod(m, void *), ip, sizeof(struct ip));
1285	} else {
1286		m->m_data -= optlen;
1287		m->m_len += optlen;
1288		m->m_pkthdr.len += optlen;
1289		ovbcopy((caddr_t)ip, mtod(m, caddr_t), sizeof(struct ip));
1290	}
1291	ip = mtod(m, struct ip *);
1292	bcopy(p->ipopt_list, ip + 1, optlen);
1293	*phlen = sizeof(struct ip) + optlen;
1294	ip->ip_v = IPVERSION;
1295	ip->ip_hl = *phlen >> 2;
1296	ip->ip_len += optlen;
1297	return (m);
1298}
1299
1300/*
1301 * Copy options from ip to jp,
1302 * omitting those not copied during fragmentation.
1303 */
1304int
1305ip_optcopy(ip, jp)
1306	struct ip *ip, *jp;
1307{
1308	register u_char *cp, *dp;
1309	int opt, optlen, cnt;
1310
1311	cp = (u_char *)(ip + 1);
1312	dp = (u_char *)(jp + 1);
1313	cnt = (ip->ip_hl << 2) - sizeof (struct ip);
1314	for (; cnt > 0; cnt -= optlen, cp += optlen) {
1315		opt = cp[0];
1316		if (opt == IPOPT_EOL)
1317			break;
1318		if (opt == IPOPT_NOP) {
1319			/* Preserve for IP mcast tunnel's LSRR alignment. */
1320			*dp++ = IPOPT_NOP;
1321			optlen = 1;
1322			continue;
1323		}
1324
1325		KASSERT(cnt >= IPOPT_OLEN + sizeof(*cp),
1326		    ("ip_optcopy: malformed ipv4 option"));
1327		optlen = cp[IPOPT_OLEN];
1328		KASSERT(optlen >= IPOPT_OLEN + sizeof(*cp) && optlen <= cnt,
1329		    ("ip_optcopy: malformed ipv4 option"));
1330
1331		/* bogus lengths should have been caught by ip_dooptions */
1332		if (optlen > cnt)
1333			optlen = cnt;
1334		if (IPOPT_COPIED(opt)) {
1335			bcopy(cp, dp, optlen);
1336			dp += optlen;
1337		}
1338	}
1339	for (optlen = dp - (u_char *)(jp+1); optlen & 0x3; optlen++)
1340		*dp++ = IPOPT_EOL;
1341	return (optlen);
1342}
1343
1344/*
1345 * IP socket option processing.
1346 */
1347int
1348ip_ctloutput(so, sopt)
1349	struct socket *so;
1350	struct sockopt *sopt;
1351{
1352	struct	inpcb *inp = sotoinpcb(so);
1353	int	error, optval;
1354
1355	error = optval = 0;
1356	if (sopt->sopt_level != IPPROTO_IP) {
1357		return (EINVAL);
1358	}
1359
1360	switch (sopt->sopt_dir) {
1361	case SOPT_SET:
1362		switch (sopt->sopt_name) {
1363		case IP_OPTIONS:
1364#ifdef notyet
1365		case IP_RETOPTS:
1366#endif
1367		{
1368			struct mbuf *m;
1369			if (sopt->sopt_valsize > MLEN) {
1370				error = EMSGSIZE;
1371				break;
1372			}
1373			MGET(m, sopt->sopt_td ? M_TRYWAIT : M_DONTWAIT, MT_HEADER);
1374			if (m == 0) {
1375				error = ENOBUFS;
1376				break;
1377			}
1378			m->m_len = sopt->sopt_valsize;
1379			error = sooptcopyin(sopt, mtod(m, char *), m->m_len,
1380					    m->m_len);
1381
1382			return (ip_pcbopts(sopt->sopt_name, &inp->inp_options,
1383					   m));
1384		}
1385
1386		case IP_TOS:
1387		case IP_TTL:
1388		case IP_RECVOPTS:
1389		case IP_RECVRETOPTS:
1390		case IP_RECVDSTADDR:
1391		case IP_RECVIF:
1392		case IP_FAITH:
1393			error = sooptcopyin(sopt, &optval, sizeof optval,
1394					    sizeof optval);
1395			if (error)
1396				break;
1397
1398			switch (sopt->sopt_name) {
1399			case IP_TOS:
1400				inp->inp_ip_tos = optval;
1401				break;
1402
1403			case IP_TTL:
1404				inp->inp_ip_ttl = optval;
1405				break;
1406#define	OPTSET(bit) \
1407	if (optval) \
1408		inp->inp_flags |= bit; \
1409	else \
1410		inp->inp_flags &= ~bit;
1411
1412			case IP_RECVOPTS:
1413				OPTSET(INP_RECVOPTS);
1414				break;
1415
1416			case IP_RECVRETOPTS:
1417				OPTSET(INP_RECVRETOPTS);
1418				break;
1419
1420			case IP_RECVDSTADDR:
1421				OPTSET(INP_RECVDSTADDR);
1422				break;
1423
1424			case IP_RECVIF:
1425				OPTSET(INP_RECVIF);
1426				break;
1427
1428			case IP_FAITH:
1429				OPTSET(INP_FAITH);
1430				break;
1431			}
1432			break;
1433#undef OPTSET
1434
1435		case IP_MULTICAST_IF:
1436		case IP_MULTICAST_VIF:
1437		case IP_MULTICAST_TTL:
1438		case IP_MULTICAST_LOOP:
1439		case IP_ADD_MEMBERSHIP:
1440		case IP_DROP_MEMBERSHIP:
1441			error = ip_setmoptions(sopt, &inp->inp_moptions);
1442			break;
1443
1444		case IP_PORTRANGE:
1445			error = sooptcopyin(sopt, &optval, sizeof optval,
1446					    sizeof optval);
1447			if (error)
1448				break;
1449
1450			switch (optval) {
1451			case IP_PORTRANGE_DEFAULT:
1452				inp->inp_flags &= ~(INP_LOWPORT);
1453				inp->inp_flags &= ~(INP_HIGHPORT);
1454				break;
1455
1456			case IP_PORTRANGE_HIGH:
1457				inp->inp_flags &= ~(INP_LOWPORT);
1458				inp->inp_flags |= INP_HIGHPORT;
1459				break;
1460
1461			case IP_PORTRANGE_LOW:
1462				inp->inp_flags &= ~(INP_HIGHPORT);
1463				inp->inp_flags |= INP_LOWPORT;
1464				break;
1465
1466			default:
1467				error = EINVAL;
1468				break;
1469			}
1470			break;
1471
1472#if defined(IPSEC) || defined(FAST_IPSEC)
1473		case IP_IPSEC_POLICY:
1474		{
1475			caddr_t req;
1476			size_t len = 0;
1477			int priv;
1478			struct mbuf *m;
1479			int optname;
1480
1481			if ((error = soopt_getm(sopt, &m)) != 0) /* XXX */
1482				break;
1483			if ((error = soopt_mcopyin(sopt, m)) != 0) /* XXX */
1484				break;
1485			priv = (sopt->sopt_td != NULL &&
1486				suser(sopt->sopt_td) != 0) ? 0 : 1;
1487			req = mtod(m, caddr_t);
1488			len = m->m_len;
1489			optname = sopt->sopt_name;
1490			error = ipsec4_set_policy(inp, optname, req, len, priv);
1491			m_freem(m);
1492			break;
1493		}
1494#endif /*IPSEC*/
1495
1496		default:
1497			error = ENOPROTOOPT;
1498			break;
1499		}
1500		break;
1501
1502	case SOPT_GET:
1503		switch (sopt->sopt_name) {
1504		case IP_OPTIONS:
1505		case IP_RETOPTS:
1506			if (inp->inp_options)
1507				error = sooptcopyout(sopt,
1508						     mtod(inp->inp_options,
1509							  char *),
1510						     inp->inp_options->m_len);
1511			else
1512				sopt->sopt_valsize = 0;
1513			break;
1514
1515		case IP_TOS:
1516		case IP_TTL:
1517		case IP_RECVOPTS:
1518		case IP_RECVRETOPTS:
1519		case IP_RECVDSTADDR:
1520		case IP_RECVIF:
1521		case IP_PORTRANGE:
1522		case IP_FAITH:
1523			switch (sopt->sopt_name) {
1524
1525			case IP_TOS:
1526				optval = inp->inp_ip_tos;
1527				break;
1528
1529			case IP_TTL:
1530				optval = inp->inp_ip_ttl;
1531				break;
1532
1533#define	OPTBIT(bit)	(inp->inp_flags & bit ? 1 : 0)
1534
1535			case IP_RECVOPTS:
1536				optval = OPTBIT(INP_RECVOPTS);
1537				break;
1538
1539			case IP_RECVRETOPTS:
1540				optval = OPTBIT(INP_RECVRETOPTS);
1541				break;
1542
1543			case IP_RECVDSTADDR:
1544				optval = OPTBIT(INP_RECVDSTADDR);
1545				break;
1546
1547			case IP_RECVIF:
1548				optval = OPTBIT(INP_RECVIF);
1549				break;
1550
1551			case IP_PORTRANGE:
1552				if (inp->inp_flags & INP_HIGHPORT)
1553					optval = IP_PORTRANGE_HIGH;
1554				else if (inp->inp_flags & INP_LOWPORT)
1555					optval = IP_PORTRANGE_LOW;
1556				else
1557					optval = 0;
1558				break;
1559
1560			case IP_FAITH:
1561				optval = OPTBIT(INP_FAITH);
1562				break;
1563			}
1564			error = sooptcopyout(sopt, &optval, sizeof optval);
1565			break;
1566
1567		case IP_MULTICAST_IF:
1568		case IP_MULTICAST_VIF:
1569		case IP_MULTICAST_TTL:
1570		case IP_MULTICAST_LOOP:
1571		case IP_ADD_MEMBERSHIP:
1572		case IP_DROP_MEMBERSHIP:
1573			error = ip_getmoptions(sopt, inp->inp_moptions);
1574			break;
1575
1576#if defined(IPSEC) || defined(FAST_IPSEC)
1577		case IP_IPSEC_POLICY:
1578		{
1579			struct mbuf *m = NULL;
1580			caddr_t req = NULL;
1581			size_t len = 0;
1582
1583			if (m != 0) {
1584				req = mtod(m, caddr_t);
1585				len = m->m_len;
1586			}
1587			error = ipsec4_get_policy(sotoinpcb(so), req, len, &m);
1588			if (error == 0)
1589				error = soopt_mcopyout(sopt, m); /* XXX */
1590			if (error == 0)
1591				m_freem(m);
1592			break;
1593		}
1594#endif /*IPSEC*/
1595
1596		default:
1597			error = ENOPROTOOPT;
1598			break;
1599		}
1600		break;
1601	}
1602	return (error);
1603}
1604
1605/*
1606 * Set up IP options in pcb for insertion in output packets.
1607 * Store in mbuf with pointer in pcbopt, adding pseudo-option
1608 * with destination address if source routed.
1609 */
1610static int
1611ip_pcbopts(optname, pcbopt, m)
1612	int optname;
1613	struct mbuf **pcbopt;
1614	register struct mbuf *m;
1615{
1616	register int cnt, optlen;
1617	register u_char *cp;
1618	u_char opt;
1619
1620	/* turn off any old options */
1621	if (*pcbopt)
1622		(void)m_free(*pcbopt);
1623	*pcbopt = 0;
1624	if (m == (struct mbuf *)0 || m->m_len == 0) {
1625		/*
1626		 * Only turning off any previous options.
1627		 */
1628		if (m)
1629			(void)m_free(m);
1630		return (0);
1631	}
1632
1633	if (m->m_len % sizeof(int32_t))
1634		goto bad;
1635	/*
1636	 * IP first-hop destination address will be stored before
1637	 * actual options; move other options back
1638	 * and clear it when none present.
1639	 */
1640	if (m->m_data + m->m_len + sizeof(struct in_addr) >= &m->m_dat[MLEN])
1641		goto bad;
1642	cnt = m->m_len;
1643	m->m_len += sizeof(struct in_addr);
1644	cp = mtod(m, u_char *) + sizeof(struct in_addr);
1645	ovbcopy(mtod(m, caddr_t), (caddr_t)cp, (unsigned)cnt);
1646	bzero(mtod(m, caddr_t), sizeof(struct in_addr));
1647
1648	for (; cnt > 0; cnt -= optlen, cp += optlen) {
1649		opt = cp[IPOPT_OPTVAL];
1650		if (opt == IPOPT_EOL)
1651			break;
1652		if (opt == IPOPT_NOP)
1653			optlen = 1;
1654		else {
1655			if (cnt < IPOPT_OLEN + sizeof(*cp))
1656				goto bad;
1657			optlen = cp[IPOPT_OLEN];
1658			if (optlen < IPOPT_OLEN + sizeof(*cp) || optlen > cnt)
1659				goto bad;
1660		}
1661		switch (opt) {
1662
1663		default:
1664			break;
1665
1666		case IPOPT_LSRR:
1667		case IPOPT_SSRR:
1668			/*
1669			 * user process specifies route as:
1670			 *	->A->B->C->D
1671			 * D must be our final destination (but we can't
1672			 * check that since we may not have connected yet).
1673			 * A is first hop destination, which doesn't appear in
1674			 * actual IP option, but is stored before the options.
1675			 */
1676			if (optlen < IPOPT_MINOFF - 1 + sizeof(struct in_addr))
1677				goto bad;
1678			m->m_len -= sizeof(struct in_addr);
1679			cnt -= sizeof(struct in_addr);
1680			optlen -= sizeof(struct in_addr);
1681			cp[IPOPT_OLEN] = optlen;
1682			/*
1683			 * Move first hop before start of options.
1684			 */
1685			bcopy((caddr_t)&cp[IPOPT_OFFSET+1], mtod(m, caddr_t),
1686			    sizeof(struct in_addr));
1687			/*
1688			 * Then copy rest of options back
1689			 * to close up the deleted entry.
1690			 */
1691			ovbcopy((caddr_t)(&cp[IPOPT_OFFSET+1] +
1692			    sizeof(struct in_addr)),
1693			    (caddr_t)&cp[IPOPT_OFFSET+1],
1694			    (unsigned)cnt + sizeof(struct in_addr));
1695			break;
1696		}
1697	}
1698	if (m->m_len > MAX_IPOPTLEN + sizeof(struct in_addr))
1699		goto bad;
1700	*pcbopt = m;
1701	return (0);
1702
1703bad:
1704	(void)m_free(m);
1705	return (EINVAL);
1706}
1707
1708/*
1709 * XXX
1710 * The whole multicast option thing needs to be re-thought.
1711 * Several of these options are equally applicable to non-multicast
1712 * transmission, and one (IP_MULTICAST_TTL) totally duplicates a
1713 * standard option (IP_TTL).
1714 */
1715
1716/*
1717 * following RFC1724 section 3.3, 0.0.0.0/8 is interpreted as interface index.
1718 */
1719static struct ifnet *
1720ip_multicast_if(a, ifindexp)
1721	struct in_addr *a;
1722	int *ifindexp;
1723{
1724	int ifindex;
1725	struct ifnet *ifp;
1726
1727	if (ifindexp)
1728		*ifindexp = 0;
1729	if (ntohl(a->s_addr) >> 24 == 0) {
1730		ifindex = ntohl(a->s_addr) & 0xffffff;
1731		if (ifindex < 0 || if_index < ifindex)
1732			return NULL;
1733		ifp = ifnet_byindex(ifindex);
1734		if (ifindexp)
1735			*ifindexp = ifindex;
1736	} else {
1737		INADDR_TO_IFP(*a, ifp);
1738	}
1739	return ifp;
1740}
1741
1742/*
1743 * Set the IP multicast options in response to user setsockopt().
1744 */
1745static int
1746ip_setmoptions(sopt, imop)
1747	struct sockopt *sopt;
1748	struct ip_moptions **imop;
1749{
1750	int error = 0;
1751	int i;
1752	struct in_addr addr;
1753	struct ip_mreq mreq;
1754	struct ifnet *ifp;
1755	struct ip_moptions *imo = *imop;
1756	struct route ro;
1757	struct sockaddr_in *dst;
1758	int ifindex;
1759	int s;
1760
1761	if (imo == NULL) {
1762		/*
1763		 * No multicast option buffer attached to the pcb;
1764		 * allocate one and initialize to default values.
1765		 */
1766		imo = (struct ip_moptions*)malloc(sizeof(*imo), M_IPMOPTS,
1767		    M_WAITOK);
1768
1769		if (imo == NULL)
1770			return (ENOBUFS);
1771		*imop = imo;
1772		imo->imo_multicast_ifp = NULL;
1773		imo->imo_multicast_addr.s_addr = INADDR_ANY;
1774		imo->imo_multicast_vif = -1;
1775		imo->imo_multicast_ttl = IP_DEFAULT_MULTICAST_TTL;
1776		imo->imo_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
1777		imo->imo_num_memberships = 0;
1778	}
1779
1780	switch (sopt->sopt_name) {
1781	/* store an index number for the vif you wanna use in the send */
1782	case IP_MULTICAST_VIF:
1783		if (legal_vif_num == 0) {
1784			error = EOPNOTSUPP;
1785			break;
1786		}
1787		error = sooptcopyin(sopt, &i, sizeof i, sizeof i);
1788		if (error)
1789			break;
1790		if (!legal_vif_num(i) && (i != -1)) {
1791			error = EINVAL;
1792			break;
1793		}
1794		imo->imo_multicast_vif = i;
1795		break;
1796
1797	case IP_MULTICAST_IF:
1798		/*
1799		 * Select the interface for outgoing multicast packets.
1800		 */
1801		error = sooptcopyin(sopt, &addr, sizeof addr, sizeof addr);
1802		if (error)
1803			break;
1804		/*
1805		 * INADDR_ANY is used to remove a previous selection.
1806		 * When no interface is selected, a default one is
1807		 * chosen every time a multicast packet is sent.
1808		 */
1809		if (addr.s_addr == INADDR_ANY) {
1810			imo->imo_multicast_ifp = NULL;
1811			break;
1812		}
1813		/*
1814		 * The selected interface is identified by its local
1815		 * IP address.  Find the interface and confirm that
1816		 * it supports multicasting.
1817		 */
1818		s = splimp();
1819		ifp = ip_multicast_if(&addr, &ifindex);
1820		if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0) {
1821			splx(s);
1822			error = EADDRNOTAVAIL;
1823			break;
1824		}
1825		imo->imo_multicast_ifp = ifp;
1826		if (ifindex)
1827			imo->imo_multicast_addr = addr;
1828		else
1829			imo->imo_multicast_addr.s_addr = INADDR_ANY;
1830		splx(s);
1831		break;
1832
1833	case IP_MULTICAST_TTL:
1834		/*
1835		 * Set the IP time-to-live for outgoing multicast packets.
1836		 * The original multicast API required a char argument,
1837		 * which is inconsistent with the rest of the socket API.
1838		 * We allow either a char or an int.
1839		 */
1840		if (sopt->sopt_valsize == 1) {
1841			u_char ttl;
1842			error = sooptcopyin(sopt, &ttl, 1, 1);
1843			if (error)
1844				break;
1845			imo->imo_multicast_ttl = ttl;
1846		} else {
1847			u_int ttl;
1848			error = sooptcopyin(sopt, &ttl, sizeof ttl,
1849					    sizeof ttl);
1850			if (error)
1851				break;
1852			if (ttl > 255)
1853				error = EINVAL;
1854			else
1855				imo->imo_multicast_ttl = ttl;
1856		}
1857		break;
1858
1859	case IP_MULTICAST_LOOP:
1860		/*
1861		 * Set the loopback flag for outgoing multicast packets.
1862		 * Must be zero or one.  The original multicast API required a
1863		 * char argument, which is inconsistent with the rest
1864		 * of the socket API.  We allow either a char or an int.
1865		 */
1866		if (sopt->sopt_valsize == 1) {
1867			u_char loop;
1868			error = sooptcopyin(sopt, &loop, 1, 1);
1869			if (error)
1870				break;
1871			imo->imo_multicast_loop = !!loop;
1872		} else {
1873			u_int loop;
1874			error = sooptcopyin(sopt, &loop, sizeof loop,
1875					    sizeof loop);
1876			if (error)
1877				break;
1878			imo->imo_multicast_loop = !!loop;
1879		}
1880		break;
1881
1882	case IP_ADD_MEMBERSHIP:
1883		/*
1884		 * Add a multicast group membership.
1885		 * Group must be a valid IP multicast address.
1886		 */
1887		error = sooptcopyin(sopt, &mreq, sizeof mreq, sizeof mreq);
1888		if (error)
1889			break;
1890
1891		if (!IN_MULTICAST(ntohl(mreq.imr_multiaddr.s_addr))) {
1892			error = EINVAL;
1893			break;
1894		}
1895		s = splimp();
1896		/*
1897		 * If no interface address was provided, use the interface of
1898		 * the route to the given multicast address.
1899		 */
1900		if (mreq.imr_interface.s_addr == INADDR_ANY) {
1901			bzero((caddr_t)&ro, sizeof(ro));
1902			dst = (struct sockaddr_in *)&ro.ro_dst;
1903			dst->sin_len = sizeof(*dst);
1904			dst->sin_family = AF_INET;
1905			dst->sin_addr = mreq.imr_multiaddr;
1906			rtalloc(&ro);
1907			if (ro.ro_rt == NULL) {
1908				error = EADDRNOTAVAIL;
1909				splx(s);
1910				break;
1911			}
1912			ifp = ro.ro_rt->rt_ifp;
1913			rtfree(ro.ro_rt);
1914		}
1915		else {
1916			ifp = ip_multicast_if(&mreq.imr_interface, NULL);
1917		}
1918
1919		/*
1920		 * See if we found an interface, and confirm that it
1921		 * supports multicast.
1922		 */
1923		if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0) {
1924			error = EADDRNOTAVAIL;
1925			splx(s);
1926			break;
1927		}
1928		/*
1929		 * See if the membership already exists or if all the
1930		 * membership slots are full.
1931		 */
1932		for (i = 0; i < imo->imo_num_memberships; ++i) {
1933			if (imo->imo_membership[i]->inm_ifp == ifp &&
1934			    imo->imo_membership[i]->inm_addr.s_addr
1935						== mreq.imr_multiaddr.s_addr)
1936				break;
1937		}
1938		if (i < imo->imo_num_memberships) {
1939			error = EADDRINUSE;
1940			splx(s);
1941			break;
1942		}
1943		if (i == IP_MAX_MEMBERSHIPS) {
1944			error = ETOOMANYREFS;
1945			splx(s);
1946			break;
1947		}
1948		/*
1949		 * Everything looks good; add a new record to the multicast
1950		 * address list for the given interface.
1951		 */
1952		if ((imo->imo_membership[i] =
1953		    in_addmulti(&mreq.imr_multiaddr, ifp)) == NULL) {
1954			error = ENOBUFS;
1955			splx(s);
1956			break;
1957		}
1958		++imo->imo_num_memberships;
1959		splx(s);
1960		break;
1961
1962	case IP_DROP_MEMBERSHIP:
1963		/*
1964		 * Drop a multicast group membership.
1965		 * Group must be a valid IP multicast address.
1966		 */
1967		error = sooptcopyin(sopt, &mreq, sizeof mreq, sizeof mreq);
1968		if (error)
1969			break;
1970
1971		if (!IN_MULTICAST(ntohl(mreq.imr_multiaddr.s_addr))) {
1972			error = EINVAL;
1973			break;
1974		}
1975
1976		s = splimp();
1977		/*
1978		 * If an interface address was specified, get a pointer
1979		 * to its ifnet structure.
1980		 */
1981		if (mreq.imr_interface.s_addr == INADDR_ANY)
1982			ifp = NULL;
1983		else {
1984			ifp = ip_multicast_if(&mreq.imr_interface, NULL);
1985			if (ifp == NULL) {
1986				error = EADDRNOTAVAIL;
1987				splx(s);
1988				break;
1989			}
1990		}
1991		/*
1992		 * Find the membership in the membership array.
1993		 */
1994		for (i = 0; i < imo->imo_num_memberships; ++i) {
1995			if ((ifp == NULL ||
1996			     imo->imo_membership[i]->inm_ifp == ifp) &&
1997			     imo->imo_membership[i]->inm_addr.s_addr ==
1998			     mreq.imr_multiaddr.s_addr)
1999				break;
2000		}
2001		if (i == imo->imo_num_memberships) {
2002			error = EADDRNOTAVAIL;
2003			splx(s);
2004			break;
2005		}
2006		/*
2007		 * Give up the multicast address record to which the
2008		 * membership points.
2009		 */
2010		in_delmulti(imo->imo_membership[i]);
2011		/*
2012		 * Remove the gap in the membership array.
2013		 */
2014		for (++i; i < imo->imo_num_memberships; ++i)
2015			imo->imo_membership[i-1] = imo->imo_membership[i];
2016		--imo->imo_num_memberships;
2017		splx(s);
2018		break;
2019
2020	default:
2021		error = EOPNOTSUPP;
2022		break;
2023	}
2024
2025	/*
2026	 * If all options have default values, no need to keep the mbuf.
2027	 */
2028	if (imo->imo_multicast_ifp == NULL &&
2029	    imo->imo_multicast_vif == -1 &&
2030	    imo->imo_multicast_ttl == IP_DEFAULT_MULTICAST_TTL &&
2031	    imo->imo_multicast_loop == IP_DEFAULT_MULTICAST_LOOP &&
2032	    imo->imo_num_memberships == 0) {
2033		free(*imop, M_IPMOPTS);
2034		*imop = NULL;
2035	}
2036
2037	return (error);
2038}
2039
2040/*
2041 * Return the IP multicast options in response to user getsockopt().
2042 */
2043static int
2044ip_getmoptions(sopt, imo)
2045	struct sockopt *sopt;
2046	register struct ip_moptions *imo;
2047{
2048	struct in_addr addr;
2049	struct in_ifaddr *ia;
2050	int error, optval;
2051	u_char coptval;
2052
2053	error = 0;
2054	switch (sopt->sopt_name) {
2055	case IP_MULTICAST_VIF:
2056		if (imo != NULL)
2057			optval = imo->imo_multicast_vif;
2058		else
2059			optval = -1;
2060		error = sooptcopyout(sopt, &optval, sizeof optval);
2061		break;
2062
2063	case IP_MULTICAST_IF:
2064		if (imo == NULL || imo->imo_multicast_ifp == NULL)
2065			addr.s_addr = INADDR_ANY;
2066		else if (imo->imo_multicast_addr.s_addr) {
2067			/* return the value user has set */
2068			addr = imo->imo_multicast_addr;
2069		} else {
2070			IFP_TO_IA(imo->imo_multicast_ifp, ia);
2071			addr.s_addr = (ia == NULL) ? INADDR_ANY
2072				: IA_SIN(ia)->sin_addr.s_addr;
2073		}
2074		error = sooptcopyout(sopt, &addr, sizeof addr);
2075		break;
2076
2077	case IP_MULTICAST_TTL:
2078		if (imo == 0)
2079			optval = coptval = IP_DEFAULT_MULTICAST_TTL;
2080		else
2081			optval = coptval = imo->imo_multicast_ttl;
2082		if (sopt->sopt_valsize == 1)
2083			error = sooptcopyout(sopt, &coptval, 1);
2084		else
2085			error = sooptcopyout(sopt, &optval, sizeof optval);
2086		break;
2087
2088	case IP_MULTICAST_LOOP:
2089		if (imo == 0)
2090			optval = coptval = IP_DEFAULT_MULTICAST_LOOP;
2091		else
2092			optval = coptval = imo->imo_multicast_loop;
2093		if (sopt->sopt_valsize == 1)
2094			error = sooptcopyout(sopt, &coptval, 1);
2095		else
2096			error = sooptcopyout(sopt, &optval, sizeof optval);
2097		break;
2098
2099	default:
2100		error = ENOPROTOOPT;
2101		break;
2102	}
2103	return (error);
2104}
2105
2106/*
2107 * Discard the IP multicast options.
2108 */
2109void
2110ip_freemoptions(imo)
2111	register struct ip_moptions *imo;
2112{
2113	register int i;
2114
2115	if (imo != NULL) {
2116		for (i = 0; i < imo->imo_num_memberships; ++i)
2117			in_delmulti(imo->imo_membership[i]);
2118		free(imo, M_IPMOPTS);
2119	}
2120}
2121
2122/*
2123 * Routine called from ip_output() to loop back a copy of an IP multicast
2124 * packet to the input queue of a specified interface.  Note that this
2125 * calls the output routine of the loopback "driver", but with an interface
2126 * pointer that might NOT be a loopback interface -- evil, but easier than
2127 * replicating that code here.
2128 */
2129static void
2130ip_mloopback(ifp, m, dst, hlen)
2131	struct ifnet *ifp;
2132	register struct mbuf *m;
2133	register struct sockaddr_in *dst;
2134	int hlen;
2135{
2136	register struct ip *ip;
2137	struct mbuf *copym;
2138
2139	copym = m_copy(m, 0, M_COPYALL);
2140	if (copym != NULL && (copym->m_flags & M_EXT || copym->m_len < hlen))
2141		copym = m_pullup(copym, hlen);
2142	if (copym != NULL) {
2143		/*
2144		 * We don't bother to fragment if the IP length is greater
2145		 * than the interface's MTU.  Can this possibly matter?
2146		 */
2147		ip = mtod(copym, struct ip *);
2148		ip->ip_len = htons(ip->ip_len);
2149		ip->ip_off = htons(ip->ip_off);
2150		ip->ip_sum = 0;
2151		ip->ip_sum = in_cksum(copym, hlen);
2152		/*
2153		 * NB:
2154		 * It's not clear whether there are any lingering
2155		 * reentrancy problems in other areas which might
2156		 * be exposed by using ip_input directly (in
2157		 * particular, everything which modifies the packet
2158		 * in-place).  Yet another option is using the
2159		 * protosw directly to deliver the looped back
2160		 * packet.  For the moment, we'll err on the side
2161		 * of safety by using if_simloop().
2162		 */
2163#if 1 /* XXX */
2164		if (dst->sin_family != AF_INET) {
2165			printf("ip_mloopback: bad address family %d\n",
2166						dst->sin_family);
2167			dst->sin_family = AF_INET;
2168		}
2169#endif
2170
2171#ifdef notdef
2172		copym->m_pkthdr.rcvif = ifp;
2173		ip_input(copym);
2174#else
2175		/* if the checksum hasn't been computed, mark it as valid */
2176		if (copym->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
2177			copym->m_pkthdr.csum_flags |=
2178			    CSUM_DATA_VALID | CSUM_PSEUDO_HDR;
2179			copym->m_pkthdr.csum_data = 0xffff;
2180		}
2181		if_simloop(ifp, copym, dst->sin_family, 0);
2182#endif
2183	}
2184}
2185