summaryrefslogtreecommitdiffstats
path: root/comm/mailnews/imap/src/ImapClient.jsm
blob: 319a03b9581f5c286da5d426c0ed36966764e117 (plain)
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
/* 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/. */

const EXPORTED_SYMBOLS = ["ImapClient"];

var { AppConstants } = ChromeUtils.importESModule(
  "resource://gre/modules/AppConstants.sys.mjs"
);
var { clearTimeout, setTimeout } = ChromeUtils.importESModule(
  "resource://gre/modules/Timer.sys.mjs"
);
var { MailStringUtils } = ChromeUtils.import(
  "resource:///modules/MailStringUtils.jsm"
);
var { ImapAuthenticator } = ChromeUtils.import(
  "resource:///modules/MailAuthenticator.jsm"
);
var { ImapResponse } = ChromeUtils.import(
  "resource:///modules/ImapResponse.jsm"
);
var { ImapUtils } = ChromeUtils.import("resource:///modules/ImapUtils.jsm");

// There can be multiple ImapClient running concurrently, assign each logger a
// unique prefix.
let loggerInstanceId = 0;

const PR_UINT32_MAX = 0xffffffff;

/**
 * A class to interact with IMAP server.
 */
class ImapClient {
  _logger = console.createInstance({
    prefix: `mailnews.imap.${loggerInstanceId++}`,
    maxLogLevel: "Warn",
    maxLogLevelPref: "mailnews.imap.loglevel",
  });

  /**
   * @param {nsIImapIncomingServer} server - The associated server instance.
   */
  constructor(server) {
    this._server = server.QueryInterface(Ci.nsIMsgIncomingServer);
    this._serverSink = this._server.QueryInterface(Ci.nsIImapServerSink);
    this._authenticator = new ImapAuthenticator(server);

    // Auth methods detected from the CAPABILITY response.
    this._supportedAuthMethods = [];
    // Subset of _supportedAuthMethods that are allowed by user preference.
    this._possibleAuthMethods = [];
    // Auth methods set by user preference.
    this._preferredAuthMethods =
      {
        [Ci.nsMsgAuthMethod.passwordCleartext]: ["PLAIN", "LOGIN"],
        [Ci.nsMsgAuthMethod.passwordEncrypted]: ["CRAM-MD5"],
        [Ci.nsMsgAuthMethod.GSSAPI]: ["GSSAPI"],
        [Ci.nsMsgAuthMethod.NTLM]: ["NTLM"],
        [Ci.nsMsgAuthMethod.OAuth2]: ["XOAUTH2"],
        [Ci.nsMsgAuthMethod.External]: ["EXTERNAL"],
      }[server.authMethod] || [];
    // The next auth method to try if the current failed.
    this._nextAuthMethod = null;

    this._tag = Math.floor(100 * Math.random());
    this._charsetManager = Cc[
      "@mozilla.org/charset-converter-manager;1"
    ].getService(Ci.nsICharsetConverterManager);

    this._messageUids = [];
    this._messages = new Map();

    this._loadPrefs();
  }

  /**
   * @type {boolean} - Whether the socket is open.
   */
  get isOnline() {
    return this._socket?.readyState == "open";
  }

  /**
   * Load imap related preferences, many behaviors depend on these pref values.
   */
  _loadPrefs() {
    this._prefs = {
      tcpTimeout: Services.prefs.getIntPref("mailnews.tcptimeout"),
    };
  }

  /**
   * Reset some internal states to be safely reused.
   */
  _reset() {
    this.onData = () => {};
    this.onDone = () => {};

    this._actionAfterDiscoverAllFolders = null;
    this.channel = null;
    this._urlListener = null;
    this._msgWindow = null;
    this._authenticating = false;
    this.verifyLogon = false;
    this._idling = false;
    if (this._idleTimer) {
      clearTimeout(this._idleTimer);
      this._idleTimer = null;
    }
  }

  /**
   * Initiate a connection to the server
   */
  connect() {
    if (this.isOnline) {
      // Reuse the connection.
      this.onReady();
      this._setSocketTimeout(this._prefs.tcpTimeout);
    } else {
      let hostname = this._server.hostName.toLowerCase();
      this._logger.debug(`Connecting to ${hostname}:${this._server.port}`);
      this._greeted = false;
      this._capabilities = null;
      this._secureTransport = this._server.socketType == Ci.nsMsgSocketType.SSL;
      this._socket = new TCPSocket(hostname, this._server.port, {
        binaryType: "arraybuffer",
        useSecureTransport: this._secureTransport,
      });
      this._socket.onopen = this._onOpen;
      this._socket.onerror = this._onError;
    }
  }

  /**
   * Set socket timeout in seconds.
   *
   * @param {number} timeout - The timeout in seconds.
   */
  _setSocketTimeout(timeout) {
    this._socket.transport?.setTimeout(
      Ci.nsISocketTransport.TIMEOUT_READ_WRITE,
      timeout
    );
  }

  /**
   * Construct an nsIMsgMailNewsUrl instance, setup urlListener to notify when
   * the current request is finished.
   *
   * @param {nsIUrlListener} urlListener - Callback for the request.
   * @param {nsIMsgWindow} msgWindow - The associated msg window.
   * @param {nsIMsgMailNewsUrl} [runningUri] - The url to run, if provided.
   * @returns {nsIMsgMailNewsUrl}
   */
  startRunningUrl(urlListener, msgWindow, runningUri) {
    this._urlListener = urlListener;
    this._msgWindow = msgWindow;
    this.runningUri = runningUri;
    if (!this.runningUri) {
      this.runningUri = Services.io.newURI(
        `imap://${this._server.hostName}:${this._server.port}`
      );
    }
    this._urlListener?.OnStartRunningUrl(this.runningUri, Cr.NS_OK);
    this.runningUri
      .QueryInterface(Ci.nsIMsgMailNewsUrl)
      .SetUrlState(true, Cr.NS_OK);
    return this.runningUri;
  }

  /**
   * Discover all folders if the current server hasn't already discovered.
   */
  _discoverAllFoldersIfNecessary = () => {
    if (this._server.hasDiscoveredFolders) {
      this.onReady();
      return;
    }
    this._actionAfterDiscoverAllFolders = this.onReady;
    this.discoverAllFolders(this._server.rootFolder);
  };

  /**
   * Discover all folders.
   *
   * @param {nsIMsgFolder} folder - The associated folder.
   */
  discoverAllFolders(folder) {
    this._logger.debug("discoverAllFolders", folder.URI);

    let handleListResponse = res => {
      this._hasTrash = res.mailboxes.some(
        mailbox => mailbox.flags & ImapUtils.FLAG_IMAP_TRASH
      );
      if (!this._hasTrash) {
        let trashFolderName = this._server.trashFolderName.toLowerCase();
        let trashMailbox = res.mailboxes.find(
          mailbox => mailbox.name.toLowerCase() == trashFolderName
        );
        if (trashMailbox) {
          this._hasTrash = true;
          trashMailbox.flags |= ImapUtils.FLAG_IMAP_TRASH;
        }
      }
      for (let mailbox of res.mailboxes) {
        this._serverSink.possibleImapMailbox(
          mailbox.name.replaceAll(mailbox.delimiter, "/"),
          mailbox.delimiter,
          mailbox.flags
        );
      }
    };

    if (this._capabilities.includes("LIST-EXTENDED")) {
      this._nextAction = res => {
        handleListResponse(res);
        this._actionFinishFolderDiscovery();
      };
      let command = 'LIST (SUBSCRIBED) "" "*"';
      if (this._capabilities.includes("SPECIAL-USE")) {
        command += " RETURN (SPECIAL-USE)"; // rfc6154
      }
      this._sendTagged(command);
      return;
    }

    this._nextAction = res => {
      this._nextAction = res2 => {
        // Per rfc3501#section-6.3.9, if LSUB returns different flags from LIST,
        // use the LIST responses.
        for (let mailbox of res2.mailboxes) {
          let mailboxFromList = res.mailboxes.find(x => x.name == mailbox.name);
          if (
            mailboxFromList?.flags &&
            mailboxFromList?.flags != mailbox.flags
          ) {
            mailbox.flags = mailboxFromList.flags;
          }
        }
        handleListResponse(res2);
        this._actionFinishFolderDiscovery();
      };
      this._sendTagged('LSUB "" "*"');
    };
    let command = 'LIST "" "*"';
    if (this._capabilities.includes("SPECIAL-USE")) {
      command += " RETURN (SPECIAL-USE)"; // rfc6154
    }
    this._sendTagged(command);
  }

