-
Notifications
You must be signed in to change notification settings - Fork 8
/
index.js
3853 lines (3655 loc) · 130 KB
/
index.js
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
var Node = {
net: require('net')
};
var MIME = {};
// REFERENCE SPECIFICATIONS:
//
// https://tools.ietf.org/html/rfc5322
// Internet Message Format
//
// https://tools.ietf.org/html/rfc5321
// Simple Mail Transfer Protocol
//
// https://tools.ietf.org/html/rfc822
// ARPA Internet Text Messages
//
// https://tools.ietf.org/html/rfc2045
// Multipurpose Internet Mail Extensions (MIME) Part One:
// Format of Internet Message Bodies
//
// https://tools.ietf.org/html/rfc2046
// Multipurpose Internet Mail Extensions (MIME) Part Two:
// Media Types
//
// https://tools.ietf.org/html/rfc2047
// MIME (Multipurpose Internet Mail Extensions) Part Three:
// Message Header Extensions for Non-ASCII Text
//
// https://tools.ietf.org/html/rfc2183
// The Content-Disposition Header Field
//
// https://tools.ietf.org/html/rfc2231
// MIME Parameter Value and Encoded Word Extensions:
// Character Sets, Languages, and Continuations
//
// https://tools.ietf.org/html/rfc3848
// ESMTP and LMTP Transmission Types Registration
//
// https://tools.ietf.org/html/rfc7103
// Advice for Safe Handling of Malformed Messages
MIME.ASCII = 1;
MIME.LOWERCASE = 2;
MIME.UPPERCASE = 4;
MIME.TRIM = 8;
MIME.FWS = Buffer.alloc(256);
MIME.FWS[9] = 1;
MIME.FWS[10] = 1;
MIME.FWS[13] = 1;
MIME.FWS[32] = 1;
MIME.ATEXT = (function() {
// RFC 5322 3.2.3 Atom
// atext = ALPHA / DIGIT / ; Printable US-ASCII
// "!" / "#" / ; characters not including
// "$" / "%" / ; specials. Used for atoms.
// "&" / "'" /
// "*" / "+" /
// "-" / "/" /
// "=" / "?" /
// "^" / "_" /
// "`" / "{" /
// "|" / "}" /
// "~"
// atom = [CFWS] 1*atext [CFWS]
var table = Buffer.alloc(256);
for (var index = 48; index <= 57; index++) table[index] = 1; // [0-9]
for (var index = 65; index <= 90; index++) table[index] = 1; // [A-Z]
for (var index = 97; index <= 122; index++) table[index] = 1; // [a-z]
var map = "!#$%&'*+-/=?^_`{|}~";
for (var index = 0, length = map.length; index < length; index++) {
table[map.charCodeAt(index)] = 1;
}
return table;
})();
MIME.DTEXT = (function() {
// RFC 5322 3.4.1 Addr-Spec Specification
// dtext = %d33-90 / ; Printable US-ASCII
// %d94-126 / ; characters not including
// obs-dtext ; "[", "]", or "\"
var table = Buffer.alloc(256);
for (var index = 33; index <= 90; index++) table[index] = 1;
for (var index = 94; index <= 126; index++) table[index] = 1;
return table;
})();
MIME.QTEXT = (function() {
// RFC 5322 3.2.4 Quoted Strings
// qtext = %d33 / ; Printable US-ASCII
// %d35-91 / ; characters not including
// %d93-126 / ; "\" or the quote character
// obs-qtext
var table = Buffer.alloc(256);
table[33] = 1;
for (var index = 35; index <= 91; index++) table[index] = 1;
for (var index = 93; index <= 126; index++) table[index] = 1;
return table;
})();
MIME.decodeBase64 = function(buffer, body) {
var self = this;
try {
return self.Base64.decode(buffer);
} catch (error) {
// RFC 2045 6.8 Base64 Content-Transfer-Encoding
//
// Any characters outside of the base64 alphabet are to be ignored in
// base64-encoded data.
// RFC 4648 3.3 Interpretation of Non-Alphabet Characters in Encoded Data
//
// Base encodings use a specific, reduced alphabet to encode binary
// data. Non-alphabet characters could exist within base-encoded data,
// caused by data corruption or by design. Non-alphabet characters may
// be exploited as a "covert channel", where non-protocol data can be
// sent for nefarious purposes. Non-alphabet characters might also be
// sent in order to exploit implementation errors leading to, e.g.,
// buffer overflow attacks.
//
// Implementations MUST reject the encoded data if it contains
// characters outside the base alphabet when interpreting base-encoded
// data, unless the specification referring to this document explicitly
// states otherwise. Such specifications may instead state, as MIME
// does, that characters outside the base encoding alphabet should
// simply be ignored when interpreting data ("be liberal in what you
// accept"). Note that this means that any adjacent carriage return/
// line feed (CRLF) characters constitute "non-alphabet characters" and
// are ignored. Furthermore, such specifications MAY ignore the pad
// character, "=", treating it as non-alphabet data, if it is present
// before the end of the encoded data. If more than the allowed number
// of pad characters is found at the end of the string (e.g., a base 64
// string terminated with "==="), the excess pad characters MAY also be
// ignored.
// Non-Spec: We reject illegal and truncated Base64.
switch (error.message) {
case 'source is corrupt':
if (body) {
throw new Error(self.Error.Base64BodyIllegal);
} else {
throw new Error(self.Error.Base64WordIllegal);
}
case 'source is truncated':
if (body) {
throw new Error(self.Error.Base64BodyTruncated);
} else {
throw new Error(self.Error.Base64WordTruncated);
}
}
throw error;
}
};
MIME.decodeBody = function(buffer, contentType, contentTransferEncoding) {
var self = this;
if (contentTransferEncoding) {
// RFC 2045 6.2 Content-Transfer-Encodings Semantics
// The Content-Transfer-Encoding values "7bit", "8bit", and "binary" all
// mean that the identity (i.e. NO) encoding transformation has been
// performed. As such, they serve simply as indicators of the domain of
// the body data, and provide useful information about the sort of
// encoding that might be needed for transmission in a given transport
// system.
// RFC 2045 6.4 Interpretation and Use
// If an entity is of type "multipart" the Content-Transfer-Encoding is not
// permitted to have any value other than "7bit", "8bit" or "binary".
// RFC 2045 6.4 Interpretation and Use
// Certain Content-Transfer-Encoding values may only be used on certain
// media types. In particular, it is EXPRESSLY FORBIDDEN to use any
// encodings other than "7bit", "8bit", or "binary" with any composite
// media type, i.e. one that recursively includes other Content-Type
// fields. Currently the only composite media types are "multipart" and
// "message". All encodings that are desired for bodies of type
// multipart or message must be done at the innermost level, by encoding
// the actual body that needs to be encoded.
// RFC 2045 6.4 Interpretation and Use
// NOTE ON ENCODING RESTRICTIONS: Though the prohibition against using
// content-transfer-encodings on composite body data may seem overly
// restrictive, it is necessary to prevent nested encodings, in which
// data are passed through an encoding algorithm multiple times, and
// must be decoded multiple times in order to be properly viewed.
// Nested encodings add considerable complexity to user agents: Aside
// from the obvious efficiency problems with such multiple encodings,
// they can obscure the basic structure of a message. In particular,
// they can imply that several decoding operations are necessary simply
// to find out what types of bodies a message contains. Banning nested
// encodings may complicate the job of certain mail gateways, but this
// seems less of a problem than the effect of nested encodings on user
// agents.
// RFC 5335 1.2 Relation to Other Standards
// This document updates Section 6.4 of RFC 2045. It removes the
// blanket ban on applying a content-transfer-encoding to all subtypes
// of message/, and instead specifies that a composite subtype MAY
// specify whether or not a content-transfer-encoding can be used for
// that subtype, with "cannot be used" as the default.
// For further relaxations see RFC 6532 and RFC 6533.
// RFC 6532 Internationalized Email Headers
// This specification updates Section 6.4 of RFC 2045 to eliminate the
// restriction prohibiting the use of non-identity content-transfer-
// encodings on subtypes of "message/".
// However, these relaxations apply only to subtypes of "message/".
// Further, some systems incorrectly apply a content-transfer-encoding to a
// multipart body, causing corruption and/or missing multiparts if the
// encoding is decoded.
if (
contentTransferEncoding !== '7bit' &&
contentTransferEncoding !== '8bit' &&
contentTransferEncoding !== 'binary'
) {
if (/^multipart\//.test(contentType.value)) {
throw new Error(self.Error.ContentTransferEncodingMultipart);
}
}
if (contentTransferEncoding === 'base64') {
// RFC 2045 6.8 Base64 Content-Transfer-Encoding
// All line breaks or other characters not
// found in Table 1 must be ignored by decoding software. In base64
// data, characters other than those in Table 1, line breaks, and other
// white space probably indicate a transmission error, about which a
// warning message or even a message rejection might be appropriate
// under some circumstances.
buffer = self.decodeBase64(buffer, true);
} else if (contentTransferEncoding === 'quoted-printable') {
buffer = self.decodeQuotedPrintable(buffer, true);
}
}
if (contentType.parameters.hasOwnProperty('charset')) {
// RFC 2045 5 Content-Type Header Field
// ...the "charset" parameter is applicable to any subtype of "text"...
// RFC 2046 4.1 Text Media Type
// A "charset" parameter may be used to
// indicate the character set of the body text for "text" subtypes,
// notably including the subtype "text/plain", which is a generic
// subtype for plain text.
// RFC 2046 4.1.2 Charset Parameter
// A critical parameter that may be specified in the Content-Type field
// for "text/plain" data is the character set.
// RFC 2046 4.1.2 Charset Parameter
// Other media types than subtypes of "text" might choose to employ the
// charset parameter as defined here, but with the CRLF/line break
// restriction removed.
// We understand the above to mean that the charset parameter can in fact be
// used by non-text media types e.g. application/json.
buffer = self.decodeCharset(buffer, contentType.parameters.charset);
}
return buffer;
};
MIME.decodeCharset = function(source, charset) {
var self = this;
if (charset === undefined || charset === '') return source;
if (typeof charset !== 'string') {
throw new Error('charset must be a string');
}
if (charset.length > 24 || !/^[\s\x21-\x7E]+$/.test(charset)) {
// Guard against malicious charsets being passed to iconv.
// We allow whitespace and any printable character (33-126).
throw new Error(self.Error.CharsetUnsupported);
}
var key = self.decodeCharsetKey(charset);
if (self.decodeCharsetIdentity.hasOwnProperty(key)) return source;
if (self.decodeCharsetCanon.hasOwnProperty(key)) {
charset = self.decodeCharsetCanon[key];
} else {
var match = key.match(/^X?WIN(DOWS)?(\d+)$/);
if (match) charset = 'WINDOWS-' + match[2];
}
try {
var iconv = new self.Iconv(charset, 'UTF-8//TRANSLIT//IGNORE');
var target = iconv.convert(source);
} catch (error) {
if (error.code === 'EILSEQ') {
// Illegal character sequence.
throw new Error(self.Error.CharsetIllegal);
} else if (error.code === 'EINVAL') {
// Incomplete character sequence.
throw new Error(self.Error.CharsetTruncated);
} else if (/^Conversion from /i.test(error.message)) {
// Encoding not supported.
throw new Error(self.Error.CharsetUnsupported);
} else {
// Unexpected error.
throw error;
}
}
return target;
};
MIME.decodeCharsetCanon = {
ANSIX31101983: 'ISO88591',
ARMSCII8: 'ARMSCII-8',
ASCII: 'ASCII',
ATARIST: 'ATARIST',
BIG5: 'BIG5',
BIG5HKSCS: 'BIG5-HKSCS',
BIG5HKSCS1999: 'BIG5-HKSCS:1999',
BIG5HKSCS2001: 'BIG5-HKSCS:2001',
BIG5HKSCS2004: 'BIG5-HKSCS:2004',
BKSC56011987: 'CP949',
C99: 'C99',
CP1125: 'CP1125',
CP1133: 'CP1133',
CP1250: 'CP1250',
CP1251: 'CP1251',
CP1252: 'CP1252',
CP1253: 'CP1253',
CP1254: 'CP1254',
CP1255: 'CP1255',
CP1256: 'CP1256',
CP1257: 'CP1257',
CP1258: 'CP1258',
CP437: 'CP437',
CP737: 'CP737',
CP775: 'CP775',
CP850: 'CP850',
CP852: 'CP852',
CP853: 'CP853',
CP855: 'CP855',
CP857: 'CP857',
CP858: 'CP858',
CP860: 'CP860',
CP861: 'CP861',
CP862: 'CP862',
CP863: 'CP863',
CP864: 'CP864',
CP865: 'CP865',
CP866: 'CP866',
CP869: 'CP869',
CP874: 'CP874',
CP932: 'CP932',
CP936: 'CP936',
CP949: 'CP949',
CP950: 'CP950',
EUCCN: 'EUC-CN',
EUCJISX0213: 'EUC-JISX0213',
EUCJP: 'EUC-JP',
EUCKR: 'EUC-KR',
EUCTW: 'EUC-TW',
GB18030: 'GB18030',
GBK: 'GBK',
GEORGIANACADEMY: 'Georgian-Academy',
GEORGIANPS: 'Georgian-PS',
HPROMAN8: 'HP-ROMAN8',
HZ: 'HZ',
ISO2022CN: 'ISO-2022-CN',
ISO2022CNEXT: 'ISO-2022-CN-EXT',
ISO2022JP: 'ISO-2022-JP',
ISO2022JP1: 'ISO-2022-JP-1',
ISO2022JP2: 'ISO-2022-JP-2',
ISO2022JP3: 'ISO-2022-JP-3',
ISO2022KR: 'ISO-2022-KR',
ISO88591: 'ISO-8859-1',
ISO885910: 'ISO-8859-10',
ISO885911: 'ISO-8859-11',
ISO885913: 'ISO-8859-13',
ISO885914: 'ISO-8859-14',
ISO885915: 'ISO-8859-15',
ISO885916: 'ISO-8859-16',
ISO88592: 'ISO-8859-2',
ISO88593: 'ISO-8859-3',
ISO88594: 'ISO-8859-4',
ISO88595: 'ISO-8859-5',
ISO88596: 'ISO-8859-6',
ISO88597: 'ISO-8859-7',
ISO88598: 'ISO-8859-8',
ISO88599: 'ISO-8859-9',
JAVA: 'JAVA',
JOHAB: 'JOHAB',
KOI8R: 'KOI8-R',
KOI8RU: 'KOI8-RU',
KOI8T: 'KOI8-T',
KOI8U: 'KOI8-U',
KSC56011987: 'CP949',
MACARABIC: 'MacArabic',
MACCENTRALEUROPE: 'MacCentralEurope',
MACCROATIAN: 'MacCroatian',
MACCYRILLIC: 'MacCyrillic',
MACGREEK: 'MacGreek',
MACHEBREW: 'MacHebrew',
MACICELAND: 'MacIceland',
MACINTOSH: 'Macintosh',
MACROMAN: 'MacRoman',
MACROMANIA: 'MacRomania',
MACTHAI: 'MacThai',
MACTURKISH: 'MacTurkish',
MACUKRAINE: 'MacUkraine',
MULELAO1: 'MuleLao-1',
NEXTSTEP: 'NEXTSTEP',
PT154: 'PT154',
RISCOSLATIN1: 'RISCOS-LATIN1',
RK1048: 'RK1048',
SHIFTJIS: 'SHIFT_JIS',
SHIFTJISX0213: 'Shift_JISX0213',
TCVN: 'TCVN',
TDS565: 'TDS565',
TIS620: 'TIS-620',
UCS2: 'UCS-2',
UCS2BE: 'UCS-2BE',
UCS2LE: 'UCS-2LE',
UCS4: 'UCS-4',
UCS4BE: 'UCS-4BE',
UCS4LE: 'UCS-4LE',
UHC: 'CP949',
UTF16: 'UTF-16',
UTF16BE: 'UTF-16BE',
UTF16LE: 'UTF-16LE',
UTF32: 'UTF-32',
UTF32BE: 'UTF-32BE',
UTF32LE: 'UTF-32LE',
UTF7: 'UTF-7',
UTF8: 'UTF-8',
VISCII: 'VISCII',
WIN949: 'CP949',
WINDOWS949: 'CP949',
XUHC: 'CP949',
XWIN949: 'CP949',
XWINDOWS949: 'CP949'
};
MIME.decodeCharsetIdentity = {
ASCII: true,
BINARY: true,
USASCII: true,
UTF8: true
};
MIME.decodeCharsetKey = function(charset) {
var self = this;
return charset.toUpperCase().replace(/[^A-Z0-9]/g, '');
};
MIME.decodeEntity = function(buffer) {
var self = this;
// An adversary can submit a few megabytes of data without any headers.
// We want to limit the amount of time we spend searching for the delimiters.
// We allow a limit of 256 KB (Exchange has 64 KB, Sendmail has 32 KB).
// Some folded header lines (together more than 1000 characters) may have many
// addresses and we want to allow these.
// We have seen instances of headers joined to the body with only a single
// CRLF followed immediately by a multipart opening boundary. While we could
// detect the "--" as the start of the body, this would lead to multiple
// renderings among clients, i.e. some clients would treat the first part as a
// preamble instead.
var limit = 262144;
var index = 0;
var length = Math.min(limit, buffer.length);
while (index < length) {
if (buffer[index] === 13) {
if (
index + 3 < length &&
buffer[index + 1] === 10 &&
buffer[index + 2] === 13 &&
buffer[index + 3] === 10
) {
return [ buffer.slice(0, index), buffer.slice(index + 4) ];
}
} else if (buffer[index] === 10) {
if (index + 1 < length && buffer[index + 1] === 10) {
return [ buffer.slice(0, index), buffer.slice(index + 2) ];
}
}
index++;
}
if (index >= limit) {
throw new Error(self.Error.HeadersLimit);
}
if (length >= 2 && buffer[length - 2] === 13 && buffer[length - 1] === 10) {
// Message ends with a single CRLF and only has headers.
return [ buffer.slice(0, length - 2), buffer.slice(length) ];
}
if (length >= 1 && buffer[length - 1] === 10) {
// Message ends with a single LF and only has headers.
return [ buffer.slice(0, length - 1), buffer.slice(length) ];
}
throw new Error(self.Error.HeadersCRLF);
};
MIME.decodeHeaderAddresses = function(buffer) {
var self = this;
var header = [];
buffer = self.decodeHeaderBuffer(buffer, true);
if (!buffer) return header;
buffer = self.decodeHeaderUnfold(buffer);
buffer = self.decodeHeaderRemoveComments(buffer);
var addresses = self.decodeHeaderSplitOutsideQuotes(
buffer,
0,
buffer.length,
self.decodeHeaderAddressesSeparators
);
for (var index = 0, length = addresses.length; index < length; index++) {
var address = self.decodeHeaderAddressesAddress(addresses[index]);
if (address) header.push(address);
}
return header;
};
MIME.decodeHeaderAddressesSeparators = Buffer.alloc(256);
MIME.decodeHeaderAddressesSeparators[44] = 1; // ','
MIME.decodeHeaderAddressesSeparators[59] = 1; // ';'
MIME.decodeHeaderAddressesSeparators[58] = 255; // ':'
MIME.decodeHeaderAddressesAddress = function(buffer) {
var self = this;
buffer = self.decodeHeaderAngleBrackets(buffer);
var parts = self.decodeHeaderSplitOutsideQuotes(
buffer,
0,
buffer.length,
self.decodeHeaderAddressesAddressSeparators
);
if (parts.length === 0) return;
// Find part containing email (regardless of display-name and addr order):
var max = parts.length - 1;
var scores = new Uint8Array(parts.length);
for (var index = 0, length = parts.length; index < length; index++) {
var part = parts[index];
// At its meeting on 13 August 2013, the ICANN Board New gTLD Program
// Committee (NGPC) adopted a resolution affirming that
// "dotless domain names" are prohibited. Dotless domain names are those
// that consist of a single label (e.g., http://example, or mail@example).
// See: https://www.icann.org/news/announcement-2013-08-30-en
// We therefore score part if part has at least an '@' followed by a '.':
var index64 = self.indexOf(part, 0, part.length, 64); // '@'
if (index64 >= 1) {
var index46 = self.indexOf(part, index64, part.length, 46); // '.'
if (index46 >= index64 + 2) {
scores[index] += 2;
// We use >= to prefer parts to the right:
if (scores[index] >= scores[max]) max = index;
}
}
}
var email = '';
if (scores[max] > 0) {
email = self.decodeHeaderQuotedStrings(parts[max]).toString('ascii');
// Non-Spec: Remove all whitespace (including around '@'):
email = email.replace(/\s+/g, '');
// Remove any angle brackets (those shielded by quoted strings):
email = email.replace(/^<+|>+$/g, '');
// Non-Spec: Remove multiple balanced single quotes:
while (/^'.*'$/.test(email)) email = email.slice(1, -1);
// Ensure that local-part exists:
if (email.indexOf('@') > 0) {
parts.splice(max, 1);
} else {
email = '';
}
}
var nameBuffers = [];
for (var index = 0, length = parts.length; index < length; index++) {
var part = parts[index];
if ((part = self.decodeHeaderQuotedStrings(part)).length > 0) {
// RFC 5322 3.2.2 Folding White Space and Comments
// Runs of FWS, comment or CFWS that occur between lexical tokens in a
// structured field header are semantically interpreted as a single
// space character.
if (nameBuffers.length > 0) {
nameBuffers.push(self.decodeHeaderAddressesAddressSpace);
}
nameBuffers.push(part);
}
}
// Non-Spec: We decode any encoded words found in quoted-strings.
var nameBuffer = Buffer.concat(nameBuffers);
var name = self.decodeHeaderEncodedWords(nameBuffer).toString('utf-8');
// Non-Spec: Remove single quotes sometimes added by Outlook:
if (/^'.*'$/.test(name)) name = name.slice(1, -1).trim();
// Non-Spec: Remove whitespace from name if name is otherwise empty:
if (/^\s+$/.test(name)) name = '';
// Do not add an empty name and empty email to the addresses list:
if (name.length === 0 && email.length === 0) return;
if (email.length === 0 && /^[^A-Z0-9]$/i.test(name)) return;
return new self.Address(name, email);
};
MIME.decodeHeaderAddressesAddressSeparators = Buffer.alloc(256);
// We split on WSP in case display-name exists but addr has no angle brackets:
MIME.decodeHeaderAddressesAddressSeparators[9] = 1; // '\t'
MIME.decodeHeaderAddressesAddressSeparators[32] = 1; // ' '
// We split on angle brackets in case there is no WSP between tokens:
MIME.decodeHeaderAddressesAddressSeparators[60] = 1; // '<'
MIME.decodeHeaderAddressesAddressSeparators[62] = 1; // '>'
MIME.decodeHeaderAddressesAddressSpace = Buffer.from([32]);
MIME.decodeHeaderAngleBrackets = function(source) {
var self = this;
// Remove any spaces in tokens surrounded by angle brackets.
// Ignore angle brackets in quoted-strings.
var range = new Array(2);
range[0] = 0;
range[1] = 0;
var target;
var targetIndex = 0;
var sourceIndex = 0;
var sourceLength = source.length;
while (sourceIndex < sourceLength) {
var match = self.decodeHeaderAngleBracketsMatch(
source,
sourceIndex,
sourceLength,
range
);
if (!match) break;
var matchIndex = match[0];
var matchLength = match[1];
if (target) {
targetIndex += source.copy(target, targetIndex, sourceIndex, matchIndex);
}
while (matchIndex < matchLength) {
if (source[matchIndex] === 9 || source[matchIndex] === 32) {
if (!target) {
target = Buffer.alloc(sourceLength);
targetIndex += source.copy(target, targetIndex, 0, matchIndex);
}
} else if (target) {
target[targetIndex++] = source[matchIndex];
}
matchIndex++;
}
sourceIndex = matchLength;
}
if (target) {
targetIndex += source.copy(target, targetIndex, sourceIndex, sourceLength);
return target.slice(0, targetIndex);
} else {
return source;
}
};
MIME.decodeHeaderAngleBracketsMatch = function(
source,
sourceIndex,
sourceLength,
range
) {
var self = this;
var opening = self.indexOutsideQuotes(source, sourceIndex, sourceLength, 60);
if (opening === -1) return;
var index = opening + 1;
while (index < sourceLength) {
if (source[index] === 62) {
range[0] = opening;
range[1] = index + 1;
return range;
} else if (source[index] === 60) {
opening = index;
} else if (!self.decodeHeaderAngleBracketsMatchTable[source[index]]) {
return;
}
index++;
}
};
MIME.decodeHeaderAngleBracketsMatchTable = (function() {
// RFC 5322 3.2.3 Atom
// atext = ALPHA / DIGIT / ; Printable US-ASCII
// "!" / "#" / ; characters not including
// "$" / "%" / ; specials. Used for atoms.
// "&" / "'" /
// "*" / "+" /
// "-" / "/" /
// "=" / "?" /
// "^" / "_" /
// "`" / "{" /
// "|" / "}" /
// "~"
// atom = [CFWS] 1*atext [CFWS]
// dot-atom-text = 1*atext *("." 1*atext)
// dot-atom = [CFWS] dot-atom-text [CFWS]
var table = Buffer.alloc(256);
for (var index = 48; index <= 57; index++) table[index] = 1; // [0-9]
for (var index = 65; index <= 90; index++) table[index] = 1; // [A-Z]
for (var index = 97; index <= 122; index++) table[index] = 1; // [a-z]
var map = "!#$%&'*+-/=?^_`{|}~.";
for (var index = 0, length = map.length; index < length; index++) {
table[map.charCodeAt(index)] = 1;
}
table[9] = 1;
table[32] = 1;
table['@'.charCodeAt(0)] = 1;
return table;
})();
MIME.decodeHeaderBuffer = function(buffer, addresses) {
var self = this;
if (buffer === undefined) {
return undefined;
} else if (Array.isArray(buffer)) {
if (buffer.length === 0) return undefined;
for (var index = 0, length = buffer.length; index < length; index++) {
if (!Buffer.isBuffer(buffer[index])) {
throw new Error('buffer must be a buffer');
}
}
// RFC 5322 4.5 Obsolete Header Fields
// Except for destination address fields (described in section 4.5.3),
// the interpretation of multiple occurrences of fields is unspecified.
//
// RFC 5322 4.5.3 Obsolete Destination Address Fields
// When multiple occurrences of destination address fields occur in a
// message, they SHOULD be treated as if the address list in the first
// occurrence of the field is combined with the address lists of the
// subsequent occurrences by adding a comma and concatenating.
if (addresses) {
var buffers = [];
for (var index = 0, length = buffer.length; index < length; index++) {
buffers.push(buffer[index]);
if (index < length - 1) buffers.push(self.decodeHeaderBufferComma);
}
return Buffer.concat(buffers);
} else {
return buffer[0];
}
} else if (Buffer.isBuffer(buffer)) {
return buffer;
} else {
throw new Error('buffer must be a buffer or an array of buffers');
}
};
MIME.decodeHeaderBufferComma = Buffer.from(',');
MIME.decodeHeaderContentDisposition = function(buffer) {
var self = this;
buffer = self.decodeHeaderBuffer(buffer, false);
if (!buffer) return new self.HeaderValueParameters('', {});
var header = self.decodeHeaderValueParameters(
self.decodeHeaderRemoveComments(
self.decodeHeaderUnfold(buffer)
)
);
return header;
};
MIME.decodeHeaderContentTransferEncoding = function(buffer) {
var self = this;
// RFC 2045 6.1 Content-Transfer-Encoding Syntax
//
// The Content-Transfer-Encoding field's value is a single token
// specifying the type of encoding, as enumerated below. Formally:
//
// encoding := "Content-Transfer-Encoding" ":" mechanism
//
// mechanism := "7bit" / "8bit" / "binary" /
// "quoted-printable" / "base64" /
// ietf-token / x-token
//
// These values are not case sensitive -- Base64 and BASE64 and bAsE64
// are all equivalent.
buffer = self.decodeHeaderBuffer(buffer, false);
if (!buffer) return '';
buffer = self.decodeHeaderRemoveComments(self.decodeHeaderUnfold(buffer));
var mechanism = self.slice(
buffer,
0,
buffer.length,
self.TRIM | self.LOWERCASE | self.ASCII
);
if (/^".*"$/.test(mechanism)) mechanism = mechanism.slice(1, -1).trim();
if (mechanism.length === 0) return '';
if (mechanism === '7-bit') {
mechanism = '7bit';
} else if (mechanism === '8-bit') {
mechanism = '8bit';
} else if (mechanism === 'base-64') {
mechanism = 'base64';
} else if (mechanism === 'quotedprintable') {
mechanism = 'quoted-printable';
}
// RFC 2045 6.4 Interpretation and Use
// Any entity with an unrecognized Content-Transfer-Encoding must be
// treated as if it has a Content-Type of "application/octet-stream",
// regardless of what the Content-Type header field actually says.
// Non-Spec: We rather raise an exception for unknown mechanisms:
if (!/(7bit|8bit|binary|base64|quoted-printable)/.test(mechanism)) {
throw new Error(self.Error.ContentTransferEncodingUnrecognized);
}
return mechanism;
};
MIME.decodeHeaderContentType = function(buffer) {
var self = this;
buffer = self.decodeHeaderBuffer(buffer, false);
if (!buffer) {
// RFC 2045 5.2 Content-Type Defaults
//
// Default RFC 822 messages without a MIME Content-Type header are taken
// by this protocol to be plain text in the US-ASCII character set,
// which can be explicitly specified as:
//
// Content-type: text/plain; charset=us-ascii
//
// This default is assumed if no Content-Type header field is specified.
// It is also recommend that this default be assumed when a
// syntactically invalid Content-Type header field is encountered. In
// the presence of a MIME-Version header field and the absence of any
// Content-Type header field, a receiving User Agent can also assume
// that plain US-ASCII text was the sender's intent. Plain US-ASCII
// text may still be assumed in the absence of a MIME-Version or the
// presence of an syntactically invalid Content-Type header field, but
// the sender's intent might have been otherwise.
buffer = Buffer.from('text/plain;charset=us-ascii');
}
var header = self.decodeHeaderValueParameters(
self.decodeHeaderRemoveComments(
self.decodeHeaderUnfold(buffer)
)
);
// Map invalid content types:
if (self.decodeHeaderContentTypeInvalid.hasOwnProperty(header.value)) {
header.value = self.decodeHeaderContentTypeInvalid[header.value];
}
if (!/^\S+\/\S+$/.test(header.value)) {
// RFC 2045 5.1 Syntax of the Content-Type Header Field
// Note also that a subtype specification is MANDATORY -- it may not be
// omitted from a Content-Type header field. As such, there are no
// default subtypes.
// TO DO: Add separate error message for missing subtype.
throw new Error(self.Error.ContentType);
}
if (/^message\/external-body$/i.test(header.value)) {
// Presents several security risks.
// https://technet.microsoft.com/en-us/library/hh547013(v=exchg.141).aspx
throw new Error(self.Error.ContentTypeExternalBody);
} else if (/^message\/partial$/i.test(header.value)) {
// Prevent anti-virus from being defeated by split attachment content.
// https://technet.microsoft.com/en-us/library/hh547013(v=exchg.141).aspx
throw new Error(self.Error.ContentTypePartial);
}
if (/^multipart\//i.test(header.value)) {
// RFC 2045 5 Content-Type Header Field
// ...the "boundary" parameter is required for any subtype of
// the "multipart" media type.
if (!header.parameters.hasOwnProperty('boundary')) {
throw new Error(self.Error.ContentTypeBoundaryMissing);
}
}
return header;
};
MIME.decodeHeaderContentTypeInvalid = {
'jpeg file/octet-stream': 'application/octet-stream'
};
MIME.decodeHeaderDate = function(buffer) {
var self = this;
buffer = self.decodeHeaderBuffer(buffer, false);
if (!buffer) return undefined;
buffer = self.decodeHeaderUnfold(buffer);
buffer = self.decodeHeaderRemoveComments(buffer);
var string = self.slice(
buffer,
0,
buffer.length,
self.TRIM | self.UPPERCASE | self.ASCII
);
var match = string.match(self.decodeHeaderDateRegex);
if (!match) return self.decodeHeaderDateInvalid(string);
var dayname = match[1] || '';
var day = parseInt(match[2], 10);
if (self.decodeHeaderDateMonth.hasOwnProperty(match[3])) {
var month = self.decodeHeaderDateMonth[match[3]];
} else {
throw new Error(self.Error.DateMonth);
}
// RFC 5322 4.3 Obsolete Date and Time
// Where a two or three digit year occurs in a date, the year is to be
// interpreted as follows: If a two digit year is encountered whose
// value is between 00 and 49, the year is interpreted by adding 2000,
// ending up with a value between 2000 and 2049. If a two digit year is
// encountered with a value between 50 and 99, or any three digit year
// is encountered, the year is interpreted by adding 1900.
var year = parseInt(match[4], 10);
if (match[4].length === 2) {
year += (year < 50) ? 2000 : 1900;
} else if (match[4].length === 3) {
year += 1900;
}
var hour = parseInt(match[5], 10);
var minute = parseInt(match[6], 10);
var second = parseInt((match[7] || '0').replace(/:/, ''), 10);
// RFC 5322 3.3 Date and Time Specification
// The form "+0000" SHOULD be used to indicate a time zone at
// Universal Time.
// Some BlackBerry clients (e.g. version 10.0.10.738) do not supply the zone.
// The date-time they provide is in UTC.
// Non-Spec: We accept a missing time zone and assume UTC.
var zone = (match[8] || '').replace(/\s/g, '') || '+0000';
if (/^[A-Z]+$/.test(zone)) {
if (self.decodeHeaderDateZones.hasOwnProperty(zone)) {
zone = self.decodeHeaderDateZones[zone];
} else {
throw new Error(self.Error.DateZone);
}
}
while (zone.length < 5) zone += '0';
var zoneHour = parseInt(zone.slice(1, 3), 10);
var zoneMinute = parseInt(zone.slice(-2), 10);
// RFC 5322 3.3 Date and Time Specification
// A date-time specification MUST be semantically valid. That is, the
// day-of-week (if included) MUST be the day implied by the date, the
// numeric day-of-month MUST be between 1 and the number of days allowed
// for the specified month (in the specified year), the time-of-day MUST
// be in the range 00:00:00 through 23:59:60 (the number of seconds
// allowing for a leap second; see [RFC1305]), and the last two digits
// of the zone MUST be within the range 00 through 59.
if (day === 0 || day > 31) throw new Error(self.Error.DateDay);
if (month === 0 || month > 12) throw new Error(self.Error.DateMonth);
if (hour > 23) throw new Error(self.Error.DateHour);
if (minute > 59) throw new Error(self.Error.DateMinute);
if (second > 60) throw new Error(self.Error.DateSecond);
if (zoneHour > 23) throw new Error(self.Error.DateZone);
if (zoneMinute > 59) throw new Error(self.Error.DateZone);
// RFC 5322 3.3 Date and Time Specification
// The date and time-of-day SHOULD express local time.
// The variables we have express local time (ahead or behind) UTC.
// Date.UTC() uses universal time instead of the local time.
// If the local date-time we provide to Date.UTC() is ahead of UTC, Date.UTC()
// will return a timestamp ahead of UTC. We should subtract the zone offset.
// If the local date-time we provide to Date.UTC() is behind UTC, Date.UTC()
// will return a timestamp behind UTC. We should add the zone offset.
var offset = ((zoneHour * 60) + zoneMinute) * 60 * 1000;
var timestamp = Date.UTC(year, month - 1, day, hour, minute, second);
if (zone[0] === '+') {
timestamp -= offset;
} else {
timestamp += offset;
}
return timestamp;
};
MIME.decodeHeaderDateInvalid = function(string) {
var self = this;
var match = string.match(self.decodeHeaderDateInvalidRegex);
if (!match) throw new Error(self.Error.Date);
var day = parseInt(match[1], 10);
if (self.decodeHeaderDateMonth.hasOwnProperty(match[2])) {
var month = self.decodeHeaderDateMonth[match[2]];
} else {
throw new Error(self.Error.DateMonth);
}
var year = parseInt(match[3], 10);
var hour = parseInt(match[4], 10);
var minute = parseInt(match[5], 10);
var second = parseInt(match[6], 10);
if (day === 0 || day > 31) throw new Error(self.Error.DateDay);
if (month === 0 || month > 12) throw new Error(self.Error.DateMonth);
if (hour > 23) throw new Error(self.Error.DateHour);
if (minute > 59) throw new Error(self.Error.DateMinute);
if (second > 60) throw new Error(self.Error.DateSecond);
return Date.UTC(year, month - 1, day, hour, minute, second);
};
MIME.decodeHeaderDateInvalidRegex = /^(\d{1,2})-(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)-(\d{4})\s+(\d{1,2}):(\d{1,2}):(\d{1,2})$/;
MIME.decodeHeaderDateMonth = {
JAN: 1,
FEB: 2,
MAR: 3,
APR: 4,
MAY: 5,
JUN: 6,
JUL: 7,
AUG: 8,
SEP: 9,
OCT: 10,
NOV: 11,
DEC: 12
};
MIME.decodeHeaderDateRegex = /^(MON|TUE|WED|THU|FRI|SAT|SUN)?\s*,?\s*(\d{1,2})\s*(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)\s*(\d{2,4})\s+(\d{1,2}):(\d{1,2})(:\d{1,2})?\s*([+-]\s*\d{2,4}|[A-Z]{1,5})?\s*$/;
MIME.decodeHeaderDateZones = {
ACDT: '+1030',
ACST: '+0930',
ACT: '+0800',
ADT: '-0300',
AEDT: '+1100',
AEST: '+1000',