-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathmwm.c
1844 lines (1487 loc) · 45.3 KB
/
mwm.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Notes by Jerry Z.X. 2005/05/30 */
/*
** we use this for pattern matching algorithm performance studies
** any problem please contact [email protected]
** by Xin Zhou @Security Lab, RIIT, Tsinghua University, Beijing ,China
** http://security.riit.tsinghua.edu.cn/
*/
/*
**
** $Id: mwm.c,v 1.3 2003/12/17 21:25:14 jh8 Exp $
**
** mwm.c - A Modified Wu-Manber Style Multi-Pattern Matcher
**
** Copyright (C) 2002 Sourcefire,Inc
** Marc Norton
**
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
**
**
**
**
** A Fast Multi-Pattern Search Engine
**
** This algorithm is based on the Wu & Manber '94 paper. This algorithm is not an
** exact implementation in that it uses a standard one or 2 byte Bad Character shift table,
** whereas Wu & Manber used a 2 byte Bad Characeter shift table. This implementation
** also uses a fixed 2 byte prefix hash table, Wu & Manber used a variable size
** 2 byte hash. Hash groups are defined as in Wu & Manber. The Pattern groups are searched
** using a reverse string compare as in Wu & Manber.
**
** A pattern match tracking mechanism has been added to reduce the effect of DOS attacks,
** and generally improve the worst case performanmce scenario. This feature is
** enabled/disabled via BITOP_TEST and requires the bitop.h file.
**
**
** Initial Version - Marc Norton - April 2002
**
**
Algorithm:
This is a simplified implementation of Wu & Manber's '92 and '94 papers.
1) A multi-pattern Boyer-Moore style bad character or word shift is done until
a possible pattern is detected.
2) Hashing is used on the 2 character prefix of the current text to index into a
group of patterns with the same prefix. Patterns must be sorted. Wu & Manber used
the last 2 characters of the psuedo multi-pattern minimum length. Either works fine.
3) A reverse string compare is performed against each pattern in the
group to see if any of the patterns match the current text prefix.
Algorithm Steps
Preprocess:
a) Sort The Patterns, forming a sorted list of patterns.
b) Build a hash table of the patterns as follows: For each pattern find it's
hash, in the hash index vector save this patterns index, now count how
many patterns following this one have the same hash as it, save this value
with the 1st pattern that has this hash.
c) Build a Boyer-Moore style bad Character shift table, using the min shift from
all patterns for the shift value for each characters in the shift table. For the
purposes of the Bad Character Shift we assume all patterns are the same length as the
shortest pattern. This works quite well in practice. Also build a Bad Word
shift table.
Search:
a) Perform Boyer-Moore Bad Character or Bad Word Shift loop to find a possible
pattern match.
b) Check if a hashed pattern group entry exists for this possible patterns prefix,
If no pattern hash exists for this suffix shift go to d)
c) If a hash exists, test all of the patterns in the pattern group to see
which ones if any match the text suffix. Use a reverse string comparison
to benefit from the increased likelihood of misses at the ends of the string.
This tidbit is based on Boyer-Moore searching. Uses bit flags to eliminate
previously hit matches from contention. This provides a better worst case
scenario for this setwise pattern matching.
d) Use a one character shift and go back to a)
Pattern Matcher Selection Heuristics:
We can use A Boyer-Moore for small sets of patterns. We can use one of 3 matchers
for larger sets. When the minimum pattern size within the pattern group is one
character we use the version without a Boyer-Moore bad character or bad word
shift. When we have groups with a minimum pattern size of 2 or more characters
we use the version with the bad character shift. When we have groups with a minimum
pattern size of 2 or more characters and the number of patterns small-medium we can use
the version with the bad word shift. More testing is needed to help determine the optimal
switching points between these algorithms.
Case vs NoCase:
We convert all patterns and search texts to one case, find a match, and if case is
important we retest just the pattern characters against the text in exact mode.
Algorithm Strengths:
Performance is limited by the minimum pattern length of the group. The bigger
the minumum, the more the bad character shift helps, and the faster the search.
The minimum pattern length also determines whether a tree based search is faster or slower.
Small groups of patterns 10-100 with a large minimum pattern size (3+ chars) get the best
performanc. Oh, if it were all that simple.
Improvements or Variations:
where to start ...much more to come...
Notes:
Observations:
This algorithm is CPU cache sensitive, aren't they all.
Ancestory:
The structure of the API interface is based on the interface used by the samples
from Dan Gusfields book.
Some References:
Boyer-Moore - The original and still one of the best.
Horspool - Boyer-Moore-Horspool.
Sunday - Quicksearch and the Tuned Boyer-Moore algorithm.
Wu and Manber - A Fast Multi-Pattern Matcher '94 -- agrep, fgrep, sgrep
Aho & Corasick- State machine approach, very slick as well.
Dan Gusfield - Algorithms on strings, trees, and sequences.
Steven Graham -
Crochemere -
NOTES:
4-2002 - Marc Norton
Initial implementation
5/23/2002 - Marc Norton -
Added Boyer-Moore-Horspool locally, so it's inlined.
We use a simple <5 pattern count to decide to use the
BMH method over the MWM method. This is not always right
but close enough for now. This may get replaced with the standard
Boyer-Moore in mString - the standard Boyer Moore may protect
better against some types of DOS'ing attempts.
11/02 - Fixed bug for multiple duplicate one byte patterns.
10/03 - Changed ID to a void * for better 64 bit compatability.
- Added BITOP_TEST to make testing rotuines easier.
- Added Windows __inline command back into bitops.
- Added Standalone Windows support for UNIT64 for standalone testing
- modified mwm.c, mwm.h, bitop.h
10/28/03 - Fixed bug in mwmPrepHashedPatternGroups(), it was setting resetting psIID
as it walked through the patterns counting the number of patterns in each group.
This caused an almost random occurrence of an already tested rule's bitop
flag to cause another rule to never get tested.
12/08/03 - Removed the usage of NumArray1, it was unneccessary, reverted back to NumArray
mwmPrepHashedPatternGroups:
When counting one byte patterns in 'ningroup' added a check for psLen==1
Broke out common search code into an inline routine ..group2()
*/
/*
** INCLUDES
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
/*
* This macro enables use of the bitop test.
*/
//#define BITOP_TEST
#ifdef BITOP_TEST
#include "mwm_bitop.h"
#endif
#ifndef WIN32
#ifndef INLINE
#define INLINE inline
#endif
#ifndef UINT64
#define UINT64 unsigned long long
#endif
#else
#ifndef INLINE
#define INLINE __inline
#endif
#ifndef UINT64
#define UINT64 __int64
#endif
#endif
#ifndef CDECL
#define CDECL
#endif
/*
** Enables display of pattern group stats
*/
//#define SHOW_STATS
#define MWM_FEATURES "MWM:BC/BW-SHIFT + 2-BYTE-HASH"
#define HASHTABLESIZE (64*1024)
#define HASHBYTES16 2
/*
** Causes mbmAddPattern to check for and not allow duplicate patterns.
** By default we allow multiple duplicate patterns, since the AND clause
** may case the whole signature to be different. We trigger each pattern
** to be processesed by default.
*/
/*
#define REQUIRE_UNIQUE_PATTERNS
*/
/*
*
* Boyer-Moore-Horsepool for small pattern groups
*
*/
typedef struct
{
unsigned char *P;
int M;
short bcShift[256];
}HBM_STRUCT;
/*
** This struct is used internally my mwm.c
*/
typedef struct _mwm_pattern_struct
{
struct _mwm_pattern_struct * next;
unsigned char *psPat; // pattern array, no case
unsigned char *psPatCase; // pattern array, case(exact)
unsigned psLen; // length of pattern in bytes
void *psID; // OTNX
unsigned psID2; // PatMatchData
int psIID; //internal ID, used by the pattern matcher
unsigned psNoCase;// Pattern match is case insensitive if true
int psOffset; // start search this deep
unsigned psDepth; // number of bytes after offset to search
HBM_STRUCT * psBmh;
}MWM_PATTERN_STRUCT;
/*
* Pattern Matching Methods - Boyer-Moore-Horspool or Modified Wu Manber
*/
#define MTH_MWM 0
#define MTH_BM 1
#define HASH_TYPE short
#define BWSHIFTABLESIZE (64*1024)
#define BM_PATTERN_NUM 5 // xinz+
/*
** Pattern GROUP Structure, this struct is is used publicly, but by reference only
*/
typedef struct _mwm_struct
{
int bmPatternNum; // xinz+
int msMethod; /* MTH_BM, MTH_MWM */
MWM_PATTERN_STRUCT * plist;
/* Array of Patterns */
int msMaxPatterns;
MWM_PATTERN_STRUCT *msPatArray;
/* Array of Group Counts, # of patterns in each hash group */
unsigned short *msNumArray;
/* One byte patterns */
unsigned short msNumArray1[256];
/* Number of Patterns loaded */
int msNumPatterns;
/* Wu-Manber Hash Tables */
unsigned msNumHashEntries;
HASH_TYPE *msHash; // 2+ character Pattern Big Hash Table
HASH_TYPE msHash1[256]; // One character Pattern Hash Table
/* Bad Character Shift Table */
short msShift[256];
unsigned msShiftLen;
/* Bad Word Shift Table */
unsigned char* msShift2;
int msLargeShifts;
#ifdef BITOP_TEST
BITOP * RuleMask;
#endif
/* Case insensitive search */
int msNoCase;
/* search function */
int (*search)( struct _mwm_struct * ps,
unsigned char * Tx, int n, unsigned char * Tc,
int(*match)(void * id, int index, void * data ),
void * data );
/* Print Group Details */
int msDetails;
/* Pattern Group Stats */
int msSmallest;
int msLargest;
int msAvg;
int msTotal;
int * msLengths;
}MWM_STRUCT;
/*
*
* Boyer-Moore-Horsepool for small pattern groups
*
*/
static HBM_STRUCT * hbm_prepx(HBM_STRUCT *p, unsigned char * pat, int m)
{
int k;
if ( !m ) return 0;
if ( !p ) return 0;
#ifdef COPYPATTERN
p->P = (unsigned char*)malloc( m + 1 )
if ( !p->P ) return 0;
memcpy(p->P,pat,m);
#else
p->P = pat;
#endif
p->M = m;
/* Compute normal Boyer-Moore Bad Character Shift */
for (k = 0; k < 256; k++) p->bcShift[k] = m;
for (k = 0; k < m; k++) p->bcShift[pat[k]] = m - k - 1;
return p;
}
/*
*
*/
static HBM_STRUCT * hbm_prep(unsigned char * pat, int m)
{
HBM_STRUCT *p;
p = (HBM_STRUCT*)malloc( sizeof(HBM_STRUCT) );
if ( !p ) return 0;
return hbm_prepx( p, pat, m );
}
//#ifdef XXX_NOT_USED
/*
*
*/
static void hbm_free( HBM_STRUCT *p )
{
if (p)
{
#ifdef COPYPATTERN
if ( p->P )free(p->P);
#endif
free(p);
}
}
//#endif
/*
* Boyer-Moore Horspool
* Does NOT use Sentinel Byte(s)
* Scan and Match Loops are unrolled and separated
* Optimized for 1 byte patterns as well
*/
static INLINE unsigned char * hbm_match(HBM_STRUCT * px, unsigned char * text, int n)
{
unsigned char *pat, *t, *et, *q;
int m1, k;
short *bcShift;
m1 = px->M-1;
pat = px->P;
bcShift= px->bcShift;
t = text + m1;
et = text + n;
/* Handle 1 Byte patterns - it's a faster loop */
if ( !m1 )
{
for ( ;t<et; t++ )
if ( *t == *pat ) return t;
return 0;
}
/* Handle MultiByte Patterns */
while ( t < et )
{
/* Scan Loop - Bad Character Shift */
do
{
t += bcShift[*t];
if ( t >= et )return 0;
;
t += (k=bcShift[*t]);
if ( t >= et )return 0;
}
while ( k );
/* Unrolled Match Loop */
k = m1;
q = t - m1;
while ( k >= 4 )
{
if ( pat[k] != q[k] )goto NoMatch;
k--;
if ( pat[k] != q[k] )goto NoMatch;
k--;
if ( pat[k] != q[k] )goto NoMatch;
k--;
if ( pat[k] != q[k] )goto NoMatch;
k--;
}
/* Finish Match Loop */
while ( k >= 0 )
{
if ( pat[k] != q[k] )goto NoMatch;
k--;
}
/* If matched - return 1st char of pattern in text */
return q;
NoMatch:
/* Shift by 1, this replaces the good suffix shift */
t++;
}
return 0;
}
/*
** mwmAlloc:: Allocate and Init Big hash Table Verions
**
** maxpats - max number of patterns to support
**
*/
void * mwmNew(int bmPatternNum)
{
MWM_STRUCT * p = (MWM_STRUCT * )calloc( sizeof(MWM_STRUCT),1 );
if ( !p )
{
return 0;
}
if(bmPatternNum <= 0)
p->bmPatternNum = BM_PATTERN_NUM;
else
p->bmPatternNum = bmPatternNum;
p->msSmallest = 32000;
return (void*)p;
}
/*
**
*/
void mwmFree( void * pv )
{
MWM_STRUCT * p = (MWM_STRUCT * )pv;
MWM_PATTERN_STRUCT *ps,*pt;
if ( p )
{
if ( p->msPatArray )
{
if ( p->msMethod == MTH_BM )
{
int i;
for (i=0;i<p->msNumPatterns;i++)
{
hbm_free(p->msPatArray[ i ].psBmh);
}
}
free( p->msPatArray );
}
if ( p->msNumArray ) free( p->msNumArray );
if ( p->msHash ) free( p->msHash );
if ( p->msShift2 ) free( p->msShift2 );
if (p->msLengths) free(p->msLengths);
if (p->plist)
{
ps=p->plist;
while(ps)
{
if(ps->psPat) free(ps->psPat);
if(ps->psPatCase) free(ps->psPatCase);
pt = ps->next;
free(ps);
ps = pt;
}
}
free( p );
}
}
/*
** mwmAddPatternEx::
**
** returns -1: max patterns exceeded
** 0: already present, uniqueness compiled in
** 1: added
*/
int mwmAddPatternEx( void *pv, unsigned char * P, int m,
unsigned noCase, unsigned offset, unsigned depth , void * id, int iid )
{
MWM_STRUCT *ps = (MWM_STRUCT*)pv;
MWM_PATTERN_STRUCT *plist=0;
MWM_PATTERN_STRUCT *p = (MWM_PATTERN_STRUCT*)calloc(sizeof(MWM_PATTERN_STRUCT),1);
if ( !p ) return -1;
#ifdef REQUIRE_UNIQUE_PATTERNS
for ( plist=ps->plist; plist!=NULL; plist=plist->next )
{
if ( plist->psLen == m )
{
if ( memcmp(P,plist->psPat,m) == 0 )
{
return 0; /*already added */
}
}
}
#endif
if ( ps->plist )
{
for ( plist=ps->plist; plist->next!=NULL; plist=plist->next )
;
plist->next = p;
}
else
ps->plist = p;
/* Allocate and store the Pattern 'P' with NO CASE info*/
p->psPat = (unsigned char*)malloc( m );
if ( !p->psPat ) return -1;
memcpy(p->psPat, P, m );
//ConvCaseToUpper( p->psPat, m );
/* Allocate and store the Pattern 'P' with CASE info*/
p->psPatCase = (unsigned char*)malloc( m );
if ( !p->psPatCase ) return -1;
memcpy( p->psPatCase, P, m );
p->psLen = m;
p->psID = id;
p->psIID = iid;
p->psNoCase = noCase;
p->psOffset = offset;
p->psDepth = depth;
ps->msNoCase += noCase;
ps->msNumPatterns++;
if ( p->psLen < (unsigned)ps->msSmallest ) ps->msSmallest= p->psLen;
if ( p->psLen > (unsigned)ps->msLargest ) ps->msLargest = p->psLen;
ps->msTotal += p->psLen;
ps->msAvg = ps->msTotal / ps->msNumPatterns;
return 1;
}
#ifdef OLDSHIT
/*
** mwmAddPatternEx::
**
** returns -1: max patterns exceeded
** 0: already present, uniqueness compiled in
** 1: added
*/
int mwmAddPatternExOrig( MWM_STRUCT *ps, unsigned char * P, int m,
unsigned noCase, unsigned offset, unsigned depth ,unsigned id, int iid )
{
int kk;
MWM_PATTERN_STRUCT *p;
if ( ps->msNumPatterns >= ps->msMaxPatterns )
{
return -1;
}
#ifdef REQUIRE_UNIQUE_PATTERNS
for (i=0;i<ps->msNumPatterns;i++)
{
if ( ps->msPatArray[i].psLen == m )
{
if ( memcmp(P,ps->msPatArray[i].psPat,m) == 0 )
{
return 0; /*already added */
}
}
}
#endif
p = &ps->msPatArray[ ps->msNumPatterns ];
/* Allocate and store the Pattern 'P' with NO CASE info*/
p->psPat = (unsigned char*)malloc( m );
memcpy(p->psPat, P, m );
//ConvCaseToUpper( p->psPat, m );
/* Allocate and store the Pattern 'P' with CASE info*/
p->psPatCase = (unsigned char*)malloc( m );
memcpy( p->psPatCase, P, m );
p->psLen = m;
p->psID = id;
p->psIID = iid;
p->psNoCase = noCase;
p->psOffset = offset;
p->psDepth = depth;
ps->msNoCase += noCase;
kk = ps->msNumPatterns;
ps->msNumPatterns++;
if ( ps->msPatArray[kk].psLen < (unsigned)ps->msSmallest ) ps->msSmallest= ps->msPatArray[kk].psLen;
if ( ps->msPatArray[kk].psLen > (unsigned)ps->msLargest ) ps->msLargest = ps->msPatArray[kk].psLen;
ps->msTotal += ps->msPatArray[kk].psLen;
ps->msAvg = ps->msTotal / ps->msNumPatterns;
return 1;
}
#endif
/*
** Exact Pattern Matcher - don't use this...
*/
int mwmAddPattern( void * pv, unsigned char * P, int m, unsigned id )
{
return mwmAddPatternEx( pv, P, m, 0, id, 0, pv, 0 );
}
/*
** bcompare::
**
** Perform a Binary comparsion of 2 byte sequences of possibly
** differing lengths.
**
** returns -1 a < b
** +1 a > b
** 0 a = b
*/
static int bcompare( unsigned char *a, int alen, unsigned char * b, int blen )
{
int stat;
if ( alen == blen )
{
return memcmp(a,b,alen);
}
else if ( alen < blen )
{
if ( (stat=memcmp(a,b,alen)) != 0 )
return stat;
return -1;
}
else
{
if ( (stat=memcmp(a,b,blen)) != 0 )
return stat;
return +1;
}
}
/*
** sortcmp:: qsort callback
*/
static int CDECL sortcmp( const void * e1, const void * e2 )
{
MWM_PATTERN_STRUCT *r1= (MWM_PATTERN_STRUCT*)e1;
MWM_PATTERN_STRUCT *r2= (MWM_PATTERN_STRUCT*)e2;
return bcompare( r1->psPat, r1->psLen, r2->psPat, r2->psLen );
}
/*
** HASH ROUTINE - used during pattern setup, but inline during searches
*/
static unsigned HASH16( unsigned char * T )
{
return (unsigned short) (((*T)<<8) | *(T+1));
}
/*
** Build the hash table, and pattern groups
*/
static void mwmPrepHashedPatternGroups(MWM_STRUCT * ps)
{
unsigned sindex,hindex,ningroup;
int i;
/*
** Allocate and Init 2+ byte pattern hash table
*/
ps->msNumHashEntries = HASHTABLESIZE;
ps->msHash = (HASH_TYPE*)malloc( sizeof(HASH_TYPE) * ps->msNumHashEntries );
if ( !ps->msHash )
{
exit(1);//xinz+
}
/* Init Hash table to default value */
for (i=0;i<(int)ps->msNumHashEntries;i++)
{
ps->msHash[i] = (HASH_TYPE)-1;
}
/* Initialize The One Byte Pattern Hash Table */
for (i=0;i<256;i++)
{
ps->msHash1[i] = (HASH_TYPE)-1;
}
/*
** Add the patterns to the hash table
*/
for (i=0;i<ps->msNumPatterns;i++)
{
if ( ps->msPatArray[i].psLen > 1 )
{
hindex = HASH16(ps->msPatArray[i].psPat);
sindex = ps->msHash[ hindex ] = i;
ningroup = 1;
while ( (++i < ps->msNumPatterns) && (hindex==HASH16(ps->msPatArray[i].psPat)) )
ningroup++;
ps->msNumArray[ sindex ] = ningroup;
i--;
}
else if ( ps->msPatArray[i].psLen == 1 )
{
hindex = ps->msPatArray[i].psPat[0];
sindex = ps->msHash1[ hindex ] = i;
ningroup = 1;
while ((++i < ps->msNumPatterns) && (hindex == ps->msPatArray[i].psPat[0]) && (ps->msPatArray[i].psLen == 1))
ningroup++;
ps->msNumArray[ sindex ] = ningroup;
i--;
}
}
}
/*
* Standard Bad Character Multi-Pattern Skip Table
*/
static void mwmPrepBadCharTable(MWM_STRUCT * ps)
{
unsigned short i, k, m, cindex, shift;
unsigned small_value=32000, large_value=0;
/* Determine largest and smallest pattern sizes */
for (i=0;i<ps->msNumPatterns;i++)
{
if ( ps->msPatArray[i].psLen < small_value ) small_value = ps->msPatArray[i].psLen;
if ( ps->msPatArray[i].psLen > large_value ) large_value = ps->msPatArray[i].psLen;
}
m = (unsigned short) small_value;
if ( m > 255 ) m = 255;
ps->msShiftLen = m;
/* Initialze the default shift table. Max shift of 256 characters */
for (i=0;i<256;i++)
{
ps->msShift[i] = m;
}
/* Multi-Pattern BAD CHARACTER SHIFT */
for (i=0;i<ps->msNumPatterns;i++)
{
for (k=0;k<m;k++)
{
shift = (unsigned short)(m - 1 - k);
if ( shift > 255 ) shift = 255;
cindex = ps->msPatArray[ i ].psPat[ k ];
if ( shift < ps->msShift[ cindex ] )
ps->msShift[ cindex ] = shift;
}
}
}
/*
** Prep and Build a Bad Word Shift table
*/
static void mbmPrepBadWordTable(MWM_STRUCT * ps)
{
int i;
unsigned short k, m, cindex;
unsigned small_value=32000, large_value=0;
unsigned shift;
ps->msShift2 = (unsigned char *)malloc(BWSHIFTABLESIZE*sizeof(char));
if ( !ps->msShift2 )
return;
/* Determine largest and smallest pattern sizes */
for (i=0;i<ps->msNumPatterns;i++)
{
if ( ps->msPatArray[i].psLen < small_value ) small_value = ps->msPatArray[i].psLen;
if ( ps->msPatArray[i].psLen > large_value ) large_value = ps->msPatArray[i].psLen;
}
m = (unsigned short) small_value; /* Maximum Boyer-Moore Shift */
/* Limit the maximum size of the smallest pattern to 255 bytes */
if ( m > 255 ) m = 255;
ps->msShiftLen = m;
/* Initialze the default shift table. */
for (i=0;i<BWSHIFTABLESIZE;i++)
{
ps->msShift2[i] = (unsigned)(m-1);
}
/* Multi-Pattern Bad Word Shift Table Values */
for (i=0;i<ps->msNumPatterns;i++)
{
for (k=0;k<m-1;k++)
{
shift = (unsigned short)(m - 2 - k);
if ( shift > 255 ) shift = 255;
cindex = ( ps->msPatArray[i].psPat[ k ] | (ps->msPatArray[i].psPat[k+1]<<8) );
if ( shift < ps->msShift2[ cindex ] )
ps->msShift2[ cindex ] = shift;
}
}
}
/*
** Print some Pattern Stats
*/
void mwmShowStats( void * pv )
{
MWM_STRUCT * ps = (MWM_STRUCT*)pv;
int i;
printf("Pattern Stats\n");
printf("-------------\n");
printf("Patterns : %d\n" , ps->msNumPatterns);
printf("Average : %d chars\n", ps->msAvg);
printf("Smallest : %d chars\n", ps->msSmallest);
printf("Largest : %d chars\n", ps->msLargest);
printf("Total chars: %d\n" , ps->msTotal);
for (i=0;i<ps->msLargest+1;i++)
{
if ( ps->msLengths[i] )
printf("Len[%d] : %d patterns\n", i, ps->msLengths[i] );
}
printf("\n");
}
/*
** Calc some pattern length stats
*/
static void mwmAnalyzePattens( MWM_STRUCT * ps )
{
int i;
ps->msLengths= (int*) malloc( sizeof(int) * (ps->msLargest+1) );
if ( ps->msLengths )
{
memset( ps->msLengths, 0, sizeof(int) * (ps->msLargest+1) );
for (i=0;i<ps->msNumPatterns;i++)
{
ps->msLengths[ ps->msPatArray[i].psLen ]++;
}
}
}
/*
** Selects the bad Word Algorithm over the bad Character algorithm
** This should be called before mwmPrepPatterns
*/
void mwmLargeShifts( void * pv, int flag)
{
MWM_STRUCT * ps = (MWM_STRUCT*)pv;
ps->msLargeShifts = flag;
}
/*
** mwmGetNpatterns::
*/
int mwmGetNumPatterns( void * pv )
{
MWM_STRUCT *p = (MWM_STRUCT*)pv;