-
Notifications
You must be signed in to change notification settings - Fork 27
/
dumptoIMAP.pl
executable file
·1060 lines (868 loc) · 25.1 KB
/
dumptoIMAP.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/dumptoIMAP.pl,v 1.19 2015/12/04 20:47:26 rick Exp $
#######################################################################
# dumptoIMAP.pl is used to load the mailboxes and messages exported #
# from an IMAP server by the imapdump.pl script. See usage() notes #
# for a list of the arguments used to run it. #
# #
# If you ran imapdump.pl -S host/user/pwd -f /tmp/BACKUP #
# then you could restore all of the mailboxes & messages with the #
# following command: #
# #
# ./dumptoIMAP.pl -i host/user/pwd -D /tmp/BACKUP #
# #
# If you wanted to restore just the INBOX and the Sent mailboxes you #
# would add -m "INBOX,Sent" #
#######################################################################
use Socket;
use IO::Socket;
use FileHandle;
use File::Find;
use Fcntl;
use Getopt::Std;
use MIME::Base64 qw(decode_base64 encode_base64);
init();
connectToHost($imapHost, \$conn);
if ( $imapUser =~ /(.+):(.+)/ ) {
# An AUTHENTICATE = PLAIN login has been requested
$imapUser = $1;
$authuser = $2;
login_plain( $imapUser, $authuser, $imapPwd, $conn ) or exit;
} else {
if ( !login($imapUser,$imapPwd, $conn) ) {
Log("Check your username and password");
print STDOUT "Login failed: Check your username and password\n";
exit;
}
}
if ( $opt_y ) {
# User-supplied mbx delimiter and prefix
($mbx_delim,$prefix) = split(/\s+/, $opt_y );
} else {
namespace( $conn, \$prefix, \$mbx_delim );
}
Log("dir = $dir");
get_mbx_list( $dir, \@mbxs );
foreach $mbx ( @mbxs ) {
$copied=0;
Log("mbx = >$mbx<") if $debug;
Log("Full path to $mbx is >$dir/$mbx<") if $debug;
Log("Copying messages from $dir/$mbx to $mbx folder on the IMAP server");
get_messages( "$dir/$mbx", \@msgs );
$n = scalar @msgs;
Log("$mbx has $n messages");
$mbx =~ s/\//$mbx_delim/g unless $mbx_delim eq '/';
if ( $prefix ) {
$mbx = $prefix . $mbx unless $mbx =~ /^INBOX/i;
}
$dstmbx = add_root_mbx( $mbx, $root_mbx );
foreach $_ ( @msgs ) {
next unless $_;
my $msg; my $date; my $seen;
$flags = '';
if ( /,S$/ ) {
$flags = '\\SEEN';
}
Log("Opening $_") if $debug;
unless ( open(F, "<$_") ) {
Log("Error opening $_: $!");
next;
}
Log("Opened $_ successfully") if $debug;
while( <F> ) {
# Log("Reading line $_") if $debug;
if ( /^Date: (.+)/ ) {
$date = $1 unless $date;
$date =~ s/\r|\m//g;
chomp $date;
}
s/\r+$//g;
$msg .= $_;
chomp $msg;
$msg .= "\r\n";
}
close F;
$size = length( $msg );
Log("The message is $size bytes") if $debug;
# Log("$msg") if $debug;
if ( $size == 0 ) {
Log("The message file is empty") if $debug;
next;
}
$copied++ if insertMsg($dstmbx, \$msg, $flags, $date, $conn);
if ( $msgs_per_folder ) {
# opt_F allows us to limit number of messages copied per folder
last if $copied == $msgs_per_folder;
}
if ( $copied/100 == int($copied/100)) { Log("$copied messages copied "); }
}
$total += $copied;
}
logout( $conn );
Log("Done. $total messages were copied.");
exit;
sub init {
if ( !getopts('m:L:i:dD:Ix:XRA:F:y:r:') ) {
usage();
}
$mbx_list = $opt_m;
$dir = $opt_D;
$logfile = $opt_L;
$extension = $opt_x;
$debug = 1 if $opt_d;
$showIMAP = 1 if $opt_I;
$admin_user = $opt_A;
$msgs_per_folder = $opt_F;
$root_mbx = $opt_r;
($imapHost,$imapUser,$imapPwd) = split(/\//, $opt_i);
$method = 'CRAM-MD5' if $opt_i =~ /CRAM-MD5/i;
$imapHost =~ s/\/CRAM-MD5//i;
if ( $logfile ) {
if ( ! open (LOG, ">> $logfile") ) {
print "Can't open logfile $logfile: $!\n";
$logfile = '';
}
}
Log("Starting");
# Determine whether we have SSL support via openSSL and IO::Socket::SSL
$ssl_installed = 1;
eval 'use IO::Socket::SSL';
if ( $@ ) {
$ssl_installed = 0;
}
}
sub usage {
print "Usage: dumptoIMAP.pl\n";
print " -D <path to the mailboxes>\n";
print " -i <server/username/password>\n";
print " (if the password is an OAUTH2 token then prefix it with 'oauth2:'\n";
print " [-A <admin_user:admin_pwd>\n";
print " [-m <mbx1,mbx2,..,mbxn> copy only the listed mailboxes]\n";
print " [-x <extension> Import only files with this extension\n";
print " [-r root_mbx] put mailboxes under this root mailbox\n";
print " [-L <logfile>]\n";
print " [-d debug]\n";
print " [-I log IMAP protocol exchanges]\n";
print "To use CRAM-MD5 for logins add /CRAM-MD5 like this: -i server/user/password/CRAM-MD5\n";
}
sub get_messages {
my $dir = shift;
my $msgs = shift;
# Get a list of the message files
if ( $debug ) {
Log("Get list of messages in $dir");
}
opendir D, $dir;
my @files = readdir( D );
closedir D;
foreach $_ ( sort @files ) {
next if /^\./;
if ( $extension ) {
next unless /$extension$/;
}
Log(" $dir/$_") if $debug;
push( @$msgs, "$dir/$_");
}
}
# Print a message to STDOUT and to the logfile if
# the opt_L option is present.
#
sub Log {
my $line = shift;
my $msg;
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime (time);
$msg = sprintf ("%.2d-%.2d-%.4d.%.2d:%.2d:%.2d %s",
$mon + 1, $mday, $year + 1900, $hour, $min, $sec, $line);
if ( $logfile ) {
print LOG "$msg\n";
}
print STDOUT "$line\n";
}
# connectToHost
#
# Make an IMAP connection to a host
#
sub connectToHost {
my $host = shift;
my $conn = shift;
Log("Connecting to $host") if $debug;
$sockaddr = 'S n a4 x8';
($name, $aliases, $proto) = getprotobyname('tcp');
($host,$port) = split(/:/, $host);
$port = 143 unless $port;
if ($host eq "") {
Log ("no remote host defined");
close LOG;
exit (1);
}
# 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;
}
}
select( $$conn ); $| = 1;
return 1;
}
#
# login in at the IMAP host with the user's name and password
#
sub login {
my $user = shift;
my $pwd = shift;
my $conn = shift;
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 ( $admin_user ) {
# An AUTHENTICATE = PLAIN login has been requested
($authuser,$authpwd) = split(/:/, $admin_user );
login_plain( $user, $authuser, $authpwd, $conn ) or exit;
return 1;
}
if ( $pwd =~ /^oauth2:(.+)/i ) {
$token = $1;
Log("password is an OAUTH2 token");
login_xoauth2( $user, $token, $conn );
return 1;
}
Log("Logging in as $user") if $debug;
$rsn = 1;
sendCommand ($conn, "$rsn LOGIN $user $pwd");
while (1) {
readResponse ( $conn );
if ($response =~ /^$rsn OK/i) {
last;
}
elsif ($response =~ /NO/) {
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");
exit;
}
last if $response =~ /^1 OK/;
if ($response =~ /^1 NO|^1 BAD|^\* BYE|failed/i) {
Log ("unexpected LOGIN response: $response");
exit;
}
$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;
++$lsn;
undef @response;
sendCommand ($conn, "$lsn LOGOUT");
while ( 1 ) {
readResponse ($conn);
if ( $response =~ /^$lsn OK/i ) {
last;
}
elsif ( $response !~ /^\*/ ) {
Log ("unexpected LOGOUT response: $response");
last;
}
}
close $conn;
return;
}
# readResponse
#
# This subroutine reads and formats an IMAP protocol response from an
# IMAP server on a specified connection.
#
sub readResponse {
my $fd = shift;
$response = <$fd>;
chop $response;
$response =~ s/\r//g;
push (@response,$response);
Log(">>$response") if $showIMAP;
}
#
# 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;
print $fd "$cmd\r\n";
Log(">>$cmd") if $showIMAP;
}
#
# insertMsg
#
# Append a message to an IMAP mailbox
#
sub insertMsg {
my $mbx = shift;
my $message = shift;
my $flags = shift;
my $date = shift;
my $conn = shift;
my ($lsn,$lenx);
Log(" Inserting message") if $debug;
$lenx = length($$message);
# Log("$$message");
($date) = split(/\s*\(/, $date);
if ( $date =~ /,/ ) {
$date =~ /(.+),\s+(.+)\s+(.+)\s+(.+)\s+(.+)\s+(.+)/;
$date = "$2-$3-$4 $5 $6";
} else {
$date =~ s/\s/-/;
$date =~ s/\s/-/;
}
# Create the mailbox unless we have already done so
++$lsn;
if ($destMbxs{"$mbx"} eq '') {
sendCommand ($conn, "$lsn CREATE \"$mbx\"");
while ( 1 ) {
readResponse ($conn);
if ( $response =~ /^$rsn OK/i ) {
last;
}
elsif ( $response !~ /^\*/ ) {
if (!($response =~ /already exists|reserved mailbox name/i)) {
Log ("WARNING: $response");
}
last;
}
}
# Subscribe to the mailbox
sendCommand( $conn, "1 SUBSCRIBE \"$mbx\"");
my $loops;
while ( 1 ) {
readResponse( $conn );
if ( $response =~ /^1 OK/i ) {
Log("Mailbox $mbx has been subscribed") if $debug;
last;
} elsif ( $response =~ /^1 NO|^1 BAD|\^* BYE/i ) {
Log("Unexpected response to subscribe $mbx command: $response");
last;
}
last if $loops++ > 99;
}
}
$destMbxs{"$mbx"} = '1';
$flags =~ s/\\Recent//i;
if ( $date ) {
$cmd = "1 APPEND \"$mbx\" ($flags) \"$date\" \{$lenx\}";
} else {
$cmd = "1 APPEND \"$mbx\" ($flags) \{$lenx\}";
}
sendCommand ($conn, $cmd);
readResponse ($conn);
if ( $response !~ /^\+/ ) {
Log ("unexpected APPEND response to $cmd");
push(@errors,"Error appending message to $mbx for $user");
return 0;
}
if ( $opt_X ) {
print $conn "$$message\n";
} else {
print $conn "$$message\r\n";
}
undef @response;
while ( 1 ) {
readResponse ($conn);
if ( $response =~ /^$lsn OK/i ) {
last;
}
elsif ( $response !~ /^\*/ ) {
Log ("unexpected APPEND response: $response");
return 0;
}
}
return 1;
}
# getMsgList
#
# Get a list of the user's messages in the indicated mailbox on
# the IMAP host
#
sub getMsgList {
my $mailbox = shift;
my $msgs = shift;
my $conn = shift;
my $seen;
my $empty;
my $msgnum;
Log("Getting list of msgs in $mailbox") if $debug;
trim( *mailbox );
sendCommand ($conn, "$rsn EXAMINE \"$mailbox\"");
undef @response;
$empty=0;
while ( 1 ) {
readResponse ( $conn );
if ( $response =~ / 0 EXISTS/i ) { $empty=1; }
if ( $response =~ /^$rsn OK/i ) {
last;
}
elsif ( $response !~ /^\*/ ) {
Log ("unexpected response: $response");
return 0;
}
}
sendCommand ( $conn, "$rsn FETCH 1:* (uid flags internaldate body[header.fields (Message-Id)])");
undef @response;
while ( 1 ) {
readResponse ( $conn );
if ( $response =~ /^$rsn OK/i ) {
last;
}
}
# Get a list of the msgs in the mailbox
#
undef @msgs;
undef $flags;
for $i (0 .. $#response) {
$seen=0;
$_ = $response[$i];
last if /OK FETCH complete/;
if ( $response[$i] =~ /FETCH \(UID / ) {
$response[$i] =~ /\* ([^FETCH \(UID]*)/;
$msgnum = $1;
}
if ($response[$i] =~ /FLAGS/) {
# Get the list of flags
$response[$i] =~ /FLAGS \(([^\)]*)/;
$flags = $1;
$flags =~ s/\\Recent//i;
}
if ( $response[$i] =~ /INTERNALDATE ([^\)]*)/ ) {
### $response[$i] =~ /INTERNALDATE (.+) ([^BODY]*)/i;
$response[$i] =~ /INTERNALDATE (.+) BODY/i;
$date = $1;
$date =~ s/"//g;
}
if ( $response[$i] =~ /^Message-Id:/i ) {
($label,$msgid) = split(/: /, $response[$i]);
push (@$msgs,$msgid);
}
}
}
# trim
#
# remove leading and trailing spaces from a string
sub trim {
local (*string) = @_;
$string =~ s/^\s+//;
$string =~ s/\s+$//;
return;
}
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 get_mbx_list {
my $dir = shift;
my $mbxs = shift;
my %MBXS;
if ( $mbx_list ) {
# The user has supplied a list of mailboxes.
@$mbxs = split(/,/, $mbx_list );
return;
}
@dirs = ();
push( @dirs, $dir );
@messages = ();
find( \&findMsgs, @dirs ); # Returns @messages
$n = scalar @messages;
Log("There are $n messages");
foreach $fn ( @messages ) {
Log("fn = $fn") if $debug;
$fn =~ s/$dir//;
Log("fn = $fn") if $debug;
$i = rindex($fn,'/');
Log("find rightmost slash, i = $i") if $debug;
if ( $fn =~ /^\// ) {
$mbx = substr($fn,1,$i);
} else {
$mbx = substr($fn,0,$i);
}
Log("mbx = $mbx") if $debug;
$mbx =~ s/\/$//;
Log("mbx = >$mbx<") if $debug;
push( @$mbxs, $mbx ) if !$MBXS{"$mbx"};
Log("Add >$mbx< to the list of mailboxes") if $debug;
$MBXS{"$mbx"} = 1;
}
}
sub findMsgs {
return if not -f;
my $fn = $File::Find::name;
push( @messages, $fn );
}
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 =~ /^1 NO|^1 BAD|^\* BYE/i ) {
Log("Unexpected response to NAMESPACE command: $response");
Log("Cannot determine the mailbox delimiter and prefix. Use -y '<delimiter prefix>' to supply it");
exit;
}
}
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;
# Experimental
if ( $public_mbxs ) {
# Figure out the public mailbox settings
/\(\((.+)\)\)\s+\(\((.+)\s+\(\((.+)\)\)/;
$public = $3;
$public =~ /"(.+)"\s+"(.+)"/;
$src_public_prefix = $1 if $conn eq $src;
$src_public_delim = $2 if $conn eq $src;
$dst_public_prefix = $1 if $conn eq $dst;
$dst_public_delim = $2 if $conn eq $dst;
}
last;
}
last if /^1 NO|^1 BAD|^\* BYE/;
}
unless ( $$delimiter ) {
# NAMESPACE command is not supported by the server
# so we will have to figure it out another way.
$delim = getDelimiter( $conn );
$$delimiter = $delim;
$$prefix = '';
}
if ( $debug ) {
Log("prefix >$$prefix<");
Log("delim >$$delimiter<");
}
}
sub mailboxName {
my $srcmbx = shift;
my $srcPrefix = shift;
my $srcDelim = shift;
my $dstPrefix = shift;
my $dstDelim = shift;
my $dstmbx;
my $substChar = '_';
if ( $public_mbxs ) {
my ($public_src,$public_dst) = split(/:/, $public_mbxs );
# If the mailbox starts with the public mailbox prefix then
# map it to the public mailbox destination prefix
if ( $srcmbx =~ /^$public_src/ ) {
Log("src: $srcmbx is a public mailbox") if $debug;
$dstmbx = $srcmbx;
$dstmbx =~ s/$public_src/$public_dst/;
Log("dst: $dstmbx") if $debug;
return $dstmbx;
}
}
# Change the mailbox name if the user has supplied mapping rules.
if ( $mbx_map{"$srcmbx"} ) {
$srcmbx = $mbx_map{"$srcmbx"}
}
# Adjust the mailbox name if the source and destination server
# have different mailbox prefixes or hierarchy delimiters.
if ( ($srcmbx =~ /[$dstDelim]/) and ($dstDelim ne $srcDelim) ) {
# The mailbox name has a character that is used on the destination
# as a mailbox hierarchy delimiter. We have to replace it.
$srcmbx =~ s^[$dstDelim]^$substChar^g;
}
if ( $debug ) {
Log("src mbx $srcmbx");
Log("src prefix $srcPrefix");
Log("src delim $srcDelim");
Log("dst prefix $dstPrefix");
Log("dst delim $dstDelim");
}
$srcmbx =~ s/^$srcPrefix//;
$srcmbx =~ s/\\$srcDelim/\//g;
if ( ($srcPrefix eq $dstPrefix) and ($srcDelim eq $dstDelim) ) {
# No adjustments necessary
# $dstmbx = $srcmbx;
if ( lc( $srcmbx ) eq 'inbox' ) {
$dstmbx = $srcmbx;
} else {
$dstmbx = $srcPrefix . $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$//;