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