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