-
Notifications
You must be signed in to change notification settings - Fork 27
/
imapfilter.pl
2242 lines (1809 loc) · 55.5 KB
/
imapfilter.pl
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
# $Header: /mhub4/sources/imap-tools/imapfilter.pl,v 1.50 2016/03/10 14:35:51 rick Exp $
#######################################################################
# Program name imapfilter.pl #
# Written by Rick Sanders #
# #
# Description #
# #
# imapfilter is a tool for moving messages from one IMAP mailbox #
# to another based on a set of regular expressions. The "rules" #
# file defines the actions to be taken: #
# #
# Header-field<tab>String<tab>source mbx<tab>destination mbx #
# #
# Header-fields are the keywords in an SMTP message header, for #
# example From, Subject, To, cc, etc. A destination mailbox may #
# a local one or on a remote IMAP server. Connection information #
# for remote servers is provided by the "RemoteServer" keyword in #
# the rules file, eg RemoteServer: myhost/myuser/mypassword. A #
# remote mailbox is defined in the rules as remotehost:mbx_name. #
# #
# ./imapfilter.pl -S host/user/password -r <rules file> [-d] [-I] #
# #
# Optional arguments: #
# -d debug #
# -I show IMAP protocol exchanges #
# #
# Notes on Date comparision operations. imapfilter permits you #
# to filter on dates which are earlier, later, or the same as a #
# specified date. The date in the rules must be in RFC822 Mail #
# date format (eg, 12 Nov 2009 12:45:10 +0500) or expressed as an #
# offset from the current date (eg +30 meaning within the past 30 #
# days). Some examples: #
# #
# Date ">22 Dec 2008 15:00:00 +0000" INBOX MOVED #
# Date "<15 Jan 2009 00:00:00 +0500" INBOX MOVED #
# Date "=25 Dec 2009 08:00:00 +0500" INBOX MOVED #
# Date ">+60" INBOX MOVED #
# Date "*2009*" DATE INBOX #
#######################################################################
use Socket;
use FileHandle;
use Fcntl;
use Getopt::Std;
use IO::Socket;
use MIME::Base64 qw( encode_base64 decode_base64);
#################################################################
# Main program. #
#################################################################
init();
sigprc();
getRules( \@rules, \%remhosts );
usage() if !$host;
foreach $user ( @users ) {
Log("$user");
$total = 0;
remoteConnections( \%remhosts ) if %remhosts;
connectToHost($host, \$conn) or die;
login( $user, $conn) or next;
@mbxs = expandRules( \@rules, $user, $conn );
foreach $rule ( @rules ) { Log("rule $rule"); }
$marked = evaluateRules( \@mbxs, $conn, \%moves );
Log("expunge_trash $expunge_trash") if $debug;
if ( $expunge_trash and !$test ) {
expunge_trash( $expunge_trash, $conn);
}
logout( $conn );
foreach $host ( keys %connections ) {
logout( $host );
}
if ( $test ) {
Log("Would have moved $total_moved messages");
} else {
Log("$total_moved total messages moved");
}
Log("Done");
}
exit;
sub init {
$version = 'V1.0.1';
$os = $ENV{'OS'};
processArgs();
if ($timeout eq '') { $timeout = 60; }
# Open the logFile
#
if ( $logfile ) {
if ( !open(LOG, ">>$logfile")) {
print STDERR "Can't open $logfile: $!\n";
}
select(LOG); $| = 1;
}
Log("$0 starting");
Log("Running in test mode, no messages will actually be moved") if $test;
$total=0;
# Determine whether we have SSL support via openSSL and IO::Socket::SSL
$ssl_installed = 1;
eval 'use IO::Socket::SSL';
if ( $@ ) {
$ssl_installed = 0;
}
if ( $users_file ) {
($sourceHost) = split(/\//, $opt_S);
if ( !open(U, "<$users_file") ) {
print STDERR "Error opening users file $users_file: $!\n";
exit;
}
my $n;
while( <U> ) {
$n++;
s/^\s+//g;
next if /^#/;
chomp;
next unless $_;
push( @users, $_ );
}
close U;
} else {
($host,$user,$pwd) = split(/\//, $opt_S);
push( @users, "$user:$pwd" );
}
Log("Processing messages in batches of $chunk");
}
sub getRules {
my $rules = shift;
my $remhosts = shift;
my $fn;
my $line;
my $field;
$xdate=0;
if ( !open(R, "<$rulesfn") ) {
Log("Can't open rules file $rulesfn: $!");
exit;
}
while ( <R> ) {
$line++;
chomp;
s/^\s+//;
next if /^\#/;
next if $_ eq '';
if ( /^LocalServer:\s*(.+)\/(.+)\/(.+)/ ) {
# Local IMAP server connection info (can be supplied
# in the rules file or in the -S argument)
$host = $1;
$user = $2;
$pwd = $3;
} elsif ( /^RemoteServer:\s*(.+)\/(.+)\/(.+)/ ) {
# Remote IMAP server connection info
my $remhost = $1;
my $remuser = $2;
my $rempwd = $3;
($remhost,$remport) = split(/:/, $remhost);
$remport = 143 unless $remport;
$$remhosts{"$remhost"} = { port=>$remport, user=>$remuser, pwd=>$rempwd };
} elsif ( !/(.+)\t(.+)\t(.+)\t(.+)/ ) {
Log("Line $line in rules file is not in tab-delimited format");
exit;
} else {
($field) = split(/\t/, $_);
if ( lc($field) eq 'date' or lc($field) eq 'internaldate' ) {
$line = $_;
# Check for date comparison operator
$xdate = 1 if advanced_date_rule( $line );
}
}
if ( /\tcopy$/i ) {
# This is a 'copy' rule not a standard 'move' rule
s/\tcopy$//i;
$COPY{"$_"} = 1;
}
push( @$rules, "$_");
}
if ( $xdate ) {
my @modules = qw( DateTime DateTime::Format::Mail DateTime::Format::DateParse );
foreach $module ( @modules ) {
eval "use $module";
if ( $@ ) {
Log("\nIn order to do 'earlier than' and 'later than' filtering on the Date");
Log("field you must install the DateTime, DateTime::Format::Mail and");
Log("DateTime::Format::DateParse Perl modules.");
exit;
}
}
}
}
sub processArgs {
if ( !getopts( "dIS:D:L:r:tfc:u:E:X:T:" ) ) {
usage();
}
($host,$user,$pwd,$method) = split(/\//, $opt_S);
if ( uc( $method ) eq 'CRAM-MD5' ) {
$method = 'CRAM-MD5';
} elsif ( $host =~ /CRAM-MD5/i ) {
$method = 'CRAM-MD5';
$host =~ s/\/CRAM-MD5//i;
}
Log("Using CRAM-MD5 login method") if $method eq 'CRAM-MD5';
$logfile = $opt_L;
$rulesfn = $opt_r;
$chunk = $opt_c;
$users_file = $opt_u;
$admin_user = $opt_E;
$expunge_trash = $opt_X;
$debug = 1 if $opt_d;
$showIMAP = 1 if $opt_I;
$top_mbx = $opt_T;
$test = 1 if $opt_t; # Dry-run
$first_match = 1 if $opt_f; # Apply only the first match, ignore others.
$chunk = 500 unless $chunk; # How many messages we fetch at a time
usage() if $opt_h;
if ( !$rulesfn ) {
usage();
}
}
sub usage {
print STDOUT "usage:\n";
print STDOUT " imapfilter.pl -S host/sourceUser/sourcePassword ";
print STDOUT "-r <rules file>\n";
print STDOUT " Optional arguments:\n";
print STDOUT " -L logfile\n";
print STDOUT " -d debug\n";
print STDOUT " -E <admin_user:admin_pwd>\n";
print STDOUT " -I show IMAP protocol exchanges\n";
print STDOUT " -c <number> the number of messages processed at a time (default 500)\n";
print STDOUT " -t test mode (don't actually move the messages\n";
print STDOUT " -X <trash_mbx> expunge the Trash mbx, eg -X Trash\n\n";
print STDOUT " To use CRAM-MD5 for logins add /CRAM-MD5 like this -S host/user/pwd/CRAM-MD5\n\n";
exit;
}
# Log
#
# This subroutine formats and writes a log message to STDERR.
#
sub Log {
my $str = shift;
# If a logile has been specified then write the output to it
# Otherwise write it to STDOUT
if ( $use_utf7 ) {
$str = Unicode::IMAPUtf7::imap_utf7_decode( $str );
}
if ( $logfile ) {
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime;
if ($year < 99) { $yr = 2000; }
else { $yr = 1900; }
$line = sprintf ("%.2d-%.2d-%d.%.2d:%.2d:%.2d %s %s\n",
$mon + 1, $mday, $year + $yr, $hour, $min, $sec,$$,$str);
print LOG "$line";
} else {
print STDOUT "$str\n";
}
print STDOUT "$str\n";
}
sub sigprc {
$SIG{'HUP'} = 'dieright';
$SIG{'INT'} = 'dieright';
$SIG{'QUIT'} = 'dieright';
$SIG{'ILL'} = 'dieright';
$SIG{'TRAP'} = 'dieright';
$SIG{'IOT'} = 'dieright';
$SIG{'EMT'} = 'dieright';
$SIG{'FPE'} = 'dieright';
$SIG{'BUS'} = 'dieright';
$SIG{'SEGV'} = 'dieright';
$SIG{'SYS'} = 'dieright';
$SIG{'PIPE'} = 'dieright';
$SIG{'ALRM'} = 'dieright';
$SIG{'TERM'} = 'dieright';
$SIG{'URG'} = 'dieright';
}
# Make a connection to an IMAP host
sub connectToHost {
my $host = shift;
my $conn = shift;
Log("Connecting to $host") if $debug;
($host,$port) = split(/:/, $host);
$port = 143 unless $port;
Log("Connecting to host $host port $port");
# We know whether to use SSL for ports 143 and 993. For any
# other ones we'll have to figure it out.
$mode = sslmode( $host, $port );
if ( $mode eq 'SSL' ) {
unless( $ssl_installed == 1 ) {
warn("You must have openSSL and IO::Socket::SSL installed to use an SSL connection");
Log("You must have openSSL and IO::Socket::SSL installed to use an SSL connection");
exit;
}
Log("Attempting an SSL connection") if $debug;
$$conn = IO::Socket::SSL->new(
Proto => "tcp",
SSL_verify_mode => 0x00,
PeerAddr => $host,
PeerPort => $port,
Domain => AF_INET,
);
unless ( $$conn ) {
$error = IO::Socket::SSL::errstr();
Log("Error connecting to $host: $error");
exit;
}
} else {
# Non-SSL connection
Log("Attempting a non-SSL connection") if $debug;
$$conn = IO::Socket::INET->new(
Proto => "tcp",
PeerAddr => $host,
PeerPort => $port,
);
unless ( $$conn ) {
Log("Error connecting to $host:$port: $@");
warn "Error connecting to $host:$port: $@";
exit;
}
}
Log("Connected to $host on port $port") if $debug;
return 1;
}
# trim
#
# remove leading and trailing spaces from a string
sub trim {
local (*string) = @_;
$string =~ s/^\s+//;
$string =~ s/\s+$//;
return;
}
# login
#
# login in at the source host with the user's name and password
#
sub login {
my $user = shift;
my $conn = shift;
($user,$pwd) = split(/:/, $user, 2);
if ( uc( $method ) eq 'CRAM-MD5' ) {
# A CRAM-MD5 login is requested
my $rc = login_cram_md5( $user, $pwd, $conn );
return $rc;
}
if ( $admin_user ) {
# An AUTHENTICATE = PLAIN login has been requested
($authuser,$pwd) = split(/:/, $admin_user);
($user) = split(/:/, $user);
my $status = login_plain( $user, $authuser, $pwd, $conn );
return $status;
}
if ( $pwd =~ /^oauth2:(.+)/i ) {
# Do an oauth2 login
$pwd = $1;
$status = login_xoauth2( $user, $pwd, $conn );
return $status;
}
# Otherwise do a normal login
unless ( $user and $pwd ) {
Log("You must supply both user and password in the users file (user:pwd)");
return 0;
}
sendCommand ($conn, "1 LOGIN \"$user\" \"$pwd\"");
while (1) {
readResponse ( $conn );
if ($response =~ /^1 OK/i) {
last;
}
elsif ($response =~ /NO|BYE|BAD/) {
Log ("unexpected LOGIN response: $response");
return 0;
}
}
Log("Logged in as $user") if $debug;
return 1;
}
# login_plain
#
# login in at the source host with the user's name and password. If provided
# with administrator credential, use them as this eliminates the need for the
# user's password.
#
sub login_plain {
my $user = shift;
my $admin = shift;
my $pwd = shift;
my $conn = shift;
# Do an AUTHENTICATE = PLAIN. If an admin user has been provided then use it.
if ( !$admin ) {
# Log in as the user
$admin = $user
}
$login_str = sprintf("%s\x00%s\x00%s", $user,$admin,$pwd);
$login_str = encode_base64("$login_str", "");
$len = length( $login_str );
# sendCommand ($conn, "1 AUTHENTICATE PLAIN {$len}" );
sendCommand ($conn, "1 AUTHENTICATE PLAIN $login_str" );
my $loops;
while (1) {
readResponse ( $conn );
last if $response =~ /^1 OK/;
if ($response =~ /^1 NO|^1 BAD|^\* BYE/i) {
Log ("unexpected LOGIN response: $response");
exit;
}
$last if $loops++ > 5;
}
return 1;
}
# login_xoauth2
#
# login in at the source host with the user's name and an XOAUTH2 token.
#
sub login_xoauth2 {
my $user = shift;
my $token = shift;
my $conn = shift;
# Do an AUTHENTICATE = XOAUTH2 login
$login_str = encode_base64("user=". $user ."\x01auth=Bearer ". $token ."\x01\x01", '');
sendCommand ($conn, "1 AUTHENTICATE XOAUTH2 $login_str" );
my $loops;
while (1) {
readResponse ( $conn );
if ( $response =~ /^\+ (.+)/ ) {
$error = decode_base64( $1 );
Log("XOAUTH authentication as $user failed: $error");
return 0;
}
last if $response =~ /^1 OK/;
if ($response =~ /^1 NO|^1 BAD|^\* BYE|failed/i) {
Log ("unexpected LOGIN response: $response");
return 0;
}
$last if $loops++ > 5;
}
Log("login complete") if $debug;
return 1;
}
sub login_cram_md5 {
my $user = shift;
my $pwd = shift;
my $conn = shift;
sendCommand ($conn, "1 AUTHENTICATE CRAM-MD5");
while (1) {
readResponse ( $conn );
last if $response =~ /^\+/;
if ($response =~ /^1 NO|^1 BAD|^\* BYE/i) {
Log ("unexpected LOGIN response: $response");
return 0;
}
}
my ($challenge) = $response =~ /^\+ (.+)/;
Log("challenge $challenge") if $debug;
$response = cram_md5( $challenge, $user, $pwd );
Log("response $response") if $debug;
sendCommand ($conn, $response);
while (1) {
readResponse ( $conn );
if ( $response =~ /Microsoft Exchange/i and $conn eq $dst ) {
# The destination is an Exchange server
$exchange = 1;
Log("The destination is an Exchange server");
}
last if $response =~ /^1 OK/i;
if ($response =~ /^1 NO|^1 BAD|^\* BYE/i) {
Log ("unexpected LOGIN response: $response");
return 0;
}
}
Log("Logged in as $user") if $debug;
return 1;
}
sub cram_md5 {
my $challenge = shift;
my $user = shift;
my $password = shift;
eval 'use Digest::HMAC_MD5 qw(hmac_md5_hex)';
use MIME::Base64 qw(decode_base64 encode_base64);
# Adapated from script by Paul Makepeace <http://paulm.com>, 2002-10-12
# Takes user, key, and base-64 encoded challenge and returns base-64
# encoded CRAM. See,
# IMAP/POP AUTHorize Extension for Simple Challenge/Response:
# RFC 2195 http://www.faqs.org/rfcs/rfc2195.html
# SMTP Service Extension for Authentication:
# RFC 2554 http://www.faqs.org/rfcs/rfc2554.html
# Args: tim tanstaaftanstaaf PDE4OTYuNjk3MTcwOTUyQHBvc3RvZmZpY2UucmVzdG9uLm1jaS5uZXQ+
# should yield: dGltIGI5MTNhNjAyYzdlZGE3YTQ5NWI0ZTZlNzMzNGQzODkw
my $challenge_data = decode_base64($challenge);
my $hmac_digest = hmac_md5_hex($challenge_data, $password);
my $response = encode_base64("$user $hmac_digest");
chomp $response;
if ( $debug ) {
Log("Challenge: $challenge_data");
Log("HMAC digest: $hmac_digest");
Log("CRAM Base64: $response");
}
return $response;
}
# logout
#
# log out from the host
#
sub logout {
my $conn = shift;
@response = ();
sendCommand ($conn, "1 LOGOUT");
$counter=0;
while (1) {
readResponse ($conn);
last if $response =~ /1 OK/i;
last if $response =~ /1 NO/;
$counter++;
last if $counter > 100;
}
close $conn;
}
sub sslmode {
my $host = shift;
my $port = shift;
my $mode;
# Determine whether to make an SSL connection
# to the host. Return 'SSL' if so.
if ( $port == 143 ) {
# Standard non-SSL port
return '';
} elsif ( $port == 993 ) {
# Standard SSL port
return 'SSL';
}
unless ( $ssl_installed ) {
# We don't have SSL installed on this machine
return '';
}
# For any other port we need to determine whether it supports SSL
my $conn = IO::Socket::SSL->new(
Proto => "tcp",
SSL_verify_mode => 0x00,
PeerAddr => $host,
PeerPort => $port,
);
if ( $conn ) {
close( $conn );
$mode = 'SSL';
} else {
$mode = '';
}
return $mode;
}
sub namespace {
my $conn = shift;
my $prefix = shift;
my $delimiter = shift;
# Query the server with NAMESPACE so we can determine its
# mailbox prefix (if any) and hierachy delimiter.
@response = ();
sendCommand( $conn, "1 NAMESPACE");
while ( 1 ) {
readResponse( $conn );
if ( $response =~ /^1 OK/i ) {
last;
} elsif ( $response =~ /NO|BAD/i ) {
Log("Unexpected response to NAMESPACE command: $response");
last;
}
}
foreach $_ ( @response ) {
if ( /NAMESPACE/i ) {
my $i = index( $_, '((' );
my $j = index( $_, '))' );
my $val = substr($_,$i+2,$j-$i-3);
($val) = split(/\)/, $val);
($$prefix,$$delimiter) = split( / /, $val );
$$prefix =~ s/"//g;
$$delimiter =~ s/"//g;
last;
}
last if /^NO|^BAD/;
}
}
sub mailboxName {
my $srcmbx = shift;
my $srcPrefix = shift;
my $srcDelim = shift;
my $dstPrefix = shift;
my $dstDelim = shift;
my $dstmbx;
# Adjust the mailbox name if the source and destination server
# have different mailbox prefixes or hierarchy delimiters.
if ( $debug ) {
Log("src mbx $srcmbx");
Log("src prefix $srcPrefix");
Log("src delim $srcDelim");
Log("dst prefix $dstPrefix");
Log("dst delim $dstDelim");
}
if ( ($srcPrefix eq $dstPrefix) and ($srcDelim eq $dstDelim) ) {
# No adjustments necessary
$dstmbx = $srcmbx;
if ( $root_mbx ) {
# Put folders under a 'root' folder on the dst
$dstmbx =~ s/^$dstPrefix//;
$dstDelim =~ s/\./\\./g;
$dstmbx =~ s/^$dstDelim//;
$dstmbx = $dstPrefix . $root_mbx . $dstDelim . $dstmbx;
if ( uc($srcmbx) eq 'INBOX' ) {
# Special case for the INBOX
$dstmbx =~ s/INBOX$//i;
$dstmbx =~ s/$dstDelim$//;
}
$dstmbx =~ s/\\//g;
}
return $dstmbx;
}
$srcmbx =~ s#^$srcPrefix##;
$dstmbx = $srcmbx;
if ( $srcDelim ne $dstDelim ) {
# Need to substitute the dst's hierarchy delimiter for the src's one
$srcDelim = '\\' . $srcDelim if $srcDelim eq '.';
$dstDelim = "\\" . $dstDelim if $dstDelim eq '.';
$dstmbx =~ s#$srcDelim#$dstDelim#g;
$dstmbx =~ s/\\//g;
}
if ( $srcPrefix ne $dstPrefix ) {
# Replace the source prefix with the dest prefix
$dstmbx =~ s#^$srcPrefix## if $srcPrefix;
if ( $dstPrefix ) {
$dstmbx = "$dstPrefix$dstmbx" unless uc($srcmbx) eq 'INBOX';
}
$dstDelim = "\\$dstDelim" if $dstDelim eq '.';
$dstmbx =~ s#^$dstDelim##;
}
if ( $root_mbx ) {
# Put folders under a 'root' folder on the dst
$dstDelim =~ s/\./\\./g;
$dstmbx =~ s/^$dstPrefix//;
$dstmbx =~ s/^$dstDelim//;
$dstmbx = $dstPrefix . $root_mbx . $dstDelim . $dstmbx;
if ( uc($srcmbx) eq 'INBOX' ) {
# Special case for the INBOX
$dstmbx =~ s/INBOX$//i;
$dstmbx =~ s/$dstDelim$//;
}
$dstmbx =~ s/\\//g;
}
return $dstmbx;
}
#
# sendCommand
#
# This subroutine formats and sends an IMAP protocol command to an
# IMAP server on a specified connection.
#
sub sendCommand
{
local($fd) = shift @_;
local($cmd) = shift @_;
print $fd "$cmd\r\n";
if ($showIMAP) { Log (">> $cmd",2); }
}
#
# readResponse
#
# This subroutine reads and formats an IMAP protocol response from an
# IMAP server on a specified connection.
#
sub readResponse {
local($fd) = shift @_;
$response = <$fd>;
chop $response;
$response =~ s/\r//g;
push (@response,$response);
if ($showIMAP) { Log ("<< $response",2); }
}
sub expungeMbx {
my $mbx = shift;
my $conn = shift;
Log(" Expunging mailbox $mbx") if $debug;
sendCommand ($conn, "1 SELECT \"$mbx\"");
while (1) {
readResponse ($conn);
if ( $response =~ /^1 NO|^1 BAD/i ) {
Log("Unexpected EXPUNGE response: $response ");
return 0;
}
last if ( $response =~ /^1 OK/i );
}
sendCommand ( $conn, "1 EXPUNGE");
$expunged=0;
while (1) {
readResponse ($conn);
$expunged++ if $response =~ /\* (.+) Expunge/i;
last if $response =~ /^1 OK EXPUNGE complete/i;
last if $response =~ /^1 OK/;
if ( $response =~ /^1 BAD|^1 NO/i ) {
Log("Error purging messages: $response");
last;
}
}
$totalExpunged += $expunged;
}
sub expandRules {
my $rules = shift;
my $user = shift;
my $conn = shift;
my $expand;
my %mbxs;
# If a user has set a rule which applies to all mailboxes
# rather than just one then add a rule for each mailbox
my %mbxs;
# Do we have a "search all mbxs" rule?
foreach $rule ( @$rules ) {
($field,$search,$srcmbx,$dstmbx) = split(/\t/, $rule);
$mbxs{"$srcmbx"} = 1;
$expand = 1 if $srcmbx eq '*';
}
unless ( $expand ) {
# No need to change the rules
@mbxs = sort keys %mbxs;
return @mbxs;
}
# Get a list of the user's mailboxes
@mbxs = getMailboxList($user, $conn);
foreach $mbx ( @mbxs ) {
next if $nosel_mbxs{"$mbx"};
$mbxs{"$mbx"} = 1 unless $mbx eq '*';
}
delete $mbxs{"*"};
# Replace any 'search all mbxs" rules with a rule for
# each mailbox.
Log("Applying the rule to $top_mbx and its subfolders") if $top_mbx;
my @newrules;
foreach $rule ( @$rules ) {
($field,$search,$srcmbx,$dstmbx) = split(/\t/, $rule);
if ( $srcmbx eq '*' ) {
foreach $mbx ( @mbxs ) {
if ( $top_mbx ) {
if ( $mbx !~ /^$top_mbx/ ) {
delete $mbxs{"$mbx"};
next;
}
}
$newrule = "$field\t$search\t$mbx\t$dstmbx";
push ( @newrules, $newrule );
}
} else {
push( @newrules, $rule );
}
}
@$rules = @newrules;
if ( $debug ) {
foreach $rule ( @$rules ) { Log("Rule $rule"); }
}
@mbxs = sort keys %mbxs;
return @mbxs;
}
sub evaluateRules {
my $mbxs = shift;
my $conn = shift;
my $moves = shift;
my $marked = 0;
# Evaluate the messages in each mailbox against the rules
# and return a list of messages to be moved.
Log("Checking for filter matches");
%$moves = ();
@msgs = @moves = ();
foreach $mbx ( @$mbxs ) {
next unless mbxExists( $mbx, $conn );
$msgcount = count_msgs( $mbx, $conn );
Log("There are $msgcount msgs in $mbx");
next if $msgcount == 0;
%$moves=();
$i=0;
$start = 1;
$range = "$start:$chunk+1";
$end = $chunk;
$total_moved = 0;
foreach $rule ( @rules ) {
$i++;
($field,$search,$srcmbx,$dstmbx) = split(/\t/, $rule);
next if $srcmbx eq $dstmbx;
next unless lc($mbx) eq lc($srcmbx);
if ( $rule =~ /^ISEARCH/i ) {
# IMAP SEARCH
$rule = format_isearch_rule( $rule );
%moves = ();
$start = 1;
$range = "$start:$chunk";
while( 1 ) {
($moved,$total) = imap_search( $range, $rule, \%moves, $conn );
$total_moved += $moved;
moveMessages( $conn, \%moves, \%remhosts );
$start = $start + $chunk - $moved;
$start = 1 if $start == 0;
$end = $start + $chunk;
$end = $total if $end >= $total;
$range = "$start:$end";
last if $total <= 0;
last if $start >= $end;
}
moveMessages( $conn, \%moves, \%remhosts ) if %moved;
} else {
# Regular search
$total_moved = 0;
%moves = ();
$start = 1;
$range = "$start:$chunk";
while( 1 ) {
$total = getMsgList( $range, $field, $mbx, \@msgs, $conn );
$moved = get_matches( $field, $search, \@msgs, \%matches );
$total_moved += $moved;
moveMessages( $conn, \%matches, \%remhosts ) if $moved != 0;
$start = $start + $chunk - $moved;
$start = 1 if $start == 0;
$end = $start + $chunk;
$end = $total if $end >= $total;
$range = "$start:$end";
last if $total <= 0;
last if $start >= $end;
}
}
}