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