ip_output.c revision 185348
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 185348 2008-11-26 22:32:07Z zec $");
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	INIT_VNET_INET(curvnet);
795	struct ip *ip;
796	u_short csum, offset;
797
798	ip = mtod(m, struct ip *);
799	offset = ip->ip_hl << 2 ;
800	csum = in_cksum_skip(m, ip->ip_len, offset);
801	if (m->m_pkthdr.csum_flags & CSUM_UDP && csum == 0)
802		csum = 0xffff;
803	offset += m->m_pkthdr.csum_data;	/* checksum offset */
804
805	if (offset + sizeof(u_short) > m->m_len) {
806		printf("delayed m_pullup, m->len: %d  off: %d  p: %d\n",
807		    m->m_len, offset, ip->ip_p);
808		/*
809		 * XXX
810		 * this shouldn't happen, but if it does, the
811		 * correct behavior may be to insert the checksum
812		 * in the appropriate next mbuf in the chain.
813		 */
814		return;
815	}
816	*(u_short *)(m->m_data + offset) = csum;
817}
818
819/*
820 * IP socket option processing.
821 */
822int
823ip_ctloutput(struct socket *so, struct sockopt *sopt)
824{
825	struct	inpcb *inp = sotoinpcb(so);
826	int	error, optval;
827
828	error = optval = 0;
829	if (sopt->sopt_level != IPPROTO_IP) {
830		if ((sopt->sopt_level == SOL_SOCKET) &&
831		    (sopt->sopt_name == SO_SETFIB)) {
832			inp->inp_inc.inc_fibnum = so->so_fibnum;
833			return (0);
834		}
835		return (EINVAL);
836	}
837
838	switch (sopt->sopt_dir) {
839	case SOPT_SET:
840		switch (sopt->sopt_name) {
841		case IP_OPTIONS:
842#ifdef notyet
843		case IP_RETOPTS:
844#endif
845		{
846			struct mbuf *m;
847			if (sopt->sopt_valsize > MLEN) {
848				error = EMSGSIZE;
849				break;
850			}
851			MGET(m, sopt->sopt_td ? M_WAIT : M_DONTWAIT, MT_DATA);
852			if (m == NULL) {
853				error = ENOBUFS;
854				break;
855			}
856			m->m_len = sopt->sopt_valsize;
857			error = sooptcopyin(sopt, mtod(m, char *), m->m_len,
858					    m->m_len);
859			if (error) {
860				m_free(m);
861				break;
862			}
863			INP_WLOCK(inp);
864			error = ip_pcbopts(inp, sopt->sopt_name, m);
865			INP_WUNLOCK(inp);
866			return (error);
867		}
868
869		case IP_TOS:
870		case IP_TTL:
871		case IP_MINTTL:
872		case IP_RECVOPTS:
873		case IP_RECVRETOPTS:
874		case IP_RECVDSTADDR:
875		case IP_RECVTTL:
876		case IP_RECVIF:
877		case IP_FAITH:
878		case IP_ONESBCAST:
879		case IP_DONTFRAG:
880			error = sooptcopyin(sopt, &optval, sizeof optval,
881					    sizeof optval);
882			if (error)
883				break;
884
885			switch (sopt->sopt_name) {
886			case IP_TOS:
887				inp->inp_ip_tos = optval;
888				break;
889
890			case IP_TTL:
891				inp->inp_ip_ttl = optval;
892				break;
893
894			case IP_MINTTL:
895				if (optval > 0 && optval <= MAXTTL)
896					inp->inp_ip_minttl = optval;
897				else
898					error = EINVAL;
899				break;
900
901#define	OPTSET(bit) do {						\
902	INP_WLOCK(inp);							\
903	if (optval)							\
904		inp->inp_flags |= bit;					\
905	else								\
906		inp->inp_flags &= ~bit;					\
907	INP_WUNLOCK(inp);						\
908} while (0)
909
910			case IP_RECVOPTS:
911				OPTSET(INP_RECVOPTS);
912				break;
913
914			case IP_RECVRETOPTS:
915				OPTSET(INP_RECVRETOPTS);
916				break;
917
918			case IP_RECVDSTADDR:
919				OPTSET(INP_RECVDSTADDR);
920				break;
921
922			case IP_RECVTTL:
923				OPTSET(INP_RECVTTL);
924				break;
925
926			case IP_RECVIF:
927				OPTSET(INP_RECVIF);
928				break;
929
930			case IP_FAITH:
931				OPTSET(INP_FAITH);
932				break;
933
934			case IP_ONESBCAST:
935				OPTSET(INP_ONESBCAST);
936				break;
937			case IP_DONTFRAG:
938				OPTSET(INP_DONTFRAG);
939				break;
940			}
941			break;
942#undef OPTSET
943
944		/*
945		 * Multicast socket options are processed by the in_mcast
946		 * module.
947		 */
948		case IP_MULTICAST_IF:
949		case IP_MULTICAST_VIF:
950		case IP_MULTICAST_TTL:
951		case IP_MULTICAST_LOOP:
952		case IP_ADD_MEMBERSHIP:
953		case IP_DROP_MEMBERSHIP:
954		case IP_ADD_SOURCE_MEMBERSHIP:
955		case IP_DROP_SOURCE_MEMBERSHIP:
956		case IP_BLOCK_SOURCE:
957		case IP_UNBLOCK_SOURCE:
958		case IP_MSFILTER:
959		case MCAST_JOIN_GROUP:
960		case MCAST_LEAVE_GROUP:
961		case MCAST_JOIN_SOURCE_GROUP:
962		case MCAST_LEAVE_SOURCE_GROUP:
963		case MCAST_BLOCK_SOURCE:
964		case MCAST_UNBLOCK_SOURCE:
965			error = inp_setmoptions(inp, sopt);
966			break;
967
968		case IP_PORTRANGE:
969			error = sooptcopyin(sopt, &optval, sizeof optval,
970					    sizeof optval);
971			if (error)
972				break;
973
974			INP_WLOCK(inp);
975			switch (optval) {
976			case IP_PORTRANGE_DEFAULT:
977				inp->inp_flags &= ~(INP_LOWPORT);
978				inp->inp_flags &= ~(INP_HIGHPORT);
979				break;
980
981			case IP_PORTRANGE_HIGH:
982				inp->inp_flags &= ~(INP_LOWPORT);
983				inp->inp_flags |= INP_HIGHPORT;
984				break;
985
986			case IP_PORTRANGE_LOW:
987				inp->inp_flags &= ~(INP_HIGHPORT);
988				inp->inp_flags |= INP_LOWPORT;
989				break;
990
991			default:
992				error = EINVAL;
993				break;
994			}
995			INP_WUNLOCK(inp);
996			break;
997
998#ifdef IPSEC
999		case IP_IPSEC_POLICY:
1000		{
1001			caddr_t req;
1002			struct mbuf *m;
1003
1004			if ((error = soopt_getm(sopt, &m)) != 0) /* XXX */
1005				break;
1006			if ((error = soopt_mcopyin(sopt, m)) != 0) /* XXX */
1007				break;
1008			req = mtod(m, caddr_t);
1009			error = ipsec4_set_policy(inp, sopt->sopt_name, req,
1010			    m->m_len, (sopt->sopt_td != NULL) ?
1011			    sopt->sopt_td->td_ucred : NULL);
1012			m_freem(m);
1013			break;
1014		}
1015#endif /* IPSEC */
1016
1017		default:
1018			error = ENOPROTOOPT;
1019			break;
1020		}
1021		break;
1022
1023	case SOPT_GET:
1024		switch (sopt->sopt_name) {
1025		case IP_OPTIONS:
1026		case IP_RETOPTS:
1027			if (inp->inp_options)
1028				error = sooptcopyout(sopt,
1029						     mtod(inp->inp_options,
1030							  char *),
1031						     inp->inp_options->m_len);
1032			else
1033				sopt->sopt_valsize = 0;
1034			break;
1035
1036		case IP_TOS:
1037		case IP_TTL:
1038		case IP_MINTTL:
1039		case IP_RECVOPTS:
1040		case IP_RECVRETOPTS:
1041		case IP_RECVDSTADDR:
1042		case IP_RECVTTL:
1043		case IP_RECVIF:
1044		case IP_PORTRANGE:
1045		case IP_FAITH:
1046		case IP_ONESBCAST:
1047		case IP_DONTFRAG:
1048			switch (sopt->sopt_name) {
1049
1050			case IP_TOS:
1051				optval = inp->inp_ip_tos;
1052				break;
1053
1054			case IP_TTL:
1055				optval = inp->inp_ip_ttl;
1056				break;
1057
1058			case IP_MINTTL:
1059				optval = inp->inp_ip_minttl;
1060				break;
1061
1062#define	OPTBIT(bit)	(inp->inp_flags & bit ? 1 : 0)
1063
1064			case IP_RECVOPTS:
1065				optval = OPTBIT(INP_RECVOPTS);
1066				break;
1067
1068			case IP_RECVRETOPTS:
1069				optval = OPTBIT(INP_RECVRETOPTS);
1070				break;
1071
1072			case IP_RECVDSTADDR:
1073				optval = OPTBIT(INP_RECVDSTADDR);
1074				break;
1075
1076			case IP_RECVTTL:
1077				optval = OPTBIT(INP_RECVTTL);
1078				break;
1079
1080			case IP_RECVIF:
1081				optval = OPTBIT(INP_RECVIF);
1082				break;
1083
1084			case IP_PORTRANGE:
1085				if (inp->inp_flags & INP_HIGHPORT)
1086					optval = IP_PORTRANGE_HIGH;
1087				else if (inp->inp_flags & INP_LOWPORT)
1088					optval = IP_PORTRANGE_LOW;
1089				else
1090					optval = 0;
1091				break;
1092
1093			case IP_FAITH:
1094				optval = OPTBIT(INP_FAITH);
1095				break;
1096
1097			case IP_ONESBCAST:
1098				optval = OPTBIT(INP_ONESBCAST);
1099				break;
1100			case IP_DONTFRAG:
1101				optval = OPTBIT(INP_DONTFRAG);
1102				break;
1103			}
1104			error = sooptcopyout(sopt, &optval, sizeof optval);
1105			break;
1106
1107		/*
1108		 * Multicast socket options are processed by the in_mcast
1109		 * module.
1110		 */
1111		case IP_MULTICAST_IF:
1112		case IP_MULTICAST_VIF:
1113		case IP_MULTICAST_TTL:
1114		case IP_MULTICAST_LOOP:
1115		case IP_MSFILTER:
1116			error = inp_getmoptions(inp, sopt);
1117			break;
1118
1119#ifdef IPSEC
1120		case IP_IPSEC_POLICY:
1121		{
1122			struct mbuf *m = NULL;
1123			caddr_t req = NULL;
1124			size_t len = 0;
1125
1126			if (m != 0) {
1127				req = mtod(m, caddr_t);
1128				len = m->m_len;
1129			}
1130			error = ipsec4_get_policy(sotoinpcb(so), req, len, &m);
1131			if (error == 0)
1132				error = soopt_mcopyout(sopt, m); /* XXX */
1133			if (error == 0)
1134				m_freem(m);
1135			break;
1136		}
1137#endif /* IPSEC */
1138
1139		default:
1140			error = ENOPROTOOPT;
1141			break;
1142		}
1143		break;
1144	}
1145	return (error);
1146}
1147
1148/*
1149 * Routine called from ip_output() to loop back a copy of an IP multicast
1150 * packet to the input queue of a specified interface.  Note that this
1151 * calls the output routine of the loopback "driver", but with an interface
1152 * pointer that might NOT be a loopback interface -- evil, but easier than
1153 * replicating that code here.
1154 */
1155static void
1156ip_mloopback(struct ifnet *ifp, struct mbuf *m, struct sockaddr_in *dst,
1157    int hlen)
1158{
1159	register struct ip *ip;
1160	struct mbuf *copym;
1161
1162	/*
1163	 * Make a deep copy of the packet because we're going to
1164	 * modify the pack in order to generate checksums.
1165	 */
1166	copym = m_dup(m, M_DONTWAIT);
1167	if (copym != NULL && (copym->m_flags & M_EXT || copym->m_len < hlen))
1168		copym = m_pullup(copym, hlen);
1169	if (copym != NULL) {
1170		/* If needed, compute the checksum and mark it as valid. */
1171		if (copym->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
1172			in_delayed_cksum(copym);
1173			copym->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
1174			copym->m_pkthdr.csum_flags |=
1175			    CSUM_DATA_VALID | CSUM_PSEUDO_HDR;
1176			copym->m_pkthdr.csum_data = 0xffff;
1177		}
1178		/*
1179		 * We don't bother to fragment if the IP length is greater
1180		 * than the interface's MTU.  Can this possibly matter?
1181		 */
1182		ip = mtod(copym, struct ip *);
1183		ip->ip_len = htons(ip->ip_len);
1184		ip->ip_off = htons(ip->ip_off);
1185		ip->ip_sum = 0;
1186		ip->ip_sum = in_cksum(copym, hlen);
1187#if 1 /* XXX */
1188		if (dst->sin_family != AF_INET) {
1189			printf("ip_mloopback: bad address family %d\n",
1190						dst->sin_family);
1191			dst->sin_family = AF_INET;
1192		}
1193#endif
1194		if_simloop(ifp, copym, dst->sin_family, 0);
1195	}
1196}
1197