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