Merge from vendor branch GCC:
[dragonfly.git] / sys / contrib / ipfilter / netinet / fil.c
1 /*
2  * Copyright (C) 1993-2001 by Darren Reed.
3  *
4  * See the IPFILTER.LICENCE file for details on licencing.
5  *
6  * @(#)fil.c        1.36 6/5/96 (C) 1993-2000 Darren Reed
7  * $FreeBSD: src/sys/contrib/ipfilter/netinet/fil.c,v 1.23.2.7 2004/07/04 09:24:38 darrenr Exp $
8  * $DragonFly: src/sys/contrib/ipfilter/netinet/fil.c,v 1.9 2004/07/28 00:22:36 hmp Exp $
9  */
10 #if defined(__sgi) && (IRIX > 602)
11 # include <sys/ptimers.h>
12 #endif
13 #include <sys/errno.h>
14 #include <sys/types.h>
15 #include <sys/param.h>
16 #include <sys/time.h>
17 #include <sys/file.h>
18 #if defined(__NetBSD__) && (NetBSD >= 199905) && !defined(IPFILTER_LKM) && \
19     defined(_KERNEL)
20 # include "opt_ipfilter_log.h"
21 #endif
22 #if (defined(KERNEL) || defined(_KERNEL)) && (defined(__DragonFly__) || (defined(__FreeBSD_version) && \
23     (__FreeBSD_version >= 220000)))
24 # if defined(__DragonFly__) || (__FreeBSD_version >= 400000)
25 #  ifndef KLD_MODULE
26 #   include "opt_inet6.h"
27 #  endif
28 #  if defined(__FreeBSD__) && (__FreeBSD_version == 400019)
29 #   define CSUM_DELAY_DATA
30 #  endif
31 # endif
32 # include <sys/filio.h>
33 # include <sys/fcntl.h>
34 #else
35 # include <sys/ioctl.h>
36 #endif
37 #if (defined(_KERNEL) || defined(KERNEL)) && !defined(linux)
38 # include <sys/systm.h>
39 #else
40 # include <stdio.h>
41 # include <string.h>
42 # include <stdlib.h>
43 #endif
44 #if !defined(__SVR4) && !defined(__svr4__)
45 # ifndef linux
46 #  include <sys/mbuf.h>
47 # endif
48 #else
49 # include <sys/cmn_err.h>
50 # include <sys/byteorder.h>
51 # if SOLARIS2 < 5
52 #  include <sys/dditypes.h>
53 # endif
54 #  include <sys/stream.h>
55 #endif
56 #ifndef linux
57 # include <sys/protosw.h>
58 # include <sys/socket.h>
59 #endif
60 #include <net/if.h>
61 #ifdef sun
62 # include <net/af.h>
63 #endif
64 #include <net/route.h>
65 #include <netinet/in.h>
66 #include <netinet/in_systm.h>
67 #include <netinet/ip.h>
68 #ifndef linux
69 # include <netinet/ip_var.h>
70 #endif
71 #if defined(__sgi) && defined(IFF_DRVRLOCK) /* IRIX 6 */
72 # include <sys/hashing.h>
73 # include <netinet/in_var.h>
74 #endif
75 #include <netinet/tcp.h>
76 #include <netinet/udp.h>
77 #include <netinet/ip_icmp.h>
78 #include "ip_compat.h"
79 #ifdef  USE_INET6
80 # include <netinet/icmp6.h>
81 # if !SOLARIS && defined(_KERNEL)
82 #  include <netinet6/in6_var.h>
83 # endif
84 #endif
85 #include <netinet/tcpip.h>
86 #include "ip_fil.h"
87 #include "ip_nat.h"
88 #include "ip_frag.h"
89 #include "ip_state.h"
90 #include "ip_proxy.h"
91 #include "ip_auth.h"
92 # if defined(__DragonFly__) || (defined(__FreeBSD_version) && (__FreeBSD_version >= 300000))
93 #  include <sys/malloc.h>
94 #  if defined(_KERNEL) && !defined(IPFILTER_LKM)
95 #   include "opt_ipfilter.h"
96 #  endif
97 # endif
98 #ifndef MIN
99 # define        MIN(a,b)        (((a)<(b))?(a):(b))
100 #endif
101 #include "ipl.h"
102
103 #include <sys/in_cksum.h>
104
105 static const char sccsid[] = "@(#)fil.c        1.36 6/5/96 (C) 1993-2000 Darren Reed";
106
107 #ifndef _KERNEL
108 # include "ipf.h"
109 # include "ipt.h"
110 extern  int     opts;
111
112 # define        FR_VERBOSE(verb_pr)                     verbose verb_pr
113 # define        FR_DEBUG(verb_pr)                       debug verb_pr
114 # define        IPLLOG(a, c, d, e)              ipflog(a, c, d, e)
115 #else /* #ifndef _KERNEL */
116 # define        FR_VERBOSE(verb_pr)
117 # define        FR_DEBUG(verb_pr)
118 # define        IPLLOG(a, c, d, e)              ipflog(a, c, d, e)
119 # if SOLARIS || defined(__sgi)
120 extern  KRWLOCK_T       ipf_mutex, ipf_auth, ipf_nat;
121 extern  kmutex_t        ipf_rw;
122 # endif /* SOLARIS || __sgi */
123 #endif /* _KERNEL */
124
125
126 struct  filterstats frstats[2] = {{0,0,0,0,0},{0,0,0,0,0}};
127 struct  frentry *ipfilter[2][2] = { { NULL, NULL }, { NULL, NULL } },
128 #ifdef  USE_INET6
129                 *ipfilter6[2][2] = { { NULL, NULL }, { NULL, NULL } },
130                 *ipacct6[2][2] = { { NULL, NULL }, { NULL, NULL } },
131 #endif
132                 *ipacct[2][2] = { { NULL, NULL }, { NULL, NULL } };
133 struct  frgroup *ipfgroups[3][2];
134 int     fr_flags = IPF_LOGGING;
135 int     fr_active = 0;
136 int     fr_chksrc = 0;
137 int     fr_minttl = 3;
138 int     fr_minttllog = 1;
139 #if defined(IPFILTER_DEFAULT_BLOCK)
140 int     fr_pass = FR_NOMATCH|FR_BLOCK;
141 #else
142 int     fr_pass = (IPF_DEFAULT_PASS|FR_NOMATCH);
143 #endif
144 char    ipfilter_version[] = IPL_VERSION;
145
146 fr_info_t       frcache[2];
147
148 static  int     frflushlist (int, minor_t, int *, frentry_t **);
149 #ifdef  _KERNEL
150 static  void    frsynclist (frentry_t *);
151 #endif
152
153 # ifndef __sgi
154 static  void    *ipf_pullup (mb_t *, fr_info_t *, int, void *);
155 # endif
156
157 /*
158  * bit values for identifying presence of individual IP options
159  */
160 struct  optlist ipopts[20] = {
161         { IPOPT_NOP,    0x000001 },
162         { IPOPT_RR,     0x000002 },
163         { IPOPT_ZSU,    0x000004 },
164         { IPOPT_MTUP,   0x000008 },
165         { IPOPT_MTUR,   0x000010 },
166         { IPOPT_ENCODE, 0x000020 },
167         { IPOPT_TS,     0x000040 },
168         { IPOPT_TR,     0x000080 },
169         { IPOPT_SECURITY, 0x000100 },
170         { IPOPT_LSRR,   0x000200 },
171         { IPOPT_E_SEC,  0x000400 },
172         { IPOPT_CIPSO,  0x000800 },
173         { IPOPT_SATID,  0x001000 },
174         { IPOPT_SSRR,   0x002000 },
175         { IPOPT_ADDEXT, 0x004000 },
176         { IPOPT_VISA,   0x008000 },
177         { IPOPT_IMITD,  0x010000 },
178         { IPOPT_EIP,    0x020000 },
179         { IPOPT_FINN,   0x040000 },
180         { 0,            0x000000 }
181 };
182
183 /*
184  * bit values for identifying presence of individual IP security options
185  */
186 struct  optlist secopt[8] = {
187         { IPSO_CLASS_RES4,      0x01 },
188         { IPSO_CLASS_TOPS,      0x02 },
189         { IPSO_CLASS_SECR,      0x04 },
190         { IPSO_CLASS_RES3,      0x08 },
191         { IPSO_CLASS_CONF,      0x10 },
192         { IPSO_CLASS_UNCL,      0x20 },
193         { IPSO_CLASS_RES2,      0x40 },
194         { IPSO_CLASS_RES1,      0x80 }
195 };
196
197
198 /*
199  * compact the IP header into a structure which contains just the info.
200  * which is useful for comparing IP headers with.
201  */
202 int     fr_makefrip(hlen, ip, fin)
203 int hlen;
204 ip_t *ip;
205 fr_info_t *fin;
206 {
207         u_short optmsk = 0, secmsk = 0, auth = 0;
208         int i, mv, ol, off, p, plen, v;
209 #if defined(_KERNEL)
210 # if SOLARIS
211         mb_t *m = fin->fin_qfm;
212 # else
213         mb_t *m = fin->fin_mp ? *fin->fin_mp : NULL;
214 # endif
215 #endif
216         fr_ip_t *fi = &fin->fin_fi;
217         struct optlist *op;
218         u_char *s, opt;
219         tcphdr_t *tcp;
220
221         fin->fin_rev = 0;
222         fin->fin_dp = NULL;
223         fin->fin_fr = NULL;
224         fin->fin_tcpf = 0;
225         fin->fin_data[0] = 0;
226         fin->fin_data[1] = 0;
227         fin->fin_rule = -1;
228         fin->fin_group = -1;
229         fin->fin_icode = ipl_unreach;
230         v = fin->fin_v;
231         fi->fi_v = v;
232         fin->fin_hlen = hlen;
233         if (v == 4) {
234                 fin->fin_id = ip->ip_id;
235                 fi->fi_tos = ip->ip_tos;
236 #if (OpenBSD >= 200311) && defined(_KERNEL)
237                 ip->ip_off = ntohs(ip->ip_off);
238 #endif
239                 off = (ip->ip_off & IP_OFFMASK);
240                 (*(((u_short *)fi) + 1)) = (*(((u_short *)ip) + 4));
241                 fi->fi_src.i6[1] = 0;
242                 fi->fi_src.i6[2] = 0;
243                 fi->fi_src.i6[3] = 0;
244                 fi->fi_dst.i6[1] = 0;
245                 fi->fi_dst.i6[2] = 0;
246                 fi->fi_dst.i6[3] = 0;
247                 fi->fi_saddr = ip->ip_src.s_addr;
248                 fi->fi_daddr = ip->ip_dst.s_addr;
249                 p = ip->ip_p;
250                 fi->fi_fl = (hlen > sizeof(ip_t)) ? FI_OPTIONS : 0;
251                 if (ip->ip_off & (IP_MF|IP_OFFMASK))
252                         fi->fi_fl |= FI_FRAG;
253 #if (OpenBSD >= 200311) && defined(_KERNEL)
254                 ip->ip_len = ntohs(ip->ip_len);
255 #endif
256                 plen = ip->ip_len;
257                 fin->fin_dlen = plen - hlen;
258         }
259 #ifdef  USE_INET6
260         else if (v == 6) {
261                 ip6_t *ip6 = (ip6_t *)ip;
262
263                 off = 0;
264                 p = ip6->ip6_nxt;
265                 fi->fi_p = p;
266                 fi->fi_ttl = ip6->ip6_hlim;
267                 fi->fi_src.in6 = ip6->ip6_src;
268                 fi->fi_dst.in6 = ip6->ip6_dst;
269                 fin->fin_id = (u_short)(ip6->ip6_flow & 0xffff);
270                 fi->fi_tos = 0;
271                 fi->fi_fl = 0;
272                 plen = ntohs(ip6->ip6_plen);
273                 fin->fin_dlen = plen;
274                 plen += sizeof(*ip6);
275         }
276 #endif
277         else
278                 return -1;
279
280         fin->fin_off = off;
281         fin->fin_plen = plen;
282         tcp = (tcphdr_t *)((char *)ip + hlen);
283         fin->fin_misc = 0;
284         off <<= 3;
285
286         /*
287          * For both ICMPV6 & ICMP, we attempt to pullup the entire packet into
288          * a single buffer for recognised error return packets.  Why?  Because 
289          * the entire data section of the ICMP payload is considered to be of
290          * significance and maybe required in NAT/state processing, so rather
291          * than be careful later, attempt to get it all in one buffeer first.
292          * For TCP we just make sure the _entire_ TCP header is in the first
293          * buffer for convienience.
294          */
295         switch (p)
296         {
297 #ifdef USE_INET6
298         case IPPROTO_ICMPV6 :
299         {
300                 int minicmpsz = sizeof(struct icmp6_hdr);
301                 struct icmp6_hdr *icmp6;
302
303                 if (!(fin->fin_fl & FI_SHORT) && (fin->fin_dlen > 1)) {
304                         fin->fin_data[0] = *(u_short *)tcp;
305
306                         icmp6 = (struct icmp6_hdr *)tcp;
307
308                         switch (icmp6->icmp6_type)
309                         {
310                         case ICMP6_ECHO_REPLY :
311                         case ICMP6_ECHO_REQUEST :
312                                 minicmpsz = ICMP6_MINLEN;
313                                 break;
314                         case ICMP6_DST_UNREACH :
315                         case ICMP6_PACKET_TOO_BIG :
316                         case ICMP6_TIME_EXCEEDED :
317                         case ICMP6_PARAM_PROB :
318 # if defined(KERNEL) && !defined(__sgi)
319                                 if ((m != NULL) && (M_BLEN(m) < plen)) {
320                                         ip = ipf_pullup(m, fin, plen, ip);
321                                         if (ip == NULL)
322                                                 return -1;
323                                         tcp = (tcphdr_t *)((char *)ip + hlen);
324                                 }
325 # endif /* KERNEL && !__sgi */
326                                 minicmpsz = ICMP6ERR_IPICMPHLEN;
327                                 break;
328                         default :
329                                 break;
330                         }
331                 }
332
333                 if (!(fin->fin_dlen >= minicmpsz))
334                         fi->fi_fl |= FI_SHORT;
335
336                 break;
337         }
338 #endif /* USE_INET6 */
339
340         case IPPROTO_ICMP :
341         {
342                 int minicmpsz = sizeof(struct icmp);
343                 icmphdr_t *icmp;
344
345                 if (!off && (fin->fin_dlen > 1) && !(fin->fin_fl & FI_SHORT)) {
346                         fin->fin_data[0] = *(u_short *)tcp;
347
348                         icmp = (icmphdr_t *)tcp;
349
350                         /*
351                          * Minimum ICMP packet is type(1) code(1) cksum(2)
352                          * plus 4 bytes following, totalling 8 bytes.
353                          */
354                         switch (icmp->icmp_type)
355                         {
356                         case ICMP_ECHOREPLY :
357                         case ICMP_ECHO :
358                         /* Router discovery messages - RFC 1256 */
359                         case ICMP_ROUTERADVERT :
360                         case ICMP_ROUTERSOLICIT :
361                                 minicmpsz = ICMP_MINLEN;
362                                 break;
363                         /*
364                          * type(1) + code(1) + cksum(2) + id(2) seq(2) +
365                          * 3*timestamp(3*4)
366                          */
367                         case ICMP_TSTAMP :
368                         case ICMP_TSTAMPREPLY :
369                                 minicmpsz = ICMP_MINLEN + 12;
370                                 break;
371                         /*
372                          * type(1) + code(1) + cksum(2) + id(2) seq(2) +
373                          * mask(4)
374                          */
375                         case ICMP_MASKREQ :
376                         case ICMP_MASKREPLY :
377                                 minicmpsz = ICMP_MINLEN + 4;
378                                 break;
379                         /*
380                          * type(1) + code(1) + cksum(2) + arg(4) ip(20+)
381                          */
382                         case ICMP_UNREACH :
383                         case ICMP_SOURCEQUENCH :
384                         case ICMP_REDIRECT :
385                         case ICMP_TIMXCEED :
386                         case ICMP_PARAMPROB :
387 #if defined(KERNEL) && !defined(__sgi)
388                                 if ((m != NULL) && (M_BLEN(m) < plen)) {
389                                         ip = ipf_pullup(m, fin, plen, ip);
390                                         if (ip == NULL)
391                                                 return -1;
392                                         tcp = (tcphdr_t *)((char *)ip + hlen);
393                                 }
394 #endif /* KERNEL && !__sgi */
395                                 minicmpsz = ICMPERR_MINPKTLEN - sizeof(ip_t);
396                                 break;
397                         default :
398                                 minicmpsz = ICMP_MINLEN;
399                                 break;
400                         }
401                 }
402
403                 if ((!(plen >= hlen + minicmpsz) && !off) ||
404                     (off && off < sizeof(struct icmp)))
405                         fi->fi_fl |= FI_SHORT;
406                 break;
407         }
408
409         case IPPROTO_TCP :
410                 fi->fi_fl |= FI_TCPUDP;
411 #ifdef  USE_INET6
412                 if (v == 6) {
413                         if (plen < sizeof(struct tcphdr))
414                                 fi->fi_fl |= FI_SHORT;
415                 } else
416 #endif
417                 if (v == 4) {
418                         if ((!IPMINLEN(ip, tcphdr) && !off) ||
419                              (off && off < sizeof(struct tcphdr)))
420                                 fi->fi_fl |= FI_SHORT;
421                 }
422
423 #if defined(KERNEL) && !defined(__sgi)
424                 if (!off && !(fi->fi_fl & FI_SHORT)) {
425                         int tlen = hlen + (tcp->th_off << 2);
426
427                         if ((m != NULL) && (M_BLEN(m) < tlen)) {
428                                 ip = ipf_pullup(m, fin, tlen, ip);
429                                 if (ip == NULL)
430                                         return -1;
431                                 tcp = (tcphdr_t *)((char *)ip + hlen);
432                         }
433                 }
434 #endif /* _KERNEL && !_sgi */
435
436                 if (!(fi->fi_fl & FI_SHORT) && !off)
437                         fin->fin_tcpf = tcp->th_flags;
438                 goto getports;
439         case IPPROTO_UDP :
440                 fi->fi_fl |= FI_TCPUDP;
441 #ifdef  USE_INET6
442                 if (v == 6) {
443                         if (plen < sizeof(struct udphdr))
444                                 fi->fi_fl |= FI_SHORT;
445                 } else
446 #endif
447                 if (v == 4) {
448                         if ((!IPMINLEN(ip, udphdr) && !off) ||
449                             (off && off < sizeof(struct udphdr)))
450                                 fi->fi_fl |= FI_SHORT;
451                 }
452 getports:
453                 if (!off && (fin->fin_dlen > 3)) {
454                         fin->fin_data[0] = ntohs(tcp->th_sport);
455                         fin->fin_data[1] = ntohs(tcp->th_dport);
456                 }
457                 break;
458         case IPPROTO_ESP :
459 #ifdef  USE_INET6
460                 if (v == 6) {
461                         if (plen < 8)
462                                 fi->fi_fl |= FI_SHORT;
463                 } else
464 #endif
465                 if (v == 4) {
466                         if (((ip->ip_len < hlen + 8) && !off) ||
467                             (off && off < 8))
468                                 fi->fi_fl |= FI_SHORT;
469                 }
470                 break;
471         default :
472                 break;
473         }
474
475         fin->fin_dp = (char *)tcp;
476
477 #ifdef  USE_INET6
478         if (v == 6) {
479                 fi->fi_optmsk = 0;
480                 fi->fi_secmsk = 0;
481                 fi->fi_auth = 0;
482                 return 0;
483         }
484 #endif
485
486         for (s = (u_char *)(ip + 1), hlen -= (int)sizeof(*ip); hlen > 0; ) {
487                 opt = *s;
488                 if (opt == '\0')
489                         break;
490                 else if (opt == IPOPT_NOP)
491                         ol = 1;
492                 else {
493                         if (hlen < 2)
494                                 break;
495                         ol = (int)*(s + 1);
496                         if (ol < 2 || ol > hlen)
497                                 break;
498                 }
499                 for (i = 9, mv = 4; mv >= 0; ) {
500                         op = ipopts + i;
501                         if (opt == (u_char)op->ol_val) {
502                                 optmsk |= op->ol_bit;
503                                 if (opt == IPOPT_SECURITY) {
504                                         struct optlist *sp;
505                                         u_char  sec;
506                                         int j, m;
507
508                                         sec = *(s + 2); /* classification */
509                                         for (j = 3, m = 2; m >= 0; ) {
510                                                 sp = secopt + j;
511                                                 if (sec == sp->ol_val) {
512                                                         secmsk |= sp->ol_bit;
513                                                         auth = *(s + 3);
514                                                         auth *= 256;
515                                                         auth += *(s + 4);
516                                                         break;
517                                                 }
518                                                 if (sec < sp->ol_val)
519                                                         j -= m--;
520                                                 else
521                                                         j += m--;
522                                         }
523                                 }
524                                 break;
525                         }
526                         if (opt < op->ol_val)
527                                 i -= mv--;
528                         else
529                                 i += mv--;
530                 }
531                 hlen -= ol;
532                 s += ol;
533         }
534         if (auth && !(auth & 0x0100))
535                 auth &= 0xff00;
536         fi->fi_optmsk = optmsk;
537         fi->fi_secmsk = secmsk;
538         fi->fi_auth = auth;
539         return 0;
540 }
541
542
543 /*
544  * check an IP packet for TCP/UDP characteristics such as ports and flags.
545  */
546 int fr_tcpudpchk(ft, fin)
547 frtuc_t *ft;
548 fr_info_t *fin;
549 {
550         u_short po, tup;
551         char i;
552         int err = 1;
553
554         /*
555          * Both ports should *always* be in the first fragment.
556          * So far, I cannot find any cases where they can not be.
557          *
558          * compare destination ports
559          */
560         if ((i = (int)ft->ftu_dcmp)) {
561                 po = ft->ftu_dport;
562                 tup = fin->fin_data[1];
563                 /*
564                  * Do opposite test to that required and
565                  * continue if that succeeds.
566                  */
567                 if (!--i && tup != po) /* EQUAL */
568                         err = 0;
569                 else if (!--i && tup == po) /* NOTEQUAL */
570                         err = 0;
571                 else if (!--i && tup >= po) /* LESSTHAN */
572                         err = 0;
573                 else if (!--i && tup <= po) /* GREATERTHAN */
574                         err = 0;
575                 else if (!--i && tup > po) /* LT or EQ */
576                         err = 0;
577                 else if (!--i && tup < po) /* GT or EQ */
578                         err = 0;
579                 else if (!--i &&           /* Out of range */
580                          (tup >= po && tup <= ft->ftu_dtop))
581                         err = 0;
582                 else if (!--i &&           /* In range */
583                          (tup <= po || tup >= ft->ftu_dtop))
584                         err = 0;
585         }
586         /*
587          * compare source ports
588          */
589         if (err && (i = (int)ft->ftu_scmp)) {
590                 po = ft->ftu_sport;
591                 tup = fin->fin_data[0];
592                 if (!--i && tup != po)
593                         err = 0;
594                 else if (!--i && tup == po)
595                         err = 0;
596                 else if (!--i && tup >= po)
597                         err = 0;
598                 else if (!--i && tup <= po)
599                         err = 0;
600                 else if (!--i && tup > po)
601                         err = 0;
602                 else if (!--i && tup < po)
603                         err = 0;
604                 else if (!--i &&           /* Out of range */
605                          (tup >= po && tup <= ft->ftu_stop))
606                         err = 0;
607                 else if (!--i &&           /* In range */
608                          (tup <= po || tup >= ft->ftu_stop))
609                         err = 0;
610         }
611
612         /*
613          * If we don't have all the TCP/UDP header, then how can we
614          * expect to do any sort of match on it ?  If we were looking for
615          * TCP flags, then NO match.  If not, then match (which should
616          * satisfy the "short" class too).
617          */
618         if (err && (fin->fin_fi.fi_p == IPPROTO_TCP)) {
619                 if (fin->fin_fl & FI_SHORT)
620                         return !(ft->ftu_tcpf | ft->ftu_tcpfm);
621                 /*
622                  * Match the flags ?  If not, abort this match.
623                  */
624                 if (ft->ftu_tcpfm &&
625                     ft->ftu_tcpf != (fin->fin_tcpf & ft->ftu_tcpfm)) {
626                         FR_DEBUG(("f. %#x & %#x != %#x\n", fin->fin_tcpf,
627                                  ft->ftu_tcpfm, ft->ftu_tcpf));
628                         err = 0;
629                 }
630         }
631         return err;
632 }
633
634 /*
635  * Check the input/output list of rules for a match and result.
636  * Could be per interface, but this gets real nasty when you don't have
637  * kernel sauce.
638  */
639 int fr_scanlist(passin, ip, fin, m)
640 u_32_t passin;
641 ip_t *ip;
642 fr_info_t *fin;
643 void *m;
644 {
645         struct frentry *fr;
646         fr_ip_t *fi = &fin->fin_fi;
647         int rulen, portcmp = 0, off, skip = 0, logged = 0;
648         u_32_t pass, passt, passl;
649         frentry_t *frl;
650
651         frl = NULL;
652         pass = passin;
653         fr = fin->fin_fr;
654         fin->fin_fr = NULL;
655         off = fin->fin_off;
656
657         if ((fi->fi_fl & FI_TCPUDP) && (fin->fin_dlen > 3) && !off)
658                 portcmp = 1;
659
660         for (rulen = 0; fr; fr = fr->fr_next, rulen++) {
661                 if (skip) {
662                         FR_VERBOSE(("%d (%#x)\n", skip, fr->fr_flags));
663                         skip--;
664                         continue;
665                 }
666                 /*
667                  * In all checks below, a null (zero) value in the
668                  * filter struture is taken to mean a wildcard.
669                  *
670                  * check that we are working for the right interface
671                  */
672 #ifdef  _KERNEL
673 # if    (BSD >= 199306)
674                 if (fin->fin_out != 0) {
675                         if ((fr->fr_oifa &&
676                              (fr->fr_oifa != ((mb_t *)m)->m_pkthdr.rcvif)))
677                                 continue;
678                 }
679 # endif
680 #else
681                 if (opts & (OPT_VERBOSE|OPT_DEBUG))
682                         printf("\n");
683 #endif
684
685                 FR_VERBOSE(("%c", fr->fr_skip ? 's' :
686                                   (pass & FR_PASS) ? 'p' : 
687                                   (pass & FR_AUTH) ? 'a' :
688                                   (pass & FR_ACCOUNT) ? 'A' :
689                                   (pass & FR_NOMATCH) ? 'n' : 'b'));
690
691                 if (fr->fr_ifa && fr->fr_ifa != fin->fin_ifp)
692                         continue;
693
694                 FR_VERBOSE((":i"));
695                 {
696                          u_32_t *ld, *lm, *lip;
697                         int i;
698
699                         lip = (u_32_t *)fi;
700                         lm = (u_32_t *)&fr->fr_mip;
701                         ld = (u_32_t *)&fr->fr_ip;
702                         i = ((*lip & *lm) != *ld);
703                         FR_DEBUG(("0. %#08x & %#08x != %#08x\n",
704                                    *lip, *lm, *ld));
705                         if (i)
706                                 continue;
707                         /*
708                          * We now know whether the packet version and the
709                          * rule version match, along with protocol, ttl and
710                          * tos.
711                          */
712                         lip++, lm++, ld++;
713                         /*
714                          * Unrolled loops (4 each, for 32 bits).
715                          */
716                         FR_DEBUG(("1a. %#08x & %#08x != %#08x\n",
717                                    *lip, *lm, *ld));
718                         i |= ((*lip++ & *lm++) != *ld++) << 5;
719                         if (fi->fi_v == 6) {
720                                 FR_DEBUG(("1b. %#08x & %#08x != %#08x\n",
721                                            *lip, *lm, *ld));
722                                 i |= ((*lip++ & *lm++) != *ld++) << 5;
723                                 FR_DEBUG(("1c. %#08x & %#08x != %#08x\n",
724                                            *lip, *lm, *ld));
725                                 i |= ((*lip++ & *lm++) != *ld++) << 5;
726                                 FR_DEBUG(("1d. %#08x & %#08x != %#08x\n",
727                                            *lip, *lm, *ld));
728                                 i |= ((*lip++ & *lm++) != *ld++) << 5;
729                         } else {
730                                 lip += 3;
731                                 lm += 3;
732                                 ld += 3;
733                         }
734                         i ^= (fr->fr_flags & FR_NOTSRCIP);
735                         if (i)
736                                 continue;
737                         FR_DEBUG(("2a. %#08x & %#08x != %#08x\n",
738                                    *lip, *lm, *ld));
739                         i |= ((*lip++ & *lm++) != *ld++) << 6;
740                         if (fi->fi_v == 6) {
741                                 FR_DEBUG(("2b. %#08x & %#08x != %#08x\n",
742                                            *lip, *lm, *ld));
743                                 i |= ((*lip++ & *lm++) != *ld++) << 6;
744                                 FR_DEBUG(("2c. %#08x & %#08x != %#08x\n",
745                                            *lip, *lm, *ld));
746                                 i |= ((*lip++ & *lm++) != *ld++) << 6;
747                                 FR_DEBUG(("2d. %#08x & %#08x != %#08x\n",
748                                            *lip, *lm, *ld));
749                                 i |= ((*lip++ & *lm++) != *ld++) << 6;
750                         } else {
751                                 lip += 3;
752                                 lm += 3;
753                                 ld += 3;
754                         }
755                         i ^= (fr->fr_flags & FR_NOTDSTIP);
756                         if (i)
757                                 continue;
758                         FR_DEBUG(("3. %#08x & %#08x != %#08x\n",
759                                    *lip, *lm, *ld));
760                         i |= ((*lip++ & *lm++) != *ld++);
761                         FR_DEBUG(("4. %#08x & %#08x != %#08x\n",
762                                    *lip, *lm, *ld));
763                         i |= ((*lip & *lm) != *ld);
764                         if (i)
765                                 continue;
766                 }
767
768                 /*
769                  * If a fragment, then only the first has what we're looking
770                  * for here...
771                  */
772                 if (!portcmp && (fr->fr_dcmp || fr->fr_scmp || fr->fr_tcpf ||
773                                  fr->fr_tcpfm))
774                         continue;
775                 if (fi->fi_fl & FI_TCPUDP) {
776                         if (!fr_tcpudpchk(&fr->fr_tuc, fin))
777                                 continue;
778                 } else if (fr->fr_icmpm || fr->fr_icmp) {
779                         if (((fi->fi_p != IPPROTO_ICMP) &&
780                             (fi->fi_p != IPPROTO_ICMPV6)) || off ||
781                             (fin->fin_dlen < 2))
782                                 continue;
783                         if ((fin->fin_data[0] & fr->fr_icmpm) != fr->fr_icmp) {
784                                 FR_DEBUG(("i. %#x & %#x != %#x\n",
785                                          fin->fin_data[0], fr->fr_icmpm,
786                                          fr->fr_icmp));
787                                 continue;
788                         }
789                 }
790                 FR_VERBOSE(("*"));
791
792                 if (fr->fr_flags & FR_NOMATCH) {
793                         passt = passl;
794                         passl = passin;
795                         fin->fin_fr = frl;
796                         frl = NULL;
797                         if (fr->fr_flags & FR_QUICK)
798                                 break;
799                         continue;
800                 }
801
802                 passl = passt;
803                 passt = fr->fr_flags;
804                 frl = fin->fin_fr;
805                 fin->fin_fr = fr;
806 #if (BSD >= 199306) && (defined(_KERNEL) || defined(KERNEL))
807                 if (securelevel <= 0)
808 #endif
809                         if ((passt & FR_CALLNOW) && fr->fr_func)
810                                 passt = (*fr->fr_func)(passt, ip, fin);
811 #ifdef  IPFILTER_LOG
812                 /*
813                  * Just log this packet...
814                  */
815                 if ((passt & FR_LOGMASK) == FR_LOG) {
816                         if (!IPLLOG(passt, ip, fin, m)) {
817                                 if (passt & FR_LOGORBLOCK)
818                                         passt |= FR_BLOCK|FR_QUICK;
819                                 ATOMIC_INCL(frstats[fin->fin_out].fr_skip);
820                         }
821                         ATOMIC_INCL(frstats[fin->fin_out].fr_pkl);
822                         logged = 1;
823                 }
824 #endif /* IPFILTER_LOG */
825                 ATOMIC_INCL(fr->fr_hits);
826                 if (passt & FR_ACCOUNT)
827                         fr->fr_bytes += (U_QUAD_T)fin->fin_plen;
828                 else
829                         fin->fin_icode = fr->fr_icode;
830                 fin->fin_rule = rulen;
831                 fin->fin_group = fr->fr_group;
832                 if (fr->fr_grp != NULL) {
833                         fin->fin_fr = fr->fr_grp;
834                         passt = fr_scanlist(passt, ip, fin, m);
835                         if (fin->fin_fr == NULL) {
836                                 fin->fin_rule = rulen;
837                                 fin->fin_group = fr->fr_group;
838                                 fin->fin_fr = fr;
839                         }
840                         if (passt & FR_DONTCACHE)
841                                 logged = 1;
842                 }
843                 if (!(skip = fr->fr_skip) && (passt & FR_LOGMASK) != FR_LOG)
844                         pass = passt;
845                 FR_DEBUG(("pass %#x\n", pass));
846                 if (passt & FR_QUICK)
847                         break;
848         }
849         if (logged)
850                 pass |= FR_DONTCACHE;
851         pass |= (fi->fi_fl << 24);
852         return pass;
853 }
854
855
856 /*
857  * frcheck - filter check
858  * check using source and destination addresses/ports in a packet whether
859  * or not to pass it on or not.
860  */
861 int fr_check(ip, hlen, ifp, out
862 #if defined(_KERNEL) && SOLARIS
863 , qif, mp)
864 qif_t *qif;
865 #else
866 , mp)
867 #endif
868 mb_t **mp;
869 ip_t *ip;
870 int hlen;
871 void *ifp;
872 int out;
873 {
874         /*
875          * The above really sucks, but short of writing a diff
876          */
877         fr_info_t frinfo, *fc;
878         fr_info_t *fin = &frinfo;
879         int changed, error = EHOSTUNREACH, v = ip->ip_v;
880         frentry_t *fr = NULL, *list;
881         u_32_t pass, apass;
882 #if !SOLARIS || !defined(_KERNEL)
883         mb_t *m = *mp;
884 #endif
885
886 #ifdef  _KERNEL
887         int p, len, drop = 0, logit = 0;
888         mb_t *mc = NULL;
889 # if !defined(__SVR4) && !defined(__svr4__)
890    /*
891     * We don't do this section for Solaris because fr_precheck() does a
892     * pullupmsg() instead, effectively achieving the same result as here
893     * so no need to duplicate it.
894     */
895 #  ifdef __sgi
896         char hbuf[128];
897 #  endif
898         int up;
899
900 #  if !defined(NETBSD_PF) && \
901       (defined(__DragonFly__) || (defined(__FreeBSD__) && (__FreeBSD_version < 500011)) || \
902        defined(__OpenBSD__) || defined(_BSDI_VERSION))
903         if (fr_checkp != fr_check && fr_running > 0) {
904                 static int counter = 0;
905
906                 if (counter == 0) {
907                         printf("WARNING: fr_checkp corrupt: value %lx\n",
908                                 (u_long)fr_checkp);
909                         printf("WARNING: fr_checkp should be %lx\n",
910                                 (u_long)fr_check);
911                         printf("WARNING: fixing fr_checkp\n");
912                 }
913                 fr_checkp = fr_check;
914                 counter++;
915                 if (counter == 10000)
916                         counter = 0;
917         }
918 #  endif
919
920 #  ifdef M_CANFASTFWD
921         /*
922          * XXX For now, IP Filter and fast-forwarding of cached flows
923          * XXX are mutually exclusive.  Eventually, IP Filter should
924          * XXX get a "can-fast-forward" filter rule.
925          */
926         m->m_flags &= ~M_CANFASTFWD;
927 #  endif /* M_CANFASTFWD */
928 #  ifdef CSUM_DELAY_DATA
929         /*
930          * disable delayed checksums.
931          */
932         if ((out != 0) && (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA)) {
933                 in_delayed_cksum(m);
934                 m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
935         }
936 #  endif /* CSUM_DELAY_DATA */
937
938 #  ifdef        USE_INET6
939         if (v == 6) {
940                 len = ntohs(((ip6_t*)ip)->ip6_plen);
941                 if (!len)
942                         return -1;      /* potential jumbo gram */
943                 len += sizeof(ip6_t);
944                 p = ((ip6_t *)ip)->ip6_nxt;
945         } else
946 #  endif
947         {
948                 p = ip->ip_p;
949                 len = ip->ip_len;
950         }
951
952         fin->fin_mp = mp;
953         fin->fin_out = out;
954
955         if ((p == IPPROTO_TCP || p == IPPROTO_UDP ||
956             (v == 4 && p == IPPROTO_ICMP)
957 #  ifdef USE_INET6
958             || (v == 6 && p == IPPROTO_ICMPV6)
959 #  endif
960            )) {
961                 int plen = 0;
962
963                 if ((v == 6) || (ip->ip_off & IP_OFFMASK) == 0)
964                         switch(p)
965                         {
966                         case IPPROTO_TCP:
967                                 plen = sizeof(tcphdr_t);
968                                 break;
969                         case IPPROTO_UDP:
970                                 plen = sizeof(udphdr_t);
971                                 break;
972                         /* 96 - enough for complete ICMP error IP header */
973                         case IPPROTO_ICMP:
974                                 plen = ICMPERR_MAXPKTLEN - sizeof(ip_t);
975                                 break;
976                         case IPPROTO_ESP:
977                                 plen = 8;
978                                 break;
979 #  ifdef USE_INET6
980                         case IPPROTO_ICMPV6 :
981                                 /*
982                                  * XXX does not take intermediate header
983                                  * into account
984                                  */
985                                 plen = ICMP6ERR_MINPKTLEN + 8 - sizeof(ip6_t);
986                                 break;
987 #  endif
988                         }
989                 if ((plen > 0) && (len < hlen + plen))
990                         fin->fin_fl |= FI_SHORT;
991                 up = MIN(hlen + plen, len);
992
993                 if (up > m->m_len) {
994 #  ifdef __sgi
995         /* Under IRIX, avoid m_pullup as it makes ping <hostname> panic */
996                         if ((up > sizeof(hbuf)) || (m_length(m) < up)) {
997                                 ATOMIC_INCL(frstats[out].fr_pull[1]);
998                                 return -1;
999                         }
1000                         m_copydata(m, 0, up, hbuf);
1001                         ATOMIC_INCL(frstats[out].fr_pull[0]);
1002                         ip = (ip_t *)hbuf;
1003 #  else /* __ sgi */
1004 #   ifndef linux
1005                         /*
1006                          * Having determined that we need to pullup some data,
1007                          * try to bring as much of the packet up into a single
1008                          * buffer with the first pullup.  This hopefully means
1009                          * less need for doing futher pullups.  Not needed for
1010                          * Solaris because fr_precheck() does it anyway.
1011                          *
1012                          * The main potential for trouble here is if MLEN/MHLEN
1013                          * become quite small, lets say < 64 bytes...but if
1014                          * that did happen, BSD networking as a whole would be
1015                          * slow/inefficient.
1016                          */
1017 #    ifdef MHLEN
1018                         /*
1019                          * Assume that M_PKTHDR is set and just work with what
1020                          * is left rather than check..  Should not make any
1021                          * real difference, anyway.
1022                          */
1023                         if ((MHLEN > up) && (len > up))
1024                                 up = MIN(len, MHLEN);
1025 #    else
1026                         if ((MLEN > up) && (len > up))
1027                                 up = MIN(len, MLEN);
1028 #    endif
1029                         ip = ipf_pullup(m, fin, up, ip);
1030                         if (ip == NULL)
1031                                 return -1;
1032                         m = *mp;
1033 #   endif /* !linux */
1034 #  endif /* __sgi */
1035                 } else
1036                         up = 0;
1037         } else
1038                 up = 0;
1039 # endif /* !defined(__SVR4) && !defined(__svr4__) */
1040 # if SOLARIS
1041         mb_t *m = qif->qf_m;
1042
1043         if ((u_int)ip & 0x3)
1044                 return 2;
1045         fin->fin_mp = mp;
1046         fin->fin_out = out;
1047         fin->fin_qfm = m;
1048         fin->fin_qif = qif;
1049 # endif
1050 #else
1051         fin->fin_mp = mp;
1052         fin->fin_out = out;
1053 #endif /* _KERNEL */
1054         
1055         changed = 0;
1056         fin->fin_v = v;
1057         fin->fin_ifp = ifp;
1058         if (fr_makefrip(hlen, ip, fin) == -1)
1059                 return -1;
1060
1061 #ifdef _KERNEL
1062 # ifdef USE_INET6
1063         if (v == 6) {
1064                 ATOMIC_INCL(frstats[0].fr_ipv6[out]);
1065                 if (((ip6_t *)ip)->ip6_hlim < fr_minttl) {
1066                         ATOMIC_INCL(frstats[0].fr_badttl);
1067                         if (fr_minttllog & 1)
1068                                 logit = -3;
1069                         if (fr_minttllog & 2)
1070                                 drop = 1;
1071                 }
1072         } else
1073 # endif
1074         if (!out) {
1075                 if (fr_chksrc && !fr_verifysrc(ip->ip_src, ifp)) {
1076                         ATOMIC_INCL(frstats[0].fr_badsrc);
1077                         if (fr_chksrc & 1)
1078                                 drop = 1;
1079                         if (fr_chksrc & 2)
1080                                 logit = -2;
1081                 } else if (ip->ip_ttl < fr_minttl) {
1082                         ATOMIC_INCL(frstats[0].fr_badttl);
1083                         if (fr_minttllog & 1)
1084                                 logit = -3;
1085                         if (fr_minttllog & 2)
1086                                 drop = 1;
1087                 }
1088         }
1089         if (drop) {
1090 # ifdef IPFILTER_LOG
1091                 if (logit) {
1092                         fin->fin_group = logit;
1093                         pass = FR_INQUE|FR_NOMATCH|FR_LOGB;
1094                         (void) IPLLOG(pass, ip, fin, m);
1095                 }
1096 # endif
1097 # if !SOLARIS
1098                 m_freem(m);
1099 # endif
1100                 return error;
1101         }
1102 #endif
1103         pass = fr_pass;
1104         if (fin->fin_fl & FI_SHORT) {
1105                 ATOMIC_INCL(frstats[out].fr_short);
1106         }
1107
1108         READ_ENTER(&ipf_mutex);
1109
1110         /*
1111          * Check auth now.  This, combined with the check below to see if apass
1112          * is 0 is to ensure that we don't count the packet twice, which can
1113          * otherwise occur when we reprocess it.  As it is, we only count it
1114          * after it has no auth. table matchup.  This also stops NAT from
1115          * occuring until after the packet has been auth'd.
1116          */
1117         apass = fr_checkauth(ip, fin);
1118
1119         if (!out) {
1120 #ifdef  USE_INET6
1121                 if (v == 6)
1122                         list = ipacct6[0][fr_active];
1123                 else
1124 #endif
1125                         list = ipacct[0][fr_active];
1126                 changed = ip_natin(ip, fin);
1127                 if (!apass && (fin->fin_fr = list) &&
1128                     (fr_scanlist(FR_NOMATCH, ip, fin, m) & FR_ACCOUNT)) {
1129                         ATOMIC_INCL(frstats[0].fr_acct);
1130                 }
1131         }
1132
1133         if (!apass) {
1134                 if ((fin->fin_fl & FI_FRAG) == FI_FRAG)
1135                         fr = ipfr_knownfrag(ip, fin);
1136                 if (!fr && !(fin->fin_fl & FI_SHORT))
1137                         fr = fr_checkstate(ip, fin);
1138                 if (fr != NULL)
1139                         pass = fr->fr_flags;
1140                 if (fr && (pass & FR_LOGFIRST))
1141                         pass &= ~(FR_LOGFIRST|FR_LOG);
1142         }
1143
1144         if (apass || !fr) {
1145                 /*
1146                  * If a packet is found in the auth table, then skip checking
1147                  * the access lists for permission but we do need to consider
1148                  * the result as if it were from the ACL's.
1149                  */
1150                 if (!apass) {
1151                         fc = frcache + out;
1152                         if (!bcmp((char *)fin, (char *)fc, FI_CSIZE)) {
1153                                 /*
1154                                  * copy cached data so we can unlock the mutex
1155                                  * earlier.
1156                                  */
1157                                 bcopy((char *)fc, (char *)fin, FI_COPYSIZE);
1158                                 ATOMIC_INCL(frstats[out].fr_chit);
1159                                 if ((fr = fin->fin_fr)) {
1160                                         ATOMIC_INCL(fr->fr_hits);
1161                                         pass = fr->fr_flags;
1162                                 }
1163                         } else {
1164 #ifdef  USE_INET6
1165                                 if (v == 6)
1166                                         list = ipfilter6[out][fr_active];
1167                                 else
1168 #endif
1169                                         list = ipfilter[out][fr_active];
1170                                 if ((fin->fin_fr = list))
1171                                         pass = fr_scanlist(fr_pass, ip, fin, m);
1172                                 if (!(pass & (FR_KEEPSTATE|FR_DONTCACHE)))
1173                                         bcopy((char *)fin, (char *)fc,
1174                                               FI_COPYSIZE);
1175                                 if (pass & FR_NOMATCH) {
1176                                         ATOMIC_INCL(frstats[out].fr_nom);
1177                                         fin->fin_fr = NULL;
1178                                 }
1179                         }
1180                 } else
1181                         pass = apass;
1182                 fr = fin->fin_fr;
1183
1184                 /*
1185                  * If we fail to add a packet to the authorization queue,
1186                  * then we drop the packet later.  However, if it was added
1187                  * then pretend we've dropped it already.
1188                  */
1189                 if ((pass & FR_AUTH)) {
1190                         if (fr_newauth((mb_t *)m, fin, ip) != 0) {
1191                                 m = *mp = NULL;
1192                                 error = 0;
1193                         } else
1194                                 error = ENOSPC;
1195                 }
1196
1197                 if (pass & FR_PREAUTH) {
1198                         READ_ENTER(&ipf_auth);
1199                         if ((fin->fin_fr = ipauth) &&
1200                             (pass = fr_scanlist(0, ip, fin, m))) {
1201                                 ATOMIC_INCL(fr_authstats.fas_hits);
1202                         } else {
1203                                 ATOMIC_INCL(fr_authstats.fas_miss);
1204                         }
1205                         RWLOCK_EXIT(&ipf_auth);
1206                 }
1207
1208                 fin->fin_fr = fr;
1209                 if ((pass & (FR_KEEPFRAG|FR_KEEPSTATE)) == FR_KEEPFRAG) {
1210                         if (fin->fin_fl & FI_FRAG) {
1211                                 if (ipfr_newfrag(ip, fin) == -1) {
1212                                         ATOMIC_INCL(frstats[out].fr_bnfr);
1213                                 } else {
1214                                         ATOMIC_INCL(frstats[out].fr_nfr);
1215                                 }
1216                         } else {
1217                                 ATOMIC_INCL(frstats[out].fr_cfr);
1218                         }
1219                 }
1220                 if (pass & FR_KEEPSTATE) {
1221                         if (fr_addstate(ip, fin, NULL, 0) == NULL) {
1222                                 ATOMIC_INCL(frstats[out].fr_bads);
1223                                 if (pass & FR_PASS) {
1224                                         pass &= ~FR_PASS;
1225                                         pass |= FR_BLOCK;
1226                                 }
1227                         } else {
1228                                 ATOMIC_INCL(frstats[out].fr_ads);
1229                         }
1230                 }
1231         } else if (fr != NULL) {
1232                 pass = fr->fr_flags;
1233                 if (pass & FR_LOGFIRST)
1234                         pass &= ~(FR_LOGFIRST|FR_LOG);
1235         }
1236
1237 #if (BSD >= 199306) && (defined(_KERNEL) || defined(KERNEL))
1238         if (securelevel <= 0)
1239 #endif
1240                 if (fr && fr->fr_func && !(pass & FR_CALLNOW))
1241                         pass = (*fr->fr_func)(pass, ip, fin);
1242
1243         /*
1244          * Only count/translate packets which will be passed on, out the
1245          * interface.
1246          */
1247         if (out && (pass & FR_PASS)) {
1248 #ifdef  USE_INET6
1249                 if (v == 6)
1250                         list = ipacct6[1][fr_active];
1251                 else
1252 #endif
1253                         list = ipacct[1][fr_active];
1254                 if (list != NULL) {
1255                         u_32_t sg, sr;
1256
1257                         fin->fin_fr = list;
1258                         sg = fin->fin_group;
1259                         sr = fin->fin_rule;
1260                         if (fr_scanlist(FR_NOMATCH, ip, fin, m) & FR_ACCOUNT) {
1261                                 ATOMIC_INCL(frstats[1].fr_acct);
1262                         }
1263                         fin->fin_group = sg;
1264                         fin->fin_rule = sr;
1265                         fin->fin_fr = fr;
1266                 }
1267                 changed = ip_natout(ip, fin);
1268         } else
1269                 fin->fin_fr = fr;
1270         RWLOCK_EXIT(&ipf_mutex);
1271
1272 #ifdef  IPFILTER_LOG
1273         if ((fr_flags & FF_LOGGING) || (pass & FR_LOGMASK)) {
1274                 if ((fr_flags & FF_LOGNOMATCH) && (pass & FR_NOMATCH)) {
1275                         pass |= FF_LOGNOMATCH;
1276                         ATOMIC_INCL(frstats[out].fr_npkl);
1277                         goto logit;
1278                 } else if (((pass & FR_LOGMASK) == FR_LOGP) ||
1279                     ((pass & FR_PASS) && (fr_flags & FF_LOGPASS))) {
1280                         if ((pass & FR_LOGMASK) != FR_LOGP)
1281                                 pass |= FF_LOGPASS;
1282                         ATOMIC_INCL(frstats[out].fr_ppkl);
1283                         goto logit;
1284                 } else if (((pass & FR_LOGMASK) == FR_LOGB) ||
1285                            ((pass & FR_BLOCK) && (fr_flags & FF_LOGBLOCK))) {
1286                         if ((pass & FR_LOGMASK) != FR_LOGB)
1287                                 pass |= FF_LOGBLOCK;
1288                         ATOMIC_INCL(frstats[out].fr_bpkl);
1289 logit:
1290                         if (!IPLLOG(pass, ip, fin, m)) {
1291                                 ATOMIC_INCL(frstats[out].fr_skip);
1292                                 if ((pass & (FR_PASS|FR_LOGORBLOCK)) ==
1293                                     (FR_PASS|FR_LOGORBLOCK))
1294                                         pass ^= FR_PASS|FR_BLOCK;
1295                         }
1296                 }
1297         }
1298 #endif /* IPFILTER_LOG */
1299
1300 #ifdef  _KERNEL
1301         /*
1302          * Only allow FR_DUP to work if a rule matched - it makes no sense to
1303          * set FR_DUP as a "default" as there are no instructions about where
1304          * to send the packet.
1305          */
1306         if (fr && (pass & FR_DUP))
1307 # if    SOLARIS
1308                 mc = dupmsg(m);
1309 # else
1310 #  if defined(__OpenBSD__) && (OpenBSD >= 199905)
1311                 mc = m_copym2(m, 0, M_COPYALL, M_DONTWAIT);
1312 #  else
1313                 mc = m_copy(m, 0, M_COPYALL);
1314 #  endif
1315 # endif
1316 #endif
1317         if (pass & FR_PASS) {
1318                 ATOMIC_INCL(frstats[out].fr_pass);
1319         } else if (pass & FR_BLOCK) {
1320                 ATOMIC_INCL(frstats[out].fr_block);
1321                 /*
1322                  * Should we return an ICMP packet to indicate error
1323                  * status passing through the packet filter ?
1324                  * WARNING: ICMP error packets AND TCP RST packets should
1325                  * ONLY be sent in repsonse to incoming packets.  Sending them
1326                  * in response to outbound packets can result in a panic on
1327                  * some operating systems.
1328                  */
1329                 if (!out) {
1330                         if (changed == -1)
1331                                 /*
1332                                  * If a packet results in a NAT error, do not
1333                                  * send a reset or ICMP error as it may disrupt
1334                                  * an existing flow.  This is the proxy saying
1335                                  * the content is bad so just drop the packet
1336                                  * silently.
1337                                  */
1338                                 ;
1339                         else if (pass & FR_RETICMP) {
1340                                 int dst;
1341
1342                                 if ((pass & FR_RETMASK) == FR_FAKEICMP)
1343                                         dst = 1;
1344                                 else
1345                                         dst = 0;
1346                                 send_icmp_err(ip, ICMP_UNREACH, fin, dst);
1347                                 ATOMIC_INCL(frstats[0].fr_ret);
1348                         } else if (((pass & FR_RETMASK) == FR_RETRST) &&
1349                                    !(fin->fin_fl & FI_SHORT)) {
1350                                 if (send_reset(ip, fin) == 0) {
1351                                         ATOMIC_INCL(frstats[1].fr_ret);
1352                                 }
1353                         }
1354                 } else {
1355                         if (pass & FR_RETRST)
1356                                 error = ECONNRESET;
1357                 }
1358         }
1359
1360         /*
1361          * If we didn't drop off the bottom of the list of rules (and thus
1362          * the 'current' rule fr is not NULL), then we may have some extra
1363          * instructions about what to do with a packet.
1364          * Once we're finished return to our caller, freeing the packet if
1365          * we are dropping it (* BSD ONLY *).
1366          */
1367         if ((changed == -1) && (pass & FR_PASS)) {
1368                 pass &= ~FR_PASS;
1369                 pass |= FR_BLOCK;
1370         }
1371 #if defined(_KERNEL)
1372 # if !SOLARIS
1373 #  if !defined(linux)
1374         if (fr) {
1375                 frdest_t *fdp = &fr->fr_tif;
1376
1377                 if (((pass & FR_FASTROUTE) && !out) ||
1378                     (fdp->fd_ifp && fdp->fd_ifp != (struct ifnet *)-1)) {
1379                         (void) ipfr_fastroute(m, mp, fin, fdp);
1380                         m = *mp;
1381                 }
1382
1383                 if (mc != NULL)
1384                         (void) ipfr_fastroute(mc, &mc, fin, &fr->fr_dif);
1385         }
1386
1387         if (!(pass & FR_PASS) && m) {
1388                 m_freem(m);
1389                 m = *mp = NULL;
1390         }
1391 #   ifdef __sgi
1392         else if (changed && up && m)
1393                 m_copyback(m, 0, up, hbuf);
1394 #   endif
1395 #  endif /* !linux */
1396 # else /* !SOLARIS */
1397         if (fr) {
1398                 frdest_t *fdp = &fr->fr_tif;
1399
1400                 if (((pass & FR_FASTROUTE) && !out) ||
1401                     (fdp->fd_ifp && fdp->fd_ifp != (struct ifnet *)-1))
1402                         (void) ipfr_fastroute(ip, m, mp, fin, fdp);
1403
1404                 if (mc != NULL)
1405                         (void) ipfr_fastroute(ip, mc, &mc, fin, &fr->fr_dif);
1406         }
1407 # endif /* !SOLARIS */
1408 #if (OpenBSD >= 200311) && defined(_KERNEL)
1409         if (pass & FR_PASS) {
1410                 ip->ip_len = htons(ip->ip_len);
1411                 ip->ip_off = htons(ip->ip_off);
1412         }
1413 #endif
1414         return (pass & FR_PASS) ? 0 : error;
1415 #else /* _KERNEL */
1416         if (pass & FR_NOMATCH)
1417                 return 1;
1418         if (pass & FR_PASS)
1419                 return 0;
1420         if (pass & FR_AUTH)
1421                 return -2;
1422         if ((pass & FR_RETMASK) == FR_RETRST)
1423                 return -3;
1424         if ((pass & FR_RETMASK) == FR_RETICMP)
1425                 return -4;
1426         if ((pass & FR_RETMASK) == FR_FAKEICMP)
1427                 return -5;
1428         return -1;
1429 #endif /* _KERNEL */
1430 }
1431
1432
1433 /*
1434  * ipf_cksum
1435  * addr should be 16bit aligned and len is in bytes.
1436  * length is in bytes
1437  */
1438 u_short ipf_cksum(addr, len)
1439 u_short *addr;
1440 int len;
1441 {
1442         u_32_t sum = 0;
1443
1444         for (sum = 0; len > 1; len -= 2)
1445                 sum += *addr++;
1446
1447         /* mop up an odd byte, if necessary */
1448         if (len == 1)
1449                 sum += *(u_char *)addr;
1450
1451         /*
1452          * add back carry outs from top 16 bits to low 16 bits
1453          */
1454         sum = (sum >> 16) + (sum & 0xffff);     /* add hi 16 to low 16 */
1455         sum += (sum >> 16);                     /* add carry */
1456         return (u_short)(~sum);
1457 }
1458
1459
1460 /*
1461  * NB: This function assumes we've pullup'd enough for all of the IP header
1462  * and the TCP header.  We also assume that data blocks aren't allocated in
1463  * odd sizes.
1464  */
1465 u_short fr_tcpsum(m, ip, tcp)
1466 mb_t *m;
1467 ip_t *ip;
1468 tcphdr_t *tcp;
1469 {
1470         u_short *sp, slen, ts;
1471         u_int sum, sum2;
1472         int hlen;
1473
1474         /*
1475          * Add up IP Header portion
1476          */
1477         hlen = ip->ip_hl << 2;
1478         slen = ip->ip_len - hlen;
1479         sum = htons((u_short)ip->ip_p);
1480         sum += htons(slen);
1481         sp = (u_short *)&ip->ip_src;
1482         sum += *sp++;   /* ip_src */
1483         sum += *sp++;
1484         sum += *sp++;   /* ip_dst */
1485         sum += *sp++;
1486         ts = tcp->th_sum;
1487         tcp->th_sum = 0;
1488 #ifdef  KERNEL
1489 # if SOLARIS
1490         sum2 = ip_cksum(m, hlen, sum);  /* hlen == offset */
1491         sum2 = (sum2 & 0xffff) + (sum2 >> 16);
1492         sum2 = ~sum2 & 0xffff;
1493 # else /* SOLARIS */
1494 #  if defined(BSD) || defined(sun)
1495 #   if BSD >= 199306
1496         m->m_data += hlen;
1497 #   else
1498         m->m_off += hlen;
1499 #   endif
1500         m->m_len -= hlen;
1501         sum2 = in_cksum(m, slen);
1502         m->m_len += hlen;
1503 #   if BSD >= 199306
1504         m->m_data -= hlen;
1505 #   else
1506         m->m_off -= hlen;
1507 #   endif
1508         /*
1509          * Both sum and sum2 are partial sums, so combine them together.
1510          */
1511         sum += ~sum2 & 0xffff;
1512         while (sum > 0xffff)
1513                 sum = (sum & 0xffff) + (sum >> 16);
1514         sum2 = ~sum & 0xffff;
1515 #  else /* defined(BSD) || defined(sun) */
1516 {
1517         union {
1518                 u_char  c[2];
1519                 u_short s;
1520         } bytes;
1521         u_short len = ip->ip_len;
1522 # if defined(__sgi)
1523         int add;
1524 # endif
1525
1526         /*
1527          * Add up IP Header portion
1528          */
1529         sp = (u_short *)&ip->ip_src;
1530         len -= (ip->ip_hl << 2);
1531         sum = ntohs(IPPROTO_TCP);
1532         sum += htons(len);
1533         sum += *sp++;   /* ip_src */
1534         sum += *sp++;
1535         sum += *sp++;   /* ip_dst */
1536         sum += *sp++;
1537         if (sp != (u_short *)tcp)
1538                 sp = (u_short *)tcp;
1539         sum += *sp++;   /* sport */
1540         sum += *sp++;   /* dport */
1541         sum += *sp++;   /* seq */
1542         sum += *sp++;
1543         sum += *sp++;   /* ack */
1544         sum += *sp++;
1545         sum += *sp++;   /* off */
1546         sum += *sp++;   /* win */
1547         sum += *sp++;   /* Skip over checksum */
1548         sum += *sp++;   /* urp */
1549
1550 # ifdef __sgi
1551         /*
1552          * In case we had to copy the IP & TCP header out of mbufs,
1553          * skip over the mbuf bits which are the header
1554          */
1555         if ((caddr_t)ip != mtod(m, caddr_t)) {
1556                 hlen = (caddr_t)sp - (caddr_t)ip;
1557                 while (hlen) {
1558                         add = MIN(hlen, m->m_len);
1559                         sp = (u_short *)(mtod(m, caddr_t) + add);
1560                         hlen -= add;
1561                         if (add == m->m_len) {
1562                                 m = m->m_next;
1563                                 if (!hlen) {
1564                                         if (!m)
1565                                                 break;
1566                                         sp = mtod(m, u_short *);
1567                                 }
1568                                 PANIC((!m),("fr_tcpsum(1): not enough data"));
1569                         }
1570                 }
1571         }
1572 # endif
1573
1574         if (!(len -= sizeof(*tcp)))
1575                 goto nodata;
1576         while (len > 1) {
1577                 if (((caddr_t)sp - mtod(m, caddr_t)) >= m->m_len) {
1578                         m = m->m_next;
1579                         PANIC((!m),("fr_tcpsum(2): not enough data"));
1580                         sp = mtod(m, u_short *);
1581                 }
1582                 if (((caddr_t)(sp + 1) - mtod(m, caddr_t)) > m->m_len) {
1583                         bytes.c[0] = *(u_char *)sp;
1584                         m = m->m_next;
1585                         PANIC((!m),("fr_tcpsum(3): not enough data"));
1586                         sp = mtod(m, u_short *);
1587                         bytes.c[1] = *(u_char *)sp;
1588                         sum += bytes.s;
1589                         sp = (u_short *)((u_char *)sp + 1);
1590                 }
1591                 if ((u_long)sp & 1) {
1592                         bcopy((char *)sp++, (char *)&bytes.s, sizeof(bytes.s));
1593                         sum += bytes.s;
1594                 } else
1595                         sum += *sp++;
1596                 len -= 2;
1597         }
1598         if (len)
1599                 sum += ntohs(*(u_char *)sp << 8);
1600 nodata:
1601         while (sum > 0xffff)
1602                 sum = (sum & 0xffff) + (sum >> 16);
1603         sum2 = (u_short)(~sum & 0xffff);
1604 }
1605 #  endif /*  defined(BSD) || defined(sun) */
1606 # endif /* SOLARIS */
1607 #else /* KERNEL */
1608         for (; slen > 1; slen -= 2)
1609                 sum += *sp++;
1610         if (slen)
1611                 sum += ntohs(*(u_char *)sp << 8);
1612         while (sum > 0xffff)
1613                 sum = (sum & 0xffff) + (sum >> 16);
1614         sum2 = (u_short)(~sum & 0xffff);
1615 #endif /* KERNEL */
1616         tcp->th_sum = ts;
1617         return sum2;
1618 }
1619
1620
1621 #if defined(_KERNEL) && ( ((BSD < 199306) && !SOLARIS) || defined(__sgi) )
1622 /*
1623  * Copyright (c) 1982, 1986, 1988, 1991, 1993
1624  *      The Regents of the University of California.  All rights reserved.
1625  *
1626  * Redistribution and use in source and binary forms, with or without
1627  * modification, are permitted provided that the following conditions
1628  * are met:
1629  * 1. Redistributions of source code must retain the above copyright
1630  *    notice, this list of conditions and the following disclaimer.
1631  * 2. Redistributions in binary form must reproduce the above copyright
1632  *    notice, this list of conditions and the following disclaimer in the
1633  *    documentation and/or other materials provided with the distribution.
1634  * 3. All advertising materials mentioning features or use of this software
1635  *    must display the following acknowledgement:
1636  *      This product includes software developed by the University of
1637  *      California, Berkeley and its contributors.
1638  * 4. Neither the name of the University nor the names of its contributors
1639  *    may be used to endorse or promote products derived from this software
1640  *    without specific prior written permission.
1641  *
1642  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
1643  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
1644  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
1645  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
1646  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
1647  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
1648  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
1649  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
1650  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
1651  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
1652  * SUCH DAMAGE.
1653  *
1654  *      @(#)uipc_mbuf.c 8.2 (Berkeley) 1/4/94
1655  * $Id: fil.c,v 2.35.2.82 2004/06/20 10:27:47 darrenr Exp $
1656  */
1657 /*
1658  * Copy data from an mbuf chain starting "off" bytes from the beginning,
1659  * continuing for "len" bytes, into the indicated buffer.
1660  */
1661 void
1662 m_copydata(m, off, len, cp)
1663         mb_t *m;
1664         int off;
1665         int len;
1666         caddr_t cp;
1667 {
1668         unsigned count;
1669
1670         if (off < 0 || len < 0)
1671                 panic("m_copydata");
1672         while (off > 0) {
1673                 if (m == 0)
1674                         panic("m_copydata");
1675                 if (off < m->m_len)
1676                         break;
1677                 off -= m->m_len;
1678                 m = m->m_next;
1679         }
1680         while (len > 0) {
1681                 if (m == 0)
1682                         panic("m_copydata");
1683                 count = MIN(m->m_len - off, len);
1684                 bcopy(mtod(m, caddr_t) + off, cp, count);
1685                 len -= count;
1686                 cp += count;
1687                 off = 0;
1688                 m = m->m_next;
1689         }
1690 }
1691
1692
1693 # ifndef linux
1694 /*
1695  * Copy data from a buffer back into the indicated mbuf chain,
1696  * starting "off" bytes from the beginning, extending the mbuf
1697  * chain if necessary.
1698  */
1699 void
1700 m_copyback(m0, off, len, cp)
1701         struct  mbuf *m0;
1702         int off;
1703         int len;
1704         caddr_t cp;
1705 {
1706         int mlen;
1707         struct mbuf *m = m0, *n;
1708         int totlen = 0;
1709
1710         if (m0 == 0)
1711                 return;
1712         while (off > (mlen = m->m_len)) {
1713                 off -= mlen;
1714                 totlen += mlen;
1715                 if (m->m_next == 0) {
1716 #ifdef __DragonFly__
1717                         n = m_getclr(MB_DONTWAIT, m->m_type);
1718 #else
1719                         n = m_getclr(M_DONTWAIT, m->m_type);
1720 #endif
1721                         if (n == 0)
1722                                 goto out;
1723                         n->m_len = min(MLEN, len + off);
1724                         m->m_next = n;
1725                 }
1726                 m = m->m_next;
1727         }
1728         while (len > 0) {
1729                 mlen = min (m->m_len - off, len);
1730                 bcopy(cp, off + mtod(m, caddr_t), (unsigned)mlen);
1731                 cp += mlen;
1732                 len -= mlen;
1733                 mlen += off;
1734                 off = 0;
1735                 totlen += mlen;
1736                 if (len == 0)
1737                         break;
1738                 if (m->m_next == 0) {
1739 #ifdef __DragonFly__
1740                         n = m_get(MB_DONTWAIT, m->m_type);
1741 #else
1742                         n = m_get(M_DONTWAIT, m->m_type);
1743 #endif
1744                         if (n == 0)
1745                                 break;
1746                         n->m_len = min(MLEN, len);
1747                         m->m_next = n;
1748                 }
1749                 m = m->m_next;
1750         }
1751 out:
1752 #if 0
1753         if (((m = m0)->m_flags & M_PKTHDR) && (m->m_pkthdr.len < totlen))
1754                 m->m_pkthdr.len = totlen;
1755 #endif
1756         return;
1757 }
1758 # endif /* linux */
1759 #endif /* (_KERNEL) && ( ((BSD < 199306) && !SOLARIS) || __sgi) */
1760
1761
1762 frgroup_t *fr_findgroup(num, flags, which, set, fgpp)
1763 u_32_t num, flags;
1764 minor_t which;
1765 int set;
1766 frgroup_t ***fgpp;
1767 {
1768         frgroup_t *fg, **fgp;
1769
1770         if (which == IPL_LOGAUTH)
1771                 fgp = &ipfgroups[2][set];
1772         else if (flags & FR_ACCOUNT)
1773                 fgp = &ipfgroups[1][set];
1774         else if (flags & (FR_OUTQUE|FR_INQUE))
1775                 fgp = &ipfgroups[0][set];
1776         else
1777                 return NULL;
1778
1779         while ((fg = *fgp))
1780                 if (fg->fg_num == num)
1781                         break;
1782                 else
1783                         fgp = &fg->fg_next;
1784         if (fgpp)
1785                 *fgpp = fgp;
1786         return fg;
1787 }
1788
1789
1790 frgroup_t *fr_addgroup(num, fp, which, set)
1791 u_32_t num;
1792 frentry_t *fp;
1793 minor_t which;
1794 int set;
1795 {
1796         frgroup_t *fg, **fgp;
1797
1798         if ((fg = fr_findgroup(num, fp->fr_flags, which, set, &fgp)))
1799                 return fg;
1800
1801         KMALLOC(fg, frgroup_t *);
1802         if (fg) {
1803                 fg->fg_num = num;
1804                 fg->fg_next = *fgp;
1805                 fg->fg_head = fp;
1806                 fg->fg_start = &fp->fr_grp;
1807                 *fgp = fg;
1808         }
1809         return fg;
1810 }
1811
1812
1813 void fr_delgroup(num, flags, which, set)
1814 u_32_t num, flags;
1815 minor_t which;
1816 int set;
1817 {
1818         frgroup_t *fg, **fgp;
1819  
1820         if (!(fg = fr_findgroup(num, flags, which, set, &fgp)))
1821                 return;
1822  
1823         *fgp = fg->fg_next;
1824         KFREE(fg);
1825 }
1826
1827
1828
1829 /*
1830  * recursively flush rules from the list, descending groups as they are
1831  * encountered.  if a rule is the head of a group and it has lost all its
1832  * group members, then also delete the group reference.
1833  */
1834 static int frflushlist(set, unit, nfreedp, listp)
1835 int set;
1836 minor_t unit;
1837 int *nfreedp;
1838 frentry_t **listp;
1839 {
1840         int freed = 0, i;
1841         frentry_t *fp;
1842
1843         while ((fp = *listp)) {
1844                 *listp = fp->fr_next;
1845                 if (fp->fr_grp) {
1846                         i = frflushlist(set, unit, nfreedp, &fp->fr_grp);
1847                         MUTEX_ENTER(&ipf_rw);
1848                         fp->fr_ref -= i;
1849                         MUTEX_EXIT(&ipf_rw);
1850                 }
1851
1852                 ATOMIC_DEC32(fp->fr_ref);
1853                 if (fp->fr_grhead) {
1854                         fr_delgroup(fp->fr_grhead, fp->fr_flags, 
1855                                     unit, set);
1856                         fp->fr_grhead = 0;
1857                 }
1858                 if (fp->fr_ref == 0) {
1859                         KFREE(fp);
1860                         freed++;
1861                 } else
1862                         fp->fr_next = NULL;
1863         }
1864         *nfreedp += freed;
1865         return freed;
1866 }
1867
1868
1869 int frflush(unit, proto, flags)
1870 minor_t unit;
1871 int proto, flags;
1872 {
1873         int flushed = 0, set;
1874
1875         if (unit != IPL_LOGIPF)
1876                 return 0;
1877         WRITE_ENTER(&ipf_mutex);
1878         bzero((char *)frcache, sizeof(frcache[0]) * 2);
1879
1880         set = fr_active;
1881         if (flags & FR_INACTIVE)
1882                 set = 1 - set;
1883
1884         if (flags & FR_OUTQUE) {
1885 #ifdef  USE_INET6
1886                 if (proto == 0 || proto == 6) {
1887                         (void) frflushlist(set, unit,
1888                                            &flushed, &ipfilter6[1][set]);
1889                         (void) frflushlist(set, unit,
1890                                            &flushed, &ipacct6[1][set]);
1891                 }
1892 #endif
1893                 if (proto == 0 || proto == 4) {
1894                         (void) frflushlist(set, unit,
1895                                            &flushed, &ipfilter[1][set]);
1896                         (void) frflushlist(set, unit,
1897                                            &flushed, &ipacct[1][set]);
1898                 }
1899         }
1900         if (flags & FR_INQUE) {
1901 #ifdef  USE_INET6
1902                 if (proto == 0 || proto == 6) {
1903                         (void) frflushlist(set, unit,
1904                                             &flushed, &ipfilter6[0][set]);
1905                         (void) frflushlist(set, unit,
1906                                            &flushed, &ipacct6[0][set]);
1907                 }
1908 #endif
1909                 if (proto == 0 || proto == 4) {
1910                         (void) frflushlist(set, unit,
1911                                            &flushed, &ipfilter[0][set]);
1912                         (void) frflushlist(set, unit,
1913                                            &flushed, &ipacct[0][set]);
1914                 }
1915         }
1916         RWLOCK_EXIT(&ipf_mutex);
1917         return flushed;
1918 }
1919
1920
1921 char *memstr(src, dst, slen, dlen)
1922 char *src, *dst;
1923 int slen, dlen;
1924 {
1925         char *s = NULL;
1926
1927         while (dlen >= slen) {
1928                 if (bcmp(src, dst, slen) == 0) {
1929                         s = dst;
1930                         break;
1931                 }
1932                 dst++;
1933                 dlen--;
1934         }
1935         return s;
1936 }
1937
1938
1939 void fixskip(listp, rp, addremove)
1940 frentry_t **listp, *rp;
1941 int addremove;
1942 {
1943         frentry_t *fp;
1944         int rules = 0, rn = 0;
1945
1946         for (fp = *listp; fp && (fp != rp); fp = fp->fr_next, rules++)
1947                 ;
1948
1949         if (!fp)
1950                 return;
1951
1952         for (fp = *listp; fp && (fp != rp); fp = fp->fr_next, rn++)
1953                 if (fp->fr_skip && (rn + fp->fr_skip >= rules))
1954                         fp->fr_skip += addremove;
1955 }
1956
1957
1958 #ifdef  _KERNEL
1959 /*
1960  * count consecutive 1's in bit mask.  If the mask generated by counting
1961  * consecutive 1's is different to that passed, return -1, else return #
1962  * of bits.
1963  */
1964 int     countbits(ip)
1965 u_32_t  ip;
1966 {
1967         u_32_t  ipn;
1968         int     cnt = 0, i, j;
1969
1970         ip = ipn = ntohl(ip);
1971         for (i = 32; i; i--, ipn *= 2)
1972                 if (ipn & 0x80000000)
1973                         cnt++;
1974                 else
1975                         break;
1976         ipn = 0;
1977         for (i = 32, j = cnt; i; i--, j--) {
1978                 ipn *= 2;
1979                 if (j > 0)
1980                         ipn++;
1981         }
1982         if (ipn == ip)
1983                 return cnt;
1984         return -1;
1985 }
1986
1987
1988 /*
1989  * return the first IP Address associated with an interface
1990  */
1991 int fr_ifpaddr(v, ifptr, inp)
1992 int v;
1993 void *ifptr;
1994 struct in_addr *inp;
1995 {
1996 # ifdef USE_INET6
1997         struct in6_addr *inp6 = NULL;
1998 # endif
1999 # if SOLARIS
2000         ill_t *ill = ifptr;
2001 # else
2002         struct ifnet *ifp = ifptr;
2003 # endif
2004         struct in_addr in;
2005
2006 # if SOLARIS
2007 #  ifdef        USE_INET6
2008         if (v == 6) {
2009                 struct in6_addr in6;
2010
2011                 /*
2012                  * First is always link local.
2013                  */
2014                 if (ill->ill_ipif->ipif_next)
2015                         in6 = ill->ill_ipif->ipif_next->ipif_v6lcl_addr;
2016                 else
2017                         bzero((char *)&in6, sizeof(in6));
2018                 bcopy((char *)&in6, (char *)inp, sizeof(in6));
2019         } else
2020 #  endif
2021         {
2022                 in.s_addr = ill->ill_ipif->ipif_local_addr;
2023                 *inp = in;
2024         }
2025 # else /* SOLARIS */
2026 #  if linux
2027         ;
2028 #  else /* linux */
2029         struct sockaddr_in *sin;
2030         struct ifaddr *ifa;
2031
2032 #   if  defined(__DragonFly__) || (__FreeBSD_version >= 300000)
2033         ifa = TAILQ_FIRST(&ifp->if_addrhead);
2034 #   else
2035 #    if defined(__NetBSD__) || defined(__OpenBSD__)
2036         ifa = ifp->if_addrlist.tqh_first;
2037 #    else
2038 #     if defined(__sgi) && defined(IFF_DRVRLOCK) /* IRIX 6 */
2039         ifa = &((struct in_ifaddr *)ifp->in_ifaddr)->ia_ifa;
2040 #     else
2041         ifa = ifp->if_addrlist;
2042 #     endif
2043 #    endif /* __NetBSD__ || __OpenBSD__ */
2044 #   endif /* __FreeBSD_version >= 300000 */
2045 #   if (BSD < 199306) && !(/*IRIX6*/defined(__sgi) && defined(IFF_DRVRLOCK))
2046         sin = (struct sockaddr_in *)&ifa->ifa_addr;
2047 #   else
2048         sin = (struct sockaddr_in *)ifa->ifa_addr;
2049         while (sin && ifa) {
2050                 if ((v == 4) && (sin->sin_family == AF_INET))
2051                         break;
2052 #    ifdef USE_INET6
2053                 if ((v == 6) && (sin->sin_family == AF_INET6)) {
2054                         inp6 = &((struct sockaddr_in6 *)sin)->sin6_addr;
2055                         if (!IN6_IS_ADDR_LINKLOCAL(inp6) &&
2056                             !IN6_IS_ADDR_LOOPBACK(inp6))
2057                                 break;
2058                 }
2059 #    endif
2060 #    if defined(__DragonFly__) || (__FreeBSD_version >= 300000)
2061                 ifa = TAILQ_NEXT(ifa, ifa_link);
2062 #    else
2063 #     if defined(__NetBSD__) || defined(__OpenBSD__)
2064                 ifa = ifa->ifa_list.tqe_next;
2065 #     else
2066                 ifa = ifa->ifa_next;
2067 #     endif
2068 #    endif /* __FreeBSD_version >= 300000 */
2069                 if (ifa)
2070                         sin = (struct sockaddr_in *)ifa->ifa_addr;
2071         }
2072         if (ifa == NULL)
2073                 sin = NULL;
2074         if (sin == NULL)
2075                 return -1;
2076 #   endif /* (BSD < 199306) && (!__sgi && IFF_DRVLOCK) */
2077 #    ifdef      USE_INET6
2078         if (v == 6)
2079                 bcopy((char *)inp6, (char *)inp, sizeof(*inp6));
2080         else
2081 #    endif
2082         {
2083                 in = sin->sin_addr;
2084                 *inp = in;
2085         }
2086 #  endif /* linux */
2087 # endif /* SOLARIS */
2088         return 0;
2089 }
2090
2091
2092 static void frsynclist(fr)
2093 frentry_t *fr;
2094 {
2095         frdest_t *fdp;
2096         int i;
2097
2098         for (; fr; fr = fr->fr_next) {
2099                 for (i = 0; i < 4; i++) {
2100                         if ((fr->fr_ifnames[i][1] == '\0') &&
2101                             ((fr->fr_ifnames[i][0] == '-') ||
2102                              (fr->fr_ifnames[i][0] == '*'))) {
2103                                 fr->fr_ifas[i] = NULL;
2104                         } else if (*fr->fr_ifnames[i]) {
2105                                 fr->fr_ifas[i] = GETUNIT(fr->fr_ifnames[i],
2106                                                          fr->fr_v);
2107                                 if (!fr->fr_ifas[i])
2108                                         fr->fr_ifas[i] = (void *)-1;
2109                         }
2110                 }
2111
2112                 fdp = &fr->fr_dif;
2113                 fr->fr_flags &= ~FR_DUP;
2114                 if (*fdp->fd_ifname) {
2115                         fdp->fd_ifp = GETUNIT(fdp->fd_ifname, fr->fr_v);
2116                         if (!fdp->fd_ifp)
2117                                 fdp->fd_ifp = (struct ifnet *)-1;
2118                         else
2119                                 fr->fr_flags |= FR_DUP;
2120                 }
2121
2122                 fdp = &fr->fr_tif;
2123                 if (*fdp->fd_ifname) {
2124                         fdp->fd_ifp = GETUNIT(fdp->fd_ifname, fr->fr_v);
2125                         if (!fdp->fd_ifp)
2126                                 fdp->fd_ifp = (struct ifnet *)-1;
2127                 }
2128
2129                 if (fr->fr_grp)
2130                         frsynclist(fr->fr_grp);
2131         }
2132 }
2133
2134
2135 void frsync()
2136 {
2137 # if !SOLARIS
2138         struct ifnet *ifp;
2139
2140 #  if defined(__DragonFly__) || defined(__OpenBSD__) || ((NetBSD >= 199511) && (NetBSD < 1991011)) || \
2141      (defined(__FreeBSD_version) && (__FreeBSD_version >= 300000))
2142 #   if (NetBSD >= 199905) || defined(__OpenBSD__)
2143         for (ifp = ifnet.tqh_first; ifp; ifp = ifp->if_list.tqe_next)
2144 #   else
2145         for (ifp = ifnet.tqh_first; ifp; ifp = ifp->if_link.tqe_next)
2146 #   endif
2147 #  else
2148         for (ifp = ifnet; ifp; ifp = ifp->if_next)
2149 #  endif
2150         {
2151                 ip_natsync(ifp);
2152                 ip_statesync(ifp);
2153         }
2154         ip_natsync((struct ifnet *)-1);
2155 # endif /* !SOLARIS */
2156
2157         WRITE_ENTER(&ipf_mutex);
2158         frsynclist(ipacct[0][fr_active]);
2159         frsynclist(ipacct[1][fr_active]);
2160         frsynclist(ipfilter[0][fr_active]);
2161         frsynclist(ipfilter[1][fr_active]);
2162 #ifdef  USE_INET6
2163         frsynclist(ipacct6[0][fr_active]);
2164         frsynclist(ipacct6[1][fr_active]);
2165         frsynclist(ipfilter6[0][fr_active]);
2166         frsynclist(ipfilter6[1][fr_active]);
2167 #endif
2168         RWLOCK_EXIT(&ipf_mutex);
2169 }
2170
2171
2172 /*
2173  * In the functions below, bcopy() is called because the pointer being
2174  * copied _from_ in this instance is a pointer to a char buf (which could
2175  * end up being unaligned) and on the kernel's local stack.
2176  */
2177 int ircopyptr(a, b, c)
2178 void *a, *b;
2179 size_t c;
2180 {
2181         caddr_t ca;
2182         int err;
2183
2184 #if SOLARIS
2185         if (copyin(a, (char *)&ca, sizeof(ca)))
2186                 return EFAULT;
2187 #else
2188         bcopy(a, &ca, sizeof(ca));
2189 #endif
2190         err = copyin(ca, b, c);
2191         if (err)
2192                 err = EFAULT;
2193         return err;
2194 }
2195
2196
2197 int iwcopyptr(a, b, c)
2198 void *a, *b;
2199 size_t c;
2200 {
2201         caddr_t ca;
2202         int err;
2203
2204 #if SOLARIS
2205         if (copyin(b, (char *)&ca, sizeof(ca)))
2206                 return EFAULT;
2207 #else
2208         bcopy(b, &ca, sizeof(ca));
2209 #endif
2210         err = copyout(a, ca, c);
2211         if (err)
2212                 err = EFAULT;
2213         return err;
2214 }
2215
2216 #else /* _KERNEL */
2217
2218
2219 /*
2220  * return the first IP Address associated with an interface
2221  */
2222 int fr_ifpaddr(v, ifptr, inp)
2223 int v;
2224 void *ifptr;
2225 struct in_addr *inp;
2226 {
2227         return 0;
2228 }
2229
2230
2231 int ircopyptr(a, b, c)
2232 void *a, *b;
2233 size_t c;
2234 {
2235         caddr_t ca;
2236
2237         bcopy(a, &ca, sizeof(ca));
2238         bcopy(ca, b, c);
2239         return 0;
2240 }
2241
2242
2243 int iwcopyptr(a, b, c)
2244 void *a, *b;
2245 size_t c;
2246 {
2247         caddr_t ca;
2248
2249         bcopy(b, &ca, sizeof(ca));
2250         bcopy(a, ca, c);
2251         return 0;
2252 }
2253
2254
2255 #endif
2256
2257
2258 int fr_lock(data, lockp)
2259 caddr_t data;
2260 int *lockp;
2261 {
2262         int arg, error;
2263
2264         error = IRCOPY(data, (caddr_t)&arg, sizeof(arg));
2265         if (!error) {
2266                 error = IWCOPY((caddr_t)lockp, data, sizeof(*lockp));
2267                 if (!error)
2268                         *lockp = arg;
2269         }
2270         return error;
2271 }
2272
2273
2274 void fr_getstat(fiop)
2275 friostat_t *fiop;
2276 {
2277         bcopy((char *)frstats, (char *)fiop->f_st, sizeof(filterstats_t) * 2);
2278         fiop->f_locks[0] = fr_state_lock;
2279         fiop->f_locks[1] = fr_nat_lock;
2280         fiop->f_locks[2] = fr_frag_lock;
2281         fiop->f_locks[3] = fr_auth_lock;
2282         fiop->f_fin[0] = ipfilter[0][0];
2283         fiop->f_fin[1] = ipfilter[0][1];
2284         fiop->f_fout[0] = ipfilter[1][0];
2285         fiop->f_fout[1] = ipfilter[1][1];
2286         fiop->f_acctin[0] = ipacct[0][0];
2287         fiop->f_acctin[1] = ipacct[0][1];
2288         fiop->f_acctout[0] = ipacct[1][0];
2289         fiop->f_acctout[1] = ipacct[1][1];
2290 #ifdef  USE_INET6
2291         fiop->f_fin6[0] = ipfilter6[0][0];
2292         fiop->f_fin6[1] = ipfilter6[0][1];
2293         fiop->f_fout6[0] = ipfilter6[1][0];
2294         fiop->f_fout6[1] = ipfilter6[1][1];
2295         fiop->f_acctin6[0] = ipacct6[0][0];
2296         fiop->f_acctin6[1] = ipacct6[0][1];
2297         fiop->f_acctout6[0] = ipacct6[1][0];
2298         fiop->f_acctout6[1] = ipacct6[1][1];
2299 #else
2300         fiop->f_fin6[0] = NULL;
2301         fiop->f_fin6[1] = NULL;
2302         fiop->f_fout6[0] = NULL;
2303         fiop->f_fout6[1] = NULL;
2304         fiop->f_acctin6[0] = NULL;
2305         fiop->f_acctin6[1] = NULL;
2306         fiop->f_acctout6[0] = NULL;
2307         fiop->f_acctout6[1] = NULL;
2308 #endif
2309         fiop->f_active = fr_active;
2310         fiop->f_froute[0] = ipl_frouteok[0];
2311         fiop->f_froute[1] = ipl_frouteok[1];
2312
2313         fiop->f_running = fr_running;
2314         fiop->f_groups[0][0] = ipfgroups[0][0];
2315         fiop->f_groups[0][1] = ipfgroups[0][1];
2316         fiop->f_groups[1][0] = ipfgroups[1][0];
2317         fiop->f_groups[1][1] = ipfgroups[1][1];
2318         fiop->f_groups[2][0] = ipfgroups[2][0];
2319         fiop->f_groups[2][1] = ipfgroups[2][1];
2320 #ifdef  IPFILTER_LOG
2321         fiop->f_logging = 1;
2322 #else
2323         fiop->f_logging = 0;
2324 #endif
2325         fiop->f_defpass = fr_pass;
2326         strncpy(fiop->f_version, ipfilter_version, sizeof(fiop->f_version));
2327 }
2328
2329
2330 #ifdef  USE_INET6
2331 int icmptoicmp6types[ICMP_MAXTYPE+1] = {
2332         ICMP6_ECHO_REPLY,       /* 0: ICMP_ECHOREPLY */
2333         -1,                     /* 1: UNUSED */
2334         -1,                     /* 2: UNUSED */
2335         ICMP6_DST_UNREACH,      /* 3: ICMP_UNREACH */
2336         -1,                     /* 4: ICMP_SOURCEQUENCH */
2337         ND_REDIRECT,            /* 5: ICMP_REDIRECT */
2338         -1,                     /* 6: UNUSED */
2339         -1,                     /* 7: UNUSED */
2340         ICMP6_ECHO_REQUEST,     /* 8: ICMP_ECHO */
2341         -1,                     /* 9: UNUSED */
2342         -1,                     /* 10: UNUSED */
2343         ICMP6_TIME_EXCEEDED,    /* 11: ICMP_TIMXCEED */
2344         ICMP6_PARAM_PROB,       /* 12: ICMP_PARAMPROB */
2345         -1,                     /* 13: ICMP_TSTAMP */
2346         -1,                     /* 14: ICMP_TSTAMPREPLY */
2347         -1,                     /* 15: ICMP_IREQ */
2348         -1,                     /* 16: ICMP_IREQREPLY */
2349         -1,                     /* 17: ICMP_MASKREQ */
2350         -1,                     /* 18: ICMP_MASKREPLY */
2351 };
2352
2353
2354 int     icmptoicmp6unreach[ICMP_MAX_UNREACH] = {
2355         ICMP6_DST_UNREACH_ADDR,         /* 0: ICMP_UNREACH_NET */
2356         ICMP6_DST_UNREACH_ADDR,         /* 1: ICMP_UNREACH_HOST */
2357         -1,                             /* 2: ICMP_UNREACH_PROTOCOL */
2358         ICMP6_DST_UNREACH_NOPORT,       /* 3: ICMP_UNREACH_PORT */
2359         -1,                             /* 4: ICMP_UNREACH_NEEDFRAG */
2360         ICMP6_DST_UNREACH_NOTNEIGHBOR,  /* 5: ICMP_UNREACH_SRCFAIL */
2361         ICMP6_DST_UNREACH_ADDR,         /* 6: ICMP_UNREACH_NET_UNKNOWN */
2362         ICMP6_DST_UNREACH_ADDR,         /* 7: ICMP_UNREACH_HOST_UNKNOWN */
2363         -1,                             /* 8: ICMP_UNREACH_ISOLATED */
2364         ICMP6_DST_UNREACH_ADMIN,        /* 9: ICMP_UNREACH_NET_PROHIB */
2365         ICMP6_DST_UNREACH_ADMIN,        /* 10: ICMP_UNREACH_HOST_PROHIB */
2366         -1,                             /* 11: ICMP_UNREACH_TOSNET */
2367         -1,                             /* 12: ICMP_UNREACH_TOSHOST */
2368         ICMP6_DST_UNREACH_ADMIN,        /* 13: ICMP_UNREACH_ADMIN_PROHIBIT */
2369 };
2370 #endif
2371
2372
2373 #ifndef _KERNEL
2374 int mbuflen(buf)
2375 mb_t *buf;
2376 {
2377         ip_t *ip;
2378
2379         ip = (ip_t *)buf;
2380         return ip->ip_len;
2381 }
2382 #endif
2383
2384
2385 #if defined(_KERNEL) && !defined(__sgi)
2386 void *ipf_pullup(m, fin, len, ipin)
2387 mb_t *m;
2388 fr_info_t *fin;
2389 int len;
2390 void *ipin;
2391 {
2392 # if SOLARIS
2393         qif_t *qf = fin->fin_qif;
2394 # endif
2395         int out = fin->fin_out, dpoff, ipoff;
2396         char *ip;
2397
2398         if (m == NULL)
2399                 return NULL;
2400
2401         ipoff = (char *)ipin - MTOD(m, char *);
2402         if (fin->fin_dp != NULL)
2403                 dpoff = (char *)fin->fin_dp - (char *)ipin;
2404         else
2405                 dpoff = 0;
2406
2407         if (M_BLEN(m) < len) {
2408 # if SOLARIS
2409                 qif_t *qf = fin->fin_qif;
2410                 int inc = 0;
2411
2412                 if (ipoff > 0) {
2413                         if ((ipoff & 3) != 0) {
2414                                 inc = 4 - (ipoff & 3);
2415                                 if (m->b_rptr - inc >= m->b_datap->db_base)
2416                                         m->b_rptr -= inc;
2417                                 else
2418                                         inc = 0;
2419                         }
2420                 }
2421                 if (!pullupmsg(m, len + ipoff + inc)) {
2422                         ATOMIC_INCL(frstats[out].fr_pull[1]);
2423                         return NULL;
2424                 }
2425                 m->b_rptr += inc;
2426                 ATOMIC_INCL(frstats[out].fr_pull[0]);
2427                 qf->qf_data = MTOD(m, char *) + ipoff;
2428 # else
2429                 m = m_pullup(m, len);
2430                 *fin->fin_mp = m;
2431                 if (m == NULL) {
2432                         ATOMIC_INCL(frstats[out].fr_pull[1]);
2433                         return NULL;
2434                 }
2435                 ATOMIC_INCL(frstats[out].fr_pull[0]);
2436 # endif /* SOLARIS */
2437         }
2438         ip = MTOD(m, char *) + ipoff;
2439         if (fin->fin_dp != NULL)
2440                 fin->fin_dp = (char *)ip + dpoff;
2441         return ip;
2442 }
2443 #endif /* _KERNEL */