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