xref: /netbsd-src/sys/netinet/ip_output.c (revision 9aa0541bdf64142d9a27c2cf274394d60182818f)
1 /*	$NetBSD: ip_output.c,v 1.209 2011/07/17 20:54:53 joerg Exp $	*/
2 
3 /*
4  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the project nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 /*-
33  * Copyright (c) 1998 The NetBSD Foundation, Inc.
34  * All rights reserved.
35  *
36  * This code is derived from software contributed to The NetBSD Foundation
37  * by Public Access Networks Corporation ("Panix").  It was developed under
38  * contract to Panix by Eric Haszlakiewicz and Thor Lancelot Simon.
39  *
40  * Redistribution and use in source and binary forms, with or without
41  * modification, are permitted provided that the following conditions
42  * are met:
43  * 1. Redistributions of source code must retain the above copyright
44  *    notice, this list of conditions and the following disclaimer.
45  * 2. Redistributions in binary form must reproduce the above copyright
46  *    notice, this list of conditions and the following disclaimer in the
47  *    documentation and/or other materials provided with the distribution.
48  *
49  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
50  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
51  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
52  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
53  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
54  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
55  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
56  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
57  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
58  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
59  * POSSIBILITY OF SUCH DAMAGE.
60  */
61 
62 /*
63  * Copyright (c) 1982, 1986, 1988, 1990, 1993
64  *	The Regents of the University of California.  All rights reserved.
65  *
66  * Redistribution and use in source and binary forms, with or without
67  * modification, are permitted provided that the following conditions
68  * are met:
69  * 1. Redistributions of source code must retain the above copyright
70  *    notice, this list of conditions and the following disclaimer.
71  * 2. Redistributions in binary form must reproduce the above copyright
72  *    notice, this list of conditions and the following disclaimer in the
73  *    documentation and/or other materials provided with the distribution.
74  * 3. Neither the name of the University nor the names of its contributors
75  *    may be used to endorse or promote products derived from this software
76  *    without specific prior written permission.
77  *
78  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
79  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
80  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
81  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
82  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
83  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
84  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
85  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
86  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
87  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
88  * SUCH DAMAGE.
89  *
90  *	@(#)ip_output.c	8.3 (Berkeley) 1/21/94
91  */
92 
93 #include <sys/cdefs.h>
94 __KERNEL_RCSID(0, "$NetBSD: ip_output.c,v 1.209 2011/07/17 20:54:53 joerg Exp $");
95 
96 #include "opt_pfil_hooks.h"
97 #include "opt_inet.h"
98 #include "opt_ipsec.h"
99 #include "opt_mrouting.h"
100 
101 #include <sys/param.h>
102 #include <sys/malloc.h>
103 #include <sys/mbuf.h>
104 #include <sys/errno.h>
105 #include <sys/protosw.h>
106 #include <sys/socket.h>
107 #include <sys/socketvar.h>
108 #include <sys/kauth.h>
109 #ifdef FAST_IPSEC
110 #include <sys/domain.h>
111 #endif
112 #include <sys/systm.h>
113 #include <sys/proc.h>
114 
115 #include <net/if.h>
116 #include <net/route.h>
117 #include <net/pfil.h>
118 
119 #include <netinet/in.h>
120 #include <netinet/in_systm.h>
121 #include <netinet/ip.h>
122 #include <netinet/in_pcb.h>
123 #include <netinet/in_var.h>
124 #include <netinet/ip_var.h>
125 #include <netinet/ip_private.h>
126 #include <netinet/in_offload.h>
127 
128 #ifdef MROUTING
129 #include <netinet/ip_mroute.h>
130 #endif
131 
132 #ifdef IPSEC
133 #include <netinet6/ipsec.h>
134 #include <netinet6/ipsec_private.h>
135 #include <netkey/key.h>
136 #include <netkey/key_debug.h>
137 #endif /*IPSEC*/
138 
139 #ifdef FAST_IPSEC
140 #include <netipsec/ipsec.h>
141 #include <netipsec/key.h>
142 #include <netipsec/xform.h>
143 #endif	/* FAST_IPSEC*/
144 
145 #ifdef IPSEC_NAT_T
146 #include <netinet/udp.h>
147 #endif
148 
149 static struct mbuf *ip_insertoptions(struct mbuf *, struct mbuf *, int *);
150 static struct ifnet *ip_multicast_if(struct in_addr *, int *);
151 static void ip_mloopback(struct ifnet *, struct mbuf *,
152     const struct sockaddr_in *);
153 
154 #ifdef PFIL_HOOKS
155 extern struct pfil_head inet_pfil_hook;			/* XXX */
156 #endif
157 
158 int	ip_do_loopback_cksum = 0;
159 
160 /*
161  * IP output.  The packet in mbuf chain m contains a skeletal IP
162  * header (with len, off, ttl, proto, tos, src, dst).
163  * The mbuf chain containing the packet will be freed.
164  * The mbuf opt, if present, will not be freed.
165  */
166 int
167 ip_output(struct mbuf *m0, ...)
168 {
169 	struct rtentry *rt;
170 	struct ip *ip;
171 	struct ifnet *ifp;
172 	struct mbuf *m = m0;
173 	int hlen = sizeof (struct ip);
174 	int len, error = 0;
175 	struct route iproute;
176 	const struct sockaddr_in *dst;
177 	struct in_ifaddr *ia;
178 	struct ifaddr *xifa;
179 	struct mbuf *opt;
180 	struct route *ro;
181 	int flags, sw_csum;
182 	int *mtu_p;
183 	u_long mtu;
184 	struct ip_moptions *imo;
185 	struct socket *so;
186 	va_list ap;
187 #ifdef IPSEC_NAT_T
188 	int natt_frag = 0;
189 #endif
190 #ifdef IPSEC
191 	struct secpolicy *sp = NULL;
192 #endif /*IPSEC*/
193 #ifdef FAST_IPSEC
194 	struct inpcb *inp;
195 	struct secpolicy *sp = NULL;
196 	int s;
197 #endif
198 	u_int16_t ip_len;
199 	union {
200 		struct sockaddr		dst;
201 		struct sockaddr_in	dst4;
202 	} u;
203 	struct sockaddr *rdst = &u.dst;	/* real IP destination, as opposed
204 					 * to the nexthop
205 					 */
206 
207 	len = 0;
208 	va_start(ap, m0);
209 	opt = va_arg(ap, struct mbuf *);
210 	ro = va_arg(ap, struct route *);
211 	flags = va_arg(ap, int);
212 	imo = va_arg(ap, struct ip_moptions *);
213 	so = va_arg(ap, struct socket *);
214 	if (flags & IP_RETURNMTU)
215 		mtu_p = va_arg(ap, int *);
216 	else
217 		mtu_p = NULL;
218 	va_end(ap);
219 
220 	MCLAIM(m, &ip_tx_mowner);
221 #ifdef FAST_IPSEC
222 	if (so != NULL && so->so_proto->pr_domain->dom_family == AF_INET)
223 		inp = (struct inpcb *)so->so_pcb;
224 	else
225 		inp = NULL;
226 #endif /* FAST_IPSEC */
227 
228 #ifdef	DIAGNOSTIC
229 	if ((m->m_flags & M_PKTHDR) == 0)
230 		panic("ip_output: no HDR");
231 
232 	if ((m->m_pkthdr.csum_flags & (M_CSUM_TCPv6|M_CSUM_UDPv6)) != 0) {
233 		panic("ip_output: IPv6 checksum offload flags: %d",
234 		    m->m_pkthdr.csum_flags);
235 	}
236 
237 	if ((m->m_pkthdr.csum_flags & (M_CSUM_TCPv4|M_CSUM_UDPv4)) ==
238 	    (M_CSUM_TCPv4|M_CSUM_UDPv4)) {
239 		panic("ip_output: conflicting checksum offload flags: %d",
240 		    m->m_pkthdr.csum_flags);
241 	}
242 #endif
243 	if (opt) {
244 		m = ip_insertoptions(m, opt, &len);
245 		if (len >= sizeof(struct ip))
246 			hlen = len;
247 	}
248 	ip = mtod(m, struct ip *);
249 	/*
250 	 * Fill in IP header.
251 	 */
252 	if ((flags & (IP_FORWARDING|IP_RAWOUTPUT)) == 0) {
253 		ip->ip_v = IPVERSION;
254 		ip->ip_off = htons(0);
255 		/* ip->ip_id filled in after we find out source ia */
256 		ip->ip_hl = hlen >> 2;
257 		IP_STATINC(IP_STAT_LOCALOUT);
258 	} else {
259 		hlen = ip->ip_hl << 2;
260 	}
261 	/*
262 	 * Route packet.
263 	 */
264 	memset(&iproute, 0, sizeof(iproute));
265 	if (ro == NULL)
266 		ro = &iproute;
267 	sockaddr_in_init(&u.dst4, &ip->ip_dst, 0);
268 	dst = satocsin(rtcache_getdst(ro));
269 	/*
270 	 * If there is a cached route,
271 	 * check that it is to the same destination
272 	 * and is still up.  If not, free it and try again.
273 	 * The address family should also be checked in case of sharing the
274 	 * cache with IPv6.
275 	 */
276 	if (dst == NULL)
277 		;
278 	else if (dst->sin_family != AF_INET ||
279 		 !in_hosteq(dst->sin_addr, ip->ip_dst))
280 		rtcache_free(ro);
281 
282 	if ((rt = rtcache_validate(ro)) == NULL &&
283 	    (rt = rtcache_update(ro, 1)) == NULL) {
284 		dst = &u.dst4;
285 		rtcache_setdst(ro, &u.dst);
286 	}
287 	/*
288 	 * If routing to interface only,
289 	 * short circuit routing lookup.
290 	 */
291 	if (flags & IP_ROUTETOIF) {
292 		if ((ia = ifatoia(ifa_ifwithladdr(sintocsa(dst)))) == NULL) {
293 			IP_STATINC(IP_STAT_NOROUTE);
294 			error = ENETUNREACH;
295 			goto bad;
296 		}
297 		ifp = ia->ia_ifp;
298 		mtu = ifp->if_mtu;
299 		ip->ip_ttl = 1;
300 	} else if ((IN_MULTICAST(ip->ip_dst.s_addr) ||
301 	    ip->ip_dst.s_addr == INADDR_BROADCAST) &&
302 	    imo != NULL && imo->imo_multicast_ifp != NULL) {
303 		ifp = imo->imo_multicast_ifp;
304 		mtu = ifp->if_mtu;
305 		IFP_TO_IA(ifp, ia);
306 	} else {
307 		if (rt == NULL)
308 			rt = rtcache_init(ro);
309 		if (rt == NULL) {
310 			IP_STATINC(IP_STAT_NOROUTE);
311 			error = EHOSTUNREACH;
312 			goto bad;
313 		}
314 		ia = ifatoia(rt->rt_ifa);
315 		ifp = rt->rt_ifp;
316 		if ((mtu = rt->rt_rmx.rmx_mtu) == 0)
317 			mtu = ifp->if_mtu;
318 		rt->rt_use++;
319 		if (rt->rt_flags & RTF_GATEWAY)
320 			dst = satosin(rt->rt_gateway);
321 	}
322 	if (IN_MULTICAST(ip->ip_dst.s_addr) ||
323 	    (ip->ip_dst.s_addr == INADDR_BROADCAST)) {
324 		struct in_multi *inm;
325 
326 		m->m_flags |= (ip->ip_dst.s_addr == INADDR_BROADCAST) ?
327 			M_BCAST : M_MCAST;
328 		/*
329 		 * See if the caller provided any multicast options
330 		 */
331 		if (imo != NULL)
332 			ip->ip_ttl = imo->imo_multicast_ttl;
333 		else
334 			ip->ip_ttl = IP_DEFAULT_MULTICAST_TTL;
335 
336 		/*
337 		 * if we don't know the outgoing ifp yet, we can't generate
338 		 * output
339 		 */
340 		if (!ifp) {
341 			IP_STATINC(IP_STAT_NOROUTE);
342 			error = ENETUNREACH;
343 			goto bad;
344 		}
345 
346 		/*
347 		 * If the packet is multicast or broadcast, confirm that
348 		 * the outgoing interface can transmit it.
349 		 */
350 		if (((m->m_flags & M_MCAST) &&
351 		     (ifp->if_flags & IFF_MULTICAST) == 0) ||
352 		    ((m->m_flags & M_BCAST) &&
353 		     (ifp->if_flags & (IFF_BROADCAST|IFF_POINTOPOINT)) == 0))  {
354 			IP_STATINC(IP_STAT_NOROUTE);
355 			error = ENETUNREACH;
356 			goto bad;
357 		}
358 		/*
359 		 * If source address not specified yet, use an address
360 		 * of outgoing interface.
361 		 */
362 		if (in_nullhost(ip->ip_src)) {
363 			struct in_ifaddr *xia;
364 
365 			IFP_TO_IA(ifp, xia);
366 			if (!xia) {
367 				error = EADDRNOTAVAIL;
368 				goto bad;
369 			}
370 			xifa = &xia->ia_ifa;
371 			if (xifa->ifa_getifa != NULL) {
372 				xia = ifatoia((*xifa->ifa_getifa)(xifa, rdst));
373 			}
374 			ip->ip_src = xia->ia_addr.sin_addr;
375 		}
376 
377 		IN_LOOKUP_MULTI(ip->ip_dst, ifp, inm);
378 		if (inm != NULL &&
379 		   (imo == NULL || imo->imo_multicast_loop)) {
380 			/*
381 			 * If we belong to the destination multicast group
382 			 * on the outgoing interface, and the caller did not
383 			 * forbid loopback, loop back a copy.
384 			 */
385 			ip_mloopback(ifp, m, &u.dst4);
386 		}
387 #ifdef MROUTING
388 		else {
389 			/*
390 			 * If we are acting as a multicast router, perform
391 			 * multicast forwarding as if the packet had just
392 			 * arrived on the interface to which we are about
393 			 * to send.  The multicast forwarding function
394 			 * recursively calls this function, using the
395 			 * IP_FORWARDING flag to prevent infinite recursion.
396 			 *
397 			 * Multicasts that are looped back by ip_mloopback(),
398 			 * above, will be forwarded by the ip_input() routine,
399 			 * if necessary.
400 			 */
401 			extern struct socket *ip_mrouter;
402 
403 			if (ip_mrouter && (flags & IP_FORWARDING) == 0) {
404 				if (ip_mforward(m, ifp) != 0) {
405 					m_freem(m);
406 					goto done;
407 				}
408 			}
409 		}
410 #endif
411 		/*
412 		 * Multicasts with a time-to-live of zero may be looped-
413 		 * back, above, but must not be transmitted on a network.
414 		 * Also, multicasts addressed to the loopback interface
415 		 * are not sent -- the above call to ip_mloopback() will
416 		 * loop back a copy if this host actually belongs to the
417 		 * destination group on the loopback interface.
418 		 */
419 		if (ip->ip_ttl == 0 || (ifp->if_flags & IFF_LOOPBACK) != 0) {
420 			m_freem(m);
421 			goto done;
422 		}
423 
424 		goto sendit;
425 	}
426 	/*
427 	 * If source address not specified yet, use address
428 	 * of outgoing interface.
429 	 */
430 	if (in_nullhost(ip->ip_src)) {
431 		xifa = &ia->ia_ifa;
432 		if (xifa->ifa_getifa != NULL)
433 			ia = ifatoia((*xifa->ifa_getifa)(xifa, rdst));
434 		ip->ip_src = ia->ia_addr.sin_addr;
435 	}
436 
437 	/*
438 	 * packets with Class-D address as source are not valid per
439 	 * RFC 1112
440 	 */
441 	if (IN_MULTICAST(ip->ip_src.s_addr)) {
442 		IP_STATINC(IP_STAT_ODROPPED);
443 		error = EADDRNOTAVAIL;
444 		goto bad;
445 	}
446 
447 	/*
448 	 * Look for broadcast address and
449 	 * and verify user is allowed to send
450 	 * such a packet.
451 	 */
452 	if (in_broadcast(dst->sin_addr, ifp)) {
453 		if ((ifp->if_flags & IFF_BROADCAST) == 0) {
454 			error = EADDRNOTAVAIL;
455 			goto bad;
456 		}
457 		if ((flags & IP_ALLOWBROADCAST) == 0) {
458 			error = EACCES;
459 			goto bad;
460 		}
461 		/* don't allow broadcast messages to be fragmented */
462 		if (ntohs(ip->ip_len) > ifp->if_mtu) {
463 			error = EMSGSIZE;
464 			goto bad;
465 		}
466 		m->m_flags |= M_BCAST;
467 	} else
468 		m->m_flags &= ~M_BCAST;
469 
470 sendit:
471 	if ((flags & (IP_FORWARDING|IP_NOIPNEWID)) == 0) {
472 		if (m->m_pkthdr.len < IP_MINFRAGSIZE) {
473 			ip->ip_id = 0;
474 		} else if ((m->m_pkthdr.csum_flags & M_CSUM_TSOv4) == 0) {
475 			ip->ip_id = ip_newid(ia);
476 		} else {
477 
478 			/*
479 			 * TSO capable interfaces (typically?) increment
480 			 * ip_id for each segment.
481 			 * "allocate" enough ids here to increase the chance
482 			 * for them to be unique.
483 			 *
484 			 * note that the following calculation is not
485 			 * needed to be precise.  wasting some ip_id is fine.
486 			 */
487 
488 			unsigned int segsz = m->m_pkthdr.segsz;
489 			unsigned int datasz = ntohs(ip->ip_len) - hlen;
490 			unsigned int num = howmany(datasz, segsz);
491 
492 			ip->ip_id = ip_newid_range(ia, num);
493 		}
494 	}
495 	/*
496 	 * If we're doing Path MTU Discovery, we need to set DF unless
497 	 * the route's MTU is locked.
498 	 */
499 	if ((flags & IP_MTUDISC) != 0 && rt != NULL &&
500 	    (rt->rt_rmx.rmx_locks & RTV_MTU) == 0)
501 		ip->ip_off |= htons(IP_DF);
502 
503 	/* Remember the current ip_len */
504 	ip_len = ntohs(ip->ip_len);
505 
506 #ifdef IPSEC
507 	/* get SP for this packet */
508 	if (so == NULL)
509 		sp = ipsec4_getpolicybyaddr(m, IPSEC_DIR_OUTBOUND,
510 		    flags, &error);
511 	else {
512 		if (IPSEC_PCB_SKIP_IPSEC(sotoinpcb_hdr(so)->inph_sp,
513 					 IPSEC_DIR_OUTBOUND))
514 			goto skip_ipsec;
515 		sp = ipsec4_getpolicybysock(m, IPSEC_DIR_OUTBOUND, so, &error);
516 	}
517 
518 	if (sp == NULL) {
519 		IPSEC_STATINC(IPSEC_STAT_IN_INVAL);
520 		goto bad;
521 	}
522 
523 	error = 0;
524 
525 	/* check policy */
526 	switch (sp->policy) {
527 	case IPSEC_POLICY_DISCARD:
528 		/*
529 		 * This packet is just discarded.
530 		 */
531 		IPSEC_STATINC(IPSEC_STAT_OUT_POLVIO);
532 		goto bad;
533 
534 	case IPSEC_POLICY_BYPASS:
535 	case IPSEC_POLICY_NONE:
536 		/* no need to do IPsec. */
537 		goto skip_ipsec;
538 
539 	case IPSEC_POLICY_IPSEC:
540 		if (sp->req == NULL) {
541 			/* XXX should be panic ? */
542 			printf("ip_output: No IPsec request specified.\n");
543 			error = EINVAL;
544 			goto bad;
545 		}
546 		break;
547 
548 	case IPSEC_POLICY_ENTRUST:
549 	default:
550 		printf("ip_output: Invalid policy found. %d\n", sp->policy);
551 	}
552 
553 #ifdef IPSEC_NAT_T
554 	/*
555 	 * NAT-T ESP fragmentation: don't do IPSec processing now,
556 	 * we'll do it on each fragmented packet.
557 	 */
558 	if (sp->req->sav &&
559 	    ((sp->req->sav->natt_type & UDP_ENCAP_ESPINUDP) ||
560 	     (sp->req->sav->natt_type & UDP_ENCAP_ESPINUDP_NON_IKE))) {
561 		if (ntohs(ip->ip_len) > sp->req->sav->esp_frag) {
562 			natt_frag = 1;
563 			mtu = sp->req->sav->esp_frag;
564 			goto skip_ipsec;
565 		}
566 	}
567 #endif /* IPSEC_NAT_T */
568 
569 	/*
570 	 * ipsec4_output() expects ip_len and ip_off in network
571 	 * order.  They have been set to network order above.
572 	 */
573 
574     {
575 	struct ipsec_output_state state;
576 	memset(&state, 0, sizeof(state));
577 	state.m = m;
578 	if (flags & IP_ROUTETOIF) {
579 		state.ro = &iproute;
580 		memset(&iproute, 0, sizeof(iproute));
581 	} else
582 		state.ro = ro;
583 	state.dst = sintocsa(dst);
584 
585 	/*
586 	 * We can't defer the checksum of payload data if
587 	 * we're about to encrypt/authenticate it.
588 	 *
589 	 * XXX When we support crypto offloading functions of
590 	 * XXX network interfaces, we need to reconsider this,
591 	 * XXX since it's likely that they'll support checksumming,
592 	 * XXX as well.
593 	 */
594 	if (m->m_pkthdr.csum_flags & (M_CSUM_TCPv4|M_CSUM_UDPv4)) {
595 		in_delayed_cksum(m);
596 		m->m_pkthdr.csum_flags &= ~(M_CSUM_TCPv4|M_CSUM_UDPv4);
597 	}
598 
599 	error = ipsec4_output(&state, sp, flags);
600 
601 	m = state.m;
602 	if (flags & IP_ROUTETOIF) {
603 		/*
604 		 * if we have tunnel mode SA, we may need to ignore
605 		 * IP_ROUTETOIF.
606 		 */
607 		if (state.ro != &iproute ||
608 		    rtcache_validate(state.ro) != NULL) {
609 			flags &= ~IP_ROUTETOIF;
610 			ro = state.ro;
611 		}
612 	} else
613 		ro = state.ro;
614 	dst = satocsin(state.dst);
615 	if (error) {
616 		/* mbuf is already reclaimed in ipsec4_output. */
617 		m0 = NULL;
618 		switch (error) {
619 		case EHOSTUNREACH:
620 		case ENETUNREACH:
621 		case EMSGSIZE:
622 		case ENOBUFS:
623 		case ENOMEM:
624 			break;
625 		default:
626 			printf("ip4_output (ipsec): error code %d\n", error);
627 			/*fall through*/
628 		case ENOENT:
629 			/* don't show these error codes to the user */
630 			error = 0;
631 			break;
632 		}
633 		goto bad;
634 	}
635 
636 	/* be sure to update variables that are affected by ipsec4_output() */
637 	ip = mtod(m, struct ip *);
638 	hlen = ip->ip_hl << 2;
639 	ip_len = ntohs(ip->ip_len);
640 
641 	if ((rt = rtcache_validate(ro)) == NULL) {
642 		if ((flags & IP_ROUTETOIF) == 0) {
643 			printf("ip_output: "
644 				"can't update route after IPsec processing\n");
645 			error = EHOSTUNREACH;	/*XXX*/
646 			goto bad;
647 		}
648 	} else {
649 		/* nobody uses ia beyond here */
650 		if (state.encap) {
651 			ifp = rt->rt_ifp;
652 			if ((mtu = rt->rt_rmx.rmx_mtu) == 0)
653 				mtu = ifp->if_mtu;
654 		}
655 	}
656     }
657 skip_ipsec:
658 #endif /*IPSEC*/
659 #ifdef FAST_IPSEC
660 	/*
661 	 * Check the security policy (SP) for the packet and, if
662 	 * required, do IPsec-related processing.  There are two
663 	 * cases here; the first time a packet is sent through
664 	 * it will be untagged and handled by ipsec4_checkpolicy.
665 	 * If the packet is resubmitted to ip_output (e.g. after
666 	 * AH, ESP, etc. processing), there will be a tag to bypass
667 	 * the lookup and related policy checking.
668 	 */
669 	if (!ipsec_outdone(m)) {
670 		s = splsoftnet();
671 		if (inp != NULL &&
672 		    IPSEC_PCB_SKIP_IPSEC(inp->inp_sp, IPSEC_DIR_OUTBOUND)) {
673 			splx(s);
674 			goto spd_done;
675 		}
676 		sp = ipsec4_checkpolicy(m, IPSEC_DIR_OUTBOUND, flags,
677 				&error, inp);
678 		/*
679 		 * There are four return cases:
680 		 *    sp != NULL	 	    apply IPsec policy
681 		 *    sp == NULL, error == 0	    no IPsec handling needed
682 		 *    sp == NULL, error == -EINVAL  discard packet w/o error
683 		 *    sp == NULL, error != 0	    discard packet, report error
684 		 */
685 		if (sp != NULL) {
686 #ifdef IPSEC_NAT_T
687 			/*
688 			 * NAT-T ESP fragmentation: don't do IPSec processing now,
689 			 * we'll do it on each fragmented packet.
690 			 */
691 			if (sp->req->sav &&
692 					((sp->req->sav->natt_type & UDP_ENCAP_ESPINUDP) ||
693 					 (sp->req->sav->natt_type & UDP_ENCAP_ESPINUDP_NON_IKE))) {
694 				if (ntohs(ip->ip_len) > sp->req->sav->esp_frag) {
695 					natt_frag = 1;
696 					mtu = sp->req->sav->esp_frag;
697 					splx(s);
698 					goto spd_done;
699 				}
700 			}
701 #endif /* IPSEC_NAT_T */
702 
703 			/*
704 			 * Do delayed checksums now because we send before
705 			 * this is done in the normal processing path.
706 			 */
707 			if (m->m_pkthdr.csum_flags & (M_CSUM_TCPv4|M_CSUM_UDPv4)) {
708 				in_delayed_cksum(m);
709 				m->m_pkthdr.csum_flags &= ~(M_CSUM_TCPv4|M_CSUM_UDPv4);
710 			}
711 
712 #ifdef __FreeBSD__
713 			ip->ip_len = htons(ip->ip_len);
714 			ip->ip_off = htons(ip->ip_off);
715 #endif
716 
717 			/* NB: callee frees mbuf */
718 			error = ipsec4_process_packet(m, sp->req, flags, 0);
719 			/*
720 			 * Preserve KAME behaviour: ENOENT can be returned
721 			 * when an SA acquire is in progress.  Don't propagate
722 			 * this to user-level; it confuses applications.
723 			 *
724 			 * XXX this will go away when the SADB is redone.
725 			 */
726 			if (error == ENOENT)
727 				error = 0;
728 			splx(s);
729 			goto done;
730 		} else {
731 			splx(s);
732 
733 			if (error != 0) {
734 				/*
735 				 * Hack: -EINVAL is used to signal that a packet
736 				 * should be silently discarded.  This is typically
737 				 * because we asked key management for an SA and
738 				 * it was delayed (e.g. kicked up to IKE).
739 				 */
740 				if (error == -EINVAL)
741 					error = 0;
742 				goto bad;
743 			} else {
744 				/* No IPsec processing for this packet. */
745 			}
746 		}
747 	}
748 spd_done:
749 #endif /* FAST_IPSEC */
750 
751 #ifdef PFIL_HOOKS
752 	/*
753 	 * Run through list of hooks for output packets.
754 	 */
755 	if ((error = pfil_run_hooks(&inet_pfil_hook, &m, ifp, PFIL_OUT)) != 0)
756 		goto done;
757 	if (m == NULL)
758 		goto done;
759 
760 	ip = mtod(m, struct ip *);
761 	hlen = ip->ip_hl << 2;
762 	ip_len = ntohs(ip->ip_len);
763 #endif /* PFIL_HOOKS */
764 
765 	m->m_pkthdr.csum_data |= hlen << 16;
766 
767 #if IFA_STATS
768 	/*
769 	 * search for the source address structure to
770 	 * maintain output statistics.
771 	 */
772 	INADDR_TO_IA(ip->ip_src, ia);
773 #endif
774 
775 	/* Maybe skip checksums on loopback interfaces. */
776 	if (IN_NEED_CHECKSUM(ifp, M_CSUM_IPv4)) {
777 		m->m_pkthdr.csum_flags |= M_CSUM_IPv4;
778 	}
779 	sw_csum = m->m_pkthdr.csum_flags & ~ifp->if_csum_flags_tx;
780 	/*
781 	 * If small enough for mtu of path, or if using TCP segmentation
782 	 * offload, can just send directly.
783 	 */
784 	if (ip_len <= mtu ||
785 	    (m->m_pkthdr.csum_flags & M_CSUM_TSOv4) != 0) {
786 #if IFA_STATS
787 		if (ia)
788 			ia->ia_ifa.ifa_data.ifad_outbytes += ip_len;
789 #endif
790 		/*
791 		 * Always initialize the sum to 0!  Some HW assisted
792 		 * checksumming requires this.
793 		 */
794 		ip->ip_sum = 0;
795 
796 		if ((m->m_pkthdr.csum_flags & M_CSUM_TSOv4) == 0) {
797 			/*
798 			 * Perform any checksums that the hardware can't do
799 			 * for us.
800 			 *
801 			 * XXX Does any hardware require the {th,uh}_sum
802 			 * XXX fields to be 0?
803 			 */
804 			if (sw_csum & M_CSUM_IPv4) {
805 				KASSERT(IN_NEED_CHECKSUM(ifp, M_CSUM_IPv4));
806 				ip->ip_sum = in_cksum(m, hlen);
807 				m->m_pkthdr.csum_flags &= ~M_CSUM_IPv4;
808 			}
809 			if (sw_csum & (M_CSUM_TCPv4|M_CSUM_UDPv4)) {
810 				if (IN_NEED_CHECKSUM(ifp,
811 				    sw_csum & (M_CSUM_TCPv4|M_CSUM_UDPv4))) {
812 					in_delayed_cksum(m);
813 				}
814 				m->m_pkthdr.csum_flags &=
815 				    ~(M_CSUM_TCPv4|M_CSUM_UDPv4);
816 			}
817 		}
818 
819 #ifdef IPSEC
820 		/* clean ipsec history once it goes out of the node */
821 		ipsec_delaux(m);
822 #endif
823 
824 		if (__predict_true(
825 		    (m->m_pkthdr.csum_flags & M_CSUM_TSOv4) == 0 ||
826 		    (ifp->if_capenable & IFCAP_TSOv4) != 0)) {
827 			KERNEL_LOCK(1, NULL);
828 			error =
829 			    (*ifp->if_output)(ifp, m,
830 				(m->m_flags & M_MCAST) ?
831 				    sintocsa(rdst) : sintocsa(dst),
832 				rt);
833 			KERNEL_UNLOCK_ONE(NULL);
834 		} else {
835 			error =
836 			    ip_tso_output(ifp, m,
837 				(m->m_flags & M_MCAST) ?
838 				    sintocsa(rdst) : sintocsa(dst),
839 				rt);
840 		}
841 		goto done;
842 	}
843 
844 	/*
845 	 * We can't use HW checksumming if we're about to
846 	 * to fragment the packet.
847 	 *
848 	 * XXX Some hardware can do this.
849 	 */
850 	if (m->m_pkthdr.csum_flags & (M_CSUM_TCPv4|M_CSUM_UDPv4)) {
851 		if (IN_NEED_CHECKSUM(ifp,
852 		    m->m_pkthdr.csum_flags & (M_CSUM_TCPv4|M_CSUM_UDPv4))) {
853 			in_delayed_cksum(m);
854 		}
855 		m->m_pkthdr.csum_flags &= ~(M_CSUM_TCPv4|M_CSUM_UDPv4);
856 	}
857 
858 	/*
859 	 * Too large for interface; fragment if possible.
860 	 * Must be able to put at least 8 bytes per fragment.
861 	 */
862 	if (ntohs(ip->ip_off) & IP_DF) {
863 		if (flags & IP_RETURNMTU)
864 			*mtu_p = mtu;
865 		error = EMSGSIZE;
866 		IP_STATINC(IP_STAT_CANTFRAG);
867 		goto bad;
868 	}
869 
870 	error = ip_fragment(m, ifp, mtu);
871 	if (error) {
872 		m = NULL;
873 		goto bad;
874 	}
875 
876 	for (; m; m = m0) {
877 		m0 = m->m_nextpkt;
878 		m->m_nextpkt = 0;
879 		if (error == 0) {
880 #if IFA_STATS
881 			if (ia)
882 				ia->ia_ifa.ifa_data.ifad_outbytes +=
883 				    ntohs(ip->ip_len);
884 #endif
885 #ifdef IPSEC
886 			/* clean ipsec history once it goes out of the node */
887 			ipsec_delaux(m);
888 #endif /* IPSEC */
889 
890 #ifdef IPSEC_NAT_T
891 			/*
892 			 * If we get there, the packet has not been handeld by
893 			 * IPSec whereas it should have. Now that it has been
894 			 * fragmented, re-inject it in ip_output so that IPsec
895 			 * processing can occur.
896 			 */
897 			if (natt_frag) {
898 				error = ip_output(m, opt,
899 				    ro, flags, imo, so, mtu_p);
900 			} else
901 #endif /* IPSEC_NAT_T */
902 			{
903 				KASSERT((m->m_pkthdr.csum_flags &
904 				    (M_CSUM_UDPv4 | M_CSUM_TCPv4)) == 0);
905 				KERNEL_LOCK(1, NULL);
906 				error = (*ifp->if_output)(ifp, m,
907 				    (m->m_flags & M_MCAST) ?
908 					sintocsa(rdst) : sintocsa(dst),
909 				    rt);
910 				KERNEL_UNLOCK_ONE(NULL);
911 			}
912 		} else
913 			m_freem(m);
914 	}
915 
916 	if (error == 0)
917 		IP_STATINC(IP_STAT_FRAGMENTED);
918 done:
919 	rtcache_free(&iproute);
920 
921 #ifdef IPSEC
922 	if (sp != NULL) {
923 		KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
924 			printf("DP ip_output call free SP:%p\n", sp));
925 		key_freesp(sp);
926 	}
927 #endif /* IPSEC */
928 #ifdef FAST_IPSEC
929 	if (sp != NULL)
930 		KEY_FREESP(&sp);
931 #endif /* FAST_IPSEC */
932 
933 	return (error);
934 bad:
935 	m_freem(m);
936 	goto done;
937 }
938 
939 int
940 ip_fragment(struct mbuf *m, struct ifnet *ifp, u_long mtu)
941 {
942 	struct ip *ip, *mhip;
943 	struct mbuf *m0;
944 	int len, hlen, off;
945 	int mhlen, firstlen;
946 	struct mbuf **mnext;
947 	int sw_csum = m->m_pkthdr.csum_flags;
948 	int fragments = 0;
949 	int s;
950 	int error = 0;
951 
952 	ip = mtod(m, struct ip *);
953 	hlen = ip->ip_hl << 2;
954 	if (ifp != NULL)
955 		sw_csum &= ~ifp->if_csum_flags_tx;
956 
957 	len = (mtu - hlen) &~ 7;
958 	if (len < 8) {
959 		m_freem(m);
960 		return (EMSGSIZE);
961 	}
962 
963 	firstlen = len;
964 	mnext = &m->m_nextpkt;
965 
966 	/*
967 	 * Loop through length of segment after first fragment,
968 	 * make new header and copy data of each part and link onto chain.
969 	 */
970 	m0 = m;
971 	mhlen = sizeof (struct ip);
972 	for (off = hlen + len; off < ntohs(ip->ip_len); off += len) {
973 		MGETHDR(m, M_DONTWAIT, MT_HEADER);
974 		if (m == 0) {
975 			error = ENOBUFS;
976 			IP_STATINC(IP_STAT_ODROPPED);
977 			goto sendorfree;
978 		}
979 		MCLAIM(m, m0->m_owner);
980 		*mnext = m;
981 		mnext = &m->m_nextpkt;
982 		m->m_data += max_linkhdr;
983 		mhip = mtod(m, struct ip *);
984 		*mhip = *ip;
985 		/* we must inherit MCAST and BCAST flags */
986 		m->m_flags |= m0->m_flags & (M_MCAST|M_BCAST);
987 		if (hlen > sizeof (struct ip)) {
988 			mhlen = ip_optcopy(ip, mhip) + sizeof (struct ip);
989 			mhip->ip_hl = mhlen >> 2;
990 		}
991 		m->m_len = mhlen;
992 		mhip->ip_off = ((off - hlen) >> 3) +
993 		    (ntohs(ip->ip_off) & ~IP_MF);
994 		if (ip->ip_off & htons(IP_MF))
995 			mhip->ip_off |= IP_MF;
996 		if (off + len >= ntohs(ip->ip_len))
997 			len = ntohs(ip->ip_len) - off;
998 		else
999 			mhip->ip_off |= IP_MF;
1000 		HTONS(mhip->ip_off);
1001 		mhip->ip_len = htons((u_int16_t)(len + mhlen));
1002 		m->m_next = m_copym(m0, off, len, M_DONTWAIT);
1003 		if (m->m_next == 0) {
1004 			error = ENOBUFS;	/* ??? */
1005 			IP_STATINC(IP_STAT_ODROPPED);
1006 			goto sendorfree;
1007 		}
1008 		m->m_pkthdr.len = mhlen + len;
1009 		m->m_pkthdr.rcvif = (struct ifnet *)0;
1010 		mhip->ip_sum = 0;
1011 		if (sw_csum & M_CSUM_IPv4) {
1012 			mhip->ip_sum = in_cksum(m, mhlen);
1013 			KASSERT((m->m_pkthdr.csum_flags & M_CSUM_IPv4) == 0);
1014 		} else {
1015 			m->m_pkthdr.csum_flags |= M_CSUM_IPv4;
1016 			m->m_pkthdr.csum_data |= mhlen << 16;
1017 		}
1018 		IP_STATINC(IP_STAT_OFRAGMENTS);
1019 		fragments++;
1020 	}
1021 	/*
1022 	 * Update first fragment by trimming what's been copied out
1023 	 * and updating header, then send each fragment (in order).
1024 	 */
1025 	m = m0;
1026 	m_adj(m, hlen + firstlen - ntohs(ip->ip_len));
1027 	m->m_pkthdr.len = hlen + firstlen;
1028 	ip->ip_len = htons((u_int16_t)m->m_pkthdr.len);
1029 	ip->ip_off |= htons(IP_MF);
1030 	ip->ip_sum = 0;
1031 	/*
1032 	 * We may not use checksums on loopback interfaces
1033 	 */
1034 	if (__predict_false(ifp == NULL) ||
1035 	    IN_NEED_CHECKSUM(ifp, M_CSUM_IPv4)) {
1036 		if (sw_csum & M_CSUM_IPv4) {
1037 			ip->ip_sum = in_cksum(m, hlen);
1038 			m->m_pkthdr.csum_flags &= ~M_CSUM_IPv4;
1039 		} else {
1040 			KASSERT(m->m_pkthdr.csum_flags & M_CSUM_IPv4);
1041 			KASSERT(M_CSUM_DATA_IPv4_IPHL(m->m_pkthdr.csum_data) >=
1042 				sizeof(struct ip));
1043 		}
1044 	}
1045 sendorfree:
1046 	/*
1047 	 * If there is no room for all the fragments, don't queue
1048 	 * any of them.
1049 	 */
1050 	if (ifp != NULL) {
1051 		s = splnet();
1052 		if (ifp->if_snd.ifq_maxlen - ifp->if_snd.ifq_len < fragments &&
1053 		    error == 0) {
1054 			error = ENOBUFS;
1055 			IP_STATINC(IP_STAT_ODROPPED);
1056 			IFQ_INC_DROPS(&ifp->if_snd);
1057 		}
1058 		splx(s);
1059 	}
1060 	if (error) {
1061 		for (m = m0; m; m = m0) {
1062 			m0 = m->m_nextpkt;
1063 			m->m_nextpkt = NULL;
1064 			m_freem(m);
1065 		}
1066 	}
1067 	return (error);
1068 }
1069 
1070 /*
1071  * Process a delayed payload checksum calculation.
1072  */
1073 void
1074 in_delayed_cksum(struct mbuf *m)
1075 {
1076 	struct ip *ip;
1077 	u_int16_t csum, offset;
1078 
1079 	ip = mtod(m, struct ip *);
1080 	offset = ip->ip_hl << 2;
1081 	csum = in4_cksum(m, 0, offset, ntohs(ip->ip_len) - offset);
1082 	if (csum == 0 && (m->m_pkthdr.csum_flags & M_CSUM_UDPv4) != 0)
1083 		csum = 0xffff;
1084 
1085 	offset += M_CSUM_DATA_IPv4_OFFSET(m->m_pkthdr.csum_data);
1086 
1087 	if ((offset + sizeof(u_int16_t)) > m->m_len) {
1088 		/* This happen when ip options were inserted
1089 		printf("in_delayed_cksum: pullup len %d off %d proto %d\n",
1090 		    m->m_len, offset, ip->ip_p);
1091 		 */
1092 		m_copyback(m, offset, sizeof(csum), (void *) &csum);
1093 	} else
1094 		*(u_int16_t *)(mtod(m, char *) + offset) = csum;
1095 }
1096 
1097 /*
1098  * Determine the maximum length of the options to be inserted;
1099  * we would far rather allocate too much space rather than too little.
1100  */
1101 
1102 u_int
1103 ip_optlen(struct inpcb *inp)
1104 {
1105 	struct mbuf *m = inp->inp_options;
1106 
1107 	if (m && m->m_len > offsetof(struct ipoption, ipopt_dst))
1108 		return (m->m_len - offsetof(struct ipoption, ipopt_dst));
1109 	else
1110 		return 0;
1111 }
1112 
1113 
1114 /*
1115  * Insert IP options into preformed packet.
1116  * Adjust IP destination as required for IP source routing,
1117  * as indicated by a non-zero in_addr at the start of the options.
1118  */
1119 static struct mbuf *
1120 ip_insertoptions(struct mbuf *m, struct mbuf *opt, int *phlen)
1121 {
1122 	struct ipoption *p = mtod(opt, struct ipoption *);
1123 	struct mbuf *n;
1124 	struct ip *ip = mtod(m, struct ip *);
1125 	unsigned optlen;
1126 
1127 	optlen = opt->m_len - sizeof(p->ipopt_dst);
1128 	if (optlen + ntohs(ip->ip_len) > IP_MAXPACKET)
1129 		return (m);		/* XXX should fail */
1130 	if (!in_nullhost(p->ipopt_dst))
1131 		ip->ip_dst = p->ipopt_dst;
1132 	if (M_READONLY(m) || M_LEADINGSPACE(m) < optlen) {
1133 		MGETHDR(n, M_DONTWAIT, MT_HEADER);
1134 		if (n == 0)
1135 			return (m);
1136 		MCLAIM(n, m->m_owner);
1137 		M_MOVE_PKTHDR(n, m);
1138 		m->m_len -= sizeof(struct ip);
1139 		m->m_data += sizeof(struct ip);
1140 		n->m_next = m;
1141 		m = n;
1142 		m->m_len = optlen + sizeof(struct ip);
1143 		m->m_data += max_linkhdr;
1144 		bcopy((void *)ip, mtod(m, void *), sizeof(struct ip));
1145 	} else {
1146 		m->m_data -= optlen;
1147 		m->m_len += optlen;
1148 		memmove(mtod(m, void *), ip, sizeof(struct ip));
1149 	}
1150 	m->m_pkthdr.len += optlen;
1151 	ip = mtod(m, struct ip *);
1152 	bcopy((void *)p->ipopt_list, (void *)(ip + 1), (unsigned)optlen);
1153 	*phlen = sizeof(struct ip) + optlen;
1154 	ip->ip_len = htons(ntohs(ip->ip_len) + optlen);
1155 	return (m);
1156 }
1157 
1158 /*
1159  * Copy options from ip to jp,
1160  * omitting those not copied during fragmentation.
1161  */
1162 int
1163 ip_optcopy(struct ip *ip, struct ip *jp)
1164 {
1165 	u_char *cp, *dp;
1166 	int opt, optlen, cnt;
1167 
1168 	cp = (u_char *)(ip + 1);
1169 	dp = (u_char *)(jp + 1);
1170 	cnt = (ip->ip_hl << 2) - sizeof (struct ip);
1171 	for (; cnt > 0; cnt -= optlen, cp += optlen) {
1172 		opt = cp[0];
1173 		if (opt == IPOPT_EOL)
1174 			break;
1175 		if (opt == IPOPT_NOP) {
1176 			/* Preserve for IP mcast tunnel's LSRR alignment. */
1177 			*dp++ = IPOPT_NOP;
1178 			optlen = 1;
1179 			continue;
1180 		}
1181 #ifdef DIAGNOSTIC
1182 		if (cnt < IPOPT_OLEN + sizeof(*cp))
1183 			panic("malformed IPv4 option passed to ip_optcopy");
1184 #endif
1185 		optlen = cp[IPOPT_OLEN];
1186 #ifdef DIAGNOSTIC
1187 		if (optlen < IPOPT_OLEN + sizeof(*cp) || optlen > cnt)
1188 			panic("malformed IPv4 option passed to ip_optcopy");
1189 #endif
1190 		/* bogus lengths should have been caught by ip_dooptions */
1191 		if (optlen > cnt)
1192 			optlen = cnt;
1193 		if (IPOPT_COPIED(opt)) {
1194 			bcopy((void *)cp, (void *)dp, (unsigned)optlen);
1195 			dp += optlen;
1196 		}
1197 	}
1198 	for (optlen = dp - (u_char *)(jp+1); optlen & 0x3; optlen++)
1199 		*dp++ = IPOPT_EOL;
1200 	return (optlen);
1201 }
1202 
1203 /*
1204  * IP socket option processing.
1205  */
1206 int
1207 ip_ctloutput(int op, struct socket *so, struct sockopt *sopt)
1208 {
1209 	struct inpcb *inp = sotoinpcb(so);
1210 	int optval = 0;
1211 	int error = 0;
1212 #if defined(IPSEC) || defined(FAST_IPSEC)
1213 	struct lwp *l = curlwp;	/*XXX*/
1214 #endif
1215 
1216 	if (sopt->sopt_level != IPPROTO_IP) {
1217 		if (sopt->sopt_level == SOL_SOCKET && sopt->sopt_name == SO_NOHEADER)
1218 			return 0;
1219 		return ENOPROTOOPT;
1220 	}
1221 
1222 	switch (op) {
1223 	case PRCO_SETOPT:
1224 		switch (sopt->sopt_name) {
1225 		case IP_OPTIONS:
1226 #ifdef notyet
1227 		case IP_RETOPTS:
1228 #endif
1229 			error = ip_pcbopts(&inp->inp_options, sopt);
1230 			break;
1231 
1232 		case IP_TOS:
1233 		case IP_TTL:
1234 		case IP_MINTTL:
1235 		case IP_RECVOPTS:
1236 		case IP_RECVRETOPTS:
1237 		case IP_RECVDSTADDR:
1238 		case IP_RECVIF:
1239 		case IP_RECVTTL:
1240 			error = sockopt_getint(sopt, &optval);
1241 			if (error)
1242 				break;
1243 
1244 			switch (sopt->sopt_name) {
1245 			case IP_TOS:
1246 				inp->inp_ip.ip_tos = optval;
1247 				break;
1248 
1249 			case IP_TTL:
1250 				inp->inp_ip.ip_ttl = optval;
1251 				break;
1252 
1253 			case IP_MINTTL:
1254 				if (optval > 0 && optval <= MAXTTL)
1255 					inp->inp_ip_minttl = optval;
1256 				else
1257 					error = EINVAL;
1258 				break;
1259 #define	OPTSET(bit) \
1260 	if (optval) \
1261 		inp->inp_flags |= bit; \
1262 	else \
1263 		inp->inp_flags &= ~bit;
1264 
1265 			case IP_RECVOPTS:
1266 				OPTSET(INP_RECVOPTS);
1267 				break;
1268 
1269 			case IP_RECVRETOPTS:
1270 				OPTSET(INP_RECVRETOPTS);
1271 				break;
1272 
1273 			case IP_RECVDSTADDR:
1274 				OPTSET(INP_RECVDSTADDR);
1275 				break;
1276 
1277 			case IP_RECVIF:
1278 				OPTSET(INP_RECVIF);
1279 				break;
1280 
1281 			case IP_RECVTTL:
1282 				OPTSET(INP_RECVTTL);
1283 				break;
1284 			}
1285 		break;
1286 #undef OPTSET
1287 
1288 		case IP_MULTICAST_IF:
1289 		case IP_MULTICAST_TTL:
1290 		case IP_MULTICAST_LOOP:
1291 		case IP_ADD_MEMBERSHIP:
1292 		case IP_DROP_MEMBERSHIP:
1293 			error = ip_setmoptions(&inp->inp_moptions, sopt);
1294 			break;
1295 
1296 		case IP_PORTRANGE:
1297 			error = sockopt_getint(sopt, &optval);
1298 			if (error)
1299 				break;
1300 
1301 			/* INP_LOCK(inp); */
1302 			switch (optval) {
1303 			case IP_PORTRANGE_DEFAULT:
1304 			case IP_PORTRANGE_HIGH:
1305 				inp->inp_flags &= ~(INP_LOWPORT);
1306 				break;
1307 
1308 			case IP_PORTRANGE_LOW:
1309 				inp->inp_flags |= INP_LOWPORT;
1310 				break;
1311 
1312 			default:
1313 				error = EINVAL;
1314 				break;
1315 			}
1316 			/* INP_UNLOCK(inp); */
1317 			break;
1318 
1319 #if defined(IPSEC) || defined(FAST_IPSEC)
1320 		case IP_IPSEC_POLICY:
1321 		    {
1322 			error = ipsec4_set_policy(inp, sopt->sopt_name,
1323 			    sopt->sopt_data, sopt->sopt_size, l->l_cred);
1324 			break;
1325 		    }
1326 #endif /*IPSEC*/
1327 
1328 		default:
1329 			error = ENOPROTOOPT;
1330 			break;
1331 		}
1332 		break;
1333 
1334 	case PRCO_GETOPT:
1335 		switch (sopt->sopt_name) {
1336 		case IP_OPTIONS:
1337 		case IP_RETOPTS:
1338 			if (inp->inp_options) {
1339 				struct mbuf *m;
1340 
1341 				m = m_copym(inp->inp_options, 0, M_COPYALL,
1342 				    M_DONTWAIT);
1343 				if (m == NULL) {
1344 					error = ENOBUFS;
1345 					break;
1346 				}
1347 
1348 				error = sockopt_setmbuf(sopt, m);
1349 			}
1350 			break;
1351 
1352 		case IP_TOS:
1353 		case IP_TTL:
1354 		case IP_MINTTL:
1355 		case IP_RECVOPTS:
1356 		case IP_RECVRETOPTS:
1357 		case IP_RECVDSTADDR:
1358 		case IP_RECVIF:
1359 		case IP_RECVTTL:
1360 		case IP_ERRORMTU:
1361 			switch (sopt->sopt_name) {
1362 			case IP_TOS:
1363 				optval = inp->inp_ip.ip_tos;
1364 				break;
1365 
1366 			case IP_TTL:
1367 				optval = inp->inp_ip.ip_ttl;
1368 				break;
1369 
1370 			case IP_MINTTL:
1371 				optval = inp->inp_ip_minttl;
1372 				break;
1373 
1374 			case IP_ERRORMTU:
1375 				optval = inp->inp_errormtu;
1376 				break;
1377 
1378 #define	OPTBIT(bit)	(inp->inp_flags & bit ? 1 : 0)
1379 
1380 			case IP_RECVOPTS:
1381 				optval = OPTBIT(INP_RECVOPTS);
1382 				break;
1383 
1384 			case IP_RECVRETOPTS:
1385 				optval = OPTBIT(INP_RECVRETOPTS);
1386 				break;
1387 
1388 			case IP_RECVDSTADDR:
1389 				optval = OPTBIT(INP_RECVDSTADDR);
1390 				break;
1391 
1392 			case IP_RECVIF:
1393 				optval = OPTBIT(INP_RECVIF);
1394 				break;
1395 
1396 			case IP_RECVTTL:
1397 				optval = OPTBIT(INP_RECVTTL);
1398 				break;
1399 			}
1400 			error = sockopt_setint(sopt, optval);
1401 			break;
1402 
1403 #if 0	/* defined(IPSEC) || defined(FAST_IPSEC) */
1404 		case IP_IPSEC_POLICY:
1405 		{
1406 			struct mbuf *m = NULL;
1407 
1408 			/* XXX this will return EINVAL as sopt is empty */
1409 			error = ipsec4_get_policy(inp, sopt->sopt_data,
1410 			    sopt->sopt_size, &m);
1411 			if (error == 0)
1412 				error = sockopt_setmbuf(sopt, m);
1413 			break;
1414 		}
1415 #endif /*IPSEC*/
1416 
1417 		case IP_MULTICAST_IF:
1418 		case IP_MULTICAST_TTL:
1419 		case IP_MULTICAST_LOOP:
1420 		case IP_ADD_MEMBERSHIP:
1421 		case IP_DROP_MEMBERSHIP:
1422 			error = ip_getmoptions(inp->inp_moptions, sopt);
1423 			break;
1424 
1425 		case IP_PORTRANGE:
1426 			if (inp->inp_flags & INP_LOWPORT)
1427 				optval = IP_PORTRANGE_LOW;
1428 			else
1429 				optval = IP_PORTRANGE_DEFAULT;
1430 
1431 			error = sockopt_setint(sopt, optval);
1432 
1433 			break;
1434 
1435 		default:
1436 			error = ENOPROTOOPT;
1437 			break;
1438 		}
1439 		break;
1440 	}
1441 	return (error);
1442 }
1443 
1444 /*
1445  * Set up IP options in pcb for insertion in output packets.
1446  * Store in mbuf with pointer in pcbopt, adding pseudo-option
1447  * with destination address if source routed.
1448  */
1449 int
1450 ip_pcbopts(struct mbuf **pcbopt, const struct sockopt *sopt)
1451 {
1452 	struct mbuf *m;
1453 	const u_char *cp;
1454 	u_char *dp;
1455 	int cnt;
1456 	uint8_t optval, olen, offset;
1457 
1458 	/* turn off any old options */
1459 	if (*pcbopt)
1460 		(void)m_free(*pcbopt);
1461 	*pcbopt = NULL;
1462 
1463 	cp = sopt->sopt_data;
1464 	cnt = sopt->sopt_size;
1465 
1466 	if (cnt == 0)
1467 		return (0);	/* Only turning off any previous options */
1468 
1469 #ifndef	__vax__
1470 	if (cnt % sizeof(int32_t))
1471 		return (EINVAL);
1472 #endif
1473 
1474 	m = m_get(M_DONTWAIT, MT_SOOPTS);
1475 	if (m == NULL)
1476 		return (ENOBUFS);
1477 
1478 	dp = mtod(m, u_char *);
1479 	memset(dp, 0, sizeof(struct in_addr));
1480 	dp += sizeof(struct in_addr);
1481 	m->m_len = sizeof(struct in_addr);
1482 
1483 	/*
1484 	 * IP option list according to RFC791. Each option is of the form
1485 	 *
1486 	 *	[optval] [olen] [(olen - 2) data bytes]
1487 	 *
1488 	 * we validate the list and copy options to an mbuf for prepending
1489 	 * to data packets. The IP first-hop destination address will be
1490 	 * stored before actual options and is zero if unset.
1491 	 */
1492 	while (cnt > 0) {
1493 		optval = cp[IPOPT_OPTVAL];
1494 
1495 		if (optval == IPOPT_EOL || optval == IPOPT_NOP) {
1496 			olen = 1;
1497 		} else {
1498 			if (cnt < IPOPT_OLEN + 1)
1499 				goto bad;
1500 
1501 			olen = cp[IPOPT_OLEN];
1502 			if (olen < IPOPT_OLEN + 1 || olen > cnt)
1503 				goto bad;
1504 		}
1505 
1506 		if (optval == IPOPT_LSRR || optval == IPOPT_SSRR) {
1507 			/*
1508 			 * user process specifies route as:
1509 			 *	->A->B->C->D
1510 			 * D must be our final destination (but we can't
1511 			 * check that since we may not have connected yet).
1512 			 * A is first hop destination, which doesn't appear in
1513 			 * actual IP option, but is stored before the options.
1514 			 */
1515 			if (olen < IPOPT_OFFSET + 1 + sizeof(struct in_addr))
1516 				goto bad;
1517 
1518 			offset = cp[IPOPT_OFFSET];
1519 			memcpy(mtod(m, u_char *), cp + IPOPT_OFFSET + 1,
1520 			    sizeof(struct in_addr));
1521 
1522 			cp += sizeof(struct in_addr);
1523 			cnt -= sizeof(struct in_addr);
1524 			olen -= sizeof(struct in_addr);
1525 
1526 			if (m->m_len + olen > MAX_IPOPTLEN + sizeof(struct in_addr))
1527 				goto bad;
1528 
1529 			memcpy(dp, cp, olen);
1530 			dp[IPOPT_OPTVAL] = optval;
1531 			dp[IPOPT_OLEN] = olen;
1532 			dp[IPOPT_OFFSET] = offset;
1533 			break;
1534 		} else {
1535 			if (m->m_len + olen > MAX_IPOPTLEN + sizeof(struct in_addr))
1536 				goto bad;
1537 
1538 			memcpy(dp, cp, olen);
1539 			break;
1540 		}
1541 
1542 		dp += olen;
1543 		m->m_len += olen;
1544 
1545 		if (optval == IPOPT_EOL)
1546 			break;
1547 
1548 		cp += olen;
1549 		cnt -= olen;
1550 	}
1551 
1552 	*pcbopt = m;
1553 	return (0);
1554 
1555 bad:
1556 	(void)m_free(m);
1557 	return (EINVAL);
1558 }
1559 
1560 /*
1561  * following RFC1724 section 3.3, 0.0.0.0/8 is interpreted as interface index.
1562  */
1563 static struct ifnet *
1564 ip_multicast_if(struct in_addr *a, int *ifindexp)
1565 {
1566 	int ifindex;
1567 	struct ifnet *ifp = NULL;
1568 	struct in_ifaddr *ia;
1569 
1570 	if (ifindexp)
1571 		*ifindexp = 0;
1572 	if (ntohl(a->s_addr) >> 24 == 0) {
1573 		ifindex = ntohl(a->s_addr) & 0xffffff;
1574 		if (ifindex < 0 || if_indexlim <= ifindex)
1575 			return NULL;
1576 		ifp = ifindex2ifnet[ifindex];
1577 		if (!ifp)
1578 			return NULL;
1579 		if (ifindexp)
1580 			*ifindexp = ifindex;
1581 	} else {
1582 		LIST_FOREACH(ia, &IN_IFADDR_HASH(a->s_addr), ia_hash) {
1583 			if (in_hosteq(ia->ia_addr.sin_addr, *a) &&
1584 			    (ia->ia_ifp->if_flags & IFF_MULTICAST) != 0) {
1585 				ifp = ia->ia_ifp;
1586 				break;
1587 			}
1588 		}
1589 	}
1590 	return ifp;
1591 }
1592 
1593 static int
1594 ip_getoptval(const struct sockopt *sopt, u_int8_t *val, u_int maxval)
1595 {
1596 	u_int tval;
1597 	u_char cval;
1598 	int error;
1599 
1600 	if (sopt == NULL)
1601 		return EINVAL;
1602 
1603 	switch (sopt->sopt_size) {
1604 	case sizeof(u_char):
1605 		error = sockopt_get(sopt, &cval, sizeof(u_char));
1606 		tval = cval;
1607 		break;
1608 
1609 	case sizeof(u_int):
1610 		error = sockopt_get(sopt, &tval, sizeof(u_int));
1611 		break;
1612 
1613 	default:
1614 		error = EINVAL;
1615 	}
1616 
1617 	if (error)
1618 		return error;
1619 
1620 	if (tval > maxval)
1621 		return EINVAL;
1622 
1623 	*val = tval;
1624 	return 0;
1625 }
1626 
1627 /*
1628  * Set the IP multicast options in response to user setsockopt().
1629  */
1630 int
1631 ip_setmoptions(struct ip_moptions **imop, const struct sockopt *sopt)
1632 {
1633 	int error = 0;
1634 	int i;
1635 	struct in_addr addr;
1636 	struct ip_mreq lmreq, *mreq;
1637 	struct ifnet *ifp;
1638 	struct ip_moptions *imo = *imop;
1639 	int ifindex;
1640 
1641 	if (imo == NULL) {
1642 		/*
1643 		 * No multicast option buffer attached to the pcb;
1644 		 * allocate one and initialize to default values.
1645 		 */
1646 		imo = malloc(sizeof(*imo), M_IPMOPTS, M_NOWAIT);
1647 		if (imo == NULL)
1648 			return (ENOBUFS);
1649 
1650 		*imop = imo;
1651 		imo->imo_multicast_ifp = NULL;
1652 		imo->imo_multicast_addr.s_addr = INADDR_ANY;
1653 		imo->imo_multicast_ttl = IP_DEFAULT_MULTICAST_TTL;
1654 		imo->imo_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
1655 		imo->imo_num_memberships = 0;
1656 	}
1657 
1658 	switch (sopt->sopt_name) {
1659 	case IP_MULTICAST_IF:
1660 		/*
1661 		 * Select the interface for outgoing multicast packets.
1662 		 */
1663 		error = sockopt_get(sopt, &addr, sizeof(addr));
1664 		if (error)
1665 			break;
1666 
1667 		/*
1668 		 * INADDR_ANY is used to remove a previous selection.
1669 		 * When no interface is selected, a default one is
1670 		 * chosen every time a multicast packet is sent.
1671 		 */
1672 		if (in_nullhost(addr)) {
1673 			imo->imo_multicast_ifp = NULL;
1674 			break;
1675 		}
1676 		/*
1677 		 * The selected interface is identified by its local
1678 		 * IP address.  Find the interface and confirm that
1679 		 * it supports multicasting.
1680 		 */
1681 		ifp = ip_multicast_if(&addr, &ifindex);
1682 		if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0) {
1683 			error = EADDRNOTAVAIL;
1684 			break;
1685 		}
1686 		imo->imo_multicast_ifp = ifp;
1687 		if (ifindex)
1688 			imo->imo_multicast_addr = addr;
1689 		else
1690 			imo->imo_multicast_addr.s_addr = INADDR_ANY;
1691 		break;
1692 
1693 	case IP_MULTICAST_TTL:
1694 		/*
1695 		 * Set the IP time-to-live for outgoing multicast packets.
1696 		 */
1697 		error = ip_getoptval(sopt, &imo->imo_multicast_ttl, MAXTTL);
1698 		break;
1699 
1700 	case IP_MULTICAST_LOOP:
1701 		/*
1702 		 * Set the loopback flag for outgoing multicast packets.
1703 		 * Must be zero or one.
1704 		 */
1705 		error = ip_getoptval(sopt, &imo->imo_multicast_loop, 1);
1706 		break;
1707 
1708 	case IP_ADD_MEMBERSHIP:
1709 		/*
1710 		 * Add a multicast group membership.
1711 		 * Group must be a valid IP multicast address.
1712 		 */
1713 		error = sockopt_get(sopt, &lmreq, sizeof(lmreq));
1714 		if (error)
1715 			break;
1716 
1717 		mreq = &lmreq;
1718 
1719 		if (!IN_MULTICAST(mreq->imr_multiaddr.s_addr)) {
1720 			error = EINVAL;
1721 			break;
1722 		}
1723 		/*
1724 		 * If no interface address was provided, use the interface of
1725 		 * the route to the given multicast address.
1726 		 */
1727 		if (in_nullhost(mreq->imr_interface)) {
1728 			struct rtentry *rt;
1729 			union {
1730 				struct sockaddr		dst;
1731 				struct sockaddr_in	dst4;
1732 			} u;
1733 			struct route ro;
1734 
1735 			memset(&ro, 0, sizeof(ro));
1736 
1737 			sockaddr_in_init(&u.dst4, &mreq->imr_multiaddr, 0);
1738 			rtcache_setdst(&ro, &u.dst);
1739 			ifp = (rt = rtcache_init(&ro)) != NULL ? rt->rt_ifp
1740 			                                        : NULL;
1741 			rtcache_free(&ro);
1742 		} else {
1743 			ifp = ip_multicast_if(&mreq->imr_interface, NULL);
1744 		}
1745 		/*
1746 		 * See if we found an interface, and confirm that it
1747 		 * supports multicast.
1748 		 */
1749 		if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0) {
1750 			error = EADDRNOTAVAIL;
1751 			break;
1752 		}
1753 		/*
1754 		 * See if the membership already exists or if all the
1755 		 * membership slots are full.
1756 		 */
1757 		for (i = 0; i < imo->imo_num_memberships; ++i) {
1758 			if (imo->imo_membership[i]->inm_ifp == ifp &&
1759 			    in_hosteq(imo->imo_membership[i]->inm_addr,
1760 				      mreq->imr_multiaddr))
1761 				break;
1762 		}
1763 		if (i < imo->imo_num_memberships) {
1764 			error = EADDRINUSE;
1765 			break;
1766 		}
1767 		if (i == IP_MAX_MEMBERSHIPS) {
1768 			error = ETOOMANYREFS;
1769 			break;
1770 		}
1771 		/*
1772 		 * Everything looks good; add a new record to the multicast
1773 		 * address list for the given interface.
1774 		 */
1775 		if ((imo->imo_membership[i] =
1776 		    in_addmulti(&mreq->imr_multiaddr, ifp)) == NULL) {
1777 			error = ENOBUFS;
1778 			break;
1779 		}
1780 		++imo->imo_num_memberships;
1781 		break;
1782 
1783 	case IP_DROP_MEMBERSHIP:
1784 		/*
1785 		 * Drop a multicast group membership.
1786 		 * Group must be a valid IP multicast address.
1787 		 */
1788 		error = sockopt_get(sopt, &lmreq, sizeof(lmreq));
1789 		if (error)
1790 			break;
1791 
1792 		mreq = &lmreq;
1793 
1794 		if (!IN_MULTICAST(mreq->imr_multiaddr.s_addr)) {
1795 			error = EINVAL;
1796 			break;
1797 		}
1798 		/*
1799 		 * If an interface address was specified, get a pointer
1800 		 * to its ifnet structure.
1801 		 */
1802 		if (in_nullhost(mreq->imr_interface))
1803 			ifp = NULL;
1804 		else {
1805 			ifp = ip_multicast_if(&mreq->imr_interface, NULL);
1806 			if (ifp == NULL) {
1807 				error = EADDRNOTAVAIL;
1808 				break;
1809 			}
1810 		}
1811 		/*
1812 		 * Find the membership in the membership array.
1813 		 */
1814 		for (i = 0; i < imo->imo_num_memberships; ++i) {
1815 			if ((ifp == NULL ||
1816 			     imo->imo_membership[i]->inm_ifp == ifp) &&
1817 			     in_hosteq(imo->imo_membership[i]->inm_addr,
1818 				       mreq->imr_multiaddr))
1819 				break;
1820 		}
1821 		if (i == imo->imo_num_memberships) {
1822 			error = EADDRNOTAVAIL;
1823 			break;
1824 		}
1825 		/*
1826 		 * Give up the multicast address record to which the
1827 		 * membership points.
1828 		 */
1829 		in_delmulti(imo->imo_membership[i]);
1830 		/*
1831 		 * Remove the gap in the membership array.
1832 		 */
1833 		for (++i; i < imo->imo_num_memberships; ++i)
1834 			imo->imo_membership[i-1] = imo->imo_membership[i];
1835 		--imo->imo_num_memberships;
1836 		break;
1837 
1838 	default:
1839 		error = EOPNOTSUPP;
1840 		break;
1841 	}
1842 
1843 	/*
1844 	 * If all options have default values, no need to keep the mbuf.
1845 	 */
1846 	if (imo->imo_multicast_ifp == NULL &&
1847 	    imo->imo_multicast_ttl == IP_DEFAULT_MULTICAST_TTL &&
1848 	    imo->imo_multicast_loop == IP_DEFAULT_MULTICAST_LOOP &&
1849 	    imo->imo_num_memberships == 0) {
1850 		free(*imop, M_IPMOPTS);
1851 		*imop = NULL;
1852 	}
1853 
1854 	return (error);
1855 }
1856 
1857 /*
1858  * Return the IP multicast options in response to user getsockopt().
1859  */
1860 int
1861 ip_getmoptions(struct ip_moptions *imo, struct sockopt *sopt)
1862 {
1863 	struct in_addr addr;
1864 	struct in_ifaddr *ia;
1865 	int error;
1866 	uint8_t optval;
1867 
1868 	error = 0;
1869 
1870 	switch (sopt->sopt_name) {
1871 	case IP_MULTICAST_IF:
1872 		if (imo == NULL || imo->imo_multicast_ifp == NULL)
1873 			addr = zeroin_addr;
1874 		else if (imo->imo_multicast_addr.s_addr) {
1875 			/* return the value user has set */
1876 			addr = imo->imo_multicast_addr;
1877 		} else {
1878 			IFP_TO_IA(imo->imo_multicast_ifp, ia);
1879 			addr = ia ? ia->ia_addr.sin_addr : zeroin_addr;
1880 		}
1881 		error = sockopt_set(sopt, &addr, sizeof(addr));
1882 		break;
1883 
1884 	case IP_MULTICAST_TTL:
1885 		optval = imo ? imo->imo_multicast_ttl
1886 			     : IP_DEFAULT_MULTICAST_TTL;
1887 
1888 		error = sockopt_set(sopt, &optval, sizeof(optval));
1889 		break;
1890 
1891 	case IP_MULTICAST_LOOP:
1892 		optval = imo ? imo->imo_multicast_loop
1893 			     : IP_DEFAULT_MULTICAST_LOOP;
1894 
1895 		error = sockopt_set(sopt, &optval, sizeof(optval));
1896 		break;
1897 
1898 	default:
1899 		error = EOPNOTSUPP;
1900 	}
1901 
1902 	return (error);
1903 }
1904 
1905 /*
1906  * Discard the IP multicast options.
1907  */
1908 void
1909 ip_freemoptions(struct ip_moptions *imo)
1910 {
1911 	int i;
1912 
1913 	if (imo != NULL) {
1914 		for (i = 0; i < imo->imo_num_memberships; ++i)
1915 			in_delmulti(imo->imo_membership[i]);
1916 		free(imo, M_IPMOPTS);
1917 	}
1918 }
1919 
1920 /*
1921  * Routine called from ip_output() to loop back a copy of an IP multicast
1922  * packet to the input queue of a specified interface.  Note that this
1923  * calls the output routine of the loopback "driver", but with an interface
1924  * pointer that might NOT be lo0ifp -- easier than replicating that code here.
1925  */
1926 static void
1927 ip_mloopback(struct ifnet *ifp, struct mbuf *m, const struct sockaddr_in *dst)
1928 {
1929 	struct ip *ip;
1930 	struct mbuf *copym;
1931 
1932 	copym = m_copypacket(m, M_DONTWAIT);
1933 	if (copym != NULL
1934 	 && (copym->m_flags & M_EXT || copym->m_len < sizeof(struct ip)))
1935 		copym = m_pullup(copym, sizeof(struct ip));
1936 	if (copym == NULL)
1937 		return;
1938 	/*
1939 	 * We don't bother to fragment if the IP length is greater
1940 	 * than the interface's MTU.  Can this possibly matter?
1941 	 */
1942 	ip = mtod(copym, struct ip *);
1943 
1944 	if (copym->m_pkthdr.csum_flags & (M_CSUM_TCPv4|M_CSUM_UDPv4)) {
1945 		in_delayed_cksum(copym);
1946 		copym->m_pkthdr.csum_flags &=
1947 		    ~(M_CSUM_TCPv4|M_CSUM_UDPv4);
1948 	}
1949 
1950 	ip->ip_sum = 0;
1951 	ip->ip_sum = in_cksum(copym, ip->ip_hl << 2);
1952 	(void)looutput(ifp, copym, sintocsa(dst), NULL);
1953 }
1954