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