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