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