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