Merge branch 'master' of git://crater.dragonflybsd.org/dragonfly
[dragonfly.git] / sys / netinet / ip_output.c
1 /*
2  * Copyright (c) 1982, 1986, 1988, 1990, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. 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.
16  *
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
27  * SUCH DAMAGE.
28  *
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.67 2008/10/28 03:07:28 sephe Exp $
32  */
33
34 #define _IP_VHL
35
36 #include "opt_ipfw.h"
37 #include "opt_ipdn.h"
38 #include "opt_ipdivert.h"
39 #include "opt_ipfilter.h"
40 #include "opt_ipsec.h"
41 #include "opt_mbuf_stress_test.h"
42 #include "opt_mpls.h"
43
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/kernel.h>
47 #include <sys/malloc.h>
48 #include <sys/mbuf.h>
49 #include <sys/protosw.h>
50 #include <sys/socket.h>
51 #include <sys/socketvar.h>
52 #include <sys/proc.h>
53 #include <sys/priv.h>
54 #include <sys/sysctl.h>
55 #include <sys/in_cksum.h>
56 #include <sys/lock.h>
57
58 #include <sys/thread2.h>
59 #include <sys/mplock2.h>
60 #include <sys/msgport2.h>
61
62 #include <net/if.h>
63 #include <net/netisr.h>
64 #include <net/pfil.h>
65 #include <net/route.h>
66
67 #include <netinet/in.h>
68 #include <netinet/in_systm.h>
69 #include <netinet/ip.h>
70 #include <netinet/in_pcb.h>
71 #include <netinet/in_var.h>
72 #include <netinet/ip_var.h>
73
74 #include <netproto/mpls/mpls_var.h>
75
76 static MALLOC_DEFINE(M_IPMOPTS, "ip_moptions", "internet multicast options");
77
78 #ifdef IPSEC
79 #include <netinet6/ipsec.h>
80 #include <netproto/key/key.h>
81 #ifdef IPSEC_DEBUG
82 #include <netproto/key/key_debug.h>
83 #else
84 #define KEYDEBUG(lev,arg)
85 #endif
86 #endif /*IPSEC*/
87
88 #ifdef FAST_IPSEC
89 #include <netproto/ipsec/ipsec.h>
90 #include <netproto/ipsec/xform.h>
91 #include <netproto/ipsec/key.h>
92 #endif /*FAST_IPSEC*/
93
94 #include <net/ipfw/ip_fw.h>
95 #include <net/dummynet/ip_dummynet.h>
96
97 #define print_ip(x, a, y)        kprintf("%s %d.%d.%d.%d%s",\
98                                 x, (ntohl(a.s_addr)>>24)&0xFF,\
99                                   (ntohl(a.s_addr)>>16)&0xFF,\
100                                   (ntohl(a.s_addr)>>8)&0xFF,\
101                                   (ntohl(a.s_addr))&0xFF, y);
102
103 u_short ip_id;
104
105 #ifdef MBUF_STRESS_TEST
106 int mbuf_frag_size = 0;
107 SYSCTL_INT(_net_inet_ip, OID_AUTO, mbuf_frag_size, CTLFLAG_RW,
108         &mbuf_frag_size, 0, "Fragment outgoing mbufs to this size");
109 #endif
110
111 static struct mbuf *ip_insertoptions(struct mbuf *, struct mbuf *, int *);
112 static struct ifnet *ip_multicast_if(struct in_addr *, int *);
113 static void     ip_mloopback
114         (struct ifnet *, struct mbuf *, struct sockaddr_in *, int);
115 static int      ip_getmoptions
116         (struct sockopt *, struct ip_moptions *);
117 static int      ip_pcbopts(int, struct mbuf **, struct mbuf *);
118 static int      ip_setmoptions
119         (struct sockopt *, struct ip_moptions **);
120
121 int     ip_optcopy(struct ip *, struct ip *);
122
123 extern  int route_assert_owner_access;
124
125 extern  struct protosw inetsw[];
126
127 static int
128 ip_localforward(struct mbuf *m, const struct sockaddr_in *dst, int hlen)
129 {
130         struct in_ifaddr_container *iac;
131
132         /*
133          * We need to figure out if we have been forwarded to a local
134          * socket.  If so, then we should somehow "loop back" to
135          * ip_input(), and get directed to the PCB as if we had received
136          * this packet.  This is because it may be difficult to identify
137          * the packets you want to forward until they are being output
138          * and have selected an interface (e.g. locally initiated
139          * packets).  If we used the loopback inteface, we would not be
140          * able to control what happens as the packet runs through
141          * ip_input() as it is done through a ISR.
142          */
143         LIST_FOREACH(iac, INADDR_HASH(dst->sin_addr.s_addr), ia_hash) {
144                 /*
145                  * If the addr to forward to is one of ours, we pretend
146                  * to be the destination for this packet.
147                  */
148                 if (IA_SIN(iac->ia)->sin_addr.s_addr == dst->sin_addr.s_addr)
149                         break;
150         }
151         if (iac != NULL) {
152                 struct ip *ip;
153
154                 if (m->m_pkthdr.rcvif == NULL)
155                         m->m_pkthdr.rcvif = ifunit("lo0");
156                 if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
157                         m->m_pkthdr.csum_flags |= CSUM_DATA_VALID |
158                                                   CSUM_PSEUDO_HDR;
159                         m->m_pkthdr.csum_data = 0xffff;
160                 }
161                 m->m_pkthdr.csum_flags |= CSUM_IP_CHECKED | CSUM_IP_VALID;
162
163                 /*
164                  * Make sure that the IP header is in one mbuf,
165                  * required by ip_input
166                  */
167                 if (m->m_len < hlen) {
168                         m = m_pullup(m, hlen);
169                         if (m == NULL) {
170                                 /* The packet was freed; we are done */
171                                 return 1;
172                         }
173                 }
174                 ip = mtod(m, struct ip *);
175
176                 ip->ip_len = htons(ip->ip_len);
177                 ip->ip_off = htons(ip->ip_off);
178                 ip_input(m);
179
180                 return 1; /* The packet gets forwarded locally */
181         }
182         return 0;
183 }
184
185 /*
186  * IP output.  The packet in mbuf chain m contains a skeletal IP
187  * header (with len, off, ttl, proto, tos, src, dst).
188  * The mbuf chain containing the packet will be freed.
189  * The mbuf opt, if present, will not be freed.
190  */
191 int
192 ip_output(struct mbuf *m0, struct mbuf *opt, struct route *ro,
193           int flags, struct ip_moptions *imo, struct inpcb *inp)
194 {
195         struct ip *ip;
196         struct ifnet *ifp = NULL;       /* keep compiler happy */
197         struct mbuf *m;
198         int hlen = sizeof(struct ip);
199         int len, error = 0;
200         struct sockaddr_in *dst = NULL; /* keep compiler happy */
201         struct in_ifaddr *ia = NULL;
202         int isbroadcast, sw_csum;
203         struct in_addr pkt_dst;
204         struct route iproute;
205         struct m_tag *mtag;
206 #ifdef IPSEC
207         struct secpolicy *sp = NULL;
208         struct socket *so = inp ? inp->inp_socket : NULL;
209 #endif
210 #ifdef FAST_IPSEC
211         struct secpolicy *sp = NULL;
212         struct tdb_ident *tdbi;
213 #endif /* FAST_IPSEC */
214         struct sockaddr_in *next_hop = NULL;
215         int src_was_INADDR_ANY = 0;     /* as the name says... */
216
217         m = m0;
218         M_ASSERTPKTHDR(m);
219
220         if (ro == NULL) {
221                 ro = &iproute;
222                 bzero(ro, sizeof *ro);
223         } else if (ro->ro_rt != NULL && ro->ro_rt->rt_cpuid != mycpuid) {
224                 if (flags & IP_DEBUGROUTE) {
225                         if (route_assert_owner_access) {
226                                 panic("ip_output: "
227                                       "rt rt_cpuid %d accessed on cpu %d\n",
228                                       ro->ro_rt->rt_cpuid, mycpuid);
229                         } else {
230                                 kprintf("ip_output: "
231                                         "rt rt_cpuid %d accessed on cpu %d\n",
232                                         ro->ro_rt->rt_cpuid, mycpuid);
233                                 print_backtrace(-1);
234                         }
235                 }
236
237                 /*
238                  * XXX
239                  * If the cached rtentry's owner CPU is not the current CPU,
240                  * then don't touch the cached rtentry (remote free is too
241                  * expensive in this context); just relocate the route.
242                  */
243                 ro = &iproute;
244                 bzero(ro, sizeof *ro);
245         }
246
247         if (m->m_pkthdr.fw_flags & IPFORWARD_MBUF_TAGGED) {
248                 /* Next hop */
249                 mtag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL);
250                 KKASSERT(mtag != NULL);
251                 next_hop = m_tag_data(mtag);
252         }
253
254         if (m->m_pkthdr.fw_flags & DUMMYNET_MBUF_TAGGED) {
255                 struct dn_pkt *dn_pkt;
256
257                 /* Extract info from dummynet tag */
258                 mtag = m_tag_find(m, PACKET_TAG_DUMMYNET, NULL);
259                 KKASSERT(mtag != NULL);
260                 dn_pkt = m_tag_data(mtag);
261
262                 /*
263                  * The packet was already tagged, so part of the
264                  * processing was already done, and we need to go down.
265                  * Get the calculated parameters from the tag.
266                  */
267                 ifp = dn_pkt->ifp;
268
269                 KKASSERT(ro == &iproute);
270                 *ro = dn_pkt->ro; /* structure copy */
271                 KKASSERT(ro->ro_rt == NULL || ro->ro_rt->rt_cpuid == mycpuid);
272
273                 dst = dn_pkt->dn_dst;
274                 if (dst == (struct sockaddr_in *)&(dn_pkt->ro.ro_dst)) {
275                         /* If 'dst' points into dummynet tag, adjust it */
276                         dst = (struct sockaddr_in *)&(ro->ro_dst);
277                 }
278
279                 ip = mtod(m, struct ip *);
280                 hlen = IP_VHL_HL(ip->ip_vhl) << 2 ;
281                 if (ro->ro_rt)
282                         ia = ifatoia(ro->ro_rt->rt_ifa);
283                 goto sendit;
284         }
285
286         if (opt) {
287                 len = 0;
288                 m = ip_insertoptions(m, opt, &len);
289                 if (len != 0)
290                         hlen = len;
291         }
292         ip = mtod(m, struct ip *);
293
294         /*
295          * Fill in IP header.
296          */
297         if (!(flags & (IP_FORWARDING|IP_RAWOUTPUT))) {
298                 ip->ip_vhl = IP_MAKE_VHL(IPVERSION, hlen >> 2);
299                 ip->ip_off &= IP_DF;
300                 ip->ip_id = ip_newid();
301                 ipstat.ips_localout++;
302         } else {
303                 hlen = IP_VHL_HL(ip->ip_vhl) << 2;
304         }
305
306 reroute:
307         pkt_dst = next_hop ? next_hop->sin_addr : ip->ip_dst;
308
309         dst = (struct sockaddr_in *)&ro->ro_dst;
310         /*
311          * If there is a cached route,
312          * check that it is to the same destination
313          * and is still up.  If not, free it and try again.
314          * The address family should also be checked in case of sharing the
315          * cache with IPv6.
316          */
317         if (ro->ro_rt &&
318             (!(ro->ro_rt->rt_flags & RTF_UP) ||
319              dst->sin_family != AF_INET ||
320              dst->sin_addr.s_addr != pkt_dst.s_addr)) {
321                 rtfree(ro->ro_rt);
322                 ro->ro_rt = NULL;
323         }
324         if (ro->ro_rt == NULL) {
325                 bzero(dst, sizeof *dst);
326                 dst->sin_family = AF_INET;
327                 dst->sin_len = sizeof *dst;
328                 dst->sin_addr = pkt_dst;
329         }
330         /*
331          * If routing to interface only,
332          * short circuit routing lookup.
333          */
334         if (flags & IP_ROUTETOIF) {
335                 if ((ia = ifatoia(ifa_ifwithdstaddr(sintosa(dst)))) == NULL &&
336                     (ia = ifatoia(ifa_ifwithnet(sintosa(dst)))) == NULL) {
337                         ipstat.ips_noroute++;
338                         error = ENETUNREACH;
339                         goto bad;
340                 }
341                 ifp = ia->ia_ifp;
342                 ip->ip_ttl = 1;
343                 isbroadcast = in_broadcast(dst->sin_addr, ifp);
344         } else if (IN_MULTICAST(ntohl(pkt_dst.s_addr)) &&
345                    imo != NULL && imo->imo_multicast_ifp != NULL) {
346                 /*
347                  * Bypass the normal routing lookup for multicast
348                  * packets if the interface is specified.
349                  */
350                 ifp = imo->imo_multicast_ifp;
351                 ia = IFP_TO_IA(ifp);
352                 isbroadcast = 0;        /* fool gcc */
353         } else {
354                 /*
355                  * If this is the case, we probably don't want to allocate
356                  * a protocol-cloned route since we didn't get one from the
357                  * ULP.  This lets TCP do its thing, while not burdening
358                  * forwarding or ICMP with the overhead of cloning a route.
359                  * Of course, we still want to do any cloning requested by
360                  * the link layer, as this is probably required in all cases
361                  * for correct operation (as it is for ARP).
362                  */
363                 if (ro->ro_rt == NULL)
364                         rtalloc_ign(ro, RTF_PRCLONING);
365                 if (ro->ro_rt == NULL) {
366                         ipstat.ips_noroute++;
367                         error = EHOSTUNREACH;
368                         goto bad;
369                 }
370                 ia = ifatoia(ro->ro_rt->rt_ifa);
371                 ifp = ro->ro_rt->rt_ifp;
372                 ro->ro_rt->rt_use++;
373                 if (ro->ro_rt->rt_flags & RTF_GATEWAY)
374                         dst = (struct sockaddr_in *)ro->ro_rt->rt_gateway;
375                 if (ro->ro_rt->rt_flags & RTF_HOST)
376                         isbroadcast = (ro->ro_rt->rt_flags & RTF_BROADCAST);
377                 else
378                         isbroadcast = in_broadcast(dst->sin_addr, ifp);
379         }
380         if (IN_MULTICAST(ntohl(pkt_dst.s_addr))) {
381                 struct in_multi *inm;
382
383                 m->m_flags |= M_MCAST;
384                 /*
385                  * IP destination address is multicast.  Make sure "dst"
386                  * still points to the address in "ro".  (It may have been
387                  * changed to point to a gateway address, above.)
388                  */
389                 dst = (struct sockaddr_in *)&ro->ro_dst;
390                 /*
391                  * See if the caller provided any multicast options
392                  */
393                 if (imo != NULL) {
394                         ip->ip_ttl = imo->imo_multicast_ttl;
395                         if (imo->imo_multicast_vif != -1) {
396                                 ip->ip_src.s_addr =
397                                     ip_mcast_src ?
398                                     ip_mcast_src(imo->imo_multicast_vif) :
399                                     INADDR_ANY;
400                         }
401                 } else {
402                         ip->ip_ttl = IP_DEFAULT_MULTICAST_TTL;
403                 }
404                 /*
405                  * Confirm that the outgoing interface supports multicast.
406                  */
407                 if ((imo == NULL) || (imo->imo_multicast_vif == -1)) {
408                         if (!(ifp->if_flags & IFF_MULTICAST)) {
409                                 ipstat.ips_noroute++;
410                                 error = ENETUNREACH;
411                                 goto bad;
412                         }
413                 }
414                 /*
415                  * If source address not specified yet, use address
416                  * of outgoing interface.
417                  */
418                 if (ip->ip_src.s_addr == INADDR_ANY) {
419                         /* Interface may have no addresses. */
420                         if (ia != NULL)
421                                 ip->ip_src = IA_SIN(ia)->sin_addr;
422                 }
423
424                 IN_LOOKUP_MULTI(pkt_dst, ifp, inm);
425                 if (inm != NULL &&
426                     (imo == NULL || imo->imo_multicast_loop)) {
427                         /*
428                          * If we belong to the destination multicast group
429                          * on the outgoing interface, and the caller did not
430                          * forbid loopback, loop back a copy.
431                          */
432                         ip_mloopback(ifp, m, dst, hlen);
433                 } else {
434                         /*
435                          * If we are acting as a multicast router, perform
436                          * multicast forwarding as if the packet had just
437                          * arrived on the interface to which we are about
438                          * to send.  The multicast forwarding function
439                          * recursively calls this function, using the
440                          * IP_FORWARDING flag to prevent infinite recursion.
441                          *
442                          * Multicasts that are looped back by ip_mloopback(),
443                          * above, will be forwarded by the ip_input() routine,
444                          * if necessary.
445                          */
446                         if (ip_mrouter && !(flags & IP_FORWARDING)) {
447                                 /*
448                                  * If rsvp daemon is not running, do not
449                                  * set ip_moptions. This ensures that the packet
450                                  * is multicast and not just sent down one link
451                                  * as prescribed by rsvpd.
452                                  */
453                                 if (!rsvp_on)
454                                         imo = NULL;
455                                 if (ip_mforward) {
456                                         get_mplock();
457                                         if (ip_mforward(ip, ifp, m, imo) != 0) {
458                                                 m_freem(m);
459                                                 rel_mplock();
460                                                 goto done;
461                                         }
462                                         rel_mplock();
463                                 }
464                         }
465                 }
466
467                 /*
468                  * Multicasts with a time-to-live of zero may be looped-
469                  * back, above, but must not be transmitted on a network.
470                  * Also, multicasts addressed to the loopback interface
471                  * are not sent -- the above call to ip_mloopback() will
472                  * loop back a copy if this host actually belongs to the
473                  * destination group on the loopback interface.
474                  */
475                 if (ip->ip_ttl == 0 || ifp->if_flags & IFF_LOOPBACK) {
476                         m_freem(m);
477                         goto done;
478                 }
479
480                 goto sendit;
481         } else {
482                 m->m_flags &= ~M_MCAST;
483         }
484
485         /*
486          * If the source address is not specified yet, use the address
487          * of the outoing interface. In case, keep note we did that, so
488          * if the the firewall changes the next-hop causing the output
489          * interface to change, we can fix that.
490          */
491         if (ip->ip_src.s_addr == INADDR_ANY || src_was_INADDR_ANY) {
492                 /* Interface may have no addresses. */
493                 if (ia != NULL) {
494                         ip->ip_src = IA_SIN(ia)->sin_addr;
495                         src_was_INADDR_ANY = 1;
496                 }
497         }
498
499 #ifdef ALTQ
500         /*
501          * Disable packet drop hack.
502          * Packetdrop should be done by queueing.
503          */
504 #else /* !ALTQ */
505         /*
506          * Verify that we have any chance at all of being able to queue
507          *      the packet or packet fragments
508          */
509         if ((ifp->if_snd.ifq_len + ip->ip_len / ifp->if_mtu + 1) >=
510             ifp->if_snd.ifq_maxlen) {
511                 error = ENOBUFS;
512                 ipstat.ips_odropped++;
513                 goto bad;
514         }
515 #endif /* !ALTQ */
516
517         /*
518          * Look for broadcast address and
519          * verify user is allowed to send
520          * such a packet.
521          */
522         if (isbroadcast) {
523                 if (!(ifp->if_flags & IFF_BROADCAST)) {
524                         error = EADDRNOTAVAIL;
525                         goto bad;
526                 }
527                 if (!(flags & IP_ALLOWBROADCAST)) {
528                         error = EACCES;
529                         goto bad;
530                 }
531                 /* don't allow broadcast messages to be fragmented */
532                 if (ip->ip_len > ifp->if_mtu) {
533                         error = EMSGSIZE;
534                         goto bad;
535                 }
536                 m->m_flags |= M_BCAST;
537         } else {
538                 m->m_flags &= ~M_BCAST;
539         }
540
541 sendit:
542 #ifdef IPSEC
543         /* get SP for this packet */
544         if (so == NULL)
545                 sp = ipsec4_getpolicybyaddr(m, IPSEC_DIR_OUTBOUND, flags, &error);
546         else
547                 sp = ipsec4_getpolicybysock(m, IPSEC_DIR_OUTBOUND, so, &error);
548
549         if (sp == NULL) {
550                 ipsecstat.out_inval++;
551                 goto bad;
552         }
553
554         error = 0;
555
556         /* check policy */
557         switch (sp->policy) {
558         case IPSEC_POLICY_DISCARD:
559                 /*
560                  * This packet is just discarded.
561                  */
562                 ipsecstat.out_polvio++;
563                 goto bad;
564
565         case IPSEC_POLICY_BYPASS:
566         case IPSEC_POLICY_NONE:
567         case IPSEC_POLICY_TCP:
568                 /* no need to do IPsec. */
569                 goto skip_ipsec;
570
571         case IPSEC_POLICY_IPSEC:
572                 if (sp->req == NULL) {
573                         /* acquire a policy */
574                         error = key_spdacquire(sp);
575                         goto bad;
576                 }
577                 break;
578
579         case IPSEC_POLICY_ENTRUST:
580         default:
581                 kprintf("ip_output: Invalid policy found. %d\n", sp->policy);
582         }
583     {
584         struct ipsec_output_state state;
585         bzero(&state, sizeof state);
586         state.m = m;
587         if (flags & IP_ROUTETOIF) {
588                 state.ro = &iproute;
589                 bzero(&iproute, sizeof iproute);
590         } else
591                 state.ro = ro;
592         state.dst = (struct sockaddr *)dst;
593
594         ip->ip_sum = 0;
595
596         /*
597          * XXX
598          * delayed checksums are not currently compatible with IPsec
599          */
600         if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
601                 in_delayed_cksum(m);
602                 m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
603         }
604
605         ip->ip_len = htons(ip->ip_len);
606         ip->ip_off = htons(ip->ip_off);
607
608         error = ipsec4_output(&state, sp, flags);
609
610         m = state.m;
611         if (flags & IP_ROUTETOIF) {
612                 /*
613                  * if we have tunnel mode SA, we may need to ignore
614                  * IP_ROUTETOIF.
615                  */
616                 if (state.ro != &iproute || state.ro->ro_rt != NULL) {
617                         flags &= ~IP_ROUTETOIF;
618                         ro = state.ro;
619                 }
620         } else
621                 ro = state.ro;
622         dst = (struct sockaddr_in *)state.dst;
623         if (error) {
624                 /* mbuf is already reclaimed in ipsec4_output. */
625                 m0 = NULL;
626                 switch (error) {
627                 case EHOSTUNREACH:
628                 case ENETUNREACH:
629                 case EMSGSIZE:
630                 case ENOBUFS:
631                 case ENOMEM:
632                         break;
633                 default:
634                         kprintf("ip4_output (ipsec): error code %d\n", error);
635                         /*fall through*/
636                 case ENOENT:
637                         /* don't show these error codes to the user */
638                         error = 0;
639                         break;
640                 }
641                 goto bad;
642         }
643     }
644
645         /* be sure to update variables that are affected by ipsec4_output() */
646         ip = mtod(m, struct ip *);
647 #ifdef _IP_VHL
648         hlen = IP_VHL_HL(ip->ip_vhl) << 2;
649 #else
650         hlen = ip->ip_hl << 2;
651 #endif
652         if (ro->ro_rt == NULL) {
653                 if (!(flags & IP_ROUTETOIF)) {
654                         kprintf("ip_output: "
655                                 "can't update route after IPsec processing\n");
656                         error = EHOSTUNREACH;   /*XXX*/
657                         goto bad;
658                 }
659         } else {
660                 ia = ifatoia(ro->ro_rt->rt_ifa);
661                 ifp = ro->ro_rt->rt_ifp;
662         }
663
664         /* make it flipped, again. */
665         ip->ip_len = ntohs(ip->ip_len);
666         ip->ip_off = ntohs(ip->ip_off);
667 skip_ipsec:
668 #endif /*IPSEC*/
669 #ifdef FAST_IPSEC
670         /*
671          * Check the security policy (SP) for the packet and, if
672          * required, do IPsec-related processing.  There are two
673          * cases here; the first time a packet is sent through
674          * it will be untagged and handled by ipsec4_checkpolicy.
675          * If the packet is resubmitted to ip_output (e.g. after
676          * AH, ESP, etc. processing), there will be a tag to bypass
677          * the lookup and related policy checking.
678          */
679         mtag = m_tag_find(m, PACKET_TAG_IPSEC_PENDING_TDB, NULL);
680         crit_enter();
681         if (mtag != NULL) {
682                 tdbi = (struct tdb_ident *)m_tag_data(mtag);
683                 sp = ipsec_getpolicy(tdbi, IPSEC_DIR_OUTBOUND);
684                 if (sp == NULL)
685                         error = -EINVAL;        /* force silent drop */
686                 m_tag_delete(m, mtag);
687         } else {
688                 sp = ipsec4_checkpolicy(m, IPSEC_DIR_OUTBOUND, flags,
689                                         &error, inp);
690         }
691         /*
692          * There are four return cases:
693          *    sp != NULL                    apply IPsec policy
694          *    sp == NULL, error == 0        no IPsec handling needed
695          *    sp == NULL, error == -EINVAL  discard packet w/o error
696          *    sp == NULL, error != 0        discard packet, report error
697          */
698         if (sp != NULL) {
699                 /* Loop detection, check if ipsec processing already done */
700                 KASSERT(sp->req != NULL, ("ip_output: no ipsec request"));
701                 for (mtag = m_tag_first(m); mtag != NULL;
702                      mtag = m_tag_next(m, mtag)) {
703                         if (mtag->m_tag_cookie != MTAG_ABI_COMPAT)
704                                 continue;
705                         if (mtag->m_tag_id != PACKET_TAG_IPSEC_OUT_DONE &&
706                             mtag->m_tag_id != PACKET_TAG_IPSEC_OUT_CRYPTO_NEEDED)
707                                 continue;
708                         /*
709                          * Check if policy has an SA associated with it.
710                          * This can happen when an SP has yet to acquire
711                          * an SA; e.g. on first reference.  If it occurs,
712                          * then we let ipsec4_process_packet do its thing.
713                          */
714                         if (sp->req->sav == NULL)
715                                 break;
716                         tdbi = (struct tdb_ident *)m_tag_data(mtag);
717                         if (tdbi->spi == sp->req->sav->spi &&
718                             tdbi->proto == sp->req->sav->sah->saidx.proto &&
719                             bcmp(&tdbi->dst, &sp->req->sav->sah->saidx.dst,
720                                  sizeof(union sockaddr_union)) == 0) {
721                                 /*
722                                  * No IPsec processing is needed, free
723                                  * reference to SP.
724                                  *
725                                  * NB: null pointer to avoid free at
726                                  *     done: below.
727                                  */
728                                 KEY_FREESP(&sp), sp = NULL;
729                                 crit_exit();
730                                 goto spd_done;
731                         }
732                 }
733
734                 /*
735                  * Do delayed checksums now because we send before
736                  * this is done in the normal processing path.
737                  */
738                 if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
739                         in_delayed_cksum(m);
740                         m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
741                 }
742
743                 ip->ip_len = htons(ip->ip_len);
744                 ip->ip_off = htons(ip->ip_off);
745
746                 /* NB: callee frees mbuf */
747                 error = ipsec4_process_packet(m, sp->req, flags, 0);
748                 /*
749                  * Preserve KAME behaviour: ENOENT can be returned
750                  * when an SA acquire is in progress.  Don't propagate
751                  * this to user-level; it confuses applications.
752                  *
753                  * XXX this will go away when the SADB is redone.
754                  */
755                 if (error == ENOENT)
756                         error = 0;
757                 crit_exit();
758                 goto done;
759         } else {
760                 crit_exit();
761
762                 if (error != 0) {
763                         /*
764                          * Hack: -EINVAL is used to signal that a packet
765                          * should be silently discarded.  This is typically
766                          * because we asked key management for an SA and
767                          * it was delayed (e.g. kicked up to IKE).
768                          */
769                         if (error == -EINVAL)
770                                 error = 0;
771                         goto bad;
772                 } else {
773                         /* No IPsec processing for this packet. */
774                 }
775 #ifdef notyet
776                 /*
777                  * If deferred crypto processing is needed, check that
778                  * the interface supports it.
779                  */
780                 mtag = m_tag_find(m, PACKET_TAG_IPSEC_OUT_CRYPTO_NEEDED, NULL);
781                 if (mtag != NULL && !(ifp->if_capenable & IFCAP_IPSEC)) {
782                         /* notify IPsec to do its own crypto */
783                         ipsp_skipcrypto_unmark((struct tdb_ident *)m_tag_data(mtag));
784                         error = EHOSTUNREACH;
785                         goto bad;
786                 }
787 #endif
788         }
789 spd_done:
790 #endif /* FAST_IPSEC */
791
792         /* We are already being fwd'd from a firewall. */
793         if (next_hop != NULL)
794                 goto pass;
795
796         /* No pfil hooks */
797         if (!pfil_has_hooks(&inet_pfil_hook)) {
798                 if (m->m_pkthdr.fw_flags & DUMMYNET_MBUF_TAGGED) {
799                         /*
800                          * Strip dummynet tags from stranded packets
801                          */
802                         mtag = m_tag_find(m, PACKET_TAG_DUMMYNET, NULL);
803                         KKASSERT(mtag != NULL);
804                         m_tag_delete(m, mtag);
805                         m->m_pkthdr.fw_flags &= ~DUMMYNET_MBUF_TAGGED;
806                 }
807                 goto pass;
808         }
809
810         /*
811          * IpHack's section.
812          * - Xlate: translate packet's addr/port (NAT).
813          * - Firewall: deny/allow/etc.
814          * - Wrap: fake packet's addr/port <unimpl.>
815          * - Encapsulate: put it in another IP and send out. <unimp.>
816          */
817
818         /*
819          * Run through list of hooks for output packets.
820          */
821         error = pfil_run_hooks(&inet_pfil_hook, &m, ifp, PFIL_OUT);
822         if (error != 0 || m == NULL)
823                 goto done;
824         ip = mtod(m, struct ip *);
825
826         if (m->m_pkthdr.fw_flags & IPFORWARD_MBUF_TAGGED) {
827                 /*
828                  * Check dst to make sure it is directly reachable on the
829                  * interface we previously thought it was.
830                  * If it isn't (which may be likely in some situations) we have
831                  * to re-route it (ie, find a route for the next-hop and the
832                  * associated interface) and set them here. This is nested
833                  * forwarding which in most cases is undesirable, except where
834                  * such control is nigh impossible. So we do it here.
835                  * And I'm babbling.
836                  */
837                 mtag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL);
838                 KKASSERT(mtag != NULL);
839                 next_hop = m_tag_data(mtag);
840
841                 /*
842                  * Try local forwarding first
843                  */
844                 if (ip_localforward(m, next_hop, hlen))
845                         goto done;
846
847                 /*
848                  * Relocate the route based on next_hop.
849                  * If the current route is inp's cache, keep it untouched.
850                  */
851                 if (ro == &iproute && ro->ro_rt != NULL) {
852                         RTFREE(ro->ro_rt);
853                         ro->ro_rt = NULL;
854                 }
855                 ro = &iproute;
856                 bzero(ro, sizeof *ro);
857
858                 /*
859                  * Forwarding to broadcast address is not allowed.
860                  * XXX Should we follow IP_ROUTETOIF?
861                  */
862                 flags &= ~(IP_ALLOWBROADCAST | IP_ROUTETOIF);
863
864                 /* We are doing forwarding now */
865                 flags |= IP_FORWARDING;
866
867                 goto reroute;
868         }
869
870         if (m->m_pkthdr.fw_flags & DUMMYNET_MBUF_TAGGED) {
871                 struct dn_pkt *dn_pkt;
872
873                 mtag = m_tag_find(m, PACKET_TAG_DUMMYNET, NULL);
874                 KKASSERT(mtag != NULL);
875                 dn_pkt = m_tag_data(mtag);
876
877                 /*
878                  * Under certain cases it is not possible to recalculate
879                  * 'ro' and 'dst', let alone 'flags', so just save them in
880                  * dummynet tag and avoid the possible wrong reculcalation
881                  * when we come back to ip_output() again.
882                  *
883                  * All other parameters have been already used and so they
884                  * are not needed anymore.
885                  * XXX if the ifp is deleted while a pkt is in dummynet,
886                  * we are in trouble! (TODO use ifnet_detach_event)
887                  *
888                  * We need to copy *ro because for ICMP pkts (and maybe
889                  * others) the caller passed a pointer into the stack;
890                  * dst might also be a pointer into *ro so it needs to
891                  * be updated.
892                  */
893                 dn_pkt->ro = *ro;
894                 if (ro->ro_rt)
895                         ro->ro_rt->rt_refcnt++;
896                 if (dst == (struct sockaddr_in *)&ro->ro_dst) {
897                         /* 'dst' points into 'ro' */
898                         dst = (struct sockaddr_in *)&(dn_pkt->ro.ro_dst);
899                 }
900                 dn_pkt->dn_dst = dst;
901                 dn_pkt->flags = flags;
902
903                 ip_dn_queue(m);
904                 goto done;
905         }
906 pass:
907         /* 127/8 must not appear on wire - RFC1122. */
908         if ((ntohl(ip->ip_dst.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET ||
909             (ntohl(ip->ip_src.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET) {
910                 if (!(ifp->if_flags & IFF_LOOPBACK)) {
911                         ipstat.ips_badaddr++;
912                         error = EADDRNOTAVAIL;
913                         goto bad;
914                 }
915         }
916
917         m->m_pkthdr.csum_flags |= CSUM_IP;
918         sw_csum = m->m_pkthdr.csum_flags & ~ifp->if_hwassist;
919         if (sw_csum & CSUM_DELAY_DATA) {
920                 in_delayed_cksum(m);
921                 sw_csum &= ~CSUM_DELAY_DATA;
922         }
923         m->m_pkthdr.csum_flags &= ifp->if_hwassist;
924
925         /*
926          * If small enough for interface, or the interface will take
927          * care of the fragmentation for us, can just send directly.
928          */
929         if (ip->ip_len <= ifp->if_mtu || ((ifp->if_hwassist & CSUM_FRAGMENT) &&
930             !(ip->ip_off & IP_DF))) {
931                 ip->ip_len = htons(ip->ip_len);
932                 ip->ip_off = htons(ip->ip_off);
933                 ip->ip_sum = 0;
934                 if (sw_csum & CSUM_DELAY_IP) {
935                         if (ip->ip_vhl == IP_VHL_BORING)
936                                 ip->ip_sum = in_cksum_hdr(ip);
937                         else
938                                 ip->ip_sum = in_cksum(m, hlen);
939                 }
940
941                 /* Record statistics for this interface address. */
942                 if (!(flags & IP_FORWARDING) && ia) {
943                         ia->ia_ifa.if_opackets++;
944                         ia->ia_ifa.if_obytes += m->m_pkthdr.len;
945                 }
946
947 #ifdef IPSEC
948                 /* clean ipsec history once it goes out of the node */
949                 ipsec_delaux(m);
950 #endif
951
952 #ifdef MBUF_STRESS_TEST
953                 if (mbuf_frag_size && m->m_pkthdr.len > mbuf_frag_size) {
954                         struct mbuf *m1, *m2;
955                         int length, tmp;
956
957                         tmp = length = m->m_pkthdr.len;
958
959                         while ((length -= mbuf_frag_size) >= 1) {
960                                 m1 = m_split(m, length, MB_DONTWAIT);
961                                 if (m1 == NULL)
962                                         break;
963                                 m2 = m;
964                                 while (m2->m_next != NULL)
965                                         m2 = m2->m_next;
966                                 m2->m_next = m1;
967                         }
968                         m->m_pkthdr.len = tmp;
969                 }
970 #endif
971
972 #ifdef MPLS
973                 if (!mpls_output_process(m, ro->ro_rt))
974                         goto done;
975 #endif
976                 error = ifp->if_output(ifp, m, (struct sockaddr *)dst,
977                                        ro->ro_rt);
978                 goto done;
979         }
980
981         if (ip->ip_off & IP_DF) {
982                 error = EMSGSIZE;
983                 /*
984                  * This case can happen if the user changed the MTU
985                  * of an interface after enabling IP on it.  Because
986                  * most netifs don't keep track of routes pointing to
987                  * them, there is no way for one to update all its
988                  * routes when the MTU is changed.
989                  */
990                 if ((ro->ro_rt->rt_flags & (RTF_UP | RTF_HOST)) &&
991                     !(ro->ro_rt->rt_rmx.rmx_locks & RTV_MTU) &&
992                     (ro->ro_rt->rt_rmx.rmx_mtu > ifp->if_mtu)) {
993                         ro->ro_rt->rt_rmx.rmx_mtu = ifp->if_mtu;
994                 }
995                 ipstat.ips_cantfrag++;
996                 goto bad;
997         }
998
999         /*
1000          * Too large for interface; fragment if possible. If successful,
1001          * on return, m will point to a list of packets to be sent.
1002          */
1003         error = ip_fragment(ip, &m, ifp->if_mtu, ifp->if_hwassist, sw_csum);
1004         if (error)
1005                 goto bad;
1006         for (; m; m = m0) {
1007                 m0 = m->m_nextpkt;
1008                 m->m_nextpkt = NULL;
1009 #ifdef IPSEC
1010                 /* clean ipsec history once it goes out of the node */
1011                 ipsec_delaux(m);
1012 #endif
1013                 if (error == 0) {
1014                         /* Record statistics for this interface address. */
1015                         if (ia != NULL) {
1016                                 ia->ia_ifa.if_opackets++;
1017                                 ia->ia_ifa.if_obytes += m->m_pkthdr.len;
1018                         }
1019 #ifdef MPLS
1020                         if (!mpls_output_process(m, ro->ro_rt))
1021                                 continue;
1022 #endif
1023                         error = ifp->if_output(ifp, m, (struct sockaddr *)dst,
1024                                                ro->ro_rt);
1025                 } else {
1026                         m_freem(m);
1027                 }
1028         }
1029
1030         if (error == 0)
1031                 ipstat.ips_fragmented++;
1032
1033 done:
1034         if (ro == &iproute && ro->ro_rt != NULL) {
1035                 RTFREE(ro->ro_rt);
1036                 ro->ro_rt = NULL;
1037         }
1038 #ifdef IPSEC
1039         if (sp != NULL) {
1040                 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1041                         kprintf("DP ip_output call free SP:%p\n", sp));
1042                 key_freesp(sp);
1043         }
1044 #endif
1045 #ifdef FAST_IPSEC
1046         if (sp != NULL)
1047                 KEY_FREESP(&sp);
1048 #endif
1049         return (error);
1050 bad:
1051         m_freem(m);
1052         goto done;
1053 }
1054
1055 /*
1056  * Create a chain of fragments which fit the given mtu. m_frag points to the
1057  * mbuf to be fragmented; on return it points to the chain with the fragments.
1058  * Return 0 if no error. If error, m_frag may contain a partially built
1059  * chain of fragments that should be freed by the caller.
1060  *
1061  * if_hwassist_flags is the hw offload capabilities (see if_data.ifi_hwassist)
1062  * sw_csum contains the delayed checksums flags (e.g., CSUM_DELAY_IP).
1063  */
1064 int
1065 ip_fragment(struct ip *ip, struct mbuf **m_frag, int mtu,
1066             u_long if_hwassist_flags, int sw_csum)
1067 {
1068         int error = 0;
1069         int hlen = IP_VHL_HL(ip->ip_vhl) << 2;
1070         int len = (mtu - hlen) & ~7;    /* size of payload in each fragment */
1071         int off;
1072         struct mbuf *m0 = *m_frag;      /* the original packet          */
1073         int firstlen;
1074         struct mbuf **mnext;
1075         int nfrags;
1076
1077         if (ip->ip_off & IP_DF) {       /* Fragmentation not allowed */
1078                 ipstat.ips_cantfrag++;
1079                 return EMSGSIZE;
1080         }
1081
1082         /*
1083          * Must be able to put at least 8 bytes per fragment.
1084          */
1085         if (len < 8)
1086                 return EMSGSIZE;
1087
1088         /*
1089          * If the interface will not calculate checksums on
1090          * fragmented packets, then do it here.
1091          */
1092         if ((m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA) &&
1093             !(if_hwassist_flags & CSUM_IP_FRAGS)) {
1094                 in_delayed_cksum(m0);
1095                 m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
1096         }
1097
1098         if (len > PAGE_SIZE) {
1099                 /*
1100                  * Fragment large datagrams such that each segment
1101                  * contains a multiple of PAGE_SIZE amount of data,
1102                  * plus headers. This enables a receiver to perform
1103                  * page-flipping zero-copy optimizations.
1104                  *
1105                  * XXX When does this help given that sender and receiver
1106                  * could have different page sizes, and also mtu could
1107                  * be less than the receiver's page size ?
1108                  */
1109                 int newlen;
1110                 struct mbuf *m;
1111
1112                 for (m = m0, off = 0; m && (off+m->m_len) <= mtu; m = m->m_next)
1113                         off += m->m_len;
1114
1115                 /*
1116                  * firstlen (off - hlen) must be aligned on an
1117                  * 8-byte boundary
1118                  */
1119                 if (off < hlen)
1120                         goto smart_frag_failure;
1121                 off = ((off - hlen) & ~7) + hlen;
1122                 newlen = (~PAGE_MASK) & mtu;
1123                 if ((newlen + sizeof(struct ip)) > mtu) {
1124                         /* we failed, go back the default */
1125 smart_frag_failure:
1126                         newlen = len;
1127                         off = hlen + len;
1128                 }
1129                 len = newlen;
1130
1131         } else {
1132                 off = hlen + len;
1133         }
1134
1135         firstlen = off - hlen;
1136         mnext = &m0->m_nextpkt;         /* pointer to next packet */
1137
1138         /*
1139          * Loop through length of segment after first fragment,
1140          * make new header and copy data of each part and link onto chain.
1141          * Here, m0 is the original packet, m is the fragment being created.
1142          * The fragments are linked off the m_nextpkt of the original
1143          * packet, which after processing serves as the first fragment.
1144          */
1145         for (nfrags = 1; off < ip->ip_len; off += len, nfrags++) {
1146                 struct ip *mhip;        /* ip header on the fragment */
1147                 struct mbuf *m;
1148                 int mhlen = sizeof(struct ip);
1149
1150                 MGETHDR(m, MB_DONTWAIT, MT_HEADER);
1151                 if (m == NULL) {
1152                         error = ENOBUFS;
1153                         ipstat.ips_odropped++;
1154                         goto done;
1155                 }
1156                 m->m_flags |= (m0->m_flags & M_MCAST) | M_FRAG;
1157                 /*
1158                  * In the first mbuf, leave room for the link header, then
1159                  * copy the original IP header including options. The payload
1160                  * goes into an additional mbuf chain returned by m_copy().
1161                  */
1162                 m->m_data += max_linkhdr;
1163                 mhip = mtod(m, struct ip *);
1164                 *mhip = *ip;
1165                 if (hlen > sizeof(struct ip)) {
1166                         mhlen = ip_optcopy(ip, mhip) + sizeof(struct ip);
1167                         mhip->ip_vhl = IP_MAKE_VHL(IPVERSION, mhlen >> 2);
1168                 }
1169                 m->m_len = mhlen;
1170                 /* XXX do we need to add ip->ip_off below ? */
1171                 mhip->ip_off = ((off - hlen) >> 3) + ip->ip_off;
1172                 if (off + len >= ip->ip_len) {  /* last fragment */
1173                         len = ip->ip_len - off;
1174                         m->m_flags |= M_LASTFRAG;
1175                 } else
1176                         mhip->ip_off |= IP_MF;
1177                 mhip->ip_len = htons((u_short)(len + mhlen));
1178                 m->m_next = m_copy(m0, off, len);
1179                 if (m->m_next == NULL) {                /* copy failed */
1180                         m_free(m);
1181                         error = ENOBUFS;        /* ??? */
1182                         ipstat.ips_odropped++;
1183                         goto done;
1184                 }
1185                 m->m_pkthdr.len = mhlen + len;
1186                 m->m_pkthdr.rcvif = NULL;
1187                 m->m_pkthdr.csum_flags = m0->m_pkthdr.csum_flags;
1188                 mhip->ip_off = htons(mhip->ip_off);
1189                 mhip->ip_sum = 0;
1190                 if (sw_csum & CSUM_DELAY_IP)
1191                         mhip->ip_sum = in_cksum(m, mhlen);
1192                 *mnext = m;
1193                 mnext = &m->m_nextpkt;
1194         }
1195         ipstat.ips_ofragments += nfrags;
1196
1197         /* set first marker for fragment chain */
1198         m0->m_flags |= M_FIRSTFRAG | M_FRAG;
1199         m0->m_pkthdr.csum_data = nfrags;
1200
1201         /*
1202          * Update first fragment by trimming what's been copied out
1203          * and updating header.
1204          */
1205         m_adj(m0, hlen + firstlen - ip->ip_len);
1206         m0->m_pkthdr.len = hlen + firstlen;
1207         ip->ip_len = htons((u_short)m0->m_pkthdr.len);
1208         ip->ip_off |= IP_MF;
1209         ip->ip_off = htons(ip->ip_off);
1210         ip->ip_sum = 0;
1211         if (sw_csum & CSUM_DELAY_IP)
1212                 ip->ip_sum = in_cksum(m0, hlen);
1213
1214 done:
1215         *m_frag = m0;
1216         return error;
1217 }
1218
1219 void
1220 in_delayed_cksum(struct mbuf *m)
1221 {
1222         struct ip *ip;
1223         u_short csum, offset;
1224
1225         ip = mtod(m, struct ip *);
1226         offset = IP_VHL_HL(ip->ip_vhl) << 2 ;
1227         csum = in_cksum_skip(m, ip->ip_len, offset);
1228         if (m->m_pkthdr.csum_flags & CSUM_UDP && csum == 0)
1229                 csum = 0xffff;
1230         offset += m->m_pkthdr.csum_data;        /* checksum offset */
1231
1232         if (offset + sizeof(u_short) > m->m_len) {
1233                 kprintf("delayed m_pullup, m->len: %d  off: %d  p: %d\n",
1234                     m->m_len, offset, ip->ip_p);
1235                 /*
1236                  * XXX
1237                  * this shouldn't happen, but if it does, the
1238                  * correct behavior may be to insert the checksum
1239                  * in the existing chain instead of rearranging it.
1240                  */
1241                 m = m_pullup(m, offset + sizeof(u_short));
1242         }
1243         *(u_short *)(m->m_data + offset) = csum;
1244 }
1245
1246 /*
1247  * Insert IP options into preformed packet.
1248  * Adjust IP destination as required for IP source routing,
1249  * as indicated by a non-zero in_addr at the start of the options.
1250  *
1251  * XXX This routine assumes that the packet has no options in place.
1252  */
1253 static struct mbuf *
1254 ip_insertoptions(struct mbuf *m, struct mbuf *opt, int *phlen)
1255 {
1256         struct ipoption *p = mtod(opt, struct ipoption *);
1257         struct mbuf *n;
1258         struct ip *ip = mtod(m, struct ip *);
1259         unsigned optlen;
1260
1261         optlen = opt->m_len - sizeof p->ipopt_dst;
1262         if (optlen + (u_short)ip->ip_len > IP_MAXPACKET) {
1263                 *phlen = 0;
1264                 return (m);             /* XXX should fail */
1265         }
1266         if (p->ipopt_dst.s_addr)
1267                 ip->ip_dst = p->ipopt_dst;
1268         if (m->m_flags & M_EXT || m->m_data - optlen < m->m_pktdat) {
1269                 MGETHDR(n, MB_DONTWAIT, MT_HEADER);
1270                 if (n == NULL) {
1271                         *phlen = 0;
1272                         return (m);
1273                 }
1274                 n->m_pkthdr.rcvif = NULL;
1275                 n->m_pkthdr.len = m->m_pkthdr.len + optlen;
1276                 m->m_len -= sizeof(struct ip);
1277                 m->m_data += sizeof(struct ip);
1278                 n->m_next = m;
1279                 m = n;
1280                 m->m_len = optlen + sizeof(struct ip);
1281                 m->m_data += max_linkhdr;
1282                 memcpy(mtod(m, void *), ip, sizeof(struct ip));
1283         } else {
1284                 m->m_data -= optlen;
1285                 m->m_len += optlen;
1286                 m->m_pkthdr.len += optlen;
1287                 ovbcopy(ip, mtod(m, caddr_t), sizeof(struct ip));
1288         }
1289         ip = mtod(m, struct ip *);
1290         bcopy(p->ipopt_list, ip + 1, optlen);
1291         *phlen = sizeof(struct ip) + optlen;
1292         ip->ip_vhl = IP_MAKE_VHL(IPVERSION, *phlen >> 2);
1293         ip->ip_len += optlen;
1294         return (m);
1295 }
1296
1297 /*
1298  * Copy options from ip to jp,
1299  * omitting those not copied during fragmentation.
1300  */
1301 int
1302 ip_optcopy(struct ip *ip, struct ip *jp)
1303 {
1304         u_char *cp, *dp;
1305         int opt, optlen, cnt;
1306
1307         cp = (u_char *)(ip + 1);
1308         dp = (u_char *)(jp + 1);
1309         cnt = (IP_VHL_HL(ip->ip_vhl) << 2) - sizeof(struct ip);
1310         for (; cnt > 0; cnt -= optlen, cp += optlen) {
1311                 opt = cp[0];
1312                 if (opt == IPOPT_EOL)
1313                         break;
1314                 if (opt == IPOPT_NOP) {
1315                         /* Preserve for IP mcast tunnel's LSRR alignment. */
1316                         *dp++ = IPOPT_NOP;
1317                         optlen = 1;
1318                         continue;
1319                 }
1320
1321                 KASSERT(cnt >= IPOPT_OLEN + sizeof *cp,
1322                     ("ip_optcopy: malformed ipv4 option"));
1323                 optlen = cp[IPOPT_OLEN];
1324                 KASSERT(optlen >= IPOPT_OLEN + sizeof *cp && optlen <= cnt,
1325                     ("ip_optcopy: malformed ipv4 option"));
1326
1327                 /* bogus lengths should have been caught by ip_dooptions */
1328                 if (optlen > cnt)
1329                         optlen = cnt;
1330                 if (IPOPT_COPIED(opt)) {
1331                         bcopy(cp, dp, optlen);
1332                         dp += optlen;
1333                 }
1334         }
1335         for (optlen = dp - (u_char *)(jp+1); optlen & 0x3; optlen++)
1336                 *dp++ = IPOPT_EOL;
1337         return (optlen);
1338 }
1339
1340 /*
1341  * IP socket option processing.
1342  */
1343 void
1344 ip_ctloutput(netmsg_t msg)
1345 {
1346         struct socket *so = msg->base.nm_so;
1347         struct sockopt *sopt = msg->ctloutput.nm_sopt;
1348         struct  inpcb *inp = so->so_pcb;
1349         int     error, optval;
1350
1351         error = optval = 0;
1352         if (sopt->sopt_level != IPPROTO_IP) {
1353                 error = EINVAL;
1354                 goto done;
1355         }
1356
1357         switch (sopt->sopt_dir) {
1358         case SOPT_SET:
1359                 switch (sopt->sopt_name) {
1360                 case IP_OPTIONS:
1361 #ifdef notyet
1362                 case IP_RETOPTS:
1363 #endif
1364                 {
1365                         struct mbuf *m;
1366                         if (sopt->sopt_valsize > MLEN) {
1367                                 error = EMSGSIZE;
1368                                 break;
1369                         }
1370                         MGET(m, sopt->sopt_td ? MB_WAIT : MB_DONTWAIT, MT_HEADER);
1371                         if (m == NULL) {
1372                                 error = ENOBUFS;
1373                                 break;
1374                         }
1375                         m->m_len = sopt->sopt_valsize;
1376                         error = soopt_to_kbuf(sopt, mtod(m, void *), m->m_len,
1377                                               m->m_len);
1378                         error = ip_pcbopts(sopt->sopt_name,
1379                                            &inp->inp_options, m);
1380                         goto done;
1381                 }
1382
1383                 case IP_TOS:
1384                 case IP_TTL:
1385                 case IP_MINTTL:
1386                 case IP_RECVOPTS:
1387                 case IP_RECVRETOPTS:
1388                 case IP_RECVDSTADDR:
1389                 case IP_RECVIF:
1390                 case IP_RECVTTL:
1391                 case IP_FAITH:
1392                         error = soopt_to_kbuf(sopt, &optval, sizeof optval,
1393                                              sizeof optval);
1394                         if (error)
1395                                 break;
1396                         switch (sopt->sopt_name) {
1397                         case IP_TOS:
1398                                 inp->inp_ip_tos = optval;
1399                                 break;
1400
1401                         case IP_TTL:
1402                                 inp->inp_ip_ttl = optval;
1403                                 break;
1404                         case IP_MINTTL:
1405                                 if (optval >= 0 && optval <= MAXTTL)
1406                                         inp->inp_ip_minttl = optval;
1407                                 else
1408                                         error = EINVAL;
1409                                 break;
1410 #define OPTSET(bit) \
1411         if (optval) \
1412                 inp->inp_flags |= bit; \
1413         else \
1414                 inp->inp_flags &= ~bit;
1415
1416                         case IP_RECVOPTS:
1417                                 OPTSET(INP_RECVOPTS);
1418                                 break;
1419
1420                         case IP_RECVRETOPTS:
1421                                 OPTSET(INP_RECVRETOPTS);
1422                                 break;
1423
1424                         case IP_RECVDSTADDR:
1425                                 OPTSET(INP_RECVDSTADDR);
1426                                 break;
1427
1428                         case IP_RECVIF:
1429                                 OPTSET(INP_RECVIF);
1430                                 break;
1431
1432                         case IP_RECVTTL:
1433                                 OPTSET(INP_RECVTTL);
1434                                 break;
1435
1436                         case IP_FAITH:
1437                                 OPTSET(INP_FAITH);
1438                                 break;
1439                         }
1440                         break;
1441 #undef OPTSET
1442
1443                 case IP_MULTICAST_IF:
1444                 case IP_MULTICAST_VIF:
1445                 case IP_MULTICAST_TTL:
1446                 case IP_MULTICAST_LOOP:
1447                 case IP_ADD_MEMBERSHIP:
1448                 case IP_DROP_MEMBERSHIP:
1449                         error = ip_setmoptions(sopt, &inp->inp_moptions);
1450                         break;
1451
1452                 case IP_PORTRANGE:
1453                         error = soopt_to_kbuf(sopt, &optval, sizeof optval,
1454                                             sizeof optval);
1455                         if (error)
1456                                 break;
1457
1458                         switch (optval) {
1459                         case IP_PORTRANGE_DEFAULT:
1460                                 inp->inp_flags &= ~(INP_LOWPORT);
1461                                 inp->inp_flags &= ~(INP_HIGHPORT);
1462                                 break;
1463
1464                         case IP_PORTRANGE_HIGH:
1465                                 inp->inp_flags &= ~(INP_LOWPORT);
1466                                 inp->inp_flags |= INP_HIGHPORT;
1467                                 break;
1468
1469                         case IP_PORTRANGE_LOW:
1470                                 inp->inp_flags &= ~(INP_HIGHPORT);
1471                                 inp->inp_flags |= INP_LOWPORT;
1472                                 break;
1473
1474                         default:
1475                                 error = EINVAL;
1476                                 break;
1477                         }
1478                         break;
1479
1480 #if defined(IPSEC) || defined(FAST_IPSEC)
1481                 case IP_IPSEC_POLICY:
1482                 {
1483                         caddr_t req;
1484                         size_t len = 0;
1485                         int priv;
1486                         struct mbuf *m;
1487                         int optname;
1488
1489                         if ((error = soopt_getm(sopt, &m)) != 0) /* XXX */
1490                                 break;
1491                         soopt_to_mbuf(sopt, m);
1492                         priv = (sopt->sopt_td != NULL &&
1493                                 priv_check(sopt->sopt_td, PRIV_ROOT) != 0) ? 0 : 1;
1494                         req = mtod(m, caddr_t);
1495                         len = m->m_len;
1496                         optname = sopt->sopt_name;
1497                         error = ipsec4_set_policy(inp, optname, req, len, priv);
1498                         m_freem(m);
1499                         break;
1500                 }
1501 #endif /*IPSEC*/
1502
1503                 default:
1504                         error = ENOPROTOOPT;
1505                         break;
1506                 }
1507                 break;
1508
1509         case SOPT_GET:
1510                 switch (sopt->sopt_name) {
1511                 case IP_OPTIONS:
1512                 case IP_RETOPTS:
1513                         if (inp->inp_options)
1514                                 soopt_from_kbuf(sopt, mtod(inp->inp_options,
1515                                                            char *),
1516                                                 inp->inp_options->m_len);
1517                         else
1518                                 sopt->sopt_valsize = 0;
1519                         break;
1520
1521                 case IP_TOS:
1522                 case IP_TTL:
1523                 case IP_MINTTL:
1524                 case IP_RECVOPTS:
1525                 case IP_RECVRETOPTS:
1526                 case IP_RECVDSTADDR:
1527                 case IP_RECVTTL:
1528                 case IP_RECVIF:
1529                 case IP_PORTRANGE:
1530                 case IP_FAITH:
1531                         switch (sopt->sopt_name) {
1532
1533                         case IP_TOS:
1534                                 optval = inp->inp_ip_tos;
1535                                 break;
1536
1537                         case IP_TTL:
1538                                 optval = inp->inp_ip_ttl;
1539                                 break;
1540                         case IP_MINTTL:
1541                                 optval = inp->inp_ip_minttl;
1542                                 break;
1543
1544 #define OPTBIT(bit)     (inp->inp_flags & bit ? 1 : 0)
1545
1546                         case IP_RECVOPTS:
1547                                 optval = OPTBIT(INP_RECVOPTS);
1548                                 break;
1549
1550                         case IP_RECVRETOPTS:
1551                                 optval = OPTBIT(INP_RECVRETOPTS);
1552                                 break;
1553
1554                         case IP_RECVDSTADDR:
1555                                 optval = OPTBIT(INP_RECVDSTADDR);
1556                                 break;
1557
1558                         case IP_RECVTTL:
1559                                 optval = OPTBIT(INP_RECVTTL);
1560                                 break;
1561
1562                         case IP_RECVIF:
1563                                 optval = OPTBIT(INP_RECVIF);
1564                                 break;
1565
1566                         case IP_PORTRANGE:
1567                                 if (inp->inp_flags & INP_HIGHPORT)
1568                                         optval = IP_PORTRANGE_HIGH;
1569                                 else if (inp->inp_flags & INP_LOWPORT)
1570                                         optval = IP_PORTRANGE_LOW;
1571                                 else
1572                                         optval = 0;
1573                                 break;
1574
1575                         case IP_FAITH:
1576                                 optval = OPTBIT(INP_FAITH);
1577                                 break;
1578                         }
1579                         soopt_from_kbuf(sopt, &optval, sizeof optval);
1580                         break;
1581
1582                 case IP_MULTICAST_IF:
1583                 case IP_MULTICAST_VIF:
1584                 case IP_MULTICAST_TTL:
1585                 case IP_MULTICAST_LOOP:
1586                 case IP_ADD_MEMBERSHIP:
1587                 case IP_DROP_MEMBERSHIP:
1588                         error = ip_getmoptions(sopt, inp->inp_moptions);
1589                         break;
1590
1591 #if defined(IPSEC) || defined(FAST_IPSEC)
1592                 case IP_IPSEC_POLICY:
1593                 {
1594                         struct mbuf *m = NULL;
1595                         caddr_t req = NULL;
1596                         size_t len = 0;
1597
1598                         if (m != NULL) {
1599                                 req = mtod(m, caddr_t);
1600                                 len = m->m_len;
1601                         }
1602                         error = ipsec4_get_policy(so->so_pcb, req, len, &m);
1603                         if (error == 0)
1604                                 error = soopt_from_mbuf(sopt, m); /* XXX */
1605                         if (error == 0)
1606                                 m_freem(m);
1607                         break;
1608                 }
1609 #endif /*IPSEC*/
1610
1611                 default:
1612                         error = ENOPROTOOPT;
1613                         break;
1614                 }
1615                 break;
1616         }
1617 done:
1618         lwkt_replymsg(&msg->lmsg, error);
1619 }
1620
1621 /*
1622  * Set up IP options in pcb for insertion in output packets.
1623  * Store in mbuf with pointer in pcbopt, adding pseudo-option
1624  * with destination address if source routed.
1625  */
1626 static int
1627 ip_pcbopts(int optname, struct mbuf **pcbopt, struct mbuf *m)
1628 {
1629         int cnt, optlen;
1630         u_char *cp;
1631         u_char opt;
1632
1633         /* turn off any old options */
1634         if (*pcbopt)
1635                 m_free(*pcbopt);
1636         *pcbopt = 0;
1637         if (m == NULL || m->m_len == 0) {
1638                 /*
1639                  * Only turning off any previous options.
1640                  */
1641                 if (m != NULL)
1642                         m_free(m);
1643                 return (0);
1644         }
1645
1646         if (m->m_len % sizeof(int32_t))
1647                 goto bad;
1648         /*
1649          * IP first-hop destination address will be stored before
1650          * actual options; move other options back
1651          * and clear it when none present.
1652          */
1653         if (m->m_data + m->m_len + sizeof(struct in_addr) >= &m->m_dat[MLEN])
1654                 goto bad;
1655         cnt = m->m_len;
1656         m->m_len += sizeof(struct in_addr);
1657         cp = mtod(m, u_char *) + sizeof(struct in_addr);
1658         ovbcopy(mtod(m, caddr_t), cp, cnt);
1659         bzero(mtod(m, caddr_t), sizeof(struct in_addr));
1660
1661         for (; cnt > 0; cnt -= optlen, cp += optlen) {
1662                 opt = cp[IPOPT_OPTVAL];
1663                 if (opt == IPOPT_EOL)
1664                         break;
1665                 if (opt == IPOPT_NOP)
1666                         optlen = 1;
1667                 else {
1668                         if (cnt < IPOPT_OLEN + sizeof *cp)
1669                                 goto bad;
1670                         optlen = cp[IPOPT_OLEN];
1671                         if (optlen < IPOPT_OLEN + sizeof *cp || optlen > cnt)
1672                                 goto bad;
1673                 }
1674                 switch (opt) {
1675
1676                 default:
1677                         break;
1678
1679                 case IPOPT_LSRR:
1680                 case IPOPT_SSRR:
1681                         /*
1682                          * user process specifies route as:
1683                          *      ->A->B->C->D
1684                          * D must be our final destination (but we can't
1685                          * check that since we may not have connected yet).
1686                          * A is first hop destination, which doesn't appear in
1687                          * actual IP option, but is stored before the options.
1688                          */
1689                         if (optlen < IPOPT_MINOFF - 1 + sizeof(struct in_addr))
1690                                 goto bad;
1691                         m->m_len -= sizeof(struct in_addr);
1692                         cnt -= sizeof(struct in_addr);
1693                         optlen -= sizeof(struct in_addr);
1694                         cp[IPOPT_OLEN] = optlen;
1695                         /*
1696                          * Move first hop before start of options.
1697                          */
1698                         bcopy(&cp[IPOPT_OFFSET+1], mtod(m, caddr_t),
1699                               sizeof(struct in_addr));
1700                         /*
1701                          * Then copy rest of options back
1702                          * to close up the deleted entry.
1703                          */
1704                         ovbcopy(&cp[IPOPT_OFFSET+1] + sizeof(struct in_addr),
1705                                 &cp[IPOPT_OFFSET+1],
1706                                 cnt - (IPOPT_MINOFF - 1));
1707                         break;
1708                 }
1709         }
1710         if (m->m_len > MAX_IPOPTLEN + sizeof(struct in_addr))
1711                 goto bad;
1712         *pcbopt = m;
1713         return (0);
1714
1715 bad:
1716         m_free(m);
1717         return (EINVAL);
1718 }
1719
1720 /*
1721  * XXX
1722  * The whole multicast option thing needs to be re-thought.
1723  * Several of these options are equally applicable to non-multicast
1724  * transmission, and one (IP_MULTICAST_TTL) totally duplicates a
1725  * standard option (IP_TTL).
1726  */
1727
1728 /*
1729  * following RFC1724 section 3.3, 0.0.0.0/8 is interpreted as interface index.
1730  */
1731 static struct ifnet *
1732 ip_multicast_if(struct in_addr *a, int *ifindexp)
1733 {
1734         int ifindex;
1735         struct ifnet *ifp;
1736
1737         if (ifindexp)
1738                 *ifindexp = 0;
1739         if (ntohl(a->s_addr) >> 24 == 0) {
1740                 ifindex = ntohl(a->s_addr) & 0xffffff;
1741                 if (ifindex < 0 || if_index < ifindex)
1742                         return NULL;
1743                 ifp = ifindex2ifnet[ifindex];
1744                 if (ifindexp)
1745                         *ifindexp = ifindex;
1746         } else {
1747                 ifp = INADDR_TO_IFP(a);
1748         }
1749         return ifp;
1750 }
1751
1752 /*
1753  * Set the IP multicast options in response to user setsockopt().
1754  */
1755 static int
1756 ip_setmoptions(struct sockopt *sopt, struct ip_moptions **imop)
1757 {
1758         int error = 0;
1759         int i;
1760         struct in_addr addr;
1761         struct ip_mreq mreq;
1762         struct ifnet *ifp;
1763         struct ip_moptions *imo = *imop;
1764         int ifindex;
1765
1766         if (imo == NULL) {
1767                 /*
1768                  * No multicast option buffer attached to the pcb;
1769                  * allocate one and initialize to default values.
1770                  */
1771                 imo = kmalloc(sizeof *imo, M_IPMOPTS, M_WAITOK);
1772
1773                 *imop = imo;
1774                 imo->imo_multicast_ifp = NULL;
1775                 imo->imo_multicast_addr.s_addr = INADDR_ANY;
1776                 imo->imo_multicast_vif = -1;
1777                 imo->imo_multicast_ttl = IP_DEFAULT_MULTICAST_TTL;
1778                 imo->imo_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
1779                 imo->imo_num_memberships = 0;
1780         }
1781         switch (sopt->sopt_name) {
1782         /* store an index number for the vif you wanna use in the send */
1783         case IP_MULTICAST_VIF:
1784                 if (legal_vif_num == 0) {
1785                         error = EOPNOTSUPP;
1786                         break;
1787                 }
1788                 error = soopt_to_kbuf(sopt, &i, sizeof i, sizeof i);
1789                 if (error)
1790                         break;
1791                 if (!legal_vif_num(i) && (i != -1)) {
1792                         error = EINVAL;
1793                         break;
1794                 }
1795                 imo->imo_multicast_vif = i;
1796                 break;
1797
1798         case IP_MULTICAST_IF:
1799                 /*
1800                  * Select the interface for outgoing multicast packets.
1801                  */
1802                 error = soopt_to_kbuf(sopt, &addr, sizeof addr, sizeof addr);
1803                 if (error)
1804                         break;
1805
1806                 /*
1807                  * INADDR_ANY is used to remove a previous selection.
1808                  * When no interface is selected, a default one is
1809                  * chosen every time a multicast packet is sent.
1810                  */
1811                 if (addr.s_addr == INADDR_ANY) {
1812                         imo->imo_multicast_ifp = NULL;
1813                         break;
1814                 }
1815                 /*
1816                  * The selected interface is identified by its local
1817                  * IP address.  Find the interface and confirm that
1818                  * it supports multicasting.
1819                  */
1820                 crit_enter();
1821                 ifp = ip_multicast_if(&addr, &ifindex);
1822                 if (ifp == NULL || !(ifp->if_flags & IFF_MULTICAST)) {
1823                         crit_exit();
1824                         error = EADDRNOTAVAIL;
1825                         break;
1826                 }
1827                 imo->imo_multicast_ifp = ifp;
1828                 if (ifindex)
1829                         imo->imo_multicast_addr = addr;
1830                 else
1831                         imo->imo_multicast_addr.s_addr = INADDR_ANY;
1832                 crit_exit();
1833                 break;
1834
1835         case IP_MULTICAST_TTL:
1836                 /*
1837                  * Set the IP time-to-live for outgoing multicast packets.
1838                  * The original multicast API required a char argument,
1839                  * which is inconsistent with the rest of the socket API.
1840                  * We allow either a char or an int.
1841                  */
1842                 if (sopt->sopt_valsize == 1) {
1843                         u_char ttl;
1844                         error = soopt_to_kbuf(sopt, &ttl, 1, 1);
1845                         if (error)
1846                                 break;
1847                         imo->imo_multicast_ttl = ttl;
1848                 } else {
1849                         u_int ttl;
1850                         error = soopt_to_kbuf(sopt, &ttl, sizeof ttl, sizeof ttl);
1851                         if (error)
1852                                 break;
1853                         if (ttl > 255)
1854                                 error = EINVAL;
1855                         else
1856                                 imo->imo_multicast_ttl = ttl;
1857                 }
1858                 break;
1859
1860         case IP_MULTICAST_LOOP:
1861                 /*
1862                  * Set the loopback flag for outgoing multicast packets.
1863                  * Must be zero or one.  The original multicast API required a
1864                  * char argument, which is inconsistent with the rest
1865                  * of the socket API.  We allow either a char or an int.
1866                  */
1867                 if (sopt->sopt_valsize == 1) {
1868                         u_char loop;
1869
1870                         error = soopt_to_kbuf(sopt, &loop, 1, 1);
1871                         if (error)
1872                                 break;
1873                         imo->imo_multicast_loop = !!loop;
1874                 } else {
1875                         u_int loop;
1876
1877                         error = soopt_to_kbuf(sopt, &loop, sizeof loop,
1878                                             sizeof loop);
1879                         if (error)
1880                                 break;
1881                         imo->imo_multicast_loop = !!loop;
1882                 }
1883                 break;
1884
1885         case IP_ADD_MEMBERSHIP:
1886                 /*
1887                  * Add a multicast group membership.
1888                  * Group must be a valid IP multicast address.
1889                  */
1890                 error = soopt_to_kbuf(sopt, &mreq, sizeof mreq, sizeof mreq);
1891                 if (error)
1892                         break;
1893
1894                 if (!IN_MULTICAST(ntohl(mreq.imr_multiaddr.s_addr))) {
1895                         error = EINVAL;
1896                         break;
1897                 }
1898                 crit_enter();
1899                 /*
1900                  * If no interface address was provided, use the interface of
1901                  * the route to the given multicast address.
1902                  */
1903                 if (mreq.imr_interface.s_addr == INADDR_ANY) {
1904                         struct sockaddr_in dst;
1905                         struct rtentry *rt;
1906
1907                         bzero(&dst, sizeof(struct sockaddr_in));
1908                         dst.sin_len = sizeof(struct sockaddr_in);
1909                         dst.sin_family = AF_INET;
1910                         dst.sin_addr = mreq.imr_multiaddr;
1911                         rt = rtlookup((struct sockaddr *)&dst);
1912                         if (rt == NULL) {
1913                                 error = EADDRNOTAVAIL;
1914                                 crit_exit();
1915                                 break;
1916                         }
1917                         --rt->rt_refcnt;
1918                         ifp = rt->rt_ifp;
1919                 } else {
1920                         ifp = ip_multicast_if(&mreq.imr_interface, NULL);
1921                 }
1922
1923                 /*
1924                  * See if we found an interface, and confirm that it
1925                  * supports multicast.
1926                  */
1927                 if (ifp == NULL || !(ifp->if_flags & IFF_MULTICAST)) {
1928                         error = EADDRNOTAVAIL;
1929                         crit_exit();
1930                         break;
1931                 }
1932                 /*
1933                  * See if the membership already exists or if all the
1934                  * membership slots are full.
1935                  */
1936                 for (i = 0; i < imo->imo_num_memberships; ++i) {
1937                         if (imo->imo_membership[i]->inm_ifp == ifp &&
1938                             imo->imo_membership[i]->inm_addr.s_addr
1939                                                 == mreq.imr_multiaddr.s_addr)
1940                                 break;
1941                 }
1942                 if (i < imo->imo_num_memberships) {
1943                         error = EADDRINUSE;
1944                         crit_exit();
1945                         break;
1946                 }
1947                 if (i == IP_MAX_MEMBERSHIPS) {
1948                         error = ETOOMANYREFS;
1949                         crit_exit();
1950                         break;
1951                 }
1952                 /*
1953                  * Everything looks good; add a new record to the multicast
1954                  * address list for the given interface.
1955                  */
1956                 if ((imo->imo_membership[i] =
1957                      in_addmulti(&mreq.imr_multiaddr, ifp)) == NULL) {
1958                         error = ENOBUFS;
1959                         crit_exit();
1960                         break;
1961                 }
1962                 ++imo->imo_num_memberships;
1963                 crit_exit();
1964                 break;
1965
1966         case IP_DROP_MEMBERSHIP:
1967                 /*
1968                  * Drop a multicast group membership.
1969                  * Group must be a valid IP multicast address.
1970                  */
1971                 error = soopt_to_kbuf(sopt, &mreq, sizeof mreq, sizeof mreq);
1972                 if (error)
1973                         break;
1974
1975                 if (!IN_MULTICAST(ntohl(mreq.imr_multiaddr.s_addr))) {
1976                         error = EINVAL;
1977                         break;
1978                 }
1979
1980                 crit_enter();
1981                 /*
1982                  * If an interface address was specified, get a pointer
1983                  * to its ifnet structure.
1984                  */
1985                 if (mreq.imr_interface.s_addr == INADDR_ANY)
1986                         ifp = NULL;
1987                 else {
1988                         ifp = ip_multicast_if(&mreq.imr_interface, NULL);
1989                         if (ifp == NULL) {
1990                                 error = EADDRNOTAVAIL;
1991                                 crit_exit();
1992                                 break;
1993                         }
1994                 }
1995                 /*
1996                  * Find the membership in the membership array.
1997                  */
1998                 for (i = 0; i < imo->imo_num_memberships; ++i) {
1999                         if ((ifp == NULL ||
2000                              imo->imo_membership[i]->inm_ifp == ifp) &&
2001                             imo->imo_membership[i]->inm_addr.s_addr ==
2002                             mreq.imr_multiaddr.s_addr)
2003                                 break;
2004                 }
2005                 if (i == imo->imo_num_memberships) {
2006                         error = EADDRNOTAVAIL;
2007                         crit_exit();
2008                         break;
2009                 }
2010                 /*
2011                  * Give up the multicast address record to which the
2012                  * membership points.
2013                  */
2014                 in_delmulti(imo->imo_membership[i]);
2015                 /*
2016                  * Remove the gap in the membership array.
2017                  */
2018                 for (++i; i < imo->imo_num_memberships; ++i)
2019                         imo->imo_membership[i-1] = imo->imo_membership[i];
2020                 --imo->imo_num_memberships;
2021                 crit_exit();
2022                 break;
2023
2024         default:
2025                 error = EOPNOTSUPP;
2026                 break;
2027         }
2028
2029         /*
2030          * If all options have default values, no need to keep the mbuf.
2031          */
2032         if (imo->imo_multicast_ifp == NULL &&
2033             imo->imo_multicast_vif == -1 &&
2034             imo->imo_multicast_ttl == IP_DEFAULT_MULTICAST_TTL &&
2035             imo->imo_multicast_loop == IP_DEFAULT_MULTICAST_LOOP &&
2036             imo->imo_num_memberships == 0) {
2037                 kfree(*imop, M_IPMOPTS);
2038                 *imop = NULL;
2039         }
2040
2041         return (error);
2042 }
2043
2044 /*
2045  * Return the IP multicast options in response to user getsockopt().
2046  */
2047 static int
2048 ip_getmoptions(struct sockopt *sopt, struct ip_moptions *imo)
2049 {
2050         struct in_addr addr;
2051         struct in_ifaddr *ia;
2052         int error, optval;
2053         u_char coptval;
2054
2055         error = 0;
2056         switch (sopt->sopt_name) {
2057         case IP_MULTICAST_VIF:
2058                 if (imo != NULL)
2059                         optval = imo->imo_multicast_vif;
2060                 else
2061                         optval = -1;
2062                 soopt_from_kbuf(sopt, &optval, sizeof optval);
2063                 break;
2064
2065         case IP_MULTICAST_IF:
2066                 if (imo == NULL || imo->imo_multicast_ifp == NULL)
2067                         addr.s_addr = INADDR_ANY;
2068                 else if (imo->imo_multicast_addr.s_addr) {
2069                         /* return the value user has set */
2070                         addr = imo->imo_multicast_addr;
2071                 } else {
2072                         ia = IFP_TO_IA(imo->imo_multicast_ifp);
2073                         addr.s_addr = (ia == NULL) ? INADDR_ANY
2074                                 : IA_SIN(ia)->sin_addr.s_addr;
2075                 }
2076                 soopt_from_kbuf(sopt, &addr, sizeof addr);
2077                 break;
2078
2079         case IP_MULTICAST_TTL:
2080                 if (imo == NULL)
2081                         optval = coptval = IP_DEFAULT_MULTICAST_TTL;
2082                 else
2083                         optval = coptval = imo->imo_multicast_ttl;
2084                 if (sopt->sopt_valsize == 1)
2085                         soopt_from_kbuf(sopt, &coptval, 1);
2086                 else
2087                         soopt_from_kbuf(sopt, &optval, sizeof optval);
2088                 break;
2089
2090         case IP_MULTICAST_LOOP:
2091                 if (imo == NULL)
2092                         optval = coptval = IP_DEFAULT_MULTICAST_LOOP;
2093                 else
2094                         optval = coptval = imo->imo_multicast_loop;
2095                 if (sopt->sopt_valsize == 1)
2096                         soopt_from_kbuf(sopt, &coptval, 1);
2097                 else
2098                         soopt_from_kbuf(sopt, &optval, sizeof optval);
2099                 break;
2100
2101         default:
2102                 error = ENOPROTOOPT;
2103                 break;
2104         }
2105         return (error);
2106 }
2107
2108 /*
2109  * Discard the IP multicast options.
2110  */
2111 void
2112 ip_freemoptions(struct ip_moptions *imo)
2113 {
2114         int i;
2115
2116         if (imo != NULL) {
2117                 for (i = 0; i < imo->imo_num_memberships; ++i)
2118                         in_delmulti(imo->imo_membership[i]);
2119                 kfree(imo, M_IPMOPTS);
2120         }
2121 }
2122
2123 /*
2124  * Routine called from ip_output() to loop back a copy of an IP multicast
2125  * packet to the input queue of a specified interface.  Note that this
2126  * calls the output routine of the loopback "driver", but with an interface
2127  * pointer that might NOT be a loopback interface -- evil, but easier than
2128  * replicating that code here.
2129  */
2130 static void
2131 ip_mloopback(struct ifnet *ifp, struct mbuf *m, struct sockaddr_in *dst,
2132              int hlen)
2133 {
2134         struct ip *ip;
2135         struct mbuf *copym;
2136
2137         copym = m_copypacket(m, MB_DONTWAIT);
2138         if (copym != NULL && (copym->m_flags & M_EXT || copym->m_len < hlen))
2139                 copym = m_pullup(copym, hlen);
2140         if (copym != NULL) {
2141                 /*
2142                  * if the checksum hasn't been computed, mark it as valid
2143                  */
2144                 if (copym->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
2145                         in_delayed_cksum(copym);
2146                         copym->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
2147                         copym->m_pkthdr.csum_flags |=
2148                             CSUM_DATA_VALID | CSUM_PSEUDO_HDR;
2149                         copym->m_pkthdr.csum_data = 0xffff;
2150                 }
2151                 /*
2152                  * We don't bother to fragment if the IP length is greater
2153                  * than the interface's MTU.  Can this possibly matter?
2154                  */
2155                 ip = mtod(copym, struct ip *);
2156                 ip->ip_len = htons(ip->ip_len);
2157                 ip->ip_off = htons(ip->ip_off);
2158                 ip->ip_sum = 0;
2159                 if (ip->ip_vhl == IP_VHL_BORING) {
2160                         ip->ip_sum = in_cksum_hdr(ip);
2161                 } else {
2162                         ip->ip_sum = in_cksum(copym, hlen);
2163                 }
2164                 /*
2165                  * NB:
2166                  * It's not clear whether there are any lingering
2167                  * reentrancy problems in other areas which might
2168                  * be exposed by using ip_input directly (in
2169                  * particular, everything which modifies the packet
2170                  * in-place).  Yet another option is using the
2171                  * protosw directly to deliver the looped back
2172                  * packet.  For the moment, we'll err on the side
2173                  * of safety by using if_simloop().
2174                  */
2175 #if 1 /* XXX */
2176                 if (dst->sin_family != AF_INET) {
2177                         kprintf("ip_mloopback: bad address family %d\n",
2178                                                 dst->sin_family);
2179                         dst->sin_family = AF_INET;
2180                 }
2181 #endif
2182                 get_mplock();   /* is if_simloop() mpsafe yet? */
2183                 if_simloop(ifp, copym, dst->sin_family, 0);
2184                 rel_mplock();
2185         }
2186 }