ip_output.c revision 140675
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 140675 2005-01-23 19:43:46Z alc $
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		M_MOVE_PKTHDR(n, m);
1068		n->m_pkthdr.rcvif = (struct ifnet *)0;
1069#ifdef MAC
1070		mac_create_mbuf_from_mbuf(m, n);
1071#endif
1072		n->m_pkthdr.len += optlen;
1073		m->m_len -= sizeof(struct ip);
1074		m->m_data += sizeof(struct ip);
1075		n->m_next = m;
1076		m = n;
1077		m->m_len = optlen + sizeof(struct ip);
1078		m->m_data += max_linkhdr;
1079		bcopy(ip, mtod(m, void *), sizeof(struct ip));
1080	} else {
1081		m->m_data -= optlen;
1082		m->m_len += optlen;
1083		m->m_pkthdr.len += optlen;
1084		bcopy(ip, mtod(m, void *), sizeof(struct ip));
1085	}
1086	ip = mtod(m, struct ip *);
1087	bcopy(p->ipopt_list, ip + 1, optlen);
1088	*phlen = sizeof(struct ip) + optlen;
1089	ip->ip_v = IPVERSION;
1090	ip->ip_hl = *phlen >> 2;
1091	ip->ip_len += optlen;
1092	return (m);
1093}
1094
1095/*
1096 * Copy options from ip to jp,
1097 * omitting those not copied during fragmentation.
1098 */
1099int
1100ip_optcopy(ip, jp)
1101	struct ip *ip, *jp;
1102{
1103	register u_char *cp, *dp;
1104	int opt, optlen, cnt;
1105
1106	cp = (u_char *)(ip + 1);
1107	dp = (u_char *)(jp + 1);
1108	cnt = (ip->ip_hl << 2) - sizeof (struct ip);
1109	for (; cnt > 0; cnt -= optlen, cp += optlen) {
1110		opt = cp[0];
1111		if (opt == IPOPT_EOL)
1112			break;
1113		if (opt == IPOPT_NOP) {
1114			/* Preserve for IP mcast tunnel's LSRR alignment. */
1115			*dp++ = IPOPT_NOP;
1116			optlen = 1;
1117			continue;
1118		}
1119
1120		KASSERT(cnt >= IPOPT_OLEN + sizeof(*cp),
1121		    ("ip_optcopy: malformed ipv4 option"));
1122		optlen = cp[IPOPT_OLEN];
1123		KASSERT(optlen >= IPOPT_OLEN + sizeof(*cp) && optlen <= cnt,
1124		    ("ip_optcopy: malformed ipv4 option"));
1125
1126		/* bogus lengths should have been caught by ip_dooptions */
1127		if (optlen > cnt)
1128			optlen = cnt;
1129		if (IPOPT_COPIED(opt)) {
1130			bcopy(cp, dp, optlen);
1131			dp += optlen;
1132		}
1133	}
1134	for (optlen = dp - (u_char *)(jp+1); optlen & 0x3; optlen++)
1135		*dp++ = IPOPT_EOL;
1136	return (optlen);
1137}
1138
1139/*
1140 * IP socket option processing.
1141 */
1142int
1143ip_ctloutput(so, sopt)
1144	struct socket *so;
1145	struct sockopt *sopt;
1146{
1147	struct	inpcb *inp = sotoinpcb(so);
1148	int	error, optval;
1149
1150	error = optval = 0;
1151	if (sopt->sopt_level != IPPROTO_IP) {
1152		return (EINVAL);
1153	}
1154
1155	switch (sopt->sopt_dir) {
1156	case SOPT_SET:
1157		switch (sopt->sopt_name) {
1158		case IP_OPTIONS:
1159#ifdef notyet
1160		case IP_RETOPTS:
1161#endif
1162		{
1163			struct mbuf *m;
1164			if (sopt->sopt_valsize > MLEN) {
1165				error = EMSGSIZE;
1166				break;
1167			}
1168			MGET(m, sopt->sopt_td ? M_TRYWAIT : M_DONTWAIT, MT_HEADER);
1169			if (m == NULL) {
1170				error = ENOBUFS;
1171				break;
1172			}
1173			m->m_len = sopt->sopt_valsize;
1174			error = sooptcopyin(sopt, mtod(m, char *), m->m_len,
1175					    m->m_len);
1176			INP_LOCK(inp);
1177			error = ip_pcbopts(inp, sopt->sopt_name, m);
1178			INP_UNLOCK(inp);
1179			return (error);
1180		}
1181
1182		case IP_TOS:
1183		case IP_TTL:
1184		case IP_RECVOPTS:
1185		case IP_RECVRETOPTS:
1186		case IP_RECVDSTADDR:
1187		case IP_RECVTTL:
1188		case IP_RECVIF:
1189		case IP_FAITH:
1190		case IP_ONESBCAST:
1191			error = sooptcopyin(sopt, &optval, sizeof optval,
1192					    sizeof optval);
1193			if (error)
1194				break;
1195
1196			switch (sopt->sopt_name) {
1197			case IP_TOS:
1198				inp->inp_ip_tos = optval;
1199				break;
1200
1201			case IP_TTL:
1202				inp->inp_ip_ttl = optval;
1203				break;
1204#define	OPTSET(bit) do {						\
1205	INP_LOCK(inp);							\
1206	if (optval)							\
1207		inp->inp_flags |= bit;					\
1208	else								\
1209		inp->inp_flags &= ~bit;					\
1210	INP_UNLOCK(inp);						\
1211} while (0)
1212
1213			case IP_RECVOPTS:
1214				OPTSET(INP_RECVOPTS);
1215				break;
1216
1217			case IP_RECVRETOPTS:
1218				OPTSET(INP_RECVRETOPTS);
1219				break;
1220
1221			case IP_RECVDSTADDR:
1222				OPTSET(INP_RECVDSTADDR);
1223				break;
1224
1225			case IP_RECVTTL:
1226				OPTSET(INP_RECVTTL);
1227				break;
1228
1229			case IP_RECVIF:
1230				OPTSET(INP_RECVIF);
1231				break;
1232
1233			case IP_FAITH:
1234				OPTSET(INP_FAITH);
1235				break;
1236
1237			case IP_ONESBCAST:
1238				OPTSET(INP_ONESBCAST);
1239				break;
1240			}
1241			break;
1242#undef OPTSET
1243
1244		case IP_MULTICAST_IF:
1245		case IP_MULTICAST_VIF:
1246		case IP_MULTICAST_TTL:
1247		case IP_MULTICAST_LOOP:
1248		case IP_ADD_MEMBERSHIP:
1249		case IP_DROP_MEMBERSHIP:
1250			error = ip_setmoptions(inp, sopt);
1251			break;
1252
1253		case IP_PORTRANGE:
1254			error = sooptcopyin(sopt, &optval, sizeof optval,
1255					    sizeof optval);
1256			if (error)
1257				break;
1258
1259			INP_LOCK(inp);
1260			switch (optval) {
1261			case IP_PORTRANGE_DEFAULT:
1262				inp->inp_flags &= ~(INP_LOWPORT);
1263				inp->inp_flags &= ~(INP_HIGHPORT);
1264				break;
1265
1266			case IP_PORTRANGE_HIGH:
1267				inp->inp_flags &= ~(INP_LOWPORT);
1268				inp->inp_flags |= INP_HIGHPORT;
1269				break;
1270
1271			case IP_PORTRANGE_LOW:
1272				inp->inp_flags &= ~(INP_HIGHPORT);
1273				inp->inp_flags |= INP_LOWPORT;
1274				break;
1275
1276			default:
1277				error = EINVAL;
1278				break;
1279			}
1280			INP_UNLOCK(inp);
1281			break;
1282
1283#if defined(IPSEC) || defined(FAST_IPSEC)
1284		case IP_IPSEC_POLICY:
1285		{
1286			caddr_t req;
1287			size_t len = 0;
1288			int priv;
1289			struct mbuf *m;
1290			int optname;
1291
1292			if ((error = soopt_getm(sopt, &m)) != 0) /* XXX */
1293				break;
1294			if ((error = soopt_mcopyin(sopt, m)) != 0) /* XXX */
1295				break;
1296			priv = (sopt->sopt_td != NULL &&
1297				suser(sopt->sopt_td) != 0) ? 0 : 1;
1298			req = mtod(m, caddr_t);
1299			len = m->m_len;
1300			optname = sopt->sopt_name;
1301			error = ipsec4_set_policy(inp, optname, req, len, priv);
1302			m_freem(m);
1303			break;
1304		}
1305#endif /*IPSEC*/
1306
1307		default:
1308			error = ENOPROTOOPT;
1309			break;
1310		}
1311		break;
1312
1313	case SOPT_GET:
1314		switch (sopt->sopt_name) {
1315		case IP_OPTIONS:
1316		case IP_RETOPTS:
1317			if (inp->inp_options)
1318				error = sooptcopyout(sopt,
1319						     mtod(inp->inp_options,
1320							  char *),
1321						     inp->inp_options->m_len);
1322			else
1323				sopt->sopt_valsize = 0;
1324			break;
1325
1326		case IP_TOS:
1327		case IP_TTL:
1328		case IP_RECVOPTS:
1329		case IP_RECVRETOPTS:
1330		case IP_RECVDSTADDR:
1331		case IP_RECVTTL:
1332		case IP_RECVIF:
1333		case IP_PORTRANGE:
1334		case IP_FAITH:
1335		case IP_ONESBCAST:
1336			switch (sopt->sopt_name) {
1337
1338			case IP_TOS:
1339				optval = inp->inp_ip_tos;
1340				break;
1341
1342			case IP_TTL:
1343				optval = inp->inp_ip_ttl;
1344				break;
1345
1346#define	OPTBIT(bit)	(inp->inp_flags & bit ? 1 : 0)
1347
1348			case IP_RECVOPTS:
1349				optval = OPTBIT(INP_RECVOPTS);
1350				break;
1351
1352			case IP_RECVRETOPTS:
1353				optval = OPTBIT(INP_RECVRETOPTS);
1354				break;
1355
1356			case IP_RECVDSTADDR:
1357				optval = OPTBIT(INP_RECVDSTADDR);
1358				break;
1359
1360			case IP_RECVTTL:
1361				optval = OPTBIT(INP_RECVTTL);
1362				break;
1363
1364			case IP_RECVIF:
1365				optval = OPTBIT(INP_RECVIF);
1366				break;
1367
1368			case IP_PORTRANGE:
1369				if (inp->inp_flags & INP_HIGHPORT)
1370					optval = IP_PORTRANGE_HIGH;
1371				else if (inp->inp_flags & INP_LOWPORT)
1372					optval = IP_PORTRANGE_LOW;
1373				else
1374					optval = 0;
1375				break;
1376
1377			case IP_FAITH:
1378				optval = OPTBIT(INP_FAITH);
1379				break;
1380
1381			case IP_ONESBCAST:
1382				optval = OPTBIT(INP_ONESBCAST);
1383				break;
1384			}
1385			error = sooptcopyout(sopt, &optval, sizeof optval);
1386			break;
1387
1388		case IP_MULTICAST_IF:
1389		case IP_MULTICAST_VIF:
1390		case IP_MULTICAST_TTL:
1391		case IP_MULTICAST_LOOP:
1392		case IP_ADD_MEMBERSHIP:
1393		case IP_DROP_MEMBERSHIP:
1394			error = ip_getmoptions(inp, sopt);
1395			break;
1396
1397#if defined(IPSEC) || defined(FAST_IPSEC)
1398		case IP_IPSEC_POLICY:
1399		{
1400			struct mbuf *m = NULL;
1401			caddr_t req = NULL;
1402			size_t len = 0;
1403
1404			if (m != 0) {
1405				req = mtod(m, caddr_t);
1406				len = m->m_len;
1407			}
1408			error = ipsec4_get_policy(sotoinpcb(so), req, len, &m);
1409			if (error == 0)
1410				error = soopt_mcopyout(sopt, m); /* XXX */
1411			if (error == 0)
1412				m_freem(m);
1413			break;
1414		}
1415#endif /*IPSEC*/
1416
1417		default:
1418			error = ENOPROTOOPT;
1419			break;
1420		}
1421		break;
1422	}
1423	return (error);
1424}
1425
1426/*
1427 * Set up IP options in pcb for insertion in output packets.
1428 * Store in mbuf with pointer in pcbopt, adding pseudo-option
1429 * with destination address if source routed.
1430 */
1431static int
1432ip_pcbopts(struct inpcb *inp, int optname, struct mbuf *m)
1433{
1434	register int cnt, optlen;
1435	register u_char *cp;
1436	struct mbuf **pcbopt;
1437	u_char opt;
1438
1439	INP_LOCK_ASSERT(inp);
1440
1441	pcbopt = &inp->inp_options;
1442
1443	/* turn off any old options */
1444	if (*pcbopt)
1445		(void)m_free(*pcbopt);
1446	*pcbopt = 0;
1447	if (m == NULL || m->m_len == 0) {
1448		/*
1449		 * Only turning off any previous options.
1450		 */
1451		if (m != NULL)
1452			(void)m_free(m);
1453		return (0);
1454	}
1455
1456	if (m->m_len % sizeof(int32_t))
1457		goto bad;
1458	/*
1459	 * IP first-hop destination address will be stored before
1460	 * actual options; move other options back
1461	 * and clear it when none present.
1462	 */
1463	if (m->m_data + m->m_len + sizeof(struct in_addr) >= &m->m_dat[MLEN])
1464		goto bad;
1465	cnt = m->m_len;
1466	m->m_len += sizeof(struct in_addr);
1467	cp = mtod(m, u_char *) + sizeof(struct in_addr);
1468	bcopy(mtod(m, void *), cp, (unsigned)cnt);
1469	bzero(mtod(m, void *), sizeof(struct in_addr));
1470
1471	for (; cnt > 0; cnt -= optlen, cp += optlen) {
1472		opt = cp[IPOPT_OPTVAL];
1473		if (opt == IPOPT_EOL)
1474			break;
1475		if (opt == IPOPT_NOP)
1476			optlen = 1;
1477		else {
1478			if (cnt < IPOPT_OLEN + sizeof(*cp))
1479				goto bad;
1480			optlen = cp[IPOPT_OLEN];
1481			if (optlen < IPOPT_OLEN + sizeof(*cp) || optlen > cnt)
1482				goto bad;
1483		}
1484		switch (opt) {
1485
1486		default:
1487			break;
1488
1489		case IPOPT_LSRR:
1490		case IPOPT_SSRR:
1491			/*
1492			 * user process specifies route as:
1493			 *	->A->B->C->D
1494			 * D must be our final destination (but we can't
1495			 * check that since we may not have connected yet).
1496			 * A is first hop destination, which doesn't appear in
1497			 * actual IP option, but is stored before the options.
1498			 */
1499			if (optlen < IPOPT_MINOFF - 1 + sizeof(struct in_addr))
1500				goto bad;
1501			m->m_len -= sizeof(struct in_addr);
1502			cnt -= sizeof(struct in_addr);
1503			optlen -= sizeof(struct in_addr);
1504			cp[IPOPT_OLEN] = optlen;
1505			/*
1506			 * Move first hop before start of options.
1507			 */
1508			bcopy((caddr_t)&cp[IPOPT_OFFSET+1], mtod(m, caddr_t),
1509			    sizeof(struct in_addr));
1510			/*
1511			 * Then copy rest of options back
1512			 * to close up the deleted entry.
1513			 */
1514			bcopy((&cp[IPOPT_OFFSET+1] + sizeof(struct in_addr)),
1515			    &cp[IPOPT_OFFSET+1],
1516			    (unsigned)cnt - (IPOPT_MINOFF - 1));
1517			break;
1518		}
1519	}
1520	if (m->m_len > MAX_IPOPTLEN + sizeof(struct in_addr))
1521		goto bad;
1522	*pcbopt = m;
1523	return (0);
1524
1525bad:
1526	(void)m_free(m);
1527	return (EINVAL);
1528}
1529
1530/*
1531 * XXX
1532 * The whole multicast option thing needs to be re-thought.
1533 * Several of these options are equally applicable to non-multicast
1534 * transmission, and one (IP_MULTICAST_TTL) totally duplicates a
1535 * standard option (IP_TTL).
1536 */
1537
1538/*
1539 * following RFC1724 section 3.3, 0.0.0.0/8 is interpreted as interface index.
1540 */
1541static struct ifnet *
1542ip_multicast_if(a, ifindexp)
1543	struct in_addr *a;
1544	int *ifindexp;
1545{
1546	int ifindex;
1547	struct ifnet *ifp;
1548
1549	if (ifindexp)
1550		*ifindexp = 0;
1551	if (ntohl(a->s_addr) >> 24 == 0) {
1552		ifindex = ntohl(a->s_addr) & 0xffffff;
1553		if (ifindex < 0 || if_index < ifindex)
1554			return NULL;
1555		ifp = ifnet_byindex(ifindex);
1556		if (ifindexp)
1557			*ifindexp = ifindex;
1558	} else {
1559		INADDR_TO_IFP(*a, ifp);
1560	}
1561	return ifp;
1562}
1563
1564/*
1565 * Set the IP multicast options in response to user setsockopt().
1566 */
1567static int
1568ip_setmoptions(struct inpcb *inp, struct sockopt *sopt)
1569{
1570	int error = 0;
1571	int i;
1572	struct in_addr addr;
1573	struct ip_mreq mreq;
1574	struct ifnet *ifp;
1575	struct ip_moptions *imo;
1576	struct route ro;
1577	struct sockaddr_in *dst;
1578	int ifindex;
1579	int s;
1580
1581	imo = inp->inp_moptions;
1582	if (imo == NULL) {
1583		/*
1584		 * No multicast option buffer attached to the pcb;
1585		 * allocate one and initialize to default values.
1586		 */
1587		imo = (struct ip_moptions*)malloc(sizeof(*imo), M_IPMOPTS,
1588		    M_WAITOK);
1589
1590		if (imo == NULL)
1591			return (ENOBUFS);
1592		inp->inp_moptions = imo;
1593		imo->imo_multicast_ifp = NULL;
1594		imo->imo_multicast_addr.s_addr = INADDR_ANY;
1595		imo->imo_multicast_vif = -1;
1596		imo->imo_multicast_ttl = IP_DEFAULT_MULTICAST_TTL;
1597		imo->imo_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
1598		imo->imo_num_memberships = 0;
1599	}
1600
1601	switch (sopt->sopt_name) {
1602	/* store an index number for the vif you wanna use in the send */
1603	case IP_MULTICAST_VIF:
1604		if (legal_vif_num == 0) {
1605			error = EOPNOTSUPP;
1606			break;
1607		}
1608		error = sooptcopyin(sopt, &i, sizeof i, sizeof i);
1609		if (error)
1610			break;
1611		if (!legal_vif_num(i) && (i != -1)) {
1612			error = EINVAL;
1613			break;
1614		}
1615		imo->imo_multicast_vif = i;
1616		break;
1617
1618	case IP_MULTICAST_IF:
1619		/*
1620		 * Select the interface for outgoing multicast packets.
1621		 */
1622		error = sooptcopyin(sopt, &addr, sizeof addr, sizeof addr);
1623		if (error)
1624			break;
1625		/*
1626		 * INADDR_ANY is used to remove a previous selection.
1627		 * When no interface is selected, a default one is
1628		 * chosen every time a multicast packet is sent.
1629		 */
1630		if (addr.s_addr == INADDR_ANY) {
1631			imo->imo_multicast_ifp = NULL;
1632			break;
1633		}
1634		/*
1635		 * The selected interface is identified by its local
1636		 * IP address.  Find the interface and confirm that
1637		 * it supports multicasting.
1638		 */
1639		s = splimp();
1640		ifp = ip_multicast_if(&addr, &ifindex);
1641		if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0) {
1642			splx(s);
1643			error = EADDRNOTAVAIL;
1644			break;
1645		}
1646		imo->imo_multicast_ifp = ifp;
1647		if (ifindex)
1648			imo->imo_multicast_addr = addr;
1649		else
1650			imo->imo_multicast_addr.s_addr = INADDR_ANY;
1651		splx(s);
1652		break;
1653
1654	case IP_MULTICAST_TTL:
1655		/*
1656		 * Set the IP time-to-live for outgoing multicast packets.
1657		 * The original multicast API required a char argument,
1658		 * which is inconsistent with the rest of the socket API.
1659		 * We allow either a char or an int.
1660		 */
1661		if (sopt->sopt_valsize == 1) {
1662			u_char ttl;
1663			error = sooptcopyin(sopt, &ttl, 1, 1);
1664			if (error)
1665				break;
1666			imo->imo_multicast_ttl = ttl;
1667		} else {
1668			u_int ttl;
1669			error = sooptcopyin(sopt, &ttl, sizeof ttl,
1670					    sizeof ttl);
1671			if (error)
1672				break;
1673			if (ttl > 255)
1674				error = EINVAL;
1675			else
1676				imo->imo_multicast_ttl = ttl;
1677		}
1678		break;
1679
1680	case IP_MULTICAST_LOOP:
1681		/*
1682		 * Set the loopback flag for outgoing multicast packets.
1683		 * Must be zero or one.  The original multicast API required a
1684		 * char argument, which is inconsistent with the rest
1685		 * of the socket API.  We allow either a char or an int.
1686		 */
1687		if (sopt->sopt_valsize == 1) {
1688			u_char loop;
1689			error = sooptcopyin(sopt, &loop, 1, 1);
1690			if (error)
1691				break;
1692			imo->imo_multicast_loop = !!loop;
1693		} else {
1694			u_int loop;
1695			error = sooptcopyin(sopt, &loop, sizeof loop,
1696					    sizeof loop);
1697			if (error)
1698				break;
1699			imo->imo_multicast_loop = !!loop;
1700		}
1701		break;
1702
1703	case IP_ADD_MEMBERSHIP:
1704		/*
1705		 * Add a multicast group membership.
1706		 * Group must be a valid IP multicast address.
1707		 */
1708		error = sooptcopyin(sopt, &mreq, sizeof mreq, sizeof mreq);
1709		if (error)
1710			break;
1711
1712		if (!IN_MULTICAST(ntohl(mreq.imr_multiaddr.s_addr))) {
1713			error = EINVAL;
1714			break;
1715		}
1716		s = splimp();
1717		/*
1718		 * If no interface address was provided, use the interface of
1719		 * the route to the given multicast address.
1720		 */
1721		if (mreq.imr_interface.s_addr == INADDR_ANY) {
1722			bzero((caddr_t)&ro, sizeof(ro));
1723			dst = (struct sockaddr_in *)&ro.ro_dst;
1724			dst->sin_len = sizeof(*dst);
1725			dst->sin_family = AF_INET;
1726			dst->sin_addr = mreq.imr_multiaddr;
1727			rtalloc_ign(&ro, RTF_CLONING);
1728			if (ro.ro_rt == NULL) {
1729				error = EADDRNOTAVAIL;
1730				splx(s);
1731				break;
1732			}
1733			ifp = ro.ro_rt->rt_ifp;
1734			RTFREE(ro.ro_rt);
1735		}
1736		else {
1737			ifp = ip_multicast_if(&mreq.imr_interface, NULL);
1738		}
1739
1740		/*
1741		 * See if we found an interface, and confirm that it
1742		 * supports multicast.
1743		 */
1744		if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0) {
1745			error = EADDRNOTAVAIL;
1746			splx(s);
1747			break;
1748		}
1749		/*
1750		 * See if the membership already exists or if all the
1751		 * membership slots are full.
1752		 */
1753		for (i = 0; i < imo->imo_num_memberships; ++i) {
1754			if (imo->imo_membership[i]->inm_ifp == ifp &&
1755			    imo->imo_membership[i]->inm_addr.s_addr
1756						== mreq.imr_multiaddr.s_addr)
1757				break;
1758		}
1759		if (i < imo->imo_num_memberships) {
1760			error = EADDRINUSE;
1761			splx(s);
1762			break;
1763		}
1764		if (i == IP_MAX_MEMBERSHIPS) {
1765			error = ETOOMANYREFS;
1766			splx(s);
1767			break;
1768		}
1769		/*
1770		 * Everything looks good; add a new record to the multicast
1771		 * address list for the given interface.
1772		 */
1773		if ((imo->imo_membership[i] =
1774		    in_addmulti(&mreq.imr_multiaddr, ifp)) == NULL) {
1775			error = ENOBUFS;
1776			splx(s);
1777			break;
1778		}
1779		++imo->imo_num_memberships;
1780		splx(s);
1781		break;
1782
1783	case IP_DROP_MEMBERSHIP:
1784		/*
1785		 * Drop a multicast group membership.
1786		 * Group must be a valid IP multicast address.
1787		 */
1788		error = sooptcopyin(sopt, &mreq, sizeof mreq, sizeof mreq);
1789		if (error)
1790			break;
1791
1792		if (!IN_MULTICAST(ntohl(mreq.imr_multiaddr.s_addr))) {
1793			error = EINVAL;
1794			break;
1795		}
1796
1797		s = splimp();
1798		/*
1799		 * If an interface address was specified, get a pointer
1800		 * to its ifnet structure.
1801		 */
1802		if (mreq.imr_interface.s_addr == INADDR_ANY)
1803			ifp = NULL;
1804		else {
1805			ifp = ip_multicast_if(&mreq.imr_interface, NULL);
1806			if (ifp == NULL) {
1807				error = EADDRNOTAVAIL;
1808				splx(s);
1809				break;
1810			}
1811		}
1812		/*
1813		 * Find the membership in the membership array.
1814		 */
1815		for (i = 0; i < imo->imo_num_memberships; ++i) {
1816			if ((ifp == NULL ||
1817			     imo->imo_membership[i]->inm_ifp == ifp) &&
1818			     imo->imo_membership[i]->inm_addr.s_addr ==
1819			     mreq.imr_multiaddr.s_addr)
1820				break;
1821		}
1822		if (i == imo->imo_num_memberships) {
1823			error = EADDRNOTAVAIL;
1824			splx(s);
1825			break;
1826		}
1827		/*
1828		 * Give up the multicast address record to which the
1829		 * membership points.
1830		 */
1831		in_delmulti(imo->imo_membership[i]);
1832		/*
1833		 * Remove the gap in the membership array.
1834		 */
1835		for (++i; i < imo->imo_num_memberships; ++i)
1836			imo->imo_membership[i-1] = imo->imo_membership[i];
1837		--imo->imo_num_memberships;
1838		splx(s);
1839		break;
1840
1841	default:
1842		error = EOPNOTSUPP;
1843		break;
1844	}
1845
1846	/*
1847	 * If all options have default values, no need to keep the mbuf.
1848	 */
1849	if (imo->imo_multicast_ifp == NULL &&
1850	    imo->imo_multicast_vif == -1 &&
1851	    imo->imo_multicast_ttl == IP_DEFAULT_MULTICAST_TTL &&
1852	    imo->imo_multicast_loop == IP_DEFAULT_MULTICAST_LOOP &&
1853	    imo->imo_num_memberships == 0) {
1854		free(inp->inp_moptions, M_IPMOPTS);
1855		inp->inp_moptions = NULL;
1856	}
1857
1858	return (error);
1859}
1860
1861/*
1862 * Return the IP multicast options in response to user getsockopt().
1863 */
1864static int
1865ip_getmoptions(struct inpcb *inp, struct sockopt *sopt)
1866{
1867	struct ip_moptions *imo;
1868	struct in_addr addr;
1869	struct in_ifaddr *ia;
1870	int error, optval;
1871	u_char coptval;
1872
1873	INP_LOCK(inp);
1874	imo = inp->inp_moptions;
1875
1876	error = 0;
1877	switch (sopt->sopt_name) {
1878	case IP_MULTICAST_VIF:
1879		if (imo != NULL)
1880			optval = imo->imo_multicast_vif;
1881		else
1882			optval = -1;
1883		INP_UNLOCK(inp);
1884		error = sooptcopyout(sopt, &optval, sizeof optval);
1885		break;
1886
1887	case IP_MULTICAST_IF:
1888		if (imo == NULL || imo->imo_multicast_ifp == NULL)
1889			addr.s_addr = INADDR_ANY;
1890		else if (imo->imo_multicast_addr.s_addr) {
1891			/* return the value user has set */
1892			addr = imo->imo_multicast_addr;
1893		} else {
1894			IFP_TO_IA(imo->imo_multicast_ifp, ia);
1895			addr.s_addr = (ia == NULL) ? INADDR_ANY
1896				: IA_SIN(ia)->sin_addr.s_addr;
1897		}
1898		INP_UNLOCK(inp);
1899		error = sooptcopyout(sopt, &addr, sizeof addr);
1900		break;
1901
1902	case IP_MULTICAST_TTL:
1903		if (imo == 0)
1904			optval = coptval = IP_DEFAULT_MULTICAST_TTL;
1905		else
1906			optval = coptval = imo->imo_multicast_ttl;
1907		INP_UNLOCK(inp);
1908		if (sopt->sopt_valsize == 1)
1909			error = sooptcopyout(sopt, &coptval, 1);
1910		else
1911			error = sooptcopyout(sopt, &optval, sizeof optval);
1912		break;
1913
1914	case IP_MULTICAST_LOOP:
1915		if (imo == 0)
1916			optval = coptval = IP_DEFAULT_MULTICAST_LOOP;
1917		else
1918			optval = coptval = imo->imo_multicast_loop;
1919		INP_UNLOCK(inp);
1920		if (sopt->sopt_valsize == 1)
1921			error = sooptcopyout(sopt, &coptval, 1);
1922		else
1923			error = sooptcopyout(sopt, &optval, sizeof optval);
1924		break;
1925
1926	default:
1927		INP_UNLOCK(inp);
1928		error = ENOPROTOOPT;
1929		break;
1930	}
1931	INP_UNLOCK_ASSERT(inp);
1932
1933	return (error);
1934}
1935
1936/*
1937 * Discard the IP multicast options.
1938 */
1939void
1940ip_freemoptions(imo)
1941	register struct ip_moptions *imo;
1942{
1943	register int i;
1944
1945	if (imo != NULL) {
1946		for (i = 0; i < imo->imo_num_memberships; ++i)
1947			in_delmulti(imo->imo_membership[i]);
1948		free(imo, M_IPMOPTS);
1949	}
1950}
1951
1952/*
1953 * Routine called from ip_output() to loop back a copy of an IP multicast
1954 * packet to the input queue of a specified interface.  Note that this
1955 * calls the output routine of the loopback "driver", but with an interface
1956 * pointer that might NOT be a loopback interface -- evil, but easier than
1957 * replicating that code here.
1958 */
1959static void
1960ip_mloopback(ifp, m, dst, hlen)
1961	struct ifnet *ifp;
1962	register struct mbuf *m;
1963	register struct sockaddr_in *dst;
1964	int hlen;
1965{
1966	register struct ip *ip;
1967	struct mbuf *copym;
1968
1969	copym = m_copy(m, 0, M_COPYALL);
1970	if (copym != NULL && (copym->m_flags & M_EXT || copym->m_len < hlen))
1971		copym = m_pullup(copym, hlen);
1972	if (copym != NULL) {
1973		/* If needed, compute the checksum and mark it as valid. */
1974		if (copym->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
1975			in_delayed_cksum(copym);
1976			copym->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
1977			copym->m_pkthdr.csum_flags |=
1978			    CSUM_DATA_VALID | CSUM_PSEUDO_HDR;
1979			copym->m_pkthdr.csum_data = 0xffff;
1980		}
1981		/*
1982		 * We don't bother to fragment if the IP length is greater
1983		 * than the interface's MTU.  Can this possibly matter?
1984		 */
1985		ip = mtod(copym, struct ip *);
1986		ip->ip_len = htons(ip->ip_len);
1987		ip->ip_off = htons(ip->ip_off);
1988		ip->ip_sum = 0;
1989		ip->ip_sum = in_cksum(copym, hlen);
1990		/*
1991		 * NB:
1992		 * It's not clear whether there are any lingering
1993		 * reentrancy problems in other areas which might
1994		 * be exposed by using ip_input directly (in
1995		 * particular, everything which modifies the packet
1996		 * in-place).  Yet another option is using the
1997		 * protosw directly to deliver the looped back
1998		 * packet.  For the moment, we'll err on the side
1999		 * of safety by using if_simloop().
2000		 */
2001#if 1 /* XXX */
2002		if (dst->sin_family != AF_INET) {
2003			printf("ip_mloopback: bad address family %d\n",
2004						dst->sin_family);
2005			dst->sin_family = AF_INET;
2006		}
2007#endif
2008
2009#ifdef notdef
2010		copym->m_pkthdr.rcvif = ifp;
2011		ip_input(copym);
2012#else
2013		if_simloop(ifp, copym, dst->sin_family, 0);
2014#endif
2015	}
2016}
2017