-
Notifications
You must be signed in to change notification settings - Fork 27
/
imapcopy_send.pl
executable file
·3267 lines (2622 loc) · 84.3 KB
/
imapcopy_send.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
use Socket;
use FileHandle;
use Fcntl;
use Getopt::Std;
use IO::Socket;
#################################################################
# Main program. #
#################################################################
$notify_file = 'imapcopy_notify.admin';
print "Looking for $notify_file\n";
if ( -e $notify_file ) {
print "Found $notify_file\n";
open(N, "<$notify_file") or print "Error opening $notify_file: $!\n";
chomp($notify = <N>);
print "notify line is $notify\n";
($smtp_server,$admin) = split(/:/, $notify);
print "smtp_server = $smtp_server\n";
print "admin addr = $admin\n";
send_mail( $smtp_server, $admin, "$user migrated", $message );
close N;
} else {
print "$notify_file was not found\n";
}
exit;
init();
# Get list of all messages on the source host
#
connectToHost($sourceHost, \$src) or exit 1;
login($sourceUser,$sourcePwd, $sourceHost, $src, $srcMethod) or exit 1;
namespace( $src, \$srcPrefix, \$srcDelim, $opt_x );
connectToHost( $destHost, \$dst ) or exit 1;
login( $destUser,$destPwd, $destHost, $dst, $dstMethod ) or exit 1;
namespace( $dst, \$dstPrefix, \$dstDelim, $opt_y );
@mbxs = getMailboxList( $srcPrefix, $src );
if ( $dovecot_mbox_format ) {
# Both the source and destination are dovecot servers with a mbox
# database. The mailboxes must be created in a special fashion).
create_dovecot_mbxs( \@mbxs, $dst );
}
get_dest_mailboxes( \%DST_MBXS, $dst );
if ( $debug ) {
Log("LIST THE DST MAILBOXES");
foreach $dstmbx ( keys %DST_MBXS ) {
Log(" dstmbx $dstmbx");
}
}
# Exclude certain mbxs if that's what the user wants
if ( $excludeMbxs or $excludeMbxs_regex ) {
exclude_mbxs( \@mbxs, $src );
}
map_mbx_names( \%mbx_map, $srcDelim, $dstDelim );
if ( $archive_dst_mbx ) {
# Create an archive mbx on the destination to receive copies of messsages
$stat = createMbx( $archive_dst_mbx, $dst );
}
if ( $archive_src_mbx ) {
# Create an archive mbx on the source to receive copies of messsages
$stat = createMbx( $archive_src_mbx, $src );
}
if ( $msgid_dbm_dir ) {
# Open a DBM to record msgids we copy
openDBM( $sourceUser );
}
$total=$mbxs_processed = 0;
my $delete_msg_list;
$num_mbxs = $#mbxs + 1;
Log("Number of mailboxes to process: $num_mbxs");
foreach $_ ( @mbxs ) { Log(" $_") if $debug; }
if ( $root_mbx ) {
$rmbx = $dstPrefix . $root_mbx;
unless ( $DST_MBXS{"$rmbx"} ) {
$stat = createMbx( $rmbx, $dst );
next if !$stat;
}
}
if ( $num_children ) {
@summary = copy_folders_parallel( \@mbxs );
} else {
foreach $srcmbx ( @mbxs ) {
$copied = copy_folder( $srcmbx, $src, $dst );
push( @summary, "Copied $copied messages from $srcmbx");
expungeMbx( $srcmbx, $src ) if $update_rm_src_msg;
}
}
Log("Done.");
Log("Summary");
Log("Copied $total total messages");
foreach $_ ( @summary ) {
Log(" $_");
}
if ( $ENV{'HTTP_CONNECTION'} ) {
@too_large_1 = @too_large;
notify_user( $sourceUser, $src, \@too_large, \@mbx_errors, 1 );
notify_user( $destUser, $dst, \@too_large_1, \@mbx_errors, 0 );
}
logout( $src );
logout( $dst );
exit;
sub init {
$os = $ENV{'OS'};
processArgs();
# Open the logFile
#
if ( $logfile ) {
if ( !open(LOG, ">> $logfile")) {
print STDOUT "Can't open $logfile: $!\n";
exit 1;
}
select(LOG); $| = 1;
}
Log("$0 starting");
Log("Running in update mode") if $update;
Log("Messages on the dest which are not on the source will be purged") if $del_from_dest;
Log("Only Seen messages will be copied") if $skip_unread;
Log("Only message headers will be copied") if $header_only;
Log("Messages will be removed from the source after they have been copied") if $rem_src_msgs;
Log("Duplicate msgs on the source will not be copied") if $dont_copy_source_dups;
Log("Copied msgs will be marked on the destinationas as SEEN") if $mark_as_seen;
if ( $special_search ) {
if ( $special_search !~ /SINCE|BEFORE/ ) {
Log("Error: Special search operators are SINCE and BEFORE.");
exit 1;
}
Log("Only those messages matching the date criteria $special_search will be copied");
}
# 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 ( $num_children ) {
if ( $OS =~ /Windows/i ) {
Log("The -Y <processes> option is not supported on Windows");
exit 1;
}
eval 'use Parallel::ForkManager';
if ( $@ ) {
Log("In order to run multiple copy processes you must install the Parallel::ForkManager Perl module.");
exit 1;
}
Log("Running in parallel mode, number of children = $num_children");
}
# Set up signal handling
$SIG{'ALRM'} = 'signalHandler';
$SIG{'HUP'} = 'signalHandler';
$SIG{'INT'} = 'signalHandler';
$SIG{'TERM'} = 'signalHandler';
$SIG{'URG'} = 'signalHandler';
if ( -e "imapcopy.skip" ) {
$skip_msgids = 1;
# Read a file of message-ids we were to skip
open( F, "<imapcopy.skip");
while( <F> ) {
chomp;
Log("putting $_ in skip file");
$SKIP{"$_"} = 1;
}
close F;
}
}
#
# sendCommand
#
# This subroutine formats and sends an IMAP protocol command to an
# IMAP server on a specified connection.
#
sub sendCommand {
my $fd = shift;
my $cmd = shift;
# If we've had to reconnect use the new connection
if ( $CONNECTIONS{"$fd"} ) {
$fd = $CONNECTIONS{"$fd"};
Log("Using the new connection $fd");
}
print $fd "$cmd\r\n";
Log (">> $cmd") if $showIMAP;
}
#
# readResponse
#
# This subroutine reads and formats an IMAP protocol response from an
# IMAP server on a specified connection.
#
sub readResponse {
my $fd = shift;
# If we've had to reconnect use the new connection
if ( $CONNECTIONS{"$fd"} ) {
$fd = $CONNECTIONS{"$fd"};
Log("Using the new connection $fd");
}
$response = <$fd>;
chop $response;
$response =~ s/\r//g;
push (@response,$response);
Log ("<< $response") if $showIMAP;
if ( $response =~ /\* BAD internal server error/i ) {
Log("Fatal IMAP server error: $response");
exit 1;
}
if ( $exchange and $response =~ /^1 NO|^1 BAD/ ) {
$errors++;
exchange_workaround() if $errors == 9;
}
if ( $response =~ /connection closed/i ) {
($src,$dst) = reconnect();
}
}
#
# Log
#
# This subroutine formats and writes a log message to STDERR.
#
sub Log {
my $str = shift;
# If a logfile has been specified then write the output to it
# Otherwise write it to STDOUT
if ( $str =~ /^\>\> 1 LOGIN (.+) "(.+)"/ ) {
# Obscure the password for security's sake
$str = ">> 1 LOGIN $1 XXXXX";
}
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\n",
$mon + 1, $mday, $year + $yr, $hour, $min, $sec,$str);
print LOG "$line";
}
select(STDOUT); $| = 1;
print STDOUT "$str\n" unless $quiet_mode;
$summary .= "$str\r\n";
}
sub today {
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime;
if ($year < 99) { $yr = 2000; }
else { $yr = 1900; }
my $today = sprintf ("%.2d-%.2d-%d", $mon + 1, $mday, $year + $yr);
return $today;
}
sub createMbx {
my $mbx = shift;
my $conn = shift;
# Create the mailbox if necessary
return 1 if uc( $mbx ) eq 'INBOX'; # Don't need to create an Inbox; it always exists
my $status = 1;
sendCommand ($conn, "1 CREATE \"$mbx\"");
while ( 1 ) {
readResponse ($conn);
last if $response =~ /^1 OK/i;
last if $response =~ /already exists/i;
if ( $response =~ /^1 NO|^1 BAD|^\* BYE/ ) {
Log ("Error creating $mbx: $response");
push( @mbx_errors, "$mbx: $response");
$status = 0;
last;
}
if ( $response eq '' or $response =~ /^1 NO/ ) {
Log ("unexpected CREATE response: >$response<");
Log("response is NULL");
($src,$dst) = reconnect();
last;
}
}
return $status;
}
# insertMsg
#
# This routine inserts a message into a user's mailbox
#
sub insertMsg {
local ($conn, $mbx, *message, $flags, $date) = @_;
local ($lenx);
$lenx = length($message);
Log(" Inserting message") if $debug;
$totalBytes = $totalBytes + $lenx;
$totalMsgs++;
$flags = flags( $flags );
fixup_date( \$date );
if ( $CONNECTIONS{"$conn"} ) {
$conn = $CONNECTIONS{"$conn"};
Log("Using the new connection $conn");
}
sendCommand ($conn, "1 APPEND \"$mbx\" ($flags) \"$date\" \{$lenx\}");
readResponse ($conn);
if ( $response !~ /^\+/ ) {
Log ("unexpected APPEND response: >$response<");
if ( $response =~ /^\* BYE/ ) {
Log("The server terminated our session");
exit 1;
}
if ( $response eq '' ) {
Log("response is NULL");
($src,$dst) = reconnect();
next;
}
push(@errors,"Error appending message to $mbx for $user");
return 0;
}
print $conn "$message\r\n";
undef @response;
my $loops;
while ( 1 ) {
readResponse ($conn);
$loops++;
exit 1 if $loops > 9;
if ( $response =~ /^1 OK/i ) {
last;
}
elsif ( $response !~ /^\*/ ) {
Log ("unexpected APPEND response: $response");
if ( $response eq '' ) {
Log("response is NULL");
($src,$dst) = reconnect();
}
next;
}
}
return 1;
}
# Make a connection to a IMAP host
sub connectToHost {
my $host = shift;
my $conn = shift;
Log("Connecting to $host") if $debug;
($host,$port) = split(/:/, $host);
$port = 143 unless $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 1;
}
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 1;
}
} 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 1;
}
}
# Log("Connected to $host on port $port");
}
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;
}
# 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 $pwd = shift;
my $host = shift;
my $conn = shift;
my $method = shift;
Log("method $method") if $debug;
return 1 if $method eq 'PREAUTH'; # Server pre-authenticates users
Log("Authenticating to $host as $user") if $debug;
if ( uc( $method ) eq 'CRAM-MD5' ) {
# A CRAM-MD5 login is requested
Log("login method $method");
my $rc = login_cram_md5( $user, $pwd, $conn );
return $rc;
}
if ( $pwd =~ /^oauth2:(.+)/i ) {
$token = $1;
Log("password is an OAUTH2 token");
login_xoauth2( $user, $token, $conn );
return 1;
}
if ( lc( $host ) eq 'imap.gmail.com:993' ) {
# Use AUTHENTICATE PLAIN with Gmail
login_plain( $user, $user, $pwd, $conn ) or exit 1;
return 1;
}
if ( $user =~ /(.+):(.+)/ ) {
# An AUTHENTICATE = PLAIN login has been requested
$sourceUser = $1;
$authuser = $2;
login_plain( $sourceUser, $authuser, $pwd, $conn ) or exit 1;
return 1;
}
# Otherwise do an ordinary login
sendCommand ($conn, "1 LOGIN $user \"$pwd\"");
while (1) {
readResponse ( $conn );
if ( $response =~ /Cyrus/i and $conn eq $dst ) {
Log("Destination is a Cyrus server");
$cyrus = 1;
}
if ( $response =~ /Microsoft Exchange/i and $conn eq $dst ) {
# The destination is an Exchange server
unless ( $exchange_override ) {
$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 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;
}
# 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" );
my $loops;
while (1) {
readResponse ( $conn );
last if $response =~ /\+/;
if ($response =~ /^1 NO|^1 BAD|^\* BYE/i) {
Log ("unexpected LOGIN response: $response");
exit 1;
}
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 $loops++ > 5;
}
sendCommand ($conn, "$login_str" );
my $loops;
while (1) {
readResponse ( $conn );
if ( $response =~ /Cyrus/i and $conn eq $dst ) {
Log("Destination is a Cyrus server");
$cyrus = 1;
}
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");
exit 1;
}
$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");
exit 1;
}
last if $response =~ /^1 OK/;
if ($response =~ /^1 NO|^1 BAD|^\* BYE|failed/i) {
Log ("unexpected LOGIN response: $response");
exit 1;
}
$last if $loops++ > 5;
}
Log("login complete") if $debug;
return 1;
}
# logout
#
# log out from the host
#
sub logout {
my $conn = shift;
undef @response;
sendCommand ($conn, "1 LOGOUT");
while ( 1 ) {
readResponse ($conn);
if ( $response =~ /^1 OK/i ) {
last;
}
elsif ( $response !~ /^\*/ ) {
Log ("unexpected LOGOUT response: $response");
last;
}
}
close $conn;
return;
}
# getMailboxList
#
# get a list of the user's mailboxes from the source host
#
sub getMailboxList {
my $prefix = shift;
my $conn = shift;
my $mbx_delimiter;
my @mbxs;
# Get a list of the user's mailboxes
#
Log("Get list of user's mailboxes",2) if $debugMode;
if ( $mbxList ) {
if ( $mbxList =~ /\|/ ) {
$mbx_delimiter = '|';
} else {
$mbx_delimiter = ',';
}
foreach $mbx ( split(/\Q$mbx_delimiter/, $mbxList) ) {
$mbx = encode( 'IMAP-UTF-7', $mbx ) unless isAscii( $srcmbx );
# $mbx = $prefix . $mbx if $prefix;
if ( $opt_R ) {
# Get all submailboxes under the ones specified
$mbx .= '*';
@mailboxes = listMailboxes( $mbx, $conn);
push( @mbxs, @mailboxes );
} else {
push( @mbxs, $mbx );
}
}
} else {
# Get all mailboxes
@mbxs = listMailboxes( '*', $conn);
}
return @mbxs;
}
# exclude_mbxs
#
# Exclude certain mailboxes from the list if the user has provided an
# exclude list of complete mailbox names with the -e argument. He may
# also supply a list of regular expressions with the -g argument
# which we will process separately.
sub exclude_mbxs {
my $mbxs = shift;
my $conn = shift;
my @new_list;
my %exclude;
my (@regex_excludes,@final_list);
# Do the exact matches first
if ( $excludeMbxs ) {
foreach my $exclude ( split(/,/, $excludeMbxs ) ) {
if ( $opt_R ) {
# Include all submailboxes
$exclude .= '*';
@mailboxes = listMailboxes( $exclude, $conn);
foreach $_ ( @mailboxes ) {
Log("Excluding $_") if $debug;
$exclude{"$_"} = 1;
}
} else {
Log("Excluding $exclude") if $debug;
$exclude{"$exclude"} = 1;
}
}
foreach my $mbx ( @$mbxs ) {
next if $exclude{"$mbx"};
push( @new_list, $mbx );
}
@$mbxs = @new_list;
}
# Next do the regular expressions if any
my %excludes;
@new_list = ();
if ( $excludeMbxs_regex ) {
my @regex_excludes;
foreach $_ ( split(/,/, $excludeMbxs_regex ) ) {
push( @regex_excludes, $_ );
}
foreach my $mbx ( @$mbxs ) {
foreach $_ ( @regex_excludes ) {
if ( $mbx =~ /$_/ ) {
$excludes{"$mbx"} = 1;
}
}
}
foreach my $mbx ( @$mbxs ) {
push( @new_list, $mbx ) unless $excludes{"$mbx"};
}
@$mbxs = @new_list;
}
@new_list = ();
}
# listMailboxes
#
# Get a list of the user's mailboxes
#
sub listMailboxes {
my $mbx = shift;
my $conn = shift;
my @mbxs;
sendCommand ($conn, "1 LIST \"\" \"$mbx\"");
undef @response;
while ( 1 ) {
&readResponse ($conn);
if ( $response =~ /\{(.+)\}$/ ) {
# The name of the mailbox is on the next line
&readResponse ($conn);
} elsif ( $response =~ /^1 OK/i ) {
last;
} elsif ( $response !~ /^\*/ ) {
&Log ("unexpected response: $response");
return 0;
}
}
@mbxs = ();
for $i (0 .. $#response) {
$response[$i] =~ s/\s+/ /;
if ( $response[$i] =~ /\{(.+)\}$/ ) {
# Mailbox name is on the next line
$mbx = $response[$i+1];
} elsif ( $response[$i] =~ /"$/ ) {
$response[$i] =~ /\* LIST \((.*)\) "(.+)" "(.+)"/i;
$mbx = $3;
} elsif ( $response[$i] =~ /\* LIST \((.*)\) NIL (.+)/i ) {
$mbx = $2;
} else {
$response[$i] =~ /\* LIST \((.*)\) "(.+)" (.+)/i;
$mbx = $3;
}
$mbx =~ s/^\s+//; $mbx =~ s/\s+$//;
if ($response[$i] =~ /NOSELECT/i) {
$nosel_mbxs{"$mbx"} = 1;
}
push ( @mbxs, $mbx ) if $mbx ne '';
}
return @mbxs;
}
# getMsgList
#
# Get a list of the user's messages in the indicated mailbox on
# the source host
#
sub getMsgList {
my $mailbox = shift;
my $msgs = shift;
my $conn = shift;
my $mode = shift;
my $seen;
my $empty;
my $msgnum;
my $from;
my $flags;
my $msgid;
my %MESSAGEIDS;
@$msgs = ();
$mode = 'SELECT' unless $mode;
sendCommand ($conn, "1 $mode \"$mailbox\"");
undef @response;
$empty=0;
while ( 1 ) {
readResponse ( $conn );
if ( $response =~ / 0 EXISTS/i ) { $empty=1; }
if ( $response =~ /^1 OK/i ) {
last;
}
elsif ( $response !~ /^\*/ ) {
Log ("unexpected response: $response");
return 0;
}
}
return 1 if $empty;
my $start = 1;
my $end = '*';
$start = $start_fetch if $start_fetch;
$end = $end_fetch if $end_fetch;
if ( $msgs_per_folder ) {
$start = 1;
$end = $msgs_per_folder;
}
sendCommand ( $conn, "1 FETCH $start:$end (uid flags internaldate RFC822.SIZE body.peek[header.fields (From Date Message-Id Subject)])");
@response = ();
my $nulls;
while ( 1 ) {
readResponse ( $conn );
if ( $response eq '' ) {
$nulls++;
if ( $nulls > 9 ) {
Log("server has stopped responding after $nulls loops");
($src,$dst) = reconnect();
return 0;
}
} else {
$nulls = 0;
}
if ( $response =~ /^1 OK/i ) {
last;
}
last if $response =~ /^1 NO|^1 BAD|^\* BYE/;
if ( $response =~ /^\* BYE/ ) {
Log("The server terminated our connection: $response");
exit 1;
}
}
$flags = '';