xref: /dflybsd-src/sys/netinet/ip_output.c (revision 895c1f850848cf50a3243e134345f0d4ff33ac59)
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  * 3. 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  * $FreeBSD: src/sys/netinet/ip_output.c,v 1.99.2.37 2003/04/15 06:44:45 silby Exp $
31  * $DragonFly: src/sys/netinet/ip_output.c,v 1.67 2008/10/28 03:07:28 sephe Exp $
32  */
33 
34 #define _IP_VHL
35 
36 #include "opt_ipfw.h"
37 #include "opt_ipdn.h"
38 #include "opt_ipdivert.h"
39 #include "opt_ipfilter.h"
40 #include "opt_ipsec.h"
41 #include "opt_mbuf_stress_test.h"
42 #include "opt_mpls.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/protosw.h>
50 #include <sys/socket.h>
51 #include <sys/socketvar.h>
52 #include <sys/proc.h>
53 #include <sys/priv.h>
54 #include <sys/sysctl.h>
55 #include <sys/thread2.h>
56 #include <sys/in_cksum.h>
57 #include <sys/lock.h>
58 
59 #include <net/if.h>
60 #include <net/netisr.h>
61 #include <net/pfil.h>
62 #include <net/route.h>
63 
64 #include <netinet/in.h>
65 #include <netinet/in_systm.h>
66 #include <netinet/ip.h>
67 #include <netinet/in_pcb.h>
68 #include <netinet/in_var.h>
69 #include <netinet/ip_var.h>
70 
71 #include <netproto/mpls/mpls_var.h>
72 
73 static MALLOC_DEFINE(M_IPMOPTS, "ip_moptions", "internet multicast options");
74 
75 #ifdef IPSEC
76 #include <netinet6/ipsec.h>
77 #include <netproto/key/key.h>
78 #ifdef IPSEC_DEBUG
79 #include <netproto/key/key_debug.h>
80 #else
81 #define	KEYDEBUG(lev,arg)
82 #endif
83 #endif /*IPSEC*/
84 
85 #ifdef FAST_IPSEC
86 #include <netproto/ipsec/ipsec.h>
87 #include <netproto/ipsec/xform.h>
88 #include <netproto/ipsec/key.h>
89 #endif /*FAST_IPSEC*/
90 
91 #include <net/ipfw/ip_fw.h>
92 #include <net/dummynet/ip_dummynet.h>
93 
94 #define print_ip(x, a, y)	 kprintf("%s %d.%d.%d.%d%s",\
95 				x, (ntohl(a.s_addr)>>24)&0xFF,\
96 				  (ntohl(a.s_addr)>>16)&0xFF,\
97 				  (ntohl(a.s_addr)>>8)&0xFF,\
98 				  (ntohl(a.s_addr))&0xFF, y);
99 
100 u_short ip_id;
101 
102 #ifdef MBUF_STRESS_TEST
103 int mbuf_frag_size = 0;
104 SYSCTL_INT(_net_inet_ip, OID_AUTO, mbuf_frag_size, CTLFLAG_RW,
105 	&mbuf_frag_size, 0, "Fragment outgoing mbufs to this size");
106 #endif
107 
108 static struct mbuf *ip_insertoptions(struct mbuf *, struct mbuf *, int *);
109 static struct ifnet *ip_multicast_if(struct in_addr *, int *);
110 static void	ip_mloopback
111 	(struct ifnet *, struct mbuf *, struct sockaddr_in *, int);
112 static int	ip_getmoptions
113 	(struct sockopt *, struct ip_moptions *);
114 static int	ip_pcbopts(int, struct mbuf **, struct mbuf *);
115 static int	ip_setmoptions
116 	(struct sockopt *, struct ip_moptions **);
117 
118 int	ip_optcopy(struct ip *, struct ip *);
119 
120 extern	int route_assert_owner_access;
121 extern	void db_print_backtrace(void);
122 
123 extern	struct protosw inetsw[];
124 
125 static int
126 ip_localforward(struct mbuf *m, const struct sockaddr_in *dst, int hlen)
127 {
128 	struct in_ifaddr_container *iac;
129 
130 	/*
131 	 * We need to figure out if we have been forwarded to a local
132 	 * socket.  If so, then we should somehow "loop back" to
133 	 * ip_input(), and get directed to the PCB as if we had received
134 	 * this packet.  This is because it may be difficult to identify
135 	 * the packets you want to forward until they are being output
136 	 * and have selected an interface (e.g. locally initiated
137 	 * packets).  If we used the loopback inteface, we would not be
138 	 * able to control what happens as the packet runs through
139 	 * ip_input() as it is done through a ISR.
140 	 */
141 	LIST_FOREACH(iac, INADDR_HASH(dst->sin_addr.s_addr), ia_hash) {
142 		/*
143 		 * If the addr to forward to is one of ours, we pretend
144 		 * to be the destination for this packet.
145 		 */
146 		if (IA_SIN(iac->ia)->sin_addr.s_addr == dst->sin_addr.s_addr)
147 			break;
148 	}
149 	if (iac != NULL) {
150 		struct ip *ip;
151 
152 		if (m->m_pkthdr.rcvif == NULL)
153 			m->m_pkthdr.rcvif = ifunit("lo0");
154 		if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
155 			m->m_pkthdr.csum_flags |= CSUM_DATA_VALID |
156 						  CSUM_PSEUDO_HDR;
157 			m->m_pkthdr.csum_data = 0xffff;
158 		}
159 		m->m_pkthdr.csum_flags |= CSUM_IP_CHECKED | CSUM_IP_VALID;
160 
161 		/*
162 		 * Make sure that the IP header is in one mbuf,
163 		 * required by ip_input
164 		 */
165 		if (m->m_len < hlen) {
166 			m = m_pullup(m, hlen);
167 			if (m == NULL) {
168 				/* The packet was freed; we are done */
169 				return 1;
170 			}
171 		}
172 		ip = mtod(m, struct ip *);
173 
174 		ip->ip_len = htons(ip->ip_len);
175 		ip->ip_off = htons(ip->ip_off);
176 		ip_input(m);
177 
178 		return 1; /* The packet gets forwarded locally */
179 	}
180 	return 0;
181 }
182 
183 /*
184  * IP output.  The packet in mbuf chain m contains a skeletal IP
185  * header (with len, off, ttl, proto, tos, src, dst).
186  * The mbuf chain containing the packet will be freed.
187  * The mbuf opt, if present, will not be freed.
188  */
189 int
190 ip_output(struct mbuf *m0, struct mbuf *opt, struct route *ro,
191 	  int flags, struct ip_moptions *imo, struct inpcb *inp)
192 {
193 	struct ip *ip;
194 	struct ifnet *ifp = NULL;	/* keep compiler happy */
195 	struct mbuf *m;
196 	int hlen = sizeof(struct ip);
197 	int len, error = 0;
198 	struct sockaddr_in *dst = NULL;	/* keep compiler happy */
199 	struct in_ifaddr *ia = NULL;
200 	int isbroadcast, sw_csum;
201 	struct in_addr pkt_dst;
202 	struct route iproute;
203 	struct m_tag *mtag;
204 #ifdef IPSEC
205 	struct secpolicy *sp = NULL;
206 	struct socket *so = inp ? inp->inp_socket : NULL;
207 #endif
208 #ifdef FAST_IPSEC
209 	struct secpolicy *sp = NULL;
210 	struct tdb_ident *tdbi;
211 #endif /* FAST_IPSEC */
212 	struct sockaddr_in *next_hop = NULL;
213 	int src_was_INADDR_ANY = 0;	/* as the name says... */
214 
215 	m = m0;
216 	M_ASSERTPKTHDR(m);
217 
218 	if (ro == NULL) {
219 		ro = &iproute;
220 		bzero(ro, sizeof *ro);
221 	} else if (ro->ro_rt != NULL && ro->ro_rt->rt_cpuid != mycpuid) {
222 		if (flags & IP_DEBUGROUTE) {
223 			if (route_assert_owner_access) {
224 				panic("ip_output: "
225 				      "rt rt_cpuid %d accessed on cpu %d\n",
226 				      ro->ro_rt->rt_cpuid, mycpuid);
227 			} else {
228 				kprintf("ip_output: "
229 					"rt rt_cpuid %d accessed on cpu %d\n",
230 					ro->ro_rt->rt_cpuid, mycpuid);
231 				db_print_backtrace();
232 			}
233 		}
234 
235 		/*
236 		 * XXX
237 		 * If the cached rtentry's owner CPU is not the current CPU,
238 		 * then don't touch the cached rtentry (remote free is too
239 		 * expensive in this context); just relocate the route.
240 		 */
241 		ro = &iproute;
242 		bzero(ro, sizeof *ro);
243 	}
244 
245 	if (m->m_pkthdr.fw_flags & IPFORWARD_MBUF_TAGGED) {
246 		/* Next hop */
247 		mtag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL);
248 		KKASSERT(mtag != NULL);
249 		next_hop = m_tag_data(mtag);
250 	}
251 
252 	if (m->m_pkthdr.fw_flags & DUMMYNET_MBUF_TAGGED) {
253 		struct dn_pkt *dn_pkt;
254 
255 		/* Extract info from dummynet tag */
256 		mtag = m_tag_find(m, PACKET_TAG_DUMMYNET, NULL);
257 		KKASSERT(mtag != NULL);
258 		dn_pkt = m_tag_data(mtag);
259 
260 		/*
261 		 * The packet was already tagged, so part of the
262 		 * processing was already done, and we need to go down.
263 		 * Get the calculated parameters from the tag.
264 		 */
265 		ifp = dn_pkt->ifp;
266 
267 		KKASSERT(ro == &iproute);
268 		*ro = dn_pkt->ro; /* structure copy */
269 		KKASSERT(ro->ro_rt == NULL || ro->ro_rt->rt_cpuid == mycpuid);
270 
271 		dst = dn_pkt->dn_dst;
272 		if (dst == (struct sockaddr_in *)&(dn_pkt->ro.ro_dst)) {
273 			/* If 'dst' points into dummynet tag, adjust it */
274 			dst = (struct sockaddr_in *)&(ro->ro_dst);
275 		}
276 
277 		ip = mtod(m, struct ip *);
278 		hlen = IP_VHL_HL(ip->ip_vhl) << 2 ;
279 		if (ro->ro_rt)
280 			ia = ifatoia(ro->ro_rt->rt_ifa);
281 		goto sendit;
282 	}
283 
284 	if (opt) {
285 		len = 0;
286 		m = ip_insertoptions(m, opt, &len);
287 		if (len != 0)
288 			hlen = len;
289 	}
290 	ip = mtod(m, struct ip *);
291 
292 	/*
293 	 * Fill in IP header.
294 	 */
295 	if (!(flags & (IP_FORWARDING|IP_RAWOUTPUT))) {
296 		ip->ip_vhl = IP_MAKE_VHL(IPVERSION, hlen >> 2);
297 		ip->ip_off &= IP_DF;
298 		ip->ip_id = ip_newid();
299 		ipstat.ips_localout++;
300 	} else {
301 		hlen = IP_VHL_HL(ip->ip_vhl) << 2;
302 	}
303 
304 reroute:
305 	pkt_dst = next_hop ? next_hop->sin_addr : ip->ip_dst;
306 
307 #ifdef INVARIANTS
308 	if (IN_MULTICAST(ntohl(pkt_dst.s_addr))) {
309 		/*
310 		 * XXX
311 		 * Multicast is not MPSAFE yet.  Caller must hold
312 		 * BGL when output a multicast IP packet.
313 		 */
314 		ASSERT_MP_LOCK_HELD(curthread);
315 	}
316 #endif
317 
318 	dst = (struct sockaddr_in *)&ro->ro_dst;
319 	/*
320 	 * If there is a cached route,
321 	 * check that it is to the same destination
322 	 * and is still up.  If not, free it and try again.
323 	 * The address family should also be checked in case of sharing the
324 	 * cache with IPv6.
325 	 */
326 	if (ro->ro_rt &&
327 	    (!(ro->ro_rt->rt_flags & RTF_UP) ||
328 	     dst->sin_family != AF_INET ||
329 	     dst->sin_addr.s_addr != pkt_dst.s_addr)) {
330 		rtfree(ro->ro_rt);
331 		ro->ro_rt = (struct rtentry *)NULL;
332 	}
333 	if (ro->ro_rt == NULL) {
334 		bzero(dst, sizeof *dst);
335 		dst->sin_family = AF_INET;
336 		dst->sin_len = sizeof *dst;
337 		dst->sin_addr = pkt_dst;
338 	}
339 	/*
340 	 * If routing to interface only,
341 	 * short circuit routing lookup.
342 	 */
343 	if (flags & IP_ROUTETOIF) {
344 		if ((ia = ifatoia(ifa_ifwithdstaddr(sintosa(dst)))) == NULL &&
345 		    (ia = ifatoia(ifa_ifwithnet(sintosa(dst)))) == NULL) {
346 			ipstat.ips_noroute++;
347 			error = ENETUNREACH;
348 			goto bad;
349 		}
350 		ifp = ia->ia_ifp;
351 		ip->ip_ttl = 1;
352 		isbroadcast = in_broadcast(dst->sin_addr, ifp);
353 	} else if (IN_MULTICAST(ntohl(pkt_dst.s_addr)) &&
354 		   imo != NULL && imo->imo_multicast_ifp != NULL) {
355 		/*
356 		 * Bypass the normal routing lookup for multicast
357 		 * packets if the interface is specified.
358 		 */
359 		ifp = imo->imo_multicast_ifp;
360 		ia = IFP_TO_IA(ifp);
361 		isbroadcast = 0;	/* fool gcc */
362 	} else {
363 		/*
364 		 * If this is the case, we probably don't want to allocate
365 		 * a protocol-cloned route since we didn't get one from the
366 		 * ULP.  This lets TCP do its thing, while not burdening
367 		 * forwarding or ICMP with the overhead of cloning a route.
368 		 * Of course, we still want to do any cloning requested by
369 		 * the link layer, as this is probably required in all cases
370 		 * for correct operation (as it is for ARP).
371 		 */
372 		if (ro->ro_rt == NULL)
373 			rtalloc_ign(ro, RTF_PRCLONING);
374 		if (ro->ro_rt == NULL) {
375 			ipstat.ips_noroute++;
376 			error = EHOSTUNREACH;
377 			goto bad;
378 		}
379 		ia = ifatoia(ro->ro_rt->rt_ifa);
380 		ifp = ro->ro_rt->rt_ifp;
381 		ro->ro_rt->rt_use++;
382 		if (ro->ro_rt->rt_flags & RTF_GATEWAY)
383 			dst = (struct sockaddr_in *)ro->ro_rt->rt_gateway;
384 		if (ro->ro_rt->rt_flags & RTF_HOST)
385 			isbroadcast = (ro->ro_rt->rt_flags & RTF_BROADCAST);
386 		else
387 			isbroadcast = in_broadcast(dst->sin_addr, ifp);
388 	}
389 	if (IN_MULTICAST(ntohl(pkt_dst.s_addr))) {
390 		struct in_multi *inm;
391 
392 		m->m_flags |= M_MCAST;
393 		/*
394 		 * IP destination address is multicast.  Make sure "dst"
395 		 * still points to the address in "ro".  (It may have been
396 		 * changed to point to a gateway address, above.)
397 		 */
398 		dst = (struct sockaddr_in *)&ro->ro_dst;
399 		/*
400 		 * See if the caller provided any multicast options
401 		 */
402 		if (imo != NULL) {
403 			ip->ip_ttl = imo->imo_multicast_ttl;
404 			if (imo->imo_multicast_vif != -1) {
405 				ip->ip_src.s_addr =
406 				    ip_mcast_src ?
407 				    ip_mcast_src(imo->imo_multicast_vif) :
408 				    INADDR_ANY;
409 			}
410 		} else {
411 			ip->ip_ttl = IP_DEFAULT_MULTICAST_TTL;
412 		}
413 		/*
414 		 * Confirm that the outgoing interface supports multicast.
415 		 */
416 		if ((imo == NULL) || (imo->imo_multicast_vif == -1)) {
417 			if (!(ifp->if_flags & IFF_MULTICAST)) {
418 				ipstat.ips_noroute++;
419 				error = ENETUNREACH;
420 				goto bad;
421 			}
422 		}
423 		/*
424 		 * If source address not specified yet, use address
425 		 * of outgoing interface.
426 		 */
427 		if (ip->ip_src.s_addr == INADDR_ANY) {
428 			/* Interface may have no addresses. */
429 			if (ia != NULL)
430 				ip->ip_src = IA_SIN(ia)->sin_addr;
431 		}
432 
433 		IN_LOOKUP_MULTI(pkt_dst, ifp, inm);
434 		if (inm != NULL &&
435 		    (imo == NULL || imo->imo_multicast_loop)) {
436 			/*
437 			 * If we belong to the destination multicast group
438 			 * on the outgoing interface, and the caller did not
439 			 * forbid loopback, loop back a copy.
440 			 */
441 			ip_mloopback(ifp, m, dst, hlen);
442 		} else {
443 			/*
444 			 * If we are acting as a multicast router, perform
445 			 * multicast forwarding as if the packet had just
446 			 * arrived on the interface to which we are about
447 			 * to send.  The multicast forwarding function
448 			 * recursively calls this function, using the
449 			 * IP_FORWARDING flag to prevent infinite recursion.
450 			 *
451 			 * Multicasts that are looped back by ip_mloopback(),
452 			 * above, will be forwarded by the ip_input() routine,
453 			 * if necessary.
454 			 */
455 			if (ip_mrouter && !(flags & IP_FORWARDING)) {
456 				/*
457 				 * If rsvp daemon is not running, do not
458 				 * set ip_moptions. This ensures that the packet
459 				 * is multicast and not just sent down one link
460 				 * as prescribed by rsvpd.
461 				 */
462 				if (!rsvp_on)
463 					imo = NULL;
464 				if (ip_mforward &&
465 				    ip_mforward(ip, ifp, m, imo) != 0) {
466 					m_freem(m);
467 					goto done;
468 				}
469 			}
470 		}
471 
472 		/*
473 		 * Multicasts with a time-to-live of zero may be looped-
474 		 * back, above, but must not be transmitted on a network.
475 		 * Also, multicasts addressed to the loopback interface
476 		 * are not sent -- the above call to ip_mloopback() will
477 		 * loop back a copy if this host actually belongs to the
478 		 * destination group on the loopback interface.
479 		 */
480 		if (ip->ip_ttl == 0 || ifp->if_flags & IFF_LOOPBACK) {
481 			m_freem(m);
482 			goto done;
483 		}
484 
485 		goto sendit;
486 	} else {
487 		m->m_flags &= ~M_MCAST;
488 	}
489 
490 	/*
491 	 * If the source address is not specified yet, use the address
492 	 * of the outoing interface. In case, keep note we did that, so
493 	 * if the the firewall changes the next-hop causing the output
494 	 * interface to change, we can fix that.
495 	 */
496 	if (ip->ip_src.s_addr == INADDR_ANY || src_was_INADDR_ANY) {
497 		/* Interface may have no addresses. */
498 		if (ia != NULL) {
499 			ip->ip_src = IA_SIN(ia)->sin_addr;
500 			src_was_INADDR_ANY = 1;
501 		}
502 	}
503 
504 #ifdef ALTQ
505 	/*
506 	 * Disable packet drop hack.
507 	 * Packetdrop should be done by queueing.
508 	 */
509 #else /* !ALTQ */
510 	/*
511 	 * Verify that we have any chance at all of being able to queue
512 	 *      the packet or packet fragments
513 	 */
514 	if ((ifp->if_snd.ifq_len + ip->ip_len / ifp->if_mtu + 1) >=
515 	    ifp->if_snd.ifq_maxlen) {
516 		error = ENOBUFS;
517 		ipstat.ips_odropped++;
518 		goto bad;
519 	}
520 #endif /* !ALTQ */
521 
522 	/*
523 	 * Look for broadcast address and
524 	 * verify user is allowed to send
525 	 * such a packet.
526 	 */
527 	if (isbroadcast) {
528 		if (!(ifp->if_flags & IFF_BROADCAST)) {
529 			error = EADDRNOTAVAIL;
530 			goto bad;
531 		}
532 		if (!(flags & IP_ALLOWBROADCAST)) {
533 			error = EACCES;
534 			goto bad;
535 		}
536 		/* don't allow broadcast messages to be fragmented */
537 		if (ip->ip_len > ifp->if_mtu) {
538 			error = EMSGSIZE;
539 			goto bad;
540 		}
541 		m->m_flags |= M_BCAST;
542 	} else {
543 		m->m_flags &= ~M_BCAST;
544 	}
545 
546 sendit:
547 #ifdef IPSEC
548 	/* get SP for this packet */
549 	if (so == NULL)
550 		sp = ipsec4_getpolicybyaddr(m, IPSEC_DIR_OUTBOUND, flags, &error);
551 	else
552 		sp = ipsec4_getpolicybysock(m, IPSEC_DIR_OUTBOUND, so, &error);
553 
554 	if (sp == NULL) {
555 		ipsecstat.out_inval++;
556 		goto bad;
557 	}
558 
559 	error = 0;
560 
561 	/* check policy */
562 	switch (sp->policy) {
563 	case IPSEC_POLICY_DISCARD:
564 		/*
565 		 * This packet is just discarded.
566 		 */
567 		ipsecstat.out_polvio++;
568 		goto bad;
569 
570 	case IPSEC_POLICY_BYPASS:
571 	case IPSEC_POLICY_NONE:
572 		/* no need to do IPsec. */
573 		goto skip_ipsec;
574 
575 	case IPSEC_POLICY_IPSEC:
576 		if (sp->req == NULL) {
577 			/* acquire a policy */
578 			error = key_spdacquire(sp);
579 			goto bad;
580 		}
581 		break;
582 
583 	case IPSEC_POLICY_ENTRUST:
584 	default:
585 		kprintf("ip_output: Invalid policy found. %d\n", sp->policy);
586 	}
587     {
588 	struct ipsec_output_state state;
589 	bzero(&state, sizeof state);
590 	state.m = m;
591 	if (flags & IP_ROUTETOIF) {
592 		state.ro = &iproute;
593 		bzero(&iproute, sizeof iproute);
594 	} else
595 		state.ro = ro;
596 	state.dst = (struct sockaddr *)dst;
597 
598 	ip->ip_sum = 0;
599 
600 	/*
601 	 * XXX
602 	 * delayed checksums are not currently compatible with IPsec
603 	 */
604 	if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
605 		in_delayed_cksum(m);
606 		m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
607 	}
608 
609 	ip->ip_len = htons(ip->ip_len);
610 	ip->ip_off = htons(ip->ip_off);
611 
612 	error = ipsec4_output(&state, sp, flags);
613 
614 	m = state.m;
615 	if (flags & IP_ROUTETOIF) {
616 		/*
617 		 * if we have tunnel mode SA, we may need to ignore
618 		 * IP_ROUTETOIF.
619 		 */
620 		if (state.ro != &iproute || state.ro->ro_rt != NULL) {
621 			flags &= ~IP_ROUTETOIF;
622 			ro = state.ro;
623 		}
624 	} else
625 		ro = state.ro;
626 	dst = (struct sockaddr_in *)state.dst;
627 	if (error) {
628 		/* mbuf is already reclaimed in ipsec4_output. */
629 		m0 = NULL;
630 		switch (error) {
631 		case EHOSTUNREACH:
632 		case ENETUNREACH:
633 		case EMSGSIZE:
634 		case ENOBUFS:
635 		case ENOMEM:
636 			break;
637 		default:
638 			kprintf("ip4_output (ipsec): error code %d\n", error);
639 			/*fall through*/
640 		case ENOENT:
641 			/* don't show these error codes to the user */
642 			error = 0;
643 			break;
644 		}
645 		goto bad;
646 	}
647     }
648 
649 	/* be sure to update variables that are affected by ipsec4_output() */
650 	ip = mtod(m, struct ip *);
651 #ifdef _IP_VHL
652 	hlen = IP_VHL_HL(ip->ip_vhl) << 2;
653 #else
654 	hlen = ip->ip_hl << 2;
655 #endif
656 	if (ro->ro_rt == NULL) {
657 		if (!(flags & IP_ROUTETOIF)) {
658 			kprintf("ip_output: "
659 				"can't update route after IPsec processing\n");
660 			error = EHOSTUNREACH;	/*XXX*/
661 			goto bad;
662 		}
663 	} else {
664 		ia = ifatoia(ro->ro_rt->rt_ifa);
665 		ifp = ro->ro_rt->rt_ifp;
666 	}
667 
668 	/* make it flipped, again. */
669 	ip->ip_len = ntohs(ip->ip_len);
670 	ip->ip_off = ntohs(ip->ip_off);
671 skip_ipsec:
672 #endif /*IPSEC*/
673 #ifdef FAST_IPSEC
674 	/*
675 	 * Check the security policy (SP) for the packet and, if
676 	 * required, do IPsec-related processing.  There are two
677 	 * cases here; the first time a packet is sent through
678 	 * it will be untagged and handled by ipsec4_checkpolicy.
679 	 * If the packet is resubmitted to ip_output (e.g. after
680 	 * AH, ESP, etc. processing), there will be a tag to bypass
681 	 * the lookup and related policy checking.
682 	 */
683 	mtag = m_tag_find(m, PACKET_TAG_IPSEC_PENDING_TDB, NULL);
684 	crit_enter();
685 	if (mtag != NULL) {
686 		tdbi = (struct tdb_ident *)m_tag_data(mtag);
687 		sp = ipsec_getpolicy(tdbi, IPSEC_DIR_OUTBOUND);
688 		if (sp == NULL)
689 			error = -EINVAL;	/* force silent drop */
690 		m_tag_delete(m, mtag);
691 	} else {
692 		sp = ipsec4_checkpolicy(m, IPSEC_DIR_OUTBOUND, flags,
693 					&error, inp);
694 	}
695 	/*
696 	 * There are four return cases:
697 	 *    sp != NULL		    apply IPsec policy
698 	 *    sp == NULL, error == 0	    no IPsec handling needed
699 	 *    sp == NULL, error == -EINVAL  discard packet w/o error
700 	 *    sp == NULL, error != 0	    discard packet, report error
701 	 */
702 	if (sp != NULL) {
703 		/* Loop detection, check if ipsec processing already done */
704 		KASSERT(sp->req != NULL, ("ip_output: no ipsec request"));
705 		for (mtag = m_tag_first(m); mtag != NULL;
706 		     mtag = m_tag_next(m, mtag)) {
707 			if (mtag->m_tag_cookie != MTAG_ABI_COMPAT)
708 				continue;
709 			if (mtag->m_tag_id != PACKET_TAG_IPSEC_OUT_DONE &&
710 			    mtag->m_tag_id != PACKET_TAG_IPSEC_OUT_CRYPTO_NEEDED)
711 				continue;
712 			/*
713 			 * Check if policy has an SA associated with it.
714 			 * This can happen when an SP has yet to acquire
715 			 * an SA; e.g. on first reference.  If it occurs,
716 			 * then we let ipsec4_process_packet do its thing.
717 			 */
718 			if (sp->req->sav == NULL)
719 				break;
720 			tdbi = (struct tdb_ident *)m_tag_data(mtag);
721 			if (tdbi->spi == sp->req->sav->spi &&
722 			    tdbi->proto == sp->req->sav->sah->saidx.proto &&
723 			    bcmp(&tdbi->dst, &sp->req->sav->sah->saidx.dst,
724 				 sizeof(union sockaddr_union)) == 0) {
725 				/*
726 				 * No IPsec processing is needed, free
727 				 * reference to SP.
728 				 *
729 				 * NB: null pointer to avoid free at
730 				 *     done: below.
731 				 */
732 				KEY_FREESP(&sp), sp = NULL;
733 				crit_exit();
734 				goto spd_done;
735 			}
736 		}
737 
738 		/*
739 		 * Do delayed checksums now because we send before
740 		 * this is done in the normal processing path.
741 		 */
742 		if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
743 			in_delayed_cksum(m);
744 			m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
745 		}
746 
747 		ip->ip_len = htons(ip->ip_len);
748 		ip->ip_off = htons(ip->ip_off);
749 
750 		/* NB: callee frees mbuf */
751 		error = ipsec4_process_packet(m, sp->req, flags, 0);
752 		/*
753 		 * Preserve KAME behaviour: ENOENT can be returned
754 		 * when an SA acquire is in progress.  Don't propagate
755 		 * this to user-level; it confuses applications.
756 		 *
757 		 * XXX this will go away when the SADB is redone.
758 		 */
759 		if (error == ENOENT)
760 			error = 0;
761 		crit_exit();
762 		goto done;
763 	} else {
764 		crit_exit();
765 
766 		if (error != 0) {
767 			/*
768 			 * Hack: -EINVAL is used to signal that a packet
769 			 * should be silently discarded.  This is typically
770 			 * because we asked key management for an SA and
771 			 * it was delayed (e.g. kicked up to IKE).
772 			 */
773 			if (error == -EINVAL)
774 				error = 0;
775 			goto bad;
776 		} else {
777 			/* No IPsec processing for this packet. */
778 		}
779 #ifdef notyet
780 		/*
781 		 * If deferred crypto processing is needed, check that
782 		 * the interface supports it.
783 		 */
784 		mtag = m_tag_find(m, PACKET_TAG_IPSEC_OUT_CRYPTO_NEEDED, NULL);
785 		if (mtag != NULL && !(ifp->if_capenable & IFCAP_IPSEC)) {
786 			/* notify IPsec to do its own crypto */
787 			ipsp_skipcrypto_unmark((struct tdb_ident *)m_tag_data(mtag));
788 			error = EHOSTUNREACH;
789 			goto bad;
790 		}
791 #endif
792 	}
793 spd_done:
794 #endif /* FAST_IPSEC */
795 
796 	/* We are already being fwd'd from a firewall. */
797 	if (next_hop != NULL)
798 		goto pass;
799 
800 	/* No pfil hooks */
801 	if (!pfil_has_hooks(&inet_pfil_hook)) {
802 		if (m->m_pkthdr.fw_flags & DUMMYNET_MBUF_TAGGED) {
803 			/*
804 			 * Strip dummynet tags from stranded packets
805 			 */
806 			mtag = m_tag_find(m, PACKET_TAG_DUMMYNET, NULL);
807 			KKASSERT(mtag != NULL);
808 			m_tag_delete(m, mtag);
809 			m->m_pkthdr.fw_flags &= ~DUMMYNET_MBUF_TAGGED;
810 		}
811 		goto pass;
812 	}
813 
814 	/*
815 	 * IpHack's section.
816 	 * - Xlate: translate packet's addr/port (NAT).
817 	 * - Firewall: deny/allow/etc.
818 	 * - Wrap: fake packet's addr/port <unimpl.>
819 	 * - Encapsulate: put it in another IP and send out. <unimp.>
820 	 */
821 
822 	/*
823 	 * Run through list of hooks for output packets.
824 	 */
825 	error = pfil_run_hooks(&inet_pfil_hook, &m, ifp, PFIL_OUT);
826 	if (error != 0 || m == NULL)
827 		goto done;
828 	ip = mtod(m, struct ip *);
829 
830 	if (m->m_pkthdr.fw_flags & IPFORWARD_MBUF_TAGGED) {
831 		/*
832 		 * Check dst to make sure it is directly reachable on the
833 		 * interface we previously thought it was.
834 		 * If it isn't (which may be likely in some situations) we have
835 		 * to re-route it (ie, find a route for the next-hop and the
836 		 * associated interface) and set them here. This is nested
837 		 * forwarding which in most cases is undesirable, except where
838 		 * such control is nigh impossible. So we do it here.
839 		 * And I'm babbling.
840 		 */
841 		mtag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL);
842 		KKASSERT(mtag != NULL);
843 		next_hop = m_tag_data(mtag);
844 
845 		/*
846 		 * Try local forwarding first
847 		 */
848 		if (ip_localforward(m, next_hop, hlen))
849 			goto done;
850 
851 		/*
852 		 * Relocate the route based on next_hop.
853 		 * If the current route is inp's cache, keep it untouched.
854 		 */
855 		if (ro == &iproute && ro->ro_rt != NULL) {
856 			RTFREE(ro->ro_rt);
857 			ro->ro_rt = NULL;
858 		}
859 		ro = &iproute;
860 		bzero(ro, sizeof *ro);
861 
862 		/*
863 		 * Forwarding to broadcast address is not allowed.
864 		 * XXX Should we follow IP_ROUTETOIF?
865 		 */
866 		flags &= ~(IP_ALLOWBROADCAST | IP_ROUTETOIF);
867 
868 		/* We are doing forwarding now */
869 		flags |= IP_FORWARDING;
870 
871 		goto reroute;
872 	}
873 
874 	if (m->m_pkthdr.fw_flags & DUMMYNET_MBUF_TAGGED) {
875 		struct dn_pkt *dn_pkt;
876 
877 		mtag = m_tag_find(m, PACKET_TAG_DUMMYNET, NULL);
878 		KKASSERT(mtag != NULL);
879 		dn_pkt = m_tag_data(mtag);
880 
881 		/*
882 		 * Under certain cases it is not possible to recalculate
883 		 * 'ro' and 'dst', let alone 'flags', so just save them in
884 		 * dummynet tag and avoid the possible wrong reculcalation
885 		 * when we come back to ip_output() again.
886 		 *
887 		 * All other parameters have been already used and so they
888 		 * are not needed anymore.
889 		 * XXX if the ifp is deleted while a pkt is in dummynet,
890 		 * we are in trouble! (TODO use ifnet_detach_event)
891 		 *
892 		 * We need to copy *ro because for ICMP pkts (and maybe
893 		 * others) the caller passed a pointer into the stack;
894 		 * dst might also be a pointer into *ro so it needs to
895 		 * be updated.
896 		 */
897 		dn_pkt->ro = *ro;
898 		if (ro->ro_rt)
899 			ro->ro_rt->rt_refcnt++;
900 		if (dst == (struct sockaddr_in *)&ro->ro_dst) {
901 			/* 'dst' points into 'ro' */
902 			dst = (struct sockaddr_in *)&(dn_pkt->ro.ro_dst);
903 		}
904 		dn_pkt->dn_dst = dst;
905 		dn_pkt->flags = flags;
906 
907 		ip_dn_queue(m);
908 		goto done;
909 	}
910 pass:
911 	/* 127/8 must not appear on wire - RFC1122. */
912 	if ((ntohl(ip->ip_dst.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET ||
913 	    (ntohl(ip->ip_src.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET) {
914 		if (!(ifp->if_flags & IFF_LOOPBACK)) {
915 			ipstat.ips_badaddr++;
916 			error = EADDRNOTAVAIL;
917 			goto bad;
918 		}
919 	}
920 
921 	m->m_pkthdr.csum_flags |= CSUM_IP;
922 	sw_csum = m->m_pkthdr.csum_flags & ~ifp->if_hwassist;
923 	if (sw_csum & CSUM_DELAY_DATA) {
924 		in_delayed_cksum(m);
925 		sw_csum &= ~CSUM_DELAY_DATA;
926 	}
927 	m->m_pkthdr.csum_flags &= ifp->if_hwassist;
928 
929 	/*
930 	 * If small enough for interface, or the interface will take
931 	 * care of the fragmentation for us, can just send directly.
932 	 */
933 	if (ip->ip_len <= ifp->if_mtu || ((ifp->if_hwassist & CSUM_FRAGMENT) &&
934 	    !(ip->ip_off & IP_DF))) {
935 		ip->ip_len = htons(ip->ip_len);
936 		ip->ip_off = htons(ip->ip_off);
937 		ip->ip_sum = 0;
938 		if (sw_csum & CSUM_DELAY_IP) {
939 			if (ip->ip_vhl == IP_VHL_BORING)
940 				ip->ip_sum = in_cksum_hdr(ip);
941 			else
942 				ip->ip_sum = in_cksum(m, hlen);
943 		}
944 
945 		/* Record statistics for this interface address. */
946 		if (!(flags & IP_FORWARDING) && ia) {
947 			ia->ia_ifa.if_opackets++;
948 			ia->ia_ifa.if_obytes += m->m_pkthdr.len;
949 		}
950 
951 #ifdef IPSEC
952 		/* clean ipsec history once it goes out of the node */
953 		ipsec_delaux(m);
954 #endif
955 
956 #ifdef MBUF_STRESS_TEST
957 		if (mbuf_frag_size && m->m_pkthdr.len > mbuf_frag_size) {
958 			struct mbuf *m1, *m2;
959 			int length, tmp;
960 
961 			tmp = length = m->m_pkthdr.len;
962 
963 			while ((length -= mbuf_frag_size) >= 1) {
964 				m1 = m_split(m, length, MB_DONTWAIT);
965 				if (m1 == NULL)
966 					break;
967 				m2 = m;
968 				while (m2->m_next != NULL)
969 					m2 = m2->m_next;
970 				m2->m_next = m1;
971 			}
972 			m->m_pkthdr.len = tmp;
973 		}
974 #endif
975 
976 #ifdef MPLS
977 		if (!mpls_output_process(m, ro->ro_rt))
978 			goto done;
979 #endif
980 		error = ifp->if_output(ifp, m, (struct sockaddr *)dst,
981 				       ro->ro_rt);
982 		goto done;
983 	}
984 
985 	if (ip->ip_off & IP_DF) {
986 		error = EMSGSIZE;
987 		/*
988 		 * This case can happen if the user changed the MTU
989 		 * of an interface after enabling IP on it.  Because
990 		 * most netifs don't keep track of routes pointing to
991 		 * them, there is no way for one to update all its
992 		 * routes when the MTU is changed.
993 		 */
994 		if ((ro->ro_rt->rt_flags & (RTF_UP | RTF_HOST)) &&
995 		    !(ro->ro_rt->rt_rmx.rmx_locks & RTV_MTU) &&
996 		    (ro->ro_rt->rt_rmx.rmx_mtu > ifp->if_mtu)) {
997 			ro->ro_rt->rt_rmx.rmx_mtu = ifp->if_mtu;
998 		}
999 		ipstat.ips_cantfrag++;
1000 		goto bad;
1001 	}
1002 
1003 	/*
1004 	 * Too large for interface; fragment if possible. If successful,
1005 	 * on return, m will point to a list of packets to be sent.
1006 	 */
1007 	error = ip_fragment(ip, &m, ifp->if_mtu, ifp->if_hwassist, sw_csum);
1008 	if (error)
1009 		goto bad;
1010 	for (; m; m = m0) {
1011 		m0 = m->m_nextpkt;
1012 		m->m_nextpkt = NULL;
1013 #ifdef IPSEC
1014 		/* clean ipsec history once it goes out of the node */
1015 		ipsec_delaux(m);
1016 #endif
1017 		if (error == 0) {
1018 			/* Record statistics for this interface address. */
1019 			if (ia != NULL) {
1020 				ia->ia_ifa.if_opackets++;
1021 				ia->ia_ifa.if_obytes += m->m_pkthdr.len;
1022 			}
1023 #ifdef MPLS
1024 			if (!mpls_output_process(m, ro->ro_rt))
1025 				continue;
1026 #endif
1027 			error = ifp->if_output(ifp, m, (struct sockaddr *)dst,
1028 					       ro->ro_rt);
1029 		} else {
1030 			m_freem(m);
1031 		}
1032 	}
1033 
1034 	if (error == 0)
1035 		ipstat.ips_fragmented++;
1036 
1037 done:
1038 	if (ro == &iproute && ro->ro_rt != NULL) {
1039 		RTFREE(ro->ro_rt);
1040 		ro->ro_rt = NULL;
1041 	}
1042 #ifdef IPSEC
1043 	if (sp != NULL) {
1044 		KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1045 			kprintf("DP ip_output call free SP:%p\n", sp));
1046 		key_freesp(sp);
1047 	}
1048 #endif
1049 #ifdef FAST_IPSEC
1050 	if (sp != NULL)
1051 		KEY_FREESP(&sp);
1052 #endif
1053 	return (error);
1054 bad:
1055 	m_freem(m);
1056 	goto done;
1057 }
1058 
1059 /*
1060  * Create a chain of fragments which fit the given mtu. m_frag points to the
1061  * mbuf to be fragmented; on return it points to the chain with the fragments.
1062  * Return 0 if no error. If error, m_frag may contain a partially built
1063  * chain of fragments that should be freed by the caller.
1064  *
1065  * if_hwassist_flags is the hw offload capabilities (see if_data.ifi_hwassist)
1066  * sw_csum contains the delayed checksums flags (e.g., CSUM_DELAY_IP).
1067  */
1068 int
1069 ip_fragment(struct ip *ip, struct mbuf **m_frag, int mtu,
1070 	    u_long if_hwassist_flags, int sw_csum)
1071 {
1072 	int error = 0;
1073 	int hlen = IP_VHL_HL(ip->ip_vhl) << 2;
1074 	int len = (mtu - hlen) & ~7;	/* size of payload in each fragment */
1075 	int off;
1076 	struct mbuf *m0 = *m_frag;	/* the original packet		*/
1077 	int firstlen;
1078 	struct mbuf **mnext;
1079 	int nfrags;
1080 
1081 	if (ip->ip_off & IP_DF) {	/* Fragmentation not allowed */
1082 		ipstat.ips_cantfrag++;
1083 		return EMSGSIZE;
1084 	}
1085 
1086 	/*
1087 	 * Must be able to put at least 8 bytes per fragment.
1088 	 */
1089 	if (len < 8)
1090 		return EMSGSIZE;
1091 
1092 	/*
1093 	 * If the interface will not calculate checksums on
1094 	 * fragmented packets, then do it here.
1095 	 */
1096 	if ((m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA) &&
1097 	    !(if_hwassist_flags & CSUM_IP_FRAGS)) {
1098 		in_delayed_cksum(m0);
1099 		m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
1100 	}
1101 
1102 	if (len > PAGE_SIZE) {
1103 		/*
1104 		 * Fragment large datagrams such that each segment
1105 		 * contains a multiple of PAGE_SIZE amount of data,
1106 		 * plus headers. This enables a receiver to perform
1107 		 * page-flipping zero-copy optimizations.
1108 		 *
1109 		 * XXX When does this help given that sender and receiver
1110 		 * could have different page sizes, and also mtu could
1111 		 * be less than the receiver's page size ?
1112 		 */
1113 		int newlen;
1114 		struct mbuf *m;
1115 
1116 		for (m = m0, off = 0; m && (off+m->m_len) <= mtu; m = m->m_next)
1117 			off += m->m_len;
1118 
1119 		/*
1120 		 * firstlen (off - hlen) must be aligned on an
1121 		 * 8-byte boundary
1122 		 */
1123 		if (off < hlen)
1124 			goto smart_frag_failure;
1125 		off = ((off - hlen) & ~7) + hlen;
1126 		newlen = (~PAGE_MASK) & mtu;
1127 		if ((newlen + sizeof(struct ip)) > mtu) {
1128 			/* we failed, go back the default */
1129 smart_frag_failure:
1130 			newlen = len;
1131 			off = hlen + len;
1132 		}
1133 		len = newlen;
1134 
1135 	} else {
1136 		off = hlen + len;
1137 	}
1138 
1139 	firstlen = off - hlen;
1140 	mnext = &m0->m_nextpkt;		/* pointer to next packet */
1141 
1142 	/*
1143 	 * Loop through length of segment after first fragment,
1144 	 * make new header and copy data of each part and link onto chain.
1145 	 * Here, m0 is the original packet, m is the fragment being created.
1146 	 * The fragments are linked off the m_nextpkt of the original
1147 	 * packet, which after processing serves as the first fragment.
1148 	 */
1149 	for (nfrags = 1; off < ip->ip_len; off += len, nfrags++) {
1150 		struct ip *mhip;	/* ip header on the fragment */
1151 		struct mbuf *m;
1152 		int mhlen = sizeof(struct ip);
1153 
1154 		MGETHDR(m, MB_DONTWAIT, MT_HEADER);
1155 		if (m == NULL) {
1156 			error = ENOBUFS;
1157 			ipstat.ips_odropped++;
1158 			goto done;
1159 		}
1160 		m->m_flags |= (m0->m_flags & M_MCAST) | M_FRAG;
1161 		/*
1162 		 * In the first mbuf, leave room for the link header, then
1163 		 * copy the original IP header including options. The payload
1164 		 * goes into an additional mbuf chain returned by m_copy().
1165 		 */
1166 		m->m_data += max_linkhdr;
1167 		mhip = mtod(m, struct ip *);
1168 		*mhip = *ip;
1169 		if (hlen > sizeof(struct ip)) {
1170 			mhlen = ip_optcopy(ip, mhip) + sizeof(struct ip);
1171 			mhip->ip_vhl = IP_MAKE_VHL(IPVERSION, mhlen >> 2);
1172 		}
1173 		m->m_len = mhlen;
1174 		/* XXX do we need to add ip->ip_off below ? */
1175 		mhip->ip_off = ((off - hlen) >> 3) + ip->ip_off;
1176 		if (off + len >= ip->ip_len) {	/* last fragment */
1177 			len = ip->ip_len - off;
1178 			m->m_flags |= M_LASTFRAG;
1179 		} else
1180 			mhip->ip_off |= IP_MF;
1181 		mhip->ip_len = htons((u_short)(len + mhlen));
1182 		m->m_next = m_copy(m0, off, len);
1183 		if (m->m_next == NULL) {		/* copy failed */
1184 			m_free(m);
1185 			error = ENOBUFS;	/* ??? */
1186 			ipstat.ips_odropped++;
1187 			goto done;
1188 		}
1189 		m->m_pkthdr.len = mhlen + len;
1190 		m->m_pkthdr.rcvif = (struct ifnet *)NULL;
1191 		m->m_pkthdr.csum_flags = m0->m_pkthdr.csum_flags;
1192 		mhip->ip_off = htons(mhip->ip_off);
1193 		mhip->ip_sum = 0;
1194 		if (sw_csum & CSUM_DELAY_IP)
1195 			mhip->ip_sum = in_cksum(m, mhlen);
1196 		*mnext = m;
1197 		mnext = &m->m_nextpkt;
1198 	}
1199 	ipstat.ips_ofragments += nfrags;
1200 
1201 	/* set first marker for fragment chain */
1202 	m0->m_flags |= M_FIRSTFRAG | M_FRAG;
1203 	m0->m_pkthdr.csum_data = nfrags;
1204 
1205 	/*
1206 	 * Update first fragment by trimming what's been copied out
1207 	 * and updating header.
1208 	 */
1209 	m_adj(m0, hlen + firstlen - ip->ip_len);
1210 	m0->m_pkthdr.len = hlen + firstlen;
1211 	ip->ip_len = htons((u_short)m0->m_pkthdr.len);
1212 	ip->ip_off |= IP_MF;
1213 	ip->ip_off = htons(ip->ip_off);
1214 	ip->ip_sum = 0;
1215 	if (sw_csum & CSUM_DELAY_IP)
1216 		ip->ip_sum = in_cksum(m0, hlen);
1217 
1218 done:
1219 	*m_frag = m0;
1220 	return error;
1221 }
1222 
1223 void
1224 in_delayed_cksum(struct mbuf *m)
1225 {
1226 	struct ip *ip;
1227 	u_short csum, offset;
1228 
1229 	ip = mtod(m, struct ip *);
1230 	offset = IP_VHL_HL(ip->ip_vhl) << 2 ;
1231 	csum = in_cksum_skip(m, ip->ip_len, offset);
1232 	if (m->m_pkthdr.csum_flags & CSUM_UDP && csum == 0)
1233 		csum = 0xffff;
1234 	offset += m->m_pkthdr.csum_data;	/* checksum offset */
1235 
1236 	if (offset + sizeof(u_short) > m->m_len) {
1237 		kprintf("delayed m_pullup, m->len: %d  off: %d  p: %d\n",
1238 		    m->m_len, offset, ip->ip_p);
1239 		/*
1240 		 * XXX
1241 		 * this shouldn't happen, but if it does, the
1242 		 * correct behavior may be to insert the checksum
1243 		 * in the existing chain instead of rearranging it.
1244 		 */
1245 		m = m_pullup(m, offset + sizeof(u_short));
1246 	}
1247 	*(u_short *)(m->m_data + offset) = csum;
1248 }
1249 
1250 /*
1251  * Insert IP options into preformed packet.
1252  * Adjust IP destination as required for IP source routing,
1253  * as indicated by a non-zero in_addr at the start of the options.
1254  *
1255  * XXX This routine assumes that the packet has no options in place.
1256  */
1257 static struct mbuf *
1258 ip_insertoptions(struct mbuf *m, struct mbuf *opt, int *phlen)
1259 {
1260 	struct ipoption *p = mtod(opt, struct ipoption *);
1261 	struct mbuf *n;
1262 	struct ip *ip = mtod(m, struct ip *);
1263 	unsigned optlen;
1264 
1265 	optlen = opt->m_len - sizeof p->ipopt_dst;
1266 	if (optlen + (u_short)ip->ip_len > IP_MAXPACKET) {
1267 		*phlen = 0;
1268 		return (m);		/* XXX should fail */
1269 	}
1270 	if (p->ipopt_dst.s_addr)
1271 		ip->ip_dst = p->ipopt_dst;
1272 	if (m->m_flags & M_EXT || m->m_data - optlen < m->m_pktdat) {
1273 		MGETHDR(n, MB_DONTWAIT, MT_HEADER);
1274 		if (n == NULL) {
1275 			*phlen = 0;
1276 			return (m);
1277 		}
1278 		n->m_pkthdr.rcvif = (struct ifnet *)NULL;
1279 		n->m_pkthdr.len = m->m_pkthdr.len + optlen;
1280 		m->m_len -= sizeof(struct ip);
1281 		m->m_data += sizeof(struct ip);
1282 		n->m_next = m;
1283 		m = n;
1284 		m->m_len = optlen + sizeof(struct ip);
1285 		m->m_data += max_linkhdr;
1286 		memcpy(mtod(m, void *), ip, sizeof(struct ip));
1287 	} else {
1288 		m->m_data -= optlen;
1289 		m->m_len += optlen;
1290 		m->m_pkthdr.len += optlen;
1291 		ovbcopy(ip, mtod(m, caddr_t), sizeof(struct ip));
1292 	}
1293 	ip = mtod(m, struct ip *);
1294 	bcopy(p->ipopt_list, ip + 1, optlen);
1295 	*phlen = sizeof(struct ip) + optlen;
1296 	ip->ip_vhl = IP_MAKE_VHL(IPVERSION, *phlen >> 2);
1297 	ip->ip_len += optlen;
1298 	return (m);
1299 }
1300 
1301 /*
1302  * Copy options from ip to jp,
1303  * omitting those not copied during fragmentation.
1304  */
1305 int
1306 ip_optcopy(struct ip *ip, struct ip *jp)
1307 {
1308 	u_char *cp, *dp;
1309 	int opt, optlen, cnt;
1310 
1311 	cp = (u_char *)(ip + 1);
1312 	dp = (u_char *)(jp + 1);
1313 	cnt = (IP_VHL_HL(ip->ip_vhl) << 2) - sizeof(struct ip);
1314 	for (; cnt > 0; cnt -= optlen, cp += optlen) {
1315 		opt = cp[0];
1316 		if (opt == IPOPT_EOL)
1317 			break;
1318 		if (opt == IPOPT_NOP) {
1319 			/* Preserve for IP mcast tunnel's LSRR alignment. */
1320 			*dp++ = IPOPT_NOP;
1321 			optlen = 1;
1322 			continue;
1323 		}
1324 
1325 		KASSERT(cnt >= IPOPT_OLEN + sizeof *cp,
1326 		    ("ip_optcopy: malformed ipv4 option"));
1327 		optlen = cp[IPOPT_OLEN];
1328 		KASSERT(optlen >= IPOPT_OLEN + sizeof *cp && optlen <= cnt,
1329 		    ("ip_optcopy: malformed ipv4 option"));
1330 
1331 		/* bogus lengths should have been caught by ip_dooptions */
1332 		if (optlen > cnt)
1333 			optlen = cnt;
1334 		if (IPOPT_COPIED(opt)) {
1335 			bcopy(cp, dp, optlen);
1336 			dp += optlen;
1337 		}
1338 	}
1339 	for (optlen = dp - (u_char *)(jp+1); optlen & 0x3; optlen++)
1340 		*dp++ = IPOPT_EOL;
1341 	return (optlen);
1342 }
1343 
1344 /*
1345  * IP socket option processing.
1346  */
1347 int
1348 ip_ctloutput(struct socket *so, struct sockopt *sopt)
1349 {
1350 	struct	inpcb *inp = so->so_pcb;
1351 	int	error, optval;
1352 
1353 	error = optval = 0;
1354 	if (sopt->sopt_level != IPPROTO_IP) {
1355 		return (EINVAL);
1356 	}
1357 
1358 	switch (sopt->sopt_dir) {
1359 	case SOPT_SET:
1360 		switch (sopt->sopt_name) {
1361 		case IP_OPTIONS:
1362 #ifdef notyet
1363 		case IP_RETOPTS:
1364 #endif
1365 		{
1366 			struct mbuf *m;
1367 			if (sopt->sopt_valsize > MLEN) {
1368 				error = EMSGSIZE;
1369 				break;
1370 			}
1371 			MGET(m, sopt->sopt_td ? MB_WAIT : MB_DONTWAIT, MT_HEADER);
1372 			if (m == NULL) {
1373 				error = ENOBUFS;
1374 				break;
1375 			}
1376 			m->m_len = sopt->sopt_valsize;
1377 			error = soopt_to_kbuf(sopt, mtod(m, void *), m->m_len,
1378 					      m->m_len);
1379 			return (ip_pcbopts(sopt->sopt_name, &inp->inp_options,
1380 					   m));
1381 		}
1382 
1383 		case IP_TOS:
1384 		case IP_TTL:
1385 		case IP_MINTTL:
1386 		case IP_RECVOPTS:
1387 		case IP_RECVRETOPTS:
1388 		case IP_RECVDSTADDR:
1389 		case IP_RECVIF:
1390 		case IP_RECVTTL:
1391 		case IP_FAITH:
1392 			error = soopt_to_kbuf(sopt, &optval, sizeof optval,
1393 					     sizeof optval);
1394 			if (error)
1395 				break;
1396 			switch (sopt->sopt_name) {
1397 			case IP_TOS:
1398 				inp->inp_ip_tos = optval;
1399 				break;
1400 
1401 			case IP_TTL:
1402 				inp->inp_ip_ttl = optval;
1403 				break;
1404 			case IP_MINTTL:
1405 				if (optval > 0 && optval <= MAXTTL)
1406 					inp->inp_ip_minttl = optval;
1407 				else
1408 					error = EINVAL;
1409 				break;
1410 #define	OPTSET(bit) \
1411 	if (optval) \
1412 		inp->inp_flags |= bit; \
1413 	else \
1414 		inp->inp_flags &= ~bit;
1415 
1416 			case IP_RECVOPTS:
1417 				OPTSET(INP_RECVOPTS);
1418 				break;
1419 
1420 			case IP_RECVRETOPTS:
1421 				OPTSET(INP_RECVRETOPTS);
1422 				break;
1423 
1424 			case IP_RECVDSTADDR:
1425 				OPTSET(INP_RECVDSTADDR);
1426 				break;
1427 
1428 			case IP_RECVIF:
1429 				OPTSET(INP_RECVIF);
1430 				break;
1431 
1432 			case IP_RECVTTL:
1433 				OPTSET(INP_RECVTTL);
1434 				break;
1435 
1436 			case IP_FAITH:
1437 				OPTSET(INP_FAITH);
1438 				break;
1439 			}
1440 			break;
1441 #undef OPTSET
1442 
1443 		case IP_MULTICAST_IF:
1444 		case IP_MULTICAST_VIF:
1445 		case IP_MULTICAST_TTL:
1446 		case IP_MULTICAST_LOOP:
1447 		case IP_ADD_MEMBERSHIP:
1448 		case IP_DROP_MEMBERSHIP:
1449 			error = ip_setmoptions(sopt, &inp->inp_moptions);
1450 			break;
1451 
1452 		case IP_PORTRANGE:
1453 			error = soopt_to_kbuf(sopt, &optval, sizeof optval,
1454 					    sizeof optval);
1455 			if (error)
1456 				break;
1457 
1458 			switch (optval) {
1459 			case IP_PORTRANGE_DEFAULT:
1460 				inp->inp_flags &= ~(INP_LOWPORT);
1461 				inp->inp_flags &= ~(INP_HIGHPORT);
1462 				break;
1463 
1464 			case IP_PORTRANGE_HIGH:
1465 				inp->inp_flags &= ~(INP_LOWPORT);
1466 				inp->inp_flags |= INP_HIGHPORT;
1467 				break;
1468 
1469 			case IP_PORTRANGE_LOW:
1470 				inp->inp_flags &= ~(INP_HIGHPORT);
1471 				inp->inp_flags |= INP_LOWPORT;
1472 				break;
1473 
1474 			default:
1475 				error = EINVAL;
1476 				break;
1477 			}
1478 			break;
1479 
1480 #if defined(IPSEC) || defined(FAST_IPSEC)
1481 		case IP_IPSEC_POLICY:
1482 		{
1483 			caddr_t req;
1484 			size_t len = 0;
1485 			int priv;
1486 			struct mbuf *m;
1487 			int optname;
1488 
1489 			if ((error = soopt_getm(sopt, &m)) != 0) /* XXX */
1490 				break;
1491 			soopt_to_mbuf(sopt, m);
1492 			priv = (sopt->sopt_td != NULL &&
1493 				priv_check(sopt->sopt_td, PRIV_ROOT) != 0) ? 0 : 1;
1494 			req = mtod(m, caddr_t);
1495 			len = m->m_len;
1496 			optname = sopt->sopt_name;
1497 			error = ipsec4_set_policy(inp, optname, req, len, priv);
1498 			m_freem(m);
1499 			break;
1500 		}
1501 #endif /*IPSEC*/
1502 
1503 		default:
1504 			error = ENOPROTOOPT;
1505 			break;
1506 		}
1507 		break;
1508 
1509 	case SOPT_GET:
1510 		switch (sopt->sopt_name) {
1511 		case IP_OPTIONS:
1512 		case IP_RETOPTS:
1513 			if (inp->inp_options)
1514 				soopt_from_kbuf(sopt, mtod(inp->inp_options,
1515 							   char *),
1516 						inp->inp_options->m_len);
1517 			else
1518 				sopt->sopt_valsize = 0;
1519 			break;
1520 
1521 		case IP_TOS:
1522 		case IP_TTL:
1523 		case IP_MINTTL:
1524 		case IP_RECVOPTS:
1525 		case IP_RECVRETOPTS:
1526 		case IP_RECVDSTADDR:
1527 		case IP_RECVTTL:
1528 		case IP_RECVIF:
1529 		case IP_PORTRANGE:
1530 		case IP_FAITH:
1531 			switch (sopt->sopt_name) {
1532 
1533 			case IP_TOS:
1534 				optval = inp->inp_ip_tos;
1535 				break;
1536 
1537 			case IP_TTL:
1538 				optval = inp->inp_ip_ttl;
1539 				break;
1540 			case IP_MINTTL:
1541 				optval = inp->inp_ip_minttl;
1542 				break;
1543 
1544 #define	OPTBIT(bit)	(inp->inp_flags & bit ? 1 : 0)
1545 
1546 			case IP_RECVOPTS:
1547 				optval = OPTBIT(INP_RECVOPTS);
1548 				break;
1549 
1550 			case IP_RECVRETOPTS:
1551 				optval = OPTBIT(INP_RECVRETOPTS);
1552 				break;
1553 
1554 			case IP_RECVDSTADDR:
1555 				optval = OPTBIT(INP_RECVDSTADDR);
1556 				break;
1557 
1558 			case IP_RECVTTL:
1559 				optval = OPTBIT(INP_RECVTTL);
1560 				break;
1561 
1562 			case IP_RECVIF:
1563 				optval = OPTBIT(INP_RECVIF);
1564 				break;
1565 
1566 			case IP_PORTRANGE:
1567 				if (inp->inp_flags & INP_HIGHPORT)
1568 					optval = IP_PORTRANGE_HIGH;
1569 				else if (inp->inp_flags & INP_LOWPORT)
1570 					optval = IP_PORTRANGE_LOW;
1571 				else
1572 					optval = 0;
1573 				break;
1574 
1575 			case IP_FAITH:
1576 				optval = OPTBIT(INP_FAITH);
1577 				break;
1578 			}
1579 			soopt_from_kbuf(sopt, &optval, sizeof optval);
1580 			break;
1581 
1582 		case IP_MULTICAST_IF:
1583 		case IP_MULTICAST_VIF:
1584 		case IP_MULTICAST_TTL:
1585 		case IP_MULTICAST_LOOP:
1586 		case IP_ADD_MEMBERSHIP:
1587 		case IP_DROP_MEMBERSHIP:
1588 			error = ip_getmoptions(sopt, inp->inp_moptions);
1589 			break;
1590 
1591 #if defined(IPSEC) || defined(FAST_IPSEC)
1592 		case IP_IPSEC_POLICY:
1593 		{
1594 			struct mbuf *m = NULL;
1595 			caddr_t req = NULL;
1596 			size_t len = 0;
1597 
1598 			if (m != NULL) {
1599 				req = mtod(m, caddr_t);
1600 				len = m->m_len;
1601 			}
1602 			error = ipsec4_get_policy(so->so_pcb, req, len, &m);
1603 			if (error == 0)
1604 				error = soopt_from_mbuf(sopt, m); /* XXX */
1605 			if (error == 0)
1606 				m_freem(m);
1607 			break;
1608 		}
1609 #endif /*IPSEC*/
1610 
1611 		default:
1612 			error = ENOPROTOOPT;
1613 			break;
1614 		}
1615 		break;
1616 	}
1617 	return (error);
1618 }
1619 
1620 /*
1621  * Set up IP options in pcb for insertion in output packets.
1622  * Store in mbuf with pointer in pcbopt, adding pseudo-option
1623  * with destination address if source routed.
1624  */
1625 static int
1626 ip_pcbopts(int optname, struct mbuf **pcbopt, struct mbuf *m)
1627 {
1628 	int cnt, optlen;
1629 	u_char *cp;
1630 	u_char opt;
1631 
1632 	/* turn off any old options */
1633 	if (*pcbopt)
1634 		m_free(*pcbopt);
1635 	*pcbopt = 0;
1636 	if (m == NULL || m->m_len == 0) {
1637 		/*
1638 		 * Only turning off any previous options.
1639 		 */
1640 		if (m != NULL)
1641 			m_free(m);
1642 		return (0);
1643 	}
1644 
1645 	if (m->m_len % sizeof(int32_t))
1646 		goto bad;
1647 	/*
1648 	 * IP first-hop destination address will be stored before
1649 	 * actual options; move other options back
1650 	 * and clear it when none present.
1651 	 */
1652 	if (m->m_data + m->m_len + sizeof(struct in_addr) >= &m->m_dat[MLEN])
1653 		goto bad;
1654 	cnt = m->m_len;
1655 	m->m_len += sizeof(struct in_addr);
1656 	cp = mtod(m, u_char *) + sizeof(struct in_addr);
1657 	ovbcopy(mtod(m, caddr_t), cp, cnt);
1658 	bzero(mtod(m, caddr_t), sizeof(struct in_addr));
1659 
1660 	for (; cnt > 0; cnt -= optlen, cp += optlen) {
1661 		opt = cp[IPOPT_OPTVAL];
1662 		if (opt == IPOPT_EOL)
1663 			break;
1664 		if (opt == IPOPT_NOP)
1665 			optlen = 1;
1666 		else {
1667 			if (cnt < IPOPT_OLEN + sizeof *cp)
1668 				goto bad;
1669 			optlen = cp[IPOPT_OLEN];
1670 			if (optlen < IPOPT_OLEN + sizeof *cp || optlen > cnt)
1671 				goto bad;
1672 		}
1673 		switch (opt) {
1674 
1675 		default:
1676 			break;
1677 
1678 		case IPOPT_LSRR:
1679 		case IPOPT_SSRR:
1680 			/*
1681 			 * user process specifies route as:
1682 			 *	->A->B->C->D
1683 			 * D must be our final destination (but we can't
1684 			 * check that since we may not have connected yet).
1685 			 * A is first hop destination, which doesn't appear in
1686 			 * actual IP option, but is stored before the options.
1687 			 */
1688 			if (optlen < IPOPT_MINOFF - 1 + sizeof(struct in_addr))
1689 				goto bad;
1690 			m->m_len -= sizeof(struct in_addr);
1691 			cnt -= sizeof(struct in_addr);
1692 			optlen -= sizeof(struct in_addr);
1693 			cp[IPOPT_OLEN] = optlen;
1694 			/*
1695 			 * Move first hop before start of options.
1696 			 */
1697 			bcopy(&cp[IPOPT_OFFSET+1], mtod(m, caddr_t),
1698 			      sizeof(struct in_addr));
1699 			/*
1700 			 * Then copy rest of options back
1701 			 * to close up the deleted entry.
1702 			 */
1703 			ovbcopy(&cp[IPOPT_OFFSET+1] + sizeof(struct in_addr),
1704 				&cp[IPOPT_OFFSET+1],
1705 				cnt - (IPOPT_MINOFF - 1));
1706 			break;
1707 		}
1708 	}
1709 	if (m->m_len > MAX_IPOPTLEN + sizeof(struct in_addr))
1710 		goto bad;
1711 	*pcbopt = m;
1712 	return (0);
1713 
1714 bad:
1715 	m_free(m);
1716 	return (EINVAL);
1717 }
1718 
1719 /*
1720  * XXX
1721  * The whole multicast option thing needs to be re-thought.
1722  * Several of these options are equally applicable to non-multicast
1723  * transmission, and one (IP_MULTICAST_TTL) totally duplicates a
1724  * standard option (IP_TTL).
1725  */
1726 
1727 /*
1728  * following RFC1724 section 3.3, 0.0.0.0/8 is interpreted as interface index.
1729  */
1730 static struct ifnet *
1731 ip_multicast_if(struct in_addr *a, int *ifindexp)
1732 {
1733 	int ifindex;
1734 	struct ifnet *ifp;
1735 
1736 	if (ifindexp)
1737 		*ifindexp = 0;
1738 	if (ntohl(a->s_addr) >> 24 == 0) {
1739 		ifindex = ntohl(a->s_addr) & 0xffffff;
1740 		if (ifindex < 0 || if_index < ifindex)
1741 			return NULL;
1742 		ifp = ifindex2ifnet[ifindex];
1743 		if (ifindexp)
1744 			*ifindexp = ifindex;
1745 	} else {
1746 		ifp = INADDR_TO_IFP(a);
1747 	}
1748 	return ifp;
1749 }
1750 
1751 /*
1752  * Set the IP multicast options in response to user setsockopt().
1753  */
1754 static int
1755 ip_setmoptions(struct sockopt *sopt, struct ip_moptions **imop)
1756 {
1757 	int error = 0;
1758 	int i;
1759 	struct in_addr addr;
1760 	struct ip_mreq mreq;
1761 	struct ifnet *ifp;
1762 	struct ip_moptions *imo = *imop;
1763 	int ifindex;
1764 
1765 	if (imo == NULL) {
1766 		/*
1767 		 * No multicast option buffer attached to the pcb;
1768 		 * allocate one and initialize to default values.
1769 		 */
1770 		imo = kmalloc(sizeof *imo, M_IPMOPTS, M_WAITOK);
1771 
1772 		*imop = imo;
1773 		imo->imo_multicast_ifp = NULL;
1774 		imo->imo_multicast_addr.s_addr = INADDR_ANY;
1775 		imo->imo_multicast_vif = -1;
1776 		imo->imo_multicast_ttl = IP_DEFAULT_MULTICAST_TTL;
1777 		imo->imo_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
1778 		imo->imo_num_memberships = 0;
1779 	}
1780 	switch (sopt->sopt_name) {
1781 	/* store an index number for the vif you wanna use in the send */
1782 	case IP_MULTICAST_VIF:
1783 		if (legal_vif_num == 0) {
1784 			error = EOPNOTSUPP;
1785 			break;
1786 		}
1787 		error = soopt_to_kbuf(sopt, &i, sizeof i, sizeof i);
1788 		if (error)
1789 			break;
1790 		if (!legal_vif_num(i) && (i != -1)) {
1791 			error = EINVAL;
1792 			break;
1793 		}
1794 		imo->imo_multicast_vif = i;
1795 		break;
1796 
1797 	case IP_MULTICAST_IF:
1798 		/*
1799 		 * Select the interface for outgoing multicast packets.
1800 		 */
1801 		error = soopt_to_kbuf(sopt, &addr, sizeof addr, sizeof addr);
1802 		if (error)
1803 			break;
1804 
1805 		/*
1806 		 * INADDR_ANY is used to remove a previous selection.
1807 		 * When no interface is selected, a default one is
1808 		 * chosen every time a multicast packet is sent.
1809 		 */
1810 		if (addr.s_addr == INADDR_ANY) {
1811 			imo->imo_multicast_ifp = NULL;
1812 			break;
1813 		}
1814 		/*
1815 		 * The selected interface is identified by its local
1816 		 * IP address.  Find the interface and confirm that
1817 		 * it supports multicasting.
1818 		 */
1819 		crit_enter();
1820 		ifp = ip_multicast_if(&addr, &ifindex);
1821 		if (ifp == NULL || !(ifp->if_flags & IFF_MULTICAST)) {
1822 			crit_exit();
1823 			error = EADDRNOTAVAIL;
1824 			break;
1825 		}
1826 		imo->imo_multicast_ifp = ifp;
1827 		if (ifindex)
1828 			imo->imo_multicast_addr = addr;
1829 		else
1830 			imo->imo_multicast_addr.s_addr = INADDR_ANY;
1831 		crit_exit();
1832 		break;
1833 
1834 	case IP_MULTICAST_TTL:
1835 		/*
1836 		 * Set the IP time-to-live for outgoing multicast packets.
1837 		 * The original multicast API required a char argument,
1838 		 * which is inconsistent with the rest of the socket API.
1839 		 * We allow either a char or an int.
1840 		 */
1841 		if (sopt->sopt_valsize == 1) {
1842 			u_char ttl;
1843 			error = soopt_to_kbuf(sopt, &ttl, 1, 1);
1844 			if (error)
1845 				break;
1846 			imo->imo_multicast_ttl = ttl;
1847 		} else {
1848 			u_int ttl;
1849 			error = soopt_to_kbuf(sopt, &ttl, sizeof ttl, sizeof ttl);
1850 			if (error)
1851 				break;
1852 			if (ttl > 255)
1853 				error = EINVAL;
1854 			else
1855 				imo->imo_multicast_ttl = ttl;
1856 		}
1857 		break;
1858 
1859 	case IP_MULTICAST_LOOP:
1860 		/*
1861 		 * Set the loopback flag for outgoing multicast packets.
1862 		 * Must be zero or one.  The original multicast API required a
1863 		 * char argument, which is inconsistent with the rest
1864 		 * of the socket API.  We allow either a char or an int.
1865 		 */
1866 		if (sopt->sopt_valsize == 1) {
1867 			u_char loop;
1868 
1869 			error = soopt_to_kbuf(sopt, &loop, 1, 1);
1870 			if (error)
1871 				break;
1872 			imo->imo_multicast_loop = !!loop;
1873 		} else {
1874 			u_int loop;
1875 
1876 			error = soopt_to_kbuf(sopt, &loop, sizeof loop,
1877 					    sizeof loop);
1878 			if (error)
1879 				break;
1880 			imo->imo_multicast_loop = !!loop;
1881 		}
1882 		break;
1883 
1884 	case IP_ADD_MEMBERSHIP:
1885 		/*
1886 		 * Add a multicast group membership.
1887 		 * Group must be a valid IP multicast address.
1888 		 */
1889 		error = soopt_to_kbuf(sopt, &mreq, sizeof mreq, sizeof mreq);
1890 		if (error)
1891 			break;
1892 
1893 		if (!IN_MULTICAST(ntohl(mreq.imr_multiaddr.s_addr))) {
1894 			error = EINVAL;
1895 			break;
1896 		}
1897 		crit_enter();
1898 		/*
1899 		 * If no interface address was provided, use the interface of
1900 		 * the route to the given multicast address.
1901 		 */
1902 		if (mreq.imr_interface.s_addr == INADDR_ANY) {
1903 			struct sockaddr_in dst;
1904 			struct rtentry *rt;
1905 
1906 			bzero(&dst, sizeof(struct sockaddr_in));
1907 			dst.sin_len = sizeof(struct sockaddr_in);
1908 			dst.sin_family = AF_INET;
1909 			dst.sin_addr = mreq.imr_multiaddr;
1910 			rt = rtlookup((struct sockaddr *)&dst);
1911 			if (rt == NULL) {
1912 				error = EADDRNOTAVAIL;
1913 				crit_exit();
1914 				break;
1915 			}
1916 			--rt->rt_refcnt;
1917 			ifp = rt->rt_ifp;
1918 		} else {
1919 			ifp = ip_multicast_if(&mreq.imr_interface, NULL);
1920 		}
1921 
1922 		/*
1923 		 * See if we found an interface, and confirm that it
1924 		 * supports multicast.
1925 		 */
1926 		if (ifp == NULL || !(ifp->if_flags & IFF_MULTICAST)) {
1927 			error = EADDRNOTAVAIL;
1928 			crit_exit();
1929 			break;
1930 		}
1931 		/*
1932 		 * See if the membership already exists or if all the
1933 		 * membership slots are full.
1934 		 */
1935 		for (i = 0; i < imo->imo_num_memberships; ++i) {
1936 			if (imo->imo_membership[i]->inm_ifp == ifp &&
1937 			    imo->imo_membership[i]->inm_addr.s_addr
1938 						== mreq.imr_multiaddr.s_addr)
1939 				break;
1940 		}
1941 		if (i < imo->imo_num_memberships) {
1942 			error = EADDRINUSE;
1943 			crit_exit();
1944 			break;
1945 		}
1946 		if (i == IP_MAX_MEMBERSHIPS) {
1947 			error = ETOOMANYREFS;
1948 			crit_exit();
1949 			break;
1950 		}
1951 		/*
1952 		 * Everything looks good; add a new record to the multicast
1953 		 * address list for the given interface.
1954 		 */
1955 		if ((imo->imo_membership[i] =
1956 		     in_addmulti(&mreq.imr_multiaddr, ifp)) == NULL) {
1957 			error = ENOBUFS;
1958 			crit_exit();
1959 			break;
1960 		}
1961 		++imo->imo_num_memberships;
1962 		crit_exit();
1963 		break;
1964 
1965 	case IP_DROP_MEMBERSHIP:
1966 		/*
1967 		 * Drop a multicast group membership.
1968 		 * Group must be a valid IP multicast address.
1969 		 */
1970 		error = soopt_to_kbuf(sopt, &mreq, sizeof mreq, sizeof mreq);
1971 		if (error)
1972 			break;
1973 
1974 		if (!IN_MULTICAST(ntohl(mreq.imr_multiaddr.s_addr))) {
1975 			error = EINVAL;
1976 			break;
1977 		}
1978 
1979 		crit_enter();
1980 		/*
1981 		 * If an interface address was specified, get a pointer
1982 		 * to its ifnet structure.
1983 		 */
1984 		if (mreq.imr_interface.s_addr == INADDR_ANY)
1985 			ifp = NULL;
1986 		else {
1987 			ifp = ip_multicast_if(&mreq.imr_interface, NULL);
1988 			if (ifp == NULL) {
1989 				error = EADDRNOTAVAIL;
1990 				crit_exit();
1991 				break;
1992 			}
1993 		}
1994 		/*
1995 		 * Find the membership in the membership array.
1996 		 */
1997 		for (i = 0; i < imo->imo_num_memberships; ++i) {
1998 			if ((ifp == NULL ||
1999 			     imo->imo_membership[i]->inm_ifp == ifp) &&
2000 			    imo->imo_membership[i]->inm_addr.s_addr ==
2001 			    mreq.imr_multiaddr.s_addr)
2002 				break;
2003 		}
2004 		if (i == imo->imo_num_memberships) {
2005 			error = EADDRNOTAVAIL;
2006 			crit_exit();
2007 			break;
2008 		}
2009 		/*
2010 		 * Give up the multicast address record to which the
2011 		 * membership points.
2012 		 */
2013 		in_delmulti(imo->imo_membership[i]);
2014 		/*
2015 		 * Remove the gap in the membership array.
2016 		 */
2017 		for (++i; i < imo->imo_num_memberships; ++i)
2018 			imo->imo_membership[i-1] = imo->imo_membership[i];
2019 		--imo->imo_num_memberships;
2020 		crit_exit();
2021 		break;
2022 
2023 	default:
2024 		error = EOPNOTSUPP;
2025 		break;
2026 	}
2027 
2028 	/*
2029 	 * If all options have default values, no need to keep the mbuf.
2030 	 */
2031 	if (imo->imo_multicast_ifp == NULL &&
2032 	    imo->imo_multicast_vif == -1 &&
2033 	    imo->imo_multicast_ttl == IP_DEFAULT_MULTICAST_TTL &&
2034 	    imo->imo_multicast_loop == IP_DEFAULT_MULTICAST_LOOP &&
2035 	    imo->imo_num_memberships == 0) {
2036 		kfree(*imop, M_IPMOPTS);
2037 		*imop = NULL;
2038 	}
2039 
2040 	return (error);
2041 }
2042 
2043 /*
2044  * Return the IP multicast options in response to user getsockopt().
2045  */
2046 static int
2047 ip_getmoptions(struct sockopt *sopt, struct ip_moptions *imo)
2048 {
2049 	struct in_addr addr;
2050 	struct in_ifaddr *ia;
2051 	int error, optval;
2052 	u_char coptval;
2053 
2054 	error = 0;
2055 	switch (sopt->sopt_name) {
2056 	case IP_MULTICAST_VIF:
2057 		if (imo != NULL)
2058 			optval = imo->imo_multicast_vif;
2059 		else
2060 			optval = -1;
2061 		soopt_from_kbuf(sopt, &optval, sizeof optval);
2062 		break;
2063 
2064 	case IP_MULTICAST_IF:
2065 		if (imo == NULL || imo->imo_multicast_ifp == NULL)
2066 			addr.s_addr = INADDR_ANY;
2067 		else if (imo->imo_multicast_addr.s_addr) {
2068 			/* return the value user has set */
2069 			addr = imo->imo_multicast_addr;
2070 		} else {
2071 			ia = IFP_TO_IA(imo->imo_multicast_ifp);
2072 			addr.s_addr = (ia == NULL) ? INADDR_ANY
2073 				: IA_SIN(ia)->sin_addr.s_addr;
2074 		}
2075 		soopt_from_kbuf(sopt, &addr, sizeof addr);
2076 		break;
2077 
2078 	case IP_MULTICAST_TTL:
2079 		if (imo == NULL)
2080 			optval = coptval = IP_DEFAULT_MULTICAST_TTL;
2081 		else
2082 			optval = coptval = imo->imo_multicast_ttl;
2083 		if (sopt->sopt_valsize == 1)
2084 			soopt_from_kbuf(sopt, &coptval, 1);
2085 		else
2086 			soopt_from_kbuf(sopt, &optval, sizeof optval);
2087 		break;
2088 
2089 	case IP_MULTICAST_LOOP:
2090 		if (imo == NULL)
2091 			optval = coptval = IP_DEFAULT_MULTICAST_LOOP;
2092 		else
2093 			optval = coptval = imo->imo_multicast_loop;
2094 		if (sopt->sopt_valsize == 1)
2095 			soopt_from_kbuf(sopt, &coptval, 1);
2096 		else
2097 			soopt_from_kbuf(sopt, &optval, sizeof optval);
2098 		break;
2099 
2100 	default:
2101 		error = ENOPROTOOPT;
2102 		break;
2103 	}
2104 	return (error);
2105 }
2106 
2107 /*
2108  * Discard the IP multicast options.
2109  */
2110 void
2111 ip_freemoptions(struct ip_moptions *imo)
2112 {
2113 	int i;
2114 
2115 	if (imo != NULL) {
2116 		for (i = 0; i < imo->imo_num_memberships; ++i)
2117 			in_delmulti(imo->imo_membership[i]);
2118 		kfree(imo, M_IPMOPTS);
2119 	}
2120 }
2121 
2122 /*
2123  * Routine called from ip_output() to loop back a copy of an IP multicast
2124  * packet to the input queue of a specified interface.  Note that this
2125  * calls the output routine of the loopback "driver", but with an interface
2126  * pointer that might NOT be a loopback interface -- evil, but easier than
2127  * replicating that code here.
2128  */
2129 static void
2130 ip_mloopback(struct ifnet *ifp, struct mbuf *m, struct sockaddr_in *dst,
2131 	     int hlen)
2132 {
2133 	struct ip *ip;
2134 	struct mbuf *copym;
2135 
2136 	copym = m_copypacket(m, MB_DONTWAIT);
2137 	if (copym != NULL && (copym->m_flags & M_EXT || copym->m_len < hlen))
2138 		copym = m_pullup(copym, hlen);
2139 	if (copym != NULL) {
2140 		/*
2141 		 * if the checksum hasn't been computed, mark it as valid
2142 		 */
2143 		if (copym->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
2144 			in_delayed_cksum(copym);
2145 			copym->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
2146 			copym->m_pkthdr.csum_flags |=
2147 			    CSUM_DATA_VALID | CSUM_PSEUDO_HDR;
2148 			copym->m_pkthdr.csum_data = 0xffff;
2149 		}
2150 		/*
2151 		 * We don't bother to fragment if the IP length is greater
2152 		 * than the interface's MTU.  Can this possibly matter?
2153 		 */
2154 		ip = mtod(copym, struct ip *);
2155 		ip->ip_len = htons(ip->ip_len);
2156 		ip->ip_off = htons(ip->ip_off);
2157 		ip->ip_sum = 0;
2158 		if (ip->ip_vhl == IP_VHL_BORING) {
2159 			ip->ip_sum = in_cksum_hdr(ip);
2160 		} else {
2161 			ip->ip_sum = in_cksum(copym, hlen);
2162 		}
2163 		/*
2164 		 * NB:
2165 		 * It's not clear whether there are any lingering
2166 		 * reentrancy problems in other areas which might
2167 		 * be exposed by using ip_input directly (in
2168 		 * particular, everything which modifies the packet
2169 		 * in-place).  Yet another option is using the
2170 		 * protosw directly to deliver the looped back
2171 		 * packet.  For the moment, we'll err on the side
2172 		 * of safety by using if_simloop().
2173 		 */
2174 #if 1 /* XXX */
2175 		if (dst->sin_family != AF_INET) {
2176 			kprintf("ip_mloopback: bad address family %d\n",
2177 						dst->sin_family);
2178 			dst->sin_family = AF_INET;
2179 		}
2180 #endif
2181 		if_simloop(ifp, copym, dst->sin_family, 0);
2182 	}
2183 }
2184