xref: /openbsd-src/sys/netinet/ip_output.c (revision cba26e98faa2b48aa4705f205ed876af460243a2)
1 /*	$OpenBSD: ip_output.c,v 1.359 2021/01/07 14:51:46 claudio Exp $	*/
2 /*	$NetBSD: ip_output.c,v 1.28 1996/02/13 23:43:07 christos Exp $	*/
3 
4 /*
5  * Copyright (c) 1982, 1986, 1988, 1990, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  *	@(#)ip_output.c	8.3 (Berkeley) 1/21/94
33  */
34 
35 #include "pf.h"
36 
37 #include <sys/param.h>
38 #include <sys/systm.h>
39 #include <sys/mbuf.h>
40 #include <sys/protosw.h>
41 #include <sys/socket.h>
42 #include <sys/socketvar.h>
43 #include <sys/proc.h>
44 #include <sys/kernel.h>
45 
46 #include <net/if.h>
47 #include <net/if_var.h>
48 #include <net/if_enc.h>
49 #include <net/route.h>
50 
51 #include <netinet/in.h>
52 #include <netinet/ip.h>
53 #include <netinet/in_pcb.h>
54 #include <netinet/in_var.h>
55 #include <netinet/ip_var.h>
56 #include <netinet/ip_icmp.h>
57 #include <netinet/tcp.h>
58 #include <netinet/udp.h>
59 #include <netinet/tcp_timer.h>
60 #include <netinet/tcp_var.h>
61 #include <netinet/udp_var.h>
62 
63 #if NPF > 0
64 #include <net/pfvar.h>
65 #endif
66 
67 #ifdef IPSEC
68 #ifdef ENCDEBUG
69 #define DPRINTF(x)    do { if (encdebug) printf x ; } while (0)
70 #else
71 #define DPRINTF(x)
72 #endif
73 #endif /* IPSEC */
74 
75 int ip_pcbopts(struct mbuf **, struct mbuf *);
76 int ip_multicast_if(struct ip_mreqn *, u_int, unsigned int *);
77 int ip_setmoptions(int, struct ip_moptions **, struct mbuf *, u_int);
78 void ip_mloopback(struct ifnet *, struct mbuf *, struct sockaddr_in *);
79 static __inline u_int16_t __attribute__((__unused__))
80     in_cksum_phdr(u_int32_t, u_int32_t, u_int32_t);
81 void in_delayed_cksum(struct mbuf *);
82 
83 #ifdef IPSEC
84 struct tdb *
85 ip_output_ipsec_lookup(struct mbuf *m, int hlen, int *error, struct inpcb *inp,
86     int ipsecflowinfo);
87 int
88 ip_output_ipsec_send(struct tdb *, struct mbuf *, struct route *, int);
89 #endif /* IPSEC */
90 
91 /*
92  * IP output.  The packet in mbuf chain m contains a skeletal IP
93  * header (with len, off, ttl, proto, tos, src, dst).
94  * The mbuf chain containing the packet will be freed.
95  * The mbuf opt, if present, will not be freed.
96  */
97 int
98 ip_output(struct mbuf *m0, struct mbuf *opt, struct route *ro, int flags,
99     struct ip_moptions *imo, struct inpcb *inp, u_int32_t ipsecflowinfo)
100 {
101 	struct ip *ip;
102 	struct ifnet *ifp = NULL;
103 	struct mbuf *m = m0;
104 	int hlen = sizeof (struct ip);
105 	int error = 0;
106 	struct route iproute;
107 	struct sockaddr_in *dst;
108 	struct tdb *tdb = NULL;
109 	u_long mtu;
110 #if defined(MROUTING)
111 	int rv;
112 #endif
113 
114 	NET_ASSERT_LOCKED();
115 
116 #ifdef IPSEC
117 	if (inp && (inp->inp_flags & INP_IPV6) != 0)
118 		panic("ip_output: IPv6 pcb is passed");
119 #endif /* IPSEC */
120 
121 #ifdef	DIAGNOSTIC
122 	if ((m->m_flags & M_PKTHDR) == 0)
123 		panic("ip_output no HDR");
124 #endif
125 	if (opt)
126 		m = ip_insertoptions(m, opt, &hlen);
127 
128 	ip = mtod(m, struct ip *);
129 
130 	/*
131 	 * Fill in IP header.
132 	 */
133 	if ((flags & (IP_FORWARDING|IP_RAWOUTPUT)) == 0) {
134 		ip->ip_v = IPVERSION;
135 		ip->ip_off &= htons(IP_DF);
136 		ip->ip_id = htons(ip_randomid());
137 		ip->ip_hl = hlen >> 2;
138 		ipstat_inc(ips_localout);
139 	} else {
140 		hlen = ip->ip_hl << 2;
141 	}
142 
143 	/*
144 	 * We should not send traffic to 0/8 say both Stevens and RFCs
145 	 * 5735 section 3 and 1122 sections 3.2.1.3 and 3.3.6.
146 	 */
147 	if ((ntohl(ip->ip_dst.s_addr) >> IN_CLASSA_NSHIFT) == 0) {
148 		error = ENETUNREACH;
149 		goto bad;
150 	}
151 
152 #if NPF > 0
153 reroute:
154 #endif
155 
156 	/*
157 	 * Do a route lookup now in case we need the source address to
158 	 * do an SPD lookup in IPsec; for most packets, the source address
159 	 * is set at a higher level protocol. ICMPs and other packets
160 	 * though (e.g., traceroute) have a source address of zeroes.
161 	 */
162 	if (ro == NULL) {
163 		ro = &iproute;
164 		memset(ro, 0, sizeof(*ro));
165 	}
166 
167 	dst = satosin(&ro->ro_dst);
168 
169 	/*
170 	 * If there is a cached route, check that it is to the same
171 	 * destination and is still up.  If not, free it and try again.
172 	 */
173 	if (!rtisvalid(ro->ro_rt) ||
174 	    dst->sin_addr.s_addr != ip->ip_dst.s_addr ||
175 	    ro->ro_tableid != m->m_pkthdr.ph_rtableid) {
176 		rtfree(ro->ro_rt);
177 		ro->ro_rt = NULL;
178 	}
179 
180 	if (ro->ro_rt == NULL) {
181 		dst->sin_family = AF_INET;
182 		dst->sin_len = sizeof(*dst);
183 		dst->sin_addr = ip->ip_dst;
184 		ro->ro_tableid = m->m_pkthdr.ph_rtableid;
185 	}
186 
187 	if ((IN_MULTICAST(ip->ip_dst.s_addr) ||
188 	    (ip->ip_dst.s_addr == INADDR_BROADCAST)) &&
189 	    imo != NULL && (ifp = if_get(imo->imo_ifidx)) != NULL) {
190 
191 		mtu = ifp->if_mtu;
192 		if (ip->ip_src.s_addr == INADDR_ANY) {
193 			struct in_ifaddr *ia;
194 
195 			IFP_TO_IA(ifp, ia);
196 			if (ia != NULL)
197 				ip->ip_src = ia->ia_addr.sin_addr;
198 		}
199 	} else {
200 		struct in_ifaddr *ia;
201 
202 		if (ro->ro_rt == NULL)
203 			ro->ro_rt = rtalloc_mpath(&ro->ro_dst,
204 			    &ip->ip_src.s_addr, ro->ro_tableid);
205 
206 		if (ro->ro_rt == NULL) {
207 			ipstat_inc(ips_noroute);
208 			error = EHOSTUNREACH;
209 			goto bad;
210 		}
211 
212 		ia = ifatoia(ro->ro_rt->rt_ifa);
213 		if (ISSET(ro->ro_rt->rt_flags, RTF_LOCAL))
214 			ifp = if_get(rtable_loindex(m->m_pkthdr.ph_rtableid));
215 		else
216 			ifp = if_get(ro->ro_rt->rt_ifidx);
217 		/*
218 		 * We aren't using rtisvalid() here because the UP/DOWN state
219 		 * machine is broken with some Ethernet drivers like em(4).
220 		 * As a result we might try to use an invalid cached route
221 		 * entry while an interface is being detached.
222 		 */
223 		if (ifp == NULL) {
224 			ipstat_inc(ips_noroute);
225 			error = EHOSTUNREACH;
226 			goto bad;
227 		}
228 		if ((mtu = ro->ro_rt->rt_mtu) == 0)
229 			mtu = ifp->if_mtu;
230 
231 		if (ro->ro_rt->rt_flags & RTF_GATEWAY)
232 			dst = satosin(ro->ro_rt->rt_gateway);
233 
234 		/* Set the source IP address */
235 		if (ip->ip_src.s_addr == INADDR_ANY && ia)
236 			ip->ip_src = ia->ia_addr.sin_addr;
237 	}
238 
239 #ifdef IPSEC
240 	if (ipsec_in_use || inp != NULL) {
241 		/* Do we have any pending SAs to apply ? */
242 		tdb = ip_output_ipsec_lookup(m, hlen, &error, inp,
243 		    ipsecflowinfo);
244 		if (error != 0) {
245 			/* Should silently drop packet */
246 			if (error == -EINVAL)
247 				error = 0;
248 			m_freem(m);
249 			goto done;
250 		}
251 		if (tdb != NULL) {
252 			/*
253 			 * If it needs TCP/UDP hardware-checksumming, do the
254 			 * computation now.
255 			 */
256 			in_proto_cksum_out(m, NULL);
257 		}
258 	}
259 #endif /* IPSEC */
260 
261 	if (IN_MULTICAST(ip->ip_dst.s_addr) ||
262 	    (ip->ip_dst.s_addr == INADDR_BROADCAST)) {
263 
264 		m->m_flags |= (ip->ip_dst.s_addr == INADDR_BROADCAST) ?
265 			M_BCAST : M_MCAST;
266 
267 		/*
268 		 * IP destination address is multicast.  Make sure "dst"
269 		 * still points to the address in "ro".  (It may have been
270 		 * changed to point to a gateway address, above.)
271 		 */
272 		dst = satosin(&ro->ro_dst);
273 
274 		/*
275 		 * See if the caller provided any multicast options
276 		 */
277 		if (imo != NULL)
278 			ip->ip_ttl = imo->imo_ttl;
279 		else
280 			ip->ip_ttl = IP_DEFAULT_MULTICAST_TTL;
281 
282 		/*
283 		 * if we don't know the outgoing ifp yet, we can't generate
284 		 * output
285 		 */
286 		if (!ifp) {
287 			ipstat_inc(ips_noroute);
288 			error = EHOSTUNREACH;
289 			goto bad;
290 		}
291 
292 		/*
293 		 * Confirm that the outgoing interface supports multicast,
294 		 * but only if the packet actually is going out on that
295 		 * interface (i.e., no IPsec is applied).
296 		 */
297 		if ((((m->m_flags & M_MCAST) &&
298 		      (ifp->if_flags & IFF_MULTICAST) == 0) ||
299 		     ((m->m_flags & M_BCAST) &&
300 		      (ifp->if_flags & IFF_BROADCAST) == 0)) && (tdb == NULL)) {
301 			ipstat_inc(ips_noroute);
302 			error = ENETUNREACH;
303 			goto bad;
304 		}
305 
306 		/*
307 		 * If source address not specified yet, use address
308 		 * of outgoing interface.
309 		 */
310 		if (ip->ip_src.s_addr == INADDR_ANY) {
311 			struct in_ifaddr *ia;
312 
313 			IFP_TO_IA(ifp, ia);
314 			if (ia != NULL)
315 				ip->ip_src = ia->ia_addr.sin_addr;
316 		}
317 
318 		if ((imo == NULL || imo->imo_loop) &&
319 		    in_hasmulti(&ip->ip_dst, ifp)) {
320 			/*
321 			 * If we belong to the destination multicast group
322 			 * on the outgoing interface, and the caller did not
323 			 * forbid loopback, loop back a copy.
324 			 * Can't defer TCP/UDP checksumming, do the
325 			 * computation now.
326 			 */
327 			in_proto_cksum_out(m, NULL);
328 			ip_mloopback(ifp, m, dst);
329 		}
330 #ifdef MROUTING
331 		else {
332 			/*
333 			 * If we are acting as a multicast router, perform
334 			 * multicast forwarding as if the packet had just
335 			 * arrived on the interface to which we are about
336 			 * to send.  The multicast forwarding function
337 			 * recursively calls this function, using the
338 			 * IP_FORWARDING flag to prevent infinite recursion.
339 			 *
340 			 * Multicasts that are looped back by ip_mloopback(),
341 			 * above, will be forwarded by the ip_input() routine,
342 			 * if necessary.
343 			 */
344 			if (ipmforwarding && ip_mrouter[ifp->if_rdomain] &&
345 			    (flags & IP_FORWARDING) == 0) {
346 				KERNEL_LOCK();
347 				rv = ip_mforward(m, ifp);
348 				KERNEL_UNLOCK();
349 				if (rv != 0) {
350 					m_freem(m);
351 					goto done;
352 				}
353 			}
354 		}
355 #endif
356 		/*
357 		 * Multicasts with a time-to-live of zero may be looped-
358 		 * back, above, but must not be transmitted on a network.
359 		 * Also, multicasts addressed to the loopback interface
360 		 * are not sent -- the above call to ip_mloopback() will
361 		 * loop back a copy if this host actually belongs to the
362 		 * destination group on the loopback interface.
363 		 */
364 		if (ip->ip_ttl == 0 || (ifp->if_flags & IFF_LOOPBACK) != 0) {
365 			m_freem(m);
366 			goto done;
367 		}
368 
369 		goto sendit;
370 	}
371 
372 	/*
373 	 * Look for broadcast address and verify user is allowed to send
374 	 * such a packet; if the packet is going in an IPsec tunnel, skip
375 	 * this check.
376 	 */
377 	if ((tdb == NULL) && ((dst->sin_addr.s_addr == INADDR_BROADCAST) ||
378 	    (ro && ro->ro_rt && ISSET(ro->ro_rt->rt_flags, RTF_BROADCAST)))) {
379 		if ((ifp->if_flags & IFF_BROADCAST) == 0) {
380 			error = EADDRNOTAVAIL;
381 			goto bad;
382 		}
383 		if ((flags & IP_ALLOWBROADCAST) == 0) {
384 			error = EACCES;
385 			goto bad;
386 		}
387 
388 		/* Don't allow broadcast messages to be fragmented */
389 		if (ntohs(ip->ip_len) > ifp->if_mtu) {
390 			error = EMSGSIZE;
391 			goto bad;
392 		}
393 		m->m_flags |= M_BCAST;
394 	} else
395 		m->m_flags &= ~M_BCAST;
396 
397 sendit:
398 	/*
399 	 * If we're doing Path MTU discovery, we need to set DF unless
400 	 * the route's MTU is locked.
401 	 */
402 	if ((flags & IP_MTUDISC) && ro && ro->ro_rt &&
403 	    (ro->ro_rt->rt_locks & RTV_MTU) == 0)
404 		ip->ip_off |= htons(IP_DF);
405 
406 #ifdef IPSEC
407 	/*
408 	 * Check if the packet needs encapsulation.
409 	 */
410 	if (tdb != NULL) {
411 		/* Callee frees mbuf */
412 		error = ip_output_ipsec_send(tdb, m, ro,
413 		    (flags & IP_FORWARDING) ? 1 : 0);
414 		goto done;
415 	}
416 #endif /* IPSEC */
417 
418 	/*
419 	 * Packet filter
420 	 */
421 #if NPF > 0
422 	if (pf_test(AF_INET, (flags & IP_FORWARDING) ? PF_FWD : PF_OUT,
423 	    ifp, &m) != PF_PASS) {
424 		error = EACCES;
425 		m_freem(m);
426 		goto done;
427 	}
428 	if (m == NULL)
429 		goto done;
430 	ip = mtod(m, struct ip *);
431 	hlen = ip->ip_hl << 2;
432 	if ((m->m_pkthdr.pf.flags & (PF_TAG_REROUTE | PF_TAG_GENERATED)) ==
433 	    (PF_TAG_REROUTE | PF_TAG_GENERATED))
434 		/* already rerun the route lookup, go on */
435 		m->m_pkthdr.pf.flags &= ~(PF_TAG_GENERATED | PF_TAG_REROUTE);
436 	else if (m->m_pkthdr.pf.flags & PF_TAG_REROUTE) {
437 		/* tag as generated to skip over pf_test on rerun */
438 		m->m_pkthdr.pf.flags |= PF_TAG_GENERATED;
439 		ro = NULL;
440 		if_put(ifp); /* drop reference since target changed */
441 		ifp = NULL;
442 		goto reroute;
443 	}
444 #endif
445 	in_proto_cksum_out(m, ifp);
446 
447 #ifdef IPSEC
448 	if (ipsec_in_use && (flags & IP_FORWARDING) && (ipforwarding == 2) &&
449 	    (m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL) == NULL)) {
450 		error = EHOSTUNREACH;
451 		m_freem(m);
452 		goto done;
453 	}
454 #endif
455 
456 	/*
457 	 * If small enough for interface, can just send directly.
458 	 */
459 	if (ntohs(ip->ip_len) <= mtu) {
460 		ip->ip_sum = 0;
461 		if ((ifp->if_capabilities & IFCAP_CSUM_IPv4) &&
462 		    (ifp->if_bridgeidx == 0))
463 			m->m_pkthdr.csum_flags |= M_IPV4_CSUM_OUT;
464 		else {
465 			ipstat_inc(ips_outswcsum);
466 			ip->ip_sum = in_cksum(m, hlen);
467 		}
468 
469 		error = ifp->if_output(ifp, m, sintosa(dst), ro->ro_rt);
470 		goto done;
471 	}
472 
473 	/*
474 	 * Too large for interface; fragment if possible.
475 	 * Must be able to put at least 8 bytes per fragment.
476 	 */
477 	if (ip->ip_off & htons(IP_DF)) {
478 #ifdef IPSEC
479 		if (ip_mtudisc)
480 			ipsec_adjust_mtu(m, ifp->if_mtu);
481 #endif
482 		error = EMSGSIZE;
483 		/*
484 		 * This case can happen if the user changed the MTU
485 		 * of an interface after enabling IP on it.  Because
486 		 * most netifs don't keep track of routes pointing to
487 		 * them, there is no way for one to update all its
488 		 * routes when the MTU is changed.
489 		 */
490 		if (rtisvalid(ro->ro_rt) &&
491 		    ISSET(ro->ro_rt->rt_flags, RTF_HOST) &&
492 		    !(ro->ro_rt->rt_locks & RTV_MTU) &&
493 		    (ro->ro_rt->rt_mtu > ifp->if_mtu)) {
494 			ro->ro_rt->rt_mtu = ifp->if_mtu;
495 		}
496 		ipstat_inc(ips_cantfrag);
497 		goto bad;
498 	}
499 
500 	error = ip_fragment(m, ifp, mtu);
501 	if (error) {
502 		m = m0 = NULL;
503 		goto bad;
504 	}
505 
506 	for (; m; m = m0) {
507 		m0 = m->m_nextpkt;
508 		m->m_nextpkt = 0;
509 		if (error == 0)
510 			error = ifp->if_output(ifp, m, sintosa(dst), ro->ro_rt);
511 		else
512 			m_freem(m);
513 	}
514 
515 	if (error == 0)
516 		ipstat_inc(ips_fragmented);
517 
518 done:
519 	if (ro == &iproute && ro->ro_rt)
520 		rtfree(ro->ro_rt);
521 	if_put(ifp);
522 	return (error);
523 bad:
524 	m_freem(m0);
525 	goto done;
526 }
527 
528 #ifdef IPSEC
529 struct tdb *
530 ip_output_ipsec_lookup(struct mbuf *m, int hlen, int *error, struct inpcb *inp,
531     int ipsecflowinfo)
532 {
533 	struct m_tag *mtag;
534 	struct tdb_ident *tdbi;
535 	struct tdb *tdb;
536 
537 	/* Do we have any pending SAs to apply ? */
538 	tdb = ipsp_spd_lookup(m, AF_INET, hlen, error, IPSP_DIRECTION_OUT,
539 	    NULL, inp, ipsecflowinfo);
540 	if (tdb == NULL)
541 		return NULL;
542 	/* Loop detection */
543 	for (mtag = m_tag_first(m); mtag != NULL; mtag = m_tag_next(m, mtag)) {
544 		if (mtag->m_tag_id != PACKET_TAG_IPSEC_OUT_DONE)
545 			continue;
546 		tdbi = (struct tdb_ident *)(mtag + 1);
547 		if (tdbi->spi == tdb->tdb_spi &&
548 		    tdbi->proto == tdb->tdb_sproto &&
549 		    tdbi->rdomain == tdb->tdb_rdomain &&
550 		    !memcmp(&tdbi->dst, &tdb->tdb_dst,
551 		    sizeof(union sockaddr_union))) {
552 			/* no IPsec needed */
553 			return NULL;
554 		}
555 	}
556 	return tdb;
557 }
558 
559 int
560 ip_output_ipsec_send(struct tdb *tdb, struct mbuf *m, struct route *ro, int fwd)
561 {
562 #if NPF > 0
563 	struct ifnet *encif;
564 #endif
565 	struct ip *ip;
566 	int error;
567 
568 #if NPF > 0
569 	/*
570 	 * Packet filter
571 	 */
572 	if ((encif = enc_getif(tdb->tdb_rdomain, tdb->tdb_tap)) == NULL ||
573 	    pf_test(AF_INET, fwd ? PF_FWD : PF_OUT, encif, &m) != PF_PASS) {
574 		m_freem(m);
575 		return EACCES;
576 	}
577 	if (m == NULL)
578 		return 0;
579 	/*
580 	 * PF_TAG_REROUTE handling or not...
581 	 * Packet is entering IPsec so the routing is
582 	 * already overruled by the IPsec policy.
583 	 * Until now the change was not reconsidered.
584 	 * What's the behaviour?
585 	 */
586 	in_proto_cksum_out(m, encif);
587 #endif
588 
589 	/* Check if we are allowed to fragment */
590 	ip = mtod(m, struct ip *);
591 	if (ip_mtudisc && (ip->ip_off & htons(IP_DF)) && tdb->tdb_mtu &&
592 	    ntohs(ip->ip_len) > tdb->tdb_mtu &&
593 	    tdb->tdb_mtutimeout > gettime()) {
594 		struct rtentry *rt = NULL;
595 		int rt_mtucloned = 0;
596 		int transportmode = 0;
597 
598 		transportmode = (tdb->tdb_dst.sa.sa_family == AF_INET) &&
599 		    (tdb->tdb_dst.sin.sin_addr.s_addr == ip->ip_dst.s_addr);
600 
601 		/* Find a host route to store the mtu in */
602 		if (ro != NULL)
603 			rt = ro->ro_rt;
604 		/* but don't add a PMTU route for transport mode SAs */
605 		if (transportmode)
606 			rt = NULL;
607 		else if (rt == NULL || (rt->rt_flags & RTF_HOST) == 0) {
608 			rt = icmp_mtudisc_clone(ip->ip_dst,
609 			    m->m_pkthdr.ph_rtableid, 1);
610 			rt_mtucloned = 1;
611 		}
612 		DPRINTF(("%s: spi %08x mtu %d rt %p cloned %d\n", __func__,
613 		    ntohl(tdb->tdb_spi), tdb->tdb_mtu, rt, rt_mtucloned));
614 		if (rt != NULL) {
615 			rt->rt_mtu = tdb->tdb_mtu;
616 			if (ro && ro->ro_rt != NULL) {
617 				rtfree(ro->ro_rt);
618 				ro->ro_rt = rtalloc(&ro->ro_dst, RT_RESOLVE,
619 				    m->m_pkthdr.ph_rtableid);
620 			}
621 			if (rt_mtucloned)
622 				rtfree(rt);
623 		}
624 		ipsec_adjust_mtu(m, tdb->tdb_mtu);
625 		m_freem(m);
626 		return EMSGSIZE;
627 	}
628 
629 	/*
630 	 * Clear these -- they'll be set in the recursive invocation
631 	 * as needed.
632 	 */
633 	m->m_flags &= ~(M_MCAST | M_BCAST);
634 
635 	/* Callee frees mbuf */
636 	error = ipsp_process_packet(m, tdb, AF_INET, 0);
637 	if (error) {
638 		ipsecstat_inc(ipsec_odrops);
639 		tdb->tdb_odrops++;
640 	}
641 	return error;
642 }
643 #endif /* IPSEC */
644 
645 int
646 ip_fragment(struct mbuf *m, struct ifnet *ifp, u_long mtu)
647 {
648 	struct ip *ip, *mhip;
649 	struct mbuf *m0;
650 	int len, hlen, off;
651 	int mhlen, firstlen;
652 	struct mbuf **mnext;
653 	int fragments = 0;
654 	int error = 0;
655 
656 	ip = mtod(m, struct ip *);
657 	hlen = ip->ip_hl << 2;
658 
659 	len = (mtu - hlen) &~ 7;
660 	if (len < 8) {
661 		m_freem(m);
662 		return (EMSGSIZE);
663 	}
664 
665 	/*
666 	 * If we are doing fragmentation, we can't defer TCP/UDP
667 	 * checksumming; compute the checksum and clear the flag.
668 	 */
669 	in_proto_cksum_out(m, NULL);
670 	firstlen = len;
671 	mnext = &m->m_nextpkt;
672 
673 	/*
674 	 * Loop through length of segment after first fragment,
675 	 * make new header and copy data of each part and link onto chain.
676 	 */
677 	m0 = m;
678 	mhlen = sizeof (struct ip);
679 	for (off = hlen + len; off < ntohs(ip->ip_len); off += len) {
680 		MGETHDR(m, M_DONTWAIT, MT_HEADER);
681 		if (m == NULL) {
682 			ipstat_inc(ips_odropped);
683 			error = ENOBUFS;
684 			goto sendorfree;
685 		}
686 		*mnext = m;
687 		mnext = &m->m_nextpkt;
688 		m->m_data += max_linkhdr;
689 		mhip = mtod(m, struct ip *);
690 		*mhip = *ip;
691 		/* we must inherit MCAST/BCAST flags, routing table and prio */
692 		m->m_flags |= m0->m_flags & (M_MCAST|M_BCAST);
693 		m->m_pkthdr.ph_rtableid = m0->m_pkthdr.ph_rtableid;
694 		m->m_pkthdr.pf.prio = m0->m_pkthdr.pf.prio;
695 		if (hlen > sizeof (struct ip)) {
696 			mhlen = ip_optcopy(ip, mhip) + sizeof (struct ip);
697 			mhip->ip_hl = mhlen >> 2;
698 		}
699 		m->m_len = mhlen;
700 		mhip->ip_off = ((off - hlen) >> 3) +
701 		    (ntohs(ip->ip_off) & ~IP_MF);
702 		if (ip->ip_off & htons(IP_MF))
703 			mhip->ip_off |= IP_MF;
704 		if (off + len >= ntohs(ip->ip_len))
705 			len = ntohs(ip->ip_len) - off;
706 		else
707 			mhip->ip_off |= IP_MF;
708 		mhip->ip_len = htons((u_int16_t)(len + mhlen));
709 		m->m_next = m_copym(m0, off, len, M_NOWAIT);
710 		if (m->m_next == 0) {
711 			ipstat_inc(ips_odropped);
712 			error = ENOBUFS;
713 			goto sendorfree;
714 		}
715 		m->m_pkthdr.len = mhlen + len;
716 		m->m_pkthdr.ph_ifidx = 0;
717 		mhip->ip_off = htons((u_int16_t)mhip->ip_off);
718 		mhip->ip_sum = 0;
719 		if ((ifp != NULL) &&
720 		    (ifp->if_capabilities & IFCAP_CSUM_IPv4) &&
721 		    (ifp->if_bridgeidx == 0))
722 			m->m_pkthdr.csum_flags |= M_IPV4_CSUM_OUT;
723 		else {
724 			ipstat_inc(ips_outswcsum);
725 			mhip->ip_sum = in_cksum(m, mhlen);
726 		}
727 		ipstat_inc(ips_ofragments);
728 		fragments++;
729 	}
730 	/*
731 	 * Update first fragment by trimming what's been copied out
732 	 * and updating header, then send each fragment (in order).
733 	 */
734 	m = m0;
735 	m_adj(m, hlen + firstlen - ntohs(ip->ip_len));
736 	m->m_pkthdr.len = hlen + firstlen;
737 	ip->ip_len = htons((u_int16_t)m->m_pkthdr.len);
738 	ip->ip_off |= htons(IP_MF);
739 	ip->ip_sum = 0;
740 	if ((ifp != NULL) &&
741 	    (ifp->if_capabilities & IFCAP_CSUM_IPv4) &&
742 	    (ifp->if_bridgeidx == 0))
743 		m->m_pkthdr.csum_flags |= M_IPV4_CSUM_OUT;
744 	else {
745 		ipstat_inc(ips_outswcsum);
746 		ip->ip_sum = in_cksum(m, hlen);
747 	}
748 sendorfree:
749 	if (error) {
750 		for (m = m0; m; m = m0) {
751 			m0 = m->m_nextpkt;
752 			m->m_nextpkt = NULL;
753 			m_freem(m);
754 		}
755 	}
756 
757 	return (error);
758 }
759 
760 /*
761  * Insert IP options into preformed packet.
762  * Adjust IP destination as required for IP source routing,
763  * as indicated by a non-zero in_addr at the start of the options.
764  */
765 struct mbuf *
766 ip_insertoptions(struct mbuf *m, struct mbuf *opt, int *phlen)
767 {
768 	struct ipoption *p = mtod(opt, struct ipoption *);
769 	struct mbuf *n;
770 	struct ip *ip = mtod(m, struct ip *);
771 	unsigned int optlen;
772 
773 	optlen = opt->m_len - sizeof(p->ipopt_dst);
774 	if (optlen + ntohs(ip->ip_len) > IP_MAXPACKET)
775 		return (m);		/* XXX should fail */
776 	if (p->ipopt_dst.s_addr)
777 		ip->ip_dst = p->ipopt_dst;
778 	if (m->m_flags & M_EXT || m->m_data - optlen < m->m_pktdat) {
779 		MGETHDR(n, M_DONTWAIT, MT_HEADER);
780 		if (n == NULL)
781 			return (m);
782 		M_MOVE_HDR(n, m);
783 		n->m_pkthdr.len += optlen;
784 		m->m_len -= sizeof(struct ip);
785 		m->m_data += sizeof(struct ip);
786 		n->m_next = m;
787 		m = n;
788 		m->m_len = optlen + sizeof(struct ip);
789 		m->m_data += max_linkhdr;
790 		memcpy(mtod(m, caddr_t), ip, sizeof(struct ip));
791 	} else {
792 		m->m_data -= optlen;
793 		m->m_len += optlen;
794 		m->m_pkthdr.len += optlen;
795 		memmove(mtod(m, caddr_t), (caddr_t)ip, sizeof(struct ip));
796 	}
797 	ip = mtod(m, struct ip *);
798 	memcpy(ip + 1, p->ipopt_list, optlen);
799 	*phlen = sizeof(struct ip) + optlen;
800 	ip->ip_len = htons(ntohs(ip->ip_len) + optlen);
801 	return (m);
802 }
803 
804 /*
805  * Copy options from ip to jp,
806  * omitting those not copied during fragmentation.
807  */
808 int
809 ip_optcopy(struct ip *ip, struct ip *jp)
810 {
811 	u_char *cp, *dp;
812 	int opt, optlen, cnt;
813 
814 	cp = (u_char *)(ip + 1);
815 	dp = (u_char *)(jp + 1);
816 	cnt = (ip->ip_hl << 2) - sizeof (struct ip);
817 	for (; cnt > 0; cnt -= optlen, cp += optlen) {
818 		opt = cp[0];
819 		if (opt == IPOPT_EOL)
820 			break;
821 		if (opt == IPOPT_NOP) {
822 			/* Preserve for IP mcast tunnel's LSRR alignment. */
823 			*dp++ = IPOPT_NOP;
824 			optlen = 1;
825 			continue;
826 		}
827 #ifdef DIAGNOSTIC
828 		if (cnt < IPOPT_OLEN + sizeof(*cp))
829 			panic("malformed IPv4 option passed to ip_optcopy");
830 #endif
831 		optlen = cp[IPOPT_OLEN];
832 #ifdef DIAGNOSTIC
833 		if (optlen < IPOPT_OLEN + sizeof(*cp) || optlen > cnt)
834 			panic("malformed IPv4 option passed to ip_optcopy");
835 #endif
836 		/* bogus lengths should have been caught by ip_dooptions */
837 		if (optlen > cnt)
838 			optlen = cnt;
839 		if (IPOPT_COPIED(opt)) {
840 			memcpy(dp, cp, optlen);
841 			dp += optlen;
842 		}
843 	}
844 	for (optlen = dp - (u_char *)(jp+1); optlen & 0x3; optlen++)
845 		*dp++ = IPOPT_EOL;
846 	return (optlen);
847 }
848 
849 /*
850  * IP socket option processing.
851  */
852 int
853 ip_ctloutput(int op, struct socket *so, int level, int optname,
854     struct mbuf *m)
855 {
856 	struct inpcb *inp = sotoinpcb(so);
857 	int optval = 0;
858 	struct proc *p = curproc; /* XXX */
859 	int error = 0;
860 	u_int rtid = 0;
861 
862 	if (level != IPPROTO_IP)
863 		return (EINVAL);
864 
865 	switch (op) {
866 	case PRCO_SETOPT:
867 		switch (optname) {
868 		case IP_OPTIONS:
869 			return (ip_pcbopts(&inp->inp_options, m));
870 
871 		case IP_TOS:
872 		case IP_TTL:
873 		case IP_MINTTL:
874 		case IP_RECVOPTS:
875 		case IP_RECVRETOPTS:
876 		case IP_RECVDSTADDR:
877 		case IP_RECVIF:
878 		case IP_RECVTTL:
879 		case IP_RECVDSTPORT:
880 		case IP_RECVRTABLE:
881 		case IP_IPSECFLOWINFO:
882 			if (m == NULL || m->m_len != sizeof(int))
883 				error = EINVAL;
884 			else {
885 				optval = *mtod(m, int *);
886 				switch (optname) {
887 
888 				case IP_TOS:
889 					inp->inp_ip.ip_tos = optval;
890 					break;
891 
892 				case IP_TTL:
893 					if (optval > 0 && optval <= MAXTTL)
894 						inp->inp_ip.ip_ttl = optval;
895 					else if (optval == -1)
896 						inp->inp_ip.ip_ttl = ip_defttl;
897 					else
898 						error = EINVAL;
899 					break;
900 
901 				case IP_MINTTL:
902 					if (optval >= 0 && optval <= MAXTTL)
903 						inp->inp_ip_minttl = optval;
904 					else
905 						error = EINVAL;
906 					break;
907 #define	OPTSET(bit) \
908 	if (optval) \
909 		inp->inp_flags |= bit; \
910 	else \
911 		inp->inp_flags &= ~bit;
912 
913 				case IP_RECVOPTS:
914 					OPTSET(INP_RECVOPTS);
915 					break;
916 
917 				case IP_RECVRETOPTS:
918 					OPTSET(INP_RECVRETOPTS);
919 					break;
920 
921 				case IP_RECVDSTADDR:
922 					OPTSET(INP_RECVDSTADDR);
923 					break;
924 				case IP_RECVIF:
925 					OPTSET(INP_RECVIF);
926 					break;
927 				case IP_RECVTTL:
928 					OPTSET(INP_RECVTTL);
929 					break;
930 				case IP_RECVDSTPORT:
931 					OPTSET(INP_RECVDSTPORT);
932 					break;
933 				case IP_RECVRTABLE:
934 					OPTSET(INP_RECVRTABLE);
935 					break;
936 				case IP_IPSECFLOWINFO:
937 					OPTSET(INP_IPSECFLOWINFO);
938 					break;
939 				}
940 			}
941 			break;
942 #undef OPTSET
943 
944 		case IP_MULTICAST_IF:
945 		case IP_MULTICAST_TTL:
946 		case IP_MULTICAST_LOOP:
947 		case IP_ADD_MEMBERSHIP:
948 		case IP_DROP_MEMBERSHIP:
949 			error = ip_setmoptions(optname, &inp->inp_moptions, m,
950 			    inp->inp_rtableid);
951 			break;
952 
953 		case IP_PORTRANGE:
954 			if (m == NULL || m->m_len != sizeof(int))
955 				error = EINVAL;
956 			else {
957 				optval = *mtod(m, int *);
958 
959 				switch (optval) {
960 
961 				case IP_PORTRANGE_DEFAULT:
962 					inp->inp_flags &= ~(INP_LOWPORT);
963 					inp->inp_flags &= ~(INP_HIGHPORT);
964 					break;
965 
966 				case IP_PORTRANGE_HIGH:
967 					inp->inp_flags &= ~(INP_LOWPORT);
968 					inp->inp_flags |= INP_HIGHPORT;
969 					break;
970 
971 				case IP_PORTRANGE_LOW:
972 					inp->inp_flags &= ~(INP_HIGHPORT);
973 					inp->inp_flags |= INP_LOWPORT;
974 					break;
975 
976 				default:
977 
978 					error = EINVAL;
979 					break;
980 				}
981 			}
982 			break;
983 		case IP_AUTH_LEVEL:
984 		case IP_ESP_TRANS_LEVEL:
985 		case IP_ESP_NETWORK_LEVEL:
986 		case IP_IPCOMP_LEVEL:
987 #ifndef IPSEC
988 			error = EOPNOTSUPP;
989 #else
990 			if (m == NULL || m->m_len != sizeof(int)) {
991 				error = EINVAL;
992 				break;
993 			}
994 			optval = *mtod(m, int *);
995 
996 			if (optval < IPSEC_LEVEL_BYPASS ||
997 			    optval > IPSEC_LEVEL_UNIQUE) {
998 				error = EINVAL;
999 				break;
1000 			}
1001 
1002 			switch (optname) {
1003 			case IP_AUTH_LEVEL:
1004 				if (optval < IPSEC_AUTH_LEVEL_DEFAULT &&
1005 				    suser(p)) {
1006 					error = EACCES;
1007 					break;
1008 				}
1009 				inp->inp_seclevel[SL_AUTH] = optval;
1010 				break;
1011 
1012 			case IP_ESP_TRANS_LEVEL:
1013 				if (optval < IPSEC_ESP_TRANS_LEVEL_DEFAULT &&
1014 				    suser(p)) {
1015 					error = EACCES;
1016 					break;
1017 				}
1018 				inp->inp_seclevel[SL_ESP_TRANS] = optval;
1019 				break;
1020 
1021 			case IP_ESP_NETWORK_LEVEL:
1022 				if (optval < IPSEC_ESP_NETWORK_LEVEL_DEFAULT &&
1023 				    suser(p)) {
1024 					error = EACCES;
1025 					break;
1026 				}
1027 				inp->inp_seclevel[SL_ESP_NETWORK] = optval;
1028 				break;
1029 			case IP_IPCOMP_LEVEL:
1030 				if (optval < IPSEC_IPCOMP_LEVEL_DEFAULT &&
1031 				    suser(p)) {
1032 					error = EACCES;
1033 					break;
1034 				}
1035 				inp->inp_seclevel[SL_IPCOMP] = optval;
1036 				break;
1037 			}
1038 #endif
1039 			break;
1040 
1041 		case IP_IPSEC_LOCAL_ID:
1042 		case IP_IPSEC_REMOTE_ID:
1043 			error = EOPNOTSUPP;
1044 			break;
1045 		case SO_RTABLE:
1046 			if (m == NULL || m->m_len < sizeof(u_int)) {
1047 				error = EINVAL;
1048 				break;
1049 			}
1050 			rtid = *mtod(m, u_int *);
1051 			if (inp->inp_rtableid == rtid)
1052 				break;
1053 			/* needs privileges to switch when already set */
1054 			if (p->p_p->ps_rtableid != rtid &&
1055 			    p->p_p->ps_rtableid != 0 &&
1056 			    (error = suser(p)) != 0)
1057 				break;
1058 			/* table must exist */
1059 			if (!rtable_exists(rtid)) {
1060 				error = EINVAL;
1061 				break;
1062 			}
1063 			if (inp->inp_lport) {
1064 				error = EBUSY;
1065 				break;
1066 			}
1067 			inp->inp_rtableid = rtid;
1068 			in_pcbrehash(inp);
1069 			break;
1070 		case IP_PIPEX:
1071 			if (m != NULL && m->m_len == sizeof(int))
1072 				inp->inp_pipex = *mtod(m, int *);
1073 			else
1074 				error = EINVAL;
1075 			break;
1076 
1077 		default:
1078 			error = ENOPROTOOPT;
1079 			break;
1080 		}
1081 		break;
1082 
1083 	case PRCO_GETOPT:
1084 		switch (optname) {
1085 		case IP_OPTIONS:
1086 		case IP_RETOPTS:
1087 			if (inp->inp_options) {
1088 				m->m_len = inp->inp_options->m_len;
1089 				memcpy(mtod(m, caddr_t),
1090 				    mtod(inp->inp_options, caddr_t), m->m_len);
1091 			} else
1092 				m->m_len = 0;
1093 			break;
1094 
1095 		case IP_TOS:
1096 		case IP_TTL:
1097 		case IP_MINTTL:
1098 		case IP_RECVOPTS:
1099 		case IP_RECVRETOPTS:
1100 		case IP_RECVDSTADDR:
1101 		case IP_RECVIF:
1102 		case IP_RECVTTL:
1103 		case IP_RECVDSTPORT:
1104 		case IP_RECVRTABLE:
1105 		case IP_IPSECFLOWINFO:
1106 		case IP_IPDEFTTL:
1107 			m->m_len = sizeof(int);
1108 			switch (optname) {
1109 
1110 			case IP_TOS:
1111 				optval = inp->inp_ip.ip_tos;
1112 				break;
1113 
1114 			case IP_TTL:
1115 				optval = inp->inp_ip.ip_ttl;
1116 				break;
1117 
1118 			case IP_MINTTL:
1119 				optval = inp->inp_ip_minttl;
1120 				break;
1121 
1122 			case IP_IPDEFTTL:
1123 				optval = ip_defttl;
1124 				break;
1125 
1126 #define	OPTBIT(bit)	(inp->inp_flags & bit ? 1 : 0)
1127 
1128 			case IP_RECVOPTS:
1129 				optval = OPTBIT(INP_RECVOPTS);
1130 				break;
1131 
1132 			case IP_RECVRETOPTS:
1133 				optval = OPTBIT(INP_RECVRETOPTS);
1134 				break;
1135 
1136 			case IP_RECVDSTADDR:
1137 				optval = OPTBIT(INP_RECVDSTADDR);
1138 				break;
1139 			case IP_RECVIF:
1140 				optval = OPTBIT(INP_RECVIF);
1141 				break;
1142 			case IP_RECVTTL:
1143 				optval = OPTBIT(INP_RECVTTL);
1144 				break;
1145 			case IP_RECVDSTPORT:
1146 				optval = OPTBIT(INP_RECVDSTPORT);
1147 				break;
1148 			case IP_RECVRTABLE:
1149 				optval = OPTBIT(INP_RECVRTABLE);
1150 				break;
1151 			case IP_IPSECFLOWINFO:
1152 				optval = OPTBIT(INP_IPSECFLOWINFO);
1153 				break;
1154 			}
1155 			*mtod(m, int *) = optval;
1156 			break;
1157 
1158 		case IP_MULTICAST_IF:
1159 		case IP_MULTICAST_TTL:
1160 		case IP_MULTICAST_LOOP:
1161 		case IP_ADD_MEMBERSHIP:
1162 		case IP_DROP_MEMBERSHIP:
1163 			error = ip_getmoptions(optname, inp->inp_moptions, m);
1164 			break;
1165 
1166 		case IP_PORTRANGE:
1167 			m->m_len = sizeof(int);
1168 
1169 			if (inp->inp_flags & INP_HIGHPORT)
1170 				optval = IP_PORTRANGE_HIGH;
1171 			else if (inp->inp_flags & INP_LOWPORT)
1172 				optval = IP_PORTRANGE_LOW;
1173 			else
1174 				optval = 0;
1175 
1176 			*mtod(m, int *) = optval;
1177 			break;
1178 
1179 		case IP_AUTH_LEVEL:
1180 		case IP_ESP_TRANS_LEVEL:
1181 		case IP_ESP_NETWORK_LEVEL:
1182 		case IP_IPCOMP_LEVEL:
1183 #ifndef IPSEC
1184 			m->m_len = sizeof(int);
1185 			*mtod(m, int *) = IPSEC_LEVEL_NONE;
1186 #else
1187 			m->m_len = sizeof(int);
1188 			switch (optname) {
1189 			case IP_AUTH_LEVEL:
1190 				optval = inp->inp_seclevel[SL_AUTH];
1191 				break;
1192 
1193 			case IP_ESP_TRANS_LEVEL:
1194 				optval = inp->inp_seclevel[SL_ESP_TRANS];
1195 				break;
1196 
1197 			case IP_ESP_NETWORK_LEVEL:
1198 				optval = inp->inp_seclevel[SL_ESP_NETWORK];
1199 				break;
1200 			case IP_IPCOMP_LEVEL:
1201 				optval = inp->inp_seclevel[SL_IPCOMP];
1202 				break;
1203 			}
1204 			*mtod(m, int *) = optval;
1205 #endif
1206 			break;
1207 		case IP_IPSEC_LOCAL_ID:
1208 		case IP_IPSEC_REMOTE_ID:
1209 			error = EOPNOTSUPP;
1210 			break;
1211 		case SO_RTABLE:
1212 			m->m_len = sizeof(u_int);
1213 			*mtod(m, u_int *) = inp->inp_rtableid;
1214 			break;
1215 		case IP_PIPEX:
1216 			m->m_len = sizeof(int);
1217 			*mtod(m, int *) = inp->inp_pipex;
1218 			break;
1219 		default:
1220 			error = ENOPROTOOPT;
1221 			break;
1222 		}
1223 		break;
1224 	}
1225 	return (error);
1226 }
1227 
1228 /*
1229  * Set up IP options in pcb for insertion in output packets.
1230  * Store in mbuf with pointer in pcbopt, adding pseudo-option
1231  * with destination address if source routed.
1232  */
1233 int
1234 ip_pcbopts(struct mbuf **pcbopt, struct mbuf *m)
1235 {
1236 	struct mbuf *n;
1237 	struct ipoption *p;
1238 	int cnt, off, optlen;
1239 	u_char *cp;
1240 	u_char opt;
1241 
1242 	/* turn off any old options */
1243 	m_freem(*pcbopt);
1244 	*pcbopt = NULL;
1245 	if (m == NULL || m->m_len == 0) {
1246 		/*
1247 		 * Only turning off any previous options.
1248 		 */
1249 		return (0);
1250 	}
1251 
1252 	if (m->m_len % sizeof(int32_t) ||
1253 	    m->m_len > MAX_IPOPTLEN + sizeof(struct in_addr))
1254 		return (EINVAL);
1255 
1256 	/* Don't sleep because NET_LOCK() is hold. */
1257 	if ((n = m_get(M_NOWAIT, MT_SOOPTS)) == NULL)
1258 		return (ENOBUFS);
1259 	p = mtod(n, struct ipoption *);
1260 	memset(p, 0, sizeof (*p));	/* 0 = IPOPT_EOL, needed for padding */
1261 	n->m_len = sizeof(struct in_addr);
1262 
1263 	off = 0;
1264 	cnt = m->m_len;
1265 	cp = mtod(m, u_char *);
1266 
1267 	while (cnt > 0) {
1268 		opt = cp[IPOPT_OPTVAL];
1269 
1270 		if (opt == IPOPT_NOP || opt == IPOPT_EOL) {
1271 			optlen = 1;
1272 		} else {
1273 			if (cnt < IPOPT_OLEN + sizeof(*cp))
1274 				goto bad;
1275 			optlen = cp[IPOPT_OLEN];
1276 			if (optlen < IPOPT_OLEN  + sizeof(*cp) || optlen > cnt)
1277 				goto bad;
1278 		}
1279 		switch (opt) {
1280 		default:
1281 			memcpy(p->ipopt_list + off, cp, optlen);
1282 			break;
1283 
1284 		case IPOPT_LSRR:
1285 		case IPOPT_SSRR:
1286 			/*
1287 			 * user process specifies route as:
1288 			 *	->A->B->C->D
1289 			 * D must be our final destination (but we can't
1290 			 * check that since we may not have connected yet).
1291 			 * A is first hop destination, which doesn't appear in
1292 			 * actual IP option, but is stored before the options.
1293 			 */
1294 			if (optlen < IPOPT_MINOFF - 1 + sizeof(struct in_addr))
1295 				goto bad;
1296 
1297 			/*
1298 			 * Optlen is smaller because first address is popped.
1299 			 * Cnt and cp will be adjusted a bit later to reflect
1300 			 * this.
1301 			 */
1302 			optlen -= sizeof(struct in_addr);
1303 			p->ipopt_list[off + IPOPT_OPTVAL] = opt;
1304 			p->ipopt_list[off + IPOPT_OLEN] = optlen;
1305 
1306 			/*
1307 			 * Move first hop before start of options.
1308 			 */
1309 			memcpy(&p->ipopt_dst, cp + IPOPT_OFFSET,
1310 			    sizeof(struct in_addr));
1311 			cp += sizeof(struct in_addr);
1312 			cnt -= sizeof(struct in_addr);
1313 			/*
1314 			 * Then copy rest of options
1315 			 */
1316 			memcpy(p->ipopt_list + off + IPOPT_OFFSET,
1317 			    cp + IPOPT_OFFSET, optlen - IPOPT_OFFSET);
1318 			break;
1319 		}
1320 		off += optlen;
1321 		cp += optlen;
1322 		cnt -= optlen;
1323 
1324 		if (opt == IPOPT_EOL)
1325 			break;
1326 	}
1327 	/* pad options to next word, since p was zeroed just adjust off */
1328 	off = (off + sizeof(int32_t) - 1) & ~(sizeof(int32_t) - 1);
1329 	n->m_len += off;
1330 	if (n->m_len > sizeof(*p)) {
1331  bad:
1332 		m_freem(n);
1333 		return (EINVAL);
1334 	}
1335 
1336 	*pcbopt = n;
1337 	return (0);
1338 }
1339 
1340 /*
1341  * Lookup the interface based on the information in the ip_mreqn struct.
1342  */
1343 int
1344 ip_multicast_if(struct ip_mreqn *mreq, u_int rtableid, unsigned int *ifidx)
1345 {
1346 	struct sockaddr_in sin;
1347 	struct rtentry *rt;
1348 
1349 	/*
1350 	 * In case userland provides the imr_ifindex use this as interface.
1351 	 * If no interface address was provided, use the interface of
1352 	 * the route to the given multicast address.
1353 	 */
1354 	if (mreq->imr_ifindex != 0) {
1355 		*ifidx = mreq->imr_ifindex;
1356 	} else if (mreq->imr_address.s_addr == INADDR_ANY) {
1357 		memset(&sin, 0, sizeof(sin));
1358 		sin.sin_len = sizeof(sin);
1359 		sin.sin_family = AF_INET;
1360 		sin.sin_addr = mreq->imr_multiaddr;
1361 		rt = rtalloc(sintosa(&sin), RT_RESOLVE, rtableid);
1362 		if (!rtisvalid(rt)) {
1363 			rtfree(rt);
1364 			return EADDRNOTAVAIL;
1365 		}
1366 		*ifidx = rt->rt_ifidx;
1367 		rtfree(rt);
1368 	} else {
1369 		memset(&sin, 0, sizeof(sin));
1370 		sin.sin_len = sizeof(sin);
1371 		sin.sin_family = AF_INET;
1372 		sin.sin_addr = mreq->imr_address;
1373 		rt = rtalloc(sintosa(&sin), 0, rtableid);
1374 		if (!rtisvalid(rt) || !ISSET(rt->rt_flags, RTF_LOCAL)) {
1375 			rtfree(rt);
1376 			return EADDRNOTAVAIL;
1377 		}
1378 		*ifidx = rt->rt_ifidx;
1379 		rtfree(rt);
1380 	}
1381 
1382 	return 0;
1383 }
1384 
1385 /*
1386  * Set the IP multicast options in response to user setsockopt().
1387  */
1388 int
1389 ip_setmoptions(int optname, struct ip_moptions **imop, struct mbuf *m,
1390     u_int rtableid)
1391 {
1392 	struct in_addr addr;
1393 	struct in_ifaddr *ia;
1394 	struct ip_mreqn mreqn;
1395 	struct ifnet *ifp = NULL;
1396 	struct ip_moptions *imo = *imop;
1397 	struct in_multi **immp;
1398 	struct sockaddr_in sin;
1399 	unsigned int ifidx;
1400 	int i, error = 0;
1401 	u_char loop;
1402 
1403 	if (imo == NULL) {
1404 		/*
1405 		 * No multicast option buffer attached to the pcb;
1406 		 * allocate one and initialize to default values.
1407 		 */
1408 		imo = malloc(sizeof(*imo), M_IPMOPTS, M_WAITOK|M_ZERO);
1409 		immp = mallocarray(IP_MIN_MEMBERSHIPS, sizeof(*immp), M_IPMOPTS,
1410 		    M_WAITOK|M_ZERO);
1411 		*imop = imo;
1412 		imo->imo_ifidx = 0;
1413 		imo->imo_ttl = IP_DEFAULT_MULTICAST_TTL;
1414 		imo->imo_loop = IP_DEFAULT_MULTICAST_LOOP;
1415 		imo->imo_num_memberships = 0;
1416 		imo->imo_max_memberships = IP_MIN_MEMBERSHIPS;
1417 		imo->imo_membership = immp;
1418 	}
1419 
1420 	switch (optname) {
1421 
1422 	case IP_MULTICAST_IF:
1423 		/*
1424 		 * Select the interface for outgoing multicast packets.
1425 		 */
1426 		if (m == NULL || m->m_len != sizeof(struct in_addr)) {
1427 			error = EINVAL;
1428 			break;
1429 		}
1430 		addr = *(mtod(m, struct in_addr *));
1431 		/*
1432 		 * INADDR_ANY is used to remove a previous selection.
1433 		 * When no interface is selected, a default one is
1434 		 * chosen every time a multicast packet is sent.
1435 		 */
1436 		if (addr.s_addr == INADDR_ANY) {
1437 			imo->imo_ifidx = 0;
1438 			break;
1439 		}
1440 		/*
1441 		 * The selected interface is identified by its local
1442 		 * IP address.  Find the interface and confirm that
1443 		 * it supports multicasting.
1444 		 */
1445 		memset(&sin, 0, sizeof(sin));
1446 		sin.sin_len = sizeof(sin);
1447 		sin.sin_family = AF_INET;
1448 		sin.sin_addr = addr;
1449 		ia = ifatoia(ifa_ifwithaddr(sintosa(&sin), rtableid));
1450 		if (ia == NULL ||
1451 		    (ia->ia_ifp->if_flags & IFF_MULTICAST) == 0) {
1452 			error = EADDRNOTAVAIL;
1453 			break;
1454 		}
1455 		imo->imo_ifidx = ia->ia_ifp->if_index;
1456 		break;
1457 
1458 	case IP_MULTICAST_TTL:
1459 		/*
1460 		 * Set the IP time-to-live for outgoing multicast packets.
1461 		 */
1462 		if (m == NULL || m->m_len != 1) {
1463 			error = EINVAL;
1464 			break;
1465 		}
1466 		imo->imo_ttl = *(mtod(m, u_char *));
1467 		break;
1468 
1469 	case IP_MULTICAST_LOOP:
1470 		/*
1471 		 * Set the loopback flag for outgoing multicast packets.
1472 		 * Must be zero or one.
1473 		 */
1474 		if (m == NULL || m->m_len != 1 ||
1475 		   (loop = *(mtod(m, u_char *))) > 1) {
1476 			error = EINVAL;
1477 			break;
1478 		}
1479 		imo->imo_loop = loop;
1480 		break;
1481 
1482 	case IP_ADD_MEMBERSHIP:
1483 		/*
1484 		 * Add a multicast group membership.
1485 		 * Group must be a valid IP multicast address.
1486 		 */
1487 		if (m == NULL || !(m->m_len == sizeof(struct ip_mreq) ||
1488 		    m->m_len == sizeof(struct ip_mreqn))) {
1489 			error = EINVAL;
1490 			break;
1491 		}
1492 		memset(&mreqn, 0, sizeof(mreqn));
1493 		memcpy(&mreqn, mtod(m, void *), m->m_len);
1494 		if (!IN_MULTICAST(mreqn.imr_multiaddr.s_addr)) {
1495 			error = EINVAL;
1496 			break;
1497 		}
1498 
1499 		error = ip_multicast_if(&mreqn, rtableid, &ifidx);
1500 		if (error)
1501 			break;
1502 
1503 		/*
1504 		 * See if we found an interface, and confirm that it
1505 		 * supports multicast.
1506 		 */
1507 		ifp = if_get(ifidx);
1508 		if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0) {
1509 			error = EADDRNOTAVAIL;
1510 			if_put(ifp);
1511 			break;
1512 		}
1513 
1514 		/*
1515 		 * See if the membership already exists or if all the
1516 		 * membership slots are full.
1517 		 */
1518 		for (i = 0; i < imo->imo_num_memberships; ++i) {
1519 			if (imo->imo_membership[i]->inm_ifidx == ifidx &&
1520 			    imo->imo_membership[i]->inm_addr.s_addr
1521 						== mreqn.imr_multiaddr.s_addr)
1522 				break;
1523 		}
1524 		if (i < imo->imo_num_memberships) {
1525 			error = EADDRINUSE;
1526 			if_put(ifp);
1527 			break;
1528 		}
1529 		if (imo->imo_num_memberships == imo->imo_max_memberships) {
1530 			struct in_multi **nmships, **omships;
1531 			size_t newmax;
1532 			/*
1533 			 * Resize the vector to next power-of-two minus 1. If
1534 			 * the size would exceed the maximum then we know we've
1535 			 * really run out of entries. Otherwise, we reallocate
1536 			 * the vector.
1537 			 */
1538 			nmships = NULL;
1539 			omships = imo->imo_membership;
1540 			newmax = ((imo->imo_max_memberships + 1) * 2) - 1;
1541 			if (newmax <= IP_MAX_MEMBERSHIPS) {
1542 				nmships = mallocarray(newmax, sizeof(*nmships),
1543 				    M_IPMOPTS, M_NOWAIT|M_ZERO);
1544 				if (nmships != NULL) {
1545 					memcpy(nmships, omships,
1546 					    sizeof(*omships) *
1547 					    imo->imo_max_memberships);
1548 					free(omships, M_IPMOPTS,
1549 					    sizeof(*omships) *
1550 					    imo->imo_max_memberships);
1551 					imo->imo_membership = nmships;
1552 					imo->imo_max_memberships = newmax;
1553 				}
1554 			}
1555 			if (nmships == NULL) {
1556 				error = ENOBUFS;
1557 				if_put(ifp);
1558 				break;
1559 			}
1560 		}
1561 		/*
1562 		 * Everything looks good; add a new record to the multicast
1563 		 * address list for the given interface.
1564 		 */
1565 		if ((imo->imo_membership[i] =
1566 		    in_addmulti(&mreqn.imr_multiaddr, ifp)) == NULL) {
1567 			error = ENOBUFS;
1568 			if_put(ifp);
1569 			break;
1570 		}
1571 		++imo->imo_num_memberships;
1572 		if_put(ifp);
1573 		break;
1574 
1575 	case IP_DROP_MEMBERSHIP:
1576 		/*
1577 		 * Drop a multicast group membership.
1578 		 * Group must be a valid IP multicast address.
1579 		 */
1580 		if (m == NULL || !(m->m_len == sizeof(struct ip_mreq) ||
1581 		    m->m_len == sizeof(struct ip_mreqn))) {
1582 			error = EINVAL;
1583 			break;
1584 		}
1585 		memset(&mreqn, 0, sizeof(mreqn));
1586 		memcpy(&mreqn, mtod(m, void *), m->m_len);
1587 		if (!IN_MULTICAST(mreqn.imr_multiaddr.s_addr)) {
1588 			error = EINVAL;
1589 			break;
1590 		}
1591 
1592 		/*
1593 		 * If an interface address was specified, get a pointer
1594 		 * to its ifnet structure.
1595 		 */
1596 		error = ip_multicast_if(&mreqn, rtableid, &ifidx);
1597 		if (error)
1598 			break;
1599 
1600 		/*
1601 		 * Find the membership in the membership array.
1602 		 */
1603 		for (i = 0; i < imo->imo_num_memberships; ++i) {
1604 			if ((ifidx == 0 ||
1605 			    imo->imo_membership[i]->inm_ifidx == ifidx) &&
1606 			     imo->imo_membership[i]->inm_addr.s_addr ==
1607 			     mreqn.imr_multiaddr.s_addr)
1608 				break;
1609 		}
1610 		if (i == imo->imo_num_memberships) {
1611 			error = EADDRNOTAVAIL;
1612 			break;
1613 		}
1614 		/*
1615 		 * Give up the multicast address record to which the
1616 		 * membership points.
1617 		 */
1618 		in_delmulti(imo->imo_membership[i]);
1619 		/*
1620 		 * Remove the gap in the membership array.
1621 		 */
1622 		for (++i; i < imo->imo_num_memberships; ++i)
1623 			imo->imo_membership[i-1] = imo->imo_membership[i];
1624 		--imo->imo_num_memberships;
1625 		break;
1626 
1627 	default:
1628 		error = EOPNOTSUPP;
1629 		break;
1630 	}
1631 
1632 	/*
1633 	 * If all options have default values, no need to keep the data.
1634 	 */
1635 	if (imo->imo_ifidx == 0 &&
1636 	    imo->imo_ttl == IP_DEFAULT_MULTICAST_TTL &&
1637 	    imo->imo_loop == IP_DEFAULT_MULTICAST_LOOP &&
1638 	    imo->imo_num_memberships == 0) {
1639 		free(imo->imo_membership , M_IPMOPTS,
1640 		    imo->imo_max_memberships * sizeof(struct in_multi *));
1641 		free(*imop, M_IPMOPTS, sizeof(**imop));
1642 		*imop = NULL;
1643 	}
1644 
1645 	return (error);
1646 }
1647 
1648 /*
1649  * Return the IP multicast options in response to user getsockopt().
1650  */
1651 int
1652 ip_getmoptions(int optname, struct ip_moptions *imo, struct mbuf *m)
1653 {
1654 	u_char *ttl;
1655 	u_char *loop;
1656 	struct in_addr *addr;
1657 	struct in_ifaddr *ia;
1658 	struct ifnet *ifp;
1659 
1660 	switch (optname) {
1661 
1662 	case IP_MULTICAST_IF:
1663 		addr = mtod(m, struct in_addr *);
1664 		m->m_len = sizeof(struct in_addr);
1665 		if (imo == NULL || (ifp = if_get(imo->imo_ifidx)) == NULL)
1666 			addr->s_addr = INADDR_ANY;
1667 		else {
1668 			IFP_TO_IA(ifp, ia);
1669 			if_put(ifp);
1670 			addr->s_addr = (ia == NULL) ? INADDR_ANY
1671 					: ia->ia_addr.sin_addr.s_addr;
1672 		}
1673 		return (0);
1674 
1675 	case IP_MULTICAST_TTL:
1676 		ttl = mtod(m, u_char *);
1677 		m->m_len = 1;
1678 		*ttl = (imo == NULL) ? IP_DEFAULT_MULTICAST_TTL
1679 				     : imo->imo_ttl;
1680 		return (0);
1681 
1682 	case IP_MULTICAST_LOOP:
1683 		loop = mtod(m, u_char *);
1684 		m->m_len = 1;
1685 		*loop = (imo == NULL) ? IP_DEFAULT_MULTICAST_LOOP
1686 				      : imo->imo_loop;
1687 		return (0);
1688 
1689 	default:
1690 		return (EOPNOTSUPP);
1691 	}
1692 }
1693 
1694 /*
1695  * Discard the IP multicast options.
1696  */
1697 void
1698 ip_freemoptions(struct ip_moptions *imo)
1699 {
1700 	int i;
1701 
1702 	if (imo != NULL) {
1703 		for (i = 0; i < imo->imo_num_memberships; ++i)
1704 			in_delmulti(imo->imo_membership[i]);
1705 		free(imo->imo_membership, M_IPMOPTS,
1706 		    imo->imo_max_memberships * sizeof(struct in_multi *));
1707 		free(imo, M_IPMOPTS, sizeof(*imo));
1708 	}
1709 }
1710 
1711 /*
1712  * Routine called from ip_output() to loop back a copy of an IP multicast
1713  * packet to the input queue of a specified interface.
1714  */
1715 void
1716 ip_mloopback(struct ifnet *ifp, struct mbuf *m, struct sockaddr_in *dst)
1717 {
1718 	struct ip *ip;
1719 	struct mbuf *copym;
1720 
1721 	copym = m_dup_pkt(m, max_linkhdr, M_DONTWAIT);
1722 	if (copym != NULL) {
1723 		/*
1724 		 * We don't bother to fragment if the IP length is greater
1725 		 * than the interface's MTU.  Can this possibly matter?
1726 		 */
1727 		ip = mtod(copym, struct ip *);
1728 		ip->ip_sum = 0;
1729 		ip->ip_sum = in_cksum(copym, ip->ip_hl << 2);
1730 		if_input_local(ifp, copym, dst->sin_family);
1731 	}
1732 }
1733 
1734 /*
1735  *	Compute significant parts of the IPv4 checksum pseudo-header
1736  *	for use in a delayed TCP/UDP checksum calculation.
1737  */
1738 static __inline u_int16_t __attribute__((__unused__))
1739 in_cksum_phdr(u_int32_t src, u_int32_t dst, u_int32_t lenproto)
1740 {
1741 	u_int32_t sum;
1742 
1743 	sum = lenproto +
1744 	      (u_int16_t)(src >> 16) +
1745 	      (u_int16_t)(src /*& 0xffff*/) +
1746 	      (u_int16_t)(dst >> 16) +
1747 	      (u_int16_t)(dst /*& 0xffff*/);
1748 
1749 	sum = (u_int16_t)(sum >> 16) + (u_int16_t)(sum /*& 0xffff*/);
1750 
1751 	if (sum > 0xffff)
1752 		sum -= 0xffff;
1753 
1754 	return (sum);
1755 }
1756 
1757 /*
1758  * Process a delayed payload checksum calculation.
1759  */
1760 void
1761 in_delayed_cksum(struct mbuf *m)
1762 {
1763 	struct ip *ip;
1764 	u_int16_t csum, offset;
1765 
1766 	ip = mtod(m, struct ip *);
1767 	offset = ip->ip_hl << 2;
1768 	csum = in4_cksum(m, 0, offset, m->m_pkthdr.len - offset);
1769 	if (csum == 0 && ip->ip_p == IPPROTO_UDP)
1770 		csum = 0xffff;
1771 
1772 	switch (ip->ip_p) {
1773 	case IPPROTO_TCP:
1774 		offset += offsetof(struct tcphdr, th_sum);
1775 		break;
1776 
1777 	case IPPROTO_UDP:
1778 		offset += offsetof(struct udphdr, uh_sum);
1779 		break;
1780 
1781 	case IPPROTO_ICMP:
1782 		offset += offsetof(struct icmp, icmp_cksum);
1783 		break;
1784 
1785 	default:
1786 		return;
1787 	}
1788 
1789 	if ((offset + sizeof(u_int16_t)) > m->m_len)
1790 		m_copyback(m, offset, sizeof(csum), &csum, M_NOWAIT);
1791 	else
1792 		*(u_int16_t *)(mtod(m, caddr_t) + offset) = csum;
1793 }
1794 
1795 void
1796 in_proto_cksum_out(struct mbuf *m, struct ifnet *ifp)
1797 {
1798 	struct ip *ip = mtod(m, struct ip *);
1799 
1800 	/* some hw and in_delayed_cksum need the pseudo header cksum */
1801 	if (m->m_pkthdr.csum_flags &
1802 	    (M_TCP_CSUM_OUT|M_UDP_CSUM_OUT|M_ICMP_CSUM_OUT)) {
1803 		u_int16_t csum = 0, offset;
1804 
1805 		offset = ip->ip_hl << 2;
1806 		if (m->m_pkthdr.csum_flags & (M_TCP_CSUM_OUT|M_UDP_CSUM_OUT))
1807 			csum = in_cksum_phdr(ip->ip_src.s_addr,
1808 			    ip->ip_dst.s_addr, htonl(ntohs(ip->ip_len) -
1809 			    offset + ip->ip_p));
1810 		if (ip->ip_p == IPPROTO_TCP)
1811 			offset += offsetof(struct tcphdr, th_sum);
1812 		else if (ip->ip_p == IPPROTO_UDP)
1813 			offset += offsetof(struct udphdr, uh_sum);
1814 		else if (ip->ip_p == IPPROTO_ICMP)
1815 			offset += offsetof(struct icmp, icmp_cksum);
1816 		if ((offset + sizeof(u_int16_t)) > m->m_len)
1817 			m_copyback(m, offset, sizeof(csum), &csum, M_NOWAIT);
1818 		else
1819 			*(u_int16_t *)(mtod(m, caddr_t) + offset) = csum;
1820 	}
1821 
1822 	if (m->m_pkthdr.csum_flags & M_TCP_CSUM_OUT) {
1823 		if (!ifp || !(ifp->if_capabilities & IFCAP_CSUM_TCPv4) ||
1824 		    ip->ip_hl != 5 || ifp->if_bridgeidx != 0) {
1825 			tcpstat_inc(tcps_outswcsum);
1826 			in_delayed_cksum(m);
1827 			m->m_pkthdr.csum_flags &= ~M_TCP_CSUM_OUT; /* Clear */
1828 		}
1829 	} else if (m->m_pkthdr.csum_flags & M_UDP_CSUM_OUT) {
1830 		if (!ifp || !(ifp->if_capabilities & IFCAP_CSUM_UDPv4) ||
1831 		    ip->ip_hl != 5 || ifp->if_bridgeidx != 0) {
1832 			udpstat_inc(udps_outswcsum);
1833 			in_delayed_cksum(m);
1834 			m->m_pkthdr.csum_flags &= ~M_UDP_CSUM_OUT; /* Clear */
1835 		}
1836 	} else if (m->m_pkthdr.csum_flags & M_ICMP_CSUM_OUT) {
1837 		in_delayed_cksum(m);
1838 		m->m_pkthdr.csum_flags &= ~M_ICMP_CSUM_OUT; /* Clear */
1839 	}
1840 }
1841