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