2 * Copyright (c) 1982, 1986, 1988, 1990, 1993
3 * The Regents of the University of California. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
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. Neither the name of the University nor the names of its contributors
14 * may be used to endorse or promote products derived from this software
15 * without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * @(#)ip_output.c 8.3 (Berkeley) 1/21/94
30 * $FreeBSD: src/sys/netinet/ip_output.c,v 1.99.2.37 2003/04/15 06:44:45 silby Exp $
31 * $DragonFly: src/sys/netinet/ip_output.c,v 1.62 2008/09/13 08:48:42 sephe Exp $
38 #include "opt_ipdivert.h"
39 #include "opt_ipfilter.h"
40 #include "opt_ipsec.h"
41 #include "opt_mbuf_stress_test.h"
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/kernel.h>
47 #include <sys/malloc.h>
49 #include <sys/protosw.h>
50 #include <sys/socket.h>
51 #include <sys/socketvar.h>
53 #include <sys/sysctl.h>
54 #include <sys/thread2.h>
55 #include <sys/in_cksum.h>
58 #include <net/netisr.h>
60 #include <net/route.h>
62 #include <netinet/in.h>
63 #include <netinet/in_systm.h>
64 #include <netinet/ip.h>
65 #include <netinet/in_pcb.h>
66 #include <netinet/in_var.h>
67 #include <netinet/ip_var.h>
68 #include <netinet/ip_divert.h>
70 #include <netproto/mpls/mpls_var.h>
72 static MALLOC_DEFINE(M_IPMOPTS, "ip_moptions", "internet multicast options");
75 #include <netinet6/ipsec.h>
76 #include <netproto/key/key.h>
78 #include <netproto/key/key_debug.h>
80 #define KEYDEBUG(lev,arg)
85 #include <netproto/ipsec/ipsec.h>
86 #include <netproto/ipsec/xform.h>
87 #include <netproto/ipsec/key.h>
90 #include <net/ipfw/ip_fw.h>
91 #include <net/dummynet/ip_dummynet.h>
93 #define print_ip(x, a, y) kprintf("%s %d.%d.%d.%d%s",\
94 x, (ntohl(a.s_addr)>>24)&0xFF,\
95 (ntohl(a.s_addr)>>16)&0xFF,\
96 (ntohl(a.s_addr)>>8)&0xFF,\
97 (ntohl(a.s_addr))&0xFF, y);
101 #ifdef MBUF_STRESS_TEST
102 int mbuf_frag_size = 0;
103 SYSCTL_INT(_net_inet_ip, OID_AUTO, mbuf_frag_size, CTLFLAG_RW,
104 &mbuf_frag_size, 0, "Fragment outgoing mbufs to this size");
107 static struct mbuf *ip_insertoptions(struct mbuf *, struct mbuf *, int *);
108 static struct ifnet *ip_multicast_if(struct in_addr *, int *);
109 static void ip_mloopback
110 (struct ifnet *, struct mbuf *, struct sockaddr_in *, int);
111 static int ip_getmoptions
112 (struct sockopt *, struct ip_moptions *);
113 static int ip_pcbopts(int, struct mbuf **, struct mbuf *);
114 static int ip_setmoptions
115 (struct sockopt *, struct ip_moptions **);
117 int ip_optcopy(struct ip *, struct ip *);
119 extern int route_assert_owner_access;
120 extern void db_print_backtrace(void);
122 extern struct protosw inetsw[];
125 ip_localforward(struct mbuf *m, const struct sockaddr_in *dst)
127 struct in_ifaddr_container *iac;
130 * We need to figure out if we have been forwarded to a local
131 * socket. If so, then we should somehow "loop back" to
132 * ip_input(), and get directed to the PCB as if we had received
133 * this packet. This is because it may be difficult to identify
134 * the packets you want to forward until they are being output
135 * and have selected an interface (e.g. locally initiated
136 * packets). If we used the loopback inteface, we would not be
137 * able to control what happens as the packet runs through
138 * ip_input() as it is done through a ISR.
140 LIST_FOREACH(iac, INADDR_HASH(dst->sin_addr.s_addr), ia_hash) {
142 * If the addr to forward to is one of ours, we pretend
143 * to be the destination for this packet.
145 if (IA_SIN(iac->ia)->sin_addr.s_addr == dst->sin_addr.s_addr)
149 struct ip *ip = mtod(m, struct ip *);
151 if (m->m_pkthdr.rcvif == NULL)
152 m->m_pkthdr.rcvif = ifunit("lo0");
153 if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
154 m->m_pkthdr.csum_flags |= CSUM_DATA_VALID |
156 m->m_pkthdr.csum_data = 0xffff;
158 m->m_pkthdr.csum_flags |= CSUM_IP_CHECKED | CSUM_IP_VALID;
160 ip->ip_len = htons(ip->ip_len);
161 ip->ip_off = htons(ip->ip_off);
164 return 1; /* Packet gets forwarded locally */
170 * IP output. The packet in mbuf chain m contains a skeletal IP
171 * header (with len, off, ttl, proto, tos, src, dst).
172 * The mbuf chain containing the packet will be freed.
173 * The mbuf opt, if present, will not be freed.
176 ip_output(struct mbuf *m0, struct mbuf *opt, struct route *ro,
177 int flags, struct ip_moptions *imo, struct inpcb *inp)
180 struct ifnet *ifp = NULL; /* keep compiler happy */
182 int hlen = sizeof(struct ip);
183 int len, off, error = 0;
184 struct sockaddr_in *dst = NULL; /* keep compiler happy */
185 struct in_ifaddr *ia = NULL;
186 int isbroadcast, sw_csum;
187 struct in_addr pkt_dst;
188 struct route iproute;
191 struct secpolicy *sp = NULL;
192 struct socket *so = inp ? inp->inp_socket : NULL;
195 struct secpolicy *sp = NULL;
196 struct tdb_ident *tdbi;
197 #endif /* FAST_IPSEC */
198 struct sockaddr_in *next_hop = NULL;
199 int src_was_INADDR_ANY = 0; /* as the name says... */
206 bzero(ro, sizeof *ro);
207 } else if (ro->ro_rt != NULL && ro->ro_rt->rt_cpuid != mycpuid) {
208 if (flags & IP_DEBUGROUTE) {
209 if (route_assert_owner_access) {
211 "rt rt_cpuid %d accessed on cpu %d\n",
212 ro->ro_rt->rt_cpuid, mycpuid);
214 kprintf("ip_output: "
215 "rt rt_cpuid %d accessed on cpu %d\n",
216 ro->ro_rt->rt_cpuid, mycpuid);
217 db_print_backtrace();
223 * If the cached rtentry's owner CPU is not the current CPU,
224 * then don't touch the cached rtentry (remote free is too
225 * expensive in this context); just relocate the route.
228 bzero(ro, sizeof *ro);
231 if (m->m_pkthdr.fw_flags & IPFORWARD_MBUF_TAGGED) {
233 mtag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL);
234 KKASSERT(mtag != NULL);
235 next_hop = m_tag_data(mtag);
238 if (m->m_pkthdr.fw_flags & DUMMYNET_MBUF_TAGGED) {
239 struct dn_pkt *dn_pkt;
241 /* Extract info from dummynet tag */
242 mtag = m_tag_find(m, PACKET_TAG_DUMMYNET, NULL);
243 KKASSERT(mtag != NULL);
244 dn_pkt = m_tag_data(mtag);
247 * The packet was already tagged, so part of the
248 * processing was already done, and we need to go down.
249 * Get the calculated parameters from the tag.
253 KKASSERT(ro == &iproute);
254 *ro = dn_pkt->ro; /* structure copy */
255 KKASSERT(ro->ro_rt == NULL || ro->ro_rt->rt_cpuid == mycpuid);
257 dst = dn_pkt->dn_dst;
258 if (dst == (struct sockaddr_in *)&(dn_pkt->ro.ro_dst)) {
259 /* If 'dst' points into dummynet tag, adjust it */
260 dst = (struct sockaddr_in *)&(ro->ro_dst);
263 ip = mtod(m, struct ip *);
264 hlen = IP_VHL_HL(ip->ip_vhl) << 2 ;
266 ia = ifatoia(ro->ro_rt->rt_ifa);
272 m = ip_insertoptions(m, opt, &len);
276 ip = mtod(m, struct ip *);
281 if (!(flags & (IP_FORWARDING|IP_RAWOUTPUT))) {
282 ip->ip_vhl = IP_MAKE_VHL(IPVERSION, hlen >> 2);
284 ip->ip_id = ip_newid();
285 ipstat.ips_localout++;
287 hlen = IP_VHL_HL(ip->ip_vhl) << 2;
291 pkt_dst = next_hop ? next_hop->sin_addr : ip->ip_dst;
293 dst = (struct sockaddr_in *)&ro->ro_dst;
295 * If there is a cached route,
296 * check that it is to the same destination
297 * and is still up. If not, free it and try again.
298 * The address family should also be checked in case of sharing the
302 (!(ro->ro_rt->rt_flags & RTF_UP) ||
303 dst->sin_family != AF_INET ||
304 dst->sin_addr.s_addr != pkt_dst.s_addr)) {
306 ro->ro_rt = (struct rtentry *)NULL;
308 if (ro->ro_rt == NULL) {
309 bzero(dst, sizeof *dst);
310 dst->sin_family = AF_INET;
311 dst->sin_len = sizeof *dst;
312 dst->sin_addr = pkt_dst;
315 * If routing to interface only,
316 * short circuit routing lookup.
318 if (flags & IP_ROUTETOIF) {
319 if ((ia = ifatoia(ifa_ifwithdstaddr(sintosa(dst)))) == NULL &&
320 (ia = ifatoia(ifa_ifwithnet(sintosa(dst)))) == NULL) {
321 ipstat.ips_noroute++;
327 isbroadcast = in_broadcast(dst->sin_addr, ifp);
328 } else if (IN_MULTICAST(ntohl(pkt_dst.s_addr)) &&
329 imo != NULL && imo->imo_multicast_ifp != NULL) {
331 * Bypass the normal routing lookup for multicast
332 * packets if the interface is specified.
334 ifp = imo->imo_multicast_ifp;
336 isbroadcast = 0; /* fool gcc */
339 * If this is the case, we probably don't want to allocate
340 * a protocol-cloned route since we didn't get one from the
341 * ULP. This lets TCP do its thing, while not burdening
342 * forwarding or ICMP with the overhead of cloning a route.
343 * Of course, we still want to do any cloning requested by
344 * the link layer, as this is probably required in all cases
345 * for correct operation (as it is for ARP).
347 if (ro->ro_rt == NULL)
348 rtalloc_ign(ro, RTF_PRCLONING);
349 if (ro->ro_rt == NULL) {
350 ipstat.ips_noroute++;
351 error = EHOSTUNREACH;
354 ia = ifatoia(ro->ro_rt->rt_ifa);
355 ifp = ro->ro_rt->rt_ifp;
357 if (ro->ro_rt->rt_flags & RTF_GATEWAY)
358 dst = (struct sockaddr_in *)ro->ro_rt->rt_gateway;
359 if (ro->ro_rt->rt_flags & RTF_HOST)
360 isbroadcast = (ro->ro_rt->rt_flags & RTF_BROADCAST);
362 isbroadcast = in_broadcast(dst->sin_addr, ifp);
364 if (IN_MULTICAST(ntohl(pkt_dst.s_addr))) {
365 struct in_multi *inm;
367 m->m_flags |= M_MCAST;
369 * IP destination address is multicast. Make sure "dst"
370 * still points to the address in "ro". (It may have been
371 * changed to point to a gateway address, above.)
373 dst = (struct sockaddr_in *)&ro->ro_dst;
375 * See if the caller provided any multicast options
378 ip->ip_ttl = imo->imo_multicast_ttl;
379 if (imo->imo_multicast_vif != -1)
382 ip_mcast_src(imo->imo_multicast_vif) :
385 ip->ip_ttl = IP_DEFAULT_MULTICAST_TTL;
387 * Confirm that the outgoing interface supports multicast.
389 if ((imo == NULL) || (imo->imo_multicast_vif == -1)) {
390 if (!(ifp->if_flags & IFF_MULTICAST)) {
391 ipstat.ips_noroute++;
397 * If source address not specified yet, use address
398 * of outgoing interface.
400 if (ip->ip_src.s_addr == INADDR_ANY) {
401 /* Interface may have no addresses. */
403 ip->ip_src = IA_SIN(ia)->sin_addr;
406 IN_LOOKUP_MULTI(pkt_dst, ifp, inm);
408 (imo == NULL || imo->imo_multicast_loop)) {
410 * If we belong to the destination multicast group
411 * on the outgoing interface, and the caller did not
412 * forbid loopback, loop back a copy.
414 ip_mloopback(ifp, m, dst, hlen);
418 * If we are acting as a multicast router, perform
419 * multicast forwarding as if the packet had just
420 * arrived on the interface to which we are about
421 * to send. The multicast forwarding function
422 * recursively calls this function, using the
423 * IP_FORWARDING flag to prevent infinite recursion.
425 * Multicasts that are looped back by ip_mloopback(),
426 * above, will be forwarded by the ip_input() routine,
429 if (ip_mrouter && !(flags & IP_FORWARDING)) {
431 * If rsvp daemon is not running, do not
432 * set ip_moptions. This ensures that the packet
433 * is multicast and not just sent down one link
434 * as prescribed by rsvpd.
439 ip_mforward(ip, ifp, m, imo) != 0) {
447 * Multicasts with a time-to-live of zero may be looped-
448 * back, above, but must not be transmitted on a network.
449 * Also, multicasts addressed to the loopback interface
450 * are not sent -- the above call to ip_mloopback() will
451 * loop back a copy if this host actually belongs to the
452 * destination group on the loopback interface.
454 if (ip->ip_ttl == 0 || ifp->if_flags & IFF_LOOPBACK) {
461 m->m_flags &= ~M_MCAST;
465 * If the source address is not specified yet, use the address
466 * of the outoing interface. In case, keep note we did that, so
467 * if the the firewall changes the next-hop causing the output
468 * interface to change, we can fix that.
470 if (ip->ip_src.s_addr == INADDR_ANY || src_was_INADDR_ANY) {
471 /* Interface may have no addresses. */
473 ip->ip_src = IA_SIN(ia)->sin_addr;
474 src_was_INADDR_ANY = 1;
480 * Disable packet drop hack.
481 * Packetdrop should be done by queueing.
485 * Verify that we have any chance at all of being able to queue
486 * the packet or packet fragments
488 if ((ifp->if_snd.ifq_len + ip->ip_len / ifp->if_mtu + 1) >=
489 ifp->if_snd.ifq_maxlen) {
491 ipstat.ips_odropped++;
497 * Look for broadcast address and
498 * verify user is allowed to send
502 if (!(ifp->if_flags & IFF_BROADCAST)) {
503 error = EADDRNOTAVAIL;
506 if (!(flags & IP_ALLOWBROADCAST)) {
510 /* don't allow broadcast messages to be fragmented */
511 if (ip->ip_len > ifp->if_mtu) {
515 m->m_flags |= M_BCAST;
517 m->m_flags &= ~M_BCAST;
522 /* get SP for this packet */
524 sp = ipsec4_getpolicybyaddr(m, IPSEC_DIR_OUTBOUND, flags, &error);
526 sp = ipsec4_getpolicybysock(m, IPSEC_DIR_OUTBOUND, so, &error);
529 ipsecstat.out_inval++;
536 switch (sp->policy) {
537 case IPSEC_POLICY_DISCARD:
539 * This packet is just discarded.
541 ipsecstat.out_polvio++;
544 case IPSEC_POLICY_BYPASS:
545 case IPSEC_POLICY_NONE:
546 /* no need to do IPsec. */
549 case IPSEC_POLICY_IPSEC:
550 if (sp->req == NULL) {
551 /* acquire a policy */
552 error = key_spdacquire(sp);
557 case IPSEC_POLICY_ENTRUST:
559 kprintf("ip_output: Invalid policy found. %d\n", sp->policy);
562 struct ipsec_output_state state;
563 bzero(&state, sizeof state);
565 if (flags & IP_ROUTETOIF) {
567 bzero(&iproute, sizeof iproute);
570 state.dst = (struct sockaddr *)dst;
576 * delayed checksums are not currently compatible with IPsec
578 if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
580 m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
583 ip->ip_len = htons(ip->ip_len);
584 ip->ip_off = htons(ip->ip_off);
586 error = ipsec4_output(&state, sp, flags);
589 if (flags & IP_ROUTETOIF) {
591 * if we have tunnel mode SA, we may need to ignore
594 if (state.ro != &iproute || state.ro->ro_rt != NULL) {
595 flags &= ~IP_ROUTETOIF;
600 dst = (struct sockaddr_in *)state.dst;
602 /* mbuf is already reclaimed in ipsec4_output. */
612 kprintf("ip4_output (ipsec): error code %d\n", error);
615 /* don't show these error codes to the user */
623 /* be sure to update variables that are affected by ipsec4_output() */
624 ip = mtod(m, struct ip *);
626 hlen = IP_VHL_HL(ip->ip_vhl) << 2;
628 hlen = ip->ip_hl << 2;
630 if (ro->ro_rt == NULL) {
631 if (!(flags & IP_ROUTETOIF)) {
632 kprintf("ip_output: "
633 "can't update route after IPsec processing\n");
634 error = EHOSTUNREACH; /*XXX*/
638 ia = ifatoia(ro->ro_rt->rt_ifa);
639 ifp = ro->ro_rt->rt_ifp;
642 /* make it flipped, again. */
643 ip->ip_len = ntohs(ip->ip_len);
644 ip->ip_off = ntohs(ip->ip_off);
649 * Check the security policy (SP) for the packet and, if
650 * required, do IPsec-related processing. There are two
651 * cases here; the first time a packet is sent through
652 * it will be untagged and handled by ipsec4_checkpolicy.
653 * If the packet is resubmitted to ip_output (e.g. after
654 * AH, ESP, etc. processing), there will be a tag to bypass
655 * the lookup and related policy checking.
657 mtag = m_tag_find(m, PACKET_TAG_IPSEC_PENDING_TDB, NULL);
660 tdbi = (struct tdb_ident *)m_tag_data(mtag);
661 sp = ipsec_getpolicy(tdbi, IPSEC_DIR_OUTBOUND);
663 error = -EINVAL; /* force silent drop */
664 m_tag_delete(m, mtag);
666 sp = ipsec4_checkpolicy(m, IPSEC_DIR_OUTBOUND, flags,
670 * There are four return cases:
671 * sp != NULL apply IPsec policy
672 * sp == NULL, error == 0 no IPsec handling needed
673 * sp == NULL, error == -EINVAL discard packet w/o error
674 * sp == NULL, error != 0 discard packet, report error
677 /* Loop detection, check if ipsec processing already done */
678 KASSERT(sp->req != NULL, ("ip_output: no ipsec request"));
679 for (mtag = m_tag_first(m); mtag != NULL;
680 mtag = m_tag_next(m, mtag)) {
681 if (mtag->m_tag_cookie != MTAG_ABI_COMPAT)
683 if (mtag->m_tag_id != PACKET_TAG_IPSEC_OUT_DONE &&
684 mtag->m_tag_id != PACKET_TAG_IPSEC_OUT_CRYPTO_NEEDED)
687 * Check if policy has an SA associated with it.
688 * This can happen when an SP has yet to acquire
689 * an SA; e.g. on first reference. If it occurs,
690 * then we let ipsec4_process_packet do its thing.
692 if (sp->req->sav == NULL)
694 tdbi = (struct tdb_ident *)m_tag_data(mtag);
695 if (tdbi->spi == sp->req->sav->spi &&
696 tdbi->proto == sp->req->sav->sah->saidx.proto &&
697 bcmp(&tdbi->dst, &sp->req->sav->sah->saidx.dst,
698 sizeof(union sockaddr_union)) == 0) {
700 * No IPsec processing is needed, free
703 * NB: null pointer to avoid free at
706 KEY_FREESP(&sp), sp = NULL;
713 * Do delayed checksums now because we send before
714 * this is done in the normal processing path.
716 if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
718 m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
721 ip->ip_len = htons(ip->ip_len);
722 ip->ip_off = htons(ip->ip_off);
724 /* NB: callee frees mbuf */
725 error = ipsec4_process_packet(m, sp->req, flags, 0);
727 * Preserve KAME behaviour: ENOENT can be returned
728 * when an SA acquire is in progress. Don't propagate
729 * this to user-level; it confuses applications.
731 * XXX this will go away when the SADB is redone.
742 * Hack: -EINVAL is used to signal that a packet
743 * should be silently discarded. This is typically
744 * because we asked key management for an SA and
745 * it was delayed (e.g. kicked up to IKE).
747 if (error == -EINVAL)
751 /* No IPsec processing for this packet. */
755 * If deferred crypto processing is needed, check that
756 * the interface supports it.
758 mtag = m_tag_find(m, PACKET_TAG_IPSEC_OUT_CRYPTO_NEEDED, NULL);
759 if (mtag != NULL && !(ifp->if_capenable & IFCAP_IPSEC)) {
760 /* notify IPsec to do its own crypto */
761 ipsp_skipcrypto_unmark((struct tdb_ident *)m_tag_data(mtag));
762 error = EHOSTUNREACH;
768 #endif /* FAST_IPSEC */
770 /* We are already being fwd'd from a firewall. */
771 if (next_hop != NULL)
776 * - Xlate: translate packet's addr/port (NAT).
777 * - Firewall: deny/allow/etc.
778 * - Wrap: fake packet's addr/port <unimpl.>
779 * - Encapsulate: put it in another IP and send out. <unimp.>
783 * Run through list of hooks for output packets.
785 if (pfil_has_hooks(&inet_pfil_hook)) {
786 error = pfil_run_hooks(&inet_pfil_hook, &m, ifp, PFIL_OUT);
787 if (error != 0 || m == NULL)
789 ip = mtod(m, struct ip *);
793 * Check with the firewall...
795 if (fw_enable && IPFW_LOADED) {
796 struct ip_fw_args args;
799 if (m->m_pkthdr.fw_flags & DUMMYNET_MBUF_TAGGED) {
800 /* Extract info from dummynet tag */
801 mtag = m_tag_find(m, PACKET_TAG_DUMMYNET, NULL);
802 KKASSERT(mtag != NULL);
804 ((struct dn_pkt *)m_tag_data(mtag))->dn_priv;
805 KKASSERT(args.rule != NULL);
807 m_tag_delete(m, mtag);
808 m->m_pkthdr.fw_flags &= ~DUMMYNET_MBUF_TAGGED;
816 off = ip_fw_chk_ptr(&args);
823 ip = mtod(m, struct ip *);
836 ip_fw_dn_io_ptr(m, args.cookie, DN_TO_IP_OUT, &args);
844 if (ip_divert_p != NULL) {
845 m = ip_divert_p(m, tee, 0);
848 ip = mtod(m, struct ip *);
852 /* not sure this is the right error msg */
858 panic("unknown ipfw return value: %d\n", off);
862 if (m->m_pkthdr.fw_flags & IPFORWARD_MBUF_TAGGED) {
864 * Check dst to make sure it is directly reachable on the
865 * interface we previously thought it was.
866 * If it isn't (which may be likely in some situations) we have
867 * to re-route it (ie, find a route for the next-hop and the
868 * associated interface) and set them here. This is nested
869 * forwarding which in most cases is undesirable, except where
870 * such control is nigh impossible. So we do it here.
873 mtag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL);
874 KKASSERT(mtag != NULL);
875 next_hop = m_tag_data(mtag);
878 * Try local forwarding first
880 if (ip_localforward(m, next_hop))
884 * Relocate the route based on next_hop.
885 * If the current route is inp's cache, keep it untouched.
887 if (ro == &iproute && ro->ro_rt != NULL) {
892 bzero(ro, sizeof *ro);
895 * Forwarding to broadcast address is not allowed.
896 * XXX Should we follow IP_ROUTETOIF?
898 flags &= ~(IP_ALLOWBROADCAST | IP_ROUTETOIF);
900 /* We are doing forwarding now */
901 flags |= IP_FORWARDING;
906 if (m->m_pkthdr.fw_flags & DUMMYNET_MBUF_TAGGED) {
907 struct dn_pkt *dn_pkt;
909 mtag = m_tag_find(m, PACKET_TAG_DUMMYNET, NULL);
910 KKASSERT(mtag != NULL);
911 dn_pkt = m_tag_data(mtag);
914 * Under certain cases it is not possible to recalculate
915 * 'ro' and 'dst', let alone 'flags', so just save them in
916 * dummynet tag and avoid the possible wrong reculcalation
917 * when we come back to ip_output() again.
919 * All other parameters have been already used and so they
920 * are not needed anymore.
921 * XXX if the ifp is deleted while a pkt is in dummynet,
922 * we are in trouble! (TODO use ifnet_detach_event)
924 * We need to copy *ro because for ICMP pkts (and maybe
925 * others) the caller passed a pointer into the stack;
926 * dst might also be a pointer into *ro so it needs to
931 ro->ro_rt->rt_refcnt++;
932 if (dst == (struct sockaddr_in *)&ro->ro_dst) {
933 /* 'dst' points into 'ro' */
934 dst = (struct sockaddr_in *)&(dn_pkt->ro.ro_dst);
936 dn_pkt->dn_dst = dst;
937 dn_pkt->flags = flags;
943 /* 127/8 must not appear on wire - RFC1122. */
944 if ((ntohl(ip->ip_dst.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET ||
945 (ntohl(ip->ip_src.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET) {
946 if (!(ifp->if_flags & IFF_LOOPBACK)) {
947 ipstat.ips_badaddr++;
948 error = EADDRNOTAVAIL;
953 m->m_pkthdr.csum_flags |= CSUM_IP;
954 sw_csum = m->m_pkthdr.csum_flags & ~ifp->if_hwassist;
955 if (sw_csum & CSUM_DELAY_DATA) {
957 sw_csum &= ~CSUM_DELAY_DATA;
959 m->m_pkthdr.csum_flags &= ifp->if_hwassist;
962 * If small enough for interface, or the interface will take
963 * care of the fragmentation for us, can just send directly.
965 if (ip->ip_len <= ifp->if_mtu || ((ifp->if_hwassist & CSUM_FRAGMENT) &&
966 !(ip->ip_off & IP_DF))) {
967 ip->ip_len = htons(ip->ip_len);
968 ip->ip_off = htons(ip->ip_off);
970 if (sw_csum & CSUM_DELAY_IP) {
971 if (ip->ip_vhl == IP_VHL_BORING) {
972 ip->ip_sum = in_cksum_hdr(ip);
974 ip->ip_sum = in_cksum(m, hlen);
978 /* Record statistics for this interface address. */
979 if (!(flags & IP_FORWARDING) && ia) {
980 ia->ia_ifa.if_opackets++;
981 ia->ia_ifa.if_obytes += m->m_pkthdr.len;
985 /* clean ipsec history once it goes out of the node */
989 #ifdef MBUF_STRESS_TEST
990 if (mbuf_frag_size && m->m_pkthdr.len > mbuf_frag_size) {
991 struct mbuf *m1, *m2;
994 tmp = length = m->m_pkthdr.len;
996 while ((length -= mbuf_frag_size) >= 1) {
997 m1 = m_split(m, length, MB_DONTWAIT);
1001 while (m2->m_next != NULL)
1005 m->m_pkthdr.len = tmp;
1010 if (!mpls_output_process(m, ro->ro_rt))
1013 error = ifp->if_output(ifp, m, (struct sockaddr *)dst,
1018 if (ip->ip_off & IP_DF) {
1021 * This case can happen if the user changed the MTU
1022 * of an interface after enabling IP on it. Because
1023 * most netifs don't keep track of routes pointing to
1024 * them, there is no way for one to update all its
1025 * routes when the MTU is changed.
1027 if ((ro->ro_rt->rt_flags & (RTF_UP | RTF_HOST)) &&
1028 !(ro->ro_rt->rt_rmx.rmx_locks & RTV_MTU) &&
1029 (ro->ro_rt->rt_rmx.rmx_mtu > ifp->if_mtu)) {
1030 ro->ro_rt->rt_rmx.rmx_mtu = ifp->if_mtu;
1032 ipstat.ips_cantfrag++;
1037 * Too large for interface; fragment if possible. If successful,
1038 * on return, m will point to a list of packets to be sent.
1040 error = ip_fragment(ip, &m, ifp->if_mtu, ifp->if_hwassist, sw_csum);
1045 m->m_nextpkt = NULL;
1047 /* clean ipsec history once it goes out of the node */
1051 /* Record statistics for this interface address. */
1053 ia->ia_ifa.if_opackets++;
1054 ia->ia_ifa.if_obytes += m->m_pkthdr.len;
1057 if (!mpls_output_process(m, ro->ro_rt))
1060 error = ifp->if_output(ifp, m, (struct sockaddr *)dst,
1068 ipstat.ips_fragmented++;
1071 if (ro == &iproute && ro->ro_rt != NULL) {
1077 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1078 kprintf("DP ip_output call free SP:%p\n", sp));
1093 * Create a chain of fragments which fit the given mtu. m_frag points to the
1094 * mbuf to be fragmented; on return it points to the chain with the fragments.
1095 * Return 0 if no error. If error, m_frag may contain a partially built
1096 * chain of fragments that should be freed by the caller.
1098 * if_hwassist_flags is the hw offload capabilities (see if_data.ifi_hwassist)
1099 * sw_csum contains the delayed checksums flags (e.g., CSUM_DELAY_IP).
1102 ip_fragment(struct ip *ip, struct mbuf **m_frag, int mtu,
1103 u_long if_hwassist_flags, int sw_csum)
1106 int hlen = IP_VHL_HL(ip->ip_vhl) << 2;
1107 int len = (mtu - hlen) & ~7; /* size of payload in each fragment */
1109 struct mbuf *m0 = *m_frag; /* the original packet */
1111 struct mbuf **mnext;
1114 if (ip->ip_off & IP_DF) { /* Fragmentation not allowed */
1115 ipstat.ips_cantfrag++;
1120 * Must be able to put at least 8 bytes per fragment.
1126 * If the interface will not calculate checksums on
1127 * fragmented packets, then do it here.
1129 if ((m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA) &&
1130 !(if_hwassist_flags & CSUM_IP_FRAGS)) {
1131 in_delayed_cksum(m0);
1132 m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
1135 if (len > PAGE_SIZE) {
1137 * Fragment large datagrams such that each segment
1138 * contains a multiple of PAGE_SIZE amount of data,
1139 * plus headers. This enables a receiver to perform
1140 * page-flipping zero-copy optimizations.
1142 * XXX When does this help given that sender and receiver
1143 * could have different page sizes, and also mtu could
1144 * be less than the receiver's page size ?
1149 for (m = m0, off = 0; m && (off+m->m_len) <= mtu; m = m->m_next)
1153 * firstlen (off - hlen) must be aligned on an
1157 goto smart_frag_failure;
1158 off = ((off - hlen) & ~7) + hlen;
1159 newlen = (~PAGE_MASK) & mtu;
1160 if ((newlen + sizeof(struct ip)) > mtu) {
1161 /* we failed, go back the default */
1172 firstlen = off - hlen;
1173 mnext = &m0->m_nextpkt; /* pointer to next packet */
1176 * Loop through length of segment after first fragment,
1177 * make new header and copy data of each part and link onto chain.
1178 * Here, m0 is the original packet, m is the fragment being created.
1179 * The fragments are linked off the m_nextpkt of the original
1180 * packet, which after processing serves as the first fragment.
1182 for (nfrags = 1; off < ip->ip_len; off += len, nfrags++) {
1183 struct ip *mhip; /* ip header on the fragment */
1185 int mhlen = sizeof(struct ip);
1187 MGETHDR(m, MB_DONTWAIT, MT_HEADER);
1190 ipstat.ips_odropped++;
1193 m->m_flags |= (m0->m_flags & M_MCAST) | M_FRAG;
1195 * In the first mbuf, leave room for the link header, then
1196 * copy the original IP header including options. The payload
1197 * goes into an additional mbuf chain returned by m_copy().
1199 m->m_data += max_linkhdr;
1200 mhip = mtod(m, struct ip *);
1202 if (hlen > sizeof(struct ip)) {
1203 mhlen = ip_optcopy(ip, mhip) + sizeof(struct ip);
1204 mhip->ip_vhl = IP_MAKE_VHL(IPVERSION, mhlen >> 2);
1207 /* XXX do we need to add ip->ip_off below ? */
1208 mhip->ip_off = ((off - hlen) >> 3) + ip->ip_off;
1209 if (off + len >= ip->ip_len) { /* last fragment */
1210 len = ip->ip_len - off;
1211 m->m_flags |= M_LASTFRAG;
1213 mhip->ip_off |= IP_MF;
1214 mhip->ip_len = htons((u_short)(len + mhlen));
1215 m->m_next = m_copy(m0, off, len);
1216 if (m->m_next == NULL) { /* copy failed */
1218 error = ENOBUFS; /* ??? */
1219 ipstat.ips_odropped++;
1222 m->m_pkthdr.len = mhlen + len;
1223 m->m_pkthdr.rcvif = (struct ifnet *)NULL;
1224 m->m_pkthdr.csum_flags = m0->m_pkthdr.csum_flags;
1225 mhip->ip_off = htons(mhip->ip_off);
1227 if (sw_csum & CSUM_DELAY_IP)
1228 mhip->ip_sum = in_cksum(m, mhlen);
1230 mnext = &m->m_nextpkt;
1232 ipstat.ips_ofragments += nfrags;
1234 /* set first marker for fragment chain */
1235 m0->m_flags |= M_FIRSTFRAG | M_FRAG;
1236 m0->m_pkthdr.csum_data = nfrags;
1239 * Update first fragment by trimming what's been copied out
1240 * and updating header.
1242 m_adj(m0, hlen + firstlen - ip->ip_len);
1243 m0->m_pkthdr.len = hlen + firstlen;
1244 ip->ip_len = htons((u_short)m0->m_pkthdr.len);
1245 ip->ip_off |= IP_MF;
1246 ip->ip_off = htons(ip->ip_off);
1248 if (sw_csum & CSUM_DELAY_IP)
1249 ip->ip_sum = in_cksum(m0, hlen);
1257 in_delayed_cksum(struct mbuf *m)
1260 u_short csum, offset;
1262 ip = mtod(m, struct ip *);
1263 offset = IP_VHL_HL(ip->ip_vhl) << 2 ;
1264 csum = in_cksum_skip(m, ip->ip_len, offset);
1265 if (m->m_pkthdr.csum_flags & CSUM_UDP && csum == 0)
1267 offset += m->m_pkthdr.csum_data; /* checksum offset */
1269 if (offset + sizeof(u_short) > m->m_len) {
1270 kprintf("delayed m_pullup, m->len: %d off: %d p: %d\n",
1271 m->m_len, offset, ip->ip_p);
1274 * this shouldn't happen, but if it does, the
1275 * correct behavior may be to insert the checksum
1276 * in the existing chain instead of rearranging it.
1278 m = m_pullup(m, offset + sizeof(u_short));
1280 *(u_short *)(m->m_data + offset) = csum;
1284 * Insert IP options into preformed packet.
1285 * Adjust IP destination as required for IP source routing,
1286 * as indicated by a non-zero in_addr at the start of the options.
1288 * XXX This routine assumes that the packet has no options in place.
1290 static struct mbuf *
1291 ip_insertoptions(struct mbuf *m, struct mbuf *opt, int *phlen)
1293 struct ipoption *p = mtod(opt, struct ipoption *);
1295 struct ip *ip = mtod(m, struct ip *);
1298 optlen = opt->m_len - sizeof p->ipopt_dst;
1299 if (optlen + (u_short)ip->ip_len > IP_MAXPACKET) {
1301 return (m); /* XXX should fail */
1303 if (p->ipopt_dst.s_addr)
1304 ip->ip_dst = p->ipopt_dst;
1305 if (m->m_flags & M_EXT || m->m_data - optlen < m->m_pktdat) {
1306 MGETHDR(n, MB_DONTWAIT, MT_HEADER);
1311 n->m_pkthdr.rcvif = (struct ifnet *)NULL;
1312 n->m_pkthdr.len = m->m_pkthdr.len + optlen;
1313 m->m_len -= sizeof(struct ip);
1314 m->m_data += sizeof(struct ip);
1317 m->m_len = optlen + sizeof(struct ip);
1318 m->m_data += max_linkhdr;
1319 memcpy(mtod(m, void *), ip, sizeof(struct ip));
1321 m->m_data -= optlen;
1323 m->m_pkthdr.len += optlen;
1324 ovbcopy(ip, mtod(m, caddr_t), sizeof(struct ip));
1326 ip = mtod(m, struct ip *);
1327 bcopy(p->ipopt_list, ip + 1, optlen);
1328 *phlen = sizeof(struct ip) + optlen;
1329 ip->ip_vhl = IP_MAKE_VHL(IPVERSION, *phlen >> 2);
1330 ip->ip_len += optlen;
1335 * Copy options from ip to jp,
1336 * omitting those not copied during fragmentation.
1339 ip_optcopy(struct ip *ip, struct ip *jp)
1342 int opt, optlen, cnt;
1344 cp = (u_char *)(ip + 1);
1345 dp = (u_char *)(jp + 1);
1346 cnt = (IP_VHL_HL(ip->ip_vhl) << 2) - sizeof(struct ip);
1347 for (; cnt > 0; cnt -= optlen, cp += optlen) {
1349 if (opt == IPOPT_EOL)
1351 if (opt == IPOPT_NOP) {
1352 /* Preserve for IP mcast tunnel's LSRR alignment. */
1358 KASSERT(cnt >= IPOPT_OLEN + sizeof *cp,
1359 ("ip_optcopy: malformed ipv4 option"));
1360 optlen = cp[IPOPT_OLEN];
1361 KASSERT(optlen >= IPOPT_OLEN + sizeof *cp && optlen <= cnt,
1362 ("ip_optcopy: malformed ipv4 option"));
1364 /* bogus lengths should have been caught by ip_dooptions */
1367 if (IPOPT_COPIED(opt)) {
1368 bcopy(cp, dp, optlen);
1372 for (optlen = dp - (u_char *)(jp+1); optlen & 0x3; optlen++)
1378 * IP socket option processing.
1381 ip_ctloutput(struct socket *so, struct sockopt *sopt)
1383 struct inpcb *inp = so->so_pcb;
1387 if (sopt->sopt_level != IPPROTO_IP) {
1391 switch (sopt->sopt_dir) {
1393 switch (sopt->sopt_name) {
1400 if (sopt->sopt_valsize > MLEN) {
1404 MGET(m, sopt->sopt_td ? MB_WAIT : MB_DONTWAIT, MT_HEADER);
1409 m->m_len = sopt->sopt_valsize;
1410 error = soopt_to_kbuf(sopt, mtod(m, void *), m->m_len,
1412 return (ip_pcbopts(sopt->sopt_name, &inp->inp_options,
1420 case IP_RECVRETOPTS:
1421 case IP_RECVDSTADDR:
1425 error = soopt_to_kbuf(sopt, &optval, sizeof optval,
1429 switch (sopt->sopt_name) {
1431 inp->inp_ip_tos = optval;
1435 inp->inp_ip_ttl = optval;
1438 if (optval > 0 && optval <= MAXTTL)
1439 inp->inp_ip_minttl = optval;
1443 #define OPTSET(bit) \
1445 inp->inp_flags |= bit; \
1447 inp->inp_flags &= ~bit;
1450 OPTSET(INP_RECVOPTS);
1453 case IP_RECVRETOPTS:
1454 OPTSET(INP_RECVRETOPTS);
1457 case IP_RECVDSTADDR:
1458 OPTSET(INP_RECVDSTADDR);
1466 OPTSET(INP_RECVTTL);
1476 case IP_MULTICAST_IF:
1477 case IP_MULTICAST_VIF:
1478 case IP_MULTICAST_TTL:
1479 case IP_MULTICAST_LOOP:
1480 case IP_ADD_MEMBERSHIP:
1481 case IP_DROP_MEMBERSHIP:
1482 error = ip_setmoptions(sopt, &inp->inp_moptions);
1486 error = soopt_to_kbuf(sopt, &optval, sizeof optval,
1492 case IP_PORTRANGE_DEFAULT:
1493 inp->inp_flags &= ~(INP_LOWPORT);
1494 inp->inp_flags &= ~(INP_HIGHPORT);
1497 case IP_PORTRANGE_HIGH:
1498 inp->inp_flags &= ~(INP_LOWPORT);
1499 inp->inp_flags |= INP_HIGHPORT;
1502 case IP_PORTRANGE_LOW:
1503 inp->inp_flags &= ~(INP_HIGHPORT);
1504 inp->inp_flags |= INP_LOWPORT;
1513 #if defined(IPSEC) || defined(FAST_IPSEC)
1514 case IP_IPSEC_POLICY:
1522 if ((error = soopt_getm(sopt, &m)) != 0) /* XXX */
1524 soopt_to_mbuf(sopt, m);
1525 priv = (sopt->sopt_td != NULL &&
1526 suser(sopt->sopt_td) != 0) ? 0 : 1;
1527 req = mtod(m, caddr_t);
1529 optname = sopt->sopt_name;
1530 error = ipsec4_set_policy(inp, optname, req, len, priv);
1537 error = ENOPROTOOPT;
1543 switch (sopt->sopt_name) {
1546 if (inp->inp_options)
1547 soopt_from_kbuf(sopt, mtod(inp->inp_options,
1549 inp->inp_options->m_len);
1551 sopt->sopt_valsize = 0;
1558 case IP_RECVRETOPTS:
1559 case IP_RECVDSTADDR:
1564 switch (sopt->sopt_name) {
1567 optval = inp->inp_ip_tos;
1571 optval = inp->inp_ip_ttl;
1574 optval = inp->inp_ip_minttl;
1577 #define OPTBIT(bit) (inp->inp_flags & bit ? 1 : 0)
1580 optval = OPTBIT(INP_RECVOPTS);
1583 case IP_RECVRETOPTS:
1584 optval = OPTBIT(INP_RECVRETOPTS);
1587 case IP_RECVDSTADDR:
1588 optval = OPTBIT(INP_RECVDSTADDR);
1592 optval = OPTBIT(INP_RECVTTL);
1596 optval = OPTBIT(INP_RECVIF);
1600 if (inp->inp_flags & INP_HIGHPORT)
1601 optval = IP_PORTRANGE_HIGH;
1602 else if (inp->inp_flags & INP_LOWPORT)
1603 optval = IP_PORTRANGE_LOW;
1609 optval = OPTBIT(INP_FAITH);
1612 soopt_from_kbuf(sopt, &optval, sizeof optval);
1615 case IP_MULTICAST_IF:
1616 case IP_MULTICAST_VIF:
1617 case IP_MULTICAST_TTL:
1618 case IP_MULTICAST_LOOP:
1619 case IP_ADD_MEMBERSHIP:
1620 case IP_DROP_MEMBERSHIP:
1621 error = ip_getmoptions(sopt, inp->inp_moptions);
1624 #if defined(IPSEC) || defined(FAST_IPSEC)
1625 case IP_IPSEC_POLICY:
1627 struct mbuf *m = NULL;
1632 req = mtod(m, caddr_t);
1635 error = ipsec4_get_policy(so->so_pcb, req, len, &m);
1637 error = soopt_from_mbuf(sopt, m); /* XXX */
1645 error = ENOPROTOOPT;
1654 * Set up IP options in pcb for insertion in output packets.
1655 * Store in mbuf with pointer in pcbopt, adding pseudo-option
1656 * with destination address if source routed.
1659 ip_pcbopts(int optname, struct mbuf **pcbopt, struct mbuf *m)
1665 /* turn off any old options */
1669 if (m == NULL || m->m_len == 0) {
1671 * Only turning off any previous options.
1678 if (m->m_len % sizeof(int32_t))
1681 * IP first-hop destination address will be stored before
1682 * actual options; move other options back
1683 * and clear it when none present.
1685 if (m->m_data + m->m_len + sizeof(struct in_addr) >= &m->m_dat[MLEN])
1688 m->m_len += sizeof(struct in_addr);
1689 cp = mtod(m, u_char *) + sizeof(struct in_addr);
1690 ovbcopy(mtod(m, caddr_t), cp, cnt);
1691 bzero(mtod(m, caddr_t), sizeof(struct in_addr));
1693 for (; cnt > 0; cnt -= optlen, cp += optlen) {
1694 opt = cp[IPOPT_OPTVAL];
1695 if (opt == IPOPT_EOL)
1697 if (opt == IPOPT_NOP)
1700 if (cnt < IPOPT_OLEN + sizeof *cp)
1702 optlen = cp[IPOPT_OLEN];
1703 if (optlen < IPOPT_OLEN + sizeof *cp || optlen > cnt)
1714 * user process specifies route as:
1716 * D must be our final destination (but we can't
1717 * check that since we may not have connected yet).
1718 * A is first hop destination, which doesn't appear in
1719 * actual IP option, but is stored before the options.
1721 if (optlen < IPOPT_MINOFF - 1 + sizeof(struct in_addr))
1723 m->m_len -= sizeof(struct in_addr);
1724 cnt -= sizeof(struct in_addr);
1725 optlen -= sizeof(struct in_addr);
1726 cp[IPOPT_OLEN] = optlen;
1728 * Move first hop before start of options.
1730 bcopy(&cp[IPOPT_OFFSET+1], mtod(m, caddr_t),
1731 sizeof(struct in_addr));
1733 * Then copy rest of options back
1734 * to close up the deleted entry.
1736 ovbcopy(&cp[IPOPT_OFFSET+1] + sizeof(struct in_addr),
1737 &cp[IPOPT_OFFSET+1],
1738 cnt - (IPOPT_MINOFF - 1));
1742 if (m->m_len > MAX_IPOPTLEN + sizeof(struct in_addr))
1754 * The whole multicast option thing needs to be re-thought.
1755 * Several of these options are equally applicable to non-multicast
1756 * transmission, and one (IP_MULTICAST_TTL) totally duplicates a
1757 * standard option (IP_TTL).
1761 * following RFC1724 section 3.3, 0.0.0.0/8 is interpreted as interface index.
1763 static struct ifnet *
1764 ip_multicast_if(struct in_addr *a, int *ifindexp)
1771 if (ntohl(a->s_addr) >> 24 == 0) {
1772 ifindex = ntohl(a->s_addr) & 0xffffff;
1773 if (ifindex < 0 || if_index < ifindex)
1775 ifp = ifindex2ifnet[ifindex];
1777 *ifindexp = ifindex;
1779 ifp = INADDR_TO_IFP(a);
1785 * Set the IP multicast options in response to user setsockopt().
1788 ip_setmoptions(struct sockopt *sopt, struct ip_moptions **imop)
1792 struct in_addr addr;
1793 struct ip_mreq mreq;
1795 struct ip_moptions *imo = *imop;
1800 * No multicast option buffer attached to the pcb;
1801 * allocate one and initialize to default values.
1803 imo = kmalloc(sizeof *imo, M_IPMOPTS, M_WAITOK);
1806 imo->imo_multicast_ifp = NULL;
1807 imo->imo_multicast_addr.s_addr = INADDR_ANY;
1808 imo->imo_multicast_vif = -1;
1809 imo->imo_multicast_ttl = IP_DEFAULT_MULTICAST_TTL;
1810 imo->imo_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
1811 imo->imo_num_memberships = 0;
1813 switch (sopt->sopt_name) {
1814 /* store an index number for the vif you wanna use in the send */
1815 case IP_MULTICAST_VIF:
1816 if (legal_vif_num == 0) {
1820 error = soopt_to_kbuf(sopt, &i, sizeof i, sizeof i);
1823 if (!legal_vif_num(i) && (i != -1)) {
1827 imo->imo_multicast_vif = i;
1830 case IP_MULTICAST_IF:
1832 * Select the interface for outgoing multicast packets.
1834 error = soopt_to_kbuf(sopt, &addr, sizeof addr, sizeof addr);
1839 * INADDR_ANY is used to remove a previous selection.
1840 * When no interface is selected, a default one is
1841 * chosen every time a multicast packet is sent.
1843 if (addr.s_addr == INADDR_ANY) {
1844 imo->imo_multicast_ifp = NULL;
1848 * The selected interface is identified by its local
1849 * IP address. Find the interface and confirm that
1850 * it supports multicasting.
1853 ifp = ip_multicast_if(&addr, &ifindex);
1854 if (ifp == NULL || !(ifp->if_flags & IFF_MULTICAST)) {
1856 error = EADDRNOTAVAIL;
1859 imo->imo_multicast_ifp = ifp;
1861 imo->imo_multicast_addr = addr;
1863 imo->imo_multicast_addr.s_addr = INADDR_ANY;
1867 case IP_MULTICAST_TTL:
1869 * Set the IP time-to-live for outgoing multicast packets.
1870 * The original multicast API required a char argument,
1871 * which is inconsistent with the rest of the socket API.
1872 * We allow either a char or an int.
1874 if (sopt->sopt_valsize == 1) {
1876 error = soopt_to_kbuf(sopt, &ttl, 1, 1);
1879 imo->imo_multicast_ttl = ttl;
1882 error = soopt_to_kbuf(sopt, &ttl, sizeof ttl, sizeof ttl);
1888 imo->imo_multicast_ttl = ttl;
1892 case IP_MULTICAST_LOOP:
1894 * Set the loopback flag for outgoing multicast packets.
1895 * Must be zero or one. The original multicast API required a
1896 * char argument, which is inconsistent with the rest
1897 * of the socket API. We allow either a char or an int.
1899 if (sopt->sopt_valsize == 1) {
1902 error = soopt_to_kbuf(sopt, &loop, 1, 1);
1905 imo->imo_multicast_loop = !!loop;
1909 error = soopt_to_kbuf(sopt, &loop, sizeof loop,
1913 imo->imo_multicast_loop = !!loop;
1917 case IP_ADD_MEMBERSHIP:
1919 * Add a multicast group membership.
1920 * Group must be a valid IP multicast address.
1922 error = soopt_to_kbuf(sopt, &mreq, sizeof mreq, sizeof mreq);
1926 if (!IN_MULTICAST(ntohl(mreq.imr_multiaddr.s_addr))) {
1932 * If no interface address was provided, use the interface of
1933 * the route to the given multicast address.
1935 if (mreq.imr_interface.s_addr == INADDR_ANY) {
1936 struct sockaddr_in dst;
1939 bzero(&dst, sizeof(struct sockaddr_in));
1940 dst.sin_len = sizeof(struct sockaddr_in);
1941 dst.sin_family = AF_INET;
1942 dst.sin_addr = mreq.imr_multiaddr;
1943 rt = rtlookup((struct sockaddr *)&dst);
1945 error = EADDRNOTAVAIL;
1952 ifp = ip_multicast_if(&mreq.imr_interface, NULL);
1956 * See if we found an interface, and confirm that it
1957 * supports multicast.
1959 if (ifp == NULL || !(ifp->if_flags & IFF_MULTICAST)) {
1960 error = EADDRNOTAVAIL;
1965 * See if the membership already exists or if all the
1966 * membership slots are full.
1968 for (i = 0; i < imo->imo_num_memberships; ++i) {
1969 if (imo->imo_membership[i]->inm_ifp == ifp &&
1970 imo->imo_membership[i]->inm_addr.s_addr
1971 == mreq.imr_multiaddr.s_addr)
1974 if (i < imo->imo_num_memberships) {
1979 if (i == IP_MAX_MEMBERSHIPS) {
1980 error = ETOOMANYREFS;
1985 * Everything looks good; add a new record to the multicast
1986 * address list for the given interface.
1988 if ((imo->imo_membership[i] =
1989 in_addmulti(&mreq.imr_multiaddr, ifp)) == NULL) {
1994 ++imo->imo_num_memberships;
1998 case IP_DROP_MEMBERSHIP:
2000 * Drop a multicast group membership.
2001 * Group must be a valid IP multicast address.
2003 error = soopt_to_kbuf(sopt, &mreq, sizeof mreq, sizeof mreq);
2007 if (!IN_MULTICAST(ntohl(mreq.imr_multiaddr.s_addr))) {
2014 * If an interface address was specified, get a pointer
2015 * to its ifnet structure.
2017 if (mreq.imr_interface.s_addr == INADDR_ANY)
2020 ifp = ip_multicast_if(&mreq.imr_interface, NULL);
2022 error = EADDRNOTAVAIL;
2028 * Find the membership in the membership array.
2030 for (i = 0; i < imo->imo_num_memberships; ++i) {
2032 imo->imo_membership[i]->inm_ifp == ifp) &&
2033 imo->imo_membership[i]->inm_addr.s_addr ==
2034 mreq.imr_multiaddr.s_addr)
2037 if (i == imo->imo_num_memberships) {
2038 error = EADDRNOTAVAIL;
2043 * Give up the multicast address record to which the
2044 * membership points.
2046 in_delmulti(imo->imo_membership[i]);
2048 * Remove the gap in the membership array.
2050 for (++i; i < imo->imo_num_memberships; ++i)
2051 imo->imo_membership[i-1] = imo->imo_membership[i];
2052 --imo->imo_num_memberships;
2062 * If all options have default values, no need to keep the mbuf.
2064 if (imo->imo_multicast_ifp == NULL &&
2065 imo->imo_multicast_vif == -1 &&
2066 imo->imo_multicast_ttl == IP_DEFAULT_MULTICAST_TTL &&
2067 imo->imo_multicast_loop == IP_DEFAULT_MULTICAST_LOOP &&
2068 imo->imo_num_memberships == 0) {
2069 kfree(*imop, M_IPMOPTS);
2077 * Return the IP multicast options in response to user getsockopt().
2080 ip_getmoptions(struct sockopt *sopt, struct ip_moptions *imo)
2082 struct in_addr addr;
2083 struct in_ifaddr *ia;
2088 switch (sopt->sopt_name) {
2089 case IP_MULTICAST_VIF:
2091 optval = imo->imo_multicast_vif;
2094 soopt_from_kbuf(sopt, &optval, sizeof optval);
2097 case IP_MULTICAST_IF:
2098 if (imo == NULL || imo->imo_multicast_ifp == NULL)
2099 addr.s_addr = INADDR_ANY;
2100 else if (imo->imo_multicast_addr.s_addr) {
2101 /* return the value user has set */
2102 addr = imo->imo_multicast_addr;
2104 ia = IFP_TO_IA(imo->imo_multicast_ifp);
2105 addr.s_addr = (ia == NULL) ? INADDR_ANY
2106 : IA_SIN(ia)->sin_addr.s_addr;
2108 soopt_from_kbuf(sopt, &addr, sizeof addr);
2111 case IP_MULTICAST_TTL:
2113 optval = coptval = IP_DEFAULT_MULTICAST_TTL;
2115 optval = coptval = imo->imo_multicast_ttl;
2116 if (sopt->sopt_valsize == 1)
2117 soopt_from_kbuf(sopt, &coptval, 1);
2119 soopt_from_kbuf(sopt, &optval, sizeof optval);
2122 case IP_MULTICAST_LOOP:
2124 optval = coptval = IP_DEFAULT_MULTICAST_LOOP;
2126 optval = coptval = imo->imo_multicast_loop;
2127 if (sopt->sopt_valsize == 1)
2128 soopt_from_kbuf(sopt, &coptval, 1);
2130 soopt_from_kbuf(sopt, &optval, sizeof optval);
2134 error = ENOPROTOOPT;
2141 * Discard the IP multicast options.
2144 ip_freemoptions(struct ip_moptions *imo)
2149 for (i = 0; i < imo->imo_num_memberships; ++i)
2150 in_delmulti(imo->imo_membership[i]);
2151 kfree(imo, M_IPMOPTS);
2156 * Routine called from ip_output() to loop back a copy of an IP multicast
2157 * packet to the input queue of a specified interface. Note that this
2158 * calls the output routine of the loopback "driver", but with an interface
2159 * pointer that might NOT be a loopback interface -- evil, but easier than
2160 * replicating that code here.
2163 ip_mloopback(struct ifnet *ifp, struct mbuf *m, struct sockaddr_in *dst,
2169 copym = m_copypacket(m, MB_DONTWAIT);
2170 if (copym != NULL && (copym->m_flags & M_EXT || copym->m_len < hlen))
2171 copym = m_pullup(copym, hlen);
2172 if (copym != NULL) {
2174 * if the checksum hasn't been computed, mark it as valid
2176 if (copym->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
2177 in_delayed_cksum(copym);
2178 copym->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
2179 copym->m_pkthdr.csum_flags |=
2180 CSUM_DATA_VALID | CSUM_PSEUDO_HDR;
2181 copym->m_pkthdr.csum_data = 0xffff;
2184 * We don't bother to fragment if the IP length is greater
2185 * than the interface's MTU. Can this possibly matter?
2187 ip = mtod(copym, struct ip *);
2188 ip->ip_len = htons(ip->ip_len);
2189 ip->ip_off = htons(ip->ip_off);
2191 if (ip->ip_vhl == IP_VHL_BORING) {
2192 ip->ip_sum = in_cksum_hdr(ip);
2194 ip->ip_sum = in_cksum(copym, hlen);
2198 * It's not clear whether there are any lingering
2199 * reentrancy problems in other areas which might
2200 * be exposed by using ip_input directly (in
2201 * particular, everything which modifies the packet
2202 * in-place). Yet another option is using the
2203 * protosw directly to deliver the looped back
2204 * packet. For the moment, we'll err on the side
2205 * of safety by using if_simloop().
2208 if (dst->sin_family != AF_INET) {
2209 kprintf("ip_mloopback: bad address family %d\n",
2211 dst->sin_family = AF_INET;
2216 copym->m_pkthdr.rcvif = ifp;
2219 if_simloop(ifp, copym, dst->sin_family, 0);