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