ip_output.c revision 22212
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 22212 1997-02-02 16:33:12Z brian $
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		ip_divert_ignore = 0;
359#else
360		action = (*ip_fw_chk_ptr)(&ip, hlen, ifp, (~0 << 16), &m);
361#endif
362		if (action == -1) {
363			error = EACCES;		/* XXX is this appropriate? */
364			goto done;
365		} else if (action != 0) {
366#ifdef IPDIVERT
367			ip_divert_port = action;	/* divert to port */
368			(*inetsw[ip_protox[IPPROTO_DIVERT]].pr_input)(m, 0);
369			goto done;
370#else
371			m_freem(m);	/* ipfw says divert, but we can't */
372			goto done;
373#endif
374		}
375	}
376#endif /* COMPAT_IPFW */
377
378	/*
379	 * If small enough for interface, can just send directly.
380	 */
381	if ((u_short)ip->ip_len <= ifp->if_mtu) {
382		ip->ip_len = htons((u_short)ip->ip_len);
383		ip->ip_off = htons((u_short)ip->ip_off);
384		ip->ip_sum = 0;
385		if (ip->ip_vhl == IP_VHL_BORING) {
386			ip->ip_sum = in_cksum_hdr(ip);
387		} else {
388			ip->ip_sum = in_cksum(m, hlen);
389		}
390		error = (*ifp->if_output)(ifp, m,
391				(struct sockaddr *)dst, ro->ro_rt);
392		goto done;
393	}
394	/*
395	 * Too large for interface; fragment if possible.
396	 * Must be able to put at least 8 bytes per fragment.
397	 */
398	if (ip->ip_off & IP_DF) {
399		error = EMSGSIZE;
400		/*
401		 * This case can happen if the user changed the MTU
402		 * of an interface after enabling IP on it.  Because
403		 * most netifs don't keep track of routes pointing to
404		 * them, there is no way for one to update all its
405		 * routes when the MTU is changed.
406		 */
407		if ((ro->ro_rt->rt_flags & (RTF_UP | RTF_HOST))
408		    && !(ro->ro_rt->rt_rmx.rmx_locks & RTV_MTU)
409		    && (ro->ro_rt->rt_rmx.rmx_mtu > ifp->if_mtu)) {
410			ro->ro_rt->rt_rmx.rmx_mtu = ifp->if_mtu;
411		}
412		ipstat.ips_cantfrag++;
413		goto bad;
414	}
415	len = (ifp->if_mtu - hlen) &~ 7;
416	if (len < 8) {
417		error = EMSGSIZE;
418		goto bad;
419	}
420
421    {
422	int mhlen, firstlen = len;
423	struct mbuf **mnext = &m->m_nextpkt;
424
425	/*
426	 * Loop through length of segment after first fragment,
427	 * make new header and copy data of each part and link onto chain.
428	 */
429	m0 = m;
430	mhlen = sizeof (struct ip);
431	for (off = hlen + len; off < (u_short)ip->ip_len; off += len) {
432		MGETHDR(m, M_DONTWAIT, MT_HEADER);
433		if (m == 0) {
434			error = ENOBUFS;
435			ipstat.ips_odropped++;
436			goto sendorfree;
437		}
438		m->m_data += max_linkhdr;
439		mhip = mtod(m, struct ip *);
440		*mhip = *ip;
441		if (hlen > sizeof (struct ip)) {
442			mhlen = ip_optcopy(ip, mhip) + sizeof (struct ip);
443			mhip->ip_vhl = IP_MAKE_VHL(IPVERSION, mhlen >> 2);
444		}
445		m->m_len = mhlen;
446		mhip->ip_off = ((off - hlen) >> 3) + (ip->ip_off & ~IP_MF);
447		if (ip->ip_off & IP_MF)
448			mhip->ip_off |= IP_MF;
449		if (off + len >= (u_short)ip->ip_len)
450			len = (u_short)ip->ip_len - off;
451		else
452			mhip->ip_off |= IP_MF;
453		mhip->ip_len = htons((u_short)(len + mhlen));
454		m->m_next = m_copy(m0, off, len);
455		if (m->m_next == 0) {
456			(void) m_free(m);
457			error = ENOBUFS;	/* ??? */
458			ipstat.ips_odropped++;
459			goto sendorfree;
460		}
461		m->m_pkthdr.len = mhlen + len;
462		m->m_pkthdr.rcvif = (struct ifnet *)0;
463		mhip->ip_off = htons((u_short)mhip->ip_off);
464		mhip->ip_sum = 0;
465		if (mhip->ip_vhl == IP_VHL_BORING) {
466			mhip->ip_sum = in_cksum_hdr(mhip);
467		} else {
468			mhip->ip_sum = in_cksum(m, mhlen);
469		}
470		*mnext = m;
471		mnext = &m->m_nextpkt;
472		ipstat.ips_ofragments++;
473	}
474	/*
475	 * Update first fragment by trimming what's been copied out
476	 * and updating header, then send each fragment (in order).
477	 */
478	m = m0;
479	m_adj(m, hlen + firstlen - (u_short)ip->ip_len);
480	m->m_pkthdr.len = hlen + firstlen;
481	ip->ip_len = htons((u_short)m->m_pkthdr.len);
482	ip->ip_off = htons((u_short)(ip->ip_off | IP_MF));
483	ip->ip_sum = 0;
484	if (ip->ip_vhl == IP_VHL_BORING) {
485		ip->ip_sum = in_cksum_hdr(ip);
486	} else {
487		ip->ip_sum = in_cksum(m, hlen);
488	}
489sendorfree:
490	for (m = m0; m; m = m0) {
491		m0 = m->m_nextpkt;
492		m->m_nextpkt = 0;
493		if (error == 0)
494			error = (*ifp->if_output)(ifp, m,
495			    (struct sockaddr *)dst, ro->ro_rt);
496		else
497			m_freem(m);
498	}
499
500	if (error == 0)
501		ipstat.ips_fragmented++;
502    }
503done:
504	return (error);
505bad:
506	m_freem(m0);
507	goto done;
508}
509
510/*
511 * Insert IP options into preformed packet.
512 * Adjust IP destination as required for IP source routing,
513 * as indicated by a non-zero in_addr at the start of the options.
514 *
515 * XXX This routine assumes that the packet has no options in place.
516 */
517static struct mbuf *
518ip_insertoptions(m, opt, phlen)
519	register struct mbuf *m;
520	struct mbuf *opt;
521	int *phlen;
522{
523	register struct ipoption *p = mtod(opt, struct ipoption *);
524	struct mbuf *n;
525	register struct ip *ip = mtod(m, struct ip *);
526	unsigned optlen;
527
528	optlen = opt->m_len - sizeof(p->ipopt_dst);
529	if (optlen + (u_short)ip->ip_len > IP_MAXPACKET)
530		return (m);		/* XXX should fail */
531	if (p->ipopt_dst.s_addr)
532		ip->ip_dst = p->ipopt_dst;
533	if (m->m_flags & M_EXT || m->m_data - optlen < m->m_pktdat) {
534		MGETHDR(n, M_DONTWAIT, MT_HEADER);
535		if (n == 0)
536			return (m);
537		n->m_pkthdr.len = m->m_pkthdr.len + optlen;
538		m->m_len -= sizeof(struct ip);
539		m->m_data += sizeof(struct ip);
540		n->m_next = m;
541		m = n;
542		m->m_len = optlen + sizeof(struct ip);
543		m->m_data += max_linkhdr;
544		(void)memcpy(mtod(m, void *), ip, sizeof(struct ip));
545	} else {
546		m->m_data -= optlen;
547		m->m_len += optlen;
548		m->m_pkthdr.len += optlen;
549		ovbcopy((caddr_t)ip, mtod(m, caddr_t), sizeof(struct ip));
550	}
551	ip = mtod(m, struct ip *);
552	bcopy(p->ipopt_list, ip + 1, optlen);
553	*phlen = sizeof(struct ip) + optlen;
554	ip->ip_vhl = IP_MAKE_VHL(IPVERSION, *phlen >> 2);
555	ip->ip_len += optlen;
556	return (m);
557}
558
559/*
560 * Copy options from ip to jp,
561 * omitting those not copied during fragmentation.
562 */
563static int
564ip_optcopy(ip, jp)
565	struct ip *ip, *jp;
566{
567	register u_char *cp, *dp;
568	int opt, optlen, cnt;
569
570	cp = (u_char *)(ip + 1);
571	dp = (u_char *)(jp + 1);
572	cnt = (IP_VHL_HL(ip->ip_vhl) << 2) - sizeof (struct ip);
573	for (; cnt > 0; cnt -= optlen, cp += optlen) {
574		opt = cp[0];
575		if (opt == IPOPT_EOL)
576			break;
577		if (opt == IPOPT_NOP) {
578			/* Preserve for IP mcast tunnel's LSRR alignment. */
579			*dp++ = IPOPT_NOP;
580			optlen = 1;
581			continue;
582		} else
583			optlen = cp[IPOPT_OLEN];
584		/* bogus lengths should have been caught by ip_dooptions */
585		if (optlen > cnt)
586			optlen = cnt;
587		if (IPOPT_COPIED(opt)) {
588			bcopy(cp, dp, optlen);
589			dp += optlen;
590		}
591	}
592	for (optlen = dp - (u_char *)(jp+1); optlen & 0x3; optlen++)
593		*dp++ = IPOPT_EOL;
594	return (optlen);
595}
596
597/*
598 * IP socket option processing.
599 */
600int
601ip_ctloutput(op, so, level, optname, mp)
602	int op;
603	struct socket *so;
604	int level, optname;
605	struct mbuf **mp;
606{
607	register struct inpcb *inp = sotoinpcb(so);
608	register struct mbuf *m = *mp;
609	register int optval = 0;
610	int error = 0;
611
612	if (level != IPPROTO_IP) {
613		error = EINVAL;
614		if (op == PRCO_SETOPT && *mp)
615			(void) m_free(*mp);
616	} else switch (op) {
617
618	case PRCO_SETOPT:
619		switch (optname) {
620		case IP_OPTIONS:
621#ifdef notyet
622		case IP_RETOPTS:
623			return (ip_pcbopts(optname, &inp->inp_options, m));
624#else
625			return (ip_pcbopts(&inp->inp_options, m));
626#endif
627
628		case IP_TOS:
629		case IP_TTL:
630		case IP_RECVOPTS:
631		case IP_RECVRETOPTS:
632		case IP_RECVDSTADDR:
633		case IP_RECVIF:
634			if (m == 0 || m->m_len != sizeof(int))
635				error = EINVAL;
636			else {
637				optval = *mtod(m, int *);
638				switch (optname) {
639
640				case IP_TOS:
641					inp->inp_ip.ip_tos = optval;
642					break;
643
644				case IP_TTL:
645					inp->inp_ip.ip_ttl = optval;
646					break;
647#define	OPTSET(bit) \
648	if (optval) \
649		inp->inp_flags |= bit; \
650	else \
651		inp->inp_flags &= ~bit;
652
653				case IP_RECVOPTS:
654					OPTSET(INP_RECVOPTS);
655					break;
656
657				case IP_RECVRETOPTS:
658					OPTSET(INP_RECVRETOPTS);
659					break;
660
661				case IP_RECVDSTADDR:
662					OPTSET(INP_RECVDSTADDR);
663					break;
664
665				case IP_RECVIF:
666					OPTSET(INP_RECVIF);
667					break;
668				}
669			}
670			break;
671#undef OPTSET
672
673		case IP_MULTICAST_IF:
674		case IP_MULTICAST_VIF:
675		case IP_MULTICAST_TTL:
676		case IP_MULTICAST_LOOP:
677		case IP_ADD_MEMBERSHIP:
678		case IP_DROP_MEMBERSHIP:
679			error = ip_setmoptions(optname, &inp->inp_moptions, m);
680			break;
681
682		case IP_PORTRANGE:
683			if (m == 0 || m->m_len != sizeof(int))
684				error = EINVAL;
685			else {
686				optval = *mtod(m, int *);
687
688				switch (optval) {
689
690				case IP_PORTRANGE_DEFAULT:
691					inp->inp_flags &= ~(INP_LOWPORT);
692					inp->inp_flags &= ~(INP_HIGHPORT);
693					break;
694
695				case IP_PORTRANGE_HIGH:
696					inp->inp_flags &= ~(INP_LOWPORT);
697					inp->inp_flags |= INP_HIGHPORT;
698					break;
699
700				case IP_PORTRANGE_LOW:
701					inp->inp_flags &= ~(INP_HIGHPORT);
702					inp->inp_flags |= INP_LOWPORT;
703					break;
704
705				default:
706					error = EINVAL;
707					break;
708				}
709			}
710			break;
711
712		default:
713			error = ENOPROTOOPT;
714			break;
715		}
716		if (m)
717			(void)m_free(m);
718		break;
719
720	case PRCO_GETOPT:
721		switch (optname) {
722		case IP_OPTIONS:
723		case IP_RETOPTS:
724			*mp = m = m_get(M_WAIT, MT_SOOPTS);
725			if (inp->inp_options) {
726				m->m_len = inp->inp_options->m_len;
727				bcopy(mtod(inp->inp_options, void *),
728				    mtod(m, void *), m->m_len);
729			} else
730				m->m_len = 0;
731			break;
732
733		case IP_TOS:
734		case IP_TTL:
735		case IP_RECVOPTS:
736		case IP_RECVRETOPTS:
737		case IP_RECVDSTADDR:
738		case IP_RECVIF:
739			*mp = m = m_get(M_WAIT, MT_SOOPTS);
740			m->m_len = sizeof(int);
741			switch (optname) {
742
743			case IP_TOS:
744				optval = inp->inp_ip.ip_tos;
745				break;
746
747			case IP_TTL:
748				optval = inp->inp_ip.ip_ttl;
749				break;
750
751#define	OPTBIT(bit)	(inp->inp_flags & bit ? 1 : 0)
752
753			case IP_RECVOPTS:
754				optval = OPTBIT(INP_RECVOPTS);
755				break;
756
757			case IP_RECVRETOPTS:
758				optval = OPTBIT(INP_RECVRETOPTS);
759				break;
760
761			case IP_RECVDSTADDR:
762				optval = OPTBIT(INP_RECVDSTADDR);
763				break;
764
765			case IP_RECVIF:
766				optval = OPTBIT(INP_RECVIF);
767				break;
768			}
769			*mtod(m, int *) = optval;
770			break;
771
772		case IP_MULTICAST_IF:
773		case IP_MULTICAST_VIF:
774		case IP_MULTICAST_TTL:
775		case IP_MULTICAST_LOOP:
776		case IP_ADD_MEMBERSHIP:
777		case IP_DROP_MEMBERSHIP:
778			error = ip_getmoptions(optname, inp->inp_moptions, mp);
779			break;
780
781		case IP_PORTRANGE:
782			*mp = m = m_get(M_WAIT, MT_SOOPTS);
783			m->m_len = sizeof(int);
784
785			if (inp->inp_flags & INP_HIGHPORT)
786				optval = IP_PORTRANGE_HIGH;
787			else if (inp->inp_flags & INP_LOWPORT)
788				optval = IP_PORTRANGE_LOW;
789			else
790				optval = 0;
791
792			*mtod(m, int *) = optval;
793			break;
794
795		default:
796			error = ENOPROTOOPT;
797			break;
798		}
799		break;
800	}
801	return (error);
802}
803
804/*
805 * Set up IP options in pcb for insertion in output packets.
806 * Store in mbuf with pointer in pcbopt, adding pseudo-option
807 * with destination address if source routed.
808 */
809static int
810#ifdef notyet
811ip_pcbopts(optname, pcbopt, m)
812	int optname;
813#else
814ip_pcbopts(pcbopt, m)
815#endif
816	struct mbuf **pcbopt;
817	register struct mbuf *m;
818{
819	register cnt, optlen;
820	register u_char *cp;
821	u_char opt;
822
823	/* turn off any old options */
824	if (*pcbopt)
825		(void)m_free(*pcbopt);
826	*pcbopt = 0;
827	if (m == (struct mbuf *)0 || m->m_len == 0) {
828		/*
829		 * Only turning off any previous options.
830		 */
831		if (m)
832			(void)m_free(m);
833		return (0);
834	}
835
836#ifndef	vax
837	if (m->m_len % sizeof(long))
838		goto bad;
839#endif
840	/*
841	 * IP first-hop destination address will be stored before
842	 * actual options; move other options back
843	 * and clear it when none present.
844	 */
845	if (m->m_data + m->m_len + sizeof(struct in_addr) >= &m->m_dat[MLEN])
846		goto bad;
847	cnt = m->m_len;
848	m->m_len += sizeof(struct in_addr);
849	cp = mtod(m, u_char *) + sizeof(struct in_addr);
850	ovbcopy(mtod(m, caddr_t), (caddr_t)cp, (unsigned)cnt);
851	bzero(mtod(m, caddr_t), sizeof(struct in_addr));
852
853	for (; cnt > 0; cnt -= optlen, cp += optlen) {
854		opt = cp[IPOPT_OPTVAL];
855		if (opt == IPOPT_EOL)
856			break;
857		if (opt == IPOPT_NOP)
858			optlen = 1;
859		else {
860			optlen = cp[IPOPT_OLEN];
861			if (optlen <= IPOPT_OLEN || optlen > cnt)
862				goto bad;
863		}
864		switch (opt) {
865
866		default:
867			break;
868
869		case IPOPT_LSRR:
870		case IPOPT_SSRR:
871			/*
872			 * user process specifies route as:
873			 *	->A->B->C->D
874			 * D must be our final destination (but we can't
875			 * check that since we may not have connected yet).
876			 * A is first hop destination, which doesn't appear in
877			 * actual IP option, but is stored before the options.
878			 */
879			if (optlen < IPOPT_MINOFF - 1 + sizeof(struct in_addr))
880				goto bad;
881			m->m_len -= sizeof(struct in_addr);
882			cnt -= sizeof(struct in_addr);
883			optlen -= sizeof(struct in_addr);
884			cp[IPOPT_OLEN] = optlen;
885			/*
886			 * Move first hop before start of options.
887			 */
888			bcopy((caddr_t)&cp[IPOPT_OFFSET+1], mtod(m, caddr_t),
889			    sizeof(struct in_addr));
890			/*
891			 * Then copy rest of options back
892			 * to close up the deleted entry.
893			 */
894			ovbcopy((caddr_t)(&cp[IPOPT_OFFSET+1] +
895			    sizeof(struct in_addr)),
896			    (caddr_t)&cp[IPOPT_OFFSET+1],
897			    (unsigned)cnt + sizeof(struct in_addr));
898			break;
899		}
900	}
901	if (m->m_len > MAX_IPOPTLEN + sizeof(struct in_addr))
902		goto bad;
903	*pcbopt = m;
904	return (0);
905
906bad:
907	(void)m_free(m);
908	return (EINVAL);
909}
910
911/*
912 * Set the IP multicast options in response to user setsockopt().
913 */
914static int
915ip_setmoptions(optname, imop, m)
916	int optname;
917	struct ip_moptions **imop;
918	struct mbuf *m;
919{
920	register int error = 0;
921	u_char loop;
922	register int i;
923	struct in_addr addr;
924	register struct ip_mreq *mreq;
925	register struct ifnet *ifp;
926	register struct ip_moptions *imo = *imop;
927	struct route ro;
928	register struct sockaddr_in *dst;
929	int s;
930
931	if (imo == NULL) {
932		/*
933		 * No multicast option buffer attached to the pcb;
934		 * allocate one and initialize to default values.
935		 */
936		imo = (struct ip_moptions*)malloc(sizeof(*imo), M_IPMOPTS,
937		    M_WAITOK);
938
939		if (imo == NULL)
940			return (ENOBUFS);
941		*imop = imo;
942		imo->imo_multicast_ifp = NULL;
943		imo->imo_multicast_vif = -1;
944		imo->imo_multicast_ttl = IP_DEFAULT_MULTICAST_TTL;
945		imo->imo_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
946		imo->imo_num_memberships = 0;
947	}
948
949	switch (optname) {
950	/* store an index number for the vif you wanna use in the send */
951	case IP_MULTICAST_VIF:
952		if (!legal_vif_num) {
953			error = EOPNOTSUPP;
954			break;
955		}
956		if (m == NULL || m->m_len != sizeof(int)) {
957			error = EINVAL;
958			break;
959		}
960		i = *(mtod(m, int *));
961		if (!legal_vif_num(i) && (i != -1)) {
962			error = EINVAL;
963			break;
964		}
965		imo->imo_multicast_vif = i;
966		break;
967
968	case IP_MULTICAST_IF:
969		/*
970		 * Select the interface for outgoing multicast packets.
971		 */
972		if (m == NULL || m->m_len != sizeof(struct in_addr)) {
973			error = EINVAL;
974			break;
975		}
976		addr = *(mtod(m, struct in_addr *));
977		/*
978		 * INADDR_ANY is used to remove a previous selection.
979		 * When no interface is selected, a default one is
980		 * chosen every time a multicast packet is sent.
981		 */
982		if (addr.s_addr == INADDR_ANY) {
983			imo->imo_multicast_ifp = NULL;
984			break;
985		}
986		/*
987		 * The selected interface is identified by its local
988		 * IP address.  Find the interface and confirm that
989		 * it supports multicasting.
990		 */
991		s = splimp();
992		INADDR_TO_IFP(addr, ifp);
993		if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0) {
994			splx(s);
995			error = EADDRNOTAVAIL;
996			break;
997		}
998		imo->imo_multicast_ifp = ifp;
999		splx(s);
1000		break;
1001
1002	case IP_MULTICAST_TTL:
1003		/*
1004		 * Set the IP time-to-live for outgoing multicast packets.
1005		 */
1006		if (m == NULL || m->m_len != 1) {
1007			error = EINVAL;
1008			break;
1009		}
1010		imo->imo_multicast_ttl = *(mtod(m, u_char *));
1011		break;
1012
1013	case IP_MULTICAST_LOOP:
1014		/*
1015		 * Set the loopback flag for outgoing multicast packets.
1016		 * Must be zero or one.
1017		 */
1018		if (m == NULL || m->m_len != 1 ||
1019		   (loop = *(mtod(m, u_char *))) > 1) {
1020			error = EINVAL;
1021			break;
1022		}
1023		imo->imo_multicast_loop = loop;
1024		break;
1025
1026	case IP_ADD_MEMBERSHIP:
1027		/*
1028		 * Add a multicast group membership.
1029		 * Group must be a valid IP multicast address.
1030		 */
1031		if (m == NULL || m->m_len != sizeof(struct ip_mreq)) {
1032			error = EINVAL;
1033			break;
1034		}
1035		mreq = mtod(m, struct ip_mreq *);
1036		if (!IN_MULTICAST(ntohl(mreq->imr_multiaddr.s_addr))) {
1037			error = EINVAL;
1038			break;
1039		}
1040		s = splimp();
1041		/*
1042		 * If no interface address was provided, use the interface of
1043		 * the route to the given multicast address.
1044		 */
1045		if (mreq->imr_interface.s_addr == INADDR_ANY) {
1046			bzero((caddr_t)&ro, sizeof(ro));
1047			dst = (struct sockaddr_in *)&ro.ro_dst;
1048			dst->sin_len = sizeof(*dst);
1049			dst->sin_family = AF_INET;
1050			dst->sin_addr = mreq->imr_multiaddr;
1051			rtalloc(&ro);
1052			if (ro.ro_rt == NULL) {
1053				error = EADDRNOTAVAIL;
1054				splx(s);
1055				break;
1056			}
1057			ifp = ro.ro_rt->rt_ifp;
1058			rtfree(ro.ro_rt);
1059		}
1060		else {
1061			INADDR_TO_IFP(mreq->imr_interface, ifp);
1062		}
1063
1064		/*
1065		 * See if we found an interface, and confirm that it
1066		 * supports multicast.
1067		 */
1068		if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0) {
1069			error = EADDRNOTAVAIL;
1070			splx(s);
1071			break;
1072		}
1073		/*
1074		 * See if the membership already exists or if all the
1075		 * membership slots are full.
1076		 */
1077		for (i = 0; i < imo->imo_num_memberships; ++i) {
1078			if (imo->imo_membership[i]->inm_ifp == ifp &&
1079			    imo->imo_membership[i]->inm_addr.s_addr
1080						== mreq->imr_multiaddr.s_addr)
1081				break;
1082		}
1083		if (i < imo->imo_num_memberships) {
1084			error = EADDRINUSE;
1085			splx(s);
1086			break;
1087		}
1088		if (i == IP_MAX_MEMBERSHIPS) {
1089			error = ETOOMANYREFS;
1090			splx(s);
1091			break;
1092		}
1093		/*
1094		 * Everything looks good; add a new record to the multicast
1095		 * address list for the given interface.
1096		 */
1097		if ((imo->imo_membership[i] =
1098		    in_addmulti(&mreq->imr_multiaddr, ifp)) == NULL) {
1099			error = ENOBUFS;
1100			splx(s);
1101			break;
1102		}
1103		++imo->imo_num_memberships;
1104		splx(s);
1105		break;
1106
1107	case IP_DROP_MEMBERSHIP:
1108		/*
1109		 * Drop a multicast group membership.
1110		 * Group must be a valid IP multicast address.
1111		 */
1112		if (m == NULL || m->m_len != sizeof(struct ip_mreq)) {
1113			error = EINVAL;
1114			break;
1115		}
1116		mreq = mtod(m, struct ip_mreq *);
1117		if (!IN_MULTICAST(ntohl(mreq->imr_multiaddr.s_addr))) {
1118			error = EINVAL;
1119			break;
1120		}
1121
1122		s = splimp();
1123		/*
1124		 * If an interface address was specified, get a pointer
1125		 * to its ifnet structure.
1126		 */
1127		if (mreq->imr_interface.s_addr == INADDR_ANY)
1128			ifp = NULL;
1129		else {
1130			INADDR_TO_IFP(mreq->imr_interface, ifp);
1131			if (ifp == NULL) {
1132				error = EADDRNOTAVAIL;
1133				splx(s);
1134				break;
1135			}
1136		}
1137		/*
1138		 * Find the membership in the membership array.
1139		 */
1140		for (i = 0; i < imo->imo_num_memberships; ++i) {
1141			if ((ifp == NULL ||
1142			     imo->imo_membership[i]->inm_ifp == ifp) &&
1143			     imo->imo_membership[i]->inm_addr.s_addr ==
1144			     mreq->imr_multiaddr.s_addr)
1145				break;
1146		}
1147		if (i == imo->imo_num_memberships) {
1148			error = EADDRNOTAVAIL;
1149			splx(s);
1150			break;
1151		}
1152		/*
1153		 * Give up the multicast address record to which the
1154		 * membership points.
1155		 */
1156		in_delmulti(imo->imo_membership[i]);
1157		/*
1158		 * Remove the gap in the membership array.
1159		 */
1160		for (++i; i < imo->imo_num_memberships; ++i)
1161			imo->imo_membership[i-1] = imo->imo_membership[i];
1162		--imo->imo_num_memberships;
1163		splx(s);
1164		break;
1165
1166	default:
1167		error = EOPNOTSUPP;
1168		break;
1169	}
1170
1171	/*
1172	 * If all options have default values, no need to keep the mbuf.
1173	 */
1174	if (imo->imo_multicast_ifp == NULL &&
1175	    imo->imo_multicast_vif == -1 &&
1176	    imo->imo_multicast_ttl == IP_DEFAULT_MULTICAST_TTL &&
1177	    imo->imo_multicast_loop == IP_DEFAULT_MULTICAST_LOOP &&
1178	    imo->imo_num_memberships == 0) {
1179		free(*imop, M_IPMOPTS);
1180		*imop = NULL;
1181	}
1182
1183	return (error);
1184}
1185
1186/*
1187 * Return the IP multicast options in response to user getsockopt().
1188 */
1189static int
1190ip_getmoptions(optname, imo, mp)
1191	int optname;
1192	register struct ip_moptions *imo;
1193	register struct mbuf **mp;
1194{
1195	u_char *ttl;
1196	u_char *loop;
1197	struct in_addr *addr;
1198	struct in_ifaddr *ia;
1199
1200	*mp = m_get(M_WAIT, MT_SOOPTS);
1201
1202	switch (optname) {
1203
1204	case IP_MULTICAST_VIF:
1205		if (imo != NULL)
1206			*(mtod(*mp, int *)) = imo->imo_multicast_vif;
1207		else
1208			*(mtod(*mp, int *)) = -1;
1209		(*mp)->m_len = sizeof(int);
1210		return(0);
1211
1212	case IP_MULTICAST_IF:
1213		addr = mtod(*mp, struct in_addr *);
1214		(*mp)->m_len = sizeof(struct in_addr);
1215		if (imo == NULL || imo->imo_multicast_ifp == NULL)
1216			addr->s_addr = INADDR_ANY;
1217		else {
1218			IFP_TO_IA(imo->imo_multicast_ifp, ia);
1219			addr->s_addr = (ia == NULL) ? INADDR_ANY
1220					: IA_SIN(ia)->sin_addr.s_addr;
1221		}
1222		return (0);
1223
1224	case IP_MULTICAST_TTL:
1225		ttl = mtod(*mp, u_char *);
1226		(*mp)->m_len = 1;
1227		*ttl = (imo == NULL) ? IP_DEFAULT_MULTICAST_TTL
1228				     : imo->imo_multicast_ttl;
1229		return (0);
1230
1231	case IP_MULTICAST_LOOP:
1232		loop = mtod(*mp, u_char *);
1233		(*mp)->m_len = 1;
1234		*loop = (imo == NULL) ? IP_DEFAULT_MULTICAST_LOOP
1235				      : imo->imo_multicast_loop;
1236		return (0);
1237
1238	default:
1239		return (EOPNOTSUPP);
1240	}
1241}
1242
1243/*
1244 * Discard the IP multicast options.
1245 */
1246void
1247ip_freemoptions(imo)
1248	register struct ip_moptions *imo;
1249{
1250	register int i;
1251
1252	if (imo != NULL) {
1253		for (i = 0; i < imo->imo_num_memberships; ++i)
1254			in_delmulti(imo->imo_membership[i]);
1255		free(imo, M_IPMOPTS);
1256	}
1257}
1258
1259/*
1260 * Routine called from ip_output() to loop back a copy of an IP multicast
1261 * packet to the input queue of a specified interface.  Note that this
1262 * calls the output routine of the loopback "driver", but with an interface
1263 * pointer that might NOT be a loopback interface -- evil, but easier than
1264 * replicating that code here.
1265 */
1266static void
1267ip_mloopback(ifp, m, dst)
1268	struct ifnet *ifp;
1269	register struct mbuf *m;
1270	register struct sockaddr_in *dst;
1271{
1272	register struct ip *ip;
1273	struct mbuf *copym;
1274
1275	copym = m_copy(m, 0, M_COPYALL);
1276	if (copym != NULL) {
1277		/*
1278		 * We don't bother to fragment if the IP length is greater
1279		 * than the interface's MTU.  Can this possibly matter?
1280		 */
1281		ip = mtod(copym, struct ip *);
1282		ip->ip_len = htons((u_short)ip->ip_len);
1283		ip->ip_off = htons((u_short)ip->ip_off);
1284		ip->ip_sum = 0;
1285		if (ip->ip_vhl == IP_VHL_BORING) {
1286			ip->ip_sum = in_cksum_hdr(ip);
1287		} else {
1288			ip->ip_sum = in_cksum(copym,
1289					      IP_VHL_HL(ip->ip_vhl) << 2);
1290		}
1291		/*
1292		 * NB:
1293		 * We can't simply call ip_input() directly because
1294		 * the ip_mforward() depends on the `input interface'
1295		 * being set to something unreasonable so that we don't
1296		 * attempt to forward the looped-back copy.
1297		 * It's also not clear whether there are any lingering
1298		 * reentrancy problems in other areas which might be
1299		 * exposed by this code.  For the moment, we'll err
1300		 * on the side of safety by continuing to abuse
1301		 * loinput().
1302		 */
1303#ifdef notdef
1304		copym->m_pkthdr.rcvif = &loif[0];
1305		ip_input(copym)
1306#else
1307		(void) looutput(ifp, copym, (struct sockaddr *)dst, NULL);
1308#endif
1309	}
1310}
1311