  /**
   * Discover all folders for the subscribe dialog.
   *
   * @param {nsIMsgFolder} folder - The associated folder.
   */
  discoverAllAndSubscribedFolders(folder) {
    this._logger.debug("discoverAllAndSubscribedFolders", folder.URI);
    let handleListResponse = res => {
      for (let mailbox of res.mailboxes) {
        this._serverSink.possibleImapMailbox(
          mailbox.name.replaceAll(mailbox.delimiter, "/"),
          mailbox.delimiter,
          mailbox.flags
        );
      }
    };

    this._nextAction = res => {
      handleListResponse(res);
      this._server.doingLsub = false;
      this._nextAction = res2 => {
        // Per rfc3501#section-6.3.9, if LSUB returns different flags from LIST,
        // use the LIST responses.
        for (let mailbox of res2.mailboxes) {
          let mailboxFromList = res.mailboxes.find(x => x.name == mailbox.name);
          if (
            mailboxFromList?.flags &&
            mailboxFromList?.flags != mailbox.flags
          ) {
            mailbox.flags = mailboxFromList.flags;
          }
        }
        handleListResponse(res2);
        this._actionDone();
      };
      this._sendTagged('LIST "" "*"');
    };
    this._sendTagged('LSUB "" "*"');
    this._server.doingLsub = true;
  }

  /**
   * Select a folder.
   *
   * @param {nsIMsgFolder} folder - The folder to select.
   */
  selectFolder(folder) {
    this._logger.debug("selectFolder", folder.URI);
    if (this.folder == folder) {
      this._actionNoop();
      return;
    }
    this._actionAfterSelectFolder = this._actionUidFetch;
    this._nextAction = this._actionSelectResponse(folder);
    this._sendTagged(`SELECT "${this._getServerFolderName(folder)}"`);
  }

  /**
   * Rename a folder.
   *
   * @param {nsIMsgFolder} folder - The folder to rename.
   * @param {string} newName - The new folder name.
   */
  renameFolder(folder, newName) {
    this._logger.debug("renameFolder", folder.URI, newName);
    let delimiter =
      folder.QueryInterface(Ci.nsIMsgImapMailFolder).hierarchyDelimiter || "/";
    let names = this._getAncestorFolderNames(folder);
    let oldName = this._getServerFolderName(folder);
    newName = this._encodeMailboxName([...names, newName].join(delimiter));

    this._nextAction = this._actionRenameResponse(oldName, newName);
    this._sendTagged(`RENAME "${oldName}" "${newName}"`);
  }

  /**
   * Move a source folder to be a child of another folder.
   *
   * @param {nsIMsgFolder} srcFolder - The source folder to move.
   * @param {nsIMsgFolder} dstFolder - The target parent folder.
   */
  moveFolder(srcFolder, dstFolder) {
    this._logger.debug("moveFolder", srcFolder.URI, dstFolder.URI);
    let oldName = this._getServerFolderName(srcFolder);
    let newName = this._getServerSubFolderName(dstFolder, srcFolder.name);
    this._nextAction = this._actionRenameResponse(oldName, newName, true);
    this._sendTagged(`RENAME "${oldName}" "${newName}"`);
  }

  /**
   * Send LIST command for a folder.
   *
   * @param {nsIMsgFolder} folder - The folder to list.
   */
  listFolder(folder) {
    this._logger.debug("listFolder", folder.URI);
    this._actionList(this._getServerFolderName(folder), () => {
      this._actionDone();
    });
  }

  /**
   * Send DELETE command for a folder and all subfolders.
   *
   * @param {nsIMsgFolder} folder - The folder to delete.
   */
  deleteFolder(folder) {
    this._logger.debug("deleteFolder", folder.URI);
    this._nextAction = res => {
      // Leaves have longer names than parent mailbox, sort them by the name
      // length, so that leaf mailbox will be deleted first.
      let mailboxes = res.mailboxes.sort(
        (x, y) => y.name.length - x.name.length
      );
      let selfName = this._getServerFolderName(folder);
      let selfIncluded = false;
      this._nextAction = () => {
        let mailbox = mailboxes.shift();
        if (mailbox) {
          this._sendTagged(`DELETE "${mailbox.name}"`);
          if (!selfIncluded && selfName == mailbox.name) {
            selfIncluded = true;
          }
        } else if (!selfIncluded) {
          this._nextAction = () => this._actionDone();
          this._sendTagged(`DELETE "${this._getServerFolderName(folder)}"`);
        } else {
          this._actionDone();
        }
      };
      this._nextAction();
    };
    this._sendTagged(`LIST "" "${this._getServerFolderName(folder)}"`);
  }

  /**
   * Ensure a folder exists on the server. Create one if not already exists.
   *
   * @param {nsIMsgFolder} parent - The parent folder to check.
   * @param {string} folderName - The folder name.
   */
  ensureFolderExists(parent, folderName) {
    this._logger.debug("ensureFolderExists", parent.URI, folderName);
    let mailboxName = this._getServerSubFolderName(parent, folderName);
    this._nextAction = res => {
      if (res.mailboxes.length) {
        // Already exists.
        this._actionDone();
        return;
      }
      // Create one and subscribe to it.
      this._actionCreateAndSubscribe(mailboxName, res => {
        this._actionList(mailboxName, () => this._actionDone());
      });
    };
    this._sendTagged(`LIST "" "${mailboxName}"`);
  }

  /**
   * Create a folder on the server.
   *
   * @param {nsIMsgFolder} parent - The parent folder to check.
   * @param {string} folderName - The folder name.
   */
  createFolder(parent, folderName) {
    this._logger.debug("createFolder", parent.URI, folderName);
    let mailboxName = this._getServerSubFolderName(parent, folderName);
    this._actionCreateAndSubscribe(mailboxName, res => {
      this._actionList(mailboxName, () => this._actionDone());
    });
  }

  /**
   * Subscribe a folder.
   *
   * @param {nsIMsgFolder} folder - The folder to subscribe.
   * @param {string} folderName - The folder name.
   */
  subscribeFolder(folder, folderName) {
    this._logger.debug("subscribeFolder", folder.URI, folderName);
    this._nextAction = () => this._server.performExpand();
    this._sendTagged(`SUBSCRIBE "${folderName}"`);
  }

  /**
   * Unsubscribe a folder.
   *
   * @param {nsIMsgFolder} folder - The folder to unsubscribe.
   * @param {string} folderName - The folder name.
   */
  unsubscribeFolder(folder, folderName) {
    this._logger.debug("unsubscribeFolder", folder.URI, folderName);
    this._nextAction = () => this._server.performExpand();
    this._sendTagged(`UNSUBSCRIBE "${folderName}"`);
  }

