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