This repository has been archived by the owner on Feb 20, 2020. It is now read-only.
/
SMTPTransport.java
2815 lines (2582 loc) · 84.7 KB
/
SMTPTransport.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
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 1997-2018 Oracle and/or its affiliates. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can
* obtain a copy of the License at
* https://oss.oracle.com/licenses/CDDL+GPL-1.1
* or LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at LICENSE.txt.
*
* GPL Classpath Exception:
* Oracle designates this particular file as subject to the "Classpath"
* exception as provided by Oracle in the GPL Version 2 section of the License
* file that accompanied this code.
*
* Modifications:
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* Contributor(s):
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package com.sun.mail.smtp;
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.logging.Level;
import java.lang.reflect.*;
import java.nio.charset.StandardCharsets;
import javax.net.ssl.SSLSocket;
import javax.mail.*;
import javax.mail.event.*;
import javax.mail.internet.*;
import com.sun.mail.util.PropUtil;
import com.sun.mail.util.MailLogger;
import com.sun.mail.util.ASCIIUtility;
import com.sun.mail.util.SocketFetcher;
import com.sun.mail.util.MailConnectException;
import com.sun.mail.util.SocketConnectException;
import com.sun.mail.util.BASE64EncoderStream;
import com.sun.mail.util.LineInputStream;
import com.sun.mail.util.TraceInputStream;
import com.sun.mail.util.TraceOutputStream;
import com.sun.mail.auth.Ntlm;
/**
* This class implements the Transport abstract class using SMTP for
* message submission and transport. <p>
*
* See the <a href="package-summary.html">com.sun.mail.smtp</a> package
* documentation for further information on the SMTP protocol provider. <p>
*
* This class includes many protected methods that allow a subclass to
* extend this class and add support for non-standard SMTP commands.
* The {@link #issueCommand} and {@link #sendCommand} methods can be
* used to send simple SMTP commands. Other methods such as the
* {@link #mailFrom} and {@link #data} methods can be overridden to
* insert new commands before or after the corresponding SMTP commands.
* For example, a subclass could do this to send the XACT command
* before sending the DATA command:
* <pre>
* protected OutputStream data() throws MessagingException {
* if (supportsExtension("XACCOUNTING"))
* issueCommand("XACT", 25);
* return super.data();
* }
* </pre>
*
* @author Max Spivak
* @author Bill Shannon
* @author Dean Gibson (DIGEST-MD5 authentication)
* @author Lu\u00EDs Serralheiro (NTLM authentication)
*
* @see javax.mail.event.ConnectionEvent
* @see javax.mail.event.TransportEvent
*/
public class SMTPTransport extends Transport {
private String name = "smtp"; // Name of this protocol
private int defaultPort = 25; // default SMTP port
private boolean isSSL = false; // use SSL?
private String host; // host we're connected to
// Following fields valid only during the sendMessage method.
private MimeMessage message; // Message to be sent
private Address[] addresses; // Addresses to which to send the msg
// Valid sent, valid unsent and invalid addresses
private Address[] validSentAddr, validUnsentAddr, invalidAddr;
// Did we send the message even though some addresses were invalid?
private boolean sendPartiallyFailed = false;
// If so, here's an exception we need to throw
private MessagingException exception;
// stream where message data is written
private SMTPOutputStream dataStream;
// Map of SMTP service extensions supported by server, if EHLO used.
private Hashtable<String, String> extMap;
private Map<String, Authenticator> authenticators
= new HashMap<>();
private String defaultAuthenticationMechanisms; // set in constructor
private boolean quitWait = false; // true if we should wait
private String saslRealm = UNKNOWN;
private String authorizationID = UNKNOWN;
private boolean enableSASL = false; // enable SASL authentication
private boolean useCanonicalHostName = false; // use canonical host name?
private String[] saslMechanisms = UNKNOWN_SA;
private String ntlmDomain = UNKNOWN; // for ntlm authentication
private boolean reportSuccess; // throw an exception even on success
private boolean useStartTLS; // use STARTTLS command
private boolean requireStartTLS; // require STARTTLS command
private boolean useRset; // use RSET instead of NOOP
private boolean noopStrict = true; // NOOP must return 250 for success
private MailLogger logger; // debug logger
private MailLogger traceLogger; // protocol trace logger
private String localHostName; // our own host name
private String lastServerResponse; // last SMTP response
private int lastReturnCode; // last SMTP return code
private boolean notificationDone; // only notify once per send
private SaslAuthenticator saslAuthenticator; // if SASL is being used
private boolean noauthdebug = true; // hide auth info in debug output
private boolean debugusername; // include username in debug output?
private boolean debugpassword; // include password in debug output?
private boolean allowutf8; // allow UTF-8 usernames and passwords?
private int chunkSize; // chunk size if CHUNKING supported
/** Headers that should not be included when sending */
private static final String[] ignoreList = { "Bcc", "Content-Length" };
private static final byte[] CRLF = { (byte)'\r', (byte)'\n' };
private static final String UNKNOWN = "UNKNOWN"; // place holder
private static final String[] UNKNOWN_SA = new String[0]; // place holder
/**
* Constructor that takes a Session object and a URLName
* that represents a specific SMTP server.
*
* @param session the Session
* @param urlname the URLName of this transport
*/
public SMTPTransport(Session session, URLName urlname) {
this(session, urlname, "smtp", false);
}
/**
* Constructor used by this class and by SMTPSSLTransport subclass.
*
* @param session the Session
* @param urlname the URLName of this transport
* @param name the protocol name of this transport
* @param isSSL use SSL to connect?
*/
protected SMTPTransport(Session session, URLName urlname,
String name, boolean isSSL) {
super(session, urlname);
Properties props = session.getProperties();
logger = new MailLogger(this.getClass(), "DEBUG SMTP",
session.getDebug(), session.getDebugOut());
traceLogger = logger.getSubLogger("protocol", null);
noauthdebug = !PropUtil.getBooleanProperty(props,
"mail.debug.auth", false);
debugusername = PropUtil.getBooleanProperty(props,
"mail.debug.auth.username", true);
debugpassword = PropUtil.getBooleanProperty(props,
"mail.debug.auth.password", false);
if (urlname != null)
name = urlname.getProtocol();
this.name = name;
if (!isSSL)
isSSL = PropUtil.getBooleanProperty(props,
"mail." + name + ".ssl.enable", false);
if (isSSL)
this.defaultPort = 465;
else
this.defaultPort = 25;
this.isSSL = isSSL;
// setting mail.smtp.quitwait to false causes us to not wait for the
// response from the QUIT command
quitWait = PropUtil.getBooleanProperty(props,
"mail." + name + ".quitwait", true);
// mail.smtp.reportsuccess causes us to throw an exception on success
reportSuccess = PropUtil.getBooleanProperty(props,
"mail." + name + ".reportsuccess", false);
// mail.smtp.starttls.enable enables use of STARTTLS command
useStartTLS = PropUtil.getBooleanProperty(props,
"mail." + name + ".starttls.enable", false);
// mail.smtp.starttls.required requires use of STARTTLS command
requireStartTLS = PropUtil.getBooleanProperty(props,
"mail." + name + ".starttls.required", false);
// mail.smtp.userset causes us to use RSET instead of NOOP
// for isConnected
useRset = PropUtil.getBooleanProperty(props,
"mail." + name + ".userset", false);
// mail.smtp.noop.strict requires 250 response to indicate success
noopStrict = PropUtil.getBooleanProperty(props,
"mail." + name + ".noop.strict", true);
// check if SASL is enabled
enableSASL = PropUtil.getBooleanProperty(props,
"mail." + name + ".sasl.enable", false);
if (enableSASL)
logger.config("enable SASL");
useCanonicalHostName = PropUtil.getBooleanProperty(props,
"mail." + name + ".sasl.usecanonicalhostname", false);
if (useCanonicalHostName)
logger.config("use canonical host name");
allowutf8 = PropUtil.getBooleanProperty(props,
"mail.mime.allowutf8", false);
if (allowutf8)
logger.config("allow UTF-8");
chunkSize = PropUtil.getIntProperty(props,
"mail." + name + ".chunksize", -1);
if (chunkSize > 0 && logger.isLoggable(Level.CONFIG))
logger.config("chunk size " + chunkSize);
// created here, because they're inner classes that reference "this"
Authenticator[] a = new Authenticator[] {
new LoginAuthenticator(),
new PlainAuthenticator(),
new DigestMD5Authenticator(),
new NtlmAuthenticator(),
new OAuth2Authenticator()
};
StringBuilder sb = new StringBuilder();
for (int i = 0; i < a.length; i++) {
authenticators.put(a[i].getMechanism(), a[i]);
sb.append(a[i].getMechanism()).append(' ');
}
defaultAuthenticationMechanisms = sb.toString();
}
/**
* Get the name of the local host, for use in the EHLO and HELO commands.
* The property mail.smtp.localhost overrides mail.smtp.localaddress,
* which overrides what InetAddress would tell us.
*
* @return the local host name
*/
public synchronized String getLocalHost() {
// get our hostname and cache it for future use
if (localHostName == null || localHostName.length() <= 0)
localHostName =
session.getProperty("mail." + name + ".localhost");
if (localHostName == null || localHostName.length() <= 0)
localHostName =
session.getProperty("mail." + name + ".localaddress");
try {
if (localHostName == null || localHostName.length() <= 0) {
InetAddress localHost = InetAddress.getLocalHost();
localHostName = localHost.getCanonicalHostName();
// if we can't get our name, use local address literal
if (localHostName == null)
// XXX - not correct for IPv6
localHostName = "[" + localHost.getHostAddress() + "]";
}
} catch (UnknownHostException uhex) {
}
// last chance, try to get our address from our socket
if (localHostName == null || localHostName.length() <= 0) {
if (serverSocket != null && serverSocket.isBound()) {
InetAddress localHost = serverSocket.getLocalAddress();
localHostName = localHost.getCanonicalHostName();
// if we can't get our name, use local address literal
if (localHostName == null)
// XXX - not correct for IPv6
localHostName = "[" + localHost.getHostAddress() + "]";
}
}
return localHostName;
}
/**
* Set the name of the local host, for use in the EHLO and HELO commands.
*
* @param localhost the local host name
* @since JavaMail 1.3.1
*/
public synchronized void setLocalHost(String localhost) {
localHostName = localhost;
}
/**
* Start the SMTP protocol on the given socket, which was already
* connected by the caller. Useful for implementing the SMTP ATRN
* command (RFC 2645) where an existing connection is used when
* the server reverses roles and becomes the client.
*
* @param socket the already connected socket
* @exception MessagingException for failures
* @since JavaMail 1.3.3
*/
public synchronized void connect(Socket socket) throws MessagingException {
serverSocket = socket;
super.connect();
}
/**
* Gets the authorization ID to be used for authentication.
*
* @return the authorization ID to use for authentication.
*
* @since JavaMail 1.4.4
*/
public synchronized String getAuthorizationId() {
if (authorizationID == UNKNOWN) {
authorizationID =
session.getProperty("mail." + name + ".sasl.authorizationid");
}
return authorizationID;
}
/**
* Sets the authorization ID to be used for authentication.
*
* @param authzid the authorization ID to use for
* authentication.
*
* @since JavaMail 1.4.4
*/
public synchronized void setAuthorizationID(String authzid) {
this.authorizationID = authzid;
}
/**
* Is SASL authentication enabled?
*
* @return true if SASL authentication is enabled
*
* @since JavaMail 1.4.4
*/
public synchronized boolean getSASLEnabled() {
return enableSASL;
}
/**
* Set whether SASL authentication is enabled.
*
* @param enableSASL should we enable SASL authentication?
*
* @since JavaMail 1.4.4
*/
public synchronized void setSASLEnabled(boolean enableSASL) {
this.enableSASL = enableSASL;
}
/**
* Gets the SASL realm to be used for DIGEST-MD5 authentication.
*
* @return the name of the realm to use for SASL authentication.
*
* @since JavaMail 1.3.1
*/
public synchronized String getSASLRealm() {
if (saslRealm == UNKNOWN) {
saslRealm = session.getProperty("mail." + name + ".sasl.realm");
if (saslRealm == null) // try old name
saslRealm = session.getProperty("mail." + name + ".saslrealm");
}
return saslRealm;
}
/**
* Sets the SASL realm to be used for DIGEST-MD5 authentication.
*
* @param saslRealm the name of the realm to use for
* SASL authentication.
*
* @since JavaMail 1.3.1
*/
public synchronized void setSASLRealm(String saslRealm) {
this.saslRealm = saslRealm;
}
/**
* Should SASL use the canonical host name?
*
* @return true if SASL should use the canonical host name
*
* @since JavaMail 1.5.2
*/
public synchronized boolean getUseCanonicalHostName() {
return useCanonicalHostName;
}
/**
* Set whether SASL should use the canonical host name.
*
* @param useCanonicalHostName should SASL use the canonical host name?
*
* @since JavaMail 1.5.2
*/
public synchronized void setUseCanonicalHostName(
boolean useCanonicalHostName) {
this.useCanonicalHostName = useCanonicalHostName;
}
/**
* Get the list of SASL mechanisms to consider if SASL authentication
* is enabled. If the list is empty or null, all available SASL mechanisms
* are considered.
*
* @return the array of SASL mechanisms to consider
*
* @since JavaMail 1.4.4
*/
public synchronized String[] getSASLMechanisms() {
if (saslMechanisms == UNKNOWN_SA) {
List<String> v = new ArrayList<>(5);
String s = session.getProperty("mail." + name + ".sasl.mechanisms");
if (s != null && s.length() > 0) {
if (logger.isLoggable(Level.FINE))
logger.fine("SASL mechanisms allowed: " + s);
StringTokenizer st = new StringTokenizer(s, " ,");
while (st.hasMoreTokens()) {
String m = st.nextToken();
if (m.length() > 0)
v.add(m);
}
}
saslMechanisms = new String[v.size()];
v.toArray(saslMechanisms);
}
if (saslMechanisms == null)
return null;
return saslMechanisms.clone();
}
/**
* Set the list of SASL mechanisms to consider if SASL authentication
* is enabled. If the list is empty or null, all available SASL mechanisms
* are considered.
*
* @param mechanisms the array of SASL mechanisms to consider
*
* @since JavaMail 1.4.4
*/
public synchronized void setSASLMechanisms(String[] mechanisms) {
if (mechanisms != null)
mechanisms = mechanisms.clone();
this.saslMechanisms = mechanisms;
}
/**
* Gets the NTLM domain to be used for NTLM authentication.
*
* @return the name of the domain to use for NTLM authentication.
*
* @since JavaMail 1.4.3
*/
public synchronized String getNTLMDomain() {
if (ntlmDomain == UNKNOWN) {
ntlmDomain =
session.getProperty("mail." + name + ".auth.ntlm.domain");
}
return ntlmDomain;
}
/**
* Sets the NTLM domain to be used for NTLM authentication.
*
* @param ntlmDomain the name of the domain to use for
* NTLM authentication.
*
* @since JavaMail 1.4.3
*/
public synchronized void setNTLMDomain(String ntlmDomain) {
this.ntlmDomain = ntlmDomain;
}
/**
* Should we report even successful sends by throwing an exception?
* If so, a <code>SendFailedException</code> will always be thrown and
* an {@link com.sun.mail.smtp.SMTPAddressSucceededException
* SMTPAddressSucceededException} will be included in the exception
* chain for each successful address, along with the usual
* {@link com.sun.mail.smtp.SMTPAddressFailedException
* SMTPAddressFailedException} for each unsuccessful address.
*
* @return true if an exception will be thrown on successful sends.
*
* @since JavaMail 1.3.2
*/
public synchronized boolean getReportSuccess() {
return reportSuccess;
}
/**
* Set whether successful sends should be reported by throwing
* an exception.
*
* @param reportSuccess should we throw an exception on success?
*
* @since JavaMail 1.3.2
*/
public synchronized void setReportSuccess(boolean reportSuccess) {
this.reportSuccess = reportSuccess;
}
/**
* Should we use the STARTTLS command to secure the connection
* if the server supports it?
*
* @return true if the STARTTLS command will be used
*
* @since JavaMail 1.3.2
*/
public synchronized boolean getStartTLS() {
return useStartTLS;
}
/**
* Set whether the STARTTLS command should be used.
*
* @param useStartTLS should we use the STARTTLS command?
*
* @since JavaMail 1.3.2
*/
public synchronized void setStartTLS(boolean useStartTLS) {
this.useStartTLS = useStartTLS;
}
/**
* Should we require the STARTTLS command to secure the connection?
*
* @return true if the STARTTLS command will be required
*
* @since JavaMail 1.4.2
*/
public synchronized boolean getRequireStartTLS() {
return requireStartTLS;
}
/**
* Set whether the STARTTLS command should be required.
*
* @param requireStartTLS should we require the STARTTLS command?
*
* @since JavaMail 1.4.2
*/
public synchronized void setRequireStartTLS(boolean requireStartTLS) {
this.requireStartTLS = requireStartTLS;
}
/**
* Is this Transport using SSL to connect to the server?
*
* @return true if using SSL
* @since JavaMail 1.4.6
*/
public synchronized boolean isSSL() {
return serverSocket instanceof SSLSocket;
}
/**
* Should we use the RSET command instead of the NOOP command
* in the @{link #isConnected isConnected} method?
*
* @return true if RSET will be used
*
* @since JavaMail 1.4
*/
public synchronized boolean getUseRset() {
return useRset;
}
/**
* Set whether the RSET command should be used instead of the
* NOOP command in the @{link #isConnected isConnected} method.
*
* @param useRset should we use the RSET command?
*
* @since JavaMail 1.4
*/
public synchronized void setUseRset(boolean useRset) {
this.useRset = useRset;
}
/**
* Is the NOOP command required to return a response code
* of 250 to indicate success?
*
* @return true if NOOP must return 250
*
* @since JavaMail 1.4.3
*/
public synchronized boolean getNoopStrict() {
return noopStrict;
}
/**
* Set whether the NOOP command is required to return a response code
* of 250 to indicate success.
*
* @param noopStrict is NOOP required to return 250?
*
* @since JavaMail 1.4.3
*/
public synchronized void setNoopStrict(boolean noopStrict) {
this.noopStrict = noopStrict;
}
/**
* Return the last response we got from the server.
* A failed send is often followed by an RSET command,
* but the response from the RSET command is not saved.
* Instead, this returns the response from the command
* before the RSET command.
*
* @return last response from server
*
* @since JavaMail 1.3.2
*/
public synchronized String getLastServerResponse() {
return lastServerResponse;
}
/**
* Return the return code from the last response we got from the server.
*
* @return return code from last response from server
*
* @since JavaMail 1.4.1
*/
public synchronized int getLastReturnCode() {
return lastReturnCode;
}
/**
* Performs the actual protocol-specific connection attempt.
* Will attempt to connect to "localhost" if the host was null. <p>
*
* Unless mail.smtp.ehlo is set to false, we'll try to identify
* ourselves using the ESMTP command EHLO.
*
* If mail.smtp.auth is set to true, we insist on having a username
* and password, and will try to authenticate ourselves if the server
* supports the AUTH extension (RFC 2554).
*
* @param host the name of the host to connect to
* @param port the port to use (-1 means use default port)
* @param user the name of the user to login as
* @param password the user's password
* @return true if connection successful, false if authentication failed
* @exception MessagingException for non-authentication failures
*/
@Override
protected synchronized boolean protocolConnect(String host, int port,
String user, String password)
throws MessagingException {
Properties props = session.getProperties();
// setting mail.smtp.auth to true enables attempts to use AUTH
boolean useAuth = PropUtil.getBooleanProperty(props,
"mail." + name + ".auth", false);
/*
* If mail.smtp.auth is set, make sure we have a valid username
* and password, even if we might not end up using it (e.g.,
* because the server doesn't support ESMTP or doesn't support
* the AUTH extension).
*/
if (useAuth && (user == null || password == null)) {
if (logger.isLoggable(Level.FINE)) {
logger.fine("need username and password for authentication");
logger.fine("protocolConnect returning false" +
", host=" + host +
", user=" + traceUser(user) +
", password=" + tracePassword(password));
}
return false;
}
// setting mail.smtp.ehlo to false disables attempts to use EHLO
boolean useEhlo = PropUtil.getBooleanProperty(props,
"mail." + name + ".ehlo", true);
if (logger.isLoggable(Level.FINE))
logger.fine("useEhlo " + useEhlo + ", useAuth " + useAuth);
/*
* If port is not specified, set it to value of mail.smtp.port
* property if it exists, otherwise default to 25.
*/
if (port == -1)
port = PropUtil.getIntProperty(props,
"mail." + name + ".port", -1);
if (port == -1)
port = defaultPort;
if (host == null || host.length() == 0)
host = "localhost";
/*
* If anything goes wrong, we need to be sure
* to close the connection.
*/
boolean connected = false;
try {
if (serverSocket != null)
openServer(); // only happens from connect(socket)
else
openServer(host, port);
boolean succeed = false;
if (useEhlo)
succeed = ehlo(getLocalHost());
if (!succeed)
helo(getLocalHost());
if (useStartTLS || requireStartTLS) {
if (serverSocket instanceof SSLSocket) {
logger.fine("STARTTLS requested but already using SSL");
} else if (supportsExtension("STARTTLS")) {
startTLS();
/*
* Have to issue another EHLO to update list of extensions
* supported, especially authentication mechanisms.
* Don't know if this could ever fail, but we ignore
* failure.
*/
ehlo(getLocalHost());
} else if (requireStartTLS) {
logger.fine("STARTTLS required but not supported");
throw new MessagingException(
"STARTTLS is required but " +
"host does not support STARTTLS");
}
}
if (allowutf8 && !supportsExtension("SMTPUTF8"))
logger.log(Level.INFO, "mail.mime.allowutf8 set " +
"but server doesn't advertise SMTPUTF8 support");
if ((useAuth || (user != null && password != null)) &&
(supportsExtension("AUTH") ||
supportsExtension("AUTH=LOGIN"))) {
if (logger.isLoggable(Level.FINE))
logger.fine("protocolConnect login" +
", host=" + host +
", user=" + traceUser(user) +
", password=" + tracePassword(password));
connected = authenticate(user, password);
return connected;
}
// we connected correctly
connected = true;
return true;
} finally {
// if we didn't connect successfully,
// make sure the connection is closed
if (!connected) {
try {
closeConnection();
} catch (MessagingException mex) {
// ignore it
}
}
}
}
/**
* Authenticate to the server.
*/
private boolean authenticate(String user, String passwd)
throws MessagingException {
// setting mail.smtp.auth.mechanisms controls which mechanisms will
// be used, and in what order they'll be considered. only the first
// match is used.
String mechs = session.getProperty("mail." + name + ".auth.mechanisms");
if (mechs == null)
mechs = defaultAuthenticationMechanisms;
String authzid = getAuthorizationId();
if (authzid == null)
authzid = user;
if (enableSASL) {
logger.fine("Authenticate with SASL");
try {
if (sasllogin(getSASLMechanisms(), getSASLRealm(), authzid,
user, passwd)) {
return true; // success
} else {
logger.fine("SASL authentication failed");
return false;
}
} catch (UnsupportedOperationException ex) {
logger.log(Level.FINE, "SASL support failed", ex);
// if the SASL support fails, fall back to non-SASL
}
}
if (logger.isLoggable(Level.FINE))
logger.fine("Attempt to authenticate using mechanisms: " + mechs);
/*
* Loop through the list of mechanisms supplied by the user
* (or defaulted) and try each in turn. If the server supports
* the mechanism and we have an authenticator for the mechanism,
* and it hasn't been disabled, use it.
*/
StringTokenizer st = new StringTokenizer(mechs);
while (st.hasMoreTokens()) {
String m = st.nextToken();
m = m.toUpperCase(Locale.ENGLISH);
Authenticator a = authenticators.get(m);
if (a == null) {
logger.log(Level.FINE, "no authenticator for mechanism {0}", m);
continue;
}
if (!supportsAuthentication(m)) {
logger.log(Level.FINE, "mechanism {0} not supported by server",
m);
continue;
}
/*
* If using the default mechanisms, check if this one is disabled.
*/
if (mechs == defaultAuthenticationMechanisms) {
String dprop = "mail." + name + ".auth." +
m.toLowerCase(Locale.ENGLISH) + ".disable";
boolean disabled = PropUtil.getBooleanProperty(
session.getProperties(),
dprop, !a.enabled());
if (disabled) {
if (logger.isLoggable(Level.FINE))
logger.fine("mechanism " + m +
" disabled by property: " + dprop);
continue;
}
}
// only the first supported and enabled mechanism is used
logger.log(Level.FINE, "Using mechanism {0}", m);
return a.authenticate(host, authzid, user, passwd);
}
// if no authentication mechanism found, fail
throw new AuthenticationFailedException(
"No authentication mechanisms supported by both server and client");
}
/**
* Abstract base class for SMTP authentication mechanism implementations.
*/
private abstract class Authenticator {
protected int resp; // the response code, used by subclasses
private final String mech; // the mechanism name, set in the constructor
private final boolean enabled; // is this mechanism enabled by default?
Authenticator(String mech) {
this(mech, true);
}
Authenticator(String mech, boolean enabled) {
this.mech = mech.toUpperCase(Locale.ENGLISH);
this.enabled = enabled;
}
String getMechanism() {
return mech;
}
boolean enabled() {
return enabled;
}
/**
* Start the authentication handshake by issuing the AUTH command.
* Delegate to the doAuth method to do the mechanism-specific
* part of the handshake.
*/
boolean authenticate(String host, String authzid,
String user, String passwd) throws MessagingException {
Throwable thrown = null;
try {
// use "initial response" capability, if supported
String ir = getInitialResponse(host, authzid, user, passwd);
if (noauthdebug && isTracing()) {
logger.fine("AUTH " + mech + " command trace suppressed");
suspendTracing();
}
if (ir != null)
resp = simpleCommand("AUTH " + mech + " " +
(ir.length() == 0 ? "=" : ir));
else
resp = simpleCommand("AUTH " + mech);
/*
* A 530 response indicates that the server wants us to
* issue a STARTTLS command first. Do that and try again.
*/
if (resp == 530) {
startTLS();
if (ir != null)
resp = simpleCommand("AUTH " + mech + " " + ir);
else
resp = simpleCommand("AUTH " + mech);
}
if (resp == 334)
doAuth(host, authzid, user, passwd);
} catch (IOException ex) { // should never happen, ignore
logger.log(Level.FINE, "AUTH " + mech + " failed", ex);
} catch (Throwable t) { // crypto can't be initialized?
logger.log(Level.FINE, "AUTH " + mech + " failed", t);
thrown = t;
} finally {
if (noauthdebug && isTracing())
logger.fine("AUTH " + mech + " " +
(resp == 235 ? "succeeded" : "failed"));
resumeTracing();
if (resp != 235) {
closeConnection();
if (thrown != null) {
if (thrown instanceof Error)
throw (Error)thrown;
if (thrown instanceof Exception)
throw new AuthenticationFailedException(
getLastServerResponse(),
(Exception)thrown);
assert false : "unknown Throwable"; // can't happen
}
throw new AuthenticationFailedException(
getLastServerResponse());
}
}
return true;
}
/**
* Provide the initial response to use in the AUTH command,
* or null if not supported. Subclasses that support the
* initial response capability will override this method.
*/
String getInitialResponse(String host, String authzid, String user,
String passwd) throws MessagingException, IOException {
return null;
}
abstract void doAuth(String host, String authzid, String user,
String passwd) throws MessagingException, IOException;
}
/**
* Perform the authentication handshake for LOGIN authentication.
*/
private class LoginAuthenticator extends Authenticator {
LoginAuthenticator() {
super("LOGIN");
}
@Override
void doAuth(String host, String authzid, String user, String passwd)
throws MessagingException, IOException {
// send username
resp = simpleCommand(BASE64EncoderStream.encode(
user.getBytes(StandardCharsets.UTF_8)));
if (resp == 334) {
// send passwd