  /**
   * Fetch the attribute of messages.
   *
   * @param {nsIMsgFolder} folder - The folder to check.
   * @param {string} uids - The message uids.
   * @param {string} attribute - The message attribute to fetch
   */
  fetchMsgAttribute(folder, uids, attribute) {
    this._logger.debug("fetchMsgAttribute", folder.URI, uids, attribute);
    this._nextAction = res => {
      if (res.done) {
        let resultAttributes = res.messages
          .map(m => m.customAttributes[attribute])
          .flat();
        this.runningUri.QueryInterface(Ci.nsIImapUrl).customAttributeResult =
          resultAttributes.length > 1
            ? `(${resultAttributes.join(" ")})`
            : resultAttributes[0];
        this._actionDone();
      }
    };
    this._sendTagged(`UID FETCH ${uids} (${attribute})`);
  }

  /**
   * Delete all the messages in a folder.
   *
   * @param {nsIMsgFolder} folder - The folder to delete messages.
   */
  deleteAllMessages(folder) {
    this._logger.debug("deleteAllMessages", folder.URI);
    this._actionInFolder(folder, () => {
      if (!this._messages.size) {
        this._actionDone();
        return;
      }

      this._nextAction = () => this.expunge(folder);
      this._sendTagged("UID STORE 1:* +FLAGS.SILENT (\\Deleted)");
    });
  }

  /**
   * Search in a folder.
   *
   * @param {nsIMsgFolder} folder - The folder to delete messages.
   * @param {string} searchCommand - The SEARCH command together with the search
   *   criteria.
   */
  search(folder, searchCommand) {
    this._logger.debug("search", folder.URI);
    this._actionInFolder(folder, () => {
      this._nextAction = res => {
        this.onData(res.search);
        this._actionDone();
      };
      this._sendTagged(`UID ${searchCommand}`);
    });
  }

  /**
   * Get the names of all ancestor folders. For example,
   *   folder a/b/c will return ['a', 'b'].
   *
   * @param {nsIMsgFolder} folder - The input folder.
   * @returns {string[]}
   */
  _getAncestorFolderNames(folder) {
    let matches = /imap:\/\/[^/]+\/(.+)/.exec(folder.URI);
    return matches[1].split("/").slice(0, -1);
  }

  /**
   * When UTF8 is enabled, use the name directly. Otherwise, encode to mUTF-7.
   *
   * @param {string} name - The mailbox name.
   */
  _encodeMailboxName(name) {
    return this._utf8Enabled ? name : this._charsetManager.unicodeToMutf7(name);
  }

  /**
   * Get the server name of a msg folder.
   *
   * @param {nsIMsgFolder} folder - The input folder.
   * @returns {string}
   */
  _getServerFolderName(folder) {
    if (folder.isServer) {
      return "";
    }

    if (folder.onlineName) {
      return folder.onlineName.replaceAll('"', '\\"');
    }
    let delimiter =
      folder.QueryInterface(Ci.nsIMsgImapMailFolder).hierarchyDelimiter || "/";
    let names = this._getAncestorFolderNames(folder);
    return this._encodeMailboxName(
      [...names, folder.name].join(delimiter)
    ).replaceAll('"', '\\"');
  }

  /**
   * Get the server name of a sub folder. The sub folder may or may not exist on
   * the server.
   *
   * @param {nsIMsgFolder} parent - The parent folder.
   * @param {string} folderName - The sub folder name.
   * @returns {string}
   */
  _getServerSubFolderName(parent, folderName) {
    folderName = this._encodeMailboxName(folderName);
    let mailboxName = this._getServerFolderName(parent);
    if (mailboxName) {
      let delimiter = parent.QueryInterface(
        Ci.nsIMsgImapMailFolder
      ).hierarchyDelimiter;
      // @see nsImapCore.h.
      const ONLINE_HIERARCHY_SEPARATOR_UNKNOWN = "^";
      if (!delimiter || delimiter == ONLINE_HIERARCHY_SEPARATOR_UNKNOWN) {
        delimiter = "/";
      }
      return mailboxName + delimiter + folderName;
    }
    return folderName;
  }

  /**
   * Fetch the full content of a message by UID.
   *
   * @param {nsIMsgFolder} folder - The associated folder.
   * @param {number} uid - The message uid.
   * @param {number} [size] - The body size to fetch.
   */
  fetchMessage(folder, uid, size) {
    this._logger.debug(`fetchMessage folder=${folder.name} uid=${uid}`);
    if (folder.hasMsgOffline(uid, null, 10)) {
      this.onDone = () => {};
      this.channel?.readFromLocalCache();
      this._actionDone();
      return;
    }
    this._actionInFolder(folder, () => {
      this._nextAction = this._actionUidFetchBodyResponse;
      let command;
      if (size) {
        command = `UID FETCH ${uid} (UID RFC822.SIZE FLAGS BODY.PEEK[HEADER.FIELDS (Content-Type Content-Transfer-Encoding)] BODY.PEEK[TEXT]<0.${size}>)`;
      } else {
        command = `UID FETCH ${uid} (UID RFC822.SIZE FLAGS BODY.PEEK[])`;
      }
      this._sendTagged(command);
    });
  }

  /**
   * Add, remove or replace flags of specified messages.
   *
   * @param {string} action - "+" means add, "-" means remove, "" means replace.
   * @param {nsIMsgFolder} folder - The target folder.
   * @param {string} messageIds - Message UIDs, e.g. "23,30:33".
   * @param {number} flags - The internal flags number to update.
   */
  updateMessageFlags(action, folder, messageIds, flags) {
    this._actionInFolder(folder, () => {
      this._nextAction = () => this._actionDone();
      // _supportedFlags is available after _actionSelectResponse.
      let flagsStr = ImapUtils.flagsToString(flags, this._supportedFlags);
      this._sendTagged(`UID STORE ${messageIds} ${action}FLAGS (${flagsStr})`);
    });
  }

  /**
   * Send EXPUNGE command to a folder.
   *
   * @param {nsIMsgFolder} folder - The associated folder.
   */
  expunge(folder) {
    this._actionInFolder(folder, () => {
      this._nextAction = () => this._actionDone();
      this._sendTagged("EXPUNGE");
    });
  }

  /**
   * Move or copy messages from a folder to another folder.
   *
   * @param {nsIMsgFolder} folder - The source folder.
   * @param {nsIMsgFolder} folder - The target folder.
   * @param {string} messageIds - The message identifiers.
   * @param {boolean} idsAreUids - If true messageIds are UIDs, otherwise,
   *   messageIds are sequences.
   * @param {boolean} isMove - If true, use MOVE command when supported.
   */
  copy(folder, dstFolder, messageIds, idsAreUids, isMove) {
    let command = idsAreUids ? "UID " : "";
    command +=
      isMove && this._capabilities.includes("MOVE")
        ? "MOVE " // rfc6851
        : "COPY ";
    command += messageIds + ` "${this._getServerFolderName(dstFolder)}"`;
    this._actionInFolder(folder, () => {
      this._nextAction = this._actionNoopResponse;
      this._sendTagged(command);
    });
  }

