ip_output.c revision 139310
1/*
2 * Copyright (c) 1982, 1986, 1988, 1990, 1993
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 * 4. Neither the name of the University nor the names of its contributors
14 *    may be used to endorse or promote products derived from this software
15 *    without specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 * SUCH DAMAGE.
28 *
29 *	@(#)ip_output.c	8.3 (Berkeley) 1/21/94
30 * $FreeBSD: head/sys/netinet/ip_output.c 139310 2004-12-25 22:59:42Z rwatson $
31 */
32
33#include "opt_ipfw.h"
34#include "opt_ipsec.h"
35#include "opt_mac.h"
36#include "opt_mbuf_stress_test.h"
37
38#include <sys/param.h>
39#include <sys/systm.h>
40#include <sys/kernel.h>
41#include <sys/mac.h>
42#include <sys/malloc.h>
43#include <sys/mbuf.h>
44#include <sys/protosw.h>
45#include <sys/socket.h>
46#include <sys/socketvar.h>
47#include <sys/sysctl.h>
48
49#include <net/if.h>
50#include <net/netisr.h>
51#include <net/pfil.h>
52#include <net/route.h>
53
54#include <netinet/in.h>
55#include <netinet/in_systm.h>
56#include <netinet/ip.h>
57#include <netinet/in_pcb.h>
58#include <netinet/in_var.h>
59#include <netinet/ip_var.h>
60
61#include <machine/in_cksum.h>
62
63static MALLOC_DEFINE(M_IPMOPTS, "ip_moptions", "internet multicast options");
64
65#ifdef IPSEC
66#include <netinet6/ipsec.h>
67#include <netkey/key.h>
68#ifdef IPSEC_DEBUG
69#include <netkey/key_debug.h>
70#else
71#define	KEYDEBUG(lev,arg)
72#endif
73#endif /*IPSEC*/
74
75#ifdef FAST_IPSEC
76#include <netipsec/ipsec.h>
77#include <netipsec/xform.h>
78#include <netipsec/key.h>
79#endif /*FAST_IPSEC*/
80
81#define print_ip(x, a, y)	 printf("%s %d.%d.%d.%d%s",\
82				x, (ntohl(a.s_addr)>>24)&0xFF,\
83				  (ntohl(a.s_addr)>>16)&0xFF,\
84				  (ntohl(a.s_addr)>>8)&0xFF,\
85				  (ntohl(a.s_addr))&0xFF, y);
86
87u_short ip_id;
88
89#ifdef MBUF_STRESS_TEST
90int mbuf_frag_size = 0;
91SYSCTL_INT(_net_inet_ip, OID_AUTO, mbuf_frag_size, CTLFLAG_RW,
92	&mbuf_frag_size, 0, "Fragment outgoing mbufs to this size");
93#endif
94
95static struct mbuf *ip_insertoptions(struct mbuf *, struct mbuf *, int *);
96static struct ifnet *ip_multicast_if(struct in_addr *, int *);
97static void	ip_mloopback
98	(struct ifnet *, struct mbuf *, struct sockaddr_in *, int);
99static int	ip_getmoptions(struct inpcb *, struct sockopt *);
100static int	ip_pcbopts(struct inpcb *, int, struct mbuf *);
101static int	ip_setmoptions(struct inpcb *, struct sockopt *);
102
103int	ip_optcopy(struct ip *, struct ip *);
104
105
106extern	struct protosw inetsw[];
107
108/*
109 * IP output.  The packet in mbuf chain m contains a skeletal IP
110 * header (with len, off, ttl, proto, tos, src, dst).
111 * The mbuf chain containing the packet will be freed.
112 * The mbuf opt, if present, will not be freed.
113 * In the IP forwarding case, the packet will arrive with options already
114 * inserted, so must have a NULL opt pointer.
115 */
116int
117ip_output(struct mbuf *m, struct mbuf *opt, struct route *ro,
118	int flags, struct ip_moptions *imo, struct inpcb *inp)
119{
120	struct ip *ip;
121	struct ifnet *ifp = NULL;	/* keep compiler happy */
122	struct mbuf *m0;
123	int hlen = sizeof (struct ip);
124	int len, error = 0;
125	struct sockaddr_in *dst = NULL;	/* keep compiler happy */
126	struct in_ifaddr *ia = NULL;
127	int isbroadcast, sw_csum;
128	struct route iproute;
129	struct in_addr odst;
130#ifdef IPFIREWALL_FORWARD
131	struct m_tag *fwd_tag = NULL;
132#endif
133#ifdef IPSEC
134	struct secpolicy *sp = NULL;
135#endif
136#ifdef FAST_IPSEC
137	struct secpolicy *sp = NULL;
138	struct tdb_ident *tdbi;
139	struct m_tag *mtag;
140	int s;
141#endif /* FAST_IPSEC */
142
143	M_ASSERTPKTHDR(m);
144
145	if (ro == NULL) {
146		ro = &iproute;
147		bzero(ro, sizeof (*ro));
148	}
149
150	if (inp != NULL)
151		INP_LOCK_ASSERT(inp);
152
153	if (opt) {
154		len = 0;
155		m = ip_insertoptions(m, opt, &len);
156		if (len != 0)
157			hlen = len;
158	}
159	ip = mtod(m, struct ip *);
160
161	/*
162	 * Fill in IP header.  If we are not allowing fragmentation,
163	 * then the ip_id field is meaningless, but we don't set it
164	 * to zero.  Doing so causes various problems when devices along
165	 * the path (routers, load balancers, firewalls, etc.) illegally
166	 * disable DF on our packet.  Note that a 16-bit counter
167	 * will wrap around in less than 10 seconds at 100 Mbit/s on a
168	 * medium with MTU 1500.  See Steven M. Bellovin, "A Technique
169	 * for Counting NATted Hosts", Proc. IMW'02, available at
170	 * <http://www.research.att.com/~smb/papers/fnat.pdf>.
171	 */
172	if ((flags & (IP_FORWARDING|IP_RAWOUTPUT)) == 0) {
173		ip->ip_v = IPVERSION;
174		ip->ip_hl = hlen >> 2;
175		ip->ip_id = ip_newid();
176		ipstat.ips_localout++;
177	} else {
178		hlen = ip->ip_hl << 2;
179	}
180
181	dst = (struct sockaddr_in *)&ro->ro_dst;
182again:
183	/*
184	 * If there is a cached route,
185	 * check that it is to the same destination
186	 * and is still up.  If not, free it and try again.
187	 * The address family should also be checked in case of sharing the
188	 * cache with IPv6.
189	 */
190	if (ro->ro_rt && ((ro->ro_rt->rt_flags & RTF_UP) == 0 ||
191			  dst->sin_family != AF_INET ||
192			  dst->sin_addr.s_addr != ip->ip_dst.s_addr)) {
193		RTFREE(ro->ro_rt);
194		ro->ro_rt = (struct rtentry *)0;
195	}
196#ifdef IPFIREWALL_FORWARD
197	if (ro->ro_rt == NULL && fwd_tag == NULL) {
198#else
199	if (ro->ro_rt == NULL) {
200#endif
201		bzero(dst, sizeof(*dst));
202		dst->sin_family = AF_INET;
203		dst->sin_len = sizeof(*dst);
204		dst->sin_addr = ip->ip_dst;
205	}
206	/*
207	 * If routing to interface only,
208	 * short circuit routing lookup.
209	 */
210	if (flags & IP_ROUTETOIF) {
211		if ((ia = ifatoia(ifa_ifwithdstaddr(sintosa(dst)))) == NULL &&
212		    (ia = ifatoia(ifa_ifwithnet(sintosa(dst)))) == NULL) {
213			ipstat.ips_noroute++;
214			error = ENETUNREACH;
215			goto bad;
216		}
217		ifp = ia->ia_ifp;
218		ip->ip_ttl = 1;
219		isbroadcast = in_broadcast(dst->sin_addr, ifp);
220	} else if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) &&
221	    imo != NULL && imo->imo_multicast_ifp != NULL) {
222		/*
223		 * Bypass the normal routing lookup for multicast
224		 * packets if the interface is specified.
225		 */
226		ifp = imo->imo_multicast_ifp;
227		IFP_TO_IA(ifp, ia);
228		isbroadcast = 0;	/* fool gcc */
229	} else {
230		/*
231		 * We want to do any cloning requested by the link layer,
232		 * as this is probably required in all cases for correct
233		 * operation (as it is for ARP).
234		 */
235		if (ro->ro_rt == NULL)
236			rtalloc_ign(ro, 0);
237		if (ro->ro_rt == NULL) {
238			ipstat.ips_noroute++;
239			error = EHOSTUNREACH;
240			goto bad;
241		}
242		ia = ifatoia(ro->ro_rt->rt_ifa);
243		ifp = ro->ro_rt->rt_ifp;
244		ro->ro_rt->rt_rmx.rmx_pksent++;
245		if (ro->ro_rt->rt_flags & RTF_GATEWAY)
246			dst = (struct sockaddr_in *)ro->ro_rt->rt_gateway;
247		if (ro->ro_rt->rt_flags & RTF_HOST)
248			isbroadcast = (ro->ro_rt->rt_flags & RTF_BROADCAST);
249		else
250			isbroadcast = in_broadcast(dst->sin_addr, ifp);
251	}
252	if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr))) {
253		struct in_multi *inm;
254
255		m->m_flags |= M_MCAST;
256		/*
257		 * IP destination address is multicast.  Make sure "dst"
258		 * still points to the address in "ro".  (It may have been
259		 * changed to point to a gateway address, above.)
260		 */
261		dst = (struct sockaddr_in *)&ro->ro_dst;
262		/*
263		 * See if the caller provided any multicast options
264		 */
265		if (imo != NULL) {
266			ip->ip_ttl = imo->imo_multicast_ttl;
267			if (imo->imo_multicast_vif != -1)
268				ip->ip_src.s_addr =
269				    ip_mcast_src ?
270				    ip_mcast_src(imo->imo_multicast_vif) :
271				    INADDR_ANY;
272		} else
273			ip->ip_ttl = IP_DEFAULT_MULTICAST_TTL;
274		/*
275		 * Confirm that the outgoing interface supports multicast.
276		 */
277		if ((imo == NULL) || (imo->imo_multicast_vif == -1)) {
278			if ((ifp->if_flags & IFF_MULTICAST) == 0) {
279				ipstat.ips_noroute++;
280				error = ENETUNREACH;
281				goto bad;
282			}
283		}
284		/*
285		 * If source address not specified yet, use address
286		 * of outgoing interface.
287		 */
288		if (ip->ip_src.s_addr == INADDR_ANY) {
289			/* Interface may have no addresses. */
290			if (ia != NULL)
291				ip->ip_src = IA_SIN(ia)->sin_addr;
292		}
293
294		IN_LOOKUP_MULTI(ip->ip_dst, ifp, inm);
295		if (inm != NULL &&
296		   (imo == NULL || imo->imo_multicast_loop)) {
297			/*
298			 * If we belong to the destination multicast group
299			 * on the outgoing interface, and the caller did not
300			 * forbid loopback, loop back a copy.
301			 */
302			ip_mloopback(ifp, m, dst, hlen);
303		}
304		else {
305			/*
306			 * If we are acting as a multicast router, perform
307			 * multicast forwarding as if the packet had just
308			 * arrived on the interface to which we are about
309			 * to send.  The multicast forwarding function
310			 * recursively calls this function, using the
311			 * IP_FORWARDING flag to prevent infinite recursion.
312			 *
313			 * Multicasts that are looped back by ip_mloopback(),
314			 * above, will be forwarded by the ip_input() routine,
315			 * if necessary.
316			 */
317			if (ip_mrouter && (flags & IP_FORWARDING) == 0) {
318				/*
319				 * If rsvp daemon is not running, do not
320				 * set ip_moptions. This ensures that the packet
321				 * is multicast and not just sent down one link
322				 * as prescribed by rsvpd.
323				 */
324				if (!rsvp_on)
325					imo = NULL;
326				if (ip_mforward &&
327				    ip_mforward(ip, ifp, m, imo) != 0) {
328					m_freem(m);
329					goto done;
330				}
331			}
332		}
333
334		/*
335		 * Multicasts with a time-to-live of zero may be looped-
336		 * back, above, but must not be transmitted on a network.
337		 * Also, multicasts addressed to the loopback interface
338		 * are not sent -- the above call to ip_mloopback() will
339		 * loop back a copy if this host actually belongs to the
340		 * destination group on the loopback interface.
341		 */
342		if (ip->ip_ttl == 0 || ifp->if_flags & IFF_LOOPBACK) {
343			m_freem(m);
344			goto done;
345		}
346
347		goto sendit;
348	}
349#ifndef notdef
350	/*
351	 * If the source address is not specified yet, use the address
352	 * of the outoing interface.
353	 */
354	if (ip->ip_src.s_addr == INADDR_ANY) {
355		/* Interface may have no addresses. */
356		if (ia != NULL) {
357			ip->ip_src = IA_SIN(ia)->sin_addr;
358		}
359	}
360#endif /* notdef */
361	/*
362	 * Verify that we have any chance at all of being able to queue the
363	 * packet or packet fragments, unless ALTQ is enabled on the given
364	 * interface in which case packetdrop should be done by queueing.
365	 */
366#ifdef ALTQ
367	if ((!ALTQ_IS_ENABLED(&ifp->if_snd)) &&
368	    ((ifp->if_snd.ifq_len + ip->ip_len / ifp->if_mtu + 1) >=
369	    ifp->if_snd.ifq_maxlen))
370#else
371	if ((ifp->if_snd.ifq_len + ip->ip_len / ifp->if_mtu + 1) >=
372	    ifp->if_snd.ifq_maxlen)
373#endif /* ALTQ */
374	{
375		error = ENOBUFS;
376		ipstat.ips_odropped++;
377		goto bad;
378	}
379
380	/*
381	 * Look for broadcast address and
382	 * verify user is allowed to send
383	 * such a packet.
384	 */
385	if (isbroadcast) {
386		if ((ifp->if_flags & IFF_BROADCAST) == 0) {
387			error = EADDRNOTAVAIL;
388			goto bad;
389		}
390		if ((flags & IP_ALLOWBROADCAST) == 0) {
391			error = EACCES;
392			goto bad;
393		}
394		/* don't allow broadcast messages to be fragmented */
395		if (ip->ip_len > ifp->if_mtu) {
396			error = EMSGSIZE;
397			goto bad;
398		}
399		if (flags & IP_SENDONES)
400			ip->ip_dst.s_addr = INADDR_BROADCAST;
401		m->m_flags |= M_BCAST;
402	} else {
403		m->m_flags &= ~M_BCAST;
404	}
405
406sendit:
407#ifdef IPSEC
408	/* get SP for this packet */
409	if (inp == NULL)
410		sp = ipsec4_getpolicybyaddr(m, IPSEC_DIR_OUTBOUND,
411		    flags, &error);
412	else
413		sp = ipsec4_getpolicybypcb(m, IPSEC_DIR_OUTBOUND, inp, &error);
414
415	if (sp == NULL) {
416		ipsecstat.out_inval++;
417		goto bad;
418	}
419
420	error = 0;
421
422	/* check policy */
423	switch (sp->policy) {
424	case IPSEC_POLICY_DISCARD:
425		/*
426		 * This packet is just discarded.
427		 */
428		ipsecstat.out_polvio++;
429		goto bad;
430
431	case IPSEC_POLICY_BYPASS:
432	case IPSEC_POLICY_NONE:
433	case IPSEC_POLICY_TCP:
434		/* no need to do IPsec. */
435		goto skip_ipsec;
436
437	case IPSEC_POLICY_IPSEC:
438		if (sp->req == NULL) {
439			/* acquire a policy */
440			error = key_spdacquire(sp);
441			goto bad;
442		}
443		break;
444
445	case IPSEC_POLICY_ENTRUST:
446	default:
447		printf("ip_output: Invalid policy found. %d\n", sp->policy);
448	}
449    {
450	struct ipsec_output_state state;
451	bzero(&state, sizeof(state));
452	state.m = m;
453	if (flags & IP_ROUTETOIF) {
454		state.ro = &iproute;
455		bzero(&iproute, sizeof(iproute));
456	} else
457		state.ro = ro;
458	state.dst = (struct sockaddr *)dst;
459
460	ip->ip_sum = 0;
461
462	/*
463	 * XXX
464	 * delayed checksums are not currently compatible with IPsec
465	 */
466	if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
467		in_delayed_cksum(m);
468		m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
469	}
470
471	ip->ip_len = htons(ip->ip_len);
472	ip->ip_off = htons(ip->ip_off);
473
474	error = ipsec4_output(&state, sp, flags);
475
476	m = state.m;
477	if (flags & IP_ROUTETOIF) {
478		/*
479		 * if we have tunnel mode SA, we may need to ignore
480		 * IP_ROUTETOIF.
481		 */
482		if (state.ro != &iproute || state.ro->ro_rt != NULL) {
483			flags &= ~IP_ROUTETOIF;
484			ro = state.ro;
485		}
486	} else
487		ro = state.ro;
488	dst = (struct sockaddr_in *)state.dst;
489	if (error) {
490		/* mbuf is already reclaimed in ipsec4_output. */
491		m = NULL;
492		switch (error) {
493		case EHOSTUNREACH:
494		case ENETUNREACH:
495		case EMSGSIZE:
496		case ENOBUFS:
497		case ENOMEM:
498			break;
499		default:
500			printf("ip4_output (ipsec): error code %d\n", error);
501			/*fall through*/
502		case ENOENT:
503			/* don't show these error codes to the user */
504			error = 0;
505			break;
506		}
507		goto bad;
508	}
509
510	/* be sure to update variables that are affected by ipsec4_output() */
511	ip = mtod(m, struct ip *);
512	hlen = ip->ip_hl << 2;
513	if (ro->ro_rt == NULL) {
514		if ((flags & IP_ROUTETOIF) == 0) {
515			printf("ip_output: "
516				"can't update route after IPsec processing\n");
517			error = EHOSTUNREACH;	/*XXX*/
518			goto bad;
519		}
520	} else {
521		if (state.encap) {
522			ia = ifatoia(ro->ro_rt->rt_ifa);
523			ifp = ro->ro_rt->rt_ifp;
524		}
525	}
526    }
527
528	/* make it flipped, again. */
529	ip->ip_len = ntohs(ip->ip_len);
530	ip->ip_off = ntohs(ip->ip_off);
531skip_ipsec:
532#endif /*IPSEC*/
533#ifdef FAST_IPSEC
534	/*
535	 * Check the security policy (SP) for the packet and, if
536	 * required, do IPsec-related processing.  There are two
537	 * cases here; the first time a packet is sent through
538	 * it will be untagged and handled by ipsec4_checkpolicy.
539	 * If the packet is resubmitted to ip_output (e.g. after
540	 * AH, ESP, etc. processing), there will be a tag to bypass
541	 * the lookup and related policy checking.
542	 */
543	mtag = m_tag_find(m, PACKET_TAG_IPSEC_PENDING_TDB, NULL);
544	s = splnet();
545	if (mtag != NULL) {
546		tdbi = (struct tdb_ident *)(mtag + 1);
547		sp = ipsec_getpolicy(tdbi, IPSEC_DIR_OUTBOUND);
548		if (sp == NULL)
549			error = -EINVAL;	/* force silent drop */
550		m_tag_delete(m, mtag);
551	} else {
552		sp = ipsec4_checkpolicy(m, IPSEC_DIR_OUTBOUND, flags,
553					&error, inp);
554	}
555	/*
556	 * There are four return cases:
557	 *    sp != NULL	 	    apply IPsec policy
558	 *    sp == NULL, error == 0	    no IPsec handling needed
559	 *    sp == NULL, error == -EINVAL  discard packet w/o error
560	 *    sp == NULL, error != 0	    discard packet, report error
561	 */
562	if (sp != NULL) {
563		/* Loop detection, check if ipsec processing already done */
564		KASSERT(sp->req != NULL, ("ip_output: no ipsec request"));
565		for (mtag = m_tag_first(m); mtag != NULL;
566		     mtag = m_tag_next(m, mtag)) {
567			if (mtag->m_tag_cookie != MTAG_ABI_COMPAT)
568				continue;
569			if (mtag->m_tag_id != PACKET_TAG_IPSEC_OUT_DONE &&
570			    mtag->m_tag_id != PACKET_TAG_IPSEC_OUT_CRYPTO_NEEDED)
571				continue;
572			/*
573			 * Check if policy has an SA associated with it.
574			 * This can happen when an SP has yet to acquire
575			 * an SA; e.g. on first reference.  If it occurs,
576			 * then we let ipsec4_process_packet do its thing.
577			 */
578			if (sp->req->sav == NULL)
579				break;
580			tdbi = (struct tdb_ident *)(mtag + 1);
581			if (tdbi->spi == sp->req->sav->spi &&
582			    tdbi->proto == sp->req->sav->sah->saidx.proto &&
583			    bcmp(&tdbi->dst, &sp->req->sav->sah->saidx.dst,
584				 sizeof (union sockaddr_union)) == 0) {
585				/*
586				 * No IPsec processing is needed, free
587				 * reference to SP.
588				 *
589				 * NB: null pointer to avoid free at
590				 *     done: below.
591				 */
592				KEY_FREESP(&sp), sp = NULL;
593				splx(s);
594				goto spd_done;
595			}
596		}
597
598		/*
599		 * Do delayed checksums now because we send before
600		 * this is done in the normal processing path.
601		 */
602		if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
603			in_delayed_cksum(m);
604			m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
605		}
606
607		ip->ip_len = htons(ip->ip_len);
608		ip->ip_off = htons(ip->ip_off);
609
610		/* NB: callee frees mbuf */
611		error = ipsec4_process_packet(m, sp->req, flags, 0);
612		/*
613		 * Preserve KAME behaviour: ENOENT can be returned
614		 * when an SA acquire is in progress.  Don't propagate
615		 * this to user-level; it confuses applications.
616		 *
617		 * XXX this will go away when the SADB is redone.
618		 */
619		if (error == ENOENT)
620			error = 0;
621		splx(s);
622		goto done;
623	} else {
624		splx(s);
625
626		if (error != 0) {
627			/*
628			 * Hack: -EINVAL is used to signal that a packet
629			 * should be silently discarded.  This is typically
630			 * because we asked key management for an SA and
631			 * it was delayed (e.g. kicked up to IKE).
632			 */
633			if (error == -EINVAL)
634				error = 0;
635			goto bad;
636		} else {
637			/* No IPsec processing for this packet. */
638		}
639#ifdef notyet
640		/*
641		 * If deferred crypto processing is needed, check that
642		 * the interface supports it.
643		 */
644		mtag = m_tag_find(m, PACKET_TAG_IPSEC_OUT_CRYPTO_NEEDED, NULL);
645		if (mtag != NULL && (ifp->if_capenable & IFCAP_IPSEC) == 0) {
646			/* notify IPsec to do its own crypto */
647			ipsp_skipcrypto_unmark((struct tdb_ident *)(mtag + 1));
648			error = EHOSTUNREACH;
649			goto bad;
650		}
651#endif
652	}
653spd_done:
654#endif /* FAST_IPSEC */
655
656	/* Jump over all PFIL processing if hooks are not active. */
657	if (inet_pfil_hook.ph_busy_count == -1)
658		goto passout;
659
660	/* Run through list of hooks for output packets. */
661	odst.s_addr = ip->ip_dst.s_addr;
662	error = pfil_run_hooks(&inet_pfil_hook, &m, ifp, PFIL_OUT, inp);
663	if (error != 0 || m == NULL)
664		goto done;
665
666	ip = mtod(m, struct ip *);
667
668	/* See if destination IP address was changed by packet filter. */
669	if (odst.s_addr != ip->ip_dst.s_addr) {
670		m->m_flags |= M_SKIP_FIREWALL;
671		/* If destination is now ourself drop to ip_input(). */
672		if (in_localip(ip->ip_dst)) {
673			m->m_flags |= M_FASTFWD_OURS;
674			if (m->m_pkthdr.rcvif == NULL)
675				m->m_pkthdr.rcvif = loif;
676			if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
677				m->m_pkthdr.csum_flags |=
678				    CSUM_DATA_VALID | CSUM_PSEUDO_HDR;
679				m->m_pkthdr.csum_data = 0xffff;
680			}
681			m->m_pkthdr.csum_flags |=
682			    CSUM_IP_CHECKED | CSUM_IP_VALID;
683
684			error = netisr_queue(NETISR_IP, m);
685			goto done;
686		} else
687			goto again;	/* Redo the routing table lookup. */
688	}
689
690#ifdef IPFIREWALL_FORWARD
691	/* See if local, if yes, send it to netisr with IP_FASTFWD_OURS. */
692	if (m->m_flags & M_FASTFWD_OURS) {
693		if (m->m_pkthdr.rcvif == NULL)
694			m->m_pkthdr.rcvif = loif;
695		if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
696			m->m_pkthdr.csum_flags |=
697			    CSUM_DATA_VALID | CSUM_PSEUDO_HDR;
698			m->m_pkthdr.csum_data = 0xffff;
699		}
700		m->m_pkthdr.csum_flags |=
701			    CSUM_IP_CHECKED | CSUM_IP_VALID;
702
703		error = netisr_queue(NETISR_IP, m);
704		goto done;
705	}
706	/* Or forward to some other address? */
707	fwd_tag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL);
708	if (fwd_tag) {
709		if (!in_localip(ip->ip_src) && !in_localaddr(ip->ip_dst)) {
710			dst = (struct sockaddr_in *)&ro->ro_dst;
711			bcopy((fwd_tag+1), dst, sizeof(struct sockaddr_in));
712			m->m_flags |= M_SKIP_FIREWALL;
713			m_tag_delete(m, fwd_tag);
714			goto again;
715		} else {
716			m_tag_delete(m, fwd_tag);
717			/* Continue. */
718		}
719	}
720#endif
721
722passout:
723	/* 127/8 must not appear on wire - RFC1122. */
724	if ((ntohl(ip->ip_dst.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET ||
725	    (ntohl(ip->ip_src.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET) {
726		if ((ifp->if_flags & IFF_LOOPBACK) == 0) {
727			ipstat.ips_badaddr++;
728			error = EADDRNOTAVAIL;
729			goto bad;
730		}
731	}
732
733	m->m_pkthdr.csum_flags |= CSUM_IP;
734	sw_csum = m->m_pkthdr.csum_flags & ~ifp->if_hwassist;
735	if (sw_csum & CSUM_DELAY_DATA) {
736		in_delayed_cksum(m);
737		sw_csum &= ~CSUM_DELAY_DATA;
738	}
739	m->m_pkthdr.csum_flags &= ifp->if_hwassist;
740
741	/*
742	 * If small enough for interface, or the interface will take
743	 * care of the fragmentation for us, can just send directly.
744	 */
745	if (ip->ip_len <= ifp->if_mtu || (ifp->if_hwassist & CSUM_FRAGMENT &&
746	    ((ip->ip_off & IP_DF) == 0))) {
747		ip->ip_len = htons(ip->ip_len);
748		ip->ip_off = htons(ip->ip_off);
749		ip->ip_sum = 0;
750		if (sw_csum & CSUM_DELAY_IP)
751			ip->ip_sum = in_cksum(m, hlen);
752
753		/* Record statistics for this interface address. */
754		if (!(flags & IP_FORWARDING) && ia) {
755			ia->ia_ifa.if_opackets++;
756			ia->ia_ifa.if_obytes += m->m_pkthdr.len;
757		}
758
759#ifdef IPSEC
760		/* clean ipsec history once it goes out of the node */
761		ipsec_delaux(m);
762#endif
763
764#ifdef MBUF_STRESS_TEST
765		if (mbuf_frag_size && m->m_pkthdr.len > mbuf_frag_size)
766			m = m_fragment(m, M_DONTWAIT, mbuf_frag_size);
767#endif
768		error = (*ifp->if_output)(ifp, m,
769				(struct sockaddr *)dst, ro->ro_rt);
770		goto done;
771	}
772
773	if (ip->ip_off & IP_DF) {
774		error = EMSGSIZE;
775		/*
776		 * This case can happen if the user changed the MTU
777		 * of an interface after enabling IP on it.  Because
778		 * most netifs don't keep track of routes pointing to
779		 * them, there is no way for one to update all its
780		 * routes when the MTU is changed.
781		 */
782		if ((ro->ro_rt->rt_flags & (RTF_UP | RTF_HOST)) &&
783		    (ro->ro_rt->rt_rmx.rmx_mtu > ifp->if_mtu)) {
784			ro->ro_rt->rt_rmx.rmx_mtu = ifp->if_mtu;
785		}
786		ipstat.ips_cantfrag++;
787		goto bad;
788	}
789
790	/*
791	 * Too large for interface; fragment if possible. If successful,
792	 * on return, m will point to a list of packets to be sent.
793	 */
794	error = ip_fragment(ip, &m, ifp->if_mtu, ifp->if_hwassist, sw_csum);
795	if (error)
796		goto bad;
797	for (; m; m = m0) {
798		m0 = m->m_nextpkt;
799		m->m_nextpkt = 0;
800#ifdef IPSEC
801		/* clean ipsec history once it goes out of the node */
802		ipsec_delaux(m);
803#endif
804		if (error == 0) {
805			/* Record statistics for this interface address. */
806			if (ia != NULL) {
807				ia->ia_ifa.if_opackets++;
808				ia->ia_ifa.if_obytes += m->m_pkthdr.len;
809			}
810
811			error = (*ifp->if_output)(ifp, m,
812			    (struct sockaddr *)dst, ro->ro_rt);
813		} else
814			m_freem(m);
815	}
816
817	if (error == 0)
818		ipstat.ips_fragmented++;
819
820done:
821	if (ro == &iproute && ro->ro_rt) {
822		RTFREE(ro->ro_rt);
823	}
824#ifdef IPSEC
825	if (sp != NULL) {
826		KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
827			printf("DP ip_output call free SP:%p\n", sp));
828		key_freesp(sp);
829	}
830#endif
831#ifdef FAST_IPSEC
832	if (sp != NULL)
833		KEY_FREESP(&sp);
834#endif
835	return (error);
836bad:
837	m_freem(m);
838	goto done;
839}
840
841/*
842 * Create a chain of fragments which fit the given mtu. m_frag points to the
843 * mbuf to be fragmented; on return it points to the chain with the fragments.
844 * Return 0 if no error. If error, m_frag may contain a partially built
845 * chain of fragments that should be freed by the caller.
846 *
847 * if_hwassist_flags is the hw offload capabilities (see if_data.ifi_hwassist)
848 * sw_csum contains the delayed checksums flags (e.g., CSUM_DELAY_IP).
849 */
850int
851ip_fragment(struct ip *ip, struct mbuf **m_frag, int mtu,
852	    u_long if_hwassist_flags, int sw_csum)
853{
854	int error = 0;
855	int hlen = ip->ip_hl << 2;
856	int len = (mtu - hlen) & ~7;	/* size of payload in each fragment */
857	int off;
858	struct mbuf *m0 = *m_frag;	/* the original packet		*/
859	int firstlen;
860	struct mbuf **mnext;
861	int nfrags;
862
863	if (ip->ip_off & IP_DF) {	/* Fragmentation not allowed */
864		ipstat.ips_cantfrag++;
865		return EMSGSIZE;
866	}
867
868	/*
869	 * Must be able to put at least 8 bytes per fragment.
870	 */
871	if (len < 8)
872		return EMSGSIZE;
873
874	/*
875	 * If the interface will not calculate checksums on
876	 * fragmented packets, then do it here.
877	 */
878	if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA &&
879	    (if_hwassist_flags & CSUM_IP_FRAGS) == 0) {
880		in_delayed_cksum(m0);
881		m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
882	}
883
884	if (len > PAGE_SIZE) {
885		/*
886		 * Fragment large datagrams such that each segment
887		 * contains a multiple of PAGE_SIZE amount of data,
888		 * plus headers. This enables a receiver to perform
889		 * page-flipping zero-copy optimizations.
890		 *
891		 * XXX When does this help given that sender and receiver
892		 * could have different page sizes, and also mtu could
893		 * be less than the receiver's page size ?
894		 */
895		int newlen;
896		struct mbuf *m;
897
898		for (m = m0, off = 0; m && (off+m->m_len) <= mtu; m = m->m_next)
899			off += m->m_len;
900
901		/*
902		 * firstlen (off - hlen) must be aligned on an
903		 * 8-byte boundary
904		 */
905		if (off < hlen)
906			goto smart_frag_failure;
907		off = ((off - hlen) & ~7) + hlen;
908		newlen = (~PAGE_MASK) & mtu;
909		if ((newlen + sizeof (struct ip)) > mtu) {
910			/* we failed, go back the default */
911smart_frag_failure:
912			newlen = len;
913			off = hlen + len;
914		}
915		len = newlen;
916
917	} else {
918		off = hlen + len;
919	}
920
921	firstlen = off - hlen;
922	mnext = &m0->m_nextpkt;		/* pointer to next packet */
923
924	/*
925	 * Loop through length of segment after first fragment,
926	 * make new header and copy data of each part and link onto chain.
927	 * Here, m0 is the original packet, m is the fragment being created.
928	 * The fragments are linked off the m_nextpkt of the original
929	 * packet, which after processing serves as the first fragment.
930	 */
931	for (nfrags = 1; off < ip->ip_len; off += len, nfrags++) {
932		struct ip *mhip;	/* ip header on the fragment */
933		struct mbuf *m;
934		int mhlen = sizeof (struct ip);
935
936		MGETHDR(m, M_DONTWAIT, MT_HEADER);
937		if (m == NULL) {
938			error = ENOBUFS;
939			ipstat.ips_odropped++;
940			goto done;
941		}
942		m->m_flags |= (m0->m_flags & M_MCAST) | M_FRAG;
943		/*
944		 * In the first mbuf, leave room for the link header, then
945		 * copy the original IP header including options. The payload
946		 * goes into an additional mbuf chain returned by m_copy().
947		 */
948		m->m_data += max_linkhdr;
949		mhip = mtod(m, struct ip *);
950		*mhip = *ip;
951		if (hlen > sizeof (struct ip)) {
952			mhlen = ip_optcopy(ip, mhip) + sizeof (struct ip);
953			mhip->ip_v = IPVERSION;
954			mhip->ip_hl = mhlen >> 2;
955		}
956		m->m_len = mhlen;
957		/* XXX do we need to add ip->ip_off below ? */
958		mhip->ip_off = ((off - hlen) >> 3) + ip->ip_off;
959		if (off + len >= ip->ip_len) {	/* last fragment */
960			len = ip->ip_len - off;
961			m->m_flags |= M_LASTFRAG;
962		} else
963			mhip->ip_off |= IP_MF;
964		mhip->ip_len = htons((u_short)(len + mhlen));
965		m->m_next = m_copy(m0, off, len);
966		if (m->m_next == NULL) {	/* copy failed */
967			m_free(m);
968			error = ENOBUFS;	/* ??? */
969			ipstat.ips_odropped++;
970			goto done;
971		}
972		m->m_pkthdr.len = mhlen + len;
973		m->m_pkthdr.rcvif = (struct ifnet *)0;
974#ifdef MAC
975		mac_create_fragment(m0, m);
976#endif
977		m->m_pkthdr.csum_flags = m0->m_pkthdr.csum_flags;
978		mhip->ip_off = htons(mhip->ip_off);
979		mhip->ip_sum = 0;
980		if (sw_csum & CSUM_DELAY_IP)
981			mhip->ip_sum = in_cksum(m, mhlen);
982		*mnext = m;
983		mnext = &m->m_nextpkt;
984	}
985	ipstat.ips_ofragments += nfrags;
986
987	/* set first marker for fragment chain */
988	m0->m_flags |= M_FIRSTFRAG | M_FRAG;
989	m0->m_pkthdr.csum_data = nfrags;
990
991	/*
992	 * Update first fragment by trimming what's been copied out
993	 * and updating header.
994	 */
995	m_adj(m0, hlen + firstlen - ip->ip_len);
996	m0->m_pkthdr.len = hlen + firstlen;
997	ip->ip_len = htons((u_short)m0->m_pkthdr.len);
998	ip->ip_off |= IP_MF;
999	ip->ip_off = htons(ip->ip_off);
1000	ip->ip_sum = 0;
1001	if (sw_csum & CSUM_DELAY_IP)
1002		ip->ip_sum = in_cksum(m0, hlen);
1003
1004done:
1005	*m_frag = m0;
1006	return error;
1007}
1008
1009void
1010in_delayed_cksum(struct mbuf *m)
1011{
1012	struct ip *ip;
1013	u_short csum, offset;
1014
1015	ip = mtod(m, struct ip *);
1016	offset = ip->ip_hl << 2 ;
1017	csum = in_cksum_skip(m, ip->ip_len, offset);
1018	if (m->m_pkthdr.csum_flags & CSUM_UDP && csum == 0)
1019		csum = 0xffff;
1020	offset += m->m_pkthdr.csum_data;	/* checksum offset */
1021
1022	if (offset + sizeof(u_short) > m->m_len) {
1023		printf("delayed m_pullup, m->len: %d  off: %d  p: %d\n",
1024		    m->m_len, offset, ip->ip_p);
1025		/*
1026		 * XXX
1027		 * this shouldn't happen, but if it does, the
1028		 * correct behavior may be to insert the checksum
1029		 * in the existing chain instead of rearranging it.
1030		 */
1031		m = m_pullup(m, offset + sizeof(u_short));
1032	}
1033	*(u_short *)(m->m_data + offset) = csum;
1034}
1035
1036/*
1037 * Insert IP options into preformed packet.
1038 * Adjust IP destination as required for IP source routing,
1039 * as indicated by a non-zero in_addr at the start of the options.
1040 *
1041 * XXX This routine assumes that the packet has no options in place.
1042 */
1043static struct mbuf *
1044ip_insertoptions(m, opt, phlen)
1045	register struct mbuf *m;
1046	struct mbuf *opt;
1047	int *phlen;
1048{
1049	register struct ipoption *p = mtod(opt, struct ipoption *);
1050	struct mbuf *n;
1051	register struct ip *ip = mtod(m, struct ip *);
1052	unsigned optlen;
1053
1054	optlen = opt->m_len - sizeof(p->ipopt_dst);
1055	if (optlen + ip->ip_len > IP_MAXPACKET) {
1056		*phlen = 0;
1057		return (m);		/* XXX should fail */
1058	}
1059	if (p->ipopt_dst.s_addr)
1060		ip->ip_dst = p->ipopt_dst;
1061	if (m->m_flags & M_EXT || m->m_data - optlen < m->m_pktdat) {
1062		MGETHDR(n, M_DONTWAIT, MT_HEADER);
1063		if (n == NULL) {
1064			*phlen = 0;
1065			return (m);
1066		}
1067		n->m_pkthdr.rcvif = (struct ifnet *)0;
1068#ifdef MAC
1069		mac_create_mbuf_from_mbuf(m, n);
1070#endif
1071		n->m_pkthdr.len = m->m_pkthdr.len + optlen;
1072		m->m_len -= sizeof(struct ip);
1073		m->m_data += sizeof(struct ip);
1074		n->m_next = m;
1075		m = n;
1076		m->m_len = optlen + sizeof(struct ip);
1077		m->m_data += max_linkhdr;
1078		bcopy(ip, mtod(m, void *), sizeof(struct ip));
1079	} else {
1080		m->m_data -= optlen;
1081		m->m_len += optlen;
1082		m->m_pkthdr.len += optlen;
1083		bcopy(ip, mtod(m, void *), sizeof(struct ip));
1084	}
1085	ip = mtod(m, struct ip *);
1086	bcopy(p->ipopt_list, ip + 1, optlen);
1087	*phlen = sizeof(struct ip) + optlen;
1088	ip->ip_v = IPVERSION;
1089	ip->ip_hl = *phlen >> 2;
1090	ip->ip_len += optlen;
1091	return (m);
1092}
1093
1094/*
1095 * Copy options from ip to jp,
1096 * omitting those not copied during fragmentation.
1097 */
1098int
1099ip_optcopy(ip, jp)
1100	struct ip *ip, *jp;
1101{
1102	register u_char *cp, *dp;
1103	int opt, optlen, cnt;
1104
1105	cp = (u_char *)(ip + 1);
1106	dp = (u_char *)(jp + 1);
1107	cnt = (ip->ip_hl << 2) - sizeof (struct ip);
1108	for (; cnt > 0; cnt -= optlen, cp += optlen) {
1109		opt = cp[0];
1110		if (opt == IPOPT_EOL)
1111			break;
1112		if (opt == IPOPT_NOP) {
1113			/* Preserve for IP mcast tunnel's LSRR alignment. */
1114			*dp++ = IPOPT_NOP;
1115			optlen = 1;
1116			continue;
1117		}
1118
1119		KASSERT(cnt >= IPOPT_OLEN + sizeof(*cp),
1120		    ("ip_optcopy: malformed ipv4 option"));
1121		optlen = cp[IPOPT_OLEN];
1122		KASSERT(optlen >= IPOPT_OLEN + sizeof(*cp) && optlen <= cnt,
1123		    ("ip_optcopy: malformed ipv4 option"));
1124
1125		/* bogus lengths should have been caught by ip_dooptions */
1126		if (optlen > cnt)
1127			optlen = cnt;
1128		if (IPOPT_COPIED(opt)) {
1129			bcopy(cp, dp, optlen);
1130			dp += optlen;
1131		}
1132	}
1133	for (optlen = dp - (u_char *)(jp+1); optlen & 0x3; optlen++)
1134		*dp++ = IPOPT_EOL;
1135	return (optlen);
1136}
1137
1138/*
1139 * IP socket option processing.
1140 */
1141int
1142ip_ctloutput(so, sopt)
1143	struct socket *so;
1144	struct sockopt *sopt;
1145{
1146	struct	inpcb *inp = sotoinpcb(so);
1147	int	error, optval;
1148
1149	error = optval = 0;
1150	if (sopt->sopt_level != IPPROTO_IP) {
1151		return (EINVAL);
1152	}
1153
1154	switch (sopt->sopt_dir) {
1155	case SOPT_SET:
1156		switch (sopt->sopt_name) {
1157		case IP_OPTIONS:
1158#ifdef notyet
1159		case IP_RETOPTS:
1160#endif
1161		{
1162			struct mbuf *m;
1163			if (sopt->sopt_valsize > MLEN) {
1164				error = EMSGSIZE;
1165				break;
1166			}
1167			MGET(m, sopt->sopt_td ? M_TRYWAIT : M_DONTWAIT, MT_HEADER);
1168			if (m == NULL) {
1169				error = ENOBUFS;
1170				break;
1171			}
1172			m->m_len = sopt->sopt_valsize;
1173			error = sooptcopyin(sopt, mtod(m, char *), m->m_len,
1174					    m->m_len);
1175			INP_LOCK(inp);
1176			error = ip_pcbopts(inp, sopt->sopt_name, m);
1177			INP_UNLOCK(inp);
1178			return (error);
1179		}
1180
1181		case IP_TOS:
1182		case IP_TTL:
1183		case IP_RECVOPTS:
1184		case IP_RECVRETOPTS:
1185		case IP_RECVDSTADDR:
1186		case IP_RECVTTL:
1187		case IP_RECVIF:
1188		case IP_FAITH:
1189		case IP_ONESBCAST:
1190			error = sooptcopyin(sopt, &optval, sizeof optval,
1191					    sizeof optval);
1192			if (error)
1193				break;
1194
1195			switch (sopt->sopt_name) {
1196			case IP_TOS:
1197				inp->inp_ip_tos = optval;
1198				break;
1199
1200			case IP_TTL:
1201				inp->inp_ip_ttl = optval;
1202				break;
1203#define	OPTSET(bit) do {						\
1204	INP_LOCK(inp);							\
1205	if (optval)							\
1206		inp->inp_flags |= bit;					\
1207	else								\
1208		inp->inp_flags &= ~bit;					\
1209	INP_UNLOCK(inp);						\
1210} while (0)
1211
1212			case IP_RECVOPTS:
1213				OPTSET(INP_RECVOPTS);
1214				break;
1215
1216			case IP_RECVRETOPTS:
1217				OPTSET(INP_RECVRETOPTS);
1218				break;
1219
1220			case IP_RECVDSTADDR:
1221				OPTSET(INP_RECVDSTADDR);
1222				break;
1223
1224			case IP_RECVTTL:
1225				OPTSET(INP_RECVTTL);
1226				break;
1227
1228			case IP_RECVIF:
1229				OPTSET(INP_RECVIF);
1230				break;
1231
1232			case IP_FAITH:
1233				OPTSET(INP_FAITH);
1234				break;
1235
1236			case IP_ONESBCAST:
1237				OPTSET(INP_ONESBCAST);
1238				break;
1239			}
1240			break;
1241#undef OPTSET
1242
1243		case IP_MULTICAST_IF:
1244		case IP_MULTICAST_VIF:
1245		case IP_MULTICAST_TTL:
1246		case IP_MULTICAST_LOOP:
1247		case IP_ADD_MEMBERSHIP:
1248		case IP_DROP_MEMBERSHIP:
1249			error = ip_setmoptions(inp, sopt);
1250			break;
1251
1252		case IP_PORTRANGE:
1253			error = sooptcopyin(sopt, &optval, sizeof optval,
1254					    sizeof optval);
1255			if (error)
1256				break;
1257
1258			INP_LOCK(inp);
1259			switch (optval) {
1260			case IP_PORTRANGE_DEFAULT:
1261				inp->inp_flags &= ~(INP_LOWPORT);
1262				inp->inp_flags &= ~(INP_HIGHPORT);
1263				break;
1264
1265			case IP_PORTRANGE_HIGH:
1266				inp->inp_flags &= ~(INP_LOWPORT);
1267				inp->inp_flags |= INP_HIGHPORT;
1268				break;
1269
1270			case IP_PORTRANGE_LOW:
1271				inp->inp_flags &= ~(INP_HIGHPORT);
1272				inp->inp_flags |= INP_LOWPORT;
1273				break;
1274
1275			default:
1276				error = EINVAL;
1277				break;
1278			}
1279			INP_UNLOCK(inp);
1280			break;
1281
1282#if defined(IPSEC) || defined(FAST_IPSEC)
1283		case IP_IPSEC_POLICY:
1284		{
1285			caddr_t req;
1286			size_t len = 0;
1287			int priv;
1288			struct mbuf *m;
1289			int optname;
1290
1291			if ((error = soopt_getm(sopt, &m)) != 0) /* XXX */
1292				break;
1293			if ((error = soopt_mcopyin(sopt, m)) != 0) /* XXX */
1294				break;
1295			priv = (sopt->sopt_td != NULL &&
1296				suser(sopt->sopt_td) != 0) ? 0 : 1;
1297			req = mtod(m, caddr_t);
1298			len = m->m_len;
1299			optname = sopt->sopt_name;
1300			error = ipsec4_set_policy(inp, optname, req, len, priv);
1301			m_freem(m);
1302			break;
1303		}
1304#endif /*IPSEC*/
1305
1306		default:
1307			error = ENOPROTOOPT;
1308			break;
1309		}
1310		break;
1311
1312	case SOPT_GET:
1313		switch (sopt->sopt_name) {
1314		case IP_OPTIONS:
1315		case IP_RETOPTS:
1316			if (inp->inp_options)
1317				error = sooptcopyout(sopt,
1318						     mtod(inp->inp_options,
1319							  char *),
1320						     inp->inp_options->m_len);
1321			else
1322				sopt->sopt_valsize = 0;
1323			break;
1324
1325		case IP_TOS:
1326		case IP_TTL:
1327		case IP_RECVOPTS:
1328		case IP_RECVRETOPTS:
1329		case IP_RECVDSTADDR:
1330		case IP_RECVTTL:
1331		case IP_RECVIF:
1332		case IP_PORTRANGE:
1333		case IP_FAITH:
1334		case IP_ONESBCAST:
1335			switch (sopt->sopt_name) {
1336
1337			case IP_TOS:
1338				optval = inp->inp_ip_tos;
1339				break;
1340
1341			case IP_TTL:
1342				optval = inp->inp_ip_ttl;
1343				break;
1344
1345#define	OPTBIT(bit)	(inp->inp_flags & bit ? 1 : 0)
1346
1347			case IP_RECVOPTS:
1348				optval = OPTBIT(INP_RECVOPTS);
1349				break;
1350
1351			case IP_RECVRETOPTS:
1352				optval = OPTBIT(INP_RECVRETOPTS);
1353				break;
1354
1355			case IP_RECVDSTADDR:
1356				optval = OPTBIT(INP_RECVDSTADDR);
1357				break;
1358
1359			case IP_RECVTTL:
1360				optval = OPTBIT(INP_RECVTTL);
1361				break;
1362
1363			case IP_RECVIF:
1364				optval = OPTBIT(INP_RECVIF);
1365				break;
1366
1367			case IP_PORTRANGE:
1368				if (inp->inp_flags & INP_HIGHPORT)
1369					optval = IP_PORTRANGE_HIGH;
1370				else if (inp->inp_flags & INP_LOWPORT)
1371					optval = IP_PORTRANGE_LOW;
1372				else
1373					optval = 0;
1374				break;
1375
1376			case IP_FAITH:
1377				optval = OPTBIT(INP_FAITH);
1378				break;
1379
1380			case IP_ONESBCAST:
1381				optval = OPTBIT(INP_ONESBCAST);
1382				break;
1383			}
1384			error = sooptcopyout(sopt, &optval, sizeof optval);
1385			break;
1386
1387		case IP_MULTICAST_IF:
1388		case IP_MULTICAST_VIF:
1389		case IP_MULTICAST_TTL:
1390		case IP_MULTICAST_LOOP:
1391		case IP_ADD_MEMBERSHIP:
1392		case IP_DROP_MEMBERSHIP:
1393			error = ip_getmoptions(inp, sopt);
1394			break;
1395
1396#if defined(IPSEC) || defined(FAST_IPSEC)
1397		case IP_IPSEC_POLICY:
1398		{
1399			struct mbuf *m = NULL;
1400			caddr_t req = NULL;
1401			size_t len = 0;
1402
1403			if (m != 0) {
1404				req = mtod(m, caddr_t);
1405				len = m->m_len;
1406			}
1407			error = ipsec4_get_policy(sotoinpcb(so), req, len, &m);
1408			if (error == 0)
1409				error = soopt_mcopyout(sopt, m); /* XXX */
1410			if (error == 0)
1411				m_freem(m);
1412			break;
1413		}
1414#endif /*IPSEC*/
1415
1416		default:
1417			error = ENOPROTOOPT;
1418			break;
1419		}
1420		break;
1421	}
1422	return (error);
1423}
1424
1425/*
1426 * Set up IP options in pcb for insertion in output packets.
1427 * Store in mbuf with pointer in pcbopt, adding pseudo-option
1428 * with destination address if source routed.
1429 */
1430static int
1431ip_pcbopts(struct inpcb *inp, int optname, struct mbuf *m)
1432{
1433	register int cnt, optlen;
1434	register u_char *cp;
1435	struct mbuf **pcbopt;
1436	u_char opt;
1437
1438	INP_LOCK_ASSERT(inp);
1439
1440	pcbopt = &inp->inp_options;
1441
1442	/* turn off any old options */
1443	if (*pcbopt)
1444		(void)m_free(*pcbopt);
1445	*pcbopt = 0;
1446	if (m == NULL || m->m_len == 0) {
1447		/*
1448		 * Only turning off any previous options.
1449		 */
1450		if (m != NULL)
1451			(void)m_free(m);
1452		return (0);
1453	}
1454
1455	if (m->m_len % sizeof(int32_t))
1456		goto bad;
1457	/*
1458	 * IP first-hop destination address will be stored before
1459	 * actual options; move other options back
1460	 * and clear it when none present.
1461	 */
1462	if (m->m_data + m->m_len + sizeof(struct in_addr) >= &m->m_dat[MLEN])
1463		goto bad;
1464	cnt = m->m_len;
1465	m->m_len += sizeof(struct in_addr);
1466	cp = mtod(m, u_char *) + sizeof(struct in_addr);
1467	bcopy(mtod(m, void *), cp, (unsigned)cnt);
1468	bzero(mtod(m, void *), sizeof(struct in_addr));
1469
1470	for (; cnt > 0; cnt -= optlen, cp += optlen) {
1471		opt = cp[IPOPT_OPTVAL];
1472		if (opt == IPOPT_EOL)
1473			break;
1474		if (opt == IPOPT_NOP)
1475			optlen = 1;
1476		else {
1477			if (cnt < IPOPT_OLEN + sizeof(*cp))
1478				goto bad;
1479			optlen = cp[IPOPT_OLEN];
1480			if (optlen < IPOPT_OLEN + sizeof(*cp) || optlen > cnt)
1481				goto bad;
1482		}
1483		switch (opt) {
1484
1485		default:
1486			break;
1487
1488		case IPOPT_LSRR:
1489		case IPOPT_SSRR:
1490			/*
1491			 * user process specifies route as:
1492			 *	->A->B->C->D
1493			 * D must be our final destination (but we can't
1494			 * check that since we may not have connected yet).
1495			 * A is first hop destination, which doesn't appear in
1496			 * actual IP option, but is stored before the options.
1497			 */
1498			if (optlen < IPOPT_MINOFF - 1 + sizeof(struct in_addr))
1499				goto bad;
1500			m->m_len -= sizeof(struct in_addr);
1501			cnt -= sizeof(struct in_addr);
1502			optlen -= sizeof(struct in_addr);
1503			cp[IPOPT_OLEN] = optlen;
1504			/*
1505			 * Move first hop before start of options.
1506			 */
1507			bcopy((caddr_t)&cp[IPOPT_OFFSET+1], mtod(m, caddr_t),
1508			    sizeof(struct in_addr));
1509			/*
1510			 * Then copy rest of options back
1511			 * to close up the deleted entry.
1512			 */
1513			bcopy((&cp[IPOPT_OFFSET+1] + sizeof(struct in_addr)),
1514			    &cp[IPOPT_OFFSET+1],
1515			    (unsigned)cnt - (IPOPT_MINOFF - 1));
1516			break;
1517		}
1518	}
1519	if (m->m_len > MAX_IPOPTLEN + sizeof(struct in_addr))
1520		goto bad;
1521	*pcbopt = m;
1522	return (0);
1523
1524bad:
1525	(void)m_free(m);
1526	return (EINVAL);
1527}
1528
1529/*
1530 * XXX
1531 * The whole multicast option thing needs to be re-thought.
1532 * Several of these options are equally applicable to non-multicast
1533 * transmission, and one (IP_MULTICAST_TTL) totally duplicates a
1534 * standard option (IP_TTL).
1535 */
1536
1537/*
1538 * following RFC1724 section 3.3, 0.0.0.0/8 is interpreted as interface index.
1539 */
1540static struct ifnet *
1541ip_multicast_if(a, ifindexp)
1542	struct in_addr *a;
1543	int *ifindexp;
1544{
1545	int ifindex;
1546	struct ifnet *ifp;
1547
1548	if (ifindexp)
1549		*ifindexp = 0;
1550	if (ntohl(a->s_addr) >> 24 == 0) {
1551		ifindex = ntohl(a->s_addr) & 0xffffff;
1552		if (ifindex < 0 || if_index < ifindex)
1553			return NULL;
1554		ifp = ifnet_byindex(ifindex);
1555		if (ifindexp)
1556			*ifindexp = ifindex;
1557	} else {
1558		INADDR_TO_IFP(*a, ifp);
1559	}
1560	return ifp;
1561}
1562
1563/*
1564 * Set the IP multicast options in response to user setsockopt().
1565 */
1566static int
1567ip_setmoptions(struct inpcb *inp, struct sockopt *sopt)
1568{
1569	int error = 0;
1570	int i;
1571	struct in_addr addr;
1572	struct ip_mreq mreq;
1573	struct ifnet *ifp;
1574	struct ip_moptions *imo;
1575	struct route ro;
1576	struct sockaddr_in *dst;
1577	int ifindex;
1578	int s;
1579
1580	imo = inp->inp_moptions;
1581	if (imo == NULL) {
1582		/*
1583		 * No multicast option buffer attached to the pcb;
1584		 * allocate one and initialize to default values.
1585		 */
1586		imo = (struct ip_moptions*)malloc(sizeof(*imo), M_IPMOPTS,
1587		    M_WAITOK);
1588
1589		if (imo == NULL)
1590			return (ENOBUFS);
1591		inp->inp_moptions = imo;
1592		imo->imo_multicast_ifp = NULL;
1593		imo->imo_multicast_addr.s_addr = INADDR_ANY;
1594		imo->imo_multicast_vif = -1;
1595		imo->imo_multicast_ttl = IP_DEFAULT_MULTICAST_TTL;
1596		imo->imo_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
1597		imo->imo_num_memberships = 0;
1598	}
1599
1600	switch (sopt->sopt_name) {
1601	/* store an index number for the vif you wanna use in the send */
1602	case IP_MULTICAST_VIF:
1603		if (legal_vif_num == 0) {
1604			error = EOPNOTSUPP;
1605			break;
1606		}
1607		error = sooptcopyin(sopt, &i, sizeof i, sizeof i);
1608		if (error)
1609			break;
1610		if (!legal_vif_num(i) && (i != -1)) {
1611			error = EINVAL;
1612			break;
1613		}
1614		imo->imo_multicast_vif = i;
1615		break;
1616
1617	case IP_MULTICAST_IF:
1618		/*
1619		 * Select the interface for outgoing multicast packets.
1620		 */
1621		error = sooptcopyin(sopt, &addr, sizeof addr, sizeof addr);
1622		if (error)
1623			break;
1624		/*
1625		 * INADDR_ANY is used to remove a previous selection.
1626		 * When no interface is selected, a default one is
1627		 * chosen every time a multicast packet is sent.
1628		 */
1629		if (addr.s_addr == INADDR_ANY) {
1630			imo->imo_multicast_ifp = NULL;
1631			break;
1632		}
1633		/*
1634		 * The selected interface is identified by its local
1635		 * IP address.  Find the interface and confirm that
1636		 * it supports multicasting.
1637		 */
1638		s = splimp();
1639		ifp = ip_multicast_if(&addr, &ifindex);
1640		if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0) {
1641			splx(s);
1642			error = EADDRNOTAVAIL;
1643			break;
1644		}
1645		imo->imo_multicast_ifp = ifp;
1646		if (ifindex)
1647			imo->imo_multicast_addr = addr;
1648		else
1649			imo->imo_multicast_addr.s_addr = INADDR_ANY;
1650		splx(s);
1651		break;
1652
1653	case IP_MULTICAST_TTL:
1654		/*
1655		 * Set the IP time-to-live for outgoing multicast packets.
1656		 * The original multicast API required a char argument,
1657		 * which is inconsistent with the rest of the socket API.
1658		 * We allow either a char or an int.
1659		 */
1660		if (sopt->sopt_valsize == 1) {
1661			u_char ttl;
1662			error = sooptcopyin(sopt, &ttl, 1, 1);
1663			if (error)
1664				break;
1665			imo->imo_multicast_ttl = ttl;
1666		} else {
1667			u_int ttl;
1668			error = sooptcopyin(sopt, &ttl, sizeof ttl,
1669					    sizeof ttl);
1670			if (error)
1671				break;
1672			if (ttl > 255)
1673				error = EINVAL;
1674			else
1675				imo->imo_multicast_ttl = ttl;
1676		}
1677		break;
1678
1679	case IP_MULTICAST_LOOP:
1680		/*
1681		 * Set the loopback flag for outgoing multicast packets.
1682		 * Must be zero or one.  The original multicast API required a
1683		 * char argument, which is inconsistent with the rest
1684		 * of the socket API.  We allow either a char or an int.
1685		 */
1686		if (sopt->sopt_valsize == 1) {
1687			u_char loop;
1688			error = sooptcopyin(sopt, &loop, 1, 1);
1689			if (error)
1690				break;
1691			imo->imo_multicast_loop = !!loop;
1692		} else {
1693			u_int loop;
1694			error = sooptcopyin(sopt, &loop, sizeof loop,
1695					    sizeof loop);
1696			if (error)
1697				break;
1698			imo->imo_multicast_loop = !!loop;
1699		}
1700		break;
1701
1702	case IP_ADD_MEMBERSHIP:
1703		/*
1704		 * Add a multicast group membership.
1705		 * Group must be a valid IP multicast address.
1706		 */
1707		error = sooptcopyin(sopt, &mreq, sizeof mreq, sizeof mreq);
1708		if (error)
1709			break;
1710
1711		if (!IN_MULTICAST(ntohl(mreq.imr_multiaddr.s_addr))) {
1712			error = EINVAL;
1713			break;
1714		}
1715		s = splimp();
1716		/*
1717		 * If no interface address was provided, use the interface of
1718		 * the route to the given multicast address.
1719		 */
1720		if (mreq.imr_interface.s_addr == INADDR_ANY) {
1721			bzero((caddr_t)&ro, sizeof(ro));
1722			dst = (struct sockaddr_in *)&ro.ro_dst;
1723			dst->sin_len = sizeof(*dst);
1724			dst->sin_family = AF_INET;
1725			dst->sin_addr = mreq.imr_multiaddr;
1726			rtalloc_ign(&ro, RTF_CLONING);
1727			if (ro.ro_rt == NULL) {
1728				error = EADDRNOTAVAIL;
1729				splx(s);
1730				break;
1731			}
1732			ifp = ro.ro_rt->rt_ifp;
1733			RTFREE(ro.ro_rt);
1734		}
1735		else {
1736			ifp = ip_multicast_if(&mreq.imr_interface, NULL);
1737		}
1738
1739		/*
1740		 * See if we found an interface, and confirm that it
1741		 * supports multicast.
1742		 */
1743		if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0) {
1744			error = EADDRNOTAVAIL;
1745			splx(s);
1746			break;
1747		}
1748		/*
1749		 * See if the membership already exists or if all the
1750		 * membership slots are full.
1751		 */
1752		for (i = 0; i < imo->imo_num_memberships; ++i) {
1753			if (imo->imo_membership[i]->inm_ifp == ifp &&
1754			    imo->imo_membership[i]->inm_addr.s_addr
1755						== mreq.imr_multiaddr.s_addr)
1756				break;
1757		}
1758		if (i < imo->imo_num_memberships) {
1759			error = EADDRINUSE;
1760			splx(s);
1761			break;
1762		}
1763		if (i == IP_MAX_MEMBERSHIPS) {
1764			error = ETOOMANYREFS;
1765			splx(s);
1766			break;
1767		}
1768		/*
1769		 * Everything looks good; add a new record to the multicast
1770		 * address list for the given interface.
1771		 */
1772		if ((imo->imo_membership[i] =
1773		    in_addmulti(&mreq.imr_multiaddr, ifp)) == NULL) {
1774			error = ENOBUFS;
1775			splx(s);
1776			break;
1777		}
1778		++imo->imo_num_memberships;
1779		splx(s);
1780		break;
1781
1782	case IP_DROP_MEMBERSHIP:
1783		/*
1784		 * Drop a multicast group membership.
1785		 * Group must be a valid IP multicast address.
1786		 */
1787		error = sooptcopyin(sopt, &mreq, sizeof mreq, sizeof mreq);
1788		if (error)
1789			break;
1790
1791		if (!IN_MULTICAST(ntohl(mreq.imr_multiaddr.s_addr))) {
1792			error = EINVAL;
1793			break;
1794		}
1795
1796		s = splimp();
1797		/*
1798		 * If an interface address was specified, get a pointer
1799		 * to its ifnet structure.
1800		 */
1801		if (mreq.imr_interface.s_addr == INADDR_ANY)
1802			ifp = NULL;
1803		else {
1804			ifp = ip_multicast_if(&mreq.imr_interface, NULL);
1805			if (ifp == NULL) {
1806				error = EADDRNOTAVAIL;
1807				splx(s);
1808				break;
1809			}
1810		}
1811		/*
1812		 * Find the membership in the membership array.
1813		 */
1814		for (i = 0; i < imo->imo_num_memberships; ++i) {
1815			if ((ifp == NULL ||
1816			     imo->imo_membership[i]->inm_ifp == ifp) &&
1817			     imo->imo_membership[i]->inm_addr.s_addr ==
1818			     mreq.imr_multiaddr.s_addr)
1819				break;
1820		}
1821		if (i == imo->imo_num_memberships) {
1822			error = EADDRNOTAVAIL;
1823			splx(s);
1824			break;
1825		}
1826		/*
1827		 * Give up the multicast address record to which the
1828		 * membership points.
1829		 */
1830		in_delmulti(imo->imo_membership[i]);
1831		/*
1832		 * Remove the gap in the membership array.
1833		 */
1834		for (++i; i < imo->imo_num_memberships; ++i)
1835			imo->imo_membership[i-1] = imo->imo_membership[i];
1836		--imo->imo_num_memberships;
1837		splx(s);
1838		break;
1839
1840	default:
1841		error = EOPNOTSUPP;
1842		break;
1843	}
1844
1845	/*
1846	 * If all options have default values, no need to keep the mbuf.
1847	 */
1848	if (imo->imo_multicast_ifp == NULL &&
1849	    imo->imo_multicast_vif == -1 &&
1850	    imo->imo_multicast_ttl == IP_DEFAULT_MULTICAST_TTL &&
1851	    imo->imo_multicast_loop == IP_DEFAULT_MULTICAST_LOOP &&
1852	    imo->imo_num_memberships == 0) {
1853		free(inp->inp_moptions, M_IPMOPTS);
1854		inp->inp_moptions = NULL;
1855	}
1856
1857	return (error);
1858}
1859
1860/*
1861 * Return the IP multicast options in response to user getsockopt().
1862 */
1863static int
1864ip_getmoptions(struct inpcb *inp, struct sockopt *sopt)
1865{
1866	struct ip_moptions *imo;
1867	struct in_addr addr;
1868	struct in_ifaddr *ia;
1869	int error, optval;
1870	u_char coptval;
1871
1872	INP_LOCK(inp);
1873	imo = inp->inp_moptions;
1874
1875	error = 0;
1876	switch (sopt->sopt_name) {
1877	case IP_MULTICAST_VIF:
1878		if (imo != NULL)
1879			optval = imo->imo_multicast_vif;
1880		else
1881			optval = -1;
1882		INP_UNLOCK(inp);
1883		error = sooptcopyout(sopt, &optval, sizeof optval);
1884		break;
1885
1886	case IP_MULTICAST_IF:
1887		if (imo == NULL || imo->imo_multicast_ifp == NULL)
1888			addr.s_addr = INADDR_ANY;
1889		else if (imo->imo_multicast_addr.s_addr) {
1890			/* return the value user has set */
1891			addr = imo->imo_multicast_addr;
1892		} else {
1893			IFP_TO_IA(imo->imo_multicast_ifp, ia);
1894			addr.s_addr = (ia == NULL) ? INADDR_ANY
1895				: IA_SIN(ia)->sin_addr.s_addr;
1896		}
1897		INP_UNLOCK(inp);
1898		error = sooptcopyout(sopt, &addr, sizeof addr);
1899		break;
1900
1901	case IP_MULTICAST_TTL:
1902		if (imo == 0)
1903			optval = coptval = IP_DEFAULT_MULTICAST_TTL;
1904		else
1905			optval = coptval = imo->imo_multicast_ttl;
1906		INP_UNLOCK(inp);
1907		if (sopt->sopt_valsize == 1)
1908			error = sooptcopyout(sopt, &coptval, 1);
1909		else
1910			error = sooptcopyout(sopt, &optval, sizeof optval);
1911		break;
1912
1913	case IP_MULTICAST_LOOP:
1914		if (imo == 0)
1915			optval = coptval = IP_DEFAULT_MULTICAST_LOOP;
1916		else
1917			optval = coptval = imo->imo_multicast_loop;
1918		INP_UNLOCK(inp);
1919		if (sopt->sopt_valsize == 1)
1920			error = sooptcopyout(sopt, &coptval, 1);
1921		else
1922			error = sooptcopyout(sopt, &optval, sizeof optval);
1923		break;
1924
1925	default:
1926		INP_UNLOCK(inp);
1927		error = ENOPROTOOPT;
1928		break;
1929	}
1930	INP_UNLOCK_ASSERT(inp);
1931
1932	return (error);
1933}
1934
1935/*
1936 * Discard the IP multicast options.
1937 */
1938void
1939ip_freemoptions(imo)
1940	register struct ip_moptions *imo;
1941{
1942	register int i;
1943
1944	if (imo != NULL) {
1945		for (i = 0; i < imo->imo_num_memberships; ++i)
1946			in_delmulti(imo->imo_membership[i]);
1947		free(imo, M_IPMOPTS);
1948	}
1949}
1950
1951/*
1952 * Routine called from ip_output() to loop back a copy of an IP multicast
1953 * packet to the input queue of a specified interface.  Note that this
1954 * calls the output routine of the loopback "driver", but with an interface
1955 * pointer that might NOT be a loopback interface -- evil, but easier than
1956 * replicating that code here.
1957 */
1958static void
1959ip_mloopback(ifp, m, dst, hlen)
1960	struct ifnet *ifp;
1961	register struct mbuf *m;
1962	register struct sockaddr_in *dst;
1963	int hlen;
1964{
1965	register struct ip *ip;
1966	struct mbuf *copym;
1967
1968	copym = m_copy(m, 0, M_COPYALL);
1969	if (copym != NULL && (copym->m_flags & M_EXT || copym->m_len < hlen))
1970		copym = m_pullup(copym, hlen);
1971	if (copym != NULL) {
1972		/* If needed, compute the checksum and mark it as valid. */
1973		if (copym->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
1974			in_delayed_cksum(copym);
1975			copym->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
1976			copym->m_pkthdr.csum_flags |=
1977			    CSUM_DATA_VALID | CSUM_PSEUDO_HDR;
1978			copym->m_pkthdr.csum_data = 0xffff;
1979		}
1980		/*
1981		 * We don't bother to fragment if the IP length is greater
1982		 * than the interface's MTU.  Can this possibly matter?
1983		 */
1984		ip = mtod(copym, struct ip *);
1985		ip->ip_len = htons(ip->ip_len);
1986		ip->ip_off = htons(ip->ip_off);
1987		ip->ip_sum = 0;
1988		ip->ip_sum = in_cksum(copym, hlen);
1989		/*
1990		 * NB:
1991		 * It's not clear whether there are any lingering
1992		 * reentrancy problems in other areas which might
1993		 * be exposed by using ip_input directly (in
1994		 * particular, everything which modifies the packet
1995		 * in-place).  Yet another option is using the
1996		 * protosw directly to deliver the looped back
1997		 * packet.  For the moment, we'll err on the side
1998		 * of safety by using if_simloop().
1999		 */
2000#if 1 /* XXX */
2001		if (dst->sin_family != AF_INET) {
2002			printf("ip_mloopback: bad address family %d\n",
2003						dst->sin_family);
2004			dst->sin_family = AF_INET;
2005		}
2006#endif
2007
2008#ifdef notdef
2009		copym->m_pkthdr.rcvif = ifp;
2010		ip_input(copym);
2011#else
2012		if_simloop(ifp, copym, dst->sin_family, 0);
2013#endif
2014	}
2015}
2016