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