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