-
Notifications
You must be signed in to change notification settings - Fork 100
/
MimeUtility.java
1842 lines (1712 loc) · 62.8 KB
/
MimeUtility.java
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
/*
* Copyright (c) 1997, 2023 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0, which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception, which is available at
* https://www.gnu.org/software/classpath/license.html.
*
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
package jakarta.mail.internet;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Properties;
import java.util.StringTokenizer;
import jakarta.activation.DataHandler;
import jakarta.activation.DataSource;
import jakarta.mail.EncodingAware;
import jakarta.mail.MessagingException;
import jakarta.mail.util.LineInputStream;
import jakarta.mail.util.StreamProvider;
import jakarta.mail.util.StreamProvider.EncoderTypes;
/**
* This is a utility class that provides various MIME related
* functionality. <p>
*
* There are a set of methods to encode and decode MIME headers as
* per RFC 2047. Note that, in general, these methods are
* <strong>not</strong> needed when using methods such as
* <code>setSubject</code> and <code>setRecipients</code>; Jakarta Mail
* will automatically encode and decode data when using these "higher
* level" methods. The methods below are only needed when maniuplating
* raw MIME headers using <code>setHeader</code> and <code>getHeader</code>
* methods. A brief description on handling such headers is given below: <p>
*
* RFC 822 mail headers <strong>must</strong> contain only US-ASCII
* characters. Headers that contain non US-ASCII characters must be
* encoded so that they contain only US-ASCII characters. Basically,
* this process involves using either BASE64 or QP to encode certain
* characters. RFC 2047 describes this in detail. <p>
*
* In Java, Strings contain (16 bit) Unicode characters. ASCII is a
* subset of Unicode (and occupies the range 0 - 127). A String
* that contains only ASCII characters is already mail-safe. If the
* String contains non US-ASCII characters, it must be encoded. An
* additional complexity in this step is that since Unicode is not
* yet a widely used charset, one might want to first charset-encode
* the String into another charset and then do the transfer-encoding.
* <p>
* Note that to get the actual bytes of a mail-safe String (say,
* for sending over SMTP), one must do
* <blockquote><pre>
*
* byte[] bytes = string.getBytes("iso-8859-1");
*
* </pre></blockquote><p>
*
* The <code>setHeader</code> and <code>addHeader</code> methods
* on MimeMessage and MimeBodyPart assume that the given header values
* are Unicode strings that contain only US-ASCII characters. Hence
* the callers of those methods must insure that the values they pass
* do not contain non US-ASCII characters. The methods in this class
* help do this. <p>
*
* The <code>getHeader</code> family of methods on MimeMessage and
* MimeBodyPart return the raw header value. These might be encoded
* as per RFC 2047, and if so, must be decoded into Unicode Strings.
* The methods in this class help to do this. <p>
*
* Several System properties control strict conformance to the MIME
* spec. Note that these are not session properties but must be set
* globally as System properties. <p>
*
* The <code>mail.mime.decodetext.strict</code> property controls
* decoding of MIME encoded words. The MIME spec requires that encoded
* words start at the beginning of a whitespace separated word. Some
* mailers incorrectly include encoded words in the middle of a word.
* If the <code>mail.mime.decodetext.strict</code> System property is
* set to <code>"false"</code>, an attempt will be made to decode these
* illegal encoded words. The default is true. <p>
*
* The <code>mail.mime.encodeeol.strict</code> property controls the
* choice of Content-Transfer-Encoding for MIME parts that are not of
* type "text". Often such parts will contain textual data for which
* an encoding that allows normal end of line conventions is appropriate.
* In rare cases, such a part will appear to contain entirely textual
* data, but will require an encoding that preserves CR and LF characters
* without change. If the <code>mail.mime.encodeeol.strict</code>
* System property is set to <code>"true"</code>, such an encoding will
* be used when necessary. The default is false. <p>
*
* In addition, the <code>mail.mime.charset</code> System property can
* be used to specify the default MIME charset to use for encoded words
* and text parts that don't otherwise specify a charset. Normally, the
* default MIME charset is derived from the default Java charset, as
* specified in the <code>file.encoding</code> System property. Most
* applications will have no need to explicitly set the default MIME
* charset. In cases where the default MIME charset to be used for
* mail messages is different than the charset used for files stored on
* the system, this property should be set. <p>
*
* The current implementation also supports the following System property.
* <p>
* The <code>mail.mime.ignoreunknownencoding</code> property controls
* whether unknown values in the <code>Content-Transfer-Encoding</code>
* header, as passed to the <code>decode</code> method, cause an exception.
* If set to <code>"true"</code>, unknown values are ignored and 8bit
* encoding is assumed. Otherwise, unknown values cause a MessagingException
* to be thrown.
*
* @author John Mani
* @author Bill Shannon
*/
public class MimeUtility {
// This class cannot be instantiated
private MimeUtility() { }
public static final int ALL = -1;
// cached map of whether a charset is compatible with ASCII
// Map<String,Boolean>
private static final Map<String, Boolean> nonAsciiCharsetMap
= new HashMap<>();
private static final String WORD_SPECIALS = "=_?\"#$%&'(),.:;<>@[\\]^`{|}~";
private static final String TEXT_SPECIALS = "=_?";
private static final boolean decodeStrict = getBooleanSystemProperty("mail.mime.decodetext.strict", true);
private static final boolean encodeEolStrict = getBooleanSystemProperty("mail.mime.encodeeol.strict", false);
private static final boolean ignoreUnknownEncoding = getBooleanSystemProperty(
"mail.mime.ignoreunknownencoding", false);
private static final boolean allowUtf8 = getBooleanSystemProperty("mail.mime.allowutf8", false);
/*
* The following two properties allow disabling the fold()
* and unfold() methods and reverting to the previous behavior.
* They should never need to be changed and are here only because
* of my paranoid concern with compatibility.
*/
private static final boolean foldEncodedWords = getBooleanSystemProperty("mail.mime.foldencodedwords", false);
private static final boolean foldText = getBooleanSystemProperty("mail.mime.foldtext", true);
/**
* Get the Content-Transfer-Encoding that should be applied
* to the input stream of this DataSource, to make it mail-safe. <p>
*
* The algorithm used here is: <br>
* <ul>
* <li>
* If the DataSource implements {@link EncodingAware}, ask it
* what encoding to use. If it returns non-null, return that value.
* <li>
* If the primary type of this datasource is "text" and if all
* the bytes in its input stream are US-ASCII, then the encoding
* is StreamProvider.BIT7_ENCODER. If more than half of the bytes are non-US-ASCII, then
* the encoding is StreamProvider.BASE_64_ENCODER. If less than half of the bytes are
* non-US-ASCII, then the encoding is StreamProvider.QUOTED_PRINTABLE_ENCODER.
* <li>
* If the primary type of this datasource is not "text", then if
* all the bytes of its input stream are US-ASCII, the encoding
* is StreamProvider.BIT7_ENCODER. If there is even one non-US-ASCII character, the
* encoding is StreamProvider.BASE_64_ENCODER.
* </ul>
*
* @param ds the DataSource
* @return the encoding. This is either StreamProvider.BIT7_ENCODER,
* StreamProvider.QUOTED_PRINTABLE_ENCODER or StreamProvider.BASE_64_ENCODER
*/
public static String getEncoding(DataSource ds) {
ContentType cType = null;
InputStream is = null;
String encoding = null;
if (ds instanceof EncodingAware) {
encoding = ((EncodingAware)ds).getEncoding();
if (encoding != null)
return encoding;
}
try {
cType = new ContentType(ds.getContentType());
is = ds.getInputStream();
boolean isText = cType.match("text/*");
// if not text, stop processing when we see non-ASCII
int i = checkAscii(is, ALL, !isText);
switch (i) {
case ALL_ASCII:
encoding = EncoderTypes.BIT7_ENCODER.getEncoder(); // all ASCII
break;
case MOSTLY_ASCII:
if (isText && nonAsciiCharset(cType))
encoding = EncoderTypes.BASE_64.getEncoder(); // charset isn't compatible with ASCII
else
encoding = EncoderTypes.QUOTED_PRINTABLE_ENCODER.getEncoder(); // mostly ASCII
break;
default:
encoding = EncoderTypes.BASE_64.getEncoder(); // mostly binary
break;
}
} catch (Exception ex) {
return EncoderTypes.BASE_64.getEncoder(); // what else ?!
} finally {
// Close the input stream
try {
if (is != null)
is.close();
} catch (IOException ioex) { }
}
return encoding;
}
/**
* Determine whether the charset in the Content-Type is compatible
* with ASCII or not. A charset is compatible with ASCII if the
* encoded byte stream representing the Unicode string "\r\n" is
* the ASCII characters CR and LF. For example, the utf-16be
* charset is not compatible with ASCII.
*
* For performance, we keep a static map that caches the results.
*/
private static boolean nonAsciiCharset(ContentType ct) {
String charset = ct.getParameter("charset");
if (charset == null)
return false;
charset = charset.toLowerCase(Locale.ENGLISH);
Boolean bool;
synchronized (nonAsciiCharsetMap) {
bool = nonAsciiCharsetMap.get(charset);
}
if (bool == null) {
try {
byte[] b = "\r\n".getBytes(charset);
bool = Boolean.valueOf(
b.length != 2 || b[0] != 015 || b[1] != 012);
} catch (UnsupportedEncodingException uex) {
bool = Boolean.FALSE; // a guess
} catch (RuntimeException ex) {
bool = Boolean.TRUE; // one of the weird ones?
}
synchronized (nonAsciiCharsetMap) {
nonAsciiCharsetMap.put(charset, bool);
}
}
return bool.booleanValue();
}
/**
* Same as <code>getEncoding(DataSource)</code> except that instead
* of reading the data from an <code>InputStream</code> it uses the
* <code>writeTo</code> method to examine the data. This is more
* efficient in the common case of a <code>DataHandler</code>
* created with an object and a MIME type (for example, a
* "text/plain" String) because all the I/O is done in this
* thread. In the case requiring an <code>InputStream</code> the
* <code>DataHandler</code> uses a thread, a pair of pipe streams,
* and the <code>writeTo</code> method to produce the data.
*
* @param dh the DataHandler
* @return the Content-Transfer-Encoding
* @since JavaMail 1.2
*/
public static String getEncoding(DataHandler dh) {
ContentType cType = null;
String encoding = null;
/*
* Try to pick the most efficient means of determining the
* encoding. If this DataHandler was created using a DataSource,
* the getEncoding(DataSource) method is typically faster. If
* the DataHandler was created with an object, this method is
* much faster. To distinguish the two cases, we use a heuristic.
* A DataHandler created with an object will always have a null name.
* A DataHandler created with a DataSource will usually have a
* non-null name.
*
* XXX - This is actually quite a disgusting hack, but it makes
* a common case run over twice as fast.
*/
if (dh.getName() != null)
return getEncoding(dh.getDataSource());
try {
cType = new ContentType(dh.getContentType());
} catch (Exception ex) {
return EncoderTypes.BASE_64.getEncoder(); // what else ?!
}
if (cType.match("text/*")) {
// Check all of the available bytes
AsciiOutputStream aos = new AsciiOutputStream(false, false);
try {
dh.writeTo(aos);
} catch (IOException ex) {
// ignore it, can't happen
}
switch (aos.getAscii()) {
case ALL_ASCII:
encoding = EncoderTypes.BIT7_ENCODER.getEncoder(); // all ascii
break;
case MOSTLY_ASCII:
encoding = EncoderTypes.QUOTED_PRINTABLE_ENCODER.getEncoder(); // mostly ascii
break;
default:
encoding = EncoderTypes.BASE_64.getEncoder(); // mostly binary
break;
}
} else { // not "text"
// Check all of available bytes, break out if we find
// at least one non-US-ASCII character
AsciiOutputStream aos =
new AsciiOutputStream(true, encodeEolStrict);
try {
dh.writeTo(aos);
} catch (IOException ex) { } // ignore it
if (aos.getAscii() == ALL_ASCII) // all ascii
encoding = EncoderTypes.BIT7_ENCODER.getEncoder();
else // found atleast one non-ascii character, use b64
encoding = EncoderTypes.BASE_64.getEncoder();
}
return encoding;
}
/**
* Decode the given input stream. The Input stream returned is
* the decoded input stream. All the encodings defined in RFC 2045
* are supported here. They include StreamProvider.BASE_64_ENCODER, StreamProvider.QUOTED_PRINTABLE_ENCODER,
* StreamProvider.BIT7_ENCODER, StreamProvider.BIT8_ENCODER, and StreamProvider.BINARY_ENCODER. In addition, StreamProvider.UU_ENCODER is also
* supported. <p>
*
* In the current implementation, if the
* <code>mail.mime.ignoreunknownencoding</code> system property is set to
* <code>"true"</code>, unknown encoding values are ignored and the
* original InputStream is returned.
*
* @param is input stream
* @param encoding the encoding of the stream.
* @return decoded input stream.
* @exception MessagingException if the encoding is unknown
*/
public static InputStream decode(InputStream is, String encoding)
throws MessagingException {
if (encoding.equalsIgnoreCase(EncoderTypes.BASE_64.getEncoder()))
return StreamProvider.provider().inputBase64(is);
else if (encoding.equalsIgnoreCase(EncoderTypes.QUOTED_PRINTABLE_ENCODER.getEncoder()))
return StreamProvider.provider().inputQP(is);
else if (encoding.equalsIgnoreCase(EncoderTypes.UU_ENCODER.getEncoder()) ||
encoding.equalsIgnoreCase(EncoderTypes.X_UU_ENCODER.getEncoder()) ||
encoding.equalsIgnoreCase(EncoderTypes.X_UUE.getEncoder()))
return StreamProvider.provider().inputUU(is);
else if (encoding.equalsIgnoreCase(EncoderTypes.BINARY_ENCODER.getEncoder()) ||
encoding.equalsIgnoreCase(EncoderTypes.BIT7_ENCODER.getEncoder()) ||
encoding.equalsIgnoreCase(EncoderTypes.BIT8_ENCODER.getEncoder()))
return StreamProvider.provider().inputBinary(is);
else {
if (!ignoreUnknownEncoding)
throw new MessagingException("Unknown encoding: " + encoding);
return is;
}
}
/**
* Wrap an encoder around the given output stream.
* All the encodings defined in RFC 2045 are supported here.
* They include StreamProvider.BASE_64_ENCODER, StreamProvider.QUOTED_PRINTABLE_ENCODER, StreamProvider.BIT7_ENCODER, StreamProvider.BIT8_ENCODER and
* StreamProvider.BINARY_ENCODER. In addition, StreamProvider.UU_ENCODER is also supported.
*
* @param os output stream
* @param encoding the encoding of the stream.
* @return output stream that applies the
* specified encoding.
* @exception MessagingException if the encoding is unknown
*/
public static OutputStream encode(OutputStream os, String encoding)
throws MessagingException {
if (encoding == null)
return os;
else if (encoding.equalsIgnoreCase(EncoderTypes.BASE_64.getEncoder()))
return StreamProvider.provider().outputBase64(os);
else if (encoding.equalsIgnoreCase(EncoderTypes.QUOTED_PRINTABLE_ENCODER.getEncoder()))
return StreamProvider.provider().outputQP(os);
else if (encoding.equalsIgnoreCase(EncoderTypes.UU_ENCODER.getEncoder()) ||
encoding.equalsIgnoreCase(EncoderTypes.X_UU_ENCODER.getEncoder()) ||
encoding.equalsIgnoreCase(EncoderTypes.X_UUE.getEncoder()))
return StreamProvider.provider().outputUU(os, null);
else if (encoding.equalsIgnoreCase(EncoderTypes.BINARY_ENCODER.getEncoder()) ||
encoding.equalsIgnoreCase(EncoderTypes.BIT7_ENCODER.getEncoder()) ||
encoding.equalsIgnoreCase(EncoderTypes.BIT8_ENCODER.getEncoder()))
return StreamProvider.provider().outputBinary(os);
else
throw new MessagingException("Unknown encoding: " +encoding);
}
/**
* Wrap an encoder around the given output stream.
* All the encodings defined in RFC 2045 are supported here.
* They include StreamProvider.BASE_64_ENCODER, StreamProvider.QUOTED_PRINTABLE_ENCODER, StreamProvider.BIT7_ENCODER, StreamProvider.BIT8_ENCODER and
* StreamProvider.BINARY_ENCODER. In addition, StreamProvider.UU_ENCODER is also supported.
* The <code>filename</code> parameter is used with the StreamProvider.UU_ENCODER
* encoding and is included in the encoded output.
*
* @param os output stream
* @param encoding the encoding of the stream.
* @param filename name for the file being encoded (only used
* with uuencode)
* @return output stream that applies the
* specified encoding.
* @exception MessagingException for unknown encodings
* @since JavaMail 1.2
*/
public static OutputStream encode(OutputStream os, String encoding,
String filename)
throws MessagingException {
if (encoding == null)
return os;
else if (encoding.equalsIgnoreCase(EncoderTypes.BASE_64.getEncoder()))
return StreamProvider.provider().outputBase64(os);
else if (encoding.equalsIgnoreCase(EncoderTypes.QUOTED_PRINTABLE_ENCODER.getEncoder()))
return StreamProvider.provider().outputQP(os);
else if (encoding.equalsIgnoreCase(EncoderTypes.UU_ENCODER.getEncoder()) ||
encoding.equalsIgnoreCase(EncoderTypes.X_UU_ENCODER.getEncoder()) ||
encoding.equalsIgnoreCase(EncoderTypes.X_UUE.getEncoder()))
return StreamProvider.provider().outputUU(os, filename);
else if (encoding.equalsIgnoreCase(EncoderTypes.BINARY_ENCODER.getEncoder()) ||
encoding.equalsIgnoreCase(EncoderTypes.BIT7_ENCODER.getEncoder()) ||
encoding.equalsIgnoreCase(EncoderTypes.BIT8_ENCODER.getEncoder()))
return StreamProvider.provider().outputBinary(os);
else
throw new MessagingException("Unknown encoding: " +encoding);
}
/**
* Encode a RFC 822 "text" token into mail-safe form as per
* RFC 2047. <p>
*
* The given Unicode string is examined for non US-ASCII
* characters. If the string contains only US-ASCII characters,
* it is returned as-is. If the string contains non US-ASCII
* characters, it is first character-encoded using the platform's
* default charset, then transfer-encoded using either the B or
* Q encoding. The resulting bytes are then returned as a Unicode
* string containing only ASCII characters. <p>
*
* Note that this method should be used to encode only
* "unstructured" RFC 822 headers. <p>
*
* Example of usage:
* <blockquote><pre>
*
* MimePart part = ...
* String rawvalue = "FooBar Mailer, Japanese version 1.1"
* try {
* // If we know for sure that rawvalue contains only US-ASCII
* // characters, we can skip the encoding part
* part.setHeader("X-mailer", MimeUtility.encodeText(rawvalue));
* } catch (UnsupportedEncodingException e) {
* // encoding failure
* } catch (MessagingException me) {
* // setHeader() failure
* }
*
* </pre></blockquote>
*
* @param text Unicode string
* @return Unicode string containing only US-ASCII characters
* @exception UnsupportedEncodingException if the encoding fails
*/
public static String encodeText(String text)
throws UnsupportedEncodingException {
return encodeText(text, null, null);
}
/**
* Encode a RFC 822 "text" token into mail-safe form as per
* RFC 2047. <p>
*
* The given Unicode string is examined for non US-ASCII
* characters. If the string contains only US-ASCII characters,
* it is returned as-is. If the string contains non US-ASCII
* characters, it is first character-encoded using the specified
* charset, then transfer-encoded using either the B or Q encoding.
* The resulting bytes are then returned as a Unicode string
* containing only ASCII characters. <p>
*
* Note that this method should be used to encode only
* "unstructured" RFC 822 headers.
*
* @param text the header value
* @param charset the charset. If this parameter is null, the
* platform's default chatset is used.
* @param encoding the encoding to be used. Currently supported
* values are "B" and "Q". If this parameter is null, then
* the "Q" encoding is used if most of characters to be
* encoded are in the ASCII charset, otherwise "B" encoding
* is used.
* @return Unicode string containing only US-ASCII characters
* @exception UnsupportedEncodingException if the charset
* conversion failed.
*/
public static String encodeText(String text, String charset,
String encoding)
throws UnsupportedEncodingException {
return encodeWord(text, charset, encoding, false);
}
/**
* Decode "unstructured" headers, that is, headers that are defined
* as '*text' as per RFC 822. <p>
*
* The string is decoded using the algorithm specified in
* RFC 2047, Section 6.1. If the charset-conversion fails
* for any sequence, an UnsupportedEncodingException is thrown.
* If the String is not an RFC 2047 style encoded header, it is
* returned as-is <p>
*
* Example of usage:
* <blockquote><pre>
*
* MimePart part = ...
* String rawvalue = null;
* String value = null;
* try {
* if ((rawvalue = part.getHeader("X-mailer")[0]) != null)
* value = MimeUtility.decodeText(rawvalue);
* } catch (UnsupportedEncodingException e) {
* // Don't care
* value = rawvalue;
* } catch (MessagingException me) { }
*
* return value;
*
* </pre></blockquote>
*
* @param etext the possibly encoded value
* @return the decoded text
* @exception UnsupportedEncodingException if the charset
* conversion failed.
*/
public static String decodeText(String etext)
throws UnsupportedEncodingException {
/*
* We look for sequences separated by "linear-white-space".
* (as per RFC 2047, Section 6.1)
* RFC 822 defines "linear-white-space" as SPACE | HT | CR | NL.
*/
String lwsp = " \t\n\r";
StringTokenizer st;
/*
* First, lets do a quick run thru the string and check
* whether the sequence "=?" exists at all. If none exists,
* we know there are no encoded-words in here and we can just
* return the string as-is, without suffering thru the later
* decoding logic.
* This handles the most common case of unencoded headers
* efficiently.
*/
if (etext.indexOf("=?") == -1)
return etext;
// Encoded words found. Start decoding ...
st = new StringTokenizer(etext, lwsp, true);
StringBuilder sb = new StringBuilder(); // decode buffer
StringBuilder wsb = new StringBuilder(); // white space buffer
boolean prevWasEncoded = false;
while (st.hasMoreTokens()) {
char c;
String s = st.nextToken();
// If whitespace, append it to the whitespace buffer
if (((c = s.charAt(0)) == ' ') || (c == '\t') ||
(c == '\r') || (c == '\n'))
wsb.append(c);
else {
// Check if token is an 'encoded-word' ..
String word;
try {
word = decodeWord(s);
// Yes, this IS an 'encoded-word'.
if (!prevWasEncoded && wsb.length() > 0) {
// if the previous word was also encoded, we
// should ignore the collected whitespace. Else
// we include the whitespace as well.
sb.append(wsb);
}
prevWasEncoded = true;
} catch (ParseException pex) {
// This is NOT an 'encoded-word'.
word = s;
// possibly decode inner encoded words
if (!decodeStrict) {
String dword = decodeInnerWords(word);
if (dword != word) {
// if a different String object was returned,
// decoding was done.
if (prevWasEncoded && word.startsWith("=?")) {
// encoded followed by encoded,
// throw away whitespace between
} else {
// include collected whitespace ..
if (wsb.length() > 0)
sb.append(wsb);
}
// did original end with encoded?
prevWasEncoded = word.endsWith("?=");
word = dword;
} else {
// include collected whitespace ..
if (wsb.length() > 0)
sb.append(wsb);
prevWasEncoded = false;
}
} else {
// include collected whitespace ..
if (wsb.length() > 0)
sb.append(wsb);
prevWasEncoded = false;
}
}
sb.append(word); // append the actual word
wsb.setLength(0); // reset wsb for reuse
}
}
sb.append(wsb); // append trailing whitespace
return sb.toString();
}
/**
* Encode a RFC 822 "word" token into mail-safe form as per
* RFC 2047. <p>
*
* The given Unicode string is examined for non US-ASCII
* characters. If the string contains only US-ASCII characters,
* it is returned as-is. If the string contains non US-ASCII
* characters, it is first character-encoded using the platform's
* default charset, then transfer-encoded using either the B or
* Q encoding. The resulting bytes are then returned as a Unicode
* string containing only ASCII characters. <p>
*
* This method is meant to be used when creating RFC 822 "phrases".
* The InternetAddress class, for example, uses this to encode
* it's 'phrase' component.
*
* @param word Unicode string
* @return Array of Unicode strings containing only US-ASCII
* characters.
* @exception UnsupportedEncodingException if the encoding fails
*/
public static String encodeWord(String word)
throws UnsupportedEncodingException {
return encodeWord(word, null, null);
}
/**
* Encode a RFC 822 "word" token into mail-safe form as per
* RFC 2047. <p>
*
* The given Unicode string is examined for non US-ASCII
* characters. If the string contains only US-ASCII characters,
* it is returned as-is. If the string contains non US-ASCII
* characters, it is first character-encoded using the specified
* charset, then transfer-encoded using either the B or Q encoding.
* The resulting bytes are then returned as a Unicode string
* containing only ASCII characters.
*
* @param word Unicode string
* @param charset the MIME charset
* @param encoding the encoding to be used. Currently supported
* values are "B" and "Q". If this parameter is null, then
* the "Q" encoding is used if most of characters to be
* encoded are in the ASCII charset, otherwise "B" encoding
* is used.
* @return Unicode string containing only US-ASCII characters
* @exception UnsupportedEncodingException if the encoding fails
*/
public static String encodeWord(String word, String charset,
String encoding)
throws UnsupportedEncodingException {
return encodeWord(word, charset, encoding, true);
}
/*
* Encode the given string. The parameter 'encodingWord' should
* be true if a RFC 822 "word" token is being encoded and false if a
* RFC 822 "text" token is being encoded. This is because the
* "Q" encoding defined in RFC 2047 has more restrictions when
* encoding "word" tokens. (Sigh)
*/
private static String encodeWord(String string, String charset,
String encoding, boolean encodingWord)
throws UnsupportedEncodingException {
// If 'string' contains only US-ASCII characters, just
// return it.
int ascii = checkAscii(string);
if (ascii == ALL_ASCII)
return string;
// Else, apply the specified charset conversion.
String jcharset;
if (charset == null) { // use default charset
jcharset = getDefaultJavaCharset(); // the java charset
charset = getDefaultMIMECharset(); // the MIME equivalent
} else // MIME charset -> java charset
jcharset = javaCharset(charset);
// If no transfer-encoding is specified, figure one out.
if (encoding == null) {
if (ascii != MOSTLY_NONASCII)
encoding = "Q";
else
encoding = "B";
}
boolean b64;
if (encoding.equalsIgnoreCase("B"))
b64 = true;
else if (encoding.equalsIgnoreCase("Q"))
b64 = false;
else
throw new UnsupportedEncodingException(
"Unknown transfer encoding: " + encoding);
StringBuilder outb = new StringBuilder(); // the output buffer
doEncode(string, b64, jcharset,
// As per RFC 2047, size of an encoded string should not
// exceed 75 bytes.
// 7 = size of "=?", '?', 'B'/'Q', '?', "?="
75 - 7 - charset.length(), // the available space
"=?" + charset + "?" + encoding + "?", // prefix
true, encodingWord, outb);
return outb.toString();
}
/**
* Returns the length of the encoded version of this byte array.
*
* @param b the byte array
* @return the length
*/
private static int bEncodedLength(byte[] b) {
return ((b.length + 2)/3) * 4;
}
/**
* Returns the length of the encoded version of this byte array.
*
* @param b the byte array
* @param encodingWord true if encoding words, false if encoding text
* @return the length
*/
private static int qEncodedLength(byte[] b, boolean encodingWord) {
int len = 0;
String specials = encodingWord ? WORD_SPECIALS: TEXT_SPECIALS;
for (int i = 0; i < b.length; i++) {
int c = b[i] & 0xff; // Mask off MSB
if (c < 040 || c >= 0177 || specials.indexOf(c) >= 0)
// needs encoding
len += 3; // Q-encoding is 1 -> 3 conversion
else
len++;
}
return len;
}
private static void doEncode(String string, boolean b64,
String jcharset, int avail, String prefix,
boolean first, boolean encodingWord, StringBuilder buf)
throws UnsupportedEncodingException {
// First find out what the length of the encoded version of
// 'string' would be.
byte[] bytes = string.getBytes(jcharset);
int len;
if (b64) // "B" encoding
len = bEncodedLength(bytes);
else // "Q"
len = qEncodedLength(bytes, encodingWord);
int size;
if ((len > avail) && ((size = string.length()) > 1)) {
// If the length is greater than 'avail', split 'string'
// into two and recurse.
// Have to make sure not to split a Unicode surrogate pair.
int split = size / 2;
if (Character.isHighSurrogate(string.charAt(split-1)))
split--;
if (split > 0)
doEncode(string.substring(0, split), b64, jcharset,
avail, prefix, first, encodingWord, buf);
doEncode(string.substring(split, size), b64, jcharset,
avail, prefix, false, encodingWord, buf);
} else {
// length <= than 'avail'. Encode the given string
ByteArrayOutputStream os = new ByteArrayOutputStream();
OutputStream eos; // the encoder
if (b64) { // "B" encoding
eos = StreamProvider.provider().outputB(os);
} else { // "Q" encoding
eos = StreamProvider.provider().outputQ(os, encodingWord);
}
try { // do the encoding
eos.write(bytes);
eos.close();
} catch (IOException ioex) { }
byte[] encodedBytes = os.toByteArray(); // the encoded stuff
// Now write out the encoded (all ASCII) bytes into our
// StringBuilder
if (!first) // not the first line of this sequence
if (foldEncodedWords)
buf.append("\r\n "); // start a continuation line
else
buf.append(" "); // line will be folded later
buf.append(prefix);
for (int i = 0; i < encodedBytes.length; i++)
buf.append((char)encodedBytes[i]);
buf.append("?="); // terminate the current sequence
}
}
/**
* The string is parsed using the rules in RFC 2047 and RFC 2231 for
* parsing an "encoded-word". If the parse fails, a ParseException is
* thrown. Otherwise, it is transfer-decoded, and then
* charset-converted into Unicode. If the charset-conversion
* fails, an UnsupportedEncodingException is thrown.
*
* @param eword the encoded value
* @return the decoded word
* @exception ParseException if the string is not an
* encoded-word as per RFC 2047 and RFC 2231.
* @exception UnsupportedEncodingException if the charset
* conversion failed.
*/
public static String decodeWord(String eword)
throws ParseException, UnsupportedEncodingException {
if (!eword.startsWith("=?")) // not an encoded word
throw new ParseException(
"encoded word does not start with \"=?\": " + eword);
// get charset
int start = 2; int pos;
if ((pos = eword.indexOf('?', start)) == -1)
throw new ParseException(
"encoded word does not include charset: " + eword);
String charset = eword.substring(start, pos);
int lpos = charset.indexOf('*'); // RFC 2231 language specified?
if (lpos >= 0) // yes, throw it away
charset = charset.substring(0, lpos);
charset = javaCharset(charset);
// get encoding
start = pos+1;
if ((pos = eword.indexOf('?', start)) == -1)
throw new ParseException(
"encoded word does not include encoding: " + eword);
String encoding = eword.substring(start, pos);
// get encoded-sequence
start = pos+1;
if ((pos = eword.indexOf("?=", start)) == -1)
throw new ParseException(
"encoded word does not end with \"?=\": " + eword);
/*
* XXX - should include this, but leaving it out for compatibility...
*
if (decodeStrict && pos != eword.length() - 2)
throw new ParseException(
"encoded word does not end with \"?=\": " + eword););
*/
String word = eword.substring(start, pos);
try {
String decodedWord;
if (word.length() > 0) {
// Extract the bytes from word
ByteArrayInputStream bis =
new ByteArrayInputStream(getBytes(word));
// Get the appropriate decoder
InputStream is;
if (encoding.equalsIgnoreCase("B"))
is = StreamProvider.provider().inputBase64(bis);
else if (encoding.equalsIgnoreCase("Q"))
is = StreamProvider.provider().inputQ(bis);
else
throw new UnsupportedEncodingException(
"unknown encoding: " + encoding);
// For b64 & q, size of decoded word <= size of word. So
// the decoded bytes must fit into the 'bytes' array. This
// is certainly more efficient than writing bytes into a
// ByteArrayOutputStream and then pulling out the byte[]
// from it.
int count = bis.available();
byte[] bytes = new byte[count];
// count is set to the actual number of decoded bytes
count = is.read(bytes, 0, count);
// Finally, convert the decoded bytes into a String using
// the specified charset
decodedWord = count <= 0 ? "" :
new String(bytes, 0, count, charset);
} else {
// no characters to decode, return empty string
decodedWord = "";
}
if (pos + 2 < eword.length()) {
// there's still more text in the string
String rest = eword.substring(pos + 2);
if (!decodeStrict)
rest = decodeInnerWords(rest);
decodedWord += rest;
}
return decodedWord;
} catch (UnsupportedEncodingException uex) {
// explicitly catch and rethrow this exception, otherwise
// the below IOException catch will swallow this up!
throw uex;
} catch (IOException ioex) {
// Shouldn't happen.
throw new ParseException(ioex.toString());
} catch (IllegalArgumentException iex) {
/* An unknown charset of the form ISO-XXX-XXX, will cause
* the JDK to throw an IllegalArgumentException ... Since the
* JDK will attempt to create a classname using this string,
* but valid classnames must not contain the character '-',
* and this results in an IllegalArgumentException, rather than
* the expected UnsupportedEncodingException. Yikes
*/
throw new UnsupportedEncodingException(charset);
}
}
/**
* Look for encoded words within a word. The MIME spec doesn't
* allow this, but many broken mailers, especially Japanese mailers,
* produce such incorrect encodings.
*/
private static String decodeInnerWords(String word)
throws UnsupportedEncodingException {
int start = 0, i;
StringBuilder buf = new StringBuilder();
while ((i = word.indexOf("=?", start)) >= 0) {
buf.append(word.substring(start, i));
// find first '?' after opening '=?' - end of charset
int end = word.indexOf('?', i + 2);
if (end < 0)
break;
// find next '?' after that - end of encoding
end = word.indexOf('?', end + 1);
if (end < 0)
break;
// find terminating '?='
end = word.indexOf("?=", end + 1);
if (end < 0)
break;
String s = word.substring(i, end + 2);
try {
s = decodeWord(s);
} catch (ParseException pex) {
// ignore it, just use the original string
}
buf.append(s);
start = end + 2;
}
if (start == 0)
return word;
if (start < word.length())
buf.append(word.substring(start));