Initial import from FreeBSD RELENG_4:
[dragonfly.git] / sys / netinet / ip_icmp.c
1 /*
2  * Copyright (c) 1982, 1986, 1988, 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_icmp.c   8.2 (Berkeley) 1/4/94
34  * $FreeBSD: src/sys/netinet/ip_icmp.c,v 1.39.2.19 2003/01/24 05:11:34 sam Exp $
35  */
36
37 #include "opt_ipsec.h"
38
39 #include <sys/param.h>
40 #include <sys/systm.h>
41 #include <sys/mbuf.h>
42 #include <sys/protosw.h>
43 #include <sys/socket.h>
44 #include <sys/time.h>
45 #include <sys/kernel.h>
46 #include <sys/sysctl.h>
47
48 #include <net/if.h>
49 #include <net/if_types.h>
50 #include <net/route.h>
51
52 #define _IP_VHL
53 #include <netinet/in.h>
54 #include <netinet/in_systm.h>
55 #include <netinet/in_var.h>
56 #include <netinet/ip.h>
57 #include <netinet/ip_icmp.h>
58 #include <netinet/ip_var.h>
59 #include <netinet/icmp_var.h>
60
61 #ifdef IPSEC
62 #include <netinet6/ipsec.h>
63 #include <netkey/key.h>
64 #endif
65
66 #ifdef FAST_IPSEC
67 #include <netipsec/ipsec.h>
68 #include <netipsec/key.h>
69 #define IPSEC
70 #endif
71
72 /*
73  * ICMP routines: error generation, receive packet processing, and
74  * routines to turnaround packets back to the originator, and
75  * host table maintenance routines.
76  */
77
78 static struct   icmpstat icmpstat;
79 SYSCTL_STRUCT(_net_inet_icmp, ICMPCTL_STATS, stats, CTLFLAG_RW,
80         &icmpstat, icmpstat, "");
81
82 static int      icmpmaskrepl = 0;
83 SYSCTL_INT(_net_inet_icmp, ICMPCTL_MASKREPL, maskrepl, CTLFLAG_RW,
84         &icmpmaskrepl, 0, "");
85
86 static int      drop_redirect = 0;
87 SYSCTL_INT(_net_inet_icmp, OID_AUTO, drop_redirect, CTLFLAG_RW, 
88         &drop_redirect, 0, "");
89
90 static int      log_redirect = 0;
91 SYSCTL_INT(_net_inet_icmp, OID_AUTO, log_redirect, CTLFLAG_RW, 
92         &log_redirect, 0, "");
93
94 #ifdef ICMP_BANDLIM 
95  
96 /*    
97  * ICMP error-response bandwidth limiting sysctl.  If not enabled, sysctl
98  *      variable content is -1 and read-only.
99  */     
100     
101 static int      icmplim = 200;
102 SYSCTL_INT(_net_inet_icmp, ICMPCTL_ICMPLIM, icmplim, CTLFLAG_RW,
103         &icmplim, 0, "");
104 #else
105
106 static int      icmplim = -1;
107 SYSCTL_INT(_net_inet_icmp, ICMPCTL_ICMPLIM, icmplim, CTLFLAG_RD,
108         &icmplim, 0, "");
109         
110 #endif 
111
112 static int      icmplim_output = 1;
113 SYSCTL_INT(_net_inet_icmp, OID_AUTO, icmplim_output, CTLFLAG_RW,
114         &icmplim_output, 0, "");
115
116 /*
117  * ICMP broadcast echo sysctl
118  */
119
120 static int      icmpbmcastecho = 0;
121 SYSCTL_INT(_net_inet_icmp, OID_AUTO, bmcastecho, CTLFLAG_RW,
122         &icmpbmcastecho, 0, "");
123
124
125 #ifdef ICMPPRINTFS
126 int     icmpprintfs = 0;
127 #endif
128
129 static void     icmp_reflect __P((struct mbuf *));
130 static void     icmp_send __P((struct mbuf *, struct mbuf *, struct route *));
131 static int      ip_next_mtu __P((int, int));
132
133 extern  struct protosw inetsw[];
134
135 /*
136  * Generate an error packet of type error
137  * in response to bad packet ip.
138  */
139 void
140 icmp_error(n, type, code, dest, destifp)
141         struct mbuf *n;
142         int type, code;
143         n_long dest;
144         struct ifnet *destifp;
145 {
146         register struct ip *oip = mtod(n, struct ip *), *nip;
147         register unsigned oiplen = IP_VHL_HL(oip->ip_vhl) << 2;
148         register struct icmp *icp;
149         register struct mbuf *m;
150         unsigned icmplen;
151
152 #ifdef ICMPPRINTFS
153         if (icmpprintfs)
154                 printf("icmp_error(%p, %x, %d)\n", oip, type, code);
155 #endif
156         if (type != ICMP_REDIRECT)
157                 icmpstat.icps_error++;
158         /*
159          * Don't send error if not the first fragment of message.
160          * Don't error if the old packet protocol was ICMP
161          * error message, only known informational types.
162          */
163         if (oip->ip_off &~ (IP_MF|IP_DF))
164                 goto freeit;
165         if (oip->ip_p == IPPROTO_ICMP && type != ICMP_REDIRECT &&
166           n->m_len >= oiplen + ICMP_MINLEN &&
167           !ICMP_INFOTYPE(((struct icmp *)((caddr_t)oip + oiplen))->icmp_type)) {
168                 icmpstat.icps_oldicmp++;
169                 goto freeit;
170         }
171         /* Don't send error in response to a multicast or broadcast packet */
172         if (n->m_flags & (M_BCAST|M_MCAST))
173                 goto freeit;
174         /*
175          * First, formulate icmp message
176          */
177         m = m_gethdr(M_DONTWAIT, MT_HEADER);
178         if (m == NULL)
179                 goto freeit;
180         icmplen = min(oiplen + 8, oip->ip_len);
181         if (icmplen < sizeof(struct ip))
182                 panic("icmp_error: bad length");
183         m->m_len = icmplen + ICMP_MINLEN;
184         MH_ALIGN(m, m->m_len);
185         icp = mtod(m, struct icmp *);
186         if ((u_int)type > ICMP_MAXTYPE)
187                 panic("icmp_error");
188         icmpstat.icps_outhist[type]++;
189         icp->icmp_type = type;
190         if (type == ICMP_REDIRECT)
191                 icp->icmp_gwaddr.s_addr = dest;
192         else {
193                 icp->icmp_void = 0;
194                 /*
195                  * The following assignments assume an overlay with the
196                  * zeroed icmp_void field.
197                  */
198                 if (type == ICMP_PARAMPROB) {
199                         icp->icmp_pptr = code;
200                         code = 0;
201                 } else if (type == ICMP_UNREACH &&
202                         code == ICMP_UNREACH_NEEDFRAG && destifp) {
203                         icp->icmp_nextmtu = htons(destifp->if_mtu);
204                 }
205         }
206
207         icp->icmp_code = code;
208         m_copydata(n, 0, icmplen, (caddr_t)&icp->icmp_ip);
209         nip = &icp->icmp_ip;
210
211         /*
212          * Convert fields to network representation.
213          */
214         HTONS(nip->ip_len);
215         HTONS(nip->ip_off);
216
217         /*
218          * Now, copy old ip header (without options)
219          * in front of icmp message.
220          */
221         if (m->m_data - sizeof(struct ip) < m->m_pktdat)
222                 panic("icmp len");
223         m->m_data -= sizeof(struct ip);
224         m->m_len += sizeof(struct ip);
225         m->m_pkthdr.len = m->m_len;
226         m->m_pkthdr.rcvif = n->m_pkthdr.rcvif;
227         nip = mtod(m, struct ip *);
228         bcopy((caddr_t)oip, (caddr_t)nip, sizeof(struct ip));
229         nip->ip_len = m->m_len;
230         nip->ip_vhl = IP_VHL_BORING;
231         nip->ip_p = IPPROTO_ICMP;
232         nip->ip_tos = 0;
233         icmp_reflect(m);
234
235 freeit:
236         m_freem(n);
237 }
238
239 static struct sockaddr_in icmpsrc = { sizeof (struct sockaddr_in), AF_INET };
240 static struct sockaddr_in icmpdst = { sizeof (struct sockaddr_in), AF_INET };
241 static struct sockaddr_in icmpgw = { sizeof (struct sockaddr_in), AF_INET };
242
243 /*
244  * Process a received ICMP message.
245  */
246 void
247 icmp_input(m, off, proto)
248         register struct mbuf *m;
249         int off, proto;
250 {
251         int hlen = off;
252         register struct icmp *icp;
253         register struct ip *ip = mtod(m, struct ip *);
254         int icmplen = ip->ip_len;
255         register int i;
256         struct in_ifaddr *ia;
257         void (*ctlfunc) __P((int, struct sockaddr *, void *));
258         int code;
259
260         /*
261          * Locate icmp structure in mbuf, and check
262          * that not corrupted and of at least minimum length.
263          */
264 #ifdef ICMPPRINTFS
265         if (icmpprintfs) {
266                 char buf[4 * sizeof "123"];
267                 strcpy(buf, inet_ntoa(ip->ip_src));
268                 printf("icmp_input from %s to %s, len %d\n",
269                        buf, inet_ntoa(ip->ip_dst), icmplen);
270         }
271 #endif
272         if (icmplen < ICMP_MINLEN) {
273                 icmpstat.icps_tooshort++;
274                 goto freeit;
275         }
276         i = hlen + min(icmplen, ICMP_ADVLENMIN);
277         if (m->m_len < i && (m = m_pullup(m, i)) == 0)  {
278                 icmpstat.icps_tooshort++;
279                 return;
280         }
281         ip = mtod(m, struct ip *);
282         m->m_len -= hlen;
283         m->m_data += hlen;
284         icp = mtod(m, struct icmp *);
285         if (in_cksum(m, icmplen)) {
286                 icmpstat.icps_checksum++;
287                 goto freeit;
288         }
289         m->m_len += hlen;
290         m->m_data -= hlen;
291
292         if (m->m_pkthdr.rcvif && m->m_pkthdr.rcvif->if_type == IFT_FAITH) {
293                 /*
294                  * Deliver very specific ICMP type only.
295                  */
296                 switch (icp->icmp_type) {
297                 case ICMP_UNREACH:
298                 case ICMP_TIMXCEED:
299                         break;
300                 default:
301                         goto freeit;
302                 }
303         }
304
305 #ifdef ICMPPRINTFS
306         if (icmpprintfs)
307                 printf("icmp_input, type %d code %d\n", icp->icmp_type,
308                     icp->icmp_code);
309 #endif
310
311         /*
312          * Message type specific processing.
313          */
314         if (icp->icmp_type > ICMP_MAXTYPE)
315                 goto raw;
316         icmpstat.icps_inhist[icp->icmp_type]++;
317         code = icp->icmp_code;
318         switch (icp->icmp_type) {
319
320         case ICMP_UNREACH:
321                 switch (code) {
322                         case ICMP_UNREACH_NET:
323                         case ICMP_UNREACH_HOST:
324                         case ICMP_UNREACH_SRCFAIL:
325                         case ICMP_UNREACH_NET_UNKNOWN:
326                         case ICMP_UNREACH_HOST_UNKNOWN:
327                         case ICMP_UNREACH_ISOLATED:
328                         case ICMP_UNREACH_TOSNET:
329                         case ICMP_UNREACH_TOSHOST:
330                         case ICMP_UNREACH_HOST_PRECEDENCE:
331                         case ICMP_UNREACH_PRECEDENCE_CUTOFF:
332                                 code = PRC_UNREACH_NET;
333                                 break;
334
335                         case ICMP_UNREACH_NEEDFRAG:
336                                 code = PRC_MSGSIZE;
337                                 break;
338
339                         /*
340                          * RFC 1122, Sections 3.2.2.1 and 4.2.3.9.
341                          * Treat subcodes 2,3 as immediate RST
342                          */
343                         case ICMP_UNREACH_PROTOCOL:
344                         case ICMP_UNREACH_PORT:
345                                 code = PRC_UNREACH_PORT;
346                                 break;
347
348                         case ICMP_UNREACH_NET_PROHIB:
349                         case ICMP_UNREACH_HOST_PROHIB:
350                         case ICMP_UNREACH_FILTER_PROHIB:
351                                 code = PRC_UNREACH_ADMIN_PROHIB;
352                                 break;
353
354                         default:
355                                 goto badcode;
356                 }
357                 goto deliver;
358
359         case ICMP_TIMXCEED:
360                 if (code > 1)
361                         goto badcode;
362                 code += PRC_TIMXCEED_INTRANS;
363                 goto deliver;
364
365         case ICMP_PARAMPROB:
366                 if (code > 1)
367                         goto badcode;
368                 code = PRC_PARAMPROB;
369                 goto deliver;
370
371         case ICMP_SOURCEQUENCH:
372                 if (code)
373                         goto badcode;
374                 code = PRC_QUENCH;
375         deliver:
376                 /*
377                  * Problem with datagram; advise higher level routines.
378                  */
379                 if (icmplen < ICMP_ADVLENMIN || icmplen < ICMP_ADVLEN(icp) ||
380                     IP_VHL_HL(icp->icmp_ip.ip_vhl) < (sizeof(struct ip) >> 2)) {
381                         icmpstat.icps_badlen++;
382                         goto freeit;
383                 }
384                 NTOHS(icp->icmp_ip.ip_len);
385                 /* Discard ICMP's in response to multicast packets */
386                 if (IN_MULTICAST(ntohl(icp->icmp_ip.ip_dst.s_addr)))
387                         goto badcode;
388 #ifdef ICMPPRINTFS
389                 if (icmpprintfs)
390                         printf("deliver to protocol %d\n", icp->icmp_ip.ip_p);
391 #endif
392                 icmpsrc.sin_addr = icp->icmp_ip.ip_dst;
393 #if 1
394                 /*
395                  * MTU discovery:
396                  * If we got a needfrag and there is a host route to the
397                  * original destination, and the MTU is not locked, then
398                  * set the MTU in the route to the suggested new value
399                  * (if given) and then notify as usual.  The ULPs will
400                  * notice that the MTU has changed and adapt accordingly.
401                  * If no new MTU was suggested, then we guess a new one
402                  * less than the current value.  If the new MTU is 
403                  * unreasonably small (arbitrarily set at 296), then
404                  * we reset the MTU to the interface value and enable the
405                  * lock bit, indicating that we are no longer doing MTU
406                  * discovery.
407                  */
408                 if (code == PRC_MSGSIZE) {
409                         struct rtentry *rt;
410                         int mtu;
411
412                         rt = rtalloc1((struct sockaddr *)&icmpsrc, 0,
413                                       RTF_CLONING | RTF_PRCLONING);
414                         if (rt && (rt->rt_flags & RTF_HOST)
415                             && !(rt->rt_rmx.rmx_locks & RTV_MTU)) {
416                                 mtu = ntohs(icp->icmp_nextmtu);
417                                 if (!mtu)
418                                         mtu = ip_next_mtu(rt->rt_rmx.rmx_mtu,
419                                                           1);
420 #ifdef DEBUG_MTUDISC
421                                 printf("MTU for %s reduced to %d\n",
422                                         inet_ntoa(icmpsrc.sin_addr), mtu);
423 #endif
424                                 if (mtu < 296) {
425                                         /* rt->rt_rmx.rmx_mtu =
426                                                 rt->rt_ifp->if_mtu; */
427                                         rt->rt_rmx.rmx_locks |= RTV_MTU;
428                                 } else if (rt->rt_rmx.rmx_mtu > mtu) {
429                                         rt->rt_rmx.rmx_mtu = mtu;
430                                 }
431                         }
432                         if (rt)
433                                 RTFREE(rt);
434                 }
435
436 #endif
437                 /*
438                  * XXX if the packet contains [IPv4 AH TCP], we can't make a
439                  * notification to TCP layer.
440                  */
441                 ctlfunc = inetsw[ip_protox[icp->icmp_ip.ip_p]].pr_ctlinput;
442                 if (ctlfunc)
443                         (*ctlfunc)(code, (struct sockaddr *)&icmpsrc,
444                                    (void *)&icp->icmp_ip);
445                 break;
446
447         badcode:
448                 icmpstat.icps_badcode++;
449                 break;
450
451         case ICMP_ECHO:
452                 if (!icmpbmcastecho
453                     && (m->m_flags & (M_MCAST | M_BCAST)) != 0) {
454                         icmpstat.icps_bmcastecho++;
455                         break;
456                 }
457                 icp->icmp_type = ICMP_ECHOREPLY;
458 #ifdef ICMP_BANDLIM
459                 if (badport_bandlim(BANDLIM_ICMP_ECHO) < 0)
460                         goto freeit;
461                 else
462 #endif
463                         goto reflect;
464
465         case ICMP_TSTAMP:
466                 if (!icmpbmcastecho
467                     && (m->m_flags & (M_MCAST | M_BCAST)) != 0) {
468                         icmpstat.icps_bmcasttstamp++;
469                         break;
470                 }
471                 if (icmplen < ICMP_TSLEN) {
472                         icmpstat.icps_badlen++;
473                         break;
474                 }
475                 icp->icmp_type = ICMP_TSTAMPREPLY;
476                 icp->icmp_rtime = iptime();
477                 icp->icmp_ttime = icp->icmp_rtime;      /* bogus, do later! */
478 #ifdef ICMP_BANDLIM
479                 if (badport_bandlim(BANDLIM_ICMP_TSTAMP) < 0)
480                         goto freeit;
481                 else
482 #endif
483                         goto reflect;
484
485         case ICMP_MASKREQ:
486                 if (icmpmaskrepl == 0)
487                         break;
488                 /*
489                  * We are not able to respond with all ones broadcast
490                  * unless we receive it over a point-to-point interface.
491                  */
492                 if (icmplen < ICMP_MASKLEN)
493                         break;
494                 switch (ip->ip_dst.s_addr) {
495
496                 case INADDR_BROADCAST:
497                 case INADDR_ANY:
498                         icmpdst.sin_addr = ip->ip_src;
499                         break;
500
501                 default:
502                         icmpdst.sin_addr = ip->ip_dst;
503                 }
504                 ia = (struct in_ifaddr *)ifaof_ifpforaddr(
505                             (struct sockaddr *)&icmpdst, m->m_pkthdr.rcvif);
506                 if (ia == 0)
507                         break;
508                 if (ia->ia_ifp == 0)
509                         break;
510                 icp->icmp_type = ICMP_MASKREPLY;
511                 icp->icmp_mask = ia->ia_sockmask.sin_addr.s_addr;
512                 if (ip->ip_src.s_addr == 0) {
513                         if (ia->ia_ifp->if_flags & IFF_BROADCAST)
514                             ip->ip_src = satosin(&ia->ia_broadaddr)->sin_addr;
515                         else if (ia->ia_ifp->if_flags & IFF_POINTOPOINT)
516                             ip->ip_src = satosin(&ia->ia_dstaddr)->sin_addr;
517                 }
518 reflect:
519                 ip->ip_len += hlen;     /* since ip_input deducts this */
520                 icmpstat.icps_reflect++;
521                 icmpstat.icps_outhist[icp->icmp_type]++;
522                 icmp_reflect(m);
523                 return;
524
525         case ICMP_REDIRECT:
526                 if (log_redirect) {
527                         u_long src, dst, gw;
528
529                         src = ntohl(ip->ip_src.s_addr);
530                         dst = ntohl(icp->icmp_ip.ip_dst.s_addr);
531                         gw = ntohl(icp->icmp_gwaddr.s_addr);
532                         printf("icmp redirect from %d.%d.%d.%d: "
533                                "%d.%d.%d.%d => %d.%d.%d.%d\n",
534                                (int)(src >> 24), (int)((src >> 16) & 0xff),
535                                (int)((src >> 8) & 0xff), (int)(src & 0xff),
536                                (int)(dst >> 24), (int)((dst >> 16) & 0xff),
537                                (int)((dst >> 8) & 0xff), (int)(dst & 0xff),
538                                (int)(gw >> 24), (int)((gw >> 16) & 0xff),
539                                (int)((gw >> 8) & 0xff), (int)(gw & 0xff));
540                 }
541                 if (drop_redirect)
542                         break;
543                 if (code > 3)
544                         goto badcode;
545                 if (icmplen < ICMP_ADVLENMIN || icmplen < ICMP_ADVLEN(icp) ||
546                     IP_VHL_HL(icp->icmp_ip.ip_vhl) < (sizeof(struct ip) >> 2)) {
547                         icmpstat.icps_badlen++;
548                         break;
549                 }
550                 /*
551                  * Short circuit routing redirects to force
552                  * immediate change in the kernel's routing
553                  * tables.  The message is also handed to anyone
554                  * listening on a raw socket (e.g. the routing
555                  * daemon for use in updating its tables).
556                  */
557                 icmpgw.sin_addr = ip->ip_src;
558                 icmpdst.sin_addr = icp->icmp_gwaddr;
559 #ifdef  ICMPPRINTFS
560                 if (icmpprintfs) {
561                         char buf[4 * sizeof "123"];
562                         strcpy(buf, inet_ntoa(icp->icmp_ip.ip_dst));
563
564                         printf("redirect dst %s to %s\n",
565                                buf, inet_ntoa(icp->icmp_gwaddr));
566                 }
567 #endif
568                 icmpsrc.sin_addr = icp->icmp_ip.ip_dst;
569                 rtredirect((struct sockaddr *)&icmpsrc,
570                   (struct sockaddr *)&icmpdst,
571                   (struct sockaddr *)0, RTF_GATEWAY | RTF_HOST,
572                   (struct sockaddr *)&icmpgw, (struct rtentry **)0);
573                 pfctlinput(PRC_REDIRECT_HOST, (struct sockaddr *)&icmpsrc);
574 #ifdef IPSEC
575                 key_sa_routechange((struct sockaddr *)&icmpsrc);
576 #endif
577                 break;
578
579         /*
580          * No kernel processing for the following;
581          * just fall through to send to raw listener.
582          */
583         case ICMP_ECHOREPLY:
584         case ICMP_ROUTERADVERT:
585         case ICMP_ROUTERSOLICIT:
586         case ICMP_TSTAMPREPLY:
587         case ICMP_IREQREPLY:
588         case ICMP_MASKREPLY:
589         default:
590                 break;
591         }
592
593 raw:
594         rip_input(m, off, proto);
595         return;
596
597 freeit:
598         m_freem(m);
599 }
600
601 /*
602  * Reflect the ip packet back to the source
603  */
604 static void
605 icmp_reflect(m)
606         struct mbuf *m;
607 {
608         struct ip *ip = mtod(m, struct ip *);
609         struct ifaddr *ifa;
610         struct in_ifaddr *ia;
611         struct in_addr t;
612         struct mbuf *opts = 0;
613         int optlen = (IP_VHL_HL(ip->ip_vhl) << 2) - sizeof(struct ip);
614         struct route *ro = NULL, rt;
615
616         if (!in_canforward(ip->ip_src) &&
617             ((ntohl(ip->ip_src.s_addr) & IN_CLASSA_NET) !=
618              (IN_LOOPBACKNET << IN_CLASSA_NSHIFT))) {
619                 m_freem(m);     /* Bad return address */
620                 icmpstat.icps_badaddr++;
621                 goto done;      /* Ip_output() will check for broadcast */
622         }
623         t = ip->ip_dst;
624         ip->ip_dst = ip->ip_src;
625         ro = &rt;
626         bzero(ro, sizeof(*ro));
627         /*
628          * If the incoming packet was addressed directly to us,
629          * use dst as the src for the reply.  Otherwise (broadcast
630          * or anonymous), use the address which corresponds
631          * to the incoming interface.
632          */
633         LIST_FOREACH(ia, INADDR_HASH(t.s_addr), ia_hash)
634                 if (t.s_addr == IA_SIN(ia)->sin_addr.s_addr)
635                         goto match;
636         if (m->m_pkthdr.rcvif != NULL &&
637             m->m_pkthdr.rcvif->if_flags & IFF_BROADCAST) {
638                 TAILQ_FOREACH(ifa, &m->m_pkthdr.rcvif->if_addrhead, ifa_link) {
639                         if (ifa->ifa_addr->sa_family != AF_INET)
640                                 continue;
641                         ia = ifatoia(ifa);
642                         if (satosin(&ia->ia_broadaddr)->sin_addr.s_addr ==
643                             t.s_addr)
644                                 goto match;
645                 }
646         }
647         ia = ip_rtaddr(ip->ip_dst, ro);
648         /* We need a route to do anything useful. */
649         if (ia == NULL) {
650                 m_freem(m);
651                 icmpstat.icps_noroute++;
652                 goto done;
653         }
654 match:
655         t = IA_SIN(ia)->sin_addr;
656         ip->ip_src = t;
657         ip->ip_ttl = ip_defttl;
658
659         if (optlen > 0) {
660                 register u_char *cp;
661                 int opt, cnt;
662                 u_int len;
663
664                 /*
665                  * Retrieve any source routing from the incoming packet;
666                  * add on any record-route or timestamp options.
667                  */
668                 cp = (u_char *) (ip + 1);
669                 if ((opts = ip_srcroute()) == 0 &&
670                     (opts = m_gethdr(M_DONTWAIT, MT_HEADER))) {
671                         opts->m_len = sizeof(struct in_addr);
672                         mtod(opts, struct in_addr *)->s_addr = 0;
673                 }
674                 if (opts) {
675 #ifdef ICMPPRINTFS
676                     if (icmpprintfs)
677                             printf("icmp_reflect optlen %d rt %d => ",
678                                 optlen, opts->m_len);
679 #endif
680                     for (cnt = optlen; cnt > 0; cnt -= len, cp += len) {
681                             opt = cp[IPOPT_OPTVAL];
682                             if (opt == IPOPT_EOL)
683                                     break;
684                             if (opt == IPOPT_NOP)
685                                     len = 1;
686                             else {
687                                     if (cnt < IPOPT_OLEN + sizeof(*cp))
688                                             break;
689                                     len = cp[IPOPT_OLEN];
690                                     if (len < IPOPT_OLEN + sizeof(*cp) ||
691                                         len > cnt)
692                                             break;
693                             }
694                             /*
695                              * Should check for overflow, but it "can't happen"
696                              */
697                             if (opt == IPOPT_RR || opt == IPOPT_TS ||
698                                 opt == IPOPT_SECURITY) {
699                                     bcopy((caddr_t)cp,
700                                         mtod(opts, caddr_t) + opts->m_len, len);
701                                     opts->m_len += len;
702                             }
703                     }
704                     /* Terminate & pad, if necessary */
705                     cnt = opts->m_len % 4;
706                     if (cnt) {
707                             for (; cnt < 4; cnt++) {
708                                     *(mtod(opts, caddr_t) + opts->m_len) =
709                                         IPOPT_EOL;
710                                     opts->m_len++;
711                             }
712                     }
713 #ifdef ICMPPRINTFS
714                     if (icmpprintfs)
715                             printf("%d\n", opts->m_len);
716 #endif
717                 }
718                 /*
719                  * Now strip out original options by copying rest of first
720                  * mbuf's data back, and adjust the IP length.
721                  */
722                 ip->ip_len -= optlen;
723                 ip->ip_vhl = IP_VHL_BORING;
724                 m->m_len -= optlen;
725                 if (m->m_flags & M_PKTHDR)
726                         m->m_pkthdr.len -= optlen;
727                 optlen += sizeof(struct ip);
728                 bcopy((caddr_t)ip + optlen, (caddr_t)(ip + 1),
729                          (unsigned)(m->m_len - sizeof(struct ip)));
730         }
731         m->m_flags &= ~(M_BCAST|M_MCAST);
732         icmp_send(m, opts, ro);
733 done:
734         if (opts)
735                 (void)m_free(opts);
736         if (ro && ro->ro_rt)
737                 RTFREE(ro->ro_rt);
738 }
739
740 /*
741  * Send an icmp packet back to the ip level,
742  * after supplying a checksum.
743  */
744 static void
745 icmp_send(m, opts, rt)
746         register struct mbuf *m;
747         struct mbuf *opts;
748         struct route *rt;
749 {
750         register struct ip *ip = mtod(m, struct ip *);
751         register int hlen;
752         register struct icmp *icp;
753
754         hlen = IP_VHL_HL(ip->ip_vhl) << 2;
755         m->m_data += hlen;
756         m->m_len -= hlen;
757         icp = mtod(m, struct icmp *);
758         icp->icmp_cksum = 0;
759         icp->icmp_cksum = in_cksum(m, ip->ip_len - hlen);
760         m->m_data -= hlen;
761         m->m_len += hlen;
762         m->m_pkthdr.rcvif = (struct ifnet *)0;
763 #ifdef ICMPPRINTFS
764         if (icmpprintfs) {
765                 char buf[4 * sizeof "123"];
766                 strcpy(buf, inet_ntoa(ip->ip_dst));
767                 printf("icmp_send dst %s src %s\n",
768                        buf, inet_ntoa(ip->ip_src));
769         }
770 #endif
771         (void) ip_output(m, opts, rt, 0, NULL, NULL);
772 }
773
774 n_time
775 iptime()
776 {
777         struct timeval atv;
778         u_long t;
779
780         getmicrotime(&atv);
781         t = (atv.tv_sec % (24*60*60)) * 1000 + atv.tv_usec / 1000;
782         return (htonl(t));
783 }
784
785 #if 1
786 /*
787  * Return the next larger or smaller MTU plateau (table from RFC 1191)
788  * given current value MTU.  If DIR is less than zero, a larger plateau
789  * is returned; otherwise, a smaller value is returned.
790  */
791 static int
792 ip_next_mtu(mtu, dir)
793         int mtu;
794         int dir;
795 {
796         static int mtutab[] = {
797                 65535, 32000, 17914, 8166, 4352, 2002, 1492, 1006, 508, 296,
798                 68, 0
799         };
800         int i;
801
802         for (i = 0; i < (sizeof mtutab) / (sizeof mtutab[0]); i++) {
803                 if (mtu >= mtutab[i])
804                         break;
805         }
806
807         if (dir < 0) {
808                 if (i == 0) {
809                         return 0;
810                 } else {
811                         return mtutab[i - 1];
812                 }
813         } else {
814                 if (mtutab[i] == 0) {
815                         return 0;
816                 } else if(mtu > mtutab[i]) {
817                         return mtutab[i];
818                 } else {
819                         return mtutab[i + 1];
820                 }
821         }
822 }
823 #endif
824
825 #ifdef ICMP_BANDLIM
826
827 /*
828  * badport_bandlim() - check for ICMP bandwidth limit
829  *
830  *      Return 0 if it is ok to send an ICMP error response, -1 if we have
831  *      hit our bandwidth limit and it is not ok.  
832  *
833  *      If icmplim is <= 0, the feature is disabled and 0 is returned.
834  *
835  *      For now we separate the TCP and UDP subsystems w/ different 'which'
836  *      values.  We may eventually remove this separation (and simplify the
837  *      code further).
838  *
839  *      Note that the printing of the error message is delayed so we can
840  *      properly print the icmp error rate that the system was trying to do
841  *      (i.e. 22000/100 pps, etc...).  This can cause long delays in printing
842  *      the 'final' error, but it doesn't make sense to solve the printing 
843  *      delay with more complex code.
844  */
845
846 int
847 badport_bandlim(int which)
848 {
849         static int lticks[BANDLIM_MAX + 1];
850         static int lpackets[BANDLIM_MAX + 1];
851         int dticks;
852         const char *bandlimittype[] = {
853                 "Limiting icmp unreach response",
854                 "Limiting icmp ping response",
855                 "Limiting icmp tstamp response",
856                 "Limiting closed port RST response",
857                 "Limiting open port RST response"
858                 };
859
860         /*
861          * Return ok status if feature disabled or argument out of
862          * ranage.
863          */
864
865         if (icmplim <= 0 || which > BANDLIM_MAX || which < 0)
866                 return(0);
867         dticks = ticks - lticks[which];
868
869         /*
870          * reset stats when cumulative dt exceeds one second.
871          */
872
873         if ((unsigned int)dticks > hz) {
874                 if (lpackets[which] > icmplim && icmplim_output) {
875                         printf("%s from %d to %d packets per second\n",
876                                 bandlimittype[which],
877                                 lpackets[which],
878                                 icmplim
879                         );
880                 }
881                 lticks[which] = ticks;
882                 lpackets[which] = 0;
883         }
884
885         /*
886          * bump packet count
887          */
888
889         if (++lpackets[which] > icmplim) {
890                 return(-1);
891         }
892         return(0);
893 }
894
895 #endif
896
897