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