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