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