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