ip_output.c revision 185101
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 */
31
32#include <sys/cdefs.h>
33__FBSDID("$FreeBSD: head/sys/netinet/ip_output.c 185101 2008-11-19 19:19:30Z julian $");
34
35#include "opt_ipfw.h"
36#include "opt_ipsec.h"
37#include "opt_mac.h"
38#include "opt_mbuf_stress_test.h"
39#include "opt_mpath.h"
40
41#include <sys/param.h>
42#include <sys/systm.h>
43#include <sys/kernel.h>
44#include <sys/malloc.h>
45#include <sys/mbuf.h>
46#include <sys/priv.h>
47#include <sys/proc.h>
48#include <sys/protosw.h>
49#include <sys/socket.h>
50#include <sys/socketvar.h>
51#include <sys/sysctl.h>
52#include <sys/ucred.h>
53#include <sys/vimage.h>
54
55#include <net/if.h>
56#include <net/netisr.h>
57#include <net/pfil.h>
58#include <net/route.h>
59#ifdef RADIX_MPATH
60#include <net/radix_mpath.h>
61#endif
62
63#include <netinet/in.h>
64#include <netinet/in_systm.h>
65#include <netinet/ip.h>
66#include <netinet/in_pcb.h>
67#include <netinet/in_var.h>
68#include <netinet/ip_var.h>
69#include <netinet/ip_options.h>
70
71#ifdef IPSEC
72#include <netinet/ip_ipsec.h>
73#include <netipsec/ipsec.h>
74#endif /* IPSEC*/
75
76#include <machine/in_cksum.h>
77
78#include <security/mac/mac_framework.h>
79
80#define print_ip(x, a, y)	 printf("%s %d.%d.%d.%d%s",\
81				x, (ntohl(a.s_addr)>>24)&0xFF,\
82				  (ntohl(a.s_addr)>>16)&0xFF,\
83				  (ntohl(a.s_addr)>>8)&0xFF,\
84				  (ntohl(a.s_addr))&0xFF, y);
85
86#ifdef VIMAGE_GLOBALS
87u_short ip_id;
88#endif
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 void	ip_mloopback
97	(struct ifnet *, struct mbuf *, struct sockaddr_in *, int);
98
99
100extern	struct protosw inetsw[];
101
102/*
103 * IP output.  The packet in mbuf chain m contains a skeletal IP
104 * header (with len, off, ttl, proto, tos, src, dst).
105 * The mbuf chain containing the packet will be freed.
106 * The mbuf opt, if present, will not be freed.
107 * In the IP forwarding case, the packet will arrive with options already
108 * inserted, so must have a NULL opt pointer.
109 */
110int
111ip_output(struct mbuf *m, struct mbuf *opt, struct route *ro, int flags,
112    struct ip_moptions *imo, struct inpcb *inp)
113{
114	INIT_VNET_NET(curvnet);
115	INIT_VNET_INET(curvnet);
116	struct ip *ip;
117	struct ifnet *ifp = NULL;	/* keep compiler happy */
118	struct mbuf *m0;
119	int hlen = sizeof (struct ip);
120	int mtu;
121	int len, error = 0;
122	struct sockaddr_in *dst = NULL;	/* keep compiler happy */
123	struct in_ifaddr *ia = NULL;
124	int isbroadcast, sw_csum;
125	struct route iproute;
126	struct in_addr odst;
127#ifdef IPFIREWALL_FORWARD
128	struct m_tag *fwd_tag = NULL;
129#endif
130	M_ASSERTPKTHDR(m);
131
132	if (ro == NULL) {
133		ro = &iproute;
134		bzero(ro, sizeof (*ro));
135	}
136
137	if (inp != NULL) {
138		M_SETFIB(m, inp->inp_inc.inc_fibnum);
139		INP_LOCK_ASSERT(inp);
140	}
141
142	if (opt) {
143		len = 0;
144		m = ip_insertoptions(m, opt, &len);
145		if (len != 0)
146			hlen = len;
147	}
148	ip = mtod(m, struct ip *);
149
150	/*
151	 * Fill in IP header.  If we are not allowing fragmentation,
152	 * then the ip_id field is meaningless, but we don't set it
153	 * to zero.  Doing so causes various problems when devices along
154	 * the path (routers, load balancers, firewalls, etc.) illegally
155	 * disable DF on our packet.  Note that a 16-bit counter
156	 * will wrap around in less than 10 seconds at 100 Mbit/s on a
157	 * medium with MTU 1500.  See Steven M. Bellovin, "A Technique
158	 * for Counting NATted Hosts", Proc. IMW'02, available at
159	 * <http://www.cs.columbia.edu/~smb/papers/fnat.pdf>.
160	 */
161	if ((flags & (IP_FORWARDING|IP_RAWOUTPUT)) == 0) {
162		ip->ip_v = IPVERSION;
163		ip->ip_hl = hlen >> 2;
164		ip->ip_id = ip_newid();
165		V_ipstat.ips_localout++;
166	} else {
167		hlen = ip->ip_hl << 2;
168	}
169
170	dst = (struct sockaddr_in *)&ro->ro_dst;
171again:
172	/*
173	 * If there is a cached route,
174	 * check that it is to the same destination
175	 * and is still up.  If not, free it and try again.
176	 * The address family should also be checked in case of sharing the
177	 * cache with IPv6.
178	 */
179	if (ro->ro_rt && ((ro->ro_rt->rt_flags & RTF_UP) == 0 ||
180			  dst->sin_family != AF_INET ||
181			  dst->sin_addr.s_addr != ip->ip_dst.s_addr)) {
182		RTFREE(ro->ro_rt);
183		ro->ro_rt = (struct rtentry *)NULL;
184	}
185#ifdef IPFIREWALL_FORWARD
186	if (ro->ro_rt == NULL && fwd_tag == NULL) {
187#else
188	if (ro->ro_rt == NULL) {
189#endif
190		bzero(dst, sizeof(*dst));
191		dst->sin_family = AF_INET;
192		dst->sin_len = sizeof(*dst);
193		dst->sin_addr = ip->ip_dst;
194	}
195	/*
196	 * If routing to interface only, short circuit routing lookup.
197	 * The use of an all-ones broadcast address implies this; an
198	 * interface is specified by the broadcast address of an interface,
199	 * or the destination address of a ptp interface.
200	 */
201	if (flags & IP_SENDONES) {
202		if ((ia = ifatoia(ifa_ifwithbroadaddr(sintosa(dst)))) == NULL &&
203		    (ia = ifatoia(ifa_ifwithdstaddr(sintosa(dst)))) == NULL) {
204			V_ipstat.ips_noroute++;
205			error = ENETUNREACH;
206			goto bad;
207		}
208		ip->ip_dst.s_addr = INADDR_BROADCAST;
209		dst->sin_addr = ip->ip_dst;
210		ifp = ia->ia_ifp;
211		ip->ip_ttl = 1;
212		isbroadcast = 1;
213	} else if (flags & IP_ROUTETOIF) {
214		if ((ia = ifatoia(ifa_ifwithdstaddr(sintosa(dst)))) == NULL &&
215		    (ia = ifatoia(ifa_ifwithnet(sintosa(dst)))) == NULL) {
216			V_ipstat.ips_noroute++;
217			error = ENETUNREACH;
218			goto bad;
219		}
220		ifp = ia->ia_ifp;
221		ip->ip_ttl = 1;
222		isbroadcast = in_broadcast(dst->sin_addr, ifp);
223	} else if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) &&
224	    imo != NULL && imo->imo_multicast_ifp != NULL) {
225		/*
226		 * Bypass the normal routing lookup for multicast
227		 * packets if the interface is specified.
228		 */
229		ifp = imo->imo_multicast_ifp;
230		IFP_TO_IA(ifp, ia);
231		isbroadcast = 0;	/* fool gcc */
232	} else {
233		/*
234		 * We want to do any cloning requested by the link layer,
235		 * as this is probably required in all cases for correct
236		 * operation (as it is for ARP).
237		 */
238		if (ro->ro_rt == NULL)
239#ifdef RADIX_MPATH
240			rtalloc_mpath_fib(ro,
241			    ntohl(ip->ip_src.s_addr ^ ip->ip_dst.s_addr),
242			    inp ? inp->inp_inc.inc_fibnum : M_GETFIB(m));
243#else
244			in_rtalloc_ign(ro, 0,
245			    inp ? inp->inp_inc.inc_fibnum : M_GETFIB(m));
246#endif
247		if (ro->ro_rt == NULL) {
248			V_ipstat.ips_noroute++;
249			error = EHOSTUNREACH;
250			goto bad;
251		}
252		ia = ifatoia(ro->ro_rt->rt_ifa);
253		ifp = ro->ro_rt->rt_ifp;
254		ro->ro_rt->rt_rmx.rmx_pksent++;
255		if (ro->ro_rt->rt_flags & RTF_GATEWAY)
256			dst = (struct sockaddr_in *)ro->ro_rt->rt_gateway;
257		if (ro->ro_rt->rt_flags & RTF_HOST)
258			isbroadcast = (ro->ro_rt->rt_flags & RTF_BROADCAST);
259		else
260			isbroadcast = in_broadcast(dst->sin_addr, ifp);
261	}
262	/*
263	 * Calculate MTU.  If we have a route that is up, use that,
264	 * otherwise use the interface's MTU.
265	 */
266	if (ro->ro_rt != NULL && (ro->ro_rt->rt_flags & (RTF_UP|RTF_HOST))) {
267		/*
268		 * This case can happen if the user changed the MTU
269		 * of an interface after enabling IP on it.  Because
270		 * most netifs don't keep track of routes pointing to
271		 * them, there is no way for one to update all its
272		 * routes when the MTU is changed.
273		 */
274		if (ro->ro_rt->rt_rmx.rmx_mtu > ifp->if_mtu)
275			ro->ro_rt->rt_rmx.rmx_mtu = ifp->if_mtu;
276		mtu = ro->ro_rt->rt_rmx.rmx_mtu;
277	} else {
278		mtu = ifp->if_mtu;
279	}
280	if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr))) {
281		struct in_multi *inm;
282
283		m->m_flags |= M_MCAST;
284		/*
285		 * IP destination address is multicast.  Make sure "dst"
286		 * still points to the address in "ro".  (It may have been
287		 * changed to point to a gateway address, above.)
288		 */
289		dst = (struct sockaddr_in *)&ro->ro_dst;
290		/*
291		 * See if the caller provided any multicast options
292		 */
293		if (imo != NULL) {
294			ip->ip_ttl = imo->imo_multicast_ttl;
295			if (imo->imo_multicast_vif != -1)
296				ip->ip_src.s_addr =
297				    ip_mcast_src ?
298				    ip_mcast_src(imo->imo_multicast_vif) :
299				    INADDR_ANY;
300		} else
301			ip->ip_ttl = IP_DEFAULT_MULTICAST_TTL;
302		/*
303		 * Confirm that the outgoing interface supports multicast.
304		 */
305		if ((imo == NULL) || (imo->imo_multicast_vif == -1)) {
306			if ((ifp->if_flags & IFF_MULTICAST) == 0) {
307				V_ipstat.ips_noroute++;
308				error = ENETUNREACH;
309				goto bad;
310			}
311		}
312		/*
313		 * If source address not specified yet, use address
314		 * of outgoing interface.
315		 */
316		if (ip->ip_src.s_addr == INADDR_ANY) {
317			/* Interface may have no addresses. */
318			if (ia != NULL)
319				ip->ip_src = IA_SIN(ia)->sin_addr;
320		}
321
322		IN_MULTI_LOCK();
323		IN_LOOKUP_MULTI(ip->ip_dst, ifp, inm);
324		if (inm != NULL &&
325		   (imo == NULL || imo->imo_multicast_loop)) {
326			IN_MULTI_UNLOCK();
327			/*
328			 * If we belong to the destination multicast group
329			 * on the outgoing interface, and the caller did not
330			 * forbid loopback, loop back a copy.
331			 */
332			ip_mloopback(ifp, m, dst, hlen);
333		}
334		else {
335			IN_MULTI_UNLOCK();
336			/*
337			 * If we are acting as a multicast router, perform
338			 * multicast forwarding as if the packet had just
339			 * arrived on the interface to which we are about
340			 * to send.  The multicast forwarding function
341			 * recursively calls this function, using the
342			 * IP_FORWARDING flag to prevent infinite recursion.
343			 *
344			 * Multicasts that are looped back by ip_mloopback(),
345			 * above, will be forwarded by the ip_input() routine,
346			 * if necessary.
347			 */
348			if (V_ip_mrouter && (flags & IP_FORWARDING) == 0) {
349				/*
350				 * If rsvp daemon is not running, do not
351				 * set ip_moptions. This ensures that the packet
352				 * is multicast and not just sent down one link
353				 * as prescribed by rsvpd.
354				 */
355				if (!V_rsvp_on)
356					imo = NULL;
357				if (ip_mforward &&
358				    ip_mforward(ip, ifp, m, imo) != 0) {
359					m_freem(m);
360					goto done;
361				}
362			}
363		}
364
365		/*
366		 * Multicasts with a time-to-live of zero may be looped-
367		 * back, above, but must not be transmitted on a network.
368		 * Also, multicasts addressed to the loopback interface
369		 * are not sent -- the above call to ip_mloopback() will
370		 * loop back a copy if this host actually belongs to the
371		 * destination group on the loopback interface.
372		 */
373		if (ip->ip_ttl == 0 || ifp->if_flags & IFF_LOOPBACK) {
374			m_freem(m);
375			goto done;
376		}
377
378		goto sendit;
379	}
380
381	/*
382	 * If the source address is not specified yet, use the address
383	 * of the outoing interface.
384	 */
385	if (ip->ip_src.s_addr == INADDR_ANY) {
386		/* Interface may have no addresses. */
387		if (ia != NULL) {
388			ip->ip_src = IA_SIN(ia)->sin_addr;
389		}
390	}
391
392	/*
393	 * Verify that we have any chance at all of being able to queue the
394	 * packet or packet fragments, unless ALTQ is enabled on the given
395	 * interface in which case packetdrop should be done by queueing.
396	 */
397#ifdef ALTQ
398	if ((!ALTQ_IS_ENABLED(&ifp->if_snd)) &&
399	    ((ifp->if_snd.ifq_len + ip->ip_len / mtu + 1) >=
400	    ifp->if_snd.ifq_maxlen))
401#else
402	if ((ifp->if_snd.ifq_len + ip->ip_len / mtu + 1) >=
403	    ifp->if_snd.ifq_maxlen)
404#endif /* ALTQ */
405	{
406		error = ENOBUFS;
407		V_ipstat.ips_odropped++;
408		ifp->if_snd.ifq_drops += (ip->ip_len / ifp->if_mtu + 1);
409		goto bad;
410	}
411
412	/*
413	 * Look for broadcast address and
414	 * verify user is allowed to send
415	 * such a packet.
416	 */
417	if (isbroadcast) {
418		if ((ifp->if_flags & IFF_BROADCAST) == 0) {
419			error = EADDRNOTAVAIL;
420			goto bad;
421		}
422		if ((flags & IP_ALLOWBROADCAST) == 0) {
423			error = EACCES;
424			goto bad;
425		}
426		/* don't allow broadcast messages to be fragmented */
427		if (ip->ip_len > mtu) {
428			error = EMSGSIZE;
429			goto bad;
430		}
431		m->m_flags |= M_BCAST;
432	} else {
433		m->m_flags &= ~M_BCAST;
434	}
435
436sendit:
437#ifdef IPSEC
438	switch(ip_ipsec_output(&m, inp, &flags, &error, &ro, &iproute, &dst, &ia, &ifp)) {
439	case 1:
440		goto bad;
441	case -1:
442		goto done;
443	case 0:
444	default:
445		break;	/* Continue with packet processing. */
446	}
447	/* Update variables that are affected by ipsec4_output(). */
448	ip = mtod(m, struct ip *);
449	hlen = ip->ip_hl << 2;
450#endif /* IPSEC */
451
452	/* Jump over all PFIL processing if hooks are not active. */
453	if (!PFIL_HOOKED(&inet_pfil_hook))
454		goto passout;
455
456	/* Run through list of hooks for output packets. */
457	odst.s_addr = ip->ip_dst.s_addr;
458	error = pfil_run_hooks(&inet_pfil_hook, &m, ifp, PFIL_OUT, inp);
459	if (error != 0 || m == NULL)
460		goto done;
461
462	ip = mtod(m, struct ip *);
463
464	/* See if destination IP address was changed by packet filter. */
465	if (odst.s_addr != ip->ip_dst.s_addr) {
466		m->m_flags |= M_SKIP_FIREWALL;
467		/* If destination is now ourself drop to ip_input(). */
468		if (in_localip(ip->ip_dst)) {
469			m->m_flags |= M_FASTFWD_OURS;
470			if (m->m_pkthdr.rcvif == NULL)
471				m->m_pkthdr.rcvif = V_loif;
472			if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
473				m->m_pkthdr.csum_flags |=
474				    CSUM_DATA_VALID | CSUM_PSEUDO_HDR;
475				m->m_pkthdr.csum_data = 0xffff;
476			}
477			m->m_pkthdr.csum_flags |=
478			    CSUM_IP_CHECKED | CSUM_IP_VALID;
479
480			error = netisr_queue(NETISR_IP, m);
481			goto done;
482		} else
483			goto again;	/* Redo the routing table lookup. */
484	}
485
486#ifdef IPFIREWALL_FORWARD
487	/* See if local, if yes, send it to netisr with IP_FASTFWD_OURS. */
488	if (m->m_flags & M_FASTFWD_OURS) {
489		if (m->m_pkthdr.rcvif == NULL)
490			m->m_pkthdr.rcvif = V_loif;
491		if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
492			m->m_pkthdr.csum_flags |=
493			    CSUM_DATA_VALID | CSUM_PSEUDO_HDR;
494			m->m_pkthdr.csum_data = 0xffff;
495		}
496		m->m_pkthdr.csum_flags |=
497			    CSUM_IP_CHECKED | CSUM_IP_VALID;
498
499		error = netisr_queue(NETISR_IP, m);
500		goto done;
501	}
502	/* Or forward to some other address? */
503	fwd_tag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL);
504	if (fwd_tag) {
505		dst = (struct sockaddr_in *)&ro->ro_dst;
506		bcopy((fwd_tag+1), dst, sizeof(struct sockaddr_in));
507		m->m_flags |= M_SKIP_FIREWALL;
508		m_tag_delete(m, fwd_tag);
509		goto again;
510	}
511#endif /* IPFIREWALL_FORWARD */
512
513passout:
514	/* 127/8 must not appear on wire - RFC1122. */
515	if ((ntohl(ip->ip_dst.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET ||
516	    (ntohl(ip->ip_src.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET) {
517		if ((ifp->if_flags & IFF_LOOPBACK) == 0) {
518			V_ipstat.ips_badaddr++;
519			error = EADDRNOTAVAIL;
520			goto bad;
521		}
522	}
523
524	m->m_pkthdr.csum_flags |= CSUM_IP;
525	sw_csum = m->m_pkthdr.csum_flags & ~ifp->if_hwassist;
526	if (sw_csum & CSUM_DELAY_DATA) {
527		in_delayed_cksum(m);
528		sw_csum &= ~CSUM_DELAY_DATA;
529	}
530	m->m_pkthdr.csum_flags &= ifp->if_hwassist;
531
532	/*
533	 * If small enough for interface, or the interface will take
534	 * care of the fragmentation for us, we can just send directly.
535	 */
536	if (ip->ip_len <= mtu ||
537	    (m->m_pkthdr.csum_flags & ifp->if_hwassist & CSUM_TSO) != 0 ||
538	    ((ip->ip_off & IP_DF) == 0 && (ifp->if_hwassist & CSUM_FRAGMENT))) {
539		ip->ip_len = htons(ip->ip_len);
540		ip->ip_off = htons(ip->ip_off);
541		ip->ip_sum = 0;
542		if (sw_csum & CSUM_DELAY_IP)
543			ip->ip_sum = in_cksum(m, hlen);
544
545		/*
546		 * Record statistics for this interface address.
547		 * With CSUM_TSO the byte/packet count will be slightly
548		 * incorrect because we count the IP+TCP headers only
549		 * once instead of for every generated packet.
550		 */
551		if (!(flags & IP_FORWARDING) && ia) {
552			if (m->m_pkthdr.csum_flags & CSUM_TSO)
553				ia->ia_ifa.if_opackets +=
554				    m->m_pkthdr.len / m->m_pkthdr.tso_segsz;
555			else
556				ia->ia_ifa.if_opackets++;
557			ia->ia_ifa.if_obytes += m->m_pkthdr.len;
558		}
559#ifdef MBUF_STRESS_TEST
560		if (mbuf_frag_size && m->m_pkthdr.len > mbuf_frag_size)
561			m = m_fragment(m, M_DONTWAIT, mbuf_frag_size);
562#endif
563		/*
564		 * Reset layer specific mbuf flags
565		 * to avoid confusing lower layers.
566		 */
567		m->m_flags &= ~(M_PROTOFLAGS);
568
569		error = (*ifp->if_output)(ifp, m,
570				(struct sockaddr *)dst, ro->ro_rt);
571		goto done;
572	}
573
574	/* Balk when DF bit is set or the interface didn't support TSO. */
575	if ((ip->ip_off & IP_DF) || (m->m_pkthdr.csum_flags & CSUM_TSO)) {
576		error = EMSGSIZE;
577		V_ipstat.ips_cantfrag++;
578		goto bad;
579	}
580
581	/*
582	 * Too large for interface; fragment if possible. If successful,
583	 * on return, m will point to a list of packets to be sent.
584	 */
585	error = ip_fragment(ip, &m, mtu, ifp->if_hwassist, sw_csum);
586	if (error)
587		goto bad;
588	for (; m; m = m0) {
589		m0 = m->m_nextpkt;
590		m->m_nextpkt = 0;
591		if (error == 0) {
592			/* Record statistics for this interface address. */
593			if (ia != NULL) {
594				ia->ia_ifa.if_opackets++;
595				ia->ia_ifa.if_obytes += m->m_pkthdr.len;
596			}
597			/*
598			 * Reset layer specific mbuf flags
599			 * to avoid confusing upper layers.
600			 */
601			m->m_flags &= ~(M_PROTOFLAGS);
602
603			error = (*ifp->if_output)(ifp, m,
604			    (struct sockaddr *)dst, ro->ro_rt);
605		} else
606			m_freem(m);
607	}
608
609	if (error == 0)
610		V_ipstat.ips_fragmented++;
611
612done:
613	if (ro == &iproute && ro->ro_rt) {
614		RTFREE(ro->ro_rt);
615	}
616	return (error);
617bad:
618	m_freem(m);
619	goto done;
620}
621
622/*
623 * Create a chain of fragments which fit the given mtu. m_frag points to the
624 * mbuf to be fragmented; on return it points to the chain with the fragments.
625 * Return 0 if no error. If error, m_frag may contain a partially built
626 * chain of fragments that should be freed by the caller.
627 *
628 * if_hwassist_flags is the hw offload capabilities (see if_data.ifi_hwassist)
629 * sw_csum contains the delayed checksums flags (e.g., CSUM_DELAY_IP).
630 */
631int
632ip_fragment(struct ip *ip, struct mbuf **m_frag, int mtu,
633    u_long if_hwassist_flags, int sw_csum)
634{
635	INIT_VNET_INET(curvnet);
636	int error = 0;
637	int hlen = ip->ip_hl << 2;
638	int len = (mtu - hlen) & ~7;	/* size of payload in each fragment */
639	int off;
640	struct mbuf *m0 = *m_frag;	/* the original packet		*/
641	int firstlen;
642	struct mbuf **mnext;
643	int nfrags;
644
645	if (ip->ip_off & IP_DF) {	/* Fragmentation not allowed */
646		V_ipstat.ips_cantfrag++;
647		return EMSGSIZE;
648	}
649
650	/*
651	 * Must be able to put at least 8 bytes per fragment.
652	 */
653	if (len < 8)
654		return EMSGSIZE;
655
656	/*
657	 * If the interface will not calculate checksums on
658	 * fragmented packets, then do it here.
659	 */
660	if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA &&
661	    (if_hwassist_flags & CSUM_IP_FRAGS) == 0) {
662		in_delayed_cksum(m0);
663		m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
664	}
665
666	if (len > PAGE_SIZE) {
667		/*
668		 * Fragment large datagrams such that each segment
669		 * contains a multiple of PAGE_SIZE amount of data,
670		 * plus headers. This enables a receiver to perform
671		 * page-flipping zero-copy optimizations.
672		 *
673		 * XXX When does this help given that sender and receiver
674		 * could have different page sizes, and also mtu could
675		 * be less than the receiver's page size ?
676		 */
677		int newlen;
678		struct mbuf *m;
679
680		for (m = m0, off = 0; m && (off+m->m_len) <= mtu; m = m->m_next)
681			off += m->m_len;
682
683		/*
684		 * firstlen (off - hlen) must be aligned on an
685		 * 8-byte boundary
686		 */
687		if (off < hlen)
688			goto smart_frag_failure;
689		off = ((off - hlen) & ~7) + hlen;
690		newlen = (~PAGE_MASK) & mtu;
691		if ((newlen + sizeof (struct ip)) > mtu) {
692			/* we failed, go back the default */
693smart_frag_failure:
694			newlen = len;
695			off = hlen + len;
696		}
697		len = newlen;
698
699	} else {
700		off = hlen + len;
701	}
702
703	firstlen = off - hlen;
704	mnext = &m0->m_nextpkt;		/* pointer to next packet */
705
706	/*
707	 * Loop through length of segment after first fragment,
708	 * make new header and copy data of each part and link onto chain.
709	 * Here, m0 is the original packet, m is the fragment being created.
710	 * The fragments are linked off the m_nextpkt of the original
711	 * packet, which after processing serves as the first fragment.
712	 */
713	for (nfrags = 1; off < ip->ip_len; off += len, nfrags++) {
714		struct ip *mhip;	/* ip header on the fragment */
715		struct mbuf *m;
716		int mhlen = sizeof (struct ip);
717
718		MGETHDR(m, M_DONTWAIT, MT_DATA);
719		if (m == NULL) {
720			error = ENOBUFS;
721			V_ipstat.ips_odropped++;
722			goto done;
723		}
724		m->m_flags |= (m0->m_flags & M_MCAST) | M_FRAG;
725		/*
726		 * In the first mbuf, leave room for the link header, then
727		 * copy the original IP header including options. The payload
728		 * goes into an additional mbuf chain returned by m_copy().
729		 */
730		m->m_data += max_linkhdr;
731		mhip = mtod(m, struct ip *);
732		*mhip = *ip;
733		if (hlen > sizeof (struct ip)) {
734			mhlen = ip_optcopy(ip, mhip) + sizeof (struct ip);
735			mhip->ip_v = IPVERSION;
736			mhip->ip_hl = mhlen >> 2;
737		}
738		m->m_len = mhlen;
739		/* XXX do we need to add ip->ip_off below ? */
740		mhip->ip_off = ((off - hlen) >> 3) + ip->ip_off;
741		if (off + len >= ip->ip_len) {	/* last fragment */
742			len = ip->ip_len - off;
743			m->m_flags |= M_LASTFRAG;
744		} else
745			mhip->ip_off |= IP_MF;
746		mhip->ip_len = htons((u_short)(len + mhlen));
747		m->m_next = m_copy(m0, off, len);
748		if (m->m_next == NULL) {	/* copy failed */
749			m_free(m);
750			error = ENOBUFS;	/* ??? */
751			V_ipstat.ips_odropped++;
752			goto done;
753		}
754		m->m_pkthdr.len = mhlen + len;
755		m->m_pkthdr.rcvif = NULL;
756#ifdef MAC
757		mac_netinet_fragment(m0, m);
758#endif
759		m->m_pkthdr.csum_flags = m0->m_pkthdr.csum_flags;
760		mhip->ip_off = htons(mhip->ip_off);
761		mhip->ip_sum = 0;
762		if (sw_csum & CSUM_DELAY_IP)
763			mhip->ip_sum = in_cksum(m, mhlen);
764		*mnext = m;
765		mnext = &m->m_nextpkt;
766	}
767	V_ipstat.ips_ofragments += nfrags;
768
769	/* set first marker for fragment chain */
770	m0->m_flags |= M_FIRSTFRAG | M_FRAG;
771	m0->m_pkthdr.csum_data = nfrags;
772
773	/*
774	 * Update first fragment by trimming what's been copied out
775	 * and updating header.
776	 */
777	m_adj(m0, hlen + firstlen - ip->ip_len);
778	m0->m_pkthdr.len = hlen + firstlen;
779	ip->ip_len = htons((u_short)m0->m_pkthdr.len);
780	ip->ip_off |= IP_MF;
781	ip->ip_off = htons(ip->ip_off);
782	ip->ip_sum = 0;
783	if (sw_csum & CSUM_DELAY_IP)
784		ip->ip_sum = in_cksum(m0, hlen);
785
786done:
787	*m_frag = m0;
788	return error;
789}
790
791void
792in_delayed_cksum(struct mbuf *m)
793{
794	struct ip *ip;
795	u_short csum, offset;
796
797	ip = mtod(m, struct ip *);
798	offset = ip->ip_hl << 2 ;
799	csum = in_cksum_skip(m, ip->ip_len, offset);
800	if (m->m_pkthdr.csum_flags & CSUM_UDP && csum == 0)
801		csum = 0xffff;
802	offset += m->m_pkthdr.csum_data;	/* checksum offset */
803
804	if (offset + sizeof(u_short) > m->m_len) {
805		printf("delayed m_pullup, m->len: %d  off: %d  p: %d\n",
806		    m->m_len, offset, ip->ip_p);
807		/*
808		 * XXX
809		 * this shouldn't happen, but if it does, the
810		 * correct behavior may be to insert the checksum
811		 * in the appropriate next mbuf in the chain.
812		 */
813		return;
814	}
815	*(u_short *)(m->m_data + offset) = csum;
816}
817
818/*
819 * IP socket option processing.
820 */
821int
822ip_ctloutput(struct socket *so, struct sockopt *sopt)
823{
824	struct	inpcb *inp = sotoinpcb(so);
825	int	error, optval;
826
827	error = optval = 0;
828	if (sopt->sopt_level != IPPROTO_IP) {
829		if ((sopt->sopt_level == SOL_SOCKET) &&
830		    (sopt->sopt_name == SO_SETFIB)) {
831			inp->inp_inc.inc_fibnum = so->so_fibnum;
832			return (0);
833		}
834		return (EINVAL);
835	}
836
837	switch (sopt->sopt_dir) {
838	case SOPT_SET:
839		switch (sopt->sopt_name) {
840		case IP_OPTIONS:
841#ifdef notyet
842		case IP_RETOPTS:
843#endif
844		{
845			struct mbuf *m;
846			if (sopt->sopt_valsize > MLEN) {
847				error = EMSGSIZE;
848				break;
849			}
850			MGET(m, sopt->sopt_td ? M_WAIT : M_DONTWAIT, MT_DATA);
851			if (m == NULL) {
852				error = ENOBUFS;
853				break;
854			}
855			m->m_len = sopt->sopt_valsize;
856			error = sooptcopyin(sopt, mtod(m, char *), m->m_len,
857					    m->m_len);
858			if (error) {
859				m_free(m);
860				break;
861			}
862			INP_WLOCK(inp);
863			error = ip_pcbopts(inp, sopt->sopt_name, m);
864			INP_WUNLOCK(inp);
865			return (error);
866		}
867
868		case IP_TOS:
869		case IP_TTL:
870		case IP_MINTTL:
871		case IP_RECVOPTS:
872		case IP_RECVRETOPTS:
873		case IP_RECVDSTADDR:
874		case IP_RECVTTL:
875		case IP_RECVIF:
876		case IP_FAITH:
877		case IP_ONESBCAST:
878		case IP_DONTFRAG:
879			error = sooptcopyin(sopt, &optval, sizeof optval,
880					    sizeof optval);
881			if (error)
882				break;
883
884			switch (sopt->sopt_name) {
885			case IP_TOS:
886				inp->inp_ip_tos = optval;
887				break;
888
889			case IP_TTL:
890				inp->inp_ip_ttl = optval;
891				break;
892
893			case IP_MINTTL:
894				if (optval > 0 && optval <= MAXTTL)
895					inp->inp_ip_minttl = optval;
896				else
897					error = EINVAL;
898				break;
899
900#define	OPTSET(bit) do {						\
901	INP_WLOCK(inp);							\
902	if (optval)							\
903		inp->inp_flags |= bit;					\
904	else								\
905		inp->inp_flags &= ~bit;					\
906	INP_WUNLOCK(inp);						\
907} while (0)
908
909			case IP_RECVOPTS:
910				OPTSET(INP_RECVOPTS);
911				break;
912
913			case IP_RECVRETOPTS:
914				OPTSET(INP_RECVRETOPTS);
915				break;
916
917			case IP_RECVDSTADDR:
918				OPTSET(INP_RECVDSTADDR);
919				break;
920
921			case IP_RECVTTL:
922				OPTSET(INP_RECVTTL);
923				break;
924
925			case IP_RECVIF:
926				OPTSET(INP_RECVIF);
927				break;
928
929			case IP_FAITH:
930				OPTSET(INP_FAITH);
931				break;
932
933			case IP_ONESBCAST:
934				OPTSET(INP_ONESBCAST);
935				break;
936			case IP_DONTFRAG:
937				OPTSET(INP_DONTFRAG);
938				break;
939			}
940			break;
941#undef OPTSET
942
943		/*
944		 * Multicast socket options are processed by the in_mcast
945		 * module.
946		 */
947		case IP_MULTICAST_IF:
948		case IP_MULTICAST_VIF:
949		case IP_MULTICAST_TTL:
950		case IP_MULTICAST_LOOP:
951		case IP_ADD_MEMBERSHIP:
952		case IP_DROP_MEMBERSHIP:
953		case IP_ADD_SOURCE_MEMBERSHIP:
954		case IP_DROP_SOURCE_MEMBERSHIP:
955		case IP_BLOCK_SOURCE:
956		case IP_UNBLOCK_SOURCE:
957		case IP_MSFILTER:
958		case MCAST_JOIN_GROUP:
959		case MCAST_LEAVE_GROUP:
960		case MCAST_JOIN_SOURCE_GROUP:
961		case MCAST_LEAVE_SOURCE_GROUP:
962		case MCAST_BLOCK_SOURCE:
963		case MCAST_UNBLOCK_SOURCE:
964			error = inp_setmoptions(inp, sopt);
965			break;
966
967		case IP_PORTRANGE:
968			error = sooptcopyin(sopt, &optval, sizeof optval,
969					    sizeof optval);
970			if (error)
971				break;
972
973			INP_WLOCK(inp);
974			switch (optval) {
975			case IP_PORTRANGE_DEFAULT:
976				inp->inp_flags &= ~(INP_LOWPORT);
977				inp->inp_flags &= ~(INP_HIGHPORT);
978				break;
979
980			case IP_PORTRANGE_HIGH:
981				inp->inp_flags &= ~(INP_LOWPORT);
982				inp->inp_flags |= INP_HIGHPORT;
983				break;
984
985			case IP_PORTRANGE_LOW:
986				inp->inp_flags &= ~(INP_HIGHPORT);
987				inp->inp_flags |= INP_LOWPORT;
988				break;
989
990			default:
991				error = EINVAL;
992				break;
993			}
994			INP_WUNLOCK(inp);
995			break;
996
997#ifdef IPSEC
998		case IP_IPSEC_POLICY:
999		{
1000			caddr_t req;
1001			struct mbuf *m;
1002
1003			if ((error = soopt_getm(sopt, &m)) != 0) /* XXX */
1004				break;
1005			if ((error = soopt_mcopyin(sopt, m)) != 0) /* XXX */
1006				break;
1007			req = mtod(m, caddr_t);
1008			error = ipsec4_set_policy(inp, sopt->sopt_name, req,
1009			    m->m_len, (sopt->sopt_td != NULL) ?
1010			    sopt->sopt_td->td_ucred : NULL);
1011			m_freem(m);
1012			break;
1013		}
1014#endif /* IPSEC */
1015
1016		default:
1017			error = ENOPROTOOPT;
1018			break;
1019		}
1020		break;
1021
1022	case SOPT_GET:
1023		switch (sopt->sopt_name) {
1024		case IP_OPTIONS:
1025		case IP_RETOPTS:
1026			if (inp->inp_options)
1027				error = sooptcopyout(sopt,
1028						     mtod(inp->inp_options,
1029							  char *),
1030						     inp->inp_options->m_len);
1031			else
1032				sopt->sopt_valsize = 0;
1033			break;
1034
1035		case IP_TOS:
1036		case IP_TTL:
1037		case IP_MINTTL:
1038		case IP_RECVOPTS:
1039		case IP_RECVRETOPTS:
1040		case IP_RECVDSTADDR:
1041		case IP_RECVTTL:
1042		case IP_RECVIF:
1043		case IP_PORTRANGE:
1044		case IP_FAITH:
1045		case IP_ONESBCAST:
1046		case IP_DONTFRAG:
1047			switch (sopt->sopt_name) {
1048
1049			case IP_TOS:
1050				optval = inp->inp_ip_tos;
1051				break;
1052
1053			case IP_TTL:
1054				optval = inp->inp_ip_ttl;
1055				break;
1056
1057			case IP_MINTTL:
1058				optval = inp->inp_ip_minttl;
1059				break;
1060
1061#define	OPTBIT(bit)	(inp->inp_flags & bit ? 1 : 0)
1062
1063			case IP_RECVOPTS:
1064				optval = OPTBIT(INP_RECVOPTS);
1065				break;
1066
1067			case IP_RECVRETOPTS:
1068				optval = OPTBIT(INP_RECVRETOPTS);
1069				break;
1070
1071			case IP_RECVDSTADDR:
1072				optval = OPTBIT(INP_RECVDSTADDR);
1073				break;
1074
1075			case IP_RECVTTL:
1076				optval = OPTBIT(INP_RECVTTL);
1077				break;
1078
1079			case IP_RECVIF:
1080				optval = OPTBIT(INP_RECVIF);
1081				break;
1082
1083			case IP_PORTRANGE:
1084				if (inp->inp_flags & INP_HIGHPORT)
1085					optval = IP_PORTRANGE_HIGH;
1086				else if (inp->inp_flags & INP_LOWPORT)
1087					optval = IP_PORTRANGE_LOW;
1088				else
1089					optval = 0;
1090				break;
1091
1092			case IP_FAITH:
1093				optval = OPTBIT(INP_FAITH);
1094				break;
1095
1096			case IP_ONESBCAST:
1097				optval = OPTBIT(INP_ONESBCAST);
1098				break;
1099			case IP_DONTFRAG:
1100				optval = OPTBIT(INP_DONTFRAG);
1101				break;
1102			}
1103			error = sooptcopyout(sopt, &optval, sizeof optval);
1104			break;
1105
1106		/*
1107		 * Multicast socket options are processed by the in_mcast
1108		 * module.
1109		 */
1110		case IP_MULTICAST_IF:
1111		case IP_MULTICAST_VIF:
1112		case IP_MULTICAST_TTL:
1113		case IP_MULTICAST_LOOP:
1114		case IP_MSFILTER:
1115			error = inp_getmoptions(inp, sopt);
1116			break;
1117
1118#ifdef IPSEC
1119		case IP_IPSEC_POLICY:
1120		{
1121			struct mbuf *m = NULL;
1122			caddr_t req = NULL;
1123			size_t len = 0;
1124
1125			if (m != 0) {
1126				req = mtod(m, caddr_t);
1127				len = m->m_len;
1128			}
1129			error = ipsec4_get_policy(sotoinpcb(so), req, len, &m);
1130			if (error == 0)
1131				error = soopt_mcopyout(sopt, m); /* XXX */
1132			if (error == 0)
1133				m_freem(m);
1134			break;
1135		}
1136#endif /* IPSEC */
1137
1138		default:
1139			error = ENOPROTOOPT;
1140			break;
1141		}
1142		break;
1143	}
1144	return (error);
1145}
1146
1147/*
1148 * Routine called from ip_output() to loop back a copy of an IP multicast
1149 * packet to the input queue of a specified interface.  Note that this
1150 * calls the output routine of the loopback "driver", but with an interface
1151 * pointer that might NOT be a loopback interface -- evil, but easier than
1152 * replicating that code here.
1153 */
1154static void
1155ip_mloopback(struct ifnet *ifp, struct mbuf *m, struct sockaddr_in *dst,
1156    int hlen)
1157{
1158	register struct ip *ip;
1159	struct mbuf *copym;
1160
1161	/*
1162	 * Make a deep copy of the packet because we're going to
1163	 * modify the pack in order to generate checksums.
1164	 */
1165	copym = m_dup(m, M_DONTWAIT);
1166	if (copym != NULL && (copym->m_flags & M_EXT || copym->m_len < hlen))
1167		copym = m_pullup(copym, hlen);
1168	if (copym != NULL) {
1169		/* If needed, compute the checksum and mark it as valid. */
1170		if (copym->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
1171			in_delayed_cksum(copym);
1172			copym->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
1173			copym->m_pkthdr.csum_flags |=
1174			    CSUM_DATA_VALID | CSUM_PSEUDO_HDR;
1175			copym->m_pkthdr.csum_data = 0xffff;
1176		}
1177		/*
1178		 * We don't bother to fragment if the IP length is greater
1179		 * than the interface's MTU.  Can this possibly matter?
1180		 */
1181		ip = mtod(copym, struct ip *);
1182		ip->ip_len = htons(ip->ip_len);
1183		ip->ip_off = htons(ip->ip_off);
1184		ip->ip_sum = 0;
1185		ip->ip_sum = in_cksum(copym, hlen);
1186#if 1 /* XXX */
1187		if (dst->sin_family != AF_INET) {
1188			printf("ip_mloopback: bad address family %d\n",
1189						dst->sin_family);
1190			dst->sin_family = AF_INET;
1191		}
1192#endif
1193		if_simloop(ifp, copym, dst->sin_family, 0);
1194	}
1195}
1196