ip_output.c revision 20407
1170890Syar/*
2170890Syar * Copyright (c) 1982, 1986, 1988, 1990, 1993
3170890Syar *	The Regents of the University of California.  All rights reserved.
4170890Syar *
5170890Syar * Redistribution and use in source and binary forms, with or without
6170890Syar * modification, are permitted provided that the following conditions
7170890Syar * are met:
8170890Syar * 1. Redistributions of source code must retain the above copyright
9170890Syar *    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 *	$Id: ip_output.c,v 1.45 1996/11/11 04:56:19 fenner Exp $
35 */
36
37#define _IP_VHL
38
39#include <sys/param.h>
40#include <sys/queue.h>
41#include <sys/systm.h>
42#include <sys/malloc.h>
43#include <sys/mbuf.h>
44#include <sys/errno.h>
45#include <sys/protosw.h>
46#include <sys/socket.h>
47#include <sys/socketvar.h>
48
49#include <net/if.h>
50#include <net/route.h>
51
52#include <netinet/in.h>
53#include <netinet/in_systm.h>
54#include <netinet/ip.h>
55#include <netinet/in_pcb.h>
56#include <netinet/in_var.h>
57#include <netinet/ip_var.h>
58
59#ifdef vax
60#include <machine/mtpr.h>
61#endif
62#include <machine/in_cksum.h>
63
64#if !defined(COMPAT_IPFW) || COMPAT_IPFW == 1
65#undef COMPAT_IPFW
66#define COMPAT_IPFW 1
67#else
68#undef COMPAT_IPFW
69#endif
70
71u_short ip_id;
72
73static struct mbuf *ip_insertoptions __P((struct mbuf *, struct mbuf *, int *));
74static void	ip_mloopback
75	__P((struct ifnet *, struct mbuf *, struct sockaddr_in *));
76static int	ip_getmoptions
77	__P((int, struct ip_moptions *, struct mbuf **));
78static int	ip_optcopy __P((struct ip *, struct ip *));
79static int	ip_pcbopts __P((struct mbuf **, struct mbuf *));
80static int	ip_setmoptions
81	__P((int, struct ip_moptions **, struct mbuf *));
82
83extern	struct protosw inetsw[];
84
85/*
86 * IP output.  The packet in mbuf chain m contains a skeletal IP
87 * header (with len, off, ttl, proto, tos, src, dst).
88 * The mbuf chain containing the packet will be freed.
89 * The mbuf opt, if present, will not be freed.
90 */
91int
92ip_output(m0, opt, ro, flags, imo)
93	struct mbuf *m0;
94	struct mbuf *opt;
95	struct route *ro;
96	int flags;
97	struct ip_moptions *imo;
98{
99	struct ip *ip, *mhip;
100	struct ifnet *ifp;
101	struct mbuf *m = m0;
102	int hlen = sizeof (struct ip);
103	int len, off, error = 0;
104	struct sockaddr_in *dst;
105	struct in_ifaddr *ia;
106	int isbroadcast;
107
108#ifdef	DIAGNOSTIC
109	if ((m->m_flags & M_PKTHDR) == 0)
110		panic("ip_output no HDR");
111	if (!ro)
112		panic("ip_output no route, proto = %d",
113		      mtod(m, struct ip *)->ip_p);
114#endif
115	if (opt) {
116		m = ip_insertoptions(m, opt, &len);
117		hlen = len;
118	}
119	ip = mtod(m, struct ip *);
120	/*
121	 * Fill in IP header.
122	 */
123	if ((flags & (IP_FORWARDING|IP_RAWOUTPUT)) == 0) {
124		ip->ip_vhl = IP_MAKE_VHL(IPVERSION, hlen >> 2);
125		ip->ip_off &= IP_DF;
126		ip->ip_id = htons(ip_id++);
127		ipstat.ips_localout++;
128	} else {
129		hlen = IP_VHL_HL(ip->ip_vhl) << 2;
130	}
131
132	dst = (struct sockaddr_in *)&ro->ro_dst;
133	/*
134	 * If there is a cached route,
135	 * check that it is to the same destination
136	 * and is still up.  If not, free it and try again.
137	 */
138	if (ro->ro_rt && ((ro->ro_rt->rt_flags & RTF_UP) == 0 ||
139	   dst->sin_addr.s_addr != ip->ip_dst.s_addr)) {
140		RTFREE(ro->ro_rt);
141		ro->ro_rt = (struct rtentry *)0;
142	}
143	if (ro->ro_rt == 0) {
144		dst->sin_family = AF_INET;
145		dst->sin_len = sizeof(*dst);
146		dst->sin_addr = ip->ip_dst;
147	}
148	/*
149	 * If routing to interface only,
150	 * short circuit routing lookup.
151	 */
152#define ifatoia(ifa)	((struct in_ifaddr *)(ifa))
153#define sintosa(sin)	((struct sockaddr *)(sin))
154	if (flags & IP_ROUTETOIF) {
155		if ((ia = ifatoia(ifa_ifwithdstaddr(sintosa(dst)))) == 0 &&
156		    (ia = ifatoia(ifa_ifwithnet(sintosa(dst)))) == 0) {
157			ipstat.ips_noroute++;
158			error = ENETUNREACH;
159			goto bad;
160		}
161		ifp = ia->ia_ifp;
162		ip->ip_ttl = 1;
163		isbroadcast = in_broadcast(dst->sin_addr, ifp);
164	} else {
165		/*
166		 * If this is the case, we probably don't want to allocate
167		 * a protocol-cloned route since we didn't get one from the
168		 * ULP.  This lets TCP do its thing, while not burdening
169		 * forwarding or ICMP with the overhead of cloning a route.
170		 * Of course, we still want to do any cloning requested by
171		 * the link layer, as this is probably required in all cases
172		 * for correct operation (as it is for ARP).
173		 */
174		if (ro->ro_rt == 0)
175			rtalloc_ign(ro, RTF_PRCLONING);
176		if (ro->ro_rt == 0) {
177			ipstat.ips_noroute++;
178			error = EHOSTUNREACH;
179			goto bad;
180		}
181		ia = ifatoia(ro->ro_rt->rt_ifa);
182		ifp = ro->ro_rt->rt_ifp;
183		ro->ro_rt->rt_use++;
184		if (ro->ro_rt->rt_flags & RTF_GATEWAY)
185			dst = (struct sockaddr_in *)ro->ro_rt->rt_gateway;
186		if (ro->ro_rt->rt_flags & RTF_HOST)
187			isbroadcast = (ro->ro_rt->rt_flags & RTF_BROADCAST);
188		else
189			isbroadcast = in_broadcast(dst->sin_addr, ifp);
190	}
191	if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr))) {
192		struct in_multi *inm;
193
194		m->m_flags |= M_MCAST;
195		/*
196		 * IP destination address is multicast.  Make sure "dst"
197		 * still points to the address in "ro".  (It may have been
198		 * changed to point to a gateway address, above.)
199		 */
200		dst = (struct sockaddr_in *)&ro->ro_dst;
201		/*
202		 * See if the caller provided any multicast options
203		 */
204		if (imo != NULL) {
205			ip->ip_ttl = imo->imo_multicast_ttl;
206			if (imo->imo_multicast_ifp != NULL)
207				ifp = imo->imo_multicast_ifp;
208			if (imo->imo_multicast_vif != -1)
209				ip->ip_src.s_addr =
210				    ip_mcast_src(imo->imo_multicast_vif);
211		} else
212			ip->ip_ttl = IP_DEFAULT_MULTICAST_TTL;
213		/*
214		 * Confirm that the outgoing interface supports multicast.
215		 */
216		if ((imo == NULL) || (imo->imo_multicast_vif == -1)) {
217			if ((ifp->if_flags & IFF_MULTICAST) == 0) {
218				ipstat.ips_noroute++;
219				error = ENETUNREACH;
220				goto bad;
221			}
222		}
223		/*
224		 * If source address not specified yet, use address
225		 * of outgoing interface.
226		 */
227		if (ip->ip_src.s_addr == INADDR_ANY) {
228			register struct in_ifaddr *ia;
229
230			for (ia = in_ifaddrhead.tqh_first; ia;
231			     ia = ia->ia_link.tqe_next)
232				if (ia->ia_ifp == ifp) {
233					ip->ip_src = IA_SIN(ia)->sin_addr;
234					break;
235				}
236		}
237
238		IN_LOOKUP_MULTI(ip->ip_dst, ifp, inm);
239		if (inm != NULL &&
240		   (imo == NULL || imo->imo_multicast_loop)) {
241			/*
242			 * If we belong to the destination multicast group
243			 * on the outgoing interface, and the caller did not
244			 * forbid loopback, loop back a copy.
245			 */
246			ip_mloopback(ifp, m, dst);
247		}
248		else {
249			/*
250			 * If we are acting as a multicast router, perform
251			 * multicast forwarding as if the packet had just
252			 * arrived on the interface to which we are about
253			 * to send.  The multicast forwarding function
254			 * recursively calls this function, using the
255			 * IP_FORWARDING flag to prevent infinite recursion.
256			 *
257			 * Multicasts that are looped back by ip_mloopback(),
258			 * above, will be forwarded by the ip_input() routine,
259			 * if necessary.
260			 */
261			if (ip_mrouter && (flags & IP_FORWARDING) == 0) {
262				/*
263				 * Check if rsvp daemon is running. If not, don't
264				 * set ip_moptions. This ensures that the packet
265				 * is multicast and not just sent down one link
266				 * as prescribed by rsvpd.
267				 */
268				if (!rsvp_on)
269				  imo = NULL;
270				if (ip_mforward(ip, ifp, m, imo) != 0) {
271					m_freem(m);
272					goto done;
273				}
274			}
275		}
276
277		/*
278		 * Multicasts with a time-to-live of zero may be looped-
279		 * back, above, but must not be transmitted on a network.
280		 * Also, multicasts addressed to the loopback interface
281		 * are not sent -- the above call to ip_mloopback() will
282		 * loop back a copy if this host actually belongs to the
283		 * destination group on the loopback interface.
284		 */
285		if (ip->ip_ttl == 0 || ifp->if_flags & IFF_LOOPBACK) {
286			m_freem(m);
287			goto done;
288		}
289
290		goto sendit;
291	}
292#ifndef notdef
293	/*
294	 * If source address not specified yet, use address
295	 * of outgoing interface.
296	 */
297	if (ip->ip_src.s_addr == INADDR_ANY)
298		ip->ip_src = IA_SIN(ia)->sin_addr;
299#endif
300	/*
301	 * Verify that we have any chance at all of being able to queue
302	 *      the packet or packet fragments
303	 */
304	if ((ifp->if_snd.ifq_len + ip->ip_len / ifp->if_mtu + 1) >=
305		ifp->if_snd.ifq_maxlen) {
306			error = ENOBUFS;
307			goto bad;
308	}
309
310	/*
311	 * Look for broadcast address and
312	 * and verify user is allowed to send
313	 * such a packet.
314	 */
315	if (isbroadcast) {
316		if ((ifp->if_flags & IFF_BROADCAST) == 0) {
317			error = EADDRNOTAVAIL;
318			goto bad;
319		}
320		if ((flags & IP_ALLOWBROADCAST) == 0) {
321			error = EACCES;
322			goto bad;
323		}
324		/* don't allow broadcast messages to be fragmented */
325		if ((u_short)ip->ip_len > ifp->if_mtu) {
326			error = EMSGSIZE;
327			goto bad;
328		}
329		m->m_flags |= M_BCAST;
330	} else {
331		m->m_flags &= ~M_BCAST;
332	}
333
334sendit:
335        /*
336	 * IpHack's section.
337	 * - Xlate: translate packet's addr/port (NAT).
338	 * - Firewall: deny/allow
339	 * - Wrap: fake packet's addr/port <unimpl.>
340	 * - Encapsulate: put it in another IP and send out. <unimp.>
341	 */
342
343#ifdef COMPAT_IPFW
344        if (ip_nat_ptr && !(*ip_nat_ptr)(&ip, &m, ifp, IP_NAT_OUT)) {
345		error = EACCES;
346		goto done;
347	}
348
349	/*
350	 * Check with the firewall...
351	 */
352	if (ip_fw_chk_ptr) {
353		int action;
354
355#ifdef IPDIVERT
356		action = (*ip_fw_chk_ptr)(&ip,
357				hlen, ifp, (~0 << 16) | ip_divert_ignore, &m);
358#else
359		action = (*ip_fw_chk_ptr)(&ip, hlen, ifp, (~0 << 16), &m);
360#endif
361		if (action == -1) {
362			error = EACCES;		/* XXX is this appropriate? */
363			goto done;
364		} else if (action != 0) {
365#ifdef IPDIVERT
366			ip_divert_port = action;	/* divert to port */
367			(*inetsw[ip_protox[IPPROTO_DIVERT]].pr_input)(m, 0);
368			goto done;
369#else
370			m_freem(m);	/* ipfw says divert, but we can't */
371			goto done;
372#endif
373		}
374	}
375#endif /* COMPAT_IPFW */
376
377	/*
378	 * If small enough for interface, can just send directly.
379	 */
380	if ((u_short)ip->ip_len <= ifp->if_mtu) {
381		ip->ip_len = htons((u_short)ip->ip_len);
382		ip->ip_off = htons((u_short)ip->ip_off);
383		ip->ip_sum = 0;
384		if (ip->ip_vhl == IP_VHL_BORING) {
385			ip->ip_sum = in_cksum_hdr(ip);
386		} else {
387			ip->ip_sum = in_cksum(m, hlen);
388		}
389		error = (*ifp->if_output)(ifp, m,
390				(struct sockaddr *)dst, ro->ro_rt);
391		goto done;
392	}
393	/*
394	 * Too large for interface; fragment if possible.
395	 * Must be able to put at least 8 bytes per fragment.
396	 */
397	if (ip->ip_off & IP_DF) {
398		error = EMSGSIZE;
399		/*
400		 * This case can happen if the user changed the MTU
401		 * of an interface after enabling IP on it.  Because
402		 * most netifs don't keep track of routes pointing to
403		 * them, there is no way for one to update all its
404		 * routes when the MTU is changed.
405		 */
406		if ((ro->ro_rt->rt_flags & (RTF_UP | RTF_HOST))
407		    && !(ro->ro_rt->rt_rmx.rmx_locks & RTV_MTU)
408		    && (ro->ro_rt->rt_rmx.rmx_mtu > ifp->if_mtu)) {
409			ro->ro_rt->rt_rmx.rmx_mtu = ifp->if_mtu;
410		}
411		ipstat.ips_cantfrag++;
412		goto bad;
413	}
414	len = (ifp->if_mtu - hlen) &~ 7;
415	if (len < 8) {
416		error = EMSGSIZE;
417		goto bad;
418	}
419
420    {
421	int mhlen, firstlen = len;
422	struct mbuf **mnext = &m->m_nextpkt;
423
424	/*
425	 * Loop through length of segment after first fragment,
426	 * make new header and copy data of each part and link onto chain.
427	 */
428	m0 = m;
429	mhlen = sizeof (struct ip);
430	for (off = hlen + len; off < (u_short)ip->ip_len; off += len) {
431		MGETHDR(m, M_DONTWAIT, MT_HEADER);
432		if (m == 0) {
433			error = ENOBUFS;
434			ipstat.ips_odropped++;
435			goto sendorfree;
436		}
437		m->m_data += max_linkhdr;
438		mhip = mtod(m, struct ip *);
439		*mhip = *ip;
440		if (hlen > sizeof (struct ip)) {
441			mhlen = ip_optcopy(ip, mhip) + sizeof (struct ip);
442			mhip->ip_vhl = IP_MAKE_VHL(IPVERSION, mhlen >> 2);
443		}
444		m->m_len = mhlen;
445		mhip->ip_off = ((off - hlen) >> 3) + (ip->ip_off & ~IP_MF);
446		if (ip->ip_off & IP_MF)
447			mhip->ip_off |= IP_MF;
448		if (off + len >= (u_short)ip->ip_len)
449			len = (u_short)ip->ip_len - off;
450		else
451			mhip->ip_off |= IP_MF;
452		mhip->ip_len = htons((u_short)(len + mhlen));
453		m->m_next = m_copy(m0, off, len);
454		if (m->m_next == 0) {
455			(void) m_free(m);
456			error = ENOBUFS;	/* ??? */
457			ipstat.ips_odropped++;
458			goto sendorfree;
459		}
460		m->m_pkthdr.len = mhlen + len;
461		m->m_pkthdr.rcvif = (struct ifnet *)0;
462		mhip->ip_off = htons((u_short)mhip->ip_off);
463		mhip->ip_sum = 0;
464		if (mhip->ip_vhl == IP_VHL_BORING) {
465			mhip->ip_sum = in_cksum_hdr(mhip);
466		} else {
467			mhip->ip_sum = in_cksum(m, mhlen);
468		}
469		*mnext = m;
470		mnext = &m->m_nextpkt;
471		ipstat.ips_ofragments++;
472	}
473	/*
474	 * Update first fragment by trimming what's been copied out
475	 * and updating header, then send each fragment (in order).
476	 */
477	m = m0;
478	m_adj(m, hlen + firstlen - (u_short)ip->ip_len);
479	m->m_pkthdr.len = hlen + firstlen;
480	ip->ip_len = htons((u_short)m->m_pkthdr.len);
481	ip->ip_off = htons((u_short)(ip->ip_off | IP_MF));
482	ip->ip_sum = 0;
483	if (ip->ip_vhl == IP_VHL_BORING) {
484		ip->ip_sum = in_cksum_hdr(ip);
485	} else {
486		ip->ip_sum = in_cksum(m, hlen);
487	}
488sendorfree:
489	for (m = m0; m; m = m0) {
490		m0 = m->m_nextpkt;
491		m->m_nextpkt = 0;
492		if (error == 0)
493			error = (*ifp->if_output)(ifp, m,
494			    (struct sockaddr *)dst, ro->ro_rt);
495		else
496			m_freem(m);
497	}
498
499	if (error == 0)
500		ipstat.ips_fragmented++;
501    }
502done:
503	return (error);
504bad:
505	m_freem(m0);
506	goto done;
507}
508
509/*
510 * Insert IP options into preformed packet.
511 * Adjust IP destination as required for IP source routing,
512 * as indicated by a non-zero in_addr at the start of the options.
513 *
514 * XXX This routine assumes that the packet has no options in place.
515 */
516static struct mbuf *
517ip_insertoptions(m, opt, phlen)
518	register struct mbuf *m;
519	struct mbuf *opt;
520	int *phlen;
521{
522	register struct ipoption *p = mtod(opt, struct ipoption *);
523	struct mbuf *n;
524	register struct ip *ip = mtod(m, struct ip *);
525	unsigned optlen;
526
527	optlen = opt->m_len - sizeof(p->ipopt_dst);
528	if (optlen + (u_short)ip->ip_len > IP_MAXPACKET)
529		return (m);		/* XXX should fail */
530	if (p->ipopt_dst.s_addr)
531		ip->ip_dst = p->ipopt_dst;
532	if (m->m_flags & M_EXT || m->m_data - optlen < m->m_pktdat) {
533		MGETHDR(n, M_DONTWAIT, MT_HEADER);
534		if (n == 0)
535			return (m);
536		n->m_pkthdr.len = m->m_pkthdr.len + optlen;
537		m->m_len -= sizeof(struct ip);
538		m->m_data += sizeof(struct ip);
539		n->m_next = m;
540		m = n;
541		m->m_len = optlen + sizeof(struct ip);
542		m->m_data += max_linkhdr;
543		(void)memcpy(mtod(m, void *), ip, sizeof(struct ip));
544	} else {
545		m->m_data -= optlen;
546		m->m_len += optlen;
547		m->m_pkthdr.len += optlen;
548		ovbcopy((caddr_t)ip, mtod(m, caddr_t), sizeof(struct ip));
549	}
550	ip = mtod(m, struct ip *);
551	bcopy(p->ipopt_list, ip + 1, optlen);
552	*phlen = sizeof(struct ip) + optlen;
553	ip->ip_vhl = IP_MAKE_VHL(IPVERSION, *phlen >> 2);
554	ip->ip_len += optlen;
555	return (m);
556}
557
558/*
559 * Copy options from ip to jp,
560 * omitting those not copied during fragmentation.
561 */
562static int
563ip_optcopy(ip, jp)
564	struct ip *ip, *jp;
565{
566	register u_char *cp, *dp;
567	int opt, optlen, cnt;
568
569	cp = (u_char *)(ip + 1);
570	dp = (u_char *)(jp + 1);
571	cnt = (IP_VHL_HL(ip->ip_vhl) << 2) - sizeof (struct ip);
572	for (; cnt > 0; cnt -= optlen, cp += optlen) {
573		opt = cp[0];
574		if (opt == IPOPT_EOL)
575			break;
576		if (opt == IPOPT_NOP) {
577			/* Preserve for IP mcast tunnel's LSRR alignment. */
578			*dp++ = IPOPT_NOP;
579			optlen = 1;
580			continue;
581		} else
582			optlen = cp[IPOPT_OLEN];
583		/* bogus lengths should have been caught by ip_dooptions */
584		if (optlen > cnt)
585			optlen = cnt;
586		if (IPOPT_COPIED(opt)) {
587			bcopy(cp, dp, optlen);
588			dp += optlen;
589		}
590	}
591	for (optlen = dp - (u_char *)(jp+1); optlen & 0x3; optlen++)
592		*dp++ = IPOPT_EOL;
593	return (optlen);
594}
595
596/*
597 * IP socket option processing.
598 */
599int
600ip_ctloutput(op, so, level, optname, mp)
601	int op;
602	struct socket *so;
603	int level, optname;
604	struct mbuf **mp;
605{
606	register struct inpcb *inp = sotoinpcb(so);
607	register struct mbuf *m = *mp;
608	register int optval = 0;
609	int error = 0;
610
611	if (level != IPPROTO_IP) {
612		error = EINVAL;
613		if (op == PRCO_SETOPT && *mp)
614			(void) m_free(*mp);
615	} else switch (op) {
616
617	case PRCO_SETOPT:
618		switch (optname) {
619		case IP_OPTIONS:
620#ifdef notyet
621		case IP_RETOPTS:
622			return (ip_pcbopts(optname, &inp->inp_options, m));
623#else
624			return (ip_pcbopts(&inp->inp_options, m));
625#endif
626
627		case IP_TOS:
628		case IP_TTL:
629		case IP_RECVOPTS:
630		case IP_RECVRETOPTS:
631		case IP_RECVDSTADDR:
632		case IP_RECVIF:
633			if (m == 0 || m->m_len != sizeof(int))
634				error = EINVAL;
635			else {
636				optval = *mtod(m, int *);
637				switch (optname) {
638
639				case IP_TOS:
640					inp->inp_ip.ip_tos = optval;
641					break;
642
643				case IP_TTL:
644					inp->inp_ip.ip_ttl = optval;
645					break;
646#define	OPTSET(bit) \
647	if (optval) \
648		inp->inp_flags |= bit; \
649	else \
650		inp->inp_flags &= ~bit;
651
652				case IP_RECVOPTS:
653					OPTSET(INP_RECVOPTS);
654					break;
655
656				case IP_RECVRETOPTS:
657					OPTSET(INP_RECVRETOPTS);
658					break;
659
660				case IP_RECVDSTADDR:
661					OPTSET(INP_RECVDSTADDR);
662					break;
663
664				case IP_RECVIF:
665					OPTSET(INP_RECVIF);
666					break;
667				}
668			}
669			break;
670#undef OPTSET
671
672		case IP_MULTICAST_IF:
673		case IP_MULTICAST_VIF:
674		case IP_MULTICAST_TTL:
675		case IP_MULTICAST_LOOP:
676		case IP_ADD_MEMBERSHIP:
677		case IP_DROP_MEMBERSHIP:
678			error = ip_setmoptions(optname, &inp->inp_moptions, m);
679			break;
680
681		case IP_PORTRANGE:
682			if (m == 0 || m->m_len != sizeof(int))
683				error = EINVAL;
684			else {
685				optval = *mtod(m, int *);
686
687				switch (optval) {
688
689				case IP_PORTRANGE_DEFAULT:
690					inp->inp_flags &= ~(INP_LOWPORT);
691					inp->inp_flags &= ~(INP_HIGHPORT);
692					break;
693
694				case IP_PORTRANGE_HIGH:
695					inp->inp_flags &= ~(INP_LOWPORT);
696					inp->inp_flags |= INP_HIGHPORT;
697					break;
698
699				case IP_PORTRANGE_LOW:
700					inp->inp_flags &= ~(INP_HIGHPORT);
701					inp->inp_flags |= INP_LOWPORT;
702					break;
703
704				default:
705					error = EINVAL;
706					break;
707				}
708			}
709			break;
710
711		default:
712			error = ENOPROTOOPT;
713			break;
714		}
715		if (m)
716			(void)m_free(m);
717		break;
718
719	case PRCO_GETOPT:
720		switch (optname) {
721		case IP_OPTIONS:
722		case IP_RETOPTS:
723			*mp = m = m_get(M_WAIT, MT_SOOPTS);
724			if (inp->inp_options) {
725				m->m_len = inp->inp_options->m_len;
726				bcopy(mtod(inp->inp_options, void *),
727				    mtod(m, void *), m->m_len);
728			} else
729				m->m_len = 0;
730			break;
731
732		case IP_TOS:
733		case IP_TTL:
734		case IP_RECVOPTS:
735		case IP_RECVRETOPTS:
736		case IP_RECVDSTADDR:
737		case IP_RECVIF:
738			*mp = m = m_get(M_WAIT, MT_SOOPTS);
739			m->m_len = sizeof(int);
740			switch (optname) {
741
742			case IP_TOS:
743				optval = inp->inp_ip.ip_tos;
744				break;
745
746			case IP_TTL:
747				optval = inp->inp_ip.ip_ttl;
748				break;
749
750#define	OPTBIT(bit)	(inp->inp_flags & bit ? 1 : 0)
751
752			case IP_RECVOPTS:
753				optval = OPTBIT(INP_RECVOPTS);
754				break;
755
756			case IP_RECVRETOPTS:
757				optval = OPTBIT(INP_RECVRETOPTS);
758				break;
759
760			case IP_RECVDSTADDR:
761				optval = OPTBIT(INP_RECVDSTADDR);
762				break;
763
764			case IP_RECVIF:
765				optval = OPTBIT(INP_RECVIF);
766				break;
767			}
768			*mtod(m, int *) = optval;
769			break;
770
771		case IP_MULTICAST_IF:
772		case IP_MULTICAST_VIF:
773		case IP_MULTICAST_TTL:
774		case IP_MULTICAST_LOOP:
775		case IP_ADD_MEMBERSHIP:
776		case IP_DROP_MEMBERSHIP:
777			error = ip_getmoptions(optname, inp->inp_moptions, mp);
778			break;
779
780		case IP_PORTRANGE:
781			*mp = m = m_get(M_WAIT, MT_SOOPTS);
782			m->m_len = sizeof(int);
783
784			if (inp->inp_flags & INP_HIGHPORT)
785				optval = IP_PORTRANGE_HIGH;
786			else if (inp->inp_flags & INP_LOWPORT)
787				optval = IP_PORTRANGE_LOW;
788			else
789				optval = 0;
790
791			*mtod(m, int *) = optval;
792			break;
793
794		default:
795			error = ENOPROTOOPT;
796			break;
797		}
798		break;
799	}
800	return (error);
801}
802
803/*
804 * Set up IP options in pcb for insertion in output packets.
805 * Store in mbuf with pointer in pcbopt, adding pseudo-option
806 * with destination address if source routed.
807 */
808static int
809#ifdef notyet
810ip_pcbopts(optname, pcbopt, m)
811	int optname;
812#else
813ip_pcbopts(pcbopt, m)
814#endif
815	struct mbuf **pcbopt;
816	register struct mbuf *m;
817{
818	register cnt, optlen;
819	register u_char *cp;
820	u_char opt;
821
822	/* turn off any old options */
823	if (*pcbopt)
824		(void)m_free(*pcbopt);
825	*pcbopt = 0;
826	if (m == (struct mbuf *)0 || m->m_len == 0) {
827		/*
828		 * Only turning off any previous options.
829		 */
830		if (m)
831			(void)m_free(m);
832		return (0);
833	}
834
835#ifndef	vax
836	if (m->m_len % sizeof(long))
837		goto bad;
838#endif
839	/*
840	 * IP first-hop destination address will be stored before
841	 * actual options; move other options back
842	 * and clear it when none present.
843	 */
844	if (m->m_data + m->m_len + sizeof(struct in_addr) >= &m->m_dat[MLEN])
845		goto bad;
846	cnt = m->m_len;
847	m->m_len += sizeof(struct in_addr);
848	cp = mtod(m, u_char *) + sizeof(struct in_addr);
849	ovbcopy(mtod(m, caddr_t), (caddr_t)cp, (unsigned)cnt);
850	bzero(mtod(m, caddr_t), sizeof(struct in_addr));
851
852	for (; cnt > 0; cnt -= optlen, cp += optlen) {
853		opt = cp[IPOPT_OPTVAL];
854		if (opt == IPOPT_EOL)
855			break;
856		if (opt == IPOPT_NOP)
857			optlen = 1;
858		else {
859			optlen = cp[IPOPT_OLEN];
860			if (optlen <= IPOPT_OLEN || optlen > cnt)
861				goto bad;
862		}
863		switch (opt) {
864
865		default:
866			break;
867
868		case IPOPT_LSRR:
869		case IPOPT_SSRR:
870			/*
871			 * user process specifies route as:
872			 *	->A->B->C->D
873			 * D must be our final destination (but we can't
874			 * check that since we may not have connected yet).
875			 * A is first hop destination, which doesn't appear in
876			 * actual IP option, but is stored before the options.
877			 */
878			if (optlen < IPOPT_MINOFF - 1 + sizeof(struct in_addr))
879				goto bad;
880			m->m_len -= sizeof(struct in_addr);
881			cnt -= sizeof(struct in_addr);
882			optlen -= sizeof(struct in_addr);
883			cp[IPOPT_OLEN] = optlen;
884			/*
885			 * Move first hop before start of options.
886			 */
887			bcopy((caddr_t)&cp[IPOPT_OFFSET+1], mtod(m, caddr_t),
888			    sizeof(struct in_addr));
889			/*
890			 * Then copy rest of options back
891			 * to close up the deleted entry.
892			 */
893			ovbcopy((caddr_t)(&cp[IPOPT_OFFSET+1] +
894			    sizeof(struct in_addr)),
895			    (caddr_t)&cp[IPOPT_OFFSET+1],
896			    (unsigned)cnt + sizeof(struct in_addr));
897			break;
898		}
899	}
900	if (m->m_len > MAX_IPOPTLEN + sizeof(struct in_addr))
901		goto bad;
902	*pcbopt = m;
903	return (0);
904
905bad:
906	(void)m_free(m);
907	return (EINVAL);
908}
909
910/*
911 * Set the IP multicast options in response to user setsockopt().
912 */
913static int
914ip_setmoptions(optname, imop, m)
915	int optname;
916	struct ip_moptions **imop;
917	struct mbuf *m;
918{
919	register int error = 0;
920	u_char loop;
921	register int i;
922	struct in_addr addr;
923	register struct ip_mreq *mreq;
924	register struct ifnet *ifp;
925	register struct ip_moptions *imo = *imop;
926	struct route ro;
927	register struct sockaddr_in *dst;
928	int s;
929
930	if (imo == NULL) {
931		/*
932		 * No multicast option buffer attached to the pcb;
933		 * allocate one and initialize to default values.
934		 */
935		imo = (struct ip_moptions*)malloc(sizeof(*imo), M_IPMOPTS,
936		    M_WAITOK);
937
938		if (imo == NULL)
939			return (ENOBUFS);
940		*imop = imo;
941		imo->imo_multicast_ifp = NULL;
942		imo->imo_multicast_vif = -1;
943		imo->imo_multicast_ttl = IP_DEFAULT_MULTICAST_TTL;
944		imo->imo_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
945		imo->imo_num_memberships = 0;
946	}
947
948	switch (optname) {
949	/* store an index number for the vif you wanna use in the send */
950	case IP_MULTICAST_VIF:
951		if (!legal_vif_num) {
952			error = EOPNOTSUPP;
953			break;
954		}
955		if (m == NULL || m->m_len != sizeof(int)) {
956			error = EINVAL;
957			break;
958		}
959		i = *(mtod(m, int *));
960		if (!legal_vif_num(i) && (i != -1)) {
961			error = EINVAL;
962			break;
963		}
964		imo->imo_multicast_vif = i;
965		break;
966
967	case IP_MULTICAST_IF:
968		/*
969		 * Select the interface for outgoing multicast packets.
970		 */
971		if (m == NULL || m->m_len != sizeof(struct in_addr)) {
972			error = EINVAL;
973			break;
974		}
975		addr = *(mtod(m, struct in_addr *));
976		/*
977		 * INADDR_ANY is used to remove a previous selection.
978		 * When no interface is selected, a default one is
979		 * chosen every time a multicast packet is sent.
980		 */
981		if (addr.s_addr == INADDR_ANY) {
982			imo->imo_multicast_ifp = NULL;
983			break;
984		}
985		/*
986		 * The selected interface is identified by its local
987		 * IP address.  Find the interface and confirm that
988		 * it supports multicasting.
989		 */
990		s = splimp();
991		INADDR_TO_IFP(addr, ifp);
992		if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0) {
993			splx(s);
994			error = EADDRNOTAVAIL;
995			break;
996		}
997		imo->imo_multicast_ifp = ifp;
998		splx(s);
999		break;
1000
1001	case IP_MULTICAST_TTL:
1002		/*
1003		 * Set the IP time-to-live for outgoing multicast packets.
1004		 */
1005		if (m == NULL || m->m_len != 1) {
1006			error = EINVAL;
1007			break;
1008		}
1009		imo->imo_multicast_ttl = *(mtod(m, u_char *));
1010		break;
1011
1012	case IP_MULTICAST_LOOP:
1013		/*
1014		 * Set the loopback flag for outgoing multicast packets.
1015		 * Must be zero or one.
1016		 */
1017		if (m == NULL || m->m_len != 1 ||
1018		   (loop = *(mtod(m, u_char *))) > 1) {
1019			error = EINVAL;
1020			break;
1021		}
1022		imo->imo_multicast_loop = loop;
1023		break;
1024
1025	case IP_ADD_MEMBERSHIP:
1026		/*
1027		 * Add a multicast group membership.
1028		 * Group must be a valid IP multicast address.
1029		 */
1030		if (m == NULL || m->m_len != sizeof(struct ip_mreq)) {
1031			error = EINVAL;
1032			break;
1033		}
1034		mreq = mtod(m, struct ip_mreq *);
1035		if (!IN_MULTICAST(ntohl(mreq->imr_multiaddr.s_addr))) {
1036			error = EINVAL;
1037			break;
1038		}
1039		s = splimp();
1040		/*
1041		 * If no interface address was provided, use the interface of
1042		 * the route to the given multicast address.
1043		 */
1044		if (mreq->imr_interface.s_addr == INADDR_ANY) {
1045			bzero((caddr_t)&ro, sizeof(ro));
1046			dst = (struct sockaddr_in *)&ro.ro_dst;
1047			dst->sin_len = sizeof(*dst);
1048			dst->sin_family = AF_INET;
1049			dst->sin_addr = mreq->imr_multiaddr;
1050			rtalloc(&ro);
1051			if (ro.ro_rt == NULL) {
1052				error = EADDRNOTAVAIL;
1053				splx(s);
1054				break;
1055			}
1056			ifp = ro.ro_rt->rt_ifp;
1057			rtfree(ro.ro_rt);
1058		}
1059		else {
1060			INADDR_TO_IFP(mreq->imr_interface, ifp);
1061		}
1062
1063		/*
1064		 * See if we found an interface, and confirm that it
1065		 * supports multicast.
1066		 */
1067		if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0) {
1068			error = EADDRNOTAVAIL;
1069			splx(s);
1070			break;
1071		}
1072		/*
1073		 * See if the membership already exists or if all the
1074		 * membership slots are full.
1075		 */
1076		for (i = 0; i < imo->imo_num_memberships; ++i) {
1077			if (imo->imo_membership[i]->inm_ifp == ifp &&
1078			    imo->imo_membership[i]->inm_addr.s_addr
1079						== mreq->imr_multiaddr.s_addr)
1080				break;
1081		}
1082		if (i < imo->imo_num_memberships) {
1083			error = EADDRINUSE;
1084			splx(s);
1085			break;
1086		}
1087		if (i == IP_MAX_MEMBERSHIPS) {
1088			error = ETOOMANYREFS;
1089			splx(s);
1090			break;
1091		}
1092		/*
1093		 * Everything looks good; add a new record to the multicast
1094		 * address list for the given interface.
1095		 */
1096		if ((imo->imo_membership[i] =
1097		    in_addmulti(&mreq->imr_multiaddr, ifp)) == NULL) {
1098			error = ENOBUFS;
1099			splx(s);
1100			break;
1101		}
1102		++imo->imo_num_memberships;
1103		splx(s);
1104		break;
1105
1106	case IP_DROP_MEMBERSHIP:
1107		/*
1108		 * Drop a multicast group membership.
1109		 * Group must be a valid IP multicast address.
1110		 */
1111		if (m == NULL || m->m_len != sizeof(struct ip_mreq)) {
1112			error = EINVAL;
1113			break;
1114		}
1115		mreq = mtod(m, struct ip_mreq *);
1116		if (!IN_MULTICAST(ntohl(mreq->imr_multiaddr.s_addr))) {
1117			error = EINVAL;
1118			break;
1119		}
1120
1121		s = splimp();
1122		/*
1123		 * If an interface address was specified, get a pointer
1124		 * to its ifnet structure.
1125		 */
1126		if (mreq->imr_interface.s_addr == INADDR_ANY)
1127			ifp = NULL;
1128		else {
1129			INADDR_TO_IFP(mreq->imr_interface, ifp);
1130			if (ifp == NULL) {
1131				error = EADDRNOTAVAIL;
1132				splx(s);
1133				break;
1134			}
1135		}
1136		/*
1137		 * Find the membership in the membership array.
1138		 */
1139		for (i = 0; i < imo->imo_num_memberships; ++i) {
1140			if ((ifp == NULL ||
1141			     imo->imo_membership[i]->inm_ifp == ifp) &&
1142			     imo->imo_membership[i]->inm_addr.s_addr ==
1143			     mreq->imr_multiaddr.s_addr)
1144				break;
1145		}
1146		if (i == imo->imo_num_memberships) {
1147			error = EADDRNOTAVAIL;
1148			splx(s);
1149			break;
1150		}
1151		/*
1152		 * Give up the multicast address record to which the
1153		 * membership points.
1154		 */
1155		in_delmulti(imo->imo_membership[i]);
1156		/*
1157		 * Remove the gap in the membership array.
1158		 */
1159		for (++i; i < imo->imo_num_memberships; ++i)
1160			imo->imo_membership[i-1] = imo->imo_membership[i];
1161		--imo->imo_num_memberships;
1162		splx(s);
1163		break;
1164
1165	default:
1166		error = EOPNOTSUPP;
1167		break;
1168	}
1169
1170	/*
1171	 * If all options have default values, no need to keep the mbuf.
1172	 */
1173	if (imo->imo_multicast_ifp == NULL &&
1174	    imo->imo_multicast_vif == -1 &&
1175	    imo->imo_multicast_ttl == IP_DEFAULT_MULTICAST_TTL &&
1176	    imo->imo_multicast_loop == IP_DEFAULT_MULTICAST_LOOP &&
1177	    imo->imo_num_memberships == 0) {
1178		free(*imop, M_IPMOPTS);
1179		*imop = NULL;
1180	}
1181
1182	return (error);
1183}
1184
1185/*
1186 * Return the IP multicast options in response to user getsockopt().
1187 */
1188static int
1189ip_getmoptions(optname, imo, mp)
1190	int optname;
1191	register struct ip_moptions *imo;
1192	register struct mbuf **mp;
1193{
1194	u_char *ttl;
1195	u_char *loop;
1196	struct in_addr *addr;
1197	struct in_ifaddr *ia;
1198
1199	*mp = m_get(M_WAIT, MT_SOOPTS);
1200
1201	switch (optname) {
1202
1203	case IP_MULTICAST_VIF:
1204		if (imo != NULL)
1205			*(mtod(*mp, int *)) = imo->imo_multicast_vif;
1206		else
1207			*(mtod(*mp, int *)) = -1;
1208		(*mp)->m_len = sizeof(int);
1209		return(0);
1210
1211	case IP_MULTICAST_IF:
1212		addr = mtod(*mp, struct in_addr *);
1213		(*mp)->m_len = sizeof(struct in_addr);
1214		if (imo == NULL || imo->imo_multicast_ifp == NULL)
1215			addr->s_addr = INADDR_ANY;
1216		else {
1217			IFP_TO_IA(imo->imo_multicast_ifp, ia);
1218			addr->s_addr = (ia == NULL) ? INADDR_ANY
1219					: IA_SIN(ia)->sin_addr.s_addr;
1220		}
1221		return (0);
1222
1223	case IP_MULTICAST_TTL:
1224		ttl = mtod(*mp, u_char *);
1225		(*mp)->m_len = 1;
1226		*ttl = (imo == NULL) ? IP_DEFAULT_MULTICAST_TTL
1227				     : imo->imo_multicast_ttl;
1228		return (0);
1229
1230	case IP_MULTICAST_LOOP:
1231		loop = mtod(*mp, u_char *);
1232		(*mp)->m_len = 1;
1233		*loop = (imo == NULL) ? IP_DEFAULT_MULTICAST_LOOP
1234				      : imo->imo_multicast_loop;
1235		return (0);
1236
1237	default:
1238		return (EOPNOTSUPP);
1239	}
1240}
1241
1242/*
1243 * Discard the IP multicast options.
1244 */
1245void
1246ip_freemoptions(imo)
1247	register struct ip_moptions *imo;
1248{
1249	register int i;
1250
1251	if (imo != NULL) {
1252		for (i = 0; i < imo->imo_num_memberships; ++i)
1253			in_delmulti(imo->imo_membership[i]);
1254		free(imo, M_IPMOPTS);
1255	}
1256}
1257
1258/*
1259 * Routine called from ip_output() to loop back a copy of an IP multicast
1260 * packet to the input queue of a specified interface.  Note that this
1261 * calls the output routine of the loopback "driver", but with an interface
1262 * pointer that might NOT be a loopback interface -- evil, but easier than
1263 * replicating that code here.
1264 */
1265static void
1266ip_mloopback(ifp, m, dst)
1267	struct ifnet *ifp;
1268	register struct mbuf *m;
1269	register struct sockaddr_in *dst;
1270{
1271	register struct ip *ip;
1272	struct mbuf *copym;
1273
1274	copym = m_copy(m, 0, M_COPYALL);
1275	if (copym != NULL) {
1276		/*
1277		 * We don't bother to fragment if the IP length is greater
1278		 * than the interface's MTU.  Can this possibly matter?
1279		 */
1280		ip = mtod(copym, struct ip *);
1281		ip->ip_len = htons((u_short)ip->ip_len);
1282		ip->ip_off = htons((u_short)ip->ip_off);
1283		ip->ip_sum = 0;
1284		if (ip->ip_vhl == IP_VHL_BORING) {
1285			ip->ip_sum = in_cksum_hdr(ip);
1286		} else {
1287			ip->ip_sum = in_cksum(copym,
1288					      IP_VHL_HL(ip->ip_vhl) << 2);
1289		}
1290		/*
1291		 * NB:
1292		 * We can't simply call ip_input() directly because
1293		 * the ip_mforward() depends on the `input interface'
1294		 * being set to something unreasonable so that we don't
1295		 * attempt to forward the looped-back copy.
1296		 * It's also not clear whether there are any lingering
1297		 * reentrancy problems in other areas which might be
1298		 * exposed by this code.  For the moment, we'll err
1299		 * on the side of safety by continuing to abuse
1300		 * loinput().
1301		 */
1302#ifdef notdef
1303		copym->m_pkthdr.rcvif = &loif[0];
1304		ip_input(copym)
1305#else
1306		(void) looutput(ifp, copym, (struct sockaddr *)dst, NULL);
1307#endif
1308	}
1309}
1310