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