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