-
Notifications
You must be signed in to change notification settings - Fork 10
/
mb2md.pl
executable file
·1855 lines (1657 loc) · 67.1 KB
/
mb2md.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 -w
#
# $Id: mb2md.pl,v 1.26 2004/03/28 00:09:46 juri Exp $
#
# mb2md-3.20.pl Converts Mbox mailboxes to Maildir format.
#
# !! This is a version modified for Dovecot. Use Dovecot mailing list
# !! <[email protected]> for questions, patches, etc. You don't have to be
# !! subscribed to send mail there. Do not send mail directly to people
# !! listed below.
# Public domain.
#
# currently maintained by:
# Juri Haberland <[email protected]>
# initially wrote by:
# Robin Whittle
#
# This script's web abode is http://batleth.sapienti-sat.org/projects/mb2md/ .
# For a changelog see http://batleth.sapienti-sat.org/projects/mb2md/changelog.txt
#
# The Mbox -> Maildir inner loop is based on qmail's script mbox2maildir, which
# was kludged by Ivan Kohler in 1997 from convertandcreate (public domain)
# by Russel Nelson. Both these convert a single mailspool file.
#
# The qmail distribution has a maildir2mbox.c program.
#
# What is does:
# =============
#
# Reads a directory full of Mbox format mailboxes and creates a set of
# Maildir format mailboxes. Some details of this are to suit Courier
# IMAP's naming conventions for Maildir mailboxes.
#
# http://www.inter7.com/courierimap/
#
# This is intended to automate the conversion of the old
# /var/spool/mail/blah file - with one call of this script - and to
# convert one or more mailboxes in a specifed directory with separate
# calls with other command line arguments.
#
# Run this as the user - in these examples "blah".
# This version supports conversion of:
#
# Date The date-time in the "From " line of the message in the
# Mbox format is the date when the message was *received*.
# This is transformed into the date-time of the file which
# contains the message in the Maildir mailbox.
#
# This relies on the Date::Parse perl module and the utime
# perl function.
#
# The script tries to cope with errant forms of the
# Mbox "From " line which it may encounter, but if
# there is something really screwy in a From line,
# then perhaps the script will fail when "touch"
# is given an invalid date. Please report the
# exact nature of any such "From " line!
#
#
# Flagged
# Replied
# Read = Seen
# Tagged for Deletion
#
# In the Mbox message, flags for these are found in the
# "Status: N" or "X-Status: N" headers, where "N" is 0
# or more of the following characters in the left column.
#
# They are converted to characters in the right column,
# which become the last characters of the file name,
# following the ":2," which indicates IMAP message status.
#
#
# F -> F Flagged
# A -> R Replied
# R -> S Read = Seen
# D -> T Tagged for Deletion (Trash)
#
# This is based on the work of Philip Mak who wrote a
# completely separate Mbox -> Maildir converter called
# perfect_maildir and posted it to the Mutt-users mailing
# list on 25 December 2001:
#
# http://www.mail-archive.com/[email protected]/msg21872.html
#
# Michael Best originally integrated those changes into mb2md.
#
# UIDs (Dovecot and Courier)
# Using the -U or -u options will cause this program to maintain
# UIDVALIDITY and UIDLAST for folders and UIDs for individual
# messages. The X-IMAP:, X-IMAPbase:, and X-UID: headers are
# examined and appropriate files generated for Dovecot or Courier
# in the destination Maildir to ensure these values are all kept.
#
# UID support added by Julian Fitzell <[email protected]> June, 2008
#
# Message Keywords (Dovecot only)
# Using the -K option will cause this program to maintain message
# keywords (also known by other names such as tags). This is
# currently only supported for Dovecot and involves looking at
# the X-IMAP:, X-IMAPbase:, and X-Keywords: headers. The keywords
# are written to a file in the Maildir which maps them to flags.
# The flags are then appended the message filenames.
#
# Keyword support added by Julian Fitzell <[email protected]> June, 2008
#
# In addition, the names of the message files in the Maildir are of a
# regular length and are of the form:
#
# 7654321.000123.mbox:2,xxx
#
# Where "7654321" is the Unix time in seconds when the script was
# run and "000123" is the six zeroes padded message number as
# messages are converted from the Mbox file. "xxx" represents zero or
# more of the above flags F, R, S or T.
#
# Message Size Tags
#
# Additionally, there is optional support for including ,S= and ,W= tags
# before the colon. These message names are still valid Maildir filenames
# and the tags are used by mail programs to speed up calculation of quotas
# and the return of message sizes to IMAP clients. ,S= is part of the
# Maildir++ standard.
# (See: http://www.inter7.com/courierimap/README.maildirquota.html )
# As far as I can tell, ,W= is probably only used by Dovecot.
# (See: http://wiki.dovecot.org/MailboxFormat/Maildir )
#
# Size Tags added by Julian Fitzell <[email protected]> June, 2008
#
# ---------------------------------------------------------------------
#
#
# USAGE
# =====
#
# Run this as the user of the mailboxes, not as root.
#
#
# mb2md -h
# mb2md [-c] [-K] [-U|-u] [-S] [-W] -m [-d destdir]
# mb2md [-c] [-K] [-U|-u] [-S] [-W] -s sourcefile [-d destdir]
# mb2md [-c] [-K] [-U|-u] [-S] [-W] -s sourcedir [-l wu-mailboxlist] [-R|-f somefolder] [-d destdir] [-r strip_extension]
#
# -c use the Content-Length: headers (if present) to find the
# beginning of the next message
# Use with caution! Results may be unreliable. I recommend to do
# a run without "-c" first and only use it if you are certain,
# that the mbox in question really needs the "-c" option
#
# -K Preserve message keywords in a Dovecot-compatible way. This
# looks for X-Keywords: tags and X-IMAP: and X-IMAPbase: tags
# to determine keywords for messages and creates a Dovecot-
# compatible "dovecot-keywords" file in "destdir"
# NOTE: NO LOCKING IS DONE AND THE FILE MUST NOT ALREADY EXIST.
# IF YOU USE THIS OPTION ON A MAILDIR THAT MAY BE ACCESSED BY
# ANOTHER PROGRAM AT THE SAME TIME, STRANGE THINGS MAY HAPPEN.
#
# -U Preserve message UIDs in a Dovecot-compatible way
# Looks for X-UID:, X-IMAP:, and X-IMAPbase: headers and
# creates a Dovecot-compatible dovecot-uidlist file in
# "destdir"
# NOTE: NO LOCKING IS DONE AND THE FILE MUST NOT ALREADY EXIST.
# IF YOU USE THIS OPTION ON A MAILDIR THAT MAY BE ACCESSED BY
# ANOTHER PROGRAM AT THE SAME TIME, STRANGE THINGS MAY HAPPEN.
#
# -u Same as -U above, except creates a Courier IMAP-compatible
# courierimapuiddb file instead. The only difference according
# to http://wiki.dovecot.org/MailboxFormat/Maildir is that
# Courier IMAP only stores the maildir file's basename
# (everything before the colon)
# NOTE: NO LOCKING IS DONE AND THE FILE MUST NOT ALREADY EXIST.
# IF YOU USE THIS OPTION ON A MAILDIR THAT MAY BE ACCESSED BY
# ANOTHER PROGRAM AT THE SAME TIME, STRANGE THINGS MAY HAPPEN.
#
# -S Add Maildir++ standard ,S= tag to the message filenames
# indicating the size of the message on disk. This can be used
# by Courier and Dovecot in calculating quotas.
# I think Dovecot always uses this but not sure about Courier.
# For Exim, see the quota_size_regex and maildir_tag config
# statements.
#
# -W Add ,W= tag to the message filename indicating the RFC822.SIZE
# of the message. This is the size of the message when actually
# sent to an IMAP client with LF characters converted to CRLF
# pairs as per the spec. Dovecot uses this to speed up returning
# these sizes. Not sure if any other applications use it.
#
# -m If this is used then the source will
# be the single mailbox at /var/spool/mail/blah for
# user blah and the destination mailbox will be the
# "destdir" mailbox itself.
#
#
# -s source Directory or file relative to the user's home directory,
# which is where the the "somefolders" directories are located.
# Or if starting with a "/" it is taken as a
# absolute path, e.g. /mnt/oldmail/user
#
# or
#
# A single mbox file which will be converted to
# the destdir.
#
# -R If defined, do not skip directories found in a mailbox
# directory, but runs recursively into each of them,
# creating all wanted folders in Maildir.
# Incompatible with '-f'
#
# -f somefolder Directories, relative to "sourcedir" where the Mbox files
# are. All mailboxes in the "sourcedir"
# directory will be converted and placed in the
# "destdir" directory. (Typically the Inbox directory
# which in this instance is also functioning as a
# folder for other mailboxes.)
#
# The "somefolder" directory
# name will be encoded into the new mailboxes' names.
# See the examples below.
#
# This does not save an UW IMAP dummy message file
# at the start of the Mbox file. Small changes
# in the code could adapt it for looking for
# other distinctive patterns of dummy messages too.
#
# Don't let the source directory you give as "somefolders"
# contain any "."s in its name, unless you want to
# create subfolders from the IMAP user's point of
# view. See the example below.
#
# Incompatible with '-f'
#
#
# -d destdir Directory where the Maildir format directories will be created.
# If not given, then the destination will be ~/Maildir .
# Typically, this is what the IMAP server sees as the
# Inbox and the folder for all user mailboxes.
# If this begins with a '/' the path is considered to be
# absolute, otherwise it is relative to the users
# home directory.
#
# -r strip_ext If defined this extension will be stripped from
# the original mailbox file name before creating
# the corresponding maildir. The extension must be
# given without the leading dot ("."). See the example below.
#
# -l WU-file File containing the list of subscribed folders. If
# migrating from WU-IMAP the list of subscribed folders will
# be found in the file called .mailboxlist in the users
# home directory. This will convert all subscribed folders
# for a single user:
# /bin/mb2md -s mail -l .mailboxlist -R -d Maildir
# and for all users in a directory as root you can do the
# following:
# for i in *; do echo $i;su - $i -c "/bin/mb2md -s mail -l .mailboxlist -R -d Maildir";done
#
#
# Example
# =======
#
# We have a bunch of directories of Mbox mailboxes located at
# /home/blah/oldmail/
#
# /home/blah/oldmail/fffff
# /home/blah/oldmail/ggggg
# /home/blah/oldmail/xxx/aaaa
# /home/blah/oldmail/xxx/bbbb
# /home/blah/oldmail/xxx/cccc
# /home/blah/oldmail/xxx/dddd
# /home/blah/oldmail/yyyy/huey
# /home/blah/oldmail/yyyy/duey
# /home/blah/oldmail/yyyy/louie
#
# With the UW IMAP server, fffff and ggggg would have appeared in the root
# of this mail server, along with the Inbox. aaaa, bbbb etc, would have
# appeared in a folder called xxx from that root, and xxx was just a folder
# not a mailbox for storing messages.
#
# We also have the mailspool Inbox at:
#
# /var/spool/mail/blah
#
#
# To convert these, as user blah, we give the first command:
#
# mb2md -m
#
# The main Maildir directory will be created if it does not exist.
# (This is true of any argument options, not just "-m".)
#
# /home/blah/Maildir/
#
# It has the following subdirectories:
#
# /home/blah/Maildir/tmp/
# /home/blah/Maildir/new/
# /home/blah/Maildir/cur/
#
# Then /var/spool/blah file is read, split into individual files and
# written into /home/blah/Maildir/cur/ .
#
# Now we give the second command:
#
# mb2md -s oldmail -R
#
# This reads recursively all Mbox mailboxes and creates:
#
# /home/blah/Maildir/.fffff/
# /home/blah/Maildir/.ggggg/
# /home/blah/Maildir/.xxx/
# /home/blah/Maildir/.xxx.aaaa/
# /home/blah/Maildir/.xxx.bbbb/
# /home/blah/Maildir/.xxx.cccc/
# /home/blah/Maildir/.xxx.aaaa/
# /home/blah/Maildir/.yyyy/
# /home/blah/Maildir/.yyyy.huey/
# /home/blah/Maildir/.yyyy.duey/
# /home/blah/Maildir/.yyyy.louie/
#
# The result, from the IMAP client's point of view is:
#
# Inbox -----------------
# |
# | fffff -----------
# | ggggg -----------
# |
# - xxx -------------
# | | aaaa --------
# | | bbbb --------
# | | cccc --------
# | | dddd --------
# |
# - yyyy ------------
# | huey -------
# | duey -------
# | louie ------
#
# Note that although ~/Maildir/.xxx/ and ~/Maildir/.yyyy may appear
# as folders to the IMAP client the above commands to not generate
# any Maildir folders of these names. These are simply elements
# of the names of other Maildir directories. (if you used '-R', they
# whill be able to act as normal folders, containing messages AND folders)
#
# With a separate run of this script, using just the "-s" option
# without "-f" nor "-R", it would be possible to create mailboxes which
# appear at the same location as far as the IMAP client is
# concerned. By having Mbox mailboxes in some directory:
# ~/oldmail/nnn/ of the form:
#
# /home/blah/oldmail/nn/xxxx
# /home/blah/oldmail/nn/yyyyy
#
# then the command:
#
# mb2md -s oldmail/nn
#
# will create two new Maildirs:
#
# /home/blah/Maildir/.xxx/
# /home/blah/Maildir/.yyyy/
#
# Then what used to be the xxx and yyyy folders now function as
# mailboxes too. Netscape 4.77 needed to be put to sleep and given ECT
# to recognise this - deleting the contents of (Win2k example):
#
# C:\Program Files\Netscape\Users\uu\ImapMail\aaa.bbb.ccc\
#
# where "uu" is the user and "aaa.bbb.ccc" is the IMAP server
#
# I often find that deleting all this directory's contents, except
# "rules.dat", forces Netscape back to reality after its IMAP innards
# have become twisted. Then maybe use File > Subscribe - but this
# seems incapable of subscribing to folders.
#
# For Outlook Express, select the mail server, then click the
# "IMAP Folders" button and use "Reset list". In the "All"
# window, select the mailboxes you want to see in normal
# usage.
#
#
# This script did not recurse subdirectories or delete old mailboxes, before addition of the '-R' parameter :)
#
# Be sure not to be accessing the Mbox mailboxes while running this
# script. It does not attempt to lock them. Likewise, don't run two
# copies of this script either.
#
#
# Trickier usage . . .
# ====================
#
# If you have a bunch of mailboxes in a directory ~/oldmail/doors/
# and you want them to appear in folders such as:
#
# ~/Maildir/.music.bands.doors.Jim
# ~/Maildir/.music.bands.doors.John
#
# etc. so they appear in an IMAP folder:
#
# Inbox -----------------
# | music
# | bands
# | doors
# | Jim
# | John
# | Robbie
# | Ray
#
# Then you could rename the source directory to:
#
# ~/oldmail/music.bands.doors/
#
# then use:
#
# mb2md -s oldmail -f music.bands.doors
#
#
# Or simply use '-R' switch with:
# mb2md -s oldmail -R
#
#
# Stripping mailbox extensions:
# =============================
#
# If you want to convert mailboxes that came for example from
# a Windows box than you might want to strip the extension of
# the mailbox name so that it won't create a subfolder in your
# mail clients view.
#
# Example:
# You have several mailboxes named Trash.mbx, Sent.mbx, Drafts.mbx
# If you don't strip the extension "mbx" you will get the following
# hierarchy:
#
# Inbox
# |
# - Trash
# | | mbx
# |
# - Sent
# | | mbx
# |
# - Drafts
# | mbx
#
# This is more than ugly!
# Just use:
# mb2md -s oldmail -r mbx
#
# Note: don't specify the dot! It will be stripped off
# automagically ;)
#
#------------------------------------------------------------------------------
use strict;
use Getopt::Std;
use Date::Parse;
use IO::Handle;
use Fcntl;
# print the usage message
sub usage() {
print "Usage:\n";
print " mb2md -h\n";
print " mb2md [-c] [-K] [-U|-u] [-S] [-W] -m [-d destdir]\n";
print " mb2md [-c] [-K] [-U|-u] [-S] [-W] -s sourcefile [-d destdir]\n";
die " mb2md [-c] [-K] [-U|-u] [-S] [-W] -s sourcedir [-l wu-mailboxlist] [-R|-f somefolder] [-d destdir] [-r strip_extension]\n";
}
# get options
my %opts;
getopts('d:f:chms:r:l:RUuKSW', \%opts) || usage();
usage() if ( defined($opts{h})
|| (!defined($opts{m}) && !defined($opts{s})) );
# Get uid, username and home dir
my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $homedir, $shell) = getpwuid($<);
# Get arguments and determine source
# and target directories.
my $mbroot = undef; # this is the base directory for the mboxes
my $mbdir = undef; # this is an mbox dir relative to the $mbroot
my $mbfile = undef; # this is an mbox file
my $dest = undef;
my $strip_ext = undef;
my $use_cl = undef; # defines whether we use the Content-Length: header if present
my $create_dovecot_keywords = 0; # defines whether we generate a Dovecot-compatible keywords file
my $create_dovecot_uidlist = 0; # defines whether we generate a Dovecot-compatible uidlist UID file
my $create_courier_uidlist = 0; # defines whether we generate a Courier IMAP-compatible courierimapuiddb UID file
my $note_message_size = 0; # Whether we should add the ,S= message size tag
my $note_rfc822_size = 0; # Whether we should add the ,W= RFC822.SIZE tag
# if option "-c" is given, we use the Content-Length: header if present
# dangerous! may be unreliable, as the whole CL stuff is a bad idea
if (defined($opts{c}))
{
$use_cl = 1;
} else {
$use_cl = 0;
}
# The -U and -u options cannot be specified together
if (defined($opts{U}) && defined($opts{u}))
{
die("Options -U and -u cannot be specified together");
}
# if option "-K" is given, we will generate a Dovecot-compatible
# dovecot-keywords file in each Maildir
if (defined($opts{K}))
{
$create_dovecot_keywords = 1;
}
# if option "-U" is given, we will generate a Dovecot-compatible
# dovecot-uidlist file in each Maildir
if (defined($opts{U}))
{
$create_dovecot_uidlist = 1;
}
# if option "-u" is given, we will generate a Courier IMAP-compatible
# courierimapuiddb file in each Maildir
if (defined($opts{u}))
{
$create_courier_uidlist = 1;
}
if (defined($opts{S}))
{
$note_message_size = 1;
}
if (defined($opts{W}))
{
$note_rfc822_size = 1;
}
# first, if the user has gone the -m option
# we simply convert their mailfile
if (defined($opts{m}))
{
if (defined($ENV{'MAIL'})) {
$mbfile = $ENV{'MAIL'};
} elsif ( -f "/var/spool/mail/$name" ) {
$mbfile = "/var/spool/mail/$name"
} elsif ( -f "/var/mail/$name" ) {
$mbfile = "/var/mail/$name"
} else {
die("I searched \$MAIL, /var/spool/mail/$name and /var/mail/$name, ".
"but I couldn't find your mail spool file - ");
}
}
# see if the user has specified a source directory
elsif (defined($opts{s}))
{
# if opts{s} doesn't start with a "/" then
# it is a subdir of the users $home
# if it does start with a "/" then
# let's take $mbroot as a absolut path
$opts{s} = "$homedir/$opts{s}" if ($opts{s} !~ /^\//);
# check if the given source is a mbox file
if (-f $opts{s})
{
$mbfile = $opts{s};
}
# otherwise check if it is a directory
elsif (-d $opts{s})
{
$mbroot = $opts{s};
# get rid of trailing /'s
$mbroot =~ s/\/$//;
# check if we have a specified sub directory,
# otherwise the sub directory is '.'
if (defined($opts{f}))
{
$mbdir = $opts{f};
# get rid of trailing /'s
$mbdir =~ s/\/$//;
}
}
# otherwise we have an error
else
{
die("Fatal: Source is not an mbox file or a directory!\n");
}
}
# get the dest
defined($opts{d}) && ($dest = $opts{d}) || ($dest = "Maildir");
# see if we have anything to strip
defined($opts{r}) && ($strip_ext = $opts{r});
# No '-f' with '-R'
if((defined($opts{R}))&&(defined($opts{f}))) { die "No recursion with \"-f\"";}
# Get list of folders
my @flist;
if(defined($opts{l}))
{
open (LIST,$opts{l}) or die "Could not open mailbox list $opts{l}: $!";
@flist=<LIST>;
close LIST;
}
# if the destination is relative to the home dir,
# check that the home dir exists
die("Fatal: home dir $homedir doesn't exist.\n") if ($dest !~ /^\// && ! -e $homedir);
#
# form the destination value
# slap the home dir on the front of the dest if the dest does not begin
# with a '/'
$dest = "$homedir/$dest" if ($dest !~ /^\//);
# get rid of trailing /'s
$dest =~ s/\/$//;
# Count the number of mailboxes, or
# at least files, we found.
my $mailboxcount = 0;
# Since we'll be making sub directories of the main
# Maildir, we need to make sure that the main maildir
# exists
&maildirmake($dest);
# Now we do different things depending on whether we convert one mbox
# file or a directory of mbox files
if (defined($mbfile))
{
if (!isamailboxfile($mbfile))
{
print "Skipping $mbfile: not a mbox file\n";
}
else
{
print "Converting $mbfile to maildir: $dest\n";
# this is easy, we just run the convert function
&convert($mbfile, $dest);
}
}
# if '-f' was used ...
elsif (defined($mbdir))
{
print "Converting mboxdir/mbdir: $mbroot/$mbdir to maildir: $dest/\n";
# Now set our source directory
my $sourcedir = "$mbroot/$mbdir";
# check that the directory we are supposed to be finding mbox
# files in, exists and is a directory
-e $sourcedir or die("Fatal: MBDIR directory $sourcedir/ does not exist.\n");
-d $sourcedir or die("Fatal: MBDIR $sourcedir is not a directory.\n");
&convertit($mbdir,"");
}
# Else, let's work in $mbroot
else
{
opendir(SDIR, $mbroot)
or die("Fatal: Cannot open source directory $mbroot/ \n");
while (my $sourcefile = readdir(SDIR))
{
if (-d "$mbroot/$sourcefile") {
# Recurse only if requested (to be changed ?)
if (defined($opts{R})) {
print "convertit($sourcefile,\"\")\n";
&convertit($sourcefile,"");
} else {
print("$sourcefile is a directory, but '-R' was not used... skipping\n");
}
}
elsif (!-f "$mbroot/$sourcefile")
{
print "Skipping $mbroot/$sourcefile : not a file nor a dir\n";
next;
}
elsif (!isamailboxfile("$mbroot/$sourcefile"))
{
print "Skipping $mbroot/$sourcefile : not a mbox file\n";
next;
}
else
{
&convertit($sourcefile,"");
}
} # end of "while ($sfile = readdir(SDIR))" loop.
closedir(SDIR);
printf("$mailboxcount files processed.\n");
}
#
exit 0;
# My debbugging placeholder I can put somewhere to show how far the script ran.
# die("So far so good.\n\n");
# The isamailboxfile function
# ----------------------
#
# Here we check if the file is a mailbox file, not an address-book or
# something else.
# If file is empty, we say it is a mbox, to create it empty.
#
# Returns 1 if file is said mbox, 0 else.
sub isamailboxfile {
my ($mbxfile) = @_;
return 1 if(-z $mbxfile);
sysopen(MBXFILE, "$mbxfile", O_RDONLY) or die "Could not open $mbxfile ! \n";
while(<MBXFILE>) {
if (/^From/) {
close(MBXFILE);
return 1;
}
else {
close(MBXFILE);
return 0;
}
}
}
# The convertit function
# -----------------------
#
# This function creates all subdirs in maildir, and calls convert()
# for each mbox file.
# Yes, it becomes the 'main loop' :)
sub convertit
{
# Get subdir as argument
my ($dir,$oldpath) = @_;
$oldpath =~ s/\/\///;
# Skip files beginning with '.' since they are
# not normally mbox files nor dirs (includes '.' and '..')
if ($dir =~ /^\./)
{
print "Skipping $dir : name begins with a '.'\n";
return;
}
my $destinationdir = $dir;
my $temppath = $oldpath;
# We don't want to have .'s in the $targetfile file
# name because they will become directories in the
# Maildir. Therefore we convert them to _'s
$temppath =~ s/\./\_/g;
$destinationdir =~ s/\./\_/g;
# Appending $oldpath => path is only missing $dest
$destinationdir = "$temppath.$destinationdir";
# Converting '/' to '.' in $destinationdir
$destinationdir =~s/\/+/\./g;
# source dir
my $srcdir="$mbroot/$oldpath/$dir";
print("convertit(): Converting $dir in $mbroot/$oldpath to $dest/$destinationdir\n");
&maildirmake("$dest/$destinationdir");
# Subfolders are Maildir++ folders and should be marked by the
# presence of an empty "maildirfolder" file
sysopen(F, "$dest/$destinationdir/maildirfolder", O_CREAT|O_WRONLY, 0600) && close F;
print("destination = $destinationdir\n");
if (-d $srcdir) {
opendir(SUBDIR, "$srcdir") or die "can't open $srcdir !\n";
my @subdirlist=readdir(SUBDIR);
closedir(SUBDIR);
foreach (@subdirlist) {
next if (/^\.+$/);
print("Sub: $_\n");
print("convertit($_,\"$oldpath/$dir\")\n");
&convertit($_,"$oldpath/$dir");
}
} else {
# Source file verifs ....
#
return if(defined($opts{l}) && !inlist("$oldpath/$dir",@flist));
if (!isamailboxfile("$mbroot/$oldpath/$dir"))
{
print "Skipping $dir (is not mbox)\n";
return;
}
# target file verifs...
#
# if $strip_extension is defined,
# strip it off the $targetfile
defined($strip_ext) && ($destinationdir =~ s/\.$strip_ext$//);
&convert("$mbroot/$oldpath/$dir","$dest/$destinationdir");
$mailboxcount++;
}
}
# The maildirmake function
# ------------------------
#
# It does the same thing that the maildirmake binary that
# comes with courier-imap distribution
#
sub maildirmake
{
foreach(@_) {
-d $_ or mkdir $_,0700 or die("Fatal: Directory $_ doesn't exist and can't be created.\n");
-d "$_/tmp" or mkdir("$_/tmp",0700) or die("Fatal: Unable to make $_/tmp/ subdirectory.\n");
-d "$_/new" or mkdir("$_/new",0700) or die("Fatal: Unable to make $_/new/ subdirectory.\n");
-d "$_/cur" or mkdir("$_/cur",0700) or die("Fatal: Unable to make $_/cur/ subdirectory.\n");
}
}
# The inlist function
# ------------------------
#
# It checks that the folder to be converted is in the list of subscribed
# folders in WU-IMAP
#
sub inlist
{
my ($file,@flist) = @_;
my $valid = 0;
# Get rid of the first / if any
$file =~ s/^\///;
foreach my $folder (@flist) {
chomp $folder;
if ($file eq $folder) {
$valid = 1;
last;
}
}
if (!$valid) {
print "$file is not in list\n";
}
else {
print "$file is in list\n";
}
return $valid;
}
#
# The convert function
# ---------------------
#
# This function does the down and dirty work of
# actually converting the mbox to a maildir
#
sub convert
{
# get the source and destination as arguments
my ($mbox, $maildir) = @_;
print("Source Mbox is $mbox\n");
print("Target Maildir is $maildir \n") ;
# create the directories for the new maildir
#
# if it is the root maildir (ie. converting the inbox)
# these already exist but thats not a big issue
&maildirmake($maildir);
# Change to the target mailbox directory.
chdir "$maildir" ;
# Converts a Mbox to multiple files
# in a Maildir.
# This is adapted from mbox2maildir.
#
# Open the Mbox mailbox file.
if (sysopen(MBOX, "$mbox", O_RDONLY))
{
#printf("Converting Mbox $mbox . . . \n");
}
else
{
die("Fatal: unable to open input mailbox file: $mbox ! \n");
}
# This loop scans the input mailbox for
# a line starting with "From ". The
# "^" before it is pattern-matching
# lingo for it being at the start of a
# line.
#
# Each email in Mbox mailbox starts
# with such a line, which is why any
# such line in the body of the email
# has to have a ">" put in front of it.
#
# This is not required in a Maildir
# mailbox, and some majik below
# finds any such quoted "> From"s and
# gets rid of the "> " quote.
#
# Each email is put in a file
# in the cur/ subdirectory with a
# name of the form:
#
# nnnnnnnnn.cccc.mbox:2,XXXX
#
# where:
# "nnnnnnnnn" is the Unix time since
# 1970 when this script started
# running, incremented by 1 for
# every email. This is to ensure
# unique names for each message
# file.
#
# ".cccc" is the message count of
# messages from this mbox.
#
# ".mbox" is just to indicate that
# this message was converted from
# an Mbox mailbox.
#
# ":2," is the start of potentially
# multiple IMAP flag characters
# "XXXX", but may be followed by
# nothing.
#
# This is sort-of compliant with
# the Maildir naming conventions
# specified at:
#
# http://www.qmail.org/man/man5/maildir.html
#
# This approach does not involve the
# process ID or the hostname, but it is
# probably good enough.
#
# When the IMAP server looks at this
# mailbox, it will move the files to
# the cur/ directory and change their
# names as it pleases. In the case
# of Courier IMAP, the names will
# become like:
#
# 995096541.25351.mbox:2,S
#
# with 25351 being Courier IMAP's
# process ID. The :2, is the start
# of the flags, and the "S" means
# that this one has been seen by
# the user. (But is this the same
# meaning as the user actually
# having opened the message to see
# its contents, rather than just the
# IMAP server having been asked to
# list the message's Subject etc.
# so the client could list it in the
# visible Inbox?)
#
# This contrasts with a message
# created by Courier IMAP, say with
# a message copy, which is like:
#
# 995096541.25351.zair,S=14285:2,S
#
# where ",S=14285" is the size of the
# message in bytes.
#
# Courier Maildrop's names are similar
# but lack the ":2,XXXX" flags . . .
# except for my modified Maildrop
# which can deliver them with a
# ":2,T" - flagged for deletion.
#
# I have extended the logic of the
# per-message inner loop to stop
# saving a file for a message with:
#
# Subject: DON'T DELETE THIS MESSAGE -- FOLDER INTERNAL DATA
#
# This is the dummy message, always
# at the start of an Mbox format
# mailbox file - and is put there
# by UW IMAPD. Since quite a few
# people will use this for
# converting from a UW system,
# I figure it is worth it.
#
# I will not save any such message
# file for the dummy message.
#