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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
|
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "msgCore.h"
#include "nsSmtpProtocol.h"
#include "nscore.h"
#include "nsIStreamListener.h"
#include "nsIInputStream.h"
#include "nsIOutputStream.h"
#include "nsISocketTransport.h"
#include "nsIMsgMailNewsUrl.h"
#include "nsMsgBaseCID.h"
#include "nsMsgCompCID.h"
#include "nsIPrompt.h"
#include "nsIAuthPrompt.h"
#include "nsStringGlue.h"
#include "nsTextFormatter.h"
#include "nsIMsgIdentity.h"
#include "nsISmtpServer.h"
#include "prtime.h"
#include "mozilla/Logging.h"
#include "prerror.h"
#include "prprf.h"
#include "prmem.h"
#include "plbase64.h"
#include "prnetdb.h"
#include "prsystem.h"
#include "nsMsgUtils.h"
#include "nsIPipe.h"
#include "nsNetUtil.h"
#include "nsIPrefService.h"
#include "nsISSLSocketControl.h"
#include "nsComposeStrings.h"
#include "nsIStringBundle.h"
#include "nsMsgCompUtils.h"
#include "nsIMsgWindow.h"
#include "MailNewsTypes2.h" // for nsMsgSocketType and nsMsgAuthMethod
#include "nsIIDNService.h"
#include "mozilla/mailnews/MimeHeaderParser.h"
#include "mozilla/Services.h"
#include "mozilla/Attributes.h"
#include "nsINetAddr.h"
#include "nsIProxyInfo.h"
#ifndef XP_UNIX
#include <stdarg.h>
#endif /* !XP_UNIX */
#undef PostMessage // avoid to collision with WinUser.h
static PRLogModuleInfo *SMTPLogModule = nullptr;
using namespace mozilla::mailnews;
/* the output_buffer_size must be larger than the largest possible line
* 2000 seems good for news
*
* jwz: I increased this to 4k since it must be big enough to hold the
* entire button-bar HTML, and with the new "mailto" format, that can
* contain arbitrarily long header fields like "references".
*
* fortezza: proxy auth is huge, buffer increased to 8k (sigh).
*/
#define OUTPUT_BUFFER_SIZE (4096*2)
////////////////////////////////////////////////////////////////////////////////////////////
// TEMPORARY HARD CODED FUNCTIONS
///////////////////////////////////////////////////////////////////////////////////////////
/* based on in NET_ExplainErrorDetails in mkmessag.c */
nsresult nsExplainErrorDetails(nsISmtpUrl * aSmtpUrl, nsresult aCode, ...)
{
NS_ENSURE_ARG(aSmtpUrl);
va_list args;
nsCOMPtr<nsIPrompt> dialog;
aSmtpUrl->GetPrompt(getter_AddRefs(dialog));
NS_ENSURE_TRUE(dialog, NS_ERROR_FAILURE);
char16_t * msg;
nsString eMsg;
nsCOMPtr<nsIStringBundleService> bundleService =
mozilla::services::GetStringBundleService();
NS_ENSURE_TRUE(bundleService, NS_ERROR_UNEXPECTED);
nsCOMPtr<nsIStringBundle> bundle;
nsresult rv = bundleService->CreateBundle(
"chrome://messenger/locale/messengercompose/composeMsgs.properties",
getter_AddRefs(bundle));
NS_ENSURE_SUCCESS(rv, rv);
va_start (args, aCode);
const char16_t* exitString;
#ifdef __GNUC__
// Temporary workaroung until bug 783526 is fixed.
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wswitch"
#endif
switch (aCode)
{
case NS_ERROR_ILLEGAL_LOCALPART:
bundle->GetStringFromName(u"errorIllegalLocalPart",
getter_Copies(eMsg));
msg = nsTextFormatter::vsmprintf(eMsg.get(), args);
break;
case NS_ERROR_SMTP_SERVER_ERROR:
case NS_ERROR_TCP_READ_ERROR:
case NS_ERROR_SMTP_TEMP_SIZE_EXCEEDED:
case NS_ERROR_SMTP_PERM_SIZE_EXCEEDED_1:
case NS_ERROR_SMTP_PERM_SIZE_EXCEEDED_2:
case NS_ERROR_SENDING_FROM_COMMAND:
case NS_ERROR_SENDING_RCPT_COMMAND:
case NS_ERROR_SENDING_DATA_COMMAND:
case NS_ERROR_SENDING_MESSAGE:
case NS_ERROR_SMTP_GREETING:
exitString = errorStringNameForErrorCode(aCode);
bundle->GetStringFromName(exitString, getter_Copies(eMsg));
msg = nsTextFormatter::vsmprintf(eMsg.get(), args);
break;
default:
NS_WARNING("falling to default error code");
bundle->GetStringFromName(u"communicationsError", getter_Copies(eMsg));
msg = nsTextFormatter::smprintf(eMsg.get(), aCode);
break;
}
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif
if (msg)
{
rv = dialog->Alert(nullptr, msg);
nsTextFormatter::smprintf_free(msg);
}
va_end (args);
return rv;
}
/* RFC 1891 -- extended smtp value encoding scheme
5. Additional parameters for RCPT and MAIL commands
The extended RCPT and MAIL commands are issued by a client when it wishes to request a DSN from the
server, under certain conditions, for a particular recipient. The extended RCPT and MAIL commands are
identical to the RCPT and MAIL commands defined in [1], except that one or more of the following parameters
appear after the sender or recipient address, respectively. The general syntax for extended SMTP commands is
defined in [4].
NOTE: Although RFC 822 ABNF is used to describe the syntax of these parameters, they are not, in the
language of that document, "structured field bodies". Therefore, while parentheses MAY appear within an
emstp-value, they are not recognized as comment delimiters.
The syntax for "esmtp-value" in [4] does not allow SP, "=", control characters, or characters outside the
traditional ASCII range of 1- 127 decimal to be transmitted in an esmtp-value. Because the ENVID and
ORCPT parameters may need to convey values outside this range, the esmtp-values for these parameters are
encoded as "xtext". "xtext" is formally defined as follows:
xtext = *( xchar / hexchar )
xchar = any ASCII CHAR between "!" (33) and "~" (126) inclusive, except for "+" and "=".
; "hexchar"s are intended to encode octets that cannot appear
; as ASCII characters within an esmtp-value.
hexchar = ASCII "+" immediately followed by two upper case hexadecimal digits
When encoding an octet sequence as xtext:
+ Any ASCII CHAR between "!" and "~" inclusive, except for "+" and "=",
MAY be encoded as itself. (A CHAR in this range MAY instead be encoded as a "hexchar", at the
implementor's discretion.)
+ ASCII CHARs that fall outside the range above must be encoded as
"hexchar".
*/
/* caller must free the return buffer */
static char *
esmtp_value_encode(const char *addr)
{
char *buffer = (char *) PR_Malloc(512); /* esmtp ORCPT allow up to 500 chars encoded addresses */
char *bp = buffer, *bpEnd = buffer+500;
int len, i;
if (!buffer) return NULL;
*bp=0;
if (! addr || *addr == 0) /* this will never happen */
return buffer;
for (i=0, len=PL_strlen(addr); i < len && bp < bpEnd; i++)
{
if (*addr >= 0x21 &&
*addr <= 0x7E &&
*addr != '+' &&
*addr != '=')
{
*bp++ = *addr++;
}
else
{
PR_snprintf(bp, bpEnd-bp, "+%.2X", ((int)*addr++));
bp += PL_strlen(bp);
}
}
*bp=0;
return buffer;
}
////////////////////////////////////////////////////////////////////////////////////////////
// END OF TEMPORARY HARD CODED FUNCTIONS
///////////////////////////////////////////////////////////////////////////////////////////
#ifdef MOZ_MAILNEWS_OAUTH2
NS_IMPL_ISUPPORTS_INHERITED(nsSmtpProtocol, nsMsgAsyncWriteProtocol,
msgIOAuth2ModuleListener)
#else
NS_IMPL_ADDREF_INHERITED(nsSmtpProtocol, nsMsgAsyncWriteProtocol)
NS_IMPL_RELEASE_INHERITED(nsSmtpProtocol, nsMsgAsyncWriteProtocol)
NS_INTERFACE_MAP_BEGIN(nsSmtpProtocol)
NS_INTERFACE_MAP_END_INHERITING(nsMsgAsyncWriteProtocol)
// TODO: See if we can use NS_IMPL_ISUPPORTS_INHERITED: https://hg.mozilla.org/comm-central/diff/eae1195fde6d/mailnews/compose/src/nsSmtpProtocol.cpp
#endif
nsSmtpProtocol::nsSmtpProtocol(nsIURI * aURL)
: nsMsgAsyncWriteProtocol(aURL)
, m_dataBuf(nullptr)
{
}
nsSmtpProtocol::~nsSmtpProtocol()
{
// free our local state
PR_FREEIF(m_dataBuf);
}
void nsSmtpProtocol::Initialize(nsIURI * aURL)
{
NS_PRECONDITION(aURL, "invalid URL passed into Smtp Protocol");
nsresult rv = NS_OK;
m_flags = 0;
m_prefAuthMethods = 0;
m_failedAuthMethods = 0;
m_currentAuthMethod = 0;
m_usernamePrompted = false;
m_prefSocketType = nsMsgSocketType::trySTARTTLS;
m_tlsInitiated = false;
m_urlErrorState = NS_ERROR_FAILURE;
if (!SMTPLogModule)
SMTPLogModule = PR_NewLogModule("SMTP");
if (aURL)
m_runningURL = do_QueryInterface(aURL);
// extract out message feedback if there is any.
nsCOMPtr<nsIMsgMailNewsUrl> mailnewsUrl = do_QueryInterface(aURL);
if (mailnewsUrl)
mailnewsUrl->GetStatusFeedback(getter_AddRefs(m_statusFeedback));
m_dataBuf = (char *) PR_Malloc(sizeof(char) * OUTPUT_BUFFER_SIZE);
m_dataBufSize = OUTPUT_BUFFER_SIZE;
m_nextState = SMTP_START_CONNECT;
m_nextStateAfterResponse = SMTP_START_CONNECT;
m_responseCode = 0;
m_previousResponseCode = 0;
m_continuationResponse = -1;
m_tlsEnabled = false;
m_addressesLeft = 0;
m_sendDone = false;
m_sizelimit = 0;
m_totalMessageSize = 0;
nsCOMPtr<nsIFile> file;
m_runningURL->GetPostMessageFile(getter_AddRefs(file));
if (file)
file->GetFileSize(&m_totalMessageSize);
m_originalContentLength = 0;
m_totalAmountRead = 0;
m_lineStreamBuffer = new nsMsgLineStreamBuffer(OUTPUT_BUFFER_SIZE, true);
// ** may want to consider caching the server capability to save lots of
// round trip communication between the client and server
int32_t authMethod = 0;
nsCOMPtr<nsISmtpServer> smtpServer;
m_runningURL->GetSmtpServer(getter_AddRefs(smtpServer));
if (smtpServer) {
smtpServer->GetAuthMethod(&authMethod);
smtpServer->GetSocketType(&m_prefSocketType);
smtpServer->GetHelloArgument(getter_Copies(m_helloArgument));
#ifdef MOZ_MAILNEWS_OAUTH2
// Query for OAuth2 support. If the SMTP server preferences don't allow
// for OAuth2, then don't carry around the OAuth2 module any longer
// since we won't need it.
mOAuth2Support = do_CreateInstance(MSGIOAUTH2MODULE_CONTRACTID);
if (mOAuth2Support)
{
bool supportsOAuth = false;
mOAuth2Support->InitFromSmtp(smtpServer, &supportsOAuth);
if (!supportsOAuth)
mOAuth2Support = nullptr;
}
#endif
}
InitPrefAuthMethods(authMethod);
nsAutoCString hostName;
int32_t port = 0;
aURL->GetPort(&port);
aURL->GetAsciiHost(hostName);
MOZ_LOG(SMTPLogModule, mozilla::LogLevel::Info, ("SMTP Connecting to: %s", hostName.get()));
// When we are making a secure connection, we need to make sure that we
// pass an interface requestor down to the socket transport so that PSM can
// retrieve a nsIPrompt instance if needed.
nsCOMPtr<nsIInterfaceRequestor> callbacks;
nsCOMPtr<nsISmtpUrl> smtpUrl(do_QueryInterface(aURL));
if (smtpUrl)
smtpUrl->GetNotificationCallbacks(getter_AddRefs(callbacks));
nsCOMPtr<nsIProxyInfo> proxyInfo;
rv = MsgExamineForProxy(this, getter_AddRefs(proxyInfo));
if (NS_FAILED(rv)) proxyInfo = nullptr;
if (m_prefSocketType == nsMsgSocketType::SSL)
rv = OpenNetworkSocketWithInfo(hostName.get(), port, "ssl", proxyInfo,
callbacks);
else if (m_prefSocketType != nsMsgSocketType::plain)
{
rv = OpenNetworkSocketWithInfo(hostName.get(), port, "starttls",
proxyInfo, callbacks);
if (NS_FAILED(rv) && m_prefSocketType == nsMsgSocketType::trySTARTTLS)
{
m_prefSocketType = nsMsgSocketType::plain;
rv = OpenNetworkSocketWithInfo(hostName.get(), port, nullptr,
proxyInfo, callbacks);
}
}
else
rv = OpenNetworkSocketWithInfo(hostName.get(), port, nullptr, proxyInfo,
callbacks);
}
void nsSmtpProtocol::AppendHelloArgument(nsACString& aResult)
{
nsresult rv;
// is a custom EHLO/HELO argument configured for the transport to be used?
if (!m_helloArgument.IsEmpty())
{
aResult += m_helloArgument;
}
else
{
// is a FQDN known for this system?
char hostName[256];
PR_GetSystemInfo(PR_SI_HOSTNAME_UNTRUNCATED, hostName, sizeof hostName);
if ((hostName[0] != '\0') && (strchr(hostName, '.') != NULL))
{
nsDependentCString cleanedHostName(hostName);
// avoid problems with hostnames containing newlines/whitespace
cleanedHostName.StripWhitespace();
aResult += cleanedHostName;
}
else
{
nsCOMPtr<nsINetAddr> iaddr; // IP address for this connection
// our transport is always a nsISocketTransport
nsCOMPtr<nsISocketTransport> socketTransport = do_QueryInterface(m_transport);
// should return the interface ip of the SMTP connection
// minimum case - see bug 68877 and RFC 2821, chapter 4.1.1.1
rv = socketTransport->GetScriptableSelfAddr(getter_AddRefs(iaddr));
if (NS_SUCCEEDED(rv))
{
// turn it into a string
nsCString ipAddressString;
rv = iaddr->GetAddress(ipAddressString);
if (NS_SUCCEEDED(rv))
{
#ifdef DEBUG
bool v4mapped = false;
iaddr->GetIsV4Mapped(&v4mapped);
NS_ASSERTION(!v4mapped,
"unexpected IPv4-mapped IPv6 address");
#endif
uint16_t family = nsINetAddr::FAMILY_INET;
iaddr->GetFamily(&family);
if (family == nsINetAddr::FAMILY_INET6) // IPv6 style address?
aResult.AppendLiteral("[IPv6:");
else
aResult.AppendLiteral("[");
aResult.Append(ipAddressString);
aResult.Append(']');
}
}
}
}
}
/////////////////////////////////////////////////////////////////////////////////////////////
// we suppport the nsIStreamListener interface
////////////////////////////////////////////////////////////////////////////////////////////
// stop binding is a "notification" informing us that the stream
// associated with aURL is going away.
NS_IMETHODIMP nsSmtpProtocol::OnStopRequest(nsIRequest *request, nsISupports *ctxt,
nsresult aStatus)
{
bool connDroppedDuringAuth = NS_SUCCEEDED(aStatus) && !m_sendDone &&
(m_nextStateAfterResponse == SMTP_AUTH_LOGIN_STEP0_RESPONSE ||
m_nextStateAfterResponse == SMTP_AUTH_LOGIN_RESPONSE);
// ignore errors handling the QUIT command so fcc can continue.
if (m_sendDone && NS_FAILED(aStatus))
{
MOZ_LOG(SMTPLogModule, mozilla::LogLevel::Info,
("SMTP connection error quitting %lx, ignoring ", aStatus));
aStatus = NS_OK;
}
if (NS_SUCCEEDED(aStatus) && !m_sendDone) {
// if we are getting OnStopRequest() with NS_OK,
// but we haven't finished clean, that's spells trouble.
// it means that the server has dropped us before we could send the whole mail
// for example, see bug #200647
MOZ_LOG(SMTPLogModule, mozilla::LogLevel::Info,
("SMTP connection dropped after %ld total bytes read", m_totalAmountRead));
if (!connDroppedDuringAuth)
nsMsgAsyncWriteProtocol::OnStopRequest(nullptr, ctxt, NS_ERROR_NET_INTERRUPT);
}
else
nsMsgAsyncWriteProtocol::OnStopRequest(nullptr, ctxt, aStatus);
// okay, we've been told that the send is done and the connection is going away. So
// we need to release all of our state
nsresult rv = nsMsgAsyncWriteProtocol::CloseSocket();
// If the server dropped the connection when we were expecting
// a login response, reprompt for password, and if the user asks,
// retry the url.
if (connDroppedDuringAuth)
{
nsCOMPtr<nsIURI> runningURI = do_QueryInterface(m_runningURL);
nsresult rv = AuthLoginResponse(nullptr, 0);
if (NS_FAILED(rv))
return rv;
return LoadUrl(runningURI, ctxt);
}
return rv;
}
/////////////////////////////////////////////////////////////////////////////////////////////
// End of nsIStreamListenerSupport
//////////////////////////////////////////////////////////////////////////////////////////////
void nsSmtpProtocol::UpdateStatus(const char16_t* aStatusName)
{
if (m_statusFeedback)
{
nsCOMPtr<nsIStringBundleService> bundleService =
mozilla::services::GetStringBundleService();
if (!bundleService) return;
nsCOMPtr<nsIStringBundle> bundle;
nsresult rv = bundleService->CreateBundle("chrome://messenger/locale/messengercompose/composeMsgs.properties", getter_AddRefs(bundle));
if (NS_FAILED(rv)) return;
nsString msg;
bundle->GetStringFromName(aStatusName, getter_Copies(msg));
UpdateStatusWithString(msg.get());
}
}
void nsSmtpProtocol::UpdateStatusWithString(const char16_t * aStatusString)
{
if (m_statusFeedback && aStatusString)
m_statusFeedback->ShowStatusString(nsDependentString(aStatusString));
}
/////////////////////////////////////////////////////////////////////////////////////////////
// Begin protocol state machine functions...
//////////////////////////////////////////////////////////////////////////////////////////////
/*
* gets the response code from the SMTP server and the
* response line
*/
nsresult nsSmtpProtocol::SmtpResponse(nsIInputStream * inputStream, uint32_t length)
{
char * line = nullptr;
char cont_char;
uint32_t ln = 0;
bool pauseForMoreData = false;
if (!m_lineStreamBuffer)
// this will force an error and at least we won't crash
return NS_ERROR_NULL_POINTER;
line = m_lineStreamBuffer->ReadNextLine(inputStream, ln, pauseForMoreData);
if (pauseForMoreData || !line)
{
SetFlag(SMTP_PAUSE_FOR_READ); /* pause */
PR_Free(line);
return NS_OK;
}
m_totalAmountRead += ln;
MOZ_LOG(SMTPLogModule, mozilla::LogLevel::Info, ("SMTP Response: %s", line));
cont_char = ' '; /* default */
// sscanf() doesn't update m_responseCode if line doesn't start
// with a number. That can be dangerous. So be sure to set
// m_responseCode to 0 if no items read.
if (PR_sscanf(line, "%d%c", &m_responseCode, &cont_char) <= 0)
m_responseCode = 0;
if (m_continuationResponse == -1)
{
if (cont_char == '-') /* begin continuation */
m_continuationResponse = m_responseCode;
// display the whole message if no valid response code or
// message shorter than 4 chars
m_responseText = (m_responseCode >= 100 && PL_strlen(line) > 3) ? line + 4 : line;
}
else
{ /* have to continue */
if (m_continuationResponse == m_responseCode && cont_char == ' ')
m_continuationResponse = -1; /* ended */
if (m_responseText.IsEmpty() || m_responseText.Last() != '\n')
m_responseText += "\n";
m_responseText += (PL_strlen(line) > 3) ? line + 4 : line;
}
if (m_responseCode == 220 && m_responseText.Length() && !m_tlsInitiated &&
!m_sendDone)
m_nextStateAfterResponse = SMTP_EXTN_LOGIN_RESPONSE;
if (m_continuationResponse == -1) /* all done with this response? */
{
m_nextState = m_nextStateAfterResponse;
ClearFlag(SMTP_PAUSE_FOR_READ); /* don't pause */
}
PR_Free(line);
return NS_OK;
}
nsresult nsSmtpProtocol::ExtensionLoginResponse(nsIInputStream * inputStream, uint32_t length)
{
nsresult status = NS_OK;
if (m_responseCode != 220)
{
#ifdef DEBUG
nsresult rv =
#endif
nsExplainErrorDetails(m_runningURL, NS_ERROR_SMTP_GREETING,
m_responseText.get());
NS_ASSERTION(NS_SUCCEEDED(rv), "failed to explain SMTP error");
m_urlErrorState = NS_ERROR_BUT_DONT_SHOW_ALERT;
return NS_ERROR_SMTP_AUTH_FAILURE;
}
nsAutoCString buffer("EHLO ");
AppendHelloArgument(buffer);
buffer += CRLF;
status = SendData(buffer.get());
m_nextState = SMTP_RESPONSE;
m_nextStateAfterResponse = SMTP_SEND_EHLO_RESPONSE;
SetFlag(SMTP_PAUSE_FOR_READ);
return(status);
}
nsresult nsSmtpProtocol::SendHeloResponse(nsIInputStream * inputStream, uint32_t length)
{
nsresult status = NS_OK;
nsAutoCString buffer;
nsresult rv;
if (m_responseCode != 250)
{
#ifdef DEBUG
rv =
#endif
nsExplainErrorDetails(m_runningURL, NS_ERROR_SMTP_SERVER_ERROR,
m_responseText.get());
NS_ASSERTION(NS_SUCCEEDED(rv), "failed to explain SMTP error");
m_urlErrorState = NS_ERROR_BUT_DONT_SHOW_ALERT;
return NS_ERROR_SMTP_AUTH_FAILURE;
}
// check if we're just verifying the ability to logon
nsCOMPtr<nsISmtpUrl> smtpUrl = do_QueryInterface(m_runningURL, &rv);
NS_ENSURE_SUCCESS(rv, rv);
bool verifyingLogon = false;
smtpUrl->GetVerifyLogon(&verifyingLogon);
if (verifyingLogon)
return SendQuit();
// extract the email address from the identity
nsCString emailAddress;
nsCOMPtr <nsIMsgIdentity> senderIdentity;
rv = m_runningURL->GetSenderIdentity(getter_AddRefs(senderIdentity));
if (NS_FAILED(rv) || !senderIdentity)
{
m_urlErrorState = NS_ERROR_COULD_NOT_GET_USERS_MAIL_ADDRESS;
return(NS_ERROR_COULD_NOT_GET_USERS_MAIL_ADDRESS);
}
senderIdentity->GetEmail(emailAddress);
if (emailAddress.IsEmpty())
{
m_urlErrorState = NS_ERROR_COULD_NOT_GET_USERS_MAIL_ADDRESS;
return(NS_ERROR_COULD_NOT_GET_USERS_MAIL_ADDRESS);
}
nsCString fullAddress;
// Quote the email address before passing it to the SMTP server.
MakeMimeAddress(EmptyCString(), emailAddress, fullAddress);
buffer = "MAIL FROM:<";
buffer += fullAddress;
buffer += ">";
nsCOMPtr<nsIPrefService> prefs = do_GetService(NS_PREFSERVICE_CONTRACTID, &rv);
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIPrefBranch> prefBranch;
rv = prefs->GetBranch(nullptr, getter_AddRefs(prefBranch));
NS_ENSURE_SUCCESS(rv, rv);
if (TestFlag(SMTP_EHLO_DSN_ENABLED))
{
bool requestDSN = false;
rv = m_runningURL->GetRequestDSN(&requestDSN);
if (requestDSN)
{
bool requestRetFull = false;
rv = prefBranch->GetBoolPref("mail.dsn.ret_full_on", &requestRetFull);
buffer += requestRetFull ? " RET=FULL" : " RET=HDRS";
nsCString dsnEnvid;
// get the envid from the smtpUrl
rv = m_runningURL->GetDsnEnvid(dsnEnvid);
if (dsnEnvid.IsEmpty())
dsnEnvid.Adopt(msg_generate_message_id(senderIdentity));
buffer += " ENVID=";
buffer += dsnEnvid;
}
}
if (TestFlag(SMTP_EHLO_8BIT_ENABLED))
{
bool strictlyMime = false;
rv = prefBranch->GetBoolPref("mail.strictly_mime", &strictlyMime);
if (!strictlyMime)
buffer.Append(" BODY=8BITMIME");
}
if (TestFlag(SMTP_EHLO_SIZE_ENABLED))
{
buffer.Append(" SIZE=");
buffer.AppendInt(m_totalMessageSize);
}
buffer += CRLF;
status = SendData(buffer.get());
m_nextState = SMTP_RESPONSE;
m_nextStateAfterResponse = SMTP_SEND_MAIL_RESPONSE;
SetFlag(SMTP_PAUSE_FOR_READ);
return(status);
}
nsresult nsSmtpProtocol::SendEhloResponse(nsIInputStream * inputStream, uint32_t length)
{
nsresult status = NS_OK;
if (m_responseCode != 250)
{
/* EHLO must not be implemented by the server, so fall back to the HELO case
* if command is unrecognized or unimplemented.
*/
if (m_responseCode == 500 || m_responseCode == 502)
{
/* If STARTTLS is requested by the user, EHLO is required to advertise it.
* But only if TLS handshake is not already accomplished.
*/
if (m_prefSocketType == nsMsgSocketType::alwaysSTARTTLS &&
!m_tlsEnabled)
{
m_nextState = SMTP_ERROR_DONE;
m_urlErrorState = NS_ERROR_STARTTLS_FAILED_EHLO_STARTTLS;
return(NS_ERROR_STARTTLS_FAILED_EHLO_STARTTLS);
}
nsAutoCString buffer("HELO ");
AppendHelloArgument(buffer);
buffer += CRLF;
status = SendData(buffer.get());
m_nextState = SMTP_RESPONSE;
m_nextStateAfterResponse = SMTP_SEND_HELO_RESPONSE;
SetFlag(SMTP_PAUSE_FOR_READ);
return (status);
}
/* e.g. getting 421 "Server says unauthorized, bye" or
* 501 "Syntax error in EHLOs parameters or arguments"
*/
else
{
#ifdef DEBUG
nsresult rv =
#endif
nsExplainErrorDetails(m_runningURL, NS_ERROR_SMTP_SERVER_ERROR,
m_responseText.get());
NS_ASSERTION(NS_SUCCEEDED(rv), "failed to explain SMTP error");
m_urlErrorState = NS_ERROR_BUT_DONT_SHOW_ALERT;
return NS_ERROR_SMTP_AUTH_FAILURE;
}
}
int32_t responseLength = m_responseText.Length();
int32_t startPos = 0;
int32_t endPos;
do
{
endPos = m_responseText.FindChar('\n', startPos + 1);
nsAutoCString responseLine;
responseLine.Assign(Substring(m_responseText, startPos,
(endPos >= 0 ? endPos : responseLength) - startPos));
MsgCompressWhitespace(responseLine);
if (responseLine.LowerCaseEqualsLiteral("starttls"))
{
SetFlag(SMTP_EHLO_STARTTLS_ENABLED);
}
else if (responseLine.LowerCaseEqualsLiteral("dsn"))
{
SetFlag(SMTP_EHLO_DSN_ENABLED);
}
else if (StringBeginsWith(responseLine, NS_LITERAL_CSTRING("AUTH"), nsCaseInsensitiveCStringComparator()))
{
SetFlag(SMTP_AUTH);
if (responseLine.Find(NS_LITERAL_CSTRING("GSSAPI"),
CaseInsensitiveCompare) >= 0)
SetFlag(SMTP_AUTH_GSSAPI_ENABLED);
if (responseLine.Find(NS_LITERAL_CSTRING("CRAM-MD5"),
CaseInsensitiveCompare) >= 0)
SetFlag(SMTP_AUTH_CRAM_MD5_ENABLED);
if (responseLine.Find(NS_LITERAL_CSTRING("NTLM"),
CaseInsensitiveCompare) >= 0)
SetFlag(SMTP_AUTH_NTLM_ENABLED);
if (responseLine.Find(NS_LITERAL_CSTRING("MSN"),
CaseInsensitiveCompare) >= 0)
SetFlag(SMTP_AUTH_MSN_ENABLED);
if (responseLine.Find(NS_LITERAL_CSTRING("PLAIN"),
CaseInsensitiveCompare) >= 0)
SetFlag(SMTP_AUTH_PLAIN_ENABLED);
if (responseLine.Find(NS_LITERAL_CSTRING("LOGIN"),
CaseInsensitiveCompare) >= 0)
SetFlag(SMTP_AUTH_LOGIN_ENABLED);
if (responseLine.Find(NS_LITERAL_CSTRING("EXTERNAL"),
CaseInsensitiveCompare) >= 0)
SetFlag(SMTP_AUTH_EXTERNAL_ENABLED);
#ifdef MOZ_MAILNEWS_OAUTH2
if (responseLine.Find(NS_LITERAL_CSTRING("XOAUTH2"),
CaseInsensitiveCompare) >= 0)
SetFlag(SMTP_AUTH_OAUTH2_ENABLED);
#endif
}
else if (StringBeginsWith(responseLine, NS_LITERAL_CSTRING("SIZE"), nsCaseInsensitiveCStringComparator()))
{
SetFlag(SMTP_EHLO_SIZE_ENABLED);
m_sizelimit = atol((responseLine.get()) + 4);
}
else if (StringBeginsWith(responseLine, NS_LITERAL_CSTRING("8BITMIME"), nsCaseInsensitiveCStringComparator()))
{
SetFlag(SMTP_EHLO_8BIT_ENABLED);
}
startPos = endPos + 1;
} while (endPos >= 0);
if (TestFlag(SMTP_EHLO_SIZE_ENABLED) &&
m_sizelimit > 0 && (int32_t)m_totalMessageSize > m_sizelimit)
{
#ifdef DEBUG
nsresult rv =
#endif
nsExplainErrorDetails(m_runningURL,
NS_ERROR_SMTP_PERM_SIZE_EXCEEDED_1, m_sizelimit);
NS_ASSERTION(NS_SUCCEEDED(rv), "failed to explain SMTP error");
m_urlErrorState = NS_ERROR_BUT_DONT_SHOW_ALERT;
return(NS_ERROR_SENDING_FROM_COMMAND);
}
m_nextState = SMTP_AUTH_PROCESS_STATE;
return status;
}
nsresult nsSmtpProtocol::SendTLSResponse()
{
// only tear down our existing connection and open a new one if we received a 220 response
// from the smtp server after we issued the STARTTLS
nsresult rv = NS_OK;
if (m_responseCode == 220)
{
nsCOMPtr<nsISupports> secInfo;
nsCOMPtr<nsISocketTransport> strans = do_QueryInterface(m_transport, &rv);
if (NS_FAILED(rv)) return rv;
rv = strans->GetSecurityInfo(getter_AddRefs(secInfo));
if (NS_SUCCEEDED(rv) && secInfo) {
nsCOMPtr<nsISSLSocketControl> sslControl = do_QueryInterface(secInfo, &rv);
if (NS_SUCCEEDED(rv) && sslControl)
rv = sslControl->StartTLS();
}
if (NS_SUCCEEDED(rv))
{
m_nextState = SMTP_EXTN_LOGIN_RESPONSE;
m_nextStateAfterResponse = SMTP_EXTN_LOGIN_RESPONSE;
m_tlsEnabled = true;
m_flags = 0; // resetting the flags
return rv;
}
}
ClearFlag(SMTP_EHLO_STARTTLS_ENABLED);
m_tlsInitiated = false;
m_nextState = SMTP_AUTH_PROCESS_STATE;
return rv;
}
void nsSmtpProtocol::InitPrefAuthMethods(int32_t authMethodPrefValue)
{
// for m_prefAuthMethods, using the same flags as server capablities.
switch (authMethodPrefValue)
{
case nsMsgAuthMethod::none:
m_prefAuthMethods = SMTP_AUTH_NONE_ENABLED;
break;
//case nsMsgAuthMethod::old -- no such thing for SMTP
case nsMsgAuthMethod::passwordCleartext:
m_prefAuthMethods = SMTP_AUTH_LOGIN_ENABLED |
SMTP_AUTH_PLAIN_ENABLED;
break;
case nsMsgAuthMethod::passwordEncrypted:
m_prefAuthMethods = SMTP_AUTH_CRAM_MD5_ENABLED;
break;
case nsMsgAuthMethod::NTLM:
m_prefAuthMethods = SMTP_AUTH_NTLM_ENABLED |
SMTP_AUTH_MSN_ENABLED;
break;
case nsMsgAuthMethod::GSSAPI:
m_prefAuthMethods = SMTP_AUTH_GSSAPI_ENABLED;
break;
#ifdef MOZ_MAILNEWS_OAUTH2
case nsMsgAuthMethod::OAuth2:
m_prefAuthMethods = SMTP_AUTH_OAUTH2_ENABLED;
break;
#endif
case nsMsgAuthMethod::secure:
m_prefAuthMethods = SMTP_AUTH_CRAM_MD5_ENABLED |
SMTP_AUTH_GSSAPI_ENABLED |
SMTP_AUTH_NTLM_ENABLED | SMTP_AUTH_MSN_ENABLED |
SMTP_AUTH_EXTERNAL_ENABLED; // TODO: Expose EXTERNAL? How?
break;
default:
NS_ASSERTION(false, "SMTP: authMethod pref invalid");
// TODO log to error console
MOZ_LOG(SMTPLogModule, mozilla::LogLevel::Error,
("SMTP: bad pref authMethod = %d\n", authMethodPrefValue));
// fall to any
MOZ_FALLTHROUGH;
case nsMsgAuthMethod::anything:
m_prefAuthMethods =
SMTP_AUTH_LOGIN_ENABLED | SMTP_AUTH_PLAIN_ENABLED |
SMTP_AUTH_CRAM_MD5_ENABLED | SMTP_AUTH_GSSAPI_ENABLED |
SMTP_AUTH_NTLM_ENABLED | SMTP_AUTH_MSN_ENABLED |
#ifdef MOZ_MAILNEWS_OAUTH2
SMTP_AUTH_OAUTH2_ENABLED |
#endif
SMTP_AUTH_EXTERNAL_ENABLED;
break;
}
#ifdef MOZ_MAILNEWS_OAUTH2
// Only enable OAuth2 support if we can do the lookup.
if ((m_prefAuthMethods & SMTP_AUTH_OAUTH2_ENABLED) && !mOAuth2Support)
m_prefAuthMethods &= ~SMTP_AUTH_OAUTH2_ENABLED;
#endif
NS_ASSERTION(m_prefAuthMethods != 0, "SMTP:InitPrefAuthMethods() failed");
}
/**
* Changes m_currentAuthMethod to pick the next-best one
* which is allowed by server and prefs and not marked failed.
* The order of preference and trying of auth methods is encoded here.
*/
nsresult nsSmtpProtocol::ChooseAuthMethod()
{
int32_t serverCaps = m_flags; // from nsMsgProtocol::TestFlag()
int32_t availCaps = serverCaps & m_prefAuthMethods & ~m_failedAuthMethods;
MOZ_LOG(SMTPLogModule, mozilla::LogLevel::Debug,
("SMTP auth: server caps 0x%X, pref 0x%X, failed 0x%X, avail caps 0x%X",
serverCaps, m_prefAuthMethods, m_failedAuthMethods, availCaps));
MOZ_LOG(SMTPLogModule, mozilla::LogLevel:: Debug,
("(GSSAPI = 0x%X, CRAM = 0x%X, NTLM = 0x%X, "
"MSN = 0x%X, PLAIN = 0x%X, LOGIN = 0x%X, EXTERNAL = 0x%X)",
SMTP_AUTH_GSSAPI_ENABLED, SMTP_AUTH_CRAM_MD5_ENABLED,
SMTP_AUTH_NTLM_ENABLED, SMTP_AUTH_MSN_ENABLED, SMTP_AUTH_PLAIN_ENABLED,
SMTP_AUTH_LOGIN_ENABLED, SMTP_AUTH_EXTERNAL_ENABLED));
if (SMTP_AUTH_GSSAPI_ENABLED & availCaps)
m_currentAuthMethod = SMTP_AUTH_GSSAPI_ENABLED;
else if (SMTP_AUTH_CRAM_MD5_ENABLED & availCaps)
m_currentAuthMethod = SMTP_AUTH_CRAM_MD5_ENABLED;
else if (SMTP_AUTH_NTLM_ENABLED & availCaps)
m_currentAuthMethod = SMTP_AUTH_NTLM_ENABLED;
else if (SMTP_AUTH_MSN_ENABLED & availCaps)
m_currentAuthMethod = SMTP_AUTH_MSN_ENABLED;
#ifdef MOZ_MAILNEWS_OAUTH2
else if (SMTP_AUTH_OAUTH2_ENABLED & availCaps)
m_currentAuthMethod = SMTP_AUTH_OAUTH2_ENABLED;
#endif
else if (SMTP_AUTH_PLAIN_ENABLED & availCaps)
m_currentAuthMethod = SMTP_AUTH_PLAIN_ENABLED;
else if (SMTP_AUTH_LOGIN_ENABLED & availCaps)
m_currentAuthMethod = SMTP_AUTH_LOGIN_ENABLED;
else if (SMTP_AUTH_EXTERNAL_ENABLED & availCaps)
m_currentAuthMethod = SMTP_AUTH_EXTERNAL_ENABLED;
else
{
MOZ_LOG(SMTPLogModule, mozilla::LogLevel::Error, ("no auth method remaining"));
m_currentAuthMethod = 0;
return NS_ERROR_SMTP_AUTH_FAILURE;
}
MOZ_LOG(SMTPLogModule, mozilla::LogLevel::Debug, ("trying auth method 0x%X", m_currentAuthMethod));
return NS_OK;
}
void nsSmtpProtocol::MarkAuthMethodAsFailed(int32_t failedAuthMethod)
{
MOZ_LOG(SMTPLogModule, mozilla::LogLevel::Debug,
("marking auth method 0x%X failed", failedAuthMethod));
m_failedAuthMethods |= failedAuthMethod;
}
/**
* Start over, trying all auth methods again
*/
void nsSmtpProtocol::ResetAuthMethods()
{
m_currentAuthMethod = 0;
m_failedAuthMethods = 0;
}
nsresult nsSmtpProtocol::ProcessAuth()
{
nsresult status = NS_OK;
nsAutoCString buffer;
if (!m_tlsEnabled)
{
if (TestFlag(SMTP_EHLO_STARTTLS_ENABLED))
{
// Do not try to combine SMTPS with STARTTLS.
// If nsMsgSocketType::SSL is set,
// we are alrady using a secure connection.
// Do not attempt to do STARTTLS,
// even if server offers it.
if (m_prefSocketType == nsMsgSocketType::trySTARTTLS ||
m_prefSocketType == nsMsgSocketType::alwaysSTARTTLS)
{
buffer = "STARTTLS";
buffer += CRLF;
status = SendData(buffer.get());
m_tlsInitiated = true;
m_nextState = SMTP_RESPONSE;
m_nextStateAfterResponse = SMTP_TLS_RESPONSE;
SetFlag(SMTP_PAUSE_FOR_READ);
return status;
}
}
else if (m_prefSocketType == nsMsgSocketType::alwaysSTARTTLS)
{
m_nextState = SMTP_ERROR_DONE;
m_urlErrorState = NS_ERROR_STARTTLS_FAILED_EHLO_STARTTLS;
return NS_ERROR_STARTTLS_FAILED_EHLO_STARTTLS;
}
}
// (wrong indention until here)
(void) ChooseAuthMethod(); // advance m_currentAuthMethod
// We don't need to auth, per pref, or the server doesn't advertise AUTH,
// so skip auth and try to send message.
if (m_prefAuthMethods == SMTP_AUTH_NONE_ENABLED || !TestFlag(SMTP_AUTH))
{
m_nextState = SMTP_SEND_HELO_RESPONSE;
// fake to 250 because SendHeloResponse() tests for this
m_responseCode = 250;
}
else if (m_currentAuthMethod == SMTP_AUTH_EXTERNAL_ENABLED)
{
buffer = "AUTH EXTERNAL =";
buffer += CRLF;
SendData(buffer.get());
m_nextState = SMTP_RESPONSE;
m_nextStateAfterResponse = SMTP_AUTH_EXTERNAL_RESPONSE;
SetFlag(SMTP_PAUSE_FOR_READ);
return NS_OK;
}
else if (m_currentAuthMethod == SMTP_AUTH_GSSAPI_ENABLED)
{
m_nextState = SMTP_SEND_AUTH_GSSAPI_FIRST;
}
else if (m_currentAuthMethod == SMTP_AUTH_CRAM_MD5_ENABLED ||
m_currentAuthMethod == SMTP_AUTH_PLAIN_ENABLED ||
m_currentAuthMethod == SMTP_AUTH_NTLM_ENABLED)
{
m_nextState = SMTP_SEND_AUTH_LOGIN_STEP1;
}
else if (m_currentAuthMethod == SMTP_AUTH_LOGIN_ENABLED ||
m_currentAuthMethod == SMTP_AUTH_MSN_ENABLED)
{
m_nextState = SMTP_SEND_AUTH_LOGIN_STEP0;
}
#ifdef MOZ_MAILNEWS_OAUTH2
else if (m_currentAuthMethod == SMTP_AUTH_OAUTH2_ENABLED)
{
m_nextState = SMTP_AUTH_OAUTH2_STEP;
}
#endif
else // All auth methods failed
{
// show an appropriate error msg
if (m_failedAuthMethods == 0)
{
// we didn't even try anything, so we had a non-working config:
// pref doesn't match server
MOZ_LOG(SMTPLogModule, mozilla::LogLevel::Error,
("no working auth mech - pref doesn't match server capas"));
// pref has encrypted pw & server claims to support plaintext pw
if (m_prefAuthMethods == SMTP_AUTH_CRAM_MD5_ENABLED &&
m_flags & (SMTP_AUTH_LOGIN_ENABLED | SMTP_AUTH_PLAIN_ENABLED))
{
// have SSL
if (m_prefSocketType == nsMsgSocketType::SSL ||
m_prefSocketType == nsMsgSocketType::alwaysSTARTTLS)
// tell user to change to plaintext pw
m_urlErrorState = NS_ERROR_SMTP_AUTH_CHANGE_ENCRYPT_TO_PLAIN_SSL;
else
// tell user to change to plaintext pw, with big warning
m_urlErrorState = NS_ERROR_SMTP_AUTH_CHANGE_ENCRYPT_TO_PLAIN_NO_SSL;
}
// pref has plaintext pw & server claims to support encrypted pw
else if (m_prefAuthMethods == (SMTP_AUTH_LOGIN_ENABLED |
SMTP_AUTH_PLAIN_ENABLED) &&
m_flags & SMTP_AUTH_CRAM_MD5_ENABLED)
// tell user to change to encrypted pw
m_urlErrorState = NS_ERROR_SMTP_AUTH_CHANGE_PLAIN_TO_ENCRYPT;
else
{
// just "change auth method"
m_urlErrorState = NS_ERROR_SMTP_AUTH_MECH_NOT_SUPPORTED;
}
}
else if (m_failedAuthMethods == SMTP_AUTH_GSSAPI_ENABLED)
{
// We have only GSSAPI, and it failed, so nothing left to do.
MOZ_LOG(SMTPLogModule, mozilla::LogLevel::Error, ("GSSAPI only and it failed"));
m_urlErrorState = NS_ERROR_SMTP_AUTH_GSSAPI;
}
else
{
// we tried to login, but it all failed
MOZ_LOG(SMTPLogModule, mozilla::LogLevel::Error, ("All auth attempts failed"));
m_urlErrorState = NS_ERROR_SMTP_AUTH_FAILURE;
}
m_nextState = SMTP_ERROR_DONE;
return NS_ERROR_SMTP_AUTH_FAILURE;
}
return NS_OK;
}
nsresult nsSmtpProtocol::AuthLoginResponse(nsIInputStream * stream, uint32_t length)
{
MOZ_LOG(SMTPLogModule, mozilla::LogLevel::Debug, ("SMTP Login response, code %d", m_responseCode));
nsresult status = NS_OK;
switch (m_responseCode/100)
{
case 2:
m_nextState = SMTP_SEND_HELO_RESPONSE;
// fake to 250 because SendHeloResponse() tests for this
m_responseCode = 250;
break;
case 3:
m_nextState = SMTP_SEND_AUTH_LOGIN_STEP2;
break;
case 5:
default:
nsCOMPtr<nsISmtpServer> smtpServer;
m_runningURL->GetSmtpServer(getter_AddRefs(smtpServer));
if (smtpServer)
{
// If one authentication failed, mark it failed, so that we're going to
// fall back on a less secure login method.
MarkAuthMethodAsFailed(m_currentAuthMethod);
bool allFailed = NS_FAILED(ChooseAuthMethod());
if (allFailed && m_failedAuthMethods > 0 &&
m_failedAuthMethods != SMTP_AUTH_GSSAPI_ENABLED &&
m_failedAuthMethods != SMTP_AUTH_EXTERNAL_ENABLED)
{
// We've tried all avail. methods, and they all failed, and we have no mechanism left.
// Ask user to try with a new password.
MOZ_LOG(SMTPLogModule, mozilla::LogLevel::Warning,
("SMTP: ask user what to do (after login failed): new password, retry or cancel"));
nsCOMPtr<nsISmtpServer> smtpServer;
nsresult rv = m_runningURL->GetSmtpServer(getter_AddRefs(smtpServer));
NS_ENSURE_SUCCESS(rv, rv);
nsCString hostname;
rv = smtpServer->GetHostname(hostname);
NS_ENSURE_SUCCESS(rv, rv);
int32_t buttonPressed = 1;
if (NS_SUCCEEDED(MsgPromptLoginFailed(nullptr, hostname,
&buttonPressed)))
{
if (buttonPressed == 1) // Cancel button
{
MOZ_LOG(SMTPLogModule, mozilla::LogLevel::Warning, ("cancel button pressed"));
// abort and get out of here
status = NS_ERROR_ABORT;
break;
}
else if (buttonPressed == 2) // 'New password' button
{
MOZ_LOG(SMTPLogModule, mozilla::LogLevel::Warning, ("new password button pressed"));
// Change password was pressed. For now, forget the stored
// password and we'll prompt for a new one next time around.
smtpServer->ForgetPassword();
if (m_usernamePrompted)
smtpServer->SetUsername(EmptyCString());
// Let's restore the original auth flags from SendEhloResponse
// so we can try them again with new password and username
ResetAuthMethods();
// except for GSSAPI and EXTERNAL, which don't care about passwords.
MarkAuthMethodAsFailed(SMTP_AUTH_GSSAPI_ENABLED);
MarkAuthMethodAsFailed(SMTP_AUTH_EXTERNAL_ENABLED);
}
else if (buttonPressed == 0) // Retry button
{
MOZ_LOG(SMTPLogModule, mozilla::LogLevel::Warning, ("retry button pressed"));
// try all again, including GSSAPI
ResetAuthMethods();
}
}
}
MOZ_LOG(SMTPLogModule, mozilla::LogLevel::Error,
("SMTP: login failed: failed %X, current %X", m_failedAuthMethods, m_currentAuthMethod));
m_nextState = SMTP_AUTH_PROCESS_STATE; // try auth (ProcessAuth()) again, with other method
}
else
status = NS_ERROR_SMTP_PASSWORD_UNDEFINED;
break;
}
return (status);
}
nsresult nsSmtpProtocol::AuthGSSAPIFirst()
{
NS_ASSERTION(m_currentAuthMethod == SMTP_AUTH_GSSAPI_ENABLED, "called in invalid state");
nsAutoCString command("AUTH GSSAPI ");
nsAutoCString resp;
nsAutoCString service("smtp@");
nsCString hostName;
nsCString userName;
nsresult rv;
nsCOMPtr<nsISmtpServer> smtpServer;
rv = m_runningURL->GetSmtpServer(getter_AddRefs(smtpServer));
if (NS_FAILED(rv))
return NS_ERROR_FAILURE;
rv = smtpServer->GetUsername(userName);
if (NS_FAILED(rv))
return NS_ERROR_FAILURE;
rv = smtpServer->GetHostname(hostName);
if (NS_FAILED(rv))
return NS_ERROR_FAILURE;
service.Append(hostName);
MOZ_LOG(SMTPLogModule, mozilla::LogLevel::Debug, ("SMTP: GSSAPI step 1 for user %s at server %s, service %s",
userName.get(), hostName.get(), service.get()));
rv = DoGSSAPIStep1(service.get(), userName.get(), resp);
if (NS_FAILED(rv))
{
MOZ_LOG(SMTPLogModule, mozilla::LogLevel::Error, ("SMTP: GSSAPI step 1 failed early"));
MarkAuthMethodAsFailed(SMTP_AUTH_GSSAPI_ENABLED);
m_nextState = SMTP_AUTH_PROCESS_STATE;
return NS_OK;
}
else
command.Append(resp);
command.Append(CRLF);
m_nextState = SMTP_RESPONSE;
m_nextStateAfterResponse = SMTP_SEND_AUTH_GSSAPI_STEP;
SetFlag(SMTP_PAUSE_FOR_READ);
return SendData(command.get());
}
// GSSAPI may consist of multiple round trips
nsresult nsSmtpProtocol::AuthGSSAPIStep()
{
MOZ_LOG(SMTPLogModule, mozilla::LogLevel::Debug, ("SMTP: GSSAPI auth step 2"));
NS_ASSERTION(m_currentAuthMethod == SMTP_AUTH_GSSAPI_ENABLED, "called in invalid state");
nsresult rv;
nsAutoCString cmd;
// Check to see what the server said
if (m_responseCode / 100 != 3) {
m_nextState = SMTP_AUTH_LOGIN_RESPONSE;
return NS_OK;
}
rv = DoGSSAPIStep2(m_responseText, cmd);
if (NS_FAILED(rv))
cmd = "*";
cmd += CRLF;
m_nextStateAfterResponse = (rv == NS_SUCCESS_AUTH_FINISHED)?SMTP_AUTH_LOGIN_RESPONSE:SMTP_SEND_AUTH_GSSAPI_STEP;
m_nextState = SMTP_RESPONSE;
SetFlag(SMTP_PAUSE_FOR_READ);
return SendData(cmd.get());
}
// LOGIN and MSN consist of three steps (MSN not through the mechanism
// but by non-RFC2821 compliant implementation in MS servers) not two as
// PLAIN or CRAM-MD5, so we've to start here and continue with AuthStep1
// if the server responds with with a 3xx code to "AUTH LOGIN" or "AUTH MSN"
nsresult nsSmtpProtocol::AuthLoginStep0()
{
NS_ASSERTION(m_currentAuthMethod == SMTP_AUTH_MSN_ENABLED ||
m_currentAuthMethod == SMTP_AUTH_LOGIN_ENABLED,
"called in invalid state");
MOZ_LOG(SMTPLogModule, mozilla::LogLevel::Debug, ("SMTP: MSN or LOGIN auth, step 0"));
nsAutoCString command(m_currentAuthMethod == SMTP_AUTH_MSN_ENABLED
? "AUTH MSN" CRLF : "AUTH LOGIN" CRLF);
m_nextState = SMTP_RESPONSE;
m_nextStateAfterResponse = SMTP_AUTH_LOGIN_STEP0_RESPONSE;
SetFlag(SMTP_PAUSE_FOR_READ);
return SendData(command.get());
}
void nsSmtpProtocol::AuthLoginStep0Response()
{
NS_ASSERTION(m_currentAuthMethod == SMTP_AUTH_MSN_ENABLED ||
m_currentAuthMethod == SMTP_AUTH_LOGIN_ENABLED,
"called in invalid state");
// need the test to be here instead in AuthLoginResponse() to
// continue with step 1 instead of 2 in case of a code 3xx
m_nextState = (m_responseCode/100 == 3) ?
SMTP_SEND_AUTH_LOGIN_STEP1 : SMTP_AUTH_LOGIN_RESPONSE;
}
nsresult nsSmtpProtocol::AuthLoginStep1()
{
char buffer[512]; // TODO nsAutoCString
nsresult rv;
nsresult status = NS_OK;
nsCString username;
char *base64Str = nullptr;
nsAutoCString password;
nsCOMPtr<nsISmtpServer> smtpServer;
rv = m_runningURL->GetSmtpServer(getter_AddRefs(smtpServer));
if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
rv = smtpServer->GetUsername(username);
if (username.IsEmpty())
{
rv = GetUsernamePassword(username, password);
m_usernamePrompted = true;
if (username.IsEmpty() || password.IsEmpty())
return NS_ERROR_SMTP_PASSWORD_UNDEFINED;
}
nsCString hostname;
smtpServer->GetHostname(hostname);
MOZ_LOG(SMTPLogModule, mozilla::LogLevel::Debug, ("SMTP AuthLoginStep1() for %s@%s",
username.get(), hostname.get()));
GetPassword(password);
if (password.IsEmpty())
{
MOZ_LOG(SMTPLogModule, mozilla::LogLevel::Error, ("SMTP: password undefined"));
m_urlErrorState = NS_ERROR_SMTP_PASSWORD_UNDEFINED;
return NS_ERROR_SMTP_PASSWORD_UNDEFINED;
}
if (m_currentAuthMethod == SMTP_AUTH_CRAM_MD5_ENABLED)
{
MOZ_LOG(SMTPLogModule, mozilla::LogLevel::Error, ("CRAM auth, step 1"));
PR_snprintf(buffer, sizeof(buffer), "AUTH CRAM-MD5" CRLF);
}
else if (m_currentAuthMethod == SMTP_AUTH_NTLM_ENABLED ||
m_currentAuthMethod == SMTP_AUTH_MSN_ENABLED)
{
MOZ_LOG(SMTPLogModule, mozilla::LogLevel::Debug, ("NTLM/MSN auth, step 1"));
nsAutoCString response;
rv = DoNtlmStep1(username.get(), password.get(), response);
PR_snprintf(buffer, sizeof(buffer), TestFlag(SMTP_AUTH_NTLM_ENABLED) ?
"AUTH NTLM %.256s" CRLF :
"%.256s" CRLF, response.get());
}
else if (m_currentAuthMethod == SMTP_AUTH_PLAIN_ENABLED)
{
MOZ_LOG(SMTPLogModule, mozilla::LogLevel::Debug, ("PLAIN auth"));
char plain_string[512];
int len = 1; /* first <NUL> char */
memset(plain_string, 0, 512);
PR_snprintf(&plain_string[1], 510, "%s", username.get());
len += username.Length();
len++; /* second <NUL> char */
PR_snprintf(&plain_string[len], 511-len, "%s", password.get());
len += password.Length();
base64Str = PL_Base64Encode(plain_string, len, nullptr);
PR_snprintf(buffer, sizeof(buffer), "AUTH PLAIN %.256s" CRLF, base64Str);
}
else if (m_currentAuthMethod == SMTP_AUTH_LOGIN_ENABLED)
{
MOZ_LOG(SMTPLogModule, mozilla::LogLevel::Debug, ("LOGIN auth"));
base64Str = PL_Base64Encode(username.get(),
username.Length(), nullptr);
PR_snprintf(buffer, sizeof(buffer), "%.256s" CRLF, base64Str);
}
else
return (NS_ERROR_COMMUNICATIONS_ERROR);
status = SendData(buffer, true);
m_nextState = SMTP_RESPONSE;
m_nextStateAfterResponse = SMTP_AUTH_LOGIN_RESPONSE;
SetFlag(SMTP_PAUSE_FOR_READ);
NS_Free(base64Str);
return (status);
}
nsresult nsSmtpProtocol::AuthLoginStep2()
{
/* use cached smtp password first
* if not then use cached pop password
* if pop password undefined
* sync with smtp password
*/
nsresult status = NS_OK;
nsresult rv;
nsAutoCString password;
GetPassword(password);
if (password.IsEmpty())
{
m_urlErrorState = NS_ERROR_SMTP_PASSWORD_UNDEFINED;
return NS_ERROR_SMTP_PASSWORD_UNDEFINED;
}
MOZ_LOG(SMTPLogModule, mozilla::LogLevel::Debug, ("SMTP AuthLoginStep2"));
if (!password.IsEmpty())
{
char buffer[512];
if (m_currentAuthMethod == SMTP_AUTH_CRAM_MD5_ENABLED)
{
MOZ_LOG(SMTPLogModule, mozilla::LogLevel::Debug, ("CRAM auth, step 2"));
unsigned char digest[DIGEST_LENGTH];
char * decodedChallenge = PL_Base64Decode(m_responseText.get(),
m_responseText.Length(), nullptr);
if (decodedChallenge)
rv = MSGCramMD5(decodedChallenge, strlen(decodedChallenge), password.get(), password.Length(), digest);
else
rv = NS_ERROR_FAILURE;
PR_Free(decodedChallenge);
if (NS_SUCCEEDED(rv))
{
nsAutoCString encodedDigest;
char hexVal[8];
for (uint32_t j=0; j<16; j++)
{
PR_snprintf (hexVal,8, "%.2x", 0x0ff & (unsigned short)digest[j]);
encodedDigest.Append(hexVal);
}
nsCOMPtr<nsISmtpServer> smtpServer;
rv = m_runningURL->GetSmtpServer(getter_AddRefs(smtpServer));
if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
nsCString userName;
rv = smtpServer->GetUsername(userName);
PR_snprintf(buffer, sizeof(buffer), "%s %s", userName.get(), encodedDigest.get());
char *base64Str = PL_Base64Encode(buffer, strlen(buffer), nullptr);
PR_snprintf(buffer, sizeof(buffer), "%s" CRLF, base64Str);
NS_Free(base64Str);
}
if (NS_FAILED(rv))
PR_snprintf(buffer, sizeof(buffer), "*" CRLF);
}
else if (m_currentAuthMethod == SMTP_AUTH_NTLM_ENABLED ||
m_currentAuthMethod == SMTP_AUTH_MSN_ENABLED)
{
MOZ_LOG(SMTPLogModule, mozilla::LogLevel::Debug, ("NTLM/MSN auth, step 2"));
nsAutoCString response;
rv = DoNtlmStep2(m_responseText, response);
PR_snprintf(buffer, sizeof(buffer), "%.509s" CRLF, response.get());
}
else if (m_currentAuthMethod == SMTP_AUTH_PLAIN_ENABLED ||
m_currentAuthMethod == SMTP_AUTH_LOGIN_ENABLED)
{
MOZ_LOG(SMTPLogModule, mozilla::LogLevel::Debug, ("PLAIN/LOGIN auth, step 2"));
char *base64Str = PL_Base64Encode(password.get(), password.Length(), nullptr);
PR_snprintf(buffer, sizeof(buffer), "%.256s" CRLF, base64Str);
NS_Free(base64Str);
}
else
return NS_ERROR_COMMUNICATIONS_ERROR;
status = SendData(buffer, true);
m_nextState = SMTP_RESPONSE;
m_nextStateAfterResponse = SMTP_AUTH_LOGIN_RESPONSE;
SetFlag(SMTP_PAUSE_FOR_READ);
return (status);
}
// XXX -1 is not a valid nsresult
return static_cast<nsresult>(-1);
}
#ifdef MOZ_MAILNEWS_OAUTH2
nsresult nsSmtpProtocol::AuthOAuth2Step1()
{
MOZ_ASSERT(mOAuth2Support, "Can't do anything without OAuth2 support");
nsresult rv = mOAuth2Support->Connect(true, this);
NS_ENSURE_SUCCESS(rv, rv);
m_nextState = SMTP_SUSPENDED;
return NS_OK;
}
nsresult nsSmtpProtocol::OnSuccess(const nsACString &aAccessToken)
{
MOZ_ASSERT(mOAuth2Support, "Can't do anything without OAuth2 support");
nsCString base64Str;
mOAuth2Support->BuildXOAuth2String(base64Str);
// Send the AUTH XOAUTH2 command, and then siphon us back to the regular
// authentication login stream.
nsAutoCString buffer;
buffer.AppendLiteral("AUTH XOAUTH2 ");
buffer += base64Str;
buffer += CRLF;
nsresult rv = SendData(buffer.get(), true);
if (NS_FAILED(rv))
{
m_nextState = SMTP_ERROR_DONE;
}
else
{
m_nextState = SMTP_RESPONSE;
m_nextStateAfterResponse = SMTP_AUTH_LOGIN_RESPONSE;
}
SetFlag(SMTP_PAUSE_FOR_READ);
ProcessProtocolState(nullptr, nullptr, 0, 0);
return NS_OK;
}
nsresult nsSmtpProtocol::OnFailure(nsresult aError)
{
MOZ_LOG(SMTPLogModule, mozilla::LogLevel::Debug, ("OAuth2 login error %08x",
(uint32_t)aError));
m_urlErrorState = aError;
m_nextState = SMTP_ERROR_DONE;
return ProcessProtocolState(nullptr, nullptr, 0, 0);
}
#endif
nsresult nsSmtpProtocol::SendMailResponse()
{
nsresult status = NS_OK;
nsAutoCString buffer;
nsresult rv;
if (m_responseCode/10 != 25)
{
nsresult errorcode;
if (TestFlag(SMTP_EHLO_SIZE_ENABLED))
errorcode = (m_responseCode == 452) ? NS_ERROR_SMTP_TEMP_SIZE_EXCEEDED :
(m_responseCode == 552) ? NS_ERROR_SMTP_PERM_SIZE_EXCEEDED_2 :
NS_ERROR_SENDING_FROM_COMMAND;
else
errorcode = NS_ERROR_SENDING_FROM_COMMAND;
rv = nsExplainErrorDetails(m_runningURL, errorcode, m_responseText.get());
NS_ASSERTION(NS_SUCCEEDED(rv), "failed to explain SMTP error");
m_urlErrorState = NS_ERROR_BUT_DONT_SHOW_ALERT;
return(NS_ERROR_SENDING_FROM_COMMAND);
}
/* Send the RCPT TO: command */
bool requestDSN = false;
rv = m_runningURL->GetRequestDSN(&requestDSN);
nsCOMPtr <nsIPrefService> prefs = do_GetService(NS_PREFSERVICE_CONTRACTID, &rv);
NS_ENSURE_SUCCESS(rv,rv);
nsCOMPtr<nsIPrefBranch> prefBranch;
rv = prefs->GetBranch(nullptr, getter_AddRefs(prefBranch));
NS_ENSURE_SUCCESS(rv,rv);
bool requestOnSuccess = false;
rv = prefBranch->GetBoolPref("mail.dsn.request_on_success_on", &requestOnSuccess);
bool requestOnFailure = false;
rv = prefBranch->GetBoolPref("mail.dsn.request_on_failure_on", &requestOnFailure);
bool requestOnDelay = false;
rv = prefBranch->GetBoolPref("mail.dsn.request_on_delay_on", &requestOnDelay);
bool requestOnNever = false;
rv = prefBranch->GetBoolPref("mail.dsn.request_never_on", &requestOnNever);
nsCString &address = m_addresses[m_addressesLeft - 1];
if (TestFlag(SMTP_EHLO_DSN_ENABLED) && requestDSN && (requestOnSuccess || requestOnFailure || requestOnDelay || requestOnNever))
{
char *encodedAddress = esmtp_value_encode(address.get());
nsAutoCString dsnBuffer;
if (encodedAddress)
{
buffer = "RCPT TO:<";
buffer += address;
buffer += "> NOTIFY=";
if (requestOnNever)
dsnBuffer += "NEVER";
else
{
if (requestOnSuccess)
dsnBuffer += "SUCCESS";
if (requestOnFailure)
dsnBuffer += dsnBuffer.IsEmpty() ? "FAILURE" : ",FAILURE";
if (requestOnDelay)
dsnBuffer += dsnBuffer.IsEmpty() ? "DELAY" : ",DELAY";
}
buffer += dsnBuffer;
buffer += " ORCPT=rfc822;";
buffer += encodedAddress;
buffer += CRLF;
PR_FREEIF(encodedAddress);
}
else
{
m_urlErrorState = NS_ERROR_OUT_OF_MEMORY;
return (NS_ERROR_OUT_OF_MEMORY);
}
}
else
{
buffer = "RCPT TO:<";
buffer += address;
buffer += ">";
buffer += CRLF;
}
status = SendData(buffer.get());
m_nextState = SMTP_RESPONSE;
m_nextStateAfterResponse = SMTP_SEND_RCPT_RESPONSE;
SetFlag(SMTP_PAUSE_FOR_READ);
return(status);
}
nsresult nsSmtpProtocol::SendRecipientResponse()
{
nsresult status = NS_OK;
nsAutoCString buffer;
nsresult rv;
if (m_responseCode / 10 != 25)
{
nsresult errorcode;
if (TestFlag(SMTP_EHLO_SIZE_ENABLED))
errorcode = (m_responseCode == 452) ? NS_ERROR_SMTP_TEMP_SIZE_EXCEEDED :
(m_responseCode == 552) ? NS_ERROR_SMTP_PERM_SIZE_EXCEEDED_2 :
NS_ERROR_SENDING_RCPT_COMMAND;
else
errorcode = NS_ERROR_SENDING_RCPT_COMMAND;
if (errorcode == NS_ERROR_SENDING_RCPT_COMMAND) {
rv = nsExplainErrorDetails(
m_runningURL, errorcode, NS_ConvertUTF8toUTF16(m_responseText).get(),
NS_ConvertUTF8toUTF16(m_addresses[m_addressesLeft - 1]).get());
} else {
rv = nsExplainErrorDetails(m_runningURL, errorcode,
m_responseText.get(),
m_addresses[m_addressesLeft - 1].get());
}
if (!NS_SUCCEEDED(rv))
NS_ASSERTION(false, "failed to explain SMTP error");
m_urlErrorState = NS_ERROR_BUT_DONT_SHOW_ALERT;
return(NS_ERROR_SENDING_RCPT_COMMAND);
}
if (--m_addressesLeft > 0)
{
// more senders to RCPT to
// fake to 250 because SendMailResponse() can't handle 251
m_responseCode = 250;
m_nextState = SMTP_SEND_MAIL_RESPONSE;
return NS_OK;
}
/* else send the DATA command */
buffer = "DATA";
buffer += CRLF;
status = SendData(buffer.get());
m_nextState = SMTP_RESPONSE;
m_nextStateAfterResponse = SMTP_SEND_DATA_RESPONSE;
SetFlag(SMTP_PAUSE_FOR_READ);
return(status);
}
nsresult nsSmtpProtocol::SendData(const char *dataBuffer, bool aSuppressLogging)
{
// XXX -1 is not a valid nsresult
if (!dataBuffer) return static_cast<nsresult>(-1);
if (!aSuppressLogging) {
MOZ_LOG(SMTPLogModule, mozilla::LogLevel::Info, ("SMTP Send: %s", dataBuffer));
} else {
MOZ_LOG(SMTPLogModule, mozilla::LogLevel::Info, ("Logging suppressed for this command (it probably contained authentication information)"));
}
return nsMsgAsyncWriteProtocol::SendData(dataBuffer);
}
nsresult nsSmtpProtocol::SendDataResponse()
{
nsresult status = NS_OK;
if (m_responseCode != 354)
{
mozilla::DebugOnly<nsresult> rv = nsExplainErrorDetails(m_runningURL,
NS_ERROR_SENDING_DATA_COMMAND,
m_responseText.get());
NS_ASSERTION(NS_SUCCEEDED(rv), "failed to explain SMTP error");
m_urlErrorState = NS_ERROR_BUT_DONT_SHOW_ALERT;
return(NS_ERROR_SENDING_DATA_COMMAND);
}
m_nextState = SMTP_SEND_POST_DATA;
ClearFlag(SMTP_PAUSE_FOR_READ); /* send data directly */
UpdateStatus(u"smtpDeliveringMail");
{
// m_runningURL->GetBodySize(&m_totalMessageSize);
}
return(status);
}
void nsSmtpProtocol::SendMessageInFile()
{
nsCOMPtr<nsIFile> file;
nsCOMPtr<nsIURI> url = do_QueryInterface(m_runningURL);
m_runningURL->GetPostMessageFile(getter_AddRefs(file));
if (url && file)
// need to fully qualify to avoid getting overwritten by a #define
// in some windows header file
nsMsgAsyncWriteProtocol::PostMessage(url, file);
SetFlag(SMTP_PAUSE_FOR_READ);
// for now, we are always done at this point..we aren't making multiple calls
// to post data...
UpdateStatus(u"smtpDeliveringMail");
m_nextState = SMTP_RESPONSE;
m_nextStateAfterResponse = SMTP_SEND_MESSAGE_RESPONSE;
}
void nsSmtpProtocol::SendPostData()
{
// mscott: as a first pass, I'm writing everything at once and am not
// doing it in chunks...
/* returns 0 on done and negative on error
* positive if it needs to continue.
*/
// check to see if url is a file..if it is...call our file handler...
bool postMessageInFile = true;
m_runningURL->GetPostMessage(&postMessageInFile);
if (postMessageInFile)
{
SendMessageInFile();
}
/* Update the thermo and the status bar. This is done by hand, rather
than using the FE_GraphProgress* functions, because there seems to be
no way to make FE_GraphProgress shut up and not display anything more
when all the data has arrived. At the end, we want to show the
"message sent; waiting for reply" status; FE_GraphProgress gets in
the way of that. See bug #23414. */
}
nsresult nsSmtpProtocol::SendMessageResponse()
{
if((m_responseCode/10 != 25))
{
mozilla::DebugOnly<nsresult> rv = nsExplainErrorDetails(m_runningURL,
NS_ERROR_SENDING_MESSAGE,
m_responseText.get());
NS_ASSERTION(NS_SUCCEEDED(rv), "failed to explain SMTP error");
m_urlErrorState = NS_ERROR_BUT_DONT_SHOW_ALERT;
return(NS_ERROR_SENDING_MESSAGE);
}
UpdateStatus(u"smtpMailSent");
/* else */
return SendQuit();
}
nsresult nsSmtpProtocol::SendQuit(SmtpState aNextStateAfterResponse)
{
m_sendDone = true;
m_nextState = SMTP_RESPONSE;
m_nextStateAfterResponse = aNextStateAfterResponse;
return SendData("QUIT" CRLF); // send a quit command to close the connection with the server.
}
nsresult nsSmtpProtocol::LoadUrl(nsIURI * aURL, nsISupports * aConsumer )
{
if (!aURL)
return NS_OK;
Initialize(aURL);
m_continuationResponse = -1; /* init */
m_runningURL = do_QueryInterface(aURL);
if (!m_runningURL)
return NS_ERROR_FAILURE;
// we had a bug where we failed to bring up an alert if the host
// name was empty....so throw up an alert saying we don't have
// a host name and inform the caller that we are not going to
// run the url...
nsAutoCString hostName;
aURL->GetHost(hostName);
if (hostName.IsEmpty())
{
nsCOMPtr <nsIMsgMailNewsUrl> aMsgUrl = do_QueryInterface(aURL);
if (aMsgUrl)
{
aMsgUrl->SetUrlState(true, NS_OK);
// set the url as a url currently being run...
aMsgUrl->SetUrlState(false /* we aren't running the url */,
NS_ERROR_SMTP_AUTH_FAILURE);
}
return NS_ERROR_BUT_DONT_SHOW_ALERT;
}
bool postMessage = false;
m_runningURL->GetPostMessage(&postMessage);
if (postMessage)
{
m_nextState = SMTP_RESPONSE;
m_nextStateAfterResponse = SMTP_EXTN_LOGIN_RESPONSE;
// compile a minimal list of valid target addresses by
// - looking only at mailboxes
// - dropping addresses with invalid localparts (until we implement RFC 6532)
// - using ACE for IDN domainparts
// - stripping duplicates
nsCString addresses;
m_runningURL->GetRecipients(getter_Copies(addresses));
ExtractEmails(EncodedHeader(addresses), UTF16ArrayAdapter<>(m_addresses));
nsCOMPtr<nsIIDNService> converter = do_GetService(NS_IDNSERVICE_CONTRACTID);
addresses.Truncate();
uint32_t count = m_addresses.Length();
for (uint32_t i = 0; i < count; i++)
{
const char *start = m_addresses[i].get();
// Location of the @ character
const char *lastAt = nullptr;
const char *ch = start;
for (; *ch; ch++)
{
if (*ch == '@')
lastAt = ch;
// Check for first illegal character (outside 0x09,0x20-0x7e)
else if ((*ch < ' ' || *ch > '~') && (*ch != '\t'))
{
break;
}
}
// validate the just parsed address
if (*ch || m_addresses[i].IsEmpty())
{
// Fortunately, we will always have an @ in each mailbox address.
// We try to fix illegal character in the domain part by converting
// that to ACE. Illegal characters in the local part are not fixable
// (which charset would it be anyway?), hence we error out in that
// case as well.
nsresult rv = NS_ERROR_FAILURE; // anything but NS_OK
if (lastAt)
{
// Illegal char in the domain part, hence use ACE
nsAutoCString domain;
domain.Assign(lastAt + 1);
rv = converter->ConvertUTF8toACE(domain, domain);
if (NS_SUCCEEDED(rv))
{
m_addresses[i].SetLength(lastAt - start + 1);
m_addresses[i] += domain;
}
}
if (NS_FAILED(rv))
{
// Throw an error, including the broken address
m_nextState = SMTP_ERROR_DONE;
ClearFlag(SMTP_PAUSE_FOR_READ);
// Unfortunately, nsExplainErrorDetails will show the error above
// the mailnews main window, because we don't necessarily get
// passed down a compose window - we might be sending in the
// background!
rv = nsExplainErrorDetails(m_runningURL,
NS_ERROR_ILLEGAL_LOCALPART, start);
NS_ASSERTION(NS_SUCCEEDED(rv), "failed to explain illegal localpart");
m_urlErrorState = NS_ERROR_BUT_DONT_SHOW_ALERT;
return NS_ERROR_BUT_DONT_SHOW_ALERT;
}
}
}
// final cleanup
m_addressesLeft = m_addresses.Length();
// hmm no addresses to send message to...
if (m_addressesLeft == 0)
{
m_nextState = SMTP_ERROR_DONE;
ClearFlag(SMTP_PAUSE_FOR_READ);
m_urlErrorState = NS_MSG_NO_RECIPIENTS;
return NS_MSG_NO_RECIPIENTS;
}
} // if post message
return nsMsgProtocol::LoadUrl(aURL, aConsumer);
}
/*
* returns negative if the transfer is finished or error'd out
*
* returns zero or more if the transfer needs to be continued.
*/
nsresult nsSmtpProtocol::ProcessProtocolState(nsIURI * url, nsIInputStream * inputStream,
uint64_t sourceOffset, uint32_t length)
{
nsresult status = NS_OK;
ClearFlag(SMTP_PAUSE_FOR_READ); /* already paused; reset */
while(!TestFlag(SMTP_PAUSE_FOR_READ))
{
MOZ_LOG(SMTPLogModule, mozilla::LogLevel::Info, ("SMTP entering state: %d",
m_nextState));
switch(m_nextState)
{
case SMTP_RESPONSE:
if (inputStream == nullptr)
SetFlag(SMTP_PAUSE_FOR_READ);
else
status = SmtpResponse(inputStream, length);
break;
case SMTP_START_CONNECT:
SetFlag(SMTP_PAUSE_FOR_READ);
m_nextState = SMTP_RESPONSE;
m_nextStateAfterResponse = SMTP_EXTN_LOGIN_RESPONSE;
break;
case SMTP_FINISH_CONNECT:
SetFlag(SMTP_PAUSE_FOR_READ);
break;
case SMTP_TLS_RESPONSE:
if (inputStream == nullptr)
SetFlag(SMTP_PAUSE_FOR_READ);
else
status = SendTLSResponse();
break;
case SMTP_EXTN_LOGIN_RESPONSE:
if (inputStream == nullptr)
SetFlag(SMTP_PAUSE_FOR_READ);
else
status = ExtensionLoginResponse(inputStream, length);
break;
case SMTP_SEND_HELO_RESPONSE:
if (inputStream == nullptr)
SetFlag(SMTP_PAUSE_FOR_READ);
else
status = SendHeloResponse(inputStream, length);
break;
case SMTP_SEND_EHLO_RESPONSE:
if (inputStream == nullptr)
SetFlag(SMTP_PAUSE_FOR_READ);
else
status = SendEhloResponse(inputStream, length);
break;
case SMTP_AUTH_PROCESS_STATE:
status = ProcessAuth();
break;
case SMTP_SEND_AUTH_GSSAPI_FIRST:
status = AuthGSSAPIFirst();
break;
case SMTP_SEND_AUTH_GSSAPI_STEP:
status = AuthGSSAPIStep();
break;
case SMTP_SEND_AUTH_LOGIN_STEP0:
status = AuthLoginStep0();
break;
case SMTP_AUTH_LOGIN_STEP0_RESPONSE:
AuthLoginStep0Response();
status = NS_OK;
break;
case SMTP_AUTH_EXTERNAL_RESPONSE:
case SMTP_AUTH_LOGIN_RESPONSE:
if (inputStream == nullptr)
SetFlag(SMTP_PAUSE_FOR_READ);
else
status = AuthLoginResponse(inputStream, length);
break;
case SMTP_SEND_AUTH_LOGIN_STEP1:
status = AuthLoginStep1();
break;
case SMTP_SEND_AUTH_LOGIN_STEP2:
status = AuthLoginStep2();
break;
#ifdef MOZ_MAILNEWS_OAUTH2
case SMTP_AUTH_OAUTH2_STEP:
status = AuthOAuth2Step1();
break;
#endif
case SMTP_SEND_MAIL_RESPONSE:
if (inputStream == nullptr)
SetFlag(SMTP_PAUSE_FOR_READ);
else
status = SendMailResponse();
break;
case SMTP_SEND_RCPT_RESPONSE:
if (inputStream == nullptr)
SetFlag(SMTP_PAUSE_FOR_READ);
else
status = SendRecipientResponse();
break;
case SMTP_SEND_DATA_RESPONSE:
if (inputStream == nullptr)
SetFlag(SMTP_PAUSE_FOR_READ);
else
status = SendDataResponse();
break;
case SMTP_SEND_POST_DATA:
SendPostData();
status = NS_OK;
break;
case SMTP_SEND_MESSAGE_RESPONSE:
if (inputStream == nullptr)
SetFlag(SMTP_PAUSE_FOR_READ);
else
status = SendMessageResponse();
break;
case SMTP_DONE:
{
nsCOMPtr <nsIMsgMailNewsUrl> mailNewsUrl = do_QueryInterface(m_runningURL);
mailNewsUrl->SetUrlState(false, NS_OK);
}
m_nextState = SMTP_FREE;
break;
case SMTP_ERROR_DONE:
{
nsCOMPtr <nsIMsgMailNewsUrl> mailNewsUrl = do_QueryInterface(m_runningURL);
// propagate the right error code
mailNewsUrl->SetUrlState(false, m_urlErrorState);
}
m_nextState = SMTP_FREE;
break;
case SMTP_FREE:
// smtp is a one time use connection so kill it if we get here...
nsMsgAsyncWriteProtocol::CloseSocket();
return NS_OK; /* final end */
#ifdef MOZ_MAILNEWS_OAUTH2
// This state means we're going into an async loop and waiting for
// something (say auth) to happen. ProcessProtocolState will be
// retriggered when necessary.
case SMTP_SUSPENDED:
return NS_OK;
#endif
default: /* should never happen !!! */
m_nextState = SMTP_ERROR_DONE;
break;
}
/* check for errors during load and call error
* state if found
*/
if (NS_FAILED(status) && m_nextState != SMTP_FREE) {
// send a quit command to close the connection with the server.
if (NS_FAILED(SendQuit(SMTP_ERROR_DONE)))
{
m_nextState = SMTP_ERROR_DONE;
// Don't exit - loop around again and do the free case
ClearFlag(SMTP_PAUSE_FOR_READ);
}
}
} /* while(!SMTP_PAUSE_FOR_READ) */
return NS_OK;
}
nsresult
nsSmtpProtocol::GetPassword(nsCString &aPassword)
{
nsresult rv;
nsCOMPtr<nsISmtpUrl> smtpUrl = do_QueryInterface(m_runningURL, &rv);
NS_ENSURE_SUCCESS(rv,rv);
nsCOMPtr<nsISmtpServer> smtpServer;
rv = smtpUrl->GetSmtpServer(getter_AddRefs(smtpServer));
NS_ENSURE_SUCCESS(rv,rv);
rv = smtpServer->GetPassword(aPassword);
NS_ENSURE_SUCCESS(rv,rv);
if (!aPassword.IsEmpty())
return rv;
// empty password
nsCOMPtr <nsIPrefService> prefs = do_GetService(NS_PREFSERVICE_CONTRACTID, &rv);
NS_ENSURE_SUCCESS(rv,rv);
nsCOMPtr<nsIPrefBranch> prefBranch;
rv = prefs->GetBranch(nullptr, getter_AddRefs(prefBranch));
NS_ENSURE_SUCCESS(rv,rv);
nsCString username;
rv = smtpServer->GetUsername(username);
NS_ENSURE_SUCCESS(rv, rv);
NS_ConvertASCIItoUTF16 usernameUTF16(username);
nsCString hostname;
rv = smtpServer->GetHostname(hostname);
NS_ENSURE_SUCCESS(rv, rv);
nsAutoString hostnameUTF16;
CopyASCIItoUTF16(hostname, hostnameUTF16);
const char16_t *formatStrings[] =
{
hostnameUTF16.get(),
usernameUTF16.get()
};
rv = PromptForPassword(smtpServer, smtpUrl, formatStrings, aPassword);
NS_ENSURE_SUCCESS(rv,rv);
return rv;
}
/**
* formatStrings is an array for the prompts, item 0 is the hostname, item 1
* is the username.
*/
nsresult
nsSmtpProtocol::PromptForPassword(nsISmtpServer *aSmtpServer, nsISmtpUrl *aSmtpUrl, const char16_t **formatStrings, nsACString &aPassword)
{
nsCOMPtr<nsIStringBundleService> stringService =
mozilla::services::GetStringBundleService();
NS_ENSURE_TRUE(stringService, NS_ERROR_UNEXPECTED);
nsCOMPtr<nsIStringBundle> composeStringBundle;
nsresult rv = stringService->CreateBundle("chrome://messenger/locale/messengercompose/composeMsgs.properties", getter_AddRefs(composeStringBundle));
NS_ENSURE_SUCCESS(rv,rv);
nsString passwordPromptString;
if(formatStrings[1])
rv = composeStringBundle->FormatStringFromName(
u"smtpEnterPasswordPromptWithUsername",
formatStrings, 2, getter_Copies(passwordPromptString));
else
rv = composeStringBundle->FormatStringFromName(
u"smtpEnterPasswordPrompt",
formatStrings, 1, getter_Copies(passwordPromptString));
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIAuthPrompt> netPrompt;
rv = aSmtpUrl->GetAuthPrompt(getter_AddRefs(netPrompt));
NS_ENSURE_SUCCESS(rv, rv);
nsString passwordTitle;
rv = composeStringBundle->GetStringFromName(
u"smtpEnterPasswordPromptTitle",
getter_Copies(passwordTitle));
NS_ENSURE_SUCCESS(rv,rv);
rv = aSmtpServer->GetPasswordWithUI(passwordPromptString.get(), passwordTitle.get(),
netPrompt, aPassword);
NS_ENSURE_SUCCESS(rv,rv);
return rv;
}
nsresult
nsSmtpProtocol::GetUsernamePassword(nsACString &aUsername,
nsACString &aPassword)
{
nsresult rv;
nsCOMPtr<nsISmtpUrl> smtpUrl = do_QueryInterface(m_runningURL, &rv);
NS_ENSURE_SUCCESS(rv,rv);
nsCOMPtr<nsISmtpServer> smtpServer;
rv = smtpUrl->GetSmtpServer(getter_AddRefs(smtpServer));
NS_ENSURE_SUCCESS(rv,rv);
rv = smtpServer->GetPassword(aPassword);
NS_ENSURE_SUCCESS(rv,rv);
if (!aPassword.IsEmpty())
{
rv = smtpServer->GetUsername(aUsername);
NS_ENSURE_SUCCESS(rv,rv);
if (!aUsername.IsEmpty())
return rv;
}
// empty password
aPassword.Truncate();
nsCString hostname;
rv = smtpServer->GetHostname(hostname);
NS_ENSURE_SUCCESS(rv, rv);
nsAutoString hostnameUTF16;
CopyASCIItoUTF16(hostname, hostnameUTF16);
const char16_t *formatStrings[] =
{
hostnameUTF16.get(),
nullptr
};
rv = PromptForPassword(smtpServer, smtpUrl, formatStrings, aPassword);
NS_ENSURE_SUCCESS(rv,rv);
return rv;
}
|