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