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