-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmbox_parser.cpp
1201 lines (1032 loc) · 43.5 KB
/
mbox_parser.cpp
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
/*
BSD 2-Clause License
Copyright (c) 2017-2023, Noël Martinon
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "mbox_parser.hpp"
#include "common.hpp"
using namespace std;
/**
* Settings for progress animation
*/
const char *Mbox_parser::Anim[] = {"-", "\\", "|", "/"};
float Mbox_parser::iAnim=0;
//---------------------------------------------------------------------------------------------
/**
* Class constructor
* Initialize global settings
*/
Mbox_parser::Mbox_parser(std::string const filename) {
if (!filename.empty()) SetMboxFile(filename);
// Variables to maintain when on re-Init() call
mailAgeMin = 0;
mailAgeMax = 0;
tt_maildatebefore = 0;
tt_maildateafter = 0;
outputdirectory = "";
bEmlToWindows = false;
bSynchronize = false;
bGenerateMboxCompact = false;
bExtractMboxEml = false;
bGenerateMboxSplit = false;
bCompressEml = false;
bExtractInvalid = false;
bExtractDeleted = false;
bExtractDuplicated = false;
mboxsplitmaxsize = 0;
GetLocalTimeZone();
cbFunc_eml_preprocess = NULL;
cbFunc_eml_process = NULL;
cbFunc_log = NULL;
readytoparse = false;
}
//---------------------------------------------------------------------------------------------
/**
* Class destructor
*/
Mbox_parser::~Mbox_parser() {}
//---------------------------------------------------------------------------------------------
/**
* SetMboxFile()
* Set the mbox source filename and open file
* Return true if file is mbox type and is ready to parse
*/
bool Mbox_parser::SetMboxFile(std::string const filename){
readytoparse = false;
mboxfile.close(); // Ensure file is closed - Useful in recursive call if throw exception
if (filename.empty()){
if (*cbFunc_log) cbFunc_log ("ERROR", "No mbox file defined");
return false;
}
// Set full path + mbox file
mboxfullname = filename;
// Set mbox file name only
mboxfilename = filename;
std::replace( mboxfilename.begin(), mboxfilename.end(), '\\', '/'); // Replace Windows '\' to '/'
size_t pos = mboxfilename.find_last_of("/");
if (pos != string::npos)
mboxfilename = mboxfilename.substr(pos+1);
mboxfile.open( mboxfullname, std::ifstream::binary );//std::ios::binary
if (mboxfile.fail()) {
if (*cbFunc_log) cbFunc_log ("ERROR", "Failed to open mbox file \""+mboxfullname+"\"");
return false;
}
mboxfile.seekg (0, mboxfile.end);
mboxlength = mboxfile.tellg();
mboxfile.seekg (0, mboxfile.beg);
// Init buffer for recursive call on same Mbox_parser object.
// Required when mbox file size is small than buffer size.
buffer.assign(1024*1024,0);
// Start reading file
mboxfile.read(buffer.data(), buffer.size());
if (!IsMboxFile()) {
mboxfile.close();
if (*cbFunc_log) cbFunc_log ("ERROR", "Input file is not mbox type : \""+mboxfullname+"\"");
return false;
}
readytoparse = true;
return true;
}
//---------------------------------------------------------------------------------------------
/**
* IsReadyToParse()
* Return true if input file is ready to be parsed
*/
bool Mbox_parser::IsReadyToParse(){
return readytoparse;
}
//---------------------------------------------------------------------------------------------
/**
* Init()
* Reset settings to proceed mbox file parsing
* Always called before Parse()
*/
void Mbox_parser::Init() {
mboxindex = 0;
nbmailread = 0; // mails read in mbox
nbmailok = 0; // mails availables that are proccessed
nbmailinvalid = 0;
nbmaildeleted = 0;
nbmailduplicated = 0;
nbmailexcluded = 0;
nbmailextracted = 0;
nbmailcompact = 0;
nbmailsplit = 0;
nbsplitfile = 0;
nbemlremoved = 0;
bDisableMboxCompact = false;
mboxsplitcurrentsize = 0;
bDisableMboxSplit = false;
splitfilename = "";
splitindex = 0;
vmails.clear();
vmail.clear();
vheader.clear();
vmailcrlf.clear();
tt_timezero = time(0);
islastmail = false;
bmaildatestored = false;
tt_maildate = 0;
newline = "\n";
iAnim=0;
emlfilename = "";
emlList.clear();
}
//---------------------------------------------------------------------------------------------
/**
* ShowProgressBar()
* Display console progress bar for current mbox file
*/
void Mbox_parser::ShowProgressBar() {
std::cout << "[" << std::string(floor(this->i_progression/2), '=') << std::string(50-floor(this->i_progression/2), ' ') << "] ";
std::cout << std::setw(3) << i_progression << "% " << Anim[(int)floor(iAnim)] << "\r";
std::cout.flush();
iAnim +=.50;
if (iAnim >= 4) iAnim = 0;
usleep(1000);
}
//---------------------------------------------------------------------------------------------
/**
* IsMboxFile()
* Return true if source file is mbox type
* This is only correct for the first buffer
*/
bool Mbox_parser::IsMboxFile() {
if (offset(buffer, "From ")!=0) return false;
return true;
}
//---------------------------------------------------------------------------------------------
/**
* GetLocalTimeZone()
* Store result from time difference between local and gmt time
*/
void Mbox_parser::GetLocalTimeZone() {
time_t now = time(0); // UTC
time_t diff;
struct tm *ptmgm = gmtime(&now); // further convert to GMT presuming now in local
time_t gmnow = mktime(ptmgm);
diff = now - gmnow;
hourlocalTZ = (diff / 3600) % 24;
minutelocalTZ = (diff / 60) % 60;
}
//---------------------------------------------------------------------------------------------
/**
* Parse()
* Process the source file by block
* Return nb of valid emails according to optional filters applied
*/
int Mbox_parser::Parse() {
if (!readytoparse){
// Case Parse() is calling just after Mbox_parser constructor without input filename
if (mboxfullname.empty()){
if (*cbFunc_log) cbFunc_log ("ERROR", "Unable to parse undefined input file");
}
// Case Parse() is calling just after Mbox_parser constructor without mbox file
else if (!mboxfile.is_open()){
if (*cbFunc_log) cbFunc_log ("ERROR", "Unable to parse file \""+mboxfullname+"\"");
}
return -1;
}
this->Init();
// Create output directory if necessary
if ((bGenerateMboxCompact || bExtractMboxEml || (bGenerateMboxSplit && mboxsplitmaxsize)) && !DirectoryExists(outputdirectory)) {
if (outputdirectory.empty()) {
mboxfile.close();
if (*cbFunc_log) cbFunc_log ("ERROR", "Output directory is undefined");
return -1;
}
else if (!createPath(outputdirectory)) {
mboxfile.close();
if (*cbFunc_log) cbFunc_log ("ERROR", "Output directory cannot be created : \""+outputdirectory+"\"");
return -1;
}
}
if (bGenerateMboxCompact) {
std::stringstream ss;
ss << std::put_time(std::localtime(&tt_timezero), "_%Y%m%d%H%M%S");
compactfilename = outputdirectory + mboxfilename + ss.str();
outputcompact.open( compactfilename, std::ofstream::binary | std::ofstream::app );
if (! outputcompact.is_open()){
mboxfile.close();
if (*cbFunc_log) cbFunc_log ("ERROR", "Could not open \""+compactfilename+"\". Compact process is aborted.");
bDisableMboxCompact = false;
}
}
tt_timezero = time(0);
if (mailAgeMax>0) SetAgeMax(mailAgeMax);
if (mailAgeMin>0) SetAgeMin(mailAgeMin);
if (tt_maildateafter>0){
std::stringstream ss;
ss << std::put_time(std::localtime(&tt_maildateafter), "Apply filter \"AFTER %a %b %d %H:%M:%S %Y\"");
if (*cbFunc_log) cbFunc_log ("INFO", ss.str());
}
if (tt_maildatebefore>0){
std::stringstream ss;
ss << std::put_time(std::localtime(&tt_maildatebefore), "Apply filter \"BEFORE %a %b %d %H:%M:%S %Y\"");
if (*cbFunc_log) cbFunc_log ("INFO", ss.str());
}
if (*cbFunc_log) cbFunc_log ("INFO", "Start parsing file \""+mboxfullname+"\"");
while(mboxfile.gcount()) {
mboxindex += mboxfile.gcount();
this->i_progression=100*((float)mboxindex/(float)mboxlength);
ProcessPacket();
mboxfile.read(buffer.data(), buffer.size());
}
cout << std::string(59, ' ') << "\r";
mboxfile.close();
readytoparse = false;
// Synchronize output directory content
if (bSynchronize && bExtractMboxEml) {
std::vector<string> vListDirectory;
// List files (only) contains in directory output
if (ListDirectoryContents(vListDirectory, outputdirectory, true, false)){
vector<string> vListDiff;
sort(vListDirectory.begin(), vListDirectory.end());
sort(emlList.begin(), emlList.end());
set_difference(vListDirectory.begin(),vListDirectory.end(),emlList.begin(),emlList.end(),back_inserter(vListDiff));
for(string n : vListDiff){
n = outputdirectory + n;
int ret = std::remove(n.c_str());
if (!ret) nbemlremoved++;
if (*cbFunc_log){
if (!ret) cbFunc_log ("INFO", "File \""+n+"\" was deleted");
else cbFunc_log ("WARNING", "Can not delete file \""+n+"\"");
}
}
}
}
// if output directory is empty then delete it
std::vector<string> vList;
ListDirectoryContents(vList, outputdirectory, true, true);
if (vList.empty()) std::remove(outputdirectory.c_str());
if (*cbFunc_log) cbFunc_log ("INFO", "End parsing and processing file");
return nbmailok;
}
//---------------------------------------------------------------------------------------------
/**
* FindMailSeparator()
* Search mbox email's separator with MBOX Email Format define as :
* Each message in mbox format begins with a line beginning with the string "From "(ASCII characters F, r, o,
* m, and space). "From" lines are followed by several more fields: envelope-sender, date, and (optionally)
* more-data. The date field is in standard UNIX asctime() format and is always 24 characters in length.
* It is formatted as 'Www Mmm dd hh:mm:ss yyyy'
*
* After several tests, it turns out that sometimes the format is 'Www Mmm d hh:mm:ss yyyy' because of the
* only one digit in the day of the month. The function supports this case.
*/
bool Mbox_parser::FindMailSeparator(bool bUseAsctime) {
// If vmails is empty then this the end of the mbox file
if (!vmails.size()) return false;
mailsize = offset(vmails, "\nFrom ", 1); // +1 to start search from vmails+1 that always is the "r" of "From"
while (mailsize!=std::string::npos || (mboxindex == mboxlength && mailsize==std::string::npos)) {
// If end of mbox file
if (mboxindex == mboxlength && mailsize==std::string::npos) {
islastmail=true;
mailsize=vmails.size();
return true;
}
// Verify that the found separator "From " is a line structure as "From sender date moreinfo"
// See http://www.digitalpreservation.gov/formats/fdd/fdd000383.shtml
else if (bUseAsctime) {
size_t pos = offset(vmails, "\n", mailsize+1);// search '\n' at the end of the line "From "
if (pos==(size_t)-1) return false;
if (vmails[pos-1] == '\r') pos--; // pos do not content any newline char
if (pos-mailsize < 6) return false;
size_t pos_s = offset(vmails, " ", mailsize+6)+1;// search next space following "From "
if (pos_s==(size_t)-1) return false;
// Extract string in order to search asctime date
const std::string s (vmails.begin()+pos_s,vmails.begin()+pos);
std::vector<std::string> v;
split(s , ' ', v, false);
if (v.size()<5) return false;
// Check if string is a 'permissive' asctime
// When verifying with strptime("%a %b %d %H:%M:%S %Y") or even worse with
// regex "^From .+ .{24}" the global process is slowing.
// So using a simple string comparaison :
string date = v[0]+" "+v[1]+" "+v[2]+" "+v[3]+" "+v[4];
if (!is_asctime(date, false))
return false;
return true;
}
// Verify if next line is a header field
else {
size_t pos_endfrom = offset(vmails, "\n", mailsize+1);// search '\n' at the end of the line "From "
if (pos_endfrom==(size_t)-1) return false;
size_t pos = offset(vmails, "\n", pos_endfrom+1);
if (pos==(size_t)-1) return false;
if (vmails[pos-1] == '\r') pos--;
const std::string s (vmails.begin()+pos_endfrom+1,vmails.begin()+pos);
std::regex rgx("^.+:");
if (std::regex_match(s, rgx))
return false;
return true;
}
mailsize = offset(vmails, "\nFrom ", mailsize+1);
}
return false;
}
//---------------------------------------------------------------------------------------------
/**
* ProcessPacket()
* Process packet of byte size defined for buffer
*/
void Mbox_parser::ProcessPacket() {
ShowProgressBar();
if (!vmails.size()) {
vmails = buffer;
}
else {
copy(buffer.begin(), buffer.begin()+mboxfile.gcount(), std::back_inserter(vmails));
}
while (FindMailSeparator()) {
vmail.assign(vmails.begin(), vmails.begin()+mailsize+((islastmail)?0:1)); // assign after \n from "\nFrom - "
vmails.erase(vmails.begin(), vmails.begin()+mailsize+((islastmail)?0:1)); // erase before \n from "\nFrom - "
nbmailread++;
ProcessMail();
}
}
//---------------------------------------------------------------------------------------------
/**
* ProcessMail()
* Process email (save to eml, create compact, split mbox or callback)
* if it is valid, not deleted and not excluded by filter
*/
void Mbox_parser::ProcessMail() {
ShowProgressBar();
newline = "\n";
int pos = offset(vmail, newline+newline);
if (pos==-1) {
newline = "\r\n";
pos = offset(vmail, newline+newline);
}
if (pos>=0) {
// header beginning with "From "
vheader.assign (vmail.begin(), vmail.begin()+pos+newline.length()); // add one newline for GetHeaderField() that terminated with "\n".
}
else {
vmail.clear();
return;
}
bmaildatestored = false;
bool bIsValidMail = IsValidMail();
emlfilename = "";
if (!bIsValidMail) {
nbmailinvalid++;
// if do not extract invalid
if (!bExtractInvalid) {
vheader.clear();
vmail.clear();
return;
}
// if set to be store (even if marked as deleted)
else {
// Generate file name based on MD5 content (without any header field)
std::string str(vmail.begin(),vmail.end());
emlfilename = "00000000000000_"+PrintMD5(str)+".eml";
if (bCompressEml) emlfilename += ".gz";
}
}
// if valid and must ignored deleted
else if (!bExtractDeleted && IsDeletedMail()) {
nbmaildeleted++;
vheader.clear();
vmail.clear();
return;
}
// Not 'else' because it's necessarily a valid email and not marked as deleted
// If email is invalid and it must extract invalid then IsExcludedMail is ignored
if (bIsValidMail && IsExcludedMail()) {
vheader.clear();
vmail.clear();
nbmailexcluded++;
return;
}
// Deleted emails are renamed
if (IsDeletedMail())
emlfilename = "del_"+EmlFilename();
// Verifying duplicate email
int nbdup = count_needle(emlList, EmlFilename());
if (nbdup > 0)
{
nbmailduplicated++;
if (!bExtractDuplicated) {
vheader.clear();
vmail.clear();
return;
}
emlfilename = "dup"+std::to_string(nbdup)+"_"+EmlFilename();
}
nbmailok++;
emlList.push_back(EmlFilename());
if (DirectoryExists(outputdirectory)) {
if (bExtractMboxEml) {
if (!FileExists(outputdirectory + EmlFilename())) {
if (SaveToEML()) {
if (*cbFunc_log) cbFunc_log ("VERBOSE3", "Successfully saved email to \""+outputdirectory + EmlFilename()+"\"");
nbmailextracted++;
}
else if (*cbFunc_log) cbFunc_log ("VERBOSE1", "Unable to save email to \""+outputdirectory + EmlFilename()+"\"");
}
else {if (*cbFunc_log) cbFunc_log ("VERBOSE2", "Already existing file \""+outputdirectory + EmlFilename()+"\"");
//emlfilename = "_" + EmlFilename();
//SaveToEML();
}
}
if (bGenerateMboxCompact && !bDisableMboxCompact) {
if (SaveToCompact()) nbmailcompact++;
}
if (bGenerateMboxSplit && !bDisableMboxSplit) {
if (SaveToSplit()) nbmailsplit++;
}
}
// If callback for eml process is defined
if (*cbFunc_eml_process) {
bool valid = true;
// If callback for previous test of eml preprocess is defined
if (*cbFunc_eml_preprocess)
valid = cbFunc_eml_preprocess(outputdirectory, EmlFilename());
if (valid) {
StoreEML();
cbFunc_eml_process(outputdirectory, EmlFilename(), vmailcrlf);
}
}
vmail.clear();
vheader.clear();
vmailcrlf.clear();
}
//---------------------------------------------------------------------------------------------
/**
* StoreEML()
* Save email to vector vmailcrlf in the brut format as it is in the inbox file unless the
* "windows-format" option is specified. In this case, the end of line character is forced to "\r\n"
*/
void Mbox_parser::StoreEML(){
if (vmailcrlf.size()) return;
int firstline = offset(vmail, "\n")+1;
if (newline == "\n" && bEmlToWindows) {
string crlf = "\r\n";
size_t prevpos = firstline;
size_t pos = offset(vmail, "\n",firstline);
while (pos != (size_t)-1) {
ShowProgressBar();
vmailcrlf.insert( std::end(vmailcrlf), std::begin(vmail)+prevpos, std::begin(vmail)+pos );
if (vmailcrlf.back() == '\r') vmailcrlf.pop_back(); // Sometimes the extracted email contains a mix of linux and windows line breaks
vmailcrlf.insert( std::end(vmailcrlf), std::begin(crlf), std::end(crlf) );
prevpos = pos+1;
pos = offset(vmail, "\n", pos+1);
}
}
else {
vmailcrlf = std::vector<char> (vmail.begin()+firstline, vmail.end());
}
if (bCompressEml) {
std::vector<char> eml_gz = compress_gzip(vmailcrlf);
vmailcrlf = eml_gz;
}
}
//---------------------------------------------------------------------------------------------
/**
* SaveToEML()
* Save email to eml file with name formated as "YYYYmmddHHMMSS_MD5ofMessageID.eml"
* or "YYYYmmddHHMMSS_MD5ofMessageID.eml.gz" if compressed
* Return true if succeed
*/
bool Mbox_parser::SaveToEML(){
string emlfullname = outputdirectory + emlfilename;
std::ofstream f( emlfullname, std::ofstream::binary );
if (! f.is_open()){
if (*cbFunc_log) cbFunc_log ("ERROR", "Could not open \""+emlfullname+"\"");
return false;
}
StoreEML();
f.write(vmailcrlf.data(), vmailcrlf.size());
if (f.bad()) {
std::remove(emlfullname.c_str());
if (*cbFunc_log) cbFunc_log ("ERROR", "Could not write to \""+emlfullname+"\"");
return false;
}
return true;
}
//---------------------------------------------------------------------------------------------
/**
* SaveToCompact()
* Add full email (with line "From - ...") to new mbox file named "mboxfilename_YYYYmmddHHMMSS"
* Return true if succeed
*/
bool Mbox_parser::SaveToCompact(){
outputcompact.write(vmail.data(), vmail.size());
if (outputcompact.bad()) {
if (*cbFunc_log) cbFunc_log ("ERROR", "Could not write to \""+compactfilename+"\". Compact process is aborted.");
bDisableMboxCompact = true;
return false;
}
return true;
}
//---------------------------------------------------------------------------------------------
/**
* SaveToSplit()
* Add full email (with line "From ...") to mbox part
* Return true if succeed
*/
bool Mbox_parser::SaveToSplit(){
if (!mboxsplitmaxsize) {
return false;
}
// If an email size exceed max split size
if (mailsize > mboxsplitmaxsize){
if (*cbFunc_log) cbFunc_log ("ERROR", "At least one email exceeds the defined maximum size of the split file. Split process is aborted.");
bDisableMboxSplit = true;
return false;
}
// if first file or add email is over maxsplit then creation of a new file
if (!splitindex || mboxsplitcurrentsize+mailsize > mboxsplitmaxsize){
int maxsliptcount = ceil(double(mboxlength) / double(mboxsplitmaxsize));
int maxsplitfill = ceil(log10(fabs(maxsliptcount)+1));
stringstream ss;
ss << mboxfilename+".";
ss << setw(maxsplitfill) << setfill('0') << ++splitindex;
splitfilename = outputdirectory + ss.str();
if (outputsplit.is_open()) outputsplit.close();
if (FileExists(splitfilename)) std::remove(splitfilename.c_str());
outputsplit.open( splitfilename, std::ofstream::binary | std::ofstream::app );
if (!outputsplit.is_open()){
if (*cbFunc_log) cbFunc_log ("ERROR", "Could not open \""+splitfilename+"\". Split process is aborted.");
bDisableMboxSplit = true;
return false;
}
mboxsplitcurrentsize = 0;
nbsplitfile++;
}
// Append data to file
outputsplit.write(vmail.data(), vmail.size());
if (outputsplit.bad()) {
if (*cbFunc_log) cbFunc_log ("ERROR", "Could not write to \""+splitfilename+"\". Split process is aborted.");
outputsplit.close();
bDisableMboxSplit = true;
return false;
}
mboxsplitcurrentsize += mailsize;
return true;
}
//---------------------------------------------------------------------------------------------
/**
* GetHeaderField()
* Read email header specified (even on multiple lines)
* Option 'index' could be used when there is many headers with same name (eg:'Received')
* Return the value of the header field else empty string
*/
string Mbox_parser::GetHeaderField(string headerField, bool insensitiveSearch, int index) {
int idx_headerField = 0;
headerField = "\n"+headerField; // Prepend with "\n" to be sure it is not a text contained in field's value
headerField += ":";
std::vector<char> vHeaderValue;
string headerValue;
size_t line=0;
while (idx_headerField++ <= index) {
if (insensitiveSearch) line = ci_offset(vheader, headerField, line);
else line = offset(vheader, headerField, line);
if (line==(size_t)-1) return "";
line++;
}
size_t endline = offset(vheader, "\n", line+1); // +1 to ignore 1st char '\n ' of headerField
if (endline==(size_t)-1) endline = vheader.size();
// Test if newline is windows crlf
if ((line+headerField.length() < endline) && vheader[endline-1] == '\r')
vHeaderValue = std::vector<char> (vheader.begin()+line+headerField.length(), vheader.begin()+endline-1);
// do next test length in case of empty field value (then line+headerField.length() >= endline !!!)
else if (line+headerField.length() < endline)
vHeaderValue = std::vector<char> (vheader.begin()+line+headerField.length(), vheader.begin()+endline);
vHeaderValue.push_back('\0');
headerValue += trim(vHeaderValue.data());
// Case multiline value
size_t endnextline = offset(vheader, "\n", endline+1);
while (endnextline != (size_t)-1) {
// Test if newline is windows crlf
if ((endline+1 < endnextline) && vheader[endnextline-1] == '\r')
vHeaderValue = std::vector<char> ( vheader.begin()+endline+1, vheader.begin()+endnextline-1 );
else if (endline+1 < endnextline)
vHeaderValue = std::vector<char> ( vheader.begin()+endline+1, vheader.begin()+endnextline );
vHeaderValue.push_back('\0');
if (match("*: *", vHeaderValue.data())) break;
headerValue += trim(vHeaderValue.data());
endline = endnextline;
endnextline = offset(vheader, "\n", endline+1);
}
return headerValue;
}
//---------------------------------------------------------------------------------------------
/**
* IsValidMail()
* According to rfc2822 an email's header must have fields 'Date', 'From' and should have 'Message-ID'
* But to ensure a certain flexibility, 'Message-ID' is here not required.
* This function checks only the presence of 'Date' and 'From' and test if email's date is correct
* Return true if this fields exists.
*/
bool Mbox_parser::IsValidMail() {
// Sometimes the header fields are in lowercase but it is rarely the case
// so a sensitive search is done in first place because it's faster
headerfield_date = GetHeaderField("Date");
if (headerfield_date.empty())
headerfield_date = GetHeaderField("Date", true);
headerfield_from = GetHeaderField("From");
if (headerfield_from.empty())
headerfield_from = GetHeaderField("From", true);
headerfield_msgid = GetHeaderField("Message-ID");
if (headerfield_msgid.empty())
headerfield_msgid = GetHeaderField("Message-ID", true); // sometimes "Message-Id" and not "...ID" !
if (headerfield_date.length() && headerfield_from.length() && GetMailDate())
return true;
return false;
}
//---------------------------------------------------------------------------------------------
/**
* IsDeletedMail()
* Check for deletion in X-Mozilla-Status (see http://mxr.mozilla.org/mozilla/source/mailnews/base/public/nsMsgMessageFlags.h)
* Return true if email is marked as deleted
*/
bool Mbox_parser::IsDeletedMail() {
int iMozStatus;
std::stringstream stream;
stream << GetHeaderField("X-Mozilla-Status");
stream >> std::hex >> iMozStatus;
if (iMozStatus & MSG_FLAG_EXPUNGED) return true;
stream.str(std::string()); stream.clear();
stream << GetHeaderField("X-Mozilla-Status2");
stream >> std::hex >> iMozStatus;
if (iMozStatus & MSG_FLAG_IMAP_DELETED) return true;
return false;
}
//---------------------------------------------------------------------------------------------
/**
* IsExcludedMail()
* Return true if email is excluded by the date filtering rules
*/
bool Mbox_parser::IsExcludedMail() {
if (tt_maildateafter == tt_maildatebefore) return false;
if (tt_maildateafter && !tt_maildatebefore) {
// If date email older than "date after" then exclude
if (tt_maildate <= tt_maildateafter) return true;
}
else if (tt_maildatebefore && !tt_maildateafter) {
// If date email younger than "date before" then exclude
if (tt_maildate >= tt_maildatebefore) return true;
}
else if (tt_maildateafter && tt_maildatebefore) {
// Reject emails between tt_maildatebefore AND tt_maildateafter
// tt_maildatebefore < tt_maildate < tt_maildateafter
if (tt_maildateafter > tt_maildatebefore) {
if (tt_maildatebefore <= tt_maildate && tt_maildate <= tt_maildateafter) return true;
}
// Reject emails before tt_maildateafter OR after tt_maildatebefore
// tt_maildate < tt_maildateafter || tt_maildate > tt_maildatebefore
else if (tt_maildateafter < tt_maildatebefore) {
if (tt_maildate <= tt_maildateafter || tt_maildate >= tt_maildatebefore) return true;
}
}
return false;
}
//---------------------------------------------------------------------------------------------
/**
* GetMailAvailable()
* According to the options 'ExtractDeleted' and 'ExtractInvalid' available emails
* may contain deletes or invalids in addition to valid emails
* Return the number of available emails
*/
int Mbox_parser::GetMailAvailable(){
return nbmailok;
}
//---------------------------------------------------------------------------------------------
int Mbox_parser::GetMailRead(){
return nbmailread;
}
//---------------------------------------------------------------------------------------------
int Mbox_parser::GetMailInvalid(){
return nbmailinvalid;
}
//---------------------------------------------------------------------------------------------
int Mbox_parser::GetMailDeleted(){
return nbmaildeleted;
}
//---------------------------------------------------------------------------------------------
int Mbox_parser::GetMailDuplicated(){
return nbmailduplicated;
}
//---------------------------------------------------------------------------------------------
int Mbox_parser::GetMailExcluded(){
return nbmailexcluded;
}
//---------------------------------------------------------------------------------------------
int Mbox_parser::GetMailExtracted(){
return nbmailextracted;
}
//---------------------------------------------------------------------------------------------
int Mbox_parser::GetMailCompact(){
return nbmailcompact;
}
//---------------------------------------------------------------------------------------------
int Mbox_parser::GetMailSplit(){
return nbmailsplit;
}
//---------------------------------------------------------------------------------------------
int Mbox_parser::GetSplitFile(){
return nbsplitfile;
}
//---------------------------------------------------------------------------------------------
int Mbox_parser::GetEmlDeleted(){
return nbemlremoved;
}
//---------------------------------------------------------------------------------------------
std::vector<string> Mbox_parser::GetEmlList(){
return emlList;
}
//---------------------------------------------------------------------------------------------
/**
* SetWindowsFormat()
* If argument is true then convert the eml to windows format :
* if necessary, all the new line characters are converted to "\r\n".
* Else keeps the newline as it is read
*/
void Mbox_parser::SetWindowsFormat(bool b) {
bEmlToWindows = b;
}
//---------------------------------------------------------------------------------------------
/**
* SetSynchronize()
* If argument is true then all extracted eml files that
* are no more in valid emails list are deleted.
* The vector 'emlList' then contains the names of the valid files.
* default is false
*/
void Mbox_parser::SetSynchronize(bool b){
bSynchronize = b;
}
//---------------------------------------------------------------------------------------------
void Mbox_parser::SetActionExtract(bool b, bool compress){
bExtractMboxEml = b;
bCompressEml = compress;
}
//---------------------------------------------------------------------------------------------
void Mbox_parser::SetActionCompact(bool b){
bGenerateMboxCompact = b;
}
//---------------------------------------------------------------------------------------------
void Mbox_parser::SetActionSplit(bool b, size_t maxsize){
bGenerateMboxSplit = b;
mboxsplitmaxsize = maxsize;
}
//---------------------------------------------------------------------------------------------
/**
* set mbox process output directory
* return reformatted output directory if necessary indented with "/"
* and all characters '\\' replaced by '/'
* and all "//" to "/"
*/
std::string Mbox_parser::SetOutputDirectory(std::string directory){
outputdirectory = path_dusting(directory);
if (!outputdirectory.empty() && *outputdirectory.rbegin() != '/') // or && outputdirectory.back() != '/')
outputdirectory += '/';
return outputdirectory;
}
//---------------------------------------------------------------------------------------------
void Mbox_parser::SetExtractInvalid(bool bExtract) {
bExtractInvalid = bExtract;
}
//---------------------------------------------------------------------------------------------
void Mbox_parser::SetExtractDeleted(bool bExtract) {
bExtractDeleted = bExtract;
}
//---------------------------------------------------------------------------------------------
void Mbox_parser::SetExtractDuplicated(bool bExtract) {
bExtractDuplicated = bExtract;
}
//---------------------------------------------------------------------------------------------
void Mbox_parser::SetAgeMin(int age) {
mailAgeMin = age;
if (age > 0) {
tt_maildatebefore = tt_timezero - age*24*60*60;
}
else tt_maildatebefore = 0;
}
//---------------------------------------------------------------------------------------------
void Mbox_parser::SetAgeMax(int age) {
mailAgeMax = age;
if (age > 0) {
tt_maildateafter = tt_timezero - age*24*60*60;
}
else tt_maildateafter = 0;
}
//---------------------------------------------------------------------------------------------
/**
* SetDateBefore()
* Filter emails that date before specified value
*/
bool Mbox_parser::SetDateBefore(string strdate) {
if (strdate.empty()) return false;
tm tm_time;
int Y,M,d,h=0,m=0,s=0;
mailAgeMin = 0;
int retval = sscanf(strdate.c_str(), "%d-%d-%d %d:%d:%d", &Y, &M, &d, &h, &m, &s);
if (retval<3) retval = sscanf(strdate.c_str(), "%d/%d/%d %d:%d:%d", &Y, &M, &d, &h, &m, &s);
if (retval<3) { tt_maildatebefore = 0; return false; }
tm_time.tm_year = Y - 1900; // Year since 1900
tm_time.tm_mon = M - 1; // 0-11
tm_time.tm_mday = d; // 1-31
tm_time.tm_hour = h; // 0-23
tm_time.tm_min = m; // 0-59
tm_time.tm_sec = s;
tt_maildatebefore = mktime(&tm_time);
if (tt_maildatebefore==-1) { tt_maildatebefore = 0; return false; }
return true;
}
//---------------------------------------------------------------------------------------------
/**