-
Notifications
You must be signed in to change notification settings - Fork 1
/
grepmail
executable file
·2710 lines (2080 loc) · 72.7 KB
/
grepmail
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
#!/usr/bin/perl
# grepmail
# Do a pod2text on this file to get full documentation, or pod2man to get
# man pages.
# Written by David Coppit (david@coppit.org, http://coppit.org/) with lots of
# debugging and patching by others -- see the CHANGES file for a complete
# list.
use 5.005;
use vars qw( %opts $commandLine $VERSION %message_ids_seen
$USE_CACHING $USE_GREP );
use Getopt::Std;
use strict;
use warnings;
use Mail::Mbox::MessageParser;
use FileHandle;
use Carp;
$VERSION = sprintf "%d.%02d%02d", q/5.31.11/ =~ /(\d+)/g;
# Set to 1 to enable caching capability
$USE_CACHING = 1;
# Set to 0 to disable use of external grep utility
$USE_GREP = 1;
# Internal function return values.
my $PRINT = 0;
my $DONE = 1;
my $SKIP = 2;
my $CONTINUE = 3;
my $NONE = 4;
my $BEFORE = 5;
my $AFTER = 6;
my $NODATE = 8;
my $BETWEEN = 9;
my $LESS_THAN = 10;
my $LESS_THAN_OR_EQUAL = 11;
my $GREATER_THAN = 12;
my $GREATER_THAN_OR_EQUAL = 13;
my $EQUAL = 14;
my $NO_PATTERN = '\127\235NO PATTERN\725\125';
my %HEADER_PATTERNS = (
'^TO:' =>
'(^((Original-)?(Resent-)?(To|Cc|Bcc)|(X-Envelope|Apparently(-Resent)?)-To):)',
'^FROM_DAEMON:' =>
'(^(Mailing-List:|Precedence:.*(junk|bulk|list)|To: Multiple recipients of |(((Resent-)?(From|Sender)|X-Envelope-From):|>?From )([^>]*[^(.%@a-z0-9])?(Post(ma?(st(e?r)?|n)|office)|(send)?Mail(er)?|daemon|m(mdf|ajordomo)|n?uucp|LIST(SERV|proc)|NETSERV|o(wner|ps)|r(e(quest|sponse)|oot)|b(ounce|bs\.smtp)|echo|mirror|s(erv(ices?|er)|mtp(error)?|ystem)|A(dmin(istrator)?|MMGR|utoanswer))(([^).!:a-z0-9][-_a-z0-9]*)?[%@>\t ][^<)]*(\(.*\).*)?)?))',
'^FROM_MAILER:' =>
'(^(((Resent-)?(From|Sender)|X-Envelope-From):|>?From)([^>]*[^(.%@a-z0-9])?(Post(ma(st(er)?|n)|office)|(send)?Mail(er)?|daemon|mmdf|n?uucp|ops|r(esponse|oot)|(bbs\.)?smtp(error)?|s(erv(ices?|er)|ystem)|A(dmin(istrator)?|MMGR))(([^).!:a-z0-9][-_a-z0-9]*)?[%@>\t][^<)]*(\(.*\).*)?)?$([^>]|$))',
);
#-------------------------------------------------------------------------------
# Outputs debug messages with the -D flag. Be sure to return 1 so code like
# 'dprint "blah\n" and exit' works.
sub dprint
{
return 1 unless $opts{'D'};
my $message = join '',@_;
foreach my $line (split /\n/, $message)
{
warn "DEBUG: $line\n";
}
return 1;
}
#-------------------------------------------------------------------------------
# Print a nice error message before exiting
sub Report_And_Exit
{
my $message = shift;
$message .= "\n" unless $message =~ /\n$/;
warn "grepmail: $message";
exit 1;
}
#-------------------------------------------------------------------------------
# Filter signals to print error messages when CTRL-C is caught, a pipe is
# empty, a pipe is killed, etc.
my %signals_and_messages = (
'PIPE' => 'Broken Pipe',
'HUP' => 'Hangup',
'INT' => 'Canceled',
'QUIT' => 'Quit',
'SEGV' => 'Segmentation violation',
'TERM' => 'Terminated',
);
# We'll store a copy of the original signal handlers and call them when we're
# done. This helps when running under the debugger.
my %old_SIG = %SIG;
sub Signal_Handler
{
my $signal = $_[0];
$old_SIG{$signal}->(@_) if $old_SIG{$signal};
Report_And_Exit($signals_and_messages{$signal});
}
# Delete the HUP signal for Windows, where it doesn't exist
delete $signals_and_messages{HUP} if $^O eq 'MSWin32';
# We have to localize %SIG to prevent odd bugs from cropping up (see
# changelog). Using an array slice on %SIG, I assign an array consisting of as
# many copies of \&Signal_Handler as there are keys in %signals_and_messages.
local @SIG{keys %signals_and_messages} =
(\&Signal_Handler) x keys %signals_and_messages;
################################ MAIN PROGRAM #################################
binmode STDOUT;
binmode STDERR;
my ($dateRestriction, $date1, $date2);
my ($sizeRestriction, $size1, $size2);
{
# PROCESS ARGUMENTS
my (@remaining_arguments,$pattern);
{
my ($opts_ref,$remaining_arguments_ref);
($opts_ref,$remaining_arguments_ref,$pattern) = Get_Options(@ARGV);
%opts = %$opts_ref;
@remaining_arguments = @$remaining_arguments_ref;
}
# Initialize seen messages data structure to empty.
%message_ids_seen = ();
# Save the command line for later when we try to decompress standard input
{
# Need to quote arguments with spaces
my @args = @ARGV;
grep { index($_, ' ') == -1 ? $_ : "'$_'" } @args;
$commandLine = "$0 @args";
}
Print_Debug_Information($commandLine);
sub Process_Date;
sub Process_Size;
sub Get_Files;
sub Validate_Files_Are_Not_Output;
# Make the pattern insensitive if we need to
$pattern = "(?i)$pattern" if ($opts{'i'}) && $pattern ne $NO_PATTERN;
# Make the pattern match word boundaries if we need to
$pattern = "\\b$pattern\\b" if ($opts{'w'}) && $pattern ne $NO_PATTERN;
if (defined $opts{'d'})
{
($dateRestriction,$date1,$date2) = Process_Date($opts{'d'});
}
else
{
$dateRestriction = $NONE;
}
if (defined $opts{'s'})
{
($sizeRestriction,$size1,$size2) = Process_Size($opts{'s'});
}
else
{
$sizeRestriction = $NONE;
}
dprint "PATTERN: $pattern\n" unless $pattern eq $NO_PATTERN;
dprint "PATTERN: <NO PATTERN>\n" if $pattern eq $NO_PATTERN;
dprint "FILES: @remaining_arguments\n";
dprint "DATE RESTRICTION: $dateRestriction\n";
dprint "FIRST DATE: $date1\n" unless $dateRestriction == $NONE;
dprint "SECOND DATE: $date2\n" unless $dateRestriction == $NONE;
dprint "SIZE RESTRICTION: $sizeRestriction\n";
dprint "FIRST SIZE: $size1\n" unless $sizeRestriction == $NONE;
dprint "SECOND SIZE: $size2\n" unless $sizeRestriction == $NONE;
Validate_Pattern($pattern);
my @files = Get_Files(@remaining_arguments);
# If the user provided input files...
if (@files)
{
Validate_Files_Are_Not_Output(@files);
Handle_Input_Files(@files,$pattern);
}
# Using STDIN
elsif (!@remaining_arguments)
{
Handle_Standard_Input($pattern);
}
exit 0;
}
#-------------------------------------------------------------------------------
sub Get_Options
{
local @ARGV = @_;
my @argv = @ARGV;
# Print usage error if no arguments given
Report_And_Exit("No arguments given.\n\n" . usage()) unless @ARGV;
# Check for --help, the standard usage command, or --version.
print usage() and exit(0) if grep { /^--help$/ } @ARGV;
print "$VERSION\n" and exit(0) if grep { /^--version$/ } @ARGV;
my @valid_options =
qw( a b B C d D e E f F i j h H l L M m n q r R s S t T u v V w X Y Z );
my %opts;
my $pattern;
# Initialize all options to zero.
map { $opts{$_} = 0; } @valid_options;
# And some to non-zero.
$opts{'d'} = $opts{'V'} = undef;
$opts{'X'} = '^-- $';
$opts{'C'} = undef;
# Ensure valid options. ALSO UPDATE 2ND GETOPT CALL BELOW
getopt("CdeEfjsXY",\%opts);
# Here we have to deal with the possibility that the user specified the
# search pattern without the -e flag.
# getopts stops as soon as it sees a non-flag, so $ARGV[0] may contain the
# pattern with more flags after it.
unless ($opts{'e'} || $opts{'E'} || $opts{'f'})
{
my $missing_flags = '';
foreach my $flag (keys %opts)
{
$missing_flags .= $flag unless $opts{$flag};
}
$missing_flags = "[$missing_flags]";
# If it looks like more flags are following, then grab the pattern and
# process them.
unless (defined $argv[-($#ARGV+2)] && $argv[-($#ARGV+2)] eq '--')
{
if ( $#ARGV > 0 && $ARGV[1] =~ /^-$missing_flags$/)
{
$pattern = shift @ARGV;
getopt("CdfjsXY",\%opts);
}
# If we've seen a -d, -j, -s, or -u flag, and it doesn't look like there
# are flags following $ARGV[0], then look at the value in $ARGV[0]
elsif ( ( defined $opts{'d'} || $opts{'j'} || $opts{'s'} || $opts{'u'} ) &&
( $#ARGV <= 0 ||
( $#ARGV > 0 && $ARGV[1] !~ /^-$missing_flags$/ )
)
)
{
# If $ARGV[0] looks like a file we assume there was no pattern and
# set a default pattern of "." to match everything.
if ($#ARGV != -1 && -f Search_Mailbox_Directories($ARGV[0]))
{
$pattern = '.';
}
# Otherwise we take the pattern and move on
else
{
$pattern = shift @ARGV;
}
}
# If we still don't have a pattern or any -d, -j, -s, or -u flag, we
# assume that $ARGV[0] is the pattern
elsif (!defined $opts{'d'} && !$opts{'j'} && !$opts{'s'} && !$opts{'u'})
{
$pattern = shift @ARGV;
}
}
}
if ($opts{'e'} || $opts{'E'} || $opts{'f'})
{
Report_And_Exit("You specified two search patterns, or a pattern and a pattern file.\n")
if defined $pattern;
if ($opts{'e'})
{
$pattern = $opts{'e'};
}
elsif ($opts{'E'})
{
$pattern = $opts{'E'};
}
else
{
open my $pattern_file, $opts{'f'}
or Report_And_Exit("Can't open pattern file $opts{'f'}");
$pattern = '(';
my $first = 1;
while (my $line = <$pattern_file>)
{
if ($first)
{
$first = 0;
}
else
{
$pattern .= '|';
}
chomp $line;
$pattern .= $line;
}
close $pattern_file;
$pattern .= ')';
}
}
elsif (defined $opts{'V'})
{
# Print version and exit if we need to
print "$VERSION\n";
exit (0);
}
elsif (!defined $pattern)
{
# The only times you don't have to specify the pattern is when -d, -j, -s, or -u
# is being used. This should catch people who do "grepmail -h" thinking
# it's help.
Report_And_Exit("Invalid arguments.\n\n" . usage())
unless defined $opts{'d'} || $opts{'j'} || $opts{'s'} || $opts{'u'};
$pattern = '.';
}
if (defined $opts{'d'})
{
if (eval {require Date::Parse})
{
import Date::Parse;
}
else
{
Report_And_Exit('You specified -d, but do not have Date::Parse. ' .
"Get it from CPAN.\n");
}
if (eval {require Time::Local})
{
import Time::Local;
}
else
{
Report_And_Exit('You specified -d, but do not have Time::Local. ' .
"Get it from CPAN.\n");
}
if (eval {require Date::Manip})
{
my ($version_number) = $Date::Manip::VERSION =~ /^(\d+\.\d+)/;
Date::Manip::Date_Init("TodayIsMidnight=1") if ($version_number >= 5.43 && $version_number < 6);
}
}
$opts{'h'} = 1 if $opts{'Y'};
# Make sure no unknown flags were given
foreach my $option (keys %opts)
{
unless (grep {/^$option$/} @valid_options)
{
Report_And_Exit("Invalid option \"$option\".\n\n" . usage());
}
}
# Check for -E flag incompatibilities.
if ($opts{'E'})
{
# Have to do -Y before -h because the former implies the latter
my @options = qw(e f M S Y);
for my $option (@options)
{
if ($opts{$option})
{
Report_And_Exit "-$option can not be used with -E";
}
}
if ($opts{'i'})
{
Report_And_Exit "-i can not be used with -E. Use -E '\$email =~ /pattern/i' instead";
}
if ($opts{'b'})
{
Report_And_Exit "-b can not be used with -E. Use -E '\$email_body =~ /pattern/' instead";
}
if ($opts{'h'})
{
Report_And_Exit "-h can not be used with -E. Use -E '\$email_header =~ /pattern/' instead";
}
}
# Check for -f flag incompatibilities.
if ($opts{'f'})
{
# Have to do -Y before -h because the former implies the latter
my @options = qw(E e);
for my $option (@options)
{
if ($opts{$option})
{
Report_And_Exit "-$option can not be used with -E";
}
}
}
unless (defined $opts{'C'})
{
if(defined $ENV{'HOME'})
{
$opts{'C'} = "$ENV{'HOME'}/.grepmail-cache";
}
elsif ($USE_CACHING)
{
# No cache file, so disable caching
$USE_CACHING = 0;
warn "grepmail: No cache file specified, and \$HOME not set. " .
"Disabling cache.\n"
unless $opts{'q'};
}
}
$opts{'R'} = 1 if $opts{'L'};
$pattern = $NO_PATTERN if $pattern eq '()';
return (\%opts, \@ARGV, $pattern);
}
#-------------------------------------------------------------------------------
sub Print_Debug_Information
{
my $commandLine = shift;
return unless $opts{'D'};
dprint "Version: $VERSION";
dprint "Command line was (special characters not escaped):";
dprint " $commandLine";
if (defined $Date::Parse::VERSION)
{
dprint "Date::Parse VERSION: $Date::Parse::VERSION";
}
dprint "Options are:";
foreach my $i (sort keys %opts)
{
if (defined $opts{$i})
{
dprint " $i: $opts{$i}";
}
else
{
dprint " $i: undef";
}
}
dprint "INC is:";
foreach my $i (@INC)
{
dprint " $i";
}
}
#-------------------------------------------------------------------------------
# Dies if the given pattern's syntax is invalid
sub Validate_Pattern
{
my $pattern = shift;
local $@;
if ($opts{'E'})
{
eval {if ($pattern) {}};
Report_And_Exit "The match condition \"$pattern\" is invalid.\n" if $@;
}
elsif ($pattern ne $NO_PATTERN)
{
eval {'string' =~ /$pattern/};
Report_And_Exit "The pattern \"$pattern\" is invalid.\n" if $@;
}
}
#-------------------------------------------------------------------------------
# Get a list of files, taking recursion into account if necessary.
sub Get_Files
{
my @files_and_directories = @_;
# We just return what we were given unless we need to recurse subdirectories.
return @files_and_directories unless $opts{'R'};
my @files;
foreach my $arg (@files_and_directories)
{
if (-f $arg)
{
push @files, $arg;
}
elsif( -d $arg || -l $arg && $opts{'L'} )
{
dprint "Recursing directory $arg looking for files..."
if -d $arg;
dprint "Following symbolic link $arg looking for files..."
if -l $arg;
unless (eval {require File::Find})
{
Report_And_Exit("You specified -R or -L, but do not have File::Find. " .
"Get it from CPAN.\n");
}
import File::Find;
# Gets all plain files in directory and descendents. Puts them in @files
$File::Find::name = '';
my $wanted = sub { push @files,$File::Find::name if -f $_ };
if ($opts{'L'})
{
find({ wanted => $wanted, follow => 1, follow_skip => 2 }, $arg);
}
else
{
find({ wanted => $wanted }, $arg);
}
}
else
{
# Ignore unknown file types
}
}
return @files;
}
#-------------------------------------------------------------------------------
sub Same_Inode {
my $fh1 = shift;
my $fh2 = shift;
return 0 unless defined $fh1 && defined $fh2;
my ($device1, $inode1) = (stat($fh1))[0,1];
my ($device2, $inode2) = (stat($fh2))[0,1];
return $device1 == $device2 && $inode1 == $inode2;
}
#-------------------------------------------------------------------------------
sub Validate_Files_Are_Not_Output {
my @files = @_;
# Doesn't work properly on Windows for some reason
return if $^O eq 'MSWin32';
foreach my $file (@files) {
my $fh = new FileHandle($file);
if (Same_Inode($fh, *STDOUT)) {
Report_And_Exit("Input file $file is also standard output");
}
if (Same_Inode($fh, *STDERR)) {
Report_And_Exit("Input file $file is also standard error");
}
}
}
#-------------------------------------------------------------------------------
sub Handle_Input_Files
{
my $pattern = pop @_;
my @files = @_;
# For each input file...
foreach my $file (@files)
{
dprint '#'x70;
dprint "Processing file $file";
# First of all, silently ignore empty files...
next if -z $file;
# ...and also ignore directories.
if (-d $file)
{
warn "grepmail: Skipping directory: '$file'\n" unless $opts{'q'};
next;
}
$file = Search_Mailbox_Directories($file) unless -f $file;
Process_Mail_File(undef,$file,$#files+1,$pattern);
}
}
#-------------------------------------------------------------------------------
sub Search_Mailbox_Directories
{
my $file = shift;
my @maildirs;
push @maildirs, $ENV{'MAILDIR'}
if defined $ENV{'MAILDIR'} && -d $ENV{'MAILDIR'};
push @maildirs, "$ENV{HOME}/mail"
if defined $ENV{'HOME'} && -d "$ENV{HOME}/mail";
push @maildirs, "$ENV{HOME}/Mail"
if defined $ENV{'HOME'} && -d "$ENV{HOME}/Mail";
push @maildirs, "$ENV{HOME}/Mailbox"
if defined $ENV{'HOME'} && -d "$ENV{HOME}/Mailbox";
foreach my $mail_folder (@maildirs)
{
my $path_and_file = "$mail_folder/$file";
return $path_and_file if -e $path_and_file;
}
return $file;
}
#-------------------------------------------------------------------------------
sub Handle_Standard_Input
{
my $pattern = shift;
dprint "Handling STDIN";
# We have to implement our own -B and -s, because STDIN gets eaten by them
binmode STDIN;
my $fileHandle = new FileHandle;
$fileHandle->open('-');
Process_Mail_File($fileHandle,undef,1,$pattern);
}
#-------------------------------------------------------------------------------
# This algorithm is complicated by code to short-circuit some
# computations. For example, if the user specified -h but not -b, when
# we can analyze the header for a match and avoid needing to search
# the body, which may be much larger.
sub Do_Simple_Pattern_Matching
{
my $email_header = shift;
my $email_body = shift;
my $fileHandle = shift;
my $fileName = shift;
my $number_files = shift;
my $numberOfMatches = shift;
my $line = shift;
my $endline = shift;
my $pattern = shift;
die unless ref $email_header && ref $email_body;
return ($CONTINUE,$numberOfMatches) if $pattern eq $NO_PATTERN;
dprint "Checking for early match or abort based on header information."
if $opts{'D'};
my ($result,$matchesHeader) =
Analyze_Header($email_header,$email_body,$fileHandle,$pattern,1,$endline);
if ($result == $SKIP)
{
dprint "Doing an early abort based on header." if $opts{'D'};
return ($CONTINUE,$numberOfMatches);
}
if ($result == $PRINT)
{
dprint "Doing an early printout based on header." if $opts{'D'};
if ($opts{'l'})
{
print Get_Filename($fileName)."\n";
# We can return since we found at least one email that matches.
return ($DONE,$numberOfMatches);
}
elsif ($opts{'r'})
{
$numberOfMatches++;
return ($CONTINUE,$numberOfMatches);
}
else
{
Convert_Email_To_Mbox_And_Print_It($fileName,$email_header,
$email_body,$number_files,$line,$endline)
if $opts{'u'} && Not_A_Duplicate($email_header) || !$opts{'u'};
return ($CONTINUE,$numberOfMatches);
}
}
#----------------------------------------------------------------
my $matchesBody = 0;
my $signature_offset = undef;
if ($opts{'S'})
{
my $signature_pattern = $opts{'X'};
$signature_pattern =~ s#\$#$/#;
if ($$email_body =~ m/($signature_pattern)/mg)
{
$signature_offset = pos($$email_body) - length($1);
pos($$email_body) = 0;
dprint "Signature offset: $signature_offset";
}
}
# Ignore the MIME attachments if -M was specified
if ($opts{'M'} &&
($$email_header =~ /^Content-Type:.*?boundary=(?:"([^"]*)"|([^\r\n]*))/ism))
{
my $boundary;
$boundary = $1 if defined $1;
$boundary = $2 if defined $2;
dprint "Found attachments with boundary:\n $boundary" if $opts{'D'};
my @attachment_positions;
# Get each of the binary attachment beginnings and endings.
while ($$email_body =~ m/\n((?:--)?\Q$boundary\E(?:--)?$endline(?:(.*?)$endline$endline)?)/sg)
{
my $header = $2;
# The beginning of this attachment is the end of the previous.
$attachment_positions[$#attachment_positions]{'end'} = pos($$email_body) - length($1)
if @attachment_positions;
$attachment_positions[$#attachment_positions+1]{'beginning'} = pos($$email_body);
# If it's the beginning of a binary attachment, store the position
if (defined $header && $header =~ /^Content-Type:\s+(?!text)/i)
{
$attachment_positions[-1]{'type'} = 'binary';
}
else
{
$attachment_positions[-1]{'type'} = 'text';
}
}
# The last boundary terminates the attachments.
pop @attachment_positions;
@attachment_positions = grep { $_->{'type'} eq 'binary' } @attachment_positions;
pos($$email_body) = 0;
# Now search the body, ignoring any matches in binary
# attachments.
# Avoid perl 5.6 bug which causes spurious warning even though
# $pattern is defined.
local $^W = 0 if $] >= 5.006 && $] < 5.8;
SEARCH: while ($$email_body =~ m/($pattern)/omg)
{
my $position = pos($$email_body) - length($1);
last SEARCH if $opts{'S'} &&
defined $signature_offset && $position > $signature_offset;
foreach my $attachment (@attachment_positions)
{
next SEARCH
if ($position > $attachment->{'beginning'} &&
$position < $attachment->{'end'});
}
$matchesBody = 1;
last;
}
pos($$email_body) = 0;
}
else
{
# Avoid perl 5.6 bug which causes spurious warning even though
# $pattern is defined.
local $^W = 0 if $] >= 5.006 && $] < 5.8;
pos($$email_body) = 0;
if ($$email_body =~ m/($pattern)/omg)
{
my $position = pos($$email_body) - length($1);
$matchesBody = 1 unless $opts{'S'} &&
defined $signature_offset && $position > $signature_offset;
}
pos($$email_body) = 0;
}
#----------------------------------------------------------------
my $matchesSize =
Is_In_Size($email_header,$email_body,$sizeRestriction,$size1,$size2);
#----------------------------------------------------------------
dprint "Checking for early match or abort based on header, body, " .
"and size information." if $opts{'D'};
my $isMatch = 1;
$isMatch = 0 if $opts{'s'} && !$matchesSize ||
$opts{'b'} && !$matchesBody ||
$opts{'h'} && !$matchesHeader ||
!$opts{'b'} && !$opts{'h'} && !($matchesBody || $matchesHeader);
if (!$isMatch && !$opts{'v'})
{
dprint "Doing an early abort based on header, body, and size."
if $opts{'D'};
return ($CONTINUE,$numberOfMatches);
}
elsif (!$isMatch && $opts{'v'})
{
dprint "Doing an early printout based on header, body, and size."
if $opts{'D'};
if ($opts{'l'})
{
print Get_Filename($fileName)."\n";
# We can return since we found at least one email that matches.
return ($DONE,$numberOfMatches);
}
elsif ($opts{'r'})
{
$numberOfMatches++;
return ($CONTINUE,$numberOfMatches);
}
else
{
Convert_Email_To_Mbox_And_Print_It($fileName,$email_header,
$email_body,$number_files,$line,$endline)
if $opts{'u'} && Not_A_Duplicate($email_header) || !$opts{'u'};
return ($CONTINUE,$numberOfMatches);
}
}
#----------------------------------------------------------------
dprint "Checking date constraint." if $opts{'D'};
$isMatch = 1;
{
my $matchesDate = Email_Matches_Date($email_header,$endline);
$isMatch = 0 if defined $opts{'d'} && !$matchesDate;
dprint "Email matches date constraint\n"
if $opts{'D'} && defined $opts{'d'} && $matchesDate;
dprint "Email doesn't match date constraint\n"
if $opts{'D'} && defined $opts{'d'} && !$matchesDate;
}
$isMatch = !$isMatch if $opts{'v'};
# If the match occurred in the right place...
if ($isMatch)
{
dprint "Email matches all patterns and constraints." if $opts{'D'};
if ($opts{'l'})
{
print Get_Filename($fileName)."\n";
# We can return since we found at least one email that matches.
return ($DONE,$numberOfMatches);
}
elsif ($opts{'r'})
{
$numberOfMatches++;
}
else
{
Convert_Email_To_Mbox_And_Print_It($fileName,$email_header,
$email_body,$number_files,$line,$endline)
if $opts{'u'} && Not_A_Duplicate($email_header) || !$opts{'u'};
}
}
else
{
dprint "Email did not match all patterns and constraints." if $opts{'D'};
}
return ($CONTINUE,$numberOfMatches);
}
#-------------------------------------------------------------------------------
# This algorithm is complicated by code to short-circuit some
# computations. For example, if the user specified -h but not -b, when
# we can analyze the header for a match and avoid needing to search
# the body, which may be much larger.
sub Do_Complex_Pattern_Matching
{
my $email_header = shift;
my $email_body = shift;
my $fileHandle = shift;
my $fileName = shift;
my $number_files = shift;
my $numberOfMatches = shift;
my $line = shift;
my $endline = shift;
my $pattern = shift;
die unless ref $email_header && ref $email_body;
return ($CONTINUE,$numberOfMatches) if $pattern eq $NO_PATTERN;
dprint "Checking for early match or abort based on header information."
if $opts{'D'};
my ($result,$matchesHeader) =
Analyze_Header($email_header,$email_body,$fileHandle,$pattern,0,$endline);
if ($result == $SKIP)
{
dprint "Doing an early abort based on header." if $opts{'D'};
return ($CONTINUE,$numberOfMatches);
}
if ($result == $PRINT)
{
dprint "Doing an early printout based on header." if $opts{'D'};
if ($opts{'l'})