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