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