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