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