  /**
   * Upload a message file to a folder.
   *
   * @param {nsIFile} file - The message file to upload.
   * @param {nsIMsgFolder} dstFolder - The target folder.
   * @param {nsImapMailCopyState} copyState - A state used by nsImapMailFolder.
   * @param {boolean} isDraft - Is the uploaded file a draft.
   */
  async uploadMessageFromFile(file, dstFolder, copyState, isDraft) {
    this._logger.debug("uploadMessageFromFile", file.path, dstFolder.URI);
    let mailbox = this._getServerFolderName(dstFolder);
    let content = MailStringUtils.uint8ArrayToByteString(
      await IOUtils.read(file.path)
    );
    this._nextAction = res => {
      if (res.tag != "+") {
        this._actionDone(Cr.NS_ERROR_FAILURE);
        return;
      }
      this._nextAction = res => {
        this._folderSink = dstFolder.QueryInterface(Ci.nsIImapMailFolderSink);
        if (
          // See rfc4315.
          this._capabilities.includes("UIDPLUS") &&
          res.attributes.appenduid
        ) {
          // The response is like `<tag> OK [APPENDUID <uidvalidity> <uid>]`.
          this._folderSink.setAppendMsgUid(
            res.attributes.appenduid[1],
            this.runningUri
          );
        }
        this._actionDone();
        if (res.exists) {
          // FIXME: _actionNoopResponse should be enough here, but it breaks
          // test_imapAttachmentSaves.js.
          this.folder = null;
        }
        try {
          this._folderSink.copyNextStreamMessage(true, copyState);
        } catch (e) {
          this._logger.warn("copyNextStreamMessage failed", e);
        }
      };
      this._send(content + (this._utf8Enabled ? ")" : ""));
    };
    let outKeywords = {};
    let flags = dstFolder
      .QueryInterface(Ci.nsIImapMessageSink)
      .getCurMoveCopyMessageInfo(this.runningUri, {}, outKeywords);
    let flagString = ImapUtils.flagsToString(flags, this._supportedFlags);
    if (isDraft && !/\b\Draft\b/.test(flagString)) {
      flagString += " \\Draft";
    }
    if (outKeywords.value) {
      flagString += " " + outKeywords.value;
    }
    let open = this._utf8Enabled ? "UTF8 (~{" : "{";
    let command = `APPEND "${mailbox}" (${flagString.trim()}) ${open}${
      content.length
    }}`;
    this._sendTagged(command);
  }

  /**
   * Check the status of a folder.
   *
   * @param {nsIMsgFolder} folder - The folder to check.
   */
  updateFolderStatus(folder) {
    this._logger.debug("updateFolderStatus", folder.URI);
    if (this._folder == folder) {
      // According to rfc3501, "the STATUS command SHOULD NOT be used on the
      // currently selected mailbox", so use NOOP instead.
      this._actionNoop();
      return;
    }

    this._nextAction = res => {
      if (res.status == "OK") {
        folder
          .QueryInterface(Ci.nsIImapMailFolderSink)
          .UpdateImapMailboxStatus(this, {
            QueryInterface: ChromeUtils.generateQI(["nsIMailboxSpec"]),
            nextUID: res.attributes.uidnext,
            numMessages: res.attributes.messages.length,
            numUnseenMessages: res.attributes.unseen,
          });
        folder.msgDatabase = null;
      }
      this._actionDone();
    };
    this._sendTagged(
      `STATUS "${this._getServerFolderName(folder)}" (UIDNEXT MESSAGES UNSEEN)`
    );
  }

  /**
   * Update message flags.
   *
   * @param {nsIMsgFolder} folder - The associated folder.
   * @param {string} flagsToAdd - The flags to add.
   * @param {string} flagsToSubtract - The flags to subtract.
   * @param {string} uids - The message uids.
   */
  storeCustomKeywords(folder, flagsToAdd, flagsToSubtract, uids) {
    this._logger.debug(
      "storeCustomKeywords",
      folder.URI,
      flagsToAdd,
      flagsToSubtract,
      uids
    );
    let subtractFlags = () => {
      if (flagsToSubtract) {
        this._nextAction = () => {
          this._actionDone();
        };
        this._sendTagged(`UID STORE ${uids} -FLAGS (${flagsToSubtract})`);
      } else {
        this._actionDone();
      }
    };
    this._actionInFolder(folder, () => {
      if (flagsToAdd) {
        this._nextAction = () => {
          subtractFlags();
        };
        this._sendTagged(`UID STORE ${uids} +FLAGS (${flagsToAdd})`);
      } else {
        subtractFlags();
      }
    });
  }

  /**
   * Get message headers by the specified uids.
   *
   * @param {nsIMsgFolder} folder - The folder of the messages.
   * @param {string[]} uids - The message uids.
   */
  getHeaders(folder, uids) {
    this._logger.debug("getHeaders", folder.URI, uids);
    this._actionInFolder(folder, () => {
      this._nextAction = this._actionUidFetchHeaderResponse;
      let extraItems = "";
      if (this._server.isGMailServer) {
        extraItems += "X-GM-MSGID X-GM-THRID X-GM-LABELS ";
      }
      this._sendTagged(
        `UID FETCH ${uids} (UID ${extraItems}RFC822.SIZE FLAGS BODY.PEEK[HEADER])`
      );
    });
  }

  /**
   * Send IDLE command to the server.
   */
  idle() {
    if (!this.folder) {
      this._actionDone();
      return;
    }
    this._nextAction = res => {
      if (res.tag == "*") {
        this.folder.performingBiff = true;
        this._actionNoopResponse(res);
      }
    };
    this._sendTagged("IDLE");
    this._setSocketTimeout(PR_UINT32_MAX);
    this._idling = true;
    this._idleTimer = setTimeout(() => {
      this.endIdle(() => {
        this._actionNoop();
      });
      // Per rfc2177, should terminate the IDLE and re-issue it at least every
      // 29 minutes. But in practice many servers timeout before that. A noop
      // every 5min is better than timeout.
    }, 5 * 60 * 1000);
    this._logger.debug(`Idling in ${this.folder.URI}`);
  }

  /**
   * Send DONE to end the IDLE command.
   *
   * @param {Function} nextAction - Callback function after IDLE is ended.
   */
  endIdle(nextAction) {
    this._nextAction = res => {
      if (res.status == "OK") {
        nextAction();
      }
    };
    this._send("DONE");
    this._idling = false;
    this.busy = true;
    clearTimeout(this._idleTimer);
    this._idleTimer = null;
  }

  /**
   * Send LOGOUT and close the socket.
   */
  logout() {
    this._sendTagged("LOGOUT");
    this._socket.close();
  }

  /**
   * The open event handler.
   */
  _onOpen = () => {
    this._logger.debug("Connected");
    this._socket.ondata = this._onData;
    this._socket.onclose = this._onClose;
    this._nextAction = res => {
      this._greeted = true;
      this._actionCapabilityResponse(res);
    };

    this._setSocketTimeout(this._prefs.tcpTimeout);
  };

  /**
   * The data event handler.
   *
   * @param {TCPSocketEvent} event - The data event.
   */
  _onData = async event => {
    // Without this, some tests are blocked waiting for response from Maild.jsm.
    // Don't know the real cause, but possibly because ImapClient and Maild runs
    // on the same process. We also have this in Pop3Client.
    await new Promise(resolve => setTimeout(resolve));

    let stringPayload = this._utf8Enabled
      ? new TextDecoder().decode(event.data)
      : MailStringUtils.uint8ArrayToByteString(new Uint8Array(event.data));
    this._logger.debug(`S: ${stringPayload}`);
    if (!this._response || this._idling || this._response.done) {
      this._response = new ImapResponse();
      this._response.onMessage = this._onMessage;
    }
    this._response.parse(stringPayload);
    if (
      !this._authenticating &&
      this._response.done &&
      this._response.status &&
      this._response.tag != "+" &&
      !["OK", "+"].includes(this._response.status)
    ) {
      this._actionDone(ImapUtils.NS_MSG_ERROR_IMAP_COMMAND_FAILED);
      return;
    }
    if (!this._greeted || this._idling || this._response.done) {
      this._nextAction?.(this._response);
    }
  };

  /**
   * The error event handler.
   *
   * @param {TCPSocketErrorEvent} event - The error event.
   */
  _onError = async event => {
    this._logger.error(`${event.name}: a ${event.message} error occurred`);
    if (event.errorCode == Cr.NS_ERROR_NET_TIMEOUT) {
      this._actionError("imapNetTimeoutError");
      this._actionDone(event.errorCode);
      return;
    }

    let secInfo =
      await event.target.transport?.tlsSocketControl?.asyncGetSecurityInfo();
    if (secInfo) {
      this._logger.error(`SecurityError info: ${secInfo.errorCodeString}`);
      if (secInfo.failedCertChain.length) {
        let chain = secInfo.failedCertChain.map(c => {
          return c.commonName + "; serial# " + c.serialNumber;
        });
        this._logger.error(`SecurityError cert chain: ${chain.join(" <- ")}`);
      }
      this.runningUri.failedSecInfo = secInfo;
      this._server.closeCachedConnections();
    } else {
      this.logout();
    }

    this._actionDone(event.errorCode);
  };

  /**
   * The close event handler.
   */
  _onClose = () => {
    this._logger.debug("Connection closed.");
    this.folder = null;
  };

  /**
   * Send a command to the server.
   *
   * @param {string} str - The command string to send.
   * @param {boolean} [suppressLogging=false] - Whether to suppress logging the str.
   */
  _send(str, suppressLogging) {
    if (suppressLogging && AppConstants.MOZ_UPDATE_CHANNEL != "default") {
      this._logger.debug(
        "C: Logging suppressed (it probably contained auth information)"
      );
    } else {
      // Do not suppress for non-release builds, so that debugging auth problems
      // is easier.
      this._logger.debug(`C: ${str}`);
    }

    if (!this.isOnline) {
      if (!str.includes("LOGOUT")) {
        this._logger.warn(
          `Failed to send because socket state is ${this._socket?.readyState}`
        );
      }
      return;
    }

    let encode = this._utf8Enabled
      ? x => new TextEncoder().encode(x)
      : MailStringUtils.byteStringToUint8Array;
    this._socket.send(encode(str + "\r\n").buffer);
  }

  /**
   * Same as _send, but prepend a tag to the command.
   */
  _sendTagged(str, suppressLogging) {
    if (this._idling) {
      let nextAction = this._nextAction;
      this.endIdle(() => {
        this._nextAction = nextAction;
        this._sendTagged(str, suppressLogging);
      });
    } else {
      this._send(`${this._getNextTag()} ${str}`, suppressLogging);
    }
  }

  /**
   * Get the next command tag.
   *
   * @returns {number}
   */
  _getNextTag() {
    this._tag = (this._tag + 1) % 100;
    return this._tag;
  }

  /**
   * Send CAPABILITY command to the server.
   */
  _actionCapability() {
    this._nextAction = this._actionCapabilityResponse;
    this._sendTagged("CAPABILITY");
  }

  /**
   * Handle the capability response.
   *
   * @param {ImapResponse} res - Response received from the server.
   */
  _actionCapabilityResponse = res => {
    if (res.capabilities) {
      this._capabilities = res.capabilities;
      this._server.wrappedJSObject.capabilities = res.capabilities;
      if (this._capabilities.includes("X-GM-EXT-1")) {
        this._server.isGMailServer = true;
      }

      this._supportedAuthMethods = res.authMethods;
      this._actionChooseFirstAuthMethod();
    } else {
      this._actionCapability();
    }
  };

  /**
   * Decide the first auth method to try.
   */
  _actionChooseFirstAuthMethod = () => {
    if (
      [
        Ci.nsMsgSocketType.trySTARTTLS,
        Ci.nsMsgSocketType.alwaysSTARTTLS,
      ].includes(this._server.socketType) &&
      !this._secureTransport
    ) {
      if (this._capabilities.includes("STARTTLS")) {
        // Init STARTTLS negotiation if required by user pref and supported.
        this._nextAction = this._actionStarttlsResponse;
        this._sendTagged("STARTTLS");
      } else {
        // Abort if not supported.
        this._logger.error("Server doesn't support STARTTLS. Aborting.");
        this._actionError("imapServerDisconnected");
        this._actionDone(Cr.NS_ERROR_FAILURE);
      }
      return;
    }

    this._possibleAuthMethods = this._preferredAuthMethods.filter(x =>
      this._supportedAuthMethods.includes(x)
    );
    if (
      !this._possibleAuthMethods.length &&
      this._server.authMethod == Ci.nsMsgAuthMethod.passwordCleartext &&
      !this._capabilities.includes("LOGINDISABLED")
    ) {
      this._possibleAuthMethods = ["OLDLOGIN"];
    }
    this._logger.debug(`Possible auth methods: ${this._possibleAuthMethods}`);
    this._nextAuthMethod = this._possibleAuthMethods[0];
    if (this._capabilities.includes("CLIENTID") && this._server.clientid) {
      this._nextAction = res => {
        if (res.status == "OK") {
          this._actionAuth();
        } else {
          this._actionDone(Cr.NS_ERROR_FAILURE);
        }
      };
      this._sendTagged(`CLIENTID UUID ${this._server.clientid}`);
    } else {
      this._actionAuth();
    }
  };

  /**
   * Handle the STARTTLS response.
   *
   * @param {ImapResponse} res - The server response.
   */
  _actionStarttlsResponse(res) {
    if (!res.status == "OK") {
      this._actionDone(Cr.NS_ERROR_FAILURE);
      return;
    }
    this._socket.upgradeToSecure();
    this._secureTransport = true;
    this._actionCapability();
  }

  /**
   * Init authentication depending on server capabilities and user prefs.
   */
  _actionAuth = async () => {
    if (!this._nextAuthMethod) {
      this._socket.close();
      this._actionDone(Cr.NS_ERROR_FAILURE);
      return;
    }

    this._authenticating = true;

    this._currentAuthMethod = this._nextAuthMethod;
    this._nextAuthMethod =
      this._possibleAuthMethods[
        this._possibleAuthMethods.indexOf(this._currentAuthMethod) + 1
      ];

    switch (this._currentAuthMethod) {
      case "OLDLOGIN":
        this._nextAction = this._actionAuthResponse;
        let password = await this._getPassword();
        this._sendTagged(
          `LOGIN ${this._authenticator.username} ${password}`,
          true
        );
        break;
      case "PLAIN":
        this._nextAction = this._actionAuthPlain;
        this._sendTagged("AUTHENTICATE PLAIN");
        break;
      case "LOGIN":
        this._nextAction = this._actionAuthLoginUser;
        this._sendTagged("AUTHENTICATE LOGIN");
        break;
      case "CRAM-MD5":
        this._nextAction = this._actionAuthCramMd5;
        this._sendTagged("AUTHENTICATE CRAM-MD5");
        break;
      case "GSSAPI": {
        this._nextAction = this._actionAuthGssapi;
        this._authenticator.initGssapiAuth("imap");
        let token;
        try {
          token = this._authenticator.getNextGssapiToken("");
        } catch (e) {
          this._logger.error(e);
          this._actionDone(Cr.NS_ERROR_FAILURE);
          return;
        }
        this._sendTagged(`AUTHENTICATE GSSAPI ${token}`, true);
        break;
      }
      case "NTLM": {
        this._nextAction = this._actionAuthNtlm;
        this._authenticator.initNtlmAuth("imap");
        let token;
        try {
          token = this._authenticator.getNextNtlmToken("");
        } catch (e) {
          this._logger.error(e);
          this._actionDone(Cr.NS_ERROR_FAILURE);
          return;
        }
        this._sendTagged(`AUTHENTICATE NTLM ${token}`, true);
        break;
      }
      case "XOAUTH2":
        this._nextAction = this._actionAuthResponse;
        let token = await this._authenticator.getOAuthToken();
        this._sendTagged(`AUTHENTICATE XOAUTH2 ${token}`, true);
        break;
      case "EXTERNAL":
        this._nextAction = this._actionAuthResponse;
        this._sendTagged(
          `AUTHENTICATE EXTERNAL ${this._authenticator.username}`
        );
        break;
      default:
        this._actionDone();
    }
  };

  /**
   * @param {ImapResponse} res - Response received from the server.
   */
  _actionAuthResponse = res => {
    this._authenticating = false;

    if (this.verifyLogon) {
      this._actionDone(res.status == "OK" ? Cr.NS_OK : Cr.NS_ERROR_FAILURE);
      return;
    }
    if (res.status == "OK") {
      this._serverSink.userAuthenticated = true;
      if (res.capabilities) {
        this._capabilities = res.capabilities;
        this._server.wrappedJSObject.capabilities = res.capabilities;
        this._actionId();
      } else {
        this._nextAction = res => {
          this._capabilities = res.capabilities;
          this._server.wrappedJSObject.capabilities = res.capabilities;
          this._actionId();
        };
        this._sendTagged("CAPABILITY");
      }
      return;
    }
    if (
      ["OLDLOGIN", "PLAIN", "LOGIN", "CRAM-MD5"].includes(
        this._currentAuthMethod
      )
    ) {
      // Ask user what to do.
      let action = this._authenticator.promptAuthFailed();
      if (action == 1) {
        // Cancel button pressed.
        this._socket.close();
        this._actionDone(Cr.NS_ERROR_FAILURE);
        return;
      }
      if (action == 2) {
        // 'New password' button pressed.
        this._authenticator.forgetPassword();
      }

      // Retry.
      this._nextAuthMethod = this._possibleAuthMethods[0];
      this._actionAuth();
      return;
    }
    this._logger.error("Authentication failed.");
    this._actionDone(Cr.NS_ERROR_FAILURE);
  };

  /**
   * Returns the saved/cached server password, or show a password dialog. If the
   * user cancels the dialog, stop the process.
   *
   * @returns {string} The server password.
   */
  async _getPassword() {
    try {
      let password = await this._authenticator.getPassword();
      return password;
    } catch (e) {
      if (e.result == Cr.NS_ERROR_ABORT) {
        this._actionDone(e.result);
      }
      throw e;
    }
  }

  /**
   * The second step of PLAIN auth. Send the auth token to the server.
   *
   * @param {ImapResponse} res - Response received from the server.
   */
  _actionAuthPlain = async res => {
    this._nextAction = this._actionAuthResponse;
    this._send(await this._authenticator.getPlainToken(), true);
  };

  /**
   * The second step of LOGIN auth. Send the username to the server.
   *
   * @param {ImapResponse} res - The server response.
   */
  _actionAuthLoginUser = res => {
    this._nextAction = this._actionAuthLoginPass;
    this._send(btoa(this._authenticator.username), true);
  };

  /**
   * The third step of LOGIN auth. Send the password to the server.
   *
   * @param {ImapResponse} res - The server response.
   */
  _actionAuthLoginPass = async res => {
    this._nextAction = this._actionAuthResponse;
    let password = MailStringUtils.stringToByteString(
      await this._getPassword()
    );
    this._send(btoa(password), true);
  };

  /**
   * The second step of CRAM-MD5 auth, send a HMAC-MD5 signature to the server.
   *
   * @param {ImapResponse} res - The server response.
   */
  _actionAuthCramMd5 = async res => {
    this._nextAction = this._actionAuthResponse;
    let password = await this._getPassword();
    this._send(
      this._authenticator.getCramMd5Token(password, res.statusText),
      true
    );
  };

  /**
   * The second and next step of GSSAPI auth.
   *
   * @param {ImapResponse} res - The server response.
   */
  _actionAuthGssapi = res => {
    if (res.tag != "+") {
      this._actionAuthResponse(res);
      return;
    }

    // Server returns a challenge, we send a new token. Can happen multiple times.
    let token;
    try {
      token = this._authenticator.getNextGssapiToken(res.statusText);
    } catch (e) {
      this._logger.error(e);
      this._actionAuthResponse(res);
      return;
    }
    this._send(token, true);
  };

  /**
   * The second and next step of NTLM auth.
   *
   * @param {ImapResponse} res - The server response.
   */
  _actionAuthNtlm = res => {
    if (res.tag != "+") {
      this._actionAuthResponse(res);
      return;
    }

    // Server returns a challenge, we send a new token. Can happen multiple times.
    let token;
    try {
      token = this._authenticator.getNextNtlmToken(res.statusText);
    } catch (e) {
      this._logger.error(e);
      this._actionAuthResponse(res);
      return;
    }
    this._send(token, true);
  };

  /**
   * Send ID command to the server.
   *
   * @param {Function} [actionAfter] - A callback after processing ID command.
   */
  _actionId = (actionAfter = this._actionEnableUtf8) => {
    if (this._capabilities.includes("ID") && Services.appinfo.name) {
      this._nextAction = res => {
        this._server.serverIDPref = res.id;
        actionAfter();
      };
      this._sendTagged(
        `ID ("name" "${Services.appinfo.name}" "version" "${Services.appinfo.version}")`
      );
    } else {
      actionAfter();
    }
  };

  /**
   * Enable UTF8 if supported by the server.
   *
   * @param {Function} [actionAfter] - A callback after processing ENABLE UTF8.
   */
  _actionEnableUtf8 = (actionAfter = this._discoverAllFoldersIfNecessary) => {
    if (
      this._server.allowUTF8Accept &&
      (this._capabilities.includes("UTF8=ACCEPT") ||
        this._capabilities.includes("UTF8=ONLY"))
    ) {
      this._nextAction = res => {
        this._utf8Enabled = res.status == "OK";
        this._server.utf8AcceptEnabled = this._utf8Enabled;
        actionAfter();
      };
      this._sendTagged("ENABLE UTF8=ACCEPT");
    } else {
      this._utf8Enabled = false;
      actionAfter();
    }
  };

  /**
   * Execute an action with a folder selected.
   *
   * @param {nsIMsgFolder} folder - The folder to select.
   * @param {Function} actionInFolder - The action to execute.
   */
  _actionInFolder(folder, actionInFolder) {
    if (this.folder == folder) {
      // If already in the folder, execute the action now.
      actionInFolder();
    } else {
      // Send the SELECT command and queue the action.
      this._actionAfterSelectFolder = actionInFolder;
      this._nextAction = this._actionSelectResponse(folder);
      this._sendTagged(`SELECT "${this._getServerFolderName(folder)}"`);
    }
  }

  /**
   * Send LSUB or LIST command depending on the server capabilities.
   *
   * @param {string} [mailbox="*"] - The mailbox to list, default to list all.
   */
  _actionListOrLsub(mailbox = "*") {
    this._nextAction = this._actionListResponse();
    let command = this._capabilities.includes("LIST-EXTENDED")
      ? "LIST (SUBSCRIBED)" // rfc5258
      : "LSUB";
    command += ` "" "${mailbox}"`;
    if (this._capabilities.includes("SPECIAL-USE")) {
      command += " RETURN (SPECIAL-USE)"; // rfc6154
    }
    this._sendTagged(command);
    this._listInboxSent = false;
  }

  /**
   * Handle LIST response.
   *
   * @param {Function} actionAfterResponse - A callback after handling the response.
   * @param {ImapResponse} res - Response received from the server.
   */
  _actionListResponse =
    (actionAfterResponse = this._actionFinishFolderDiscovery) =>
    res => {
      if (!this._hasInbox) {
        this._hasInbox = res.mailboxes.some(
          mailbox => mailbox.flags & ImapUtils.FLAG_IMAP_INBOX
        );
      }
      for (let mailbox of res.mailboxes) {
        this._serverSink.possibleImapMailbox(
          mailbox.name.replaceAll(mailbox.delimiter, "/"),
          mailbox.delimiter,
          mailbox.flags
        );
      }

      actionAfterResponse(res);
    };

  /**
   * Send LIST command.
   *
   * @param {string} folderName - The name of the folder to list.
   * @param {Function} actionAfterResponse - A callback after handling the response.
   */
  _actionList(folderName, actionAfterResponse) {
    this._nextAction = this._actionListResponse(actionAfterResponse);
    this._sendTagged(`LIST "" "${folderName}"`);
  }

  /**
   * Finish folder discovery after checking Inbox and Trash folders.
   */
  _actionFinishFolderDiscovery = () => {
    if (!this._hasInbox && !this._listInboxSent) {
      this._actionList("INBOX");
      this._listInboxSent = true;
      return;
    }
    if (!this._hasTrash && !this._listTrashSent) {
      this._actionCreateTrashFolderIfNeeded();
      return;
    }
    this._serverSink.discoveryDone();
    this._actionAfterDiscoverAllFolders
      ? this._actionAfterDiscoverAllFolders()
      : this._actionDone();
  };

  /**
   * If Trash folder is not found on server, create one and subscribe to it.
   */
  _actionCreateTrashFolderIfNeeded() {
    let trashFolderName = this._server.trashFolderName;
    this._actionList(trashFolderName, res => {
      this._hasTrash = res.mailboxes.length > 0;
      if (this._hasTrash) {
        // Trash folder exists.
        this._actionFinishFolderDiscovery();
      } else {
        // Trash folder doesn't exist, create one and subscribe to it.
        this._nextAction = res => {
          this._actionList(trashFolderName, () => {
            // After subscribing, finish folder discovery.
            this._nextAction = this._actionFinishFolderDiscovery;
            this._sendTagged(`SUBSCRIBE "${trashFolderName}"`);
          });
        };
        this._sendTagged(`CREATE "${trashFolderName}"`);
      }
    });
    this._listTrashSent = true;
  }

  /**
   * Create and subscribe to a folder.
   *
   * @param {string} folderName - The folder name.
   * @param {Function} callbackAfterSubscribe - The action after the subscribe
   *   command.
   */
  _actionCreateAndSubscribe(folderName, callbackAfterSubscribe) {
    this._nextAction = res => {
      this._nextAction = callbackAfterSubscribe;
      this._sendTagged(`SUBSCRIBE "${folderName}"`);
    };
    this._sendTagged(`CREATE "${folderName}"`);
  }

  /**
   * Handle SELECT response.
   */
  _actionSelectResponse = folder => res => {
    if (folder) {
      this.folder = folder;
    }
    this._supportedFlags = res.permanentflags || res.flags;
    this._folderState = res;
    if (this._capabilities.includes("QUOTA")) {
      this._actionGetQuotaData();
    } else {
      this._actionAfterSelectFolder();
    }
  };

  /**
   * Send GETQUOTAROOT command and handle the response.
   */
  _actionGetQuotaData() {
    this._folderSink = this.folder.QueryInterface(Ci.nsIImapMailFolderSink);
    this._nextAction = res => {
      const INVALIDATE_QUOTA = 0;
      const STORE_QUOTA = 1;
      const VALIDATE_QUOTA = 2;
      for (let root of res.quotaRoots || []) {
        this._folderSink.setFolderQuotaData(INVALIDATE_QUOTA, root, 0, 0);
      }
      for (let [mailbox, resource, usage, limit] of res.quotas || []) {
        this._folderSink.setFolderQuotaData(
          STORE_QUOTA,
          mailbox ? `${mailbox} / ${resource}` : resource,
          usage,
          limit
        );
      }
      this._folderSink.setFolderQuotaData(VALIDATE_QUOTA, "", 0, 0);
      this._actionAfterSelectFolder();
    };
    this._sendTagged(
      `GETQUOTAROOT "${this._getServerFolderName(this.folder)}"`
    );
    this._folderSink.folderQuotaCommandIssued = true;
  }

  /**
   * Handle RENAME response. Three steps are involved.
   *
   * @param {string} oldName - The old folder name.
   * @param {string} newName - The new folder name.
   * @param {boolean} [isMove] - Is it response to MOVE command.
   * @param {ImapResponse} res - The server response.
   */
  _actionRenameResponse = (oldName, newName, isMove) => res => {
    // Step 3: Rename the local folder and send LIST command to re-sync folders.
    let actionAfterUnsubscribe = () => {
      this._serverSink.onlineFolderRename(this._msgWindow, oldName, newName);
      if (isMove) {
        this._actionDone();
      } else {
        this._actionListOrLsub(newName);
      }
    };
    // Step 2: unsubscribe to the oldName.
    this._nextAction = () => {
      this._nextAction = actionAfterUnsubscribe;
      this._sendTagged(`UNSUBSCRIBE "${oldName}"`);
    };
    // Step 1: subscribe to the newName.
    this._sendTagged(`SUBSCRIBE "${newName}"`);
  };

  /**
   * Send UID FETCH request to the server.
   */
  _actionUidFetch() {
    if (this.runningUri.imapAction == Ci.nsIImapUrl.nsImapLiteSelectFolder) {
      this._nextAction = () => this._actionDone();
    } else {
      this._nextAction = this._actionUidFetchResponse;
    }
    this._sendTagged("UID FETCH 1:* (FLAGS)");
  }

  /**
   * Handle UID FETCH response.
   *
   * @param {ImapResponse} res - Response received from the server.
   */
  _actionUidFetchResponse(res) {
    let outFolderInfo = {};
    this.folder.getDBFolderInfoAndDB(outFolderInfo);
    let highestUid = outFolderInfo.value.getUint32Property(
      "highestRecordedUID",
      0
    );
    this._folderSink = this.folder.QueryInterface(Ci.nsIImapMailFolderSink);
    this._folderSink.UpdateImapMailboxInfo(this, this._getMailboxSpec());
    let latestUid = this._messageUids.at(-1);
    if (latestUid > highestUid) {
      let extraItems = "";
      if (this._server.isGMailServer) {
        extraItems += "X-GM-MSGID X-GM-THRID X-GM-LABELS ";
      }
      this._nextAction = this._actionUidFetchHeaderResponse;
      this._sendTagged(
        `UID FETCH ${
          highestUid + 1
        }:${latestUid} (UID ${extraItems}RFC822.SIZE FLAGS BODY.PEEK[HEADER])`
      );
    } else {
      this._folderSink.headerFetchCompleted(this);
      if (this._bodysToDownload.length) {
        let uids = this._bodysToDownload.join(",");
        this._nextAction = this._actionUidFetchBodyResponse;
        this._sendTagged(
          `UID FETCH ${uids} (UID RFC822.SIZE FLAGS BODY.PEEK[])`
        );
        return;
      }
      this._actionDone();
    }
  }

  /**
   * Make an nsIMailboxSpec instance to interact with nsIImapMailFolderSink.
   *
   * @returns {nsIMailboxSpec}
   */
  _getMailboxSpec() {
    return {
      QueryInterface: ChromeUtils.generateQI(["nsIMailboxSpec"]),
      folder_UIDVALIDITY: this._folderState.uidvalidity,
      box_flags: this._folderState.flags,
      supportedUserFlags: this._folderState.supportedUserFlags,
      nextUID: this._folderState.attributes.uidnext,
      numMessages: this._messages.size,
      numUnseenMessages: this._folderState.attributes.unseen,
      flagState: this.flagAndUidState,
    };
  }

  /**
   * Handle UID FETCH BODY.PEEK[HEADER] response.
   *
   * @param {ImapResponse} res - Response received from the server.
   */
  _actionUidFetchHeaderResponse(res) {
    this.folder
      .QueryInterface(Ci.nsIImapMailFolderSink)
      .headerFetchCompleted(this);
    if (this._bodysToDownload.length) {
      // nsImapMailFolder decides to fetch the full body by calling
      // NotifyBodysToDownload.
      let uids = this._bodysToDownload.join(",");
      this._nextAction = this._actionUidFetchBodyResponse;
      this._sendTagged(`UID FETCH ${uids} (UID RFC822.SIZE FLAGS BODY.PEEK[])`);
      return;
    }
    this._actionDone();
  }

  /**
   * Handle UID FETCH BODY response.
   *
   * @param {ImapResponse} res - Response received from the server.
   */
  _actionUidFetchBodyResponse(res) {
    this._actionDone();
  }

  /**
   * Handle a single message data response.
   *
   * @param {MessageData} msg - Message data parsed in ImapResponse.
   */
  _onMessage = msg => {
    this._msgSink = this.folder.QueryInterface(Ci.nsIImapMessageSink);
    this._folderSink = this.folder.QueryInterface(Ci.nsIImapMailFolderSink);

    // Handle message flags.
    if ((msg.uid || msg.sequence) && msg.flags != undefined) {
      let uid = msg.uid;
      if (uid && msg.sequence) {
        this._messageUids[msg.sequence] = uid;
        this._messages.set(uid, msg);
      } else if (msg.sequence) {
        uid = this._messageUids[msg.sequence];
      }
      if (uid) {
        this.folder
          .QueryInterface(Ci.nsIImapMessageSink)
          .notifyMessageFlags(
            msg.flags,
            msg.keywords,
            uid,
            this._folderState.highestmodseq
          );
      }
    }

    if (msg.body) {
      if (!msg.body.endsWith("\r\n")) {
        msg.body += "\r\n";
      }
      if (msg.bodySection.length == 1 && msg.bodySection[0] == "HEADER") {
        // Handle message headers.
        this._messageUids[msg.sequence] = msg.uid;
        this._messages.set(msg.uid, msg);
        this._folderSink.StartMessage(this.runningUri);
        let hdrXferInfo = {
          numHeaders: 1,
          getHeader() {
            return {
              msgUid: msg.uid,
              msgSize: msg.size,
              get msgHdrs() {
                let sepIndex = msg.body.indexOf("\r\n\r\n");
                return sepIndex == -1
                  ? msg.body + "\r\n"
                  : msg.body.slice(0, sepIndex + 2);
              },
            };
          },
        };
        this._folderSink.parseMsgHdrs(this, hdrXferInfo);
      } else {
        // Handle message body.
        let shouldStoreMsgOffline = false;
        try {
          shouldStoreMsgOffline = this.folder.shouldStoreMsgOffline(msg.uid);
        } catch (e) {}
        if (
          (shouldStoreMsgOffline ||
            this.runningUri.QueryInterface(Ci.nsIImapUrl)
              .storeResultsOffline) &&
          msg.body
        ) {
          this._folderSink.StartMessage(this.runningUri);
          this._msgSink.parseAdoptedMsgLine(msg.body, msg.uid, this.runningUri);
          this._msgSink.normalEndMsgWriteStream(
            msg.uid,
            true,
            this.runningUri,
            msg.body.length
          );
          this._folderSink.EndMessage(this.runningUri, msg.uid);
        }

        this.onData?.(msg.body);
        // Release some memory.
        msg.body = "";
      }
    }
  };

  /**
   * Send NOOP command.
   */
  _actionNoop() {
    this._nextAction = this._actionNoopResponse;
    this._sendTagged("NOOP");
  }

  /**
   * Handle NOOP response.
   *
   * @param {ImapResponse} res - Response received from the server.
   */
  _actionNoopResponse(res) {
    if (
      (res.exists && res.exists != this._folderState.exists) ||
      res.expunged.length
    ) {
      // Handle messages number changes, re-sync the folder.
      this._folderState.exists = res.exists;
      this._actionAfterSelectFolder = this._actionUidFetch;
      this._nextAction = this._actionSelectResponse();
      if (res.expunged.length) {
        this._messageUids = [];
        this._messages.clear();
      }
      let folder = this.folder;
      this.folder = null;
      this.selectFolder(folder);
    } else if (res.messages.length || res.exists) {
      let outFolderInfo = {};
      this.folder.getDBFolderInfoAndDB(outFolderInfo);
      let highestUid = outFolderInfo.value.getUint32Property(
        "highestRecordedUID",
        0
      );
      this._nextAction = this._actionUidFetchResponse;
      this._sendTagged(`UID FETCH ${highestUid + 1}:* (FLAGS)`);
    } else {
      if (res.exists == 0) {
        this._messageUids = [];
        this._messages.clear();
        this.folder
          .QueryInterface(Ci.nsIImapMailFolderSink)
          .UpdateImapMailboxInfo(this, this._getMailboxSpec());
      }
      if (!this._idling) {
        this._actionDone();
      }
    }
  }

  /**
   * Show an error prompt.
   *
   * @param {string} errorName - An error name corresponds to an entry of
   *   imapMsgs.properties.
   */
  _actionError(errorName) {
    if (!this._msgWindow) {
      return;
    }
    let bundle = Services.strings.createBundle(
      "chrome://messenger/locale/imapMsgs.properties"
    );
    let errorMsg = bundle.formatStringFromName(errorName, [
      this._server.hostName,
    ]);
    Services.prompt.alert(this._msgWindow.domWindow, null, errorMsg);
  }

  /**
   * Finish a request and do necessary cleanup.
   */
  _actionDone = (status = Cr.NS_OK) => {
    this._logger.debug(`Done with status=${status}`);
    this._nextAction = null;
    this._urlListener?.OnStopRunningUrl(this.runningUri, status);
    this.runningUri.SetUrlState(false, status);
    this.onDone?.(status);
    this._reset();
    // Tell ImapIncomingServer this client can be reused now.
    this.onFree?.();
  };

  /** @see nsIImapProtocol */
  NotifyBodysToDownload(keys) {
    this._logger.debug("NotifyBodysToDownload", keys);
    this._bodysToDownload = keys;
  }

  GetRunningUrl() {
    this._logger.debug("GetRunningUrl");
  }

  get flagAndUidState() {
    // The server sequence is 1 based, nsIImapFlagAndUidState sequence is 0 based.
    let getUidOfMessage = index => this._messageUids[index + 1];
    let getMessageFlagsByUid = uid => this._messages.get(uid)?.flags;

    return {
      QueryInterface: ChromeUtils.generateQI(["nsIImapFlagAndUidState"]),
      numberOfMessages: this._messages.size,
      getUidOfMessage,
      getMessageFlags: index => getMessageFlagsByUid(getUidOfMessage(index)),
      hasMessage: uid => this._messages.has(uid),
      getMessageFlagsByUid,
      getCustomFlags: uid => this._messages.get(uid)?.keywords,
      getCustomAttribute: (uid, name) => {
        let value = this._messages.get(uid)?.customAttributes[name];
        return Array.isArray(value) ? value.join(" ") : value;
      },
    };
  }
}