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