ip_output.c revision 129126
11590Srgrimes/*
21590Srgrimes * Copyright (c) 1982, 1986, 1988, 1990, 1993
31590Srgrimes *	The Regents of the University of California.  All rights reserved.
41590Srgrimes *
51590Srgrimes * Redistribution and use in source and binary forms, with or without
61590Srgrimes * modification, are permitted provided that the following conditions
71590Srgrimes * are met:
81590Srgrimes * 1. Redistributions of source code must retain the above copyright
91590Srgrimes *    notice, this list of conditions and the following disclaimer.
101590Srgrimes * 2. Redistributions in binary form must reproduce the above copyright
111590Srgrimes *    notice, this list of conditions and the following disclaimer in the
121590Srgrimes *    documentation and/or other materials provided with the distribution.
131590Srgrimes * 4. Neither the name of the University nor the names of its contributors
141590Srgrimes *    may be used to endorse or promote products derived from this software
151590Srgrimes *    without specific prior written permission.
161590Srgrimes *
171590Srgrimes * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
181590Srgrimes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
191590Srgrimes * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
201590Srgrimes * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
211590Srgrimes * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
221590Srgrimes * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
231590Srgrimes * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
241590Srgrimes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
251590Srgrimes * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
261590Srgrimes * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
271590Srgrimes * SUCH DAMAGE.
281590Srgrimes *
291590Srgrimes *	@(#)ip_output.c	8.3 (Berkeley) 1/21/94
301590Srgrimes * $FreeBSD: head/sys/netinet/ip_output.c 129126 2004-05-11 19:14:44Z maxim $
311590Srgrimes */
321590Srgrimes
331590Srgrimes#include "opt_ipfw.h"
341590Srgrimes#include "opt_ipdn.h"
3528454Scharnier#include "opt_ipdivert.h"
361590Srgrimes#include "opt_ipfilter.h"
371590Srgrimes#include "opt_ipsec.h"
381590Srgrimes#include "opt_mac.h"
391590Srgrimes#include "opt_pfil_hooks.h"
401590Srgrimes#include "opt_random_ip_id.h"
4128454Scharnier#include "opt_mbuf_stress_test.h"
421590Srgrimes
4328454Scharnier#include <sys/param.h>
4428454Scharnier#include <sys/systm.h>
4550477Speter#include <sys/kernel.h>
461590Srgrimes#include <sys/mac.h>
471590Srgrimes#include <sys/malloc.h>
4828454Scharnier#include <sys/mbuf.h>
491590Srgrimes#include <sys/protosw.h>
5028454Scharnier#include <sys/socket.h>
5128454Scharnier#include <sys/socketvar.h>
5228454Scharnier#include <sys/sysctl.h>
5328454Scharnier
541590Srgrimes#include <net/if.h>
551590Srgrimes#include <net/route.h>
561590Srgrimes
571590Srgrimes#include <netinet/in.h>
581590Srgrimes#include <netinet/in_systm.h>
591590Srgrimes#include <netinet/ip.h>
601590Srgrimes#include <netinet/in_pcb.h>
611590Srgrimes#include <netinet/in_var.h>
621590Srgrimes#include <netinet/ip_var.h>
631590Srgrimes
641590Srgrimes#ifdef PFIL_HOOKS
651590Srgrimes#include <net/pfil.h>
661590Srgrimes#endif
671590Srgrimes
681590Srgrimes#include <machine/in_cksum.h>
691590Srgrimes
701590Srgrimesstatic MALLOC_DEFINE(M_IPMOPTS, "ip_moptions", "internet multicast options");
711590Srgrimes
721590Srgrimes#ifdef IPSEC
731590Srgrimes#include <netinet6/ipsec.h>
741590Srgrimes#include <netkey/key.h>
751590Srgrimes#ifdef IPSEC_DEBUG
761590Srgrimes#include <netkey/key_debug.h>
771590Srgrimes#else
781590Srgrimes#define	KEYDEBUG(lev,arg)
791590Srgrimes#endif
801590Srgrimes#endif /*IPSEC*/
811590Srgrimes
821590Srgrimes#ifdef FAST_IPSEC
831590Srgrimes#include <netipsec/ipsec.h>
841590Srgrimes#include <netipsec/xform.h>
851590Srgrimes#include <netipsec/key.h>
861590Srgrimes#endif /*FAST_IPSEC*/
8728454Scharnier
8828454Scharnier#include <netinet/ip_fw.h>
8928454Scharnier#include <netinet/ip_divert.h>
9028454Scharnier#include <netinet/ip_dummynet.h>
9128454Scharnier
9228454Scharnier#define print_ip(x, a, y)	 printf("%s %d.%d.%d.%d%s",\
9328454Scharnier				x, (ntohl(a.s_addr)>>24)&0xFF,\
9428454Scharnier				  (ntohl(a.s_addr)>>16)&0xFF,\
9528454Scharnier				  (ntohl(a.s_addr)>>8)&0xFF,\
9628454Scharnier				  (ntohl(a.s_addr))&0xFF, y);
9728454Scharnier
9828454Scharnieru_short ip_id;
9928454Scharnier
1001590Srgrimes#ifdef MBUF_STRESS_TEST
1011590Srgrimesint mbuf_frag_size = 0;
10228789ScharnierSYSCTL_INT(_net_inet_ip, OID_AUTO, mbuf_frag_size, CTLFLAG_RW,
1031590Srgrimes	&mbuf_frag_size, 0, "Fragment outgoing mbufs to this size");
1041590Srgrimes#endif
1051590Srgrimes
1061590Srgrimesstatic struct mbuf *ip_insertoptions(struct mbuf *, struct mbuf *, int *);
1071590Srgrimesstatic struct ifnet *ip_multicast_if(struct in_addr *, int *);
1081590Srgrimesstatic void	ip_mloopback
1091590Srgrimes	(struct ifnet *, struct mbuf *, struct sockaddr_in *, int);
1101590Srgrimesstatic int	ip_getmoptions
1111590Srgrimes	(struct sockopt *, struct ip_moptions *);
1121590Srgrimesstatic int	ip_pcbopts(int, struct mbuf **, struct mbuf *);
1131590Srgrimesstatic int	ip_setmoptions
1141590Srgrimes	(struct sockopt *, struct ip_moptions **);
11524360Simp
1161590Srgrimesint	ip_optcopy(struct ip *, struct ip *);
1171590Srgrimes
1181590Srgrimes
1191590Srgrimesextern	struct protosw inetsw[];
1201590Srgrimes
1211590Srgrimes/*
1221590Srgrimes * IP output.  The packet in mbuf chain m contains a skeletal IP
1231590Srgrimes * header (with len, off, ttl, proto, tos, src, dst).
1241590Srgrimes * The mbuf chain containing the packet will be freed.
1251590Srgrimes * The mbuf opt, if present, will not be freed.
12628454Scharnier * In the IP forwarding case, the packet will arrive with options already
1271590Srgrimes * inserted, so must have a NULL opt pointer.
1281590Srgrimes */
1291590Srgrimesint
1301590Srgrimesip_output(struct mbuf *m, struct mbuf *opt, struct route *ro,
1311590Srgrimes	int flags, struct ip_moptions *imo, struct inpcb *inp)
1321590Srgrimes{
1331590Srgrimes	struct ip *ip;
1341590Srgrimes	struct ifnet *ifp = NULL;	/* keep compiler happy */
13528454Scharnier	struct mbuf *m0;
1361590Srgrimes	int hlen = sizeof (struct ip);
1371590Srgrimes	int len, off, error = 0;
1381590Srgrimes	struct sockaddr_in *dst = NULL;	/* keep compiler happy */
1391590Srgrimes	struct in_ifaddr *ia = NULL;
1401590Srgrimes	int isbroadcast, sw_csum;
1411590Srgrimes	struct in_addr pkt_dst;
1421590Srgrimes	struct route iproute;
1431590Srgrimes	struct m_tag *mtag, *dummytag;
1441590Srgrimes#ifdef IPSEC
1451590Srgrimes	struct secpolicy *sp = NULL;
1461590Srgrimes#endif
1471590Srgrimes#ifdef FAST_IPSEC
1481590Srgrimes	struct secpolicy *sp = NULL;
1491590Srgrimes	struct tdb_ident *tdbi;
1501590Srgrimes	int s;
1511590Srgrimes#endif /* FAST_IPSEC */
15228454Scharnier	struct ip_fw_args args;
15328454Scharnier	int src_was_INADDR_ANY = 0;	/* as the name says... */
15428454Scharnier
1551590Srgrimes	args.eh = NULL;
1561590Srgrimes	args.rule = NULL;
1571590Srgrimes
1581590Srgrimes	M_ASSERTPKTHDR(m);
1591590Srgrimes
16028454Scharnier	args.next_hop = m_claim_next(m, PACKET_TAG_IPFORWARD);
16128454Scharnier	dummytag = m_tag_find(m, PACKET_TAG_DUMMYNET, NULL);
16228454Scharnier	if (dummytag != NULL) {
16328454Scharnier		struct dn_pkt_tag *dt = (struct dn_pkt_tag *)(dummytag+1);
16428454Scharnier		/*
16528454Scharnier		 * Prevent lower layers from finding the tag
16628454Scharnier		 * Cleanup and free is done below
16728454Scharnier		 */
1681590Srgrimes		m_tag_unlink(m, dummytag);
1691590Srgrimes		/*
1701590Srgrimes		 * the packet was already tagged, so part of the
1711590Srgrimes		 * processing was already done, and we need to go down.
1721590Srgrimes		 * Get parameters from the header.
1731590Srgrimes		 */
1741590Srgrimes		args.rule = dt->rule;
1751590Srgrimes		ro = &(dt->ro);
1761590Srgrimes		dst = dt->dn_dst;
1771590Srgrimes		ifp = dt->ifp;
1781590Srgrimes	}
1791590Srgrimes
1801590Srgrimes	if (ro == NULL) {
1811590Srgrimes		ro = &iproute;
1821590Srgrimes		bzero(ro, sizeof (*ro));
1831590Srgrimes	}
1841590Srgrimes
1851590Srgrimes	if (inp != NULL)
1861590Srgrimes		INP_LOCK_ASSERT(inp);
1871590Srgrimes
1881590Srgrimes	if (args.rule != NULL) {	/* dummynet already saw us */
1891590Srgrimes		ip = mtod(m, struct ip *);
1901590Srgrimes		hlen = ip->ip_hl << 2 ;
1911590Srgrimes		if (ro->ro_rt)
1921590Srgrimes			ia = ifatoia(ro->ro_rt->rt_ifa);
1931590Srgrimes		goto sendit;
1941590Srgrimes	}
1951590Srgrimes
1961590Srgrimes	if (opt) {
1971590Srgrimes		len = 0;
1981590Srgrimes		m = ip_insertoptions(m, opt, &len);
1991590Srgrimes		if (len != 0)
2001590Srgrimes			hlen = len;
2011590Srgrimes	}
2021590Srgrimes	ip = mtod(m, struct ip *);
2031590Srgrimes	pkt_dst = args.next_hop ? args.next_hop->sin_addr : ip->ip_dst;
2041590Srgrimes
2051590Srgrimes	/*
2061590Srgrimes	 * Fill in IP header.  If we are not allowing fragmentation,
2071590Srgrimes	 * then the ip_id field is meaningless, but we don't set it
2081590Srgrimes	 * to zero.  Doing so causes various problems when devices along
2091590Srgrimes	 * the path (routers, load balancers, firewalls, etc.) illegally
2101590Srgrimes	 * disable DF on our packet.  Note that a 16-bit counter
2111590Srgrimes	 * will wrap around in less than 10 seconds at 100 Mbit/s on a
2121590Srgrimes	 * medium with MTU 1500.  See Steven M. Bellovin, "A Technique
2131590Srgrimes	 * for Counting NATted Hosts", Proc. IMW'02, available at
2141590Srgrimes	 * <http://www.research.att.com/~smb/papers/fnat.pdf>.
2151590Srgrimes	 */
2161590Srgrimes	if ((flags & (IP_FORWARDING|IP_RAWOUTPUT)) == 0) {
2171590Srgrimes		ip->ip_v = IPVERSION;
2181590Srgrimes		ip->ip_hl = hlen >> 2;
2191590Srgrimes#ifdef RANDOM_IP_ID
2201590Srgrimes		ip->ip_id = ip_randomid();
2211590Srgrimes#else
2221590Srgrimes		ip->ip_id = htons(ip_id++);
2231590Srgrimes#endif
2241590Srgrimes		ipstat.ips_localout++;
2251590Srgrimes	} else {
2261590Srgrimes		hlen = ip->ip_hl << 2;
2271590Srgrimes	}
2281590Srgrimes
2291590Srgrimes	dst = (struct sockaddr_in *)&ro->ro_dst;
2301590Srgrimes	/*
2311590Srgrimes	 * If there is a cached route,
23228454Scharnier	 * check that it is to the same destination
2331590Srgrimes	 * and is still up.  If not, free it and try again.
2341590Srgrimes	 * The address family should also be checked in case of sharing the
2351590Srgrimes	 * cache with IPv6.
2361590Srgrimes	 */
2371590Srgrimes	if (ro->ro_rt && ((ro->ro_rt->rt_flags & RTF_UP) == 0 ||
2381590Srgrimes			  dst->sin_family != AF_INET ||
2391590Srgrimes			  dst->sin_addr.s_addr != pkt_dst.s_addr)) {
2401590Srgrimes		RTFREE(ro->ro_rt);
2411590Srgrimes		ro->ro_rt = (struct rtentry *)0;
2421590Srgrimes	}
2431590Srgrimes	if (ro->ro_rt == 0) {
2441590Srgrimes		bzero(dst, sizeof(*dst));
2451590Srgrimes		dst->sin_family = AF_INET;
2461590Srgrimes		dst->sin_len = sizeof(*dst);
2471590Srgrimes		dst->sin_addr = pkt_dst;
2481590Srgrimes	}
2491590Srgrimes	/*
2501590Srgrimes	 * If routing to interface only,
2511590Srgrimes	 * short circuit routing lookup.
2521590Srgrimes	 */
2531590Srgrimes	if (flags & IP_ROUTETOIF) {
2541590Srgrimes		if ((ia = ifatoia(ifa_ifwithdstaddr(sintosa(dst)))) == 0 &&
2551590Srgrimes		    (ia = ifatoia(ifa_ifwithnet(sintosa(dst)))) == 0) {
2561590Srgrimes			ipstat.ips_noroute++;
2571590Srgrimes			error = ENETUNREACH;
2581590Srgrimes			goto bad;
2591590Srgrimes		}
2601590Srgrimes		ifp = ia->ia_ifp;
2611590Srgrimes		ip->ip_ttl = 1;
2621590Srgrimes		isbroadcast = in_broadcast(dst->sin_addr, ifp);
2631590Srgrimes	} else if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) &&
2641590Srgrimes	    imo != NULL && imo->imo_multicast_ifp != NULL) {
2651590Srgrimes		/*
2661590Srgrimes		 * Bypass the normal routing lookup for multicast
2671590Srgrimes		 * packets if the interface is specified.
2681590Srgrimes		 */
2691590Srgrimes		ifp = imo->imo_multicast_ifp;
2701590Srgrimes		IFP_TO_IA(ifp, ia);
2711590Srgrimes		isbroadcast = 0;	/* fool gcc */
2721590Srgrimes	} else {
2731590Srgrimes		/*
2741590Srgrimes		 * We want to do any cloning requested by the link layer,
2751590Srgrimes		 * as this is probably required in all cases for correct
2761590Srgrimes		 * operation (as it is for ARP).
2771590Srgrimes		 */
27828454Scharnier		if (ro->ro_rt == 0)
2791590Srgrimes			rtalloc_ign(ro, 0);
2801590Srgrimes		if (ro->ro_rt == 0) {
2811590Srgrimes			ipstat.ips_noroute++;
2821590Srgrimes			error = EHOSTUNREACH;
2831590Srgrimes			goto bad;
2841590Srgrimes		}
2851590Srgrimes		ia = ifatoia(ro->ro_rt->rt_ifa);
2861590Srgrimes		ifp = ro->ro_rt->rt_ifp;
2871590Srgrimes		ro->ro_rt->rt_rmx.rmx_pksent++;
2881590Srgrimes		if (ro->ro_rt->rt_flags & RTF_GATEWAY)
28928454Scharnier			dst = (struct sockaddr_in *)ro->ro_rt->rt_gateway;
2901590Srgrimes		if (ro->ro_rt->rt_flags & RTF_HOST)
2911590Srgrimes			isbroadcast = (ro->ro_rt->rt_flags & RTF_BROADCAST);
2921590Srgrimes		else
2931590Srgrimes			isbroadcast = in_broadcast(dst->sin_addr, ifp);
2941590Srgrimes	}
2951590Srgrimes	if (IN_MULTICAST(ntohl(pkt_dst.s_addr))) {
2961590Srgrimes		struct in_multi *inm;
2971590Srgrimes
2981590Srgrimes		m->m_flags |= M_MCAST;
2991590Srgrimes		/*
3001590Srgrimes		 * IP destination address is multicast.  Make sure "dst"
30128454Scharnier		 * still points to the address in "ro".  (It may have been
3021590Srgrimes		 * changed to point to a gateway address, above.)
3031590Srgrimes		 */
3041590Srgrimes		dst = (struct sockaddr_in *)&ro->ro_dst;
3051590Srgrimes		/*
3061590Srgrimes		 * See if the caller provided any multicast options
3071590Srgrimes		 */
3081590Srgrimes		if (imo != NULL) {
3091590Srgrimes			ip->ip_ttl = imo->imo_multicast_ttl;
3101590Srgrimes			if (imo->imo_multicast_vif != -1)
3111590Srgrimes				ip->ip_src.s_addr =
3121590Srgrimes				    ip_mcast_src ?
3131590Srgrimes				    ip_mcast_src(imo->imo_multicast_vif) :
3141590Srgrimes				    INADDR_ANY;
3151590Srgrimes		} else
3161590Srgrimes			ip->ip_ttl = IP_DEFAULT_MULTICAST_TTL;
3171590Srgrimes		/*
31828454Scharnier		 * Confirm that the outgoing interface supports multicast.
3191590Srgrimes		 */
3201590Srgrimes		if ((imo == NULL) || (imo->imo_multicast_vif == -1)) {
3211590Srgrimes			if ((ifp->if_flags & IFF_MULTICAST) == 0) {
3221590Srgrimes				ipstat.ips_noroute++;
3231590Srgrimes				error = ENETUNREACH;
3241590Srgrimes				goto bad;
3251590Srgrimes			}
3261590Srgrimes		}
3271590Srgrimes		/*
3281590Srgrimes		 * If source address not specified yet, use address
3291590Srgrimes		 * of outgoing interface.
3301590Srgrimes		 */
3311590Srgrimes		if (ip->ip_src.s_addr == INADDR_ANY) {
3321590Srgrimes			/* Interface may have no addresses. */
3331590Srgrimes			if (ia != NULL)
3341590Srgrimes				ip->ip_src = IA_SIN(ia)->sin_addr;
3351590Srgrimes		}
3361590Srgrimes
3371590Srgrimes		IN_LOOKUP_MULTI(pkt_dst, ifp, inm);
3381590Srgrimes		if (inm != NULL &&
3391590Srgrimes		   (imo == NULL || imo->imo_multicast_loop)) {
3401590Srgrimes			/*
3411590Srgrimes			 * If we belong to the destination multicast group
3421590Srgrimes			 * on the outgoing interface, and the caller did not
3431590Srgrimes			 * forbid loopback, loop back a copy.
3441590Srgrimes			 */
3451590Srgrimes			ip_mloopback(ifp, m, dst, hlen);
3461590Srgrimes		}
3471590Srgrimes		else {
3481590Srgrimes			/*
3491590Srgrimes			 * If we are acting as a multicast router, perform
3501590Srgrimes			 * multicast forwarding as if the packet had just
3511590Srgrimes			 * arrived on the interface to which we are about
3521590Srgrimes			 * to send.  The multicast forwarding function
3531590Srgrimes			 * recursively calls this function, using the
3541590Srgrimes			 * IP_FORWARDING flag to prevent infinite recursion.
3551590Srgrimes			 *
35628454Scharnier			 * Multicasts that are looped back by ip_mloopback(),
3571590Srgrimes			 * above, will be forwarded by the ip_input() routine,
3581590Srgrimes			 * if necessary.
3591590Srgrimes			 */
3601590Srgrimes			if (ip_mrouter && (flags & IP_FORWARDING) == 0) {
3611590Srgrimes				/*
3621590Srgrimes				 * If rsvp daemon is not running, do not
3631590Srgrimes				 * set ip_moptions. This ensures that the packet
3641590Srgrimes				 * is multicast and not just sent down one link
3651590Srgrimes				 * as prescribed by rsvpd.
3661590Srgrimes				 */
3671590Srgrimes				if (!rsvp_on)
3681590Srgrimes					imo = NULL;
3691590Srgrimes				if (ip_mforward &&
3701590Srgrimes				    ip_mforward(ip, ifp, m, imo) != 0) {
3711590Srgrimes					m_freem(m);
3721590Srgrimes					goto done;
3731590Srgrimes				}
3741590Srgrimes			}
3751590Srgrimes		}
3761590Srgrimes
3771590Srgrimes		/*
3781590Srgrimes		 * Multicasts with a time-to-live of zero may be looped-
3791590Srgrimes		 * back, above, but must not be transmitted on a network.
38028454Scharnier		 * Also, multicasts addressed to the loopback interface
3811590Srgrimes		 * are not sent -- the above call to ip_mloopback() will
3821590Srgrimes		 * loop back a copy if this host actually belongs to the
3831590Srgrimes		 * destination group on the loopback interface.
3841590Srgrimes		 */
3851590Srgrimes		if (ip->ip_ttl == 0 || ifp->if_flags & IFF_LOOPBACK) {
3861590Srgrimes			m_freem(m);
3871590Srgrimes			goto done;
3881590Srgrimes		}
3891590Srgrimes
39028454Scharnier		goto sendit;
3911590Srgrimes	}
3921590Srgrimes#ifndef notdef
3931590Srgrimes	/*
3941590Srgrimes	 * If the source address is not specified yet, use the address
3951590Srgrimes	 * of the outoing interface. In case, keep note we did that, so
3961590Srgrimes	 * if the the firewall changes the next-hop causing the output
3971590Srgrimes	 * interface to change, we can fix that.
3981590Srgrimes	 */
3991590Srgrimes	if (ip->ip_src.s_addr == INADDR_ANY) {
4001590Srgrimes		/* Interface may have no addresses. */
4011590Srgrimes		if (ia != NULL) {
40228454Scharnier			ip->ip_src = IA_SIN(ia)->sin_addr;
4031590Srgrimes			src_was_INADDR_ANY = 1;
4041590Srgrimes		}
4051590Srgrimes	}
4061590Srgrimes#endif /* notdef */
4071590Srgrimes	/*
4081590Srgrimes	 * Verify that we have any chance at all of being able to queue
4091590Srgrimes	 *      the packet or packet fragments
4101590Srgrimes	 */
4111590Srgrimes	if ((ifp->if_snd.ifq_len + ip->ip_len / ifp->if_mtu + 1) >=
41228454Scharnier		ifp->if_snd.ifq_maxlen) {
4131590Srgrimes			error = ENOBUFS;
4141590Srgrimes			ipstat.ips_odropped++;
4151590Srgrimes			goto bad;
4161590Srgrimes	}
4171590Srgrimes
4181590Srgrimes	/*
4191590Srgrimes	 * Look for broadcast address and
4201590Srgrimes	 * verify user is allowed to send
4211590Srgrimes	 * such a packet.
4221590Srgrimes	 */
4231590Srgrimes	if (isbroadcast) {
4241590Srgrimes		if ((ifp->if_flags & IFF_BROADCAST) == 0) {
4251590Srgrimes			error = EADDRNOTAVAIL;
4261590Srgrimes			goto bad;
4271590Srgrimes		}
4281590Srgrimes		if ((flags & IP_ALLOWBROADCAST) == 0) {
4291590Srgrimes			error = EACCES;
4301590Srgrimes			goto bad;
4311590Srgrimes		}
4321590Srgrimes		/* don't allow broadcast messages to be fragmented */
4331590Srgrimes		if (ip->ip_len > ifp->if_mtu) {
4341590Srgrimes			error = EMSGSIZE;
4351590Srgrimes			goto bad;
4361590Srgrimes		}
4371590Srgrimes		if (flags & IP_SENDONES)
4381590Srgrimes			ip->ip_dst.s_addr = INADDR_BROADCAST;
4391590Srgrimes		m->m_flags |= M_BCAST;
4401590Srgrimes	} else {
4411590Srgrimes		m->m_flags &= ~M_BCAST;
4421590Srgrimes	}
4431590Srgrimes
4441590Srgrimessendit:
4451590Srgrimes#ifdef IPSEC
4461590Srgrimes	/* get SP for this packet */
4471590Srgrimes	if (inp == NULL)
4481590Srgrimes		sp = ipsec4_getpolicybyaddr(m, IPSEC_DIR_OUTBOUND,
4491590Srgrimes		    flags, &error);
4501590Srgrimes	else
4511590Srgrimes		sp = ipsec4_getpolicybypcb(m, IPSEC_DIR_OUTBOUND, inp, &error);
4528874Srgrimes
4531590Srgrimes	if (sp == NULL) {
4541590Srgrimes		ipsecstat.out_inval++;
4551590Srgrimes		goto bad;
4561590Srgrimes	}
4571590Srgrimes
4581590Srgrimes	error = 0;
4591590Srgrimes
4601590Srgrimes	/* check policy */
4611590Srgrimes	switch (sp->policy) {
4621590Srgrimes	case IPSEC_POLICY_DISCARD:
4631590Srgrimes		/*
4641590Srgrimes		 * This packet is just discarded.
46528454Scharnier		 */
4661590Srgrimes		ipsecstat.out_polvio++;
4671590Srgrimes		goto bad;
4681590Srgrimes
46928454Scharnier	case IPSEC_POLICY_BYPASS:
4701590Srgrimes	case IPSEC_POLICY_NONE:
4711590Srgrimes	case IPSEC_POLICY_TCP:
4721590Srgrimes		/* no need to do IPsec. */
4731590Srgrimes		goto skip_ipsec;
47428454Scharnier
4751590Srgrimes	case IPSEC_POLICY_IPSEC:
4761590Srgrimes		if (sp->req == NULL) {
4771590Srgrimes			/* acquire a policy */
4781590Srgrimes			error = key_spdacquire(sp);
4791590Srgrimes			goto bad;
4801590Srgrimes		}
4811590Srgrimes		break;
4821590Srgrimes
4831590Srgrimes	case IPSEC_POLICY_ENTRUST:
4841590Srgrimes	default:
48528454Scharnier		printf("ip_output: Invalid policy found. %d\n", sp->policy);
48628454Scharnier	}
4871590Srgrimes    {
4881590Srgrimes	struct ipsec_output_state state;
4891590Srgrimes	bzero(&state, sizeof(state));
4901590Srgrimes	state.m = m;
49128454Scharnier	if (flags & IP_ROUTETOIF) {
4921590Srgrimes		state.ro = &iproute;
4931590Srgrimes		bzero(&iproute, sizeof(iproute));
4941590Srgrimes	} else
4951590Srgrimes		state.ro = ro;
4961590Srgrimes	state.dst = (struct sockaddr *)dst;
4971590Srgrimes
4981590Srgrimes	ip->ip_sum = 0;
4991590Srgrimes
5001590Srgrimes	/*
5011590Srgrimes	 * XXX
5021590Srgrimes	 * delayed checksums are not currently compatible with IPsec
5031590Srgrimes	 */
5041590Srgrimes	if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
5051590Srgrimes		in_delayed_cksum(m);
5061590Srgrimes		m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
5071590Srgrimes	}
5081590Srgrimes
5091590Srgrimes	ip->ip_len = htons(ip->ip_len);
5101590Srgrimes	ip->ip_off = htons(ip->ip_off);
5111590Srgrimes
5121590Srgrimes	error = ipsec4_output(&state, sp, flags);
5131590Srgrimes
5141590Srgrimes	m = state.m;
5151590Srgrimes	if (flags & IP_ROUTETOIF) {
5161590Srgrimes		/*
5171590Srgrimes		 * if we have tunnel mode SA, we may need to ignore
5181590Srgrimes		 * IP_ROUTETOIF.
5191590Srgrimes		 */
5201590Srgrimes		if (state.ro != &iproute || state.ro->ro_rt != NULL) {
5211590Srgrimes			flags &= ~IP_ROUTETOIF;
5221590Srgrimes			ro = state.ro;
5231590Srgrimes		}
5241590Srgrimes	} else
5251590Srgrimes		ro = state.ro;
5261590Srgrimes	dst = (struct sockaddr_in *)state.dst;
5271590Srgrimes	if (error) {
5281590Srgrimes		/* mbuf is already reclaimed in ipsec4_output. */
5291590Srgrimes		m = NULL;
5301590Srgrimes		switch (error) {
5311590Srgrimes		case EHOSTUNREACH:
5321590Srgrimes		case ENETUNREACH:
5331590Srgrimes		case EMSGSIZE:
5341590Srgrimes		case ENOBUFS:
5351590Srgrimes		case ENOMEM:
5361590Srgrimes			break;
537		default:
538			printf("ip4_output (ipsec): error code %d\n", error);
539			/*fall through*/
540		case ENOENT:
541			/* don't show these error codes to the user */
542			error = 0;
543			break;
544		}
545		goto bad;
546	}
547
548	/* be sure to update variables that are affected by ipsec4_output() */
549	ip = mtod(m, struct ip *);
550	hlen = ip->ip_hl << 2;
551	if (ro->ro_rt == NULL) {
552		if ((flags & IP_ROUTETOIF) == 0) {
553			printf("ip_output: "
554				"can't update route after IPsec processing\n");
555			error = EHOSTUNREACH;	/*XXX*/
556			goto bad;
557		}
558	} else {
559		if (state.encap) {
560			ia = ifatoia(ro->ro_rt->rt_ifa);
561			ifp = ro->ro_rt->rt_ifp;
562		}
563	}
564    }
565
566	/* make it flipped, again. */
567	ip->ip_len = ntohs(ip->ip_len);
568	ip->ip_off = ntohs(ip->ip_off);
569skip_ipsec:
570#endif /*IPSEC*/
571#ifdef FAST_IPSEC
572	/*
573	 * Check the security policy (SP) for the packet and, if
574	 * required, do IPsec-related processing.  There are two
575	 * cases here; the first time a packet is sent through
576	 * it will be untagged and handled by ipsec4_checkpolicy.
577	 * If the packet is resubmitted to ip_output (e.g. after
578	 * AH, ESP, etc. processing), there will be a tag to bypass
579	 * the lookup and related policy checking.
580	 */
581	mtag = m_tag_find(m, PACKET_TAG_IPSEC_PENDING_TDB, NULL);
582	s = splnet();
583	if (mtag != NULL) {
584		tdbi = (struct tdb_ident *)(mtag + 1);
585		sp = ipsec_getpolicy(tdbi, IPSEC_DIR_OUTBOUND);
586		if (sp == NULL)
587			error = -EINVAL;	/* force silent drop */
588		m_tag_delete(m, mtag);
589	} else {
590		sp = ipsec4_checkpolicy(m, IPSEC_DIR_OUTBOUND, flags,
591					&error, inp);
592	}
593	/*
594	 * There are four return cases:
595	 *    sp != NULL	 	    apply IPsec policy
596	 *    sp == NULL, error == 0	    no IPsec handling needed
597	 *    sp == NULL, error == -EINVAL  discard packet w/o error
598	 *    sp == NULL, error != 0	    discard packet, report error
599	 */
600	if (sp != NULL) {
601		/* Loop detection, check if ipsec processing already done */
602		KASSERT(sp->req != NULL, ("ip_output: no ipsec request"));
603		for (mtag = m_tag_first(m); mtag != NULL;
604		     mtag = m_tag_next(m, mtag)) {
605			if (mtag->m_tag_cookie != MTAG_ABI_COMPAT)
606				continue;
607			if (mtag->m_tag_id != PACKET_TAG_IPSEC_OUT_DONE &&
608			    mtag->m_tag_id != PACKET_TAG_IPSEC_OUT_CRYPTO_NEEDED)
609				continue;
610			/*
611			 * Check if policy has an SA associated with it.
612			 * This can happen when an SP has yet to acquire
613			 * an SA; e.g. on first reference.  If it occurs,
614			 * then we let ipsec4_process_packet do its thing.
615			 */
616			if (sp->req->sav == NULL)
617				break;
618			tdbi = (struct tdb_ident *)(mtag + 1);
619			if (tdbi->spi == sp->req->sav->spi &&
620			    tdbi->proto == sp->req->sav->sah->saidx.proto &&
621			    bcmp(&tdbi->dst, &sp->req->sav->sah->saidx.dst,
622				 sizeof (union sockaddr_union)) == 0) {
623				/*
624				 * No IPsec processing is needed, free
625				 * reference to SP.
626				 *
627				 * NB: null pointer to avoid free at
628				 *     done: below.
629				 */
630				KEY_FREESP(&sp), sp = NULL;
631				splx(s);
632				goto spd_done;
633			}
634		}
635
636		/*
637		 * Do delayed checksums now because we send before
638		 * this is done in the normal processing path.
639		 */
640		if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
641			in_delayed_cksum(m);
642			m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
643		}
644
645		ip->ip_len = htons(ip->ip_len);
646		ip->ip_off = htons(ip->ip_off);
647
648		/* NB: callee frees mbuf */
649		error = ipsec4_process_packet(m, sp->req, flags, 0);
650		/*
651		 * Preserve KAME behaviour: ENOENT can be returned
652		 * when an SA acquire is in progress.  Don't propagate
653		 * this to user-level; it confuses applications.
654		 *
655		 * XXX this will go away when the SADB is redone.
656		 */
657		if (error == ENOENT)
658			error = 0;
659		splx(s);
660		goto done;
661	} else {
662		splx(s);
663
664		if (error != 0) {
665			/*
666			 * Hack: -EINVAL is used to signal that a packet
667			 * should be silently discarded.  This is typically
668			 * because we asked key management for an SA and
669			 * it was delayed (e.g. kicked up to IKE).
670			 */
671			if (error == -EINVAL)
672				error = 0;
673			goto bad;
674		} else {
675			/* No IPsec processing for this packet. */
676		}
677#ifdef notyet
678		/*
679		 * If deferred crypto processing is needed, check that
680		 * the interface supports it.
681		 */
682		mtag = m_tag_find(m, PACKET_TAG_IPSEC_OUT_CRYPTO_NEEDED, NULL);
683		if (mtag != NULL && (ifp->if_capenable & IFCAP_IPSEC) == 0) {
684			/* notify IPsec to do its own crypto */
685			ipsp_skipcrypto_unmark((struct tdb_ident *)(mtag + 1));
686			error = EHOSTUNREACH;
687			goto bad;
688		}
689#endif
690	}
691spd_done:
692#endif /* FAST_IPSEC */
693
694	/*
695	 * IpHack's section.
696	 * - Xlate: translate packet's addr/port (NAT).
697	 * - Firewall: deny/allow/etc.
698	 * - Wrap: fake packet's addr/port <unimpl.>
699	 * - Encapsulate: put it in another IP and send out. <unimp.>
700	 */
701#ifdef PFIL_HOOKS
702	/*
703	 * Run through list of hooks for output packets.
704	 */
705	error = pfil_run_hooks(&inet_pfil_hook, &m, ifp, PFIL_OUT);
706	if (error != 0 || m == NULL)
707		goto done;
708	ip = mtod(m, struct ip *);
709#endif /* PFIL_HOOKS */
710
711	/*
712	 * Check with the firewall...
713	 * but not if we are already being fwd'd from a firewall.
714	 */
715	if (fw_enable && IPFW_LOADED && !args.next_hop) {
716		struct sockaddr_in *old = dst;
717
718		args.m = m;
719		args.next_hop = dst;
720		args.oif = ifp;
721		off = ip_fw_chk_ptr(&args);
722		m = args.m;
723		dst = args.next_hop;
724
725                /*
726		 * On return we must do the following:
727		 * m == NULL	-> drop the pkt (old interface, deprecated)
728		 * (off & IP_FW_PORT_DENY_FLAG)	-> drop the pkt (new interface)
729		 * 1<=off<= 0xffff		-> DIVERT
730		 * (off & IP_FW_PORT_DYNT_FLAG)	-> send to a DUMMYNET pipe
731		 * (off & IP_FW_PORT_TEE_FLAG)	-> TEE the packet
732		 * dst != old			-> IPFIREWALL_FORWARD
733		 * off==0, dst==old		-> accept
734		 * If some of the above modules are not compiled in, then
735		 * we should't have to check the corresponding condition
736		 * (because the ipfw control socket should not accept
737		 * unsupported rules), but better play safe and drop
738		 * packets in case of doubt.
739		 */
740		if ( (off & IP_FW_PORT_DENY_FLAG) || m == NULL) {
741			if (m)
742				m_freem(m);
743			error = EACCES;
744			goto done;
745		}
746		ip = mtod(m, struct ip *);
747		if (off == 0 && dst == old)		/* common case */
748			goto pass;
749                if (DUMMYNET_LOADED && (off & IP_FW_PORT_DYNT_FLAG) != 0) {
750			/*
751			 * pass the pkt to dummynet. Need to include
752			 * pipe number, m, ifp, ro, dst because these are
753			 * not recomputed in the next pass.
754			 * All other parameters have been already used and
755			 * so they are not needed anymore.
756			 * XXX note: if the ifp or ro entry are deleted
757			 * while a pkt is in dummynet, we are in trouble!
758			 */
759			args.ro = ro;
760			args.dst = dst;
761			args.flags = flags;
762
763			error = ip_dn_io_ptr(m, off & 0xffff, DN_TO_IP_OUT,
764				&args);
765			goto done;
766		}
767#ifdef IPDIVERT
768		if (off != 0 && (off & IP_FW_PORT_DYNT_FLAG) == 0) {
769			struct mbuf *clone;
770
771			/* Clone packet if we're doing a 'tee' */
772			if ((off & IP_FW_PORT_TEE_FLAG) != 0)
773				clone = divert_clone(m);
774			else
775				clone = NULL;
776
777			/*
778			 * XXX
779			 * delayed checksums are not currently compatible
780			 * with divert sockets.
781			 */
782			if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
783				in_delayed_cksum(m);
784				m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
785			}
786
787			/* Restore packet header fields to original values */
788			ip->ip_len = htons(ip->ip_len);
789			ip->ip_off = htons(ip->ip_off);
790
791			/* Deliver packet to divert input routine */
792			divert_packet(m, 0);
793
794			/* If 'tee', continue with original packet */
795			if (clone != NULL) {
796				m = clone;
797				ip = mtod(m, struct ip *);
798				goto pass;
799			}
800			goto done;
801		}
802#endif
803
804		/* IPFIREWALL_FORWARD */
805		/*
806		 * Check dst to make sure it is directly reachable on the
807		 * interface we previously thought it was.
808		 * If it isn't (which may be likely in some situations) we have
809		 * to re-route it (ie, find a route for the next-hop and the
810		 * associated interface) and set them here. This is nested
811		 * forwarding which in most cases is undesirable, except where
812		 * such control is nigh impossible. So we do it here.
813		 * And I'm babbling.
814		 */
815		if (off == 0 && old != dst) { /* FORWARD, dst has changed */
816#if 0
817			/*
818			 * XXX To improve readability, this block should be
819			 * changed into a function call as below:
820			 */
821			error = ip_ipforward(&m, &dst, &ifp);
822			if (error)
823				goto bad;
824			if (m == NULL) /* ip_input consumed the mbuf */
825				goto done;
826#else
827			struct in_ifaddr *ia;
828
829			/*
830			 * XXX sro_fwd below is static, and a pointer
831			 * to it gets passed to routines downstream.
832			 * This could have surprisingly bad results in
833			 * practice, because its content is overwritten
834			 * by subsequent packets.
835			 */
836			/* There must be a better way to do this next line... */
837			static struct route sro_fwd;
838			struct route *ro_fwd = &sro_fwd;
839
840#if 0
841			print_ip("IPFIREWALL_FORWARD: New dst ip: ",
842			    dst->sin_addr, "\n");
843#endif
844
845			/*
846			 * We need to figure out if we have been forwarded
847			 * to a local socket. If so, then we should somehow
848			 * "loop back" to ip_input, and get directed to the
849			 * PCB as if we had received this packet. This is
850			 * because it may be dificult to identify the packets
851			 * you want to forward until they are being output
852			 * and have selected an interface. (e.g. locally
853			 * initiated packets) If we used the loopback inteface,
854			 * we would not be able to control what happens
855			 * as the packet runs through ip_input() as
856			 * it is done through an ISR.
857			 */
858			LIST_FOREACH(ia,
859			    INADDR_HASH(dst->sin_addr.s_addr), ia_hash) {
860				/*
861				 * If the addr to forward to is one
862				 * of ours, we pretend to
863				 * be the destination for this packet.
864				 */
865				if (IA_SIN(ia)->sin_addr.s_addr ==
866						 dst->sin_addr.s_addr)
867					break;
868			}
869			if (ia) {	/* tell ip_input "dont filter" */
870				mtag = m_tag_get(
871				    PACKET_TAG_IPFORWARD,
872				    sizeof(struct sockaddr_in *), M_NOWAIT);
873				if (mtag == NULL) {
874					error = ENOBUFS;
875					goto bad;
876				}
877				*(struct sockaddr_in **)(mtag+1) =
878				    args.next_hop;
879				m_tag_prepend(m, mtag);
880
881				if (m->m_pkthdr.rcvif == NULL)
882					m->m_pkthdr.rcvif = ifunit("lo0");
883				if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
884					m->m_pkthdr.csum_flags |=
885					    CSUM_DATA_VALID | CSUM_PSEUDO_HDR;
886					m->m_pkthdr.csum_data = 0xffff;
887				}
888				m->m_pkthdr.csum_flags |=
889				    CSUM_IP_CHECKED | CSUM_IP_VALID;
890				ip->ip_len = htons(ip->ip_len);
891				ip->ip_off = htons(ip->ip_off);
892				ip_input(m);
893				goto done;
894			}
895			/*
896			 * Some of the logic for this was
897			 * nicked from above.
898			 */
899			bcopy(dst, &ro_fwd->ro_dst, sizeof(*dst));
900
901			ro_fwd->ro_rt = 0;
902			rtalloc_ign(ro_fwd, RTF_CLONING);
903
904			if (ro_fwd->ro_rt == 0) {
905				ipstat.ips_noroute++;
906				error = EHOSTUNREACH;
907				goto bad;
908			}
909
910			ia = ifatoia(ro_fwd->ro_rt->rt_ifa);
911			ifp = ro_fwd->ro_rt->rt_ifp;
912			ro_fwd->ro_rt->rt_rmx.rmx_pksent++;
913			if (ro_fwd->ro_rt->rt_flags & RTF_GATEWAY)
914				dst = (struct sockaddr_in *)
915					ro_fwd->ro_rt->rt_gateway;
916			if (ro_fwd->ro_rt->rt_flags & RTF_HOST)
917				isbroadcast =
918				    (ro_fwd->ro_rt->rt_flags & RTF_BROADCAST);
919			else
920				isbroadcast = in_broadcast(dst->sin_addr, ifp);
921			if (ro->ro_rt)
922				RTFREE(ro->ro_rt);
923			ro->ro_rt = ro_fwd->ro_rt;
924			dst = (struct sockaddr_in *)&ro_fwd->ro_dst;
925
926#endif	/* ... block to be put into a function */
927			/*
928			 * If we added a default src ip earlier,
929			 * which would have been gotten from the-then
930			 * interface, do it again, from the new one.
931			 */
932			if (src_was_INADDR_ANY)
933				ip->ip_src = IA_SIN(ia)->sin_addr;
934			goto pass ;
935		}
936
937                /*
938                 * if we get here, none of the above matches, and
939                 * we have to drop the pkt
940                 */
941		m_freem(m);
942                error = EACCES; /* not sure this is the right error msg */
943                goto done;
944	}
945
946pass:
947	/* 127/8 must not appear on wire - RFC1122. */
948	if ((ntohl(ip->ip_dst.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET ||
949	    (ntohl(ip->ip_src.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET) {
950		if ((ifp->if_flags & IFF_LOOPBACK) == 0) {
951			ipstat.ips_badaddr++;
952			error = EADDRNOTAVAIL;
953			goto bad;
954		}
955	}
956
957	m->m_pkthdr.csum_flags |= CSUM_IP;
958	sw_csum = m->m_pkthdr.csum_flags & ~ifp->if_hwassist;
959	if (sw_csum & CSUM_DELAY_DATA) {
960		in_delayed_cksum(m);
961		sw_csum &= ~CSUM_DELAY_DATA;
962	}
963	m->m_pkthdr.csum_flags &= ifp->if_hwassist;
964
965	/*
966	 * If small enough for interface, or the interface will take
967	 * care of the fragmentation for us, can just send directly.
968	 */
969	if (ip->ip_len <= ifp->if_mtu || (ifp->if_hwassist & CSUM_FRAGMENT &&
970	    ((ip->ip_off & IP_DF) == 0))) {
971		ip->ip_len = htons(ip->ip_len);
972		ip->ip_off = htons(ip->ip_off);
973		ip->ip_sum = 0;
974		if (sw_csum & CSUM_DELAY_IP)
975			ip->ip_sum = in_cksum(m, hlen);
976
977		/* Record statistics for this interface address. */
978		if (!(flags & IP_FORWARDING) && ia) {
979			ia->ia_ifa.if_opackets++;
980			ia->ia_ifa.if_obytes += m->m_pkthdr.len;
981		}
982
983#ifdef IPSEC
984		/* clean ipsec history once it goes out of the node */
985		ipsec_delaux(m);
986#endif
987
988#ifdef MBUF_STRESS_TEST
989		if (mbuf_frag_size && m->m_pkthdr.len > mbuf_frag_size)
990			m = m_fragment(m, M_DONTWAIT, mbuf_frag_size);
991#endif
992		error = (*ifp->if_output)(ifp, m,
993				(struct sockaddr *)dst, ro->ro_rt);
994		goto done;
995	}
996
997	if (ip->ip_off & IP_DF) {
998		error = EMSGSIZE;
999		/*
1000		 * This case can happen if the user changed the MTU
1001		 * of an interface after enabling IP on it.  Because
1002		 * most netifs don't keep track of routes pointing to
1003		 * them, there is no way for one to update all its
1004		 * routes when the MTU is changed.
1005		 */
1006		if ((ro->ro_rt->rt_flags & (RTF_UP | RTF_HOST)) &&
1007		    (ro->ro_rt->rt_rmx.rmx_mtu > ifp->if_mtu)) {
1008			ro->ro_rt->rt_rmx.rmx_mtu = ifp->if_mtu;
1009		}
1010		ipstat.ips_cantfrag++;
1011		goto bad;
1012	}
1013
1014	/*
1015	 * Too large for interface; fragment if possible. If successful,
1016	 * on return, m will point to a list of packets to be sent.
1017	 */
1018	error = ip_fragment(ip, &m, ifp->if_mtu, ifp->if_hwassist, sw_csum);
1019	if (error)
1020		goto bad;
1021	for (; m; m = m0) {
1022		m0 = m->m_nextpkt;
1023		m->m_nextpkt = 0;
1024#ifdef IPSEC
1025		/* clean ipsec history once it goes out of the node */
1026		ipsec_delaux(m);
1027#endif
1028		if (error == 0) {
1029			/* Record statistics for this interface address. */
1030			if (ia != NULL) {
1031				ia->ia_ifa.if_opackets++;
1032				ia->ia_ifa.if_obytes += m->m_pkthdr.len;
1033			}
1034
1035			error = (*ifp->if_output)(ifp, m,
1036			    (struct sockaddr *)dst, ro->ro_rt);
1037		} else
1038			m_freem(m);
1039	}
1040
1041	if (error == 0)
1042		ipstat.ips_fragmented++;
1043
1044done:
1045	if (ro == &iproute && ro->ro_rt) {
1046		RTFREE(ro->ro_rt);
1047		ro->ro_rt = NULL;
1048	}
1049	if (dummytag) {
1050		struct dn_pkt_tag *dt = (struct dn_pkt_tag *)(dummytag+1);
1051		if (dt->ro.ro_rt)
1052			RTFREE(dt->ro.ro_rt);
1053		m_tag_free(dummytag);
1054	}
1055#ifdef IPSEC
1056	if (sp != NULL) {
1057		KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1058			printf("DP ip_output call free SP:%p\n", sp));
1059		key_freesp(sp);
1060	}
1061#endif
1062#ifdef FAST_IPSEC
1063	if (sp != NULL)
1064		KEY_FREESP(&sp);
1065#endif
1066	return (error);
1067bad:
1068	m_freem(m);
1069	goto done;
1070}
1071
1072/*
1073 * Create a chain of fragments which fit the given mtu. m_frag points to the
1074 * mbuf to be fragmented; on return it points to the chain with the fragments.
1075 * Return 0 if no error. If error, m_frag may contain a partially built
1076 * chain of fragments that should be freed by the caller.
1077 *
1078 * if_hwassist_flags is the hw offload capabilities (see if_data.ifi_hwassist)
1079 * sw_csum contains the delayed checksums flags (e.g., CSUM_DELAY_IP).
1080 */
1081int
1082ip_fragment(struct ip *ip, struct mbuf **m_frag, int mtu,
1083	    u_long if_hwassist_flags, int sw_csum)
1084{
1085	int error = 0;
1086	int hlen = ip->ip_hl << 2;
1087	int len = (mtu - hlen) & ~7;	/* size of payload in each fragment */
1088	int off;
1089	struct mbuf *m0 = *m_frag;	/* the original packet		*/
1090	int firstlen;
1091	struct mbuf **mnext;
1092	int nfrags;
1093
1094	if (ip->ip_off & IP_DF) {	/* Fragmentation not allowed */
1095		ipstat.ips_cantfrag++;
1096		return EMSGSIZE;
1097	}
1098
1099	/*
1100	 * Must be able to put at least 8 bytes per fragment.
1101	 */
1102	if (len < 8)
1103		return EMSGSIZE;
1104
1105	/*
1106	 * If the interface will not calculate checksums on
1107	 * fragmented packets, then do it here.
1108	 */
1109	if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA &&
1110	    (if_hwassist_flags & CSUM_IP_FRAGS) == 0) {
1111		in_delayed_cksum(m0);
1112		m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
1113	}
1114
1115	if (len > PAGE_SIZE) {
1116		/*
1117		 * Fragment large datagrams such that each segment
1118		 * contains a multiple of PAGE_SIZE amount of data,
1119		 * plus headers. This enables a receiver to perform
1120		 * page-flipping zero-copy optimizations.
1121		 *
1122		 * XXX When does this help given that sender and receiver
1123		 * could have different page sizes, and also mtu could
1124		 * be less than the receiver's page size ?
1125		 */
1126		int newlen;
1127		struct mbuf *m;
1128
1129		for (m = m0, off = 0; m && (off+m->m_len) <= mtu; m = m->m_next)
1130			off += m->m_len;
1131
1132		/*
1133		 * firstlen (off - hlen) must be aligned on an
1134		 * 8-byte boundary
1135		 */
1136		if (off < hlen)
1137			goto smart_frag_failure;
1138		off = ((off - hlen) & ~7) + hlen;
1139		newlen = (~PAGE_MASK) & mtu;
1140		if ((newlen + sizeof (struct ip)) > mtu) {
1141			/* we failed, go back the default */
1142smart_frag_failure:
1143			newlen = len;
1144			off = hlen + len;
1145		}
1146		len = newlen;
1147
1148	} else {
1149		off = hlen + len;
1150	}
1151
1152	firstlen = off - hlen;
1153	mnext = &m0->m_nextpkt;		/* pointer to next packet */
1154
1155	/*
1156	 * Loop through length of segment after first fragment,
1157	 * make new header and copy data of each part and link onto chain.
1158	 * Here, m0 is the original packet, m is the fragment being created.
1159	 * The fragments are linked off the m_nextpkt of the original
1160	 * packet, which after processing serves as the first fragment.
1161	 */
1162	for (nfrags = 1; off < ip->ip_len; off += len, nfrags++) {
1163		struct ip *mhip;	/* ip header on the fragment */
1164		struct mbuf *m;
1165		int mhlen = sizeof (struct ip);
1166
1167		MGETHDR(m, M_DONTWAIT, MT_HEADER);
1168		if (m == 0) {
1169			error = ENOBUFS;
1170			ipstat.ips_odropped++;
1171			goto done;
1172		}
1173		m->m_flags |= (m0->m_flags & M_MCAST) | M_FRAG;
1174		/*
1175		 * In the first mbuf, leave room for the link header, then
1176		 * copy the original IP header including options. The payload
1177		 * goes into an additional mbuf chain returned by m_copy().
1178		 */
1179		m->m_data += max_linkhdr;
1180		mhip = mtod(m, struct ip *);
1181		*mhip = *ip;
1182		if (hlen > sizeof (struct ip)) {
1183			mhlen = ip_optcopy(ip, mhip) + sizeof (struct ip);
1184			mhip->ip_v = IPVERSION;
1185			mhip->ip_hl = mhlen >> 2;
1186		}
1187		m->m_len = mhlen;
1188		/* XXX do we need to add ip->ip_off below ? */
1189		mhip->ip_off = ((off - hlen) >> 3) + ip->ip_off;
1190		if (off + len >= ip->ip_len) {	/* last fragment */
1191			len = ip->ip_len - off;
1192			m->m_flags |= M_LASTFRAG;
1193		} else
1194			mhip->ip_off |= IP_MF;
1195		mhip->ip_len = htons((u_short)(len + mhlen));
1196		m->m_next = m_copy(m0, off, len);
1197		if (m->m_next == 0) {		/* copy failed */
1198			m_free(m);
1199			error = ENOBUFS;	/* ??? */
1200			ipstat.ips_odropped++;
1201			goto done;
1202		}
1203		m->m_pkthdr.len = mhlen + len;
1204		m->m_pkthdr.rcvif = (struct ifnet *)0;
1205#ifdef MAC
1206		mac_create_fragment(m0, m);
1207#endif
1208		m->m_pkthdr.csum_flags = m0->m_pkthdr.csum_flags;
1209		mhip->ip_off = htons(mhip->ip_off);
1210		mhip->ip_sum = 0;
1211		if (sw_csum & CSUM_DELAY_IP)
1212			mhip->ip_sum = in_cksum(m, mhlen);
1213		*mnext = m;
1214		mnext = &m->m_nextpkt;
1215	}
1216	ipstat.ips_ofragments += nfrags;
1217
1218	/* set first marker for fragment chain */
1219	m0->m_flags |= M_FIRSTFRAG | M_FRAG;
1220	m0->m_pkthdr.csum_data = nfrags;
1221
1222	/*
1223	 * Update first fragment by trimming what's been copied out
1224	 * and updating header.
1225	 */
1226	m_adj(m0, hlen + firstlen - ip->ip_len);
1227	m0->m_pkthdr.len = hlen + firstlen;
1228	ip->ip_len = htons((u_short)m0->m_pkthdr.len);
1229	ip->ip_off |= IP_MF;
1230	ip->ip_off = htons(ip->ip_off);
1231	ip->ip_sum = 0;
1232	if (sw_csum & CSUM_DELAY_IP)
1233		ip->ip_sum = in_cksum(m0, hlen);
1234
1235done:
1236	*m_frag = m0;
1237	return error;
1238}
1239
1240void
1241in_delayed_cksum(struct mbuf *m)
1242{
1243	struct ip *ip;
1244	u_short csum, offset;
1245
1246	ip = mtod(m, struct ip *);
1247	offset = ip->ip_hl << 2 ;
1248	csum = in_cksum_skip(m, ip->ip_len, offset);
1249	if (m->m_pkthdr.csum_flags & CSUM_UDP && csum == 0)
1250		csum = 0xffff;
1251	offset += m->m_pkthdr.csum_data;	/* checksum offset */
1252
1253	if (offset + sizeof(u_short) > m->m_len) {
1254		printf("delayed m_pullup, m->len: %d  off: %d  p: %d\n",
1255		    m->m_len, offset, ip->ip_p);
1256		/*
1257		 * XXX
1258		 * this shouldn't happen, but if it does, the
1259		 * correct behavior may be to insert the checksum
1260		 * in the existing chain instead of rearranging it.
1261		 */
1262		m = m_pullup(m, offset + sizeof(u_short));
1263	}
1264	*(u_short *)(m->m_data + offset) = csum;
1265}
1266
1267/*
1268 * Insert IP options into preformed packet.
1269 * Adjust IP destination as required for IP source routing,
1270 * as indicated by a non-zero in_addr at the start of the options.
1271 *
1272 * XXX This routine assumes that the packet has no options in place.
1273 */
1274static struct mbuf *
1275ip_insertoptions(m, opt, phlen)
1276	register struct mbuf *m;
1277	struct mbuf *opt;
1278	int *phlen;
1279{
1280	register struct ipoption *p = mtod(opt, struct ipoption *);
1281	struct mbuf *n;
1282	register struct ip *ip = mtod(m, struct ip *);
1283	unsigned optlen;
1284
1285	optlen = opt->m_len - sizeof(p->ipopt_dst);
1286	if (optlen + ip->ip_len > IP_MAXPACKET) {
1287		*phlen = 0;
1288		return (m);		/* XXX should fail */
1289	}
1290	if (p->ipopt_dst.s_addr)
1291		ip->ip_dst = p->ipopt_dst;
1292	if (m->m_flags & M_EXT || m->m_data - optlen < m->m_pktdat) {
1293		MGETHDR(n, M_DONTWAIT, MT_HEADER);
1294		if (n == 0) {
1295			*phlen = 0;
1296			return (m);
1297		}
1298		n->m_pkthdr.rcvif = (struct ifnet *)0;
1299#ifdef MAC
1300		mac_create_mbuf_from_mbuf(m, n);
1301#endif
1302		n->m_pkthdr.len = m->m_pkthdr.len + optlen;
1303		m->m_len -= sizeof(struct ip);
1304		m->m_data += sizeof(struct ip);
1305		n->m_next = m;
1306		m = n;
1307		m->m_len = optlen + sizeof(struct ip);
1308		m->m_data += max_linkhdr;
1309		bcopy(ip, mtod(m, void *), sizeof(struct ip));
1310	} else {
1311		m->m_data -= optlen;
1312		m->m_len += optlen;
1313		m->m_pkthdr.len += optlen;
1314		bcopy(ip, mtod(m, void *), sizeof(struct ip));
1315	}
1316	ip = mtod(m, struct ip *);
1317	bcopy(p->ipopt_list, ip + 1, optlen);
1318	*phlen = sizeof(struct ip) + optlen;
1319	ip->ip_v = IPVERSION;
1320	ip->ip_hl = *phlen >> 2;
1321	ip->ip_len += optlen;
1322	return (m);
1323}
1324
1325/*
1326 * Copy options from ip to jp,
1327 * omitting those not copied during fragmentation.
1328 */
1329int
1330ip_optcopy(ip, jp)
1331	struct ip *ip, *jp;
1332{
1333	register u_char *cp, *dp;
1334	int opt, optlen, cnt;
1335
1336	cp = (u_char *)(ip + 1);
1337	dp = (u_char *)(jp + 1);
1338	cnt = (ip->ip_hl << 2) - sizeof (struct ip);
1339	for (; cnt > 0; cnt -= optlen, cp += optlen) {
1340		opt = cp[0];
1341		if (opt == IPOPT_EOL)
1342			break;
1343		if (opt == IPOPT_NOP) {
1344			/* Preserve for IP mcast tunnel's LSRR alignment. */
1345			*dp++ = IPOPT_NOP;
1346			optlen = 1;
1347			continue;
1348		}
1349
1350		KASSERT(cnt >= IPOPT_OLEN + sizeof(*cp),
1351		    ("ip_optcopy: malformed ipv4 option"));
1352		optlen = cp[IPOPT_OLEN];
1353		KASSERT(optlen >= IPOPT_OLEN + sizeof(*cp) && optlen <= cnt,
1354		    ("ip_optcopy: malformed ipv4 option"));
1355
1356		/* bogus lengths should have been caught by ip_dooptions */
1357		if (optlen > cnt)
1358			optlen = cnt;
1359		if (IPOPT_COPIED(opt)) {
1360			bcopy(cp, dp, optlen);
1361			dp += optlen;
1362		}
1363	}
1364	for (optlen = dp - (u_char *)(jp+1); optlen & 0x3; optlen++)
1365		*dp++ = IPOPT_EOL;
1366	return (optlen);
1367}
1368
1369/*
1370 * IP socket option processing.
1371 */
1372int
1373ip_ctloutput(so, sopt)
1374	struct socket *so;
1375	struct sockopt *sopt;
1376{
1377	struct	inpcb *inp = sotoinpcb(so);
1378	int	error, optval;
1379
1380	error = optval = 0;
1381	if (sopt->sopt_level != IPPROTO_IP) {
1382		return (EINVAL);
1383	}
1384
1385	switch (sopt->sopt_dir) {
1386	case SOPT_SET:
1387		switch (sopt->sopt_name) {
1388		case IP_OPTIONS:
1389#ifdef notyet
1390		case IP_RETOPTS:
1391#endif
1392		{
1393			struct mbuf *m;
1394			if (sopt->sopt_valsize > MLEN) {
1395				error = EMSGSIZE;
1396				break;
1397			}
1398			MGET(m, sopt->sopt_td ? M_TRYWAIT : M_DONTWAIT, MT_HEADER);
1399			if (m == 0) {
1400				error = ENOBUFS;
1401				break;
1402			}
1403			m->m_len = sopt->sopt_valsize;
1404			error = sooptcopyin(sopt, mtod(m, char *), m->m_len,
1405					    m->m_len);
1406
1407			return (ip_pcbopts(sopt->sopt_name, &inp->inp_options,
1408					   m));
1409		}
1410
1411		case IP_TOS:
1412		case IP_TTL:
1413		case IP_RECVOPTS:
1414		case IP_RECVRETOPTS:
1415		case IP_RECVDSTADDR:
1416		case IP_RECVTTL:
1417		case IP_RECVIF:
1418		case IP_FAITH:
1419		case IP_ONESBCAST:
1420			error = sooptcopyin(sopt, &optval, sizeof optval,
1421					    sizeof optval);
1422			if (error)
1423				break;
1424
1425			switch (sopt->sopt_name) {
1426			case IP_TOS:
1427				inp->inp_ip_tos = optval;
1428				break;
1429
1430			case IP_TTL:
1431				inp->inp_ip_ttl = optval;
1432				break;
1433#define	OPTSET(bit) \
1434	if (optval) \
1435		inp->inp_flags |= bit; \
1436	else \
1437		inp->inp_flags &= ~bit;
1438
1439			case IP_RECVOPTS:
1440				OPTSET(INP_RECVOPTS);
1441				break;
1442
1443			case IP_RECVRETOPTS:
1444				OPTSET(INP_RECVRETOPTS);
1445				break;
1446
1447			case IP_RECVDSTADDR:
1448				OPTSET(INP_RECVDSTADDR);
1449				break;
1450
1451			case IP_RECVTTL:
1452				OPTSET(INP_RECVTTL);
1453				break;
1454
1455			case IP_RECVIF:
1456				OPTSET(INP_RECVIF);
1457				break;
1458
1459			case IP_FAITH:
1460				OPTSET(INP_FAITH);
1461				break;
1462
1463			case IP_ONESBCAST:
1464				OPTSET(INP_ONESBCAST);
1465				break;
1466			}
1467			break;
1468#undef OPTSET
1469
1470		case IP_MULTICAST_IF:
1471		case IP_MULTICAST_VIF:
1472		case IP_MULTICAST_TTL:
1473		case IP_MULTICAST_LOOP:
1474		case IP_ADD_MEMBERSHIP:
1475		case IP_DROP_MEMBERSHIP:
1476			error = ip_setmoptions(sopt, &inp->inp_moptions);
1477			break;
1478
1479		case IP_PORTRANGE:
1480			error = sooptcopyin(sopt, &optval, sizeof optval,
1481					    sizeof optval);
1482			if (error)
1483				break;
1484
1485			switch (optval) {
1486			case IP_PORTRANGE_DEFAULT:
1487				inp->inp_flags &= ~(INP_LOWPORT);
1488				inp->inp_flags &= ~(INP_HIGHPORT);
1489				break;
1490
1491			case IP_PORTRANGE_HIGH:
1492				inp->inp_flags &= ~(INP_LOWPORT);
1493				inp->inp_flags |= INP_HIGHPORT;
1494				break;
1495
1496			case IP_PORTRANGE_LOW:
1497				inp->inp_flags &= ~(INP_HIGHPORT);
1498				inp->inp_flags |= INP_LOWPORT;
1499				break;
1500
1501			default:
1502				error = EINVAL;
1503				break;
1504			}
1505			break;
1506
1507#if defined(IPSEC) || defined(FAST_IPSEC)
1508		case IP_IPSEC_POLICY:
1509		{
1510			caddr_t req;
1511			size_t len = 0;
1512			int priv;
1513			struct mbuf *m;
1514			int optname;
1515
1516			if ((error = soopt_getm(sopt, &m)) != 0) /* XXX */
1517				break;
1518			if ((error = soopt_mcopyin(sopt, m)) != 0) /* XXX */
1519				break;
1520			priv = (sopt->sopt_td != NULL &&
1521				suser(sopt->sopt_td) != 0) ? 0 : 1;
1522			req = mtod(m, caddr_t);
1523			len = m->m_len;
1524			optname = sopt->sopt_name;
1525			error = ipsec4_set_policy(inp, optname, req, len, priv);
1526			m_freem(m);
1527			break;
1528		}
1529#endif /*IPSEC*/
1530
1531		default:
1532			error = ENOPROTOOPT;
1533			break;
1534		}
1535		break;
1536
1537	case SOPT_GET:
1538		switch (sopt->sopt_name) {
1539		case IP_OPTIONS:
1540		case IP_RETOPTS:
1541			if (inp->inp_options)
1542				error = sooptcopyout(sopt,
1543						     mtod(inp->inp_options,
1544							  char *),
1545						     inp->inp_options->m_len);
1546			else
1547				sopt->sopt_valsize = 0;
1548			break;
1549
1550		case IP_TOS:
1551		case IP_TTL:
1552		case IP_RECVOPTS:
1553		case IP_RECVRETOPTS:
1554		case IP_RECVDSTADDR:
1555		case IP_RECVTTL:
1556		case IP_RECVIF:
1557		case IP_PORTRANGE:
1558		case IP_FAITH:
1559		case IP_ONESBCAST:
1560			switch (sopt->sopt_name) {
1561
1562			case IP_TOS:
1563				optval = inp->inp_ip_tos;
1564				break;
1565
1566			case IP_TTL:
1567				optval = inp->inp_ip_ttl;
1568				break;
1569
1570#define	OPTBIT(bit)	(inp->inp_flags & bit ? 1 : 0)
1571
1572			case IP_RECVOPTS:
1573				optval = OPTBIT(INP_RECVOPTS);
1574				break;
1575
1576			case IP_RECVRETOPTS:
1577				optval = OPTBIT(INP_RECVRETOPTS);
1578				break;
1579
1580			case IP_RECVDSTADDR:
1581				optval = OPTBIT(INP_RECVDSTADDR);
1582				break;
1583
1584			case IP_RECVTTL:
1585				optval = OPTBIT(INP_RECVTTL);
1586				break;
1587
1588			case IP_RECVIF:
1589				optval = OPTBIT(INP_RECVIF);
1590				break;
1591
1592			case IP_PORTRANGE:
1593				if (inp->inp_flags & INP_HIGHPORT)
1594					optval = IP_PORTRANGE_HIGH;
1595				else if (inp->inp_flags & INP_LOWPORT)
1596					optval = IP_PORTRANGE_LOW;
1597				else
1598					optval = 0;
1599				break;
1600
1601			case IP_FAITH:
1602				optval = OPTBIT(INP_FAITH);
1603				break;
1604
1605			case IP_ONESBCAST:
1606				optval = OPTBIT(INP_ONESBCAST);
1607				break;
1608			}
1609			error = sooptcopyout(sopt, &optval, sizeof optval);
1610			break;
1611
1612		case IP_MULTICAST_IF:
1613		case IP_MULTICAST_VIF:
1614		case IP_MULTICAST_TTL:
1615		case IP_MULTICAST_LOOP:
1616		case IP_ADD_MEMBERSHIP:
1617		case IP_DROP_MEMBERSHIP:
1618			error = ip_getmoptions(sopt, inp->inp_moptions);
1619			break;
1620
1621#if defined(IPSEC) || defined(FAST_IPSEC)
1622		case IP_IPSEC_POLICY:
1623		{
1624			struct mbuf *m = NULL;
1625			caddr_t req = NULL;
1626			size_t len = 0;
1627
1628			if (m != 0) {
1629				req = mtod(m, caddr_t);
1630				len = m->m_len;
1631			}
1632			error = ipsec4_get_policy(sotoinpcb(so), req, len, &m);
1633			if (error == 0)
1634				error = soopt_mcopyout(sopt, m); /* XXX */
1635			if (error == 0)
1636				m_freem(m);
1637			break;
1638		}
1639#endif /*IPSEC*/
1640
1641		default:
1642			error = ENOPROTOOPT;
1643			break;
1644		}
1645		break;
1646	}
1647	return (error);
1648}
1649
1650/*
1651 * Set up IP options in pcb for insertion in output packets.
1652 * Store in mbuf with pointer in pcbopt, adding pseudo-option
1653 * with destination address if source routed.
1654 */
1655static int
1656ip_pcbopts(optname, pcbopt, m)
1657	int optname;
1658	struct mbuf **pcbopt;
1659	register struct mbuf *m;
1660{
1661	register int cnt, optlen;
1662	register u_char *cp;
1663	u_char opt;
1664
1665	/* turn off any old options */
1666	if (*pcbopt)
1667		(void)m_free(*pcbopt);
1668	*pcbopt = 0;
1669	if (m == (struct mbuf *)0 || m->m_len == 0) {
1670		/*
1671		 * Only turning off any previous options.
1672		 */
1673		if (m)
1674			(void)m_free(m);
1675		return (0);
1676	}
1677
1678	if (m->m_len % sizeof(int32_t))
1679		goto bad;
1680	/*
1681	 * IP first-hop destination address will be stored before
1682	 * actual options; move other options back
1683	 * and clear it when none present.
1684	 */
1685	if (m->m_data + m->m_len + sizeof(struct in_addr) >= &m->m_dat[MLEN])
1686		goto bad;
1687	cnt = m->m_len;
1688	m->m_len += sizeof(struct in_addr);
1689	cp = mtod(m, u_char *) + sizeof(struct in_addr);
1690	bcopy(mtod(m, void *), cp, (unsigned)cnt);
1691	bzero(mtod(m, void *), sizeof(struct in_addr));
1692
1693	for (; cnt > 0; cnt -= optlen, cp += optlen) {
1694		opt = cp[IPOPT_OPTVAL];
1695		if (opt == IPOPT_EOL)
1696			break;
1697		if (opt == IPOPT_NOP)
1698			optlen = 1;
1699		else {
1700			if (cnt < IPOPT_OLEN + sizeof(*cp))
1701				goto bad;
1702			optlen = cp[IPOPT_OLEN];
1703			if (optlen < IPOPT_OLEN + sizeof(*cp) || optlen > cnt)
1704				goto bad;
1705		}
1706		switch (opt) {
1707
1708		default:
1709			break;
1710
1711		case IPOPT_LSRR:
1712		case IPOPT_SSRR:
1713			/*
1714			 * user process specifies route as:
1715			 *	->A->B->C->D
1716			 * D must be our final destination (but we can't
1717			 * check that since we may not have connected yet).
1718			 * A is first hop destination, which doesn't appear in
1719			 * actual IP option, but is stored before the options.
1720			 */
1721			if (optlen < IPOPT_MINOFF - 1 + sizeof(struct in_addr))
1722				goto bad;
1723			m->m_len -= sizeof(struct in_addr);
1724			cnt -= sizeof(struct in_addr);
1725			optlen -= sizeof(struct in_addr);
1726			cp[IPOPT_OLEN] = optlen;
1727			/*
1728			 * Move first hop before start of options.
1729			 */
1730			bcopy((caddr_t)&cp[IPOPT_OFFSET+1], mtod(m, caddr_t),
1731			    sizeof(struct in_addr));
1732			/*
1733			 * Then copy rest of options back
1734			 * to close up the deleted entry.
1735			 */
1736			bcopy((&cp[IPOPT_OFFSET+1] + sizeof(struct in_addr)),
1737			    &cp[IPOPT_OFFSET+1],
1738			    (unsigned)cnt - (IPOPT_MINOFF - 1));
1739			break;
1740		}
1741	}
1742	if (m->m_len > MAX_IPOPTLEN + sizeof(struct in_addr))
1743		goto bad;
1744	*pcbopt = m;
1745	return (0);
1746
1747bad:
1748	(void)m_free(m);
1749	return (EINVAL);
1750}
1751
1752/*
1753 * XXX
1754 * The whole multicast option thing needs to be re-thought.
1755 * Several of these options are equally applicable to non-multicast
1756 * transmission, and one (IP_MULTICAST_TTL) totally duplicates a
1757 * standard option (IP_TTL).
1758 */
1759
1760/*
1761 * following RFC1724 section 3.3, 0.0.0.0/8 is interpreted as interface index.
1762 */
1763static struct ifnet *
1764ip_multicast_if(a, ifindexp)
1765	struct in_addr *a;
1766	int *ifindexp;
1767{
1768	int ifindex;
1769	struct ifnet *ifp;
1770
1771	if (ifindexp)
1772		*ifindexp = 0;
1773	if (ntohl(a->s_addr) >> 24 == 0) {
1774		ifindex = ntohl(a->s_addr) & 0xffffff;
1775		if (ifindex < 0 || if_index < ifindex)
1776			return NULL;
1777		ifp = ifnet_byindex(ifindex);
1778		if (ifindexp)
1779			*ifindexp = ifindex;
1780	} else {
1781		INADDR_TO_IFP(*a, ifp);
1782	}
1783	return ifp;
1784}
1785
1786/*
1787 * Set the IP multicast options in response to user setsockopt().
1788 */
1789static int
1790ip_setmoptions(sopt, imop)
1791	struct sockopt *sopt;
1792	struct ip_moptions **imop;
1793{
1794	int error = 0;
1795	int i;
1796	struct in_addr addr;
1797	struct ip_mreq mreq;
1798	struct ifnet *ifp;
1799	struct ip_moptions *imo = *imop;
1800	struct route ro;
1801	struct sockaddr_in *dst;
1802	int ifindex;
1803	int s;
1804
1805	if (imo == NULL) {
1806		/*
1807		 * No multicast option buffer attached to the pcb;
1808		 * allocate one and initialize to default values.
1809		 */
1810		imo = (struct ip_moptions*)malloc(sizeof(*imo), M_IPMOPTS,
1811		    M_WAITOK);
1812
1813		if (imo == NULL)
1814			return (ENOBUFS);
1815		*imop = imo;
1816		imo->imo_multicast_ifp = NULL;
1817		imo->imo_multicast_addr.s_addr = INADDR_ANY;
1818		imo->imo_multicast_vif = -1;
1819		imo->imo_multicast_ttl = IP_DEFAULT_MULTICAST_TTL;
1820		imo->imo_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
1821		imo->imo_num_memberships = 0;
1822	}
1823
1824	switch (sopt->sopt_name) {
1825	/* store an index number for the vif you wanna use in the send */
1826	case IP_MULTICAST_VIF:
1827		if (legal_vif_num == 0) {
1828			error = EOPNOTSUPP;
1829			break;
1830		}
1831		error = sooptcopyin(sopt, &i, sizeof i, sizeof i);
1832		if (error)
1833			break;
1834		if (!legal_vif_num(i) && (i != -1)) {
1835			error = EINVAL;
1836			break;
1837		}
1838		imo->imo_multicast_vif = i;
1839		break;
1840
1841	case IP_MULTICAST_IF:
1842		/*
1843		 * Select the interface for outgoing multicast packets.
1844		 */
1845		error = sooptcopyin(sopt, &addr, sizeof addr, sizeof addr);
1846		if (error)
1847			break;
1848		/*
1849		 * INADDR_ANY is used to remove a previous selection.
1850		 * When no interface is selected, a default one is
1851		 * chosen every time a multicast packet is sent.
1852		 */
1853		if (addr.s_addr == INADDR_ANY) {
1854			imo->imo_multicast_ifp = NULL;
1855			break;
1856		}
1857		/*
1858		 * The selected interface is identified by its local
1859		 * IP address.  Find the interface and confirm that
1860		 * it supports multicasting.
1861		 */
1862		s = splimp();
1863		ifp = ip_multicast_if(&addr, &ifindex);
1864		if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0) {
1865			splx(s);
1866			error = EADDRNOTAVAIL;
1867			break;
1868		}
1869		imo->imo_multicast_ifp = ifp;
1870		if (ifindex)
1871			imo->imo_multicast_addr = addr;
1872		else
1873			imo->imo_multicast_addr.s_addr = INADDR_ANY;
1874		splx(s);
1875		break;
1876
1877	case IP_MULTICAST_TTL:
1878		/*
1879		 * Set the IP time-to-live for outgoing multicast packets.
1880		 * The original multicast API required a char argument,
1881		 * which is inconsistent with the rest of the socket API.
1882		 * We allow either a char or an int.
1883		 */
1884		if (sopt->sopt_valsize == 1) {
1885			u_char ttl;
1886			error = sooptcopyin(sopt, &ttl, 1, 1);
1887			if (error)
1888				break;
1889			imo->imo_multicast_ttl = ttl;
1890		} else {
1891			u_int ttl;
1892			error = sooptcopyin(sopt, &ttl, sizeof ttl,
1893					    sizeof ttl);
1894			if (error)
1895				break;
1896			if (ttl > 255)
1897				error = EINVAL;
1898			else
1899				imo->imo_multicast_ttl = ttl;
1900		}
1901		break;
1902
1903	case IP_MULTICAST_LOOP:
1904		/*
1905		 * Set the loopback flag for outgoing multicast packets.
1906		 * Must be zero or one.  The original multicast API required a
1907		 * char argument, which is inconsistent with the rest
1908		 * of the socket API.  We allow either a char or an int.
1909		 */
1910		if (sopt->sopt_valsize == 1) {
1911			u_char loop;
1912			error = sooptcopyin(sopt, &loop, 1, 1);
1913			if (error)
1914				break;
1915			imo->imo_multicast_loop = !!loop;
1916		} else {
1917			u_int loop;
1918			error = sooptcopyin(sopt, &loop, sizeof loop,
1919					    sizeof loop);
1920			if (error)
1921				break;
1922			imo->imo_multicast_loop = !!loop;
1923		}
1924		break;
1925
1926	case IP_ADD_MEMBERSHIP:
1927		/*
1928		 * Add a multicast group membership.
1929		 * Group must be a valid IP multicast address.
1930		 */
1931		error = sooptcopyin(sopt, &mreq, sizeof mreq, sizeof mreq);
1932		if (error)
1933			break;
1934
1935		if (!IN_MULTICAST(ntohl(mreq.imr_multiaddr.s_addr))) {
1936			error = EINVAL;
1937			break;
1938		}
1939		s = splimp();
1940		/*
1941		 * If no interface address was provided, use the interface of
1942		 * the route to the given multicast address.
1943		 */
1944		if (mreq.imr_interface.s_addr == INADDR_ANY) {
1945			bzero((caddr_t)&ro, sizeof(ro));
1946			dst = (struct sockaddr_in *)&ro.ro_dst;
1947			dst->sin_len = sizeof(*dst);
1948			dst->sin_family = AF_INET;
1949			dst->sin_addr = mreq.imr_multiaddr;
1950			rtalloc_ign(&ro, RTF_CLONING);
1951			if (ro.ro_rt == NULL) {
1952				error = EADDRNOTAVAIL;
1953				splx(s);
1954				break;
1955			}
1956			ifp = ro.ro_rt->rt_ifp;
1957			RTFREE(ro.ro_rt);
1958		}
1959		else {
1960			ifp = ip_multicast_if(&mreq.imr_interface, NULL);
1961		}
1962
1963		/*
1964		 * See if we found an interface, and confirm that it
1965		 * supports multicast.
1966		 */
1967		if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0) {
1968			error = EADDRNOTAVAIL;
1969			splx(s);
1970			break;
1971		}
1972		/*
1973		 * See if the membership already exists or if all the
1974		 * membership slots are full.
1975		 */
1976		for (i = 0; i < imo->imo_num_memberships; ++i) {
1977			if (imo->imo_membership[i]->inm_ifp == ifp &&
1978			    imo->imo_membership[i]->inm_addr.s_addr
1979						== mreq.imr_multiaddr.s_addr)
1980				break;
1981		}
1982		if (i < imo->imo_num_memberships) {
1983			error = EADDRINUSE;
1984			splx(s);
1985			break;
1986		}
1987		if (i == IP_MAX_MEMBERSHIPS) {
1988			error = ETOOMANYREFS;
1989			splx(s);
1990			break;
1991		}
1992		/*
1993		 * Everything looks good; add a new record to the multicast
1994		 * address list for the given interface.
1995		 */
1996		if ((imo->imo_membership[i] =
1997		    in_addmulti(&mreq.imr_multiaddr, ifp)) == NULL) {
1998			error = ENOBUFS;
1999			splx(s);
2000			break;
2001		}
2002		++imo->imo_num_memberships;
2003		splx(s);
2004		break;
2005
2006	case IP_DROP_MEMBERSHIP:
2007		/*
2008		 * Drop a multicast group membership.
2009		 * Group must be a valid IP multicast address.
2010		 */
2011		error = sooptcopyin(sopt, &mreq, sizeof mreq, sizeof mreq);
2012		if (error)
2013			break;
2014
2015		if (!IN_MULTICAST(ntohl(mreq.imr_multiaddr.s_addr))) {
2016			error = EINVAL;
2017			break;
2018		}
2019
2020		s = splimp();
2021		/*
2022		 * If an interface address was specified, get a pointer
2023		 * to its ifnet structure.
2024		 */
2025		if (mreq.imr_interface.s_addr == INADDR_ANY)
2026			ifp = NULL;
2027		else {
2028			ifp = ip_multicast_if(&mreq.imr_interface, NULL);
2029			if (ifp == NULL) {
2030				error = EADDRNOTAVAIL;
2031				splx(s);
2032				break;
2033			}
2034		}
2035		/*
2036		 * Find the membership in the membership array.
2037		 */
2038		for (i = 0; i < imo->imo_num_memberships; ++i) {
2039			if ((ifp == NULL ||
2040			     imo->imo_membership[i]->inm_ifp == ifp) &&
2041			     imo->imo_membership[i]->inm_addr.s_addr ==
2042			     mreq.imr_multiaddr.s_addr)
2043				break;
2044		}
2045		if (i == imo->imo_num_memberships) {
2046			error = EADDRNOTAVAIL;
2047			splx(s);
2048			break;
2049		}
2050		/*
2051		 * Give up the multicast address record to which the
2052		 * membership points.
2053		 */
2054		in_delmulti(imo->imo_membership[i]);
2055		/*
2056		 * Remove the gap in the membership array.
2057		 */
2058		for (++i; i < imo->imo_num_memberships; ++i)
2059			imo->imo_membership[i-1] = imo->imo_membership[i];
2060		--imo->imo_num_memberships;
2061		splx(s);
2062		break;
2063
2064	default:
2065		error = EOPNOTSUPP;
2066		break;
2067	}
2068
2069	/*
2070	 * If all options have default values, no need to keep the mbuf.
2071	 */
2072	if (imo->imo_multicast_ifp == NULL &&
2073	    imo->imo_multicast_vif == -1 &&
2074	    imo->imo_multicast_ttl == IP_DEFAULT_MULTICAST_TTL &&
2075	    imo->imo_multicast_loop == IP_DEFAULT_MULTICAST_LOOP &&
2076	    imo->imo_num_memberships == 0) {
2077		free(*imop, M_IPMOPTS);
2078		*imop = NULL;
2079	}
2080
2081	return (error);
2082}
2083
2084/*
2085 * Return the IP multicast options in response to user getsockopt().
2086 */
2087static int
2088ip_getmoptions(sopt, imo)
2089	struct sockopt *sopt;
2090	register struct ip_moptions *imo;
2091{
2092	struct in_addr addr;
2093	struct in_ifaddr *ia;
2094	int error, optval;
2095	u_char coptval;
2096
2097	error = 0;
2098	switch (sopt->sopt_name) {
2099	case IP_MULTICAST_VIF:
2100		if (imo != NULL)
2101			optval = imo->imo_multicast_vif;
2102		else
2103			optval = -1;
2104		error = sooptcopyout(sopt, &optval, sizeof optval);
2105		break;
2106
2107	case IP_MULTICAST_IF:
2108		if (imo == NULL || imo->imo_multicast_ifp == NULL)
2109			addr.s_addr = INADDR_ANY;
2110		else if (imo->imo_multicast_addr.s_addr) {
2111			/* return the value user has set */
2112			addr = imo->imo_multicast_addr;
2113		} else {
2114			IFP_TO_IA(imo->imo_multicast_ifp, ia);
2115			addr.s_addr = (ia == NULL) ? INADDR_ANY
2116				: IA_SIN(ia)->sin_addr.s_addr;
2117		}
2118		error = sooptcopyout(sopt, &addr, sizeof addr);
2119		break;
2120
2121	case IP_MULTICAST_TTL:
2122		if (imo == 0)
2123			optval = coptval = IP_DEFAULT_MULTICAST_TTL;
2124		else
2125			optval = coptval = imo->imo_multicast_ttl;
2126		if (sopt->sopt_valsize == 1)
2127			error = sooptcopyout(sopt, &coptval, 1);
2128		else
2129			error = sooptcopyout(sopt, &optval, sizeof optval);
2130		break;
2131
2132	case IP_MULTICAST_LOOP:
2133		if (imo == 0)
2134			optval = coptval = IP_DEFAULT_MULTICAST_LOOP;
2135		else
2136			optval = coptval = imo->imo_multicast_loop;
2137		if (sopt->sopt_valsize == 1)
2138			error = sooptcopyout(sopt, &coptval, 1);
2139		else
2140			error = sooptcopyout(sopt, &optval, sizeof optval);
2141		break;
2142
2143	default:
2144		error = ENOPROTOOPT;
2145		break;
2146	}
2147	return (error);
2148}
2149
2150/*
2151 * Discard the IP multicast options.
2152 */
2153void
2154ip_freemoptions(imo)
2155	register struct ip_moptions *imo;
2156{
2157	register int i;
2158
2159	if (imo != NULL) {
2160		for (i = 0; i < imo->imo_num_memberships; ++i)
2161			in_delmulti(imo->imo_membership[i]);
2162		free(imo, M_IPMOPTS);
2163	}
2164}
2165
2166/*
2167 * Routine called from ip_output() to loop back a copy of an IP multicast
2168 * packet to the input queue of a specified interface.  Note that this
2169 * calls the output routine of the loopback "driver", but with an interface
2170 * pointer that might NOT be a loopback interface -- evil, but easier than
2171 * replicating that code here.
2172 */
2173static void
2174ip_mloopback(ifp, m, dst, hlen)
2175	struct ifnet *ifp;
2176	register struct mbuf *m;
2177	register struct sockaddr_in *dst;
2178	int hlen;
2179{
2180	register struct ip *ip;
2181	struct mbuf *copym;
2182
2183	copym = m_copy(m, 0, M_COPYALL);
2184	if (copym != NULL && (copym->m_flags & M_EXT || copym->m_len < hlen))
2185		copym = m_pullup(copym, hlen);
2186	if (copym != NULL) {
2187		/* If needed, compute the checksum and mark it as valid. */
2188		if (copym->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
2189			in_delayed_cksum(copym);
2190			copym->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
2191			copym->m_pkthdr.csum_flags |=
2192			    CSUM_DATA_VALID | CSUM_PSEUDO_HDR;
2193			copym->m_pkthdr.csum_data = 0xffff;
2194		}
2195		/*
2196		 * We don't bother to fragment if the IP length is greater
2197		 * than the interface's MTU.  Can this possibly matter?
2198		 */
2199		ip = mtod(copym, struct ip *);
2200		ip->ip_len = htons(ip->ip_len);
2201		ip->ip_off = htons(ip->ip_off);
2202		ip->ip_sum = 0;
2203		ip->ip_sum = in_cksum(copym, hlen);
2204		/*
2205		 * NB:
2206		 * It's not clear whether there are any lingering
2207		 * reentrancy problems in other areas which might
2208		 * be exposed by using ip_input directly (in
2209		 * particular, everything which modifies the packet
2210		 * in-place).  Yet another option is using the
2211		 * protosw directly to deliver the looped back
2212		 * packet.  For the moment, we'll err on the side
2213		 * of safety by using if_simloop().
2214		 */
2215#if 1 /* XXX */
2216		if (dst->sin_family != AF_INET) {
2217			printf("ip_mloopback: bad address family %d\n",
2218						dst->sin_family);
2219			dst->sin_family = AF_INET;
2220		}
2221#endif
2222
2223#ifdef notdef
2224		copym->m_pkthdr.rcvif = ifp;
2225		ip_input(copym);
2226#else
2227		if_simloop(ifp, copym, dst->sin_family, 0);
2228#endif
2229	}
2230}
2231