-
-
Notifications
You must be signed in to change notification settings - Fork 65
/
imap-flow.js
3008 lines (2619 loc) · 113 KB
/
imap-flow.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
/**
* @module imapflow
*/
// TODO:
// * Use buffers for compiled commands
// * OAuth2 authentication
const tls = require('tls');
const net = require('net');
const crypto = require('crypto');
const { EventEmitter } = require('events');
const logger = require('./logger');
const libmime = require('libmime');
const zlib = require('zlib');
const { Headers } = require('mailsplit');
const { LimitedPassthrough } = require('./limited-passthrough');
const { ImapStream } = require('./handler/imap-stream');
const { parser, compiler } = require('./handler/imap-handler');
const packageInfo = require('../package.json');
const libqp = require('libqp');
const libbase64 = require('libbase64');
const FlowedDecoder = require('mailsplit/lib/flowed-decoder');
const { PassThrough } = require('stream');
const { proxyConnection } = require('./proxy-connection');
const { comparePaths, updateCapabilities, getFolderTree, formatMessageResponse, getDecoder, packMessageRange, normalizePath, expandRange } = require('./tools');
const imapCommands = require('./imap-commands.js');
const CONNECT_TIMEOUT = 90 * 1000;
const GREETING_TIMEOUT = 16 * 1000;
const UPGRADE_TIMEOUT = 10 * 1000;
const SOCKET_TIMEOUT = 5 * 60 * 1000;
const states = {
NOT_AUTHENTICATED: 0x01,
AUTHENTICATED: 0x02,
SELECTED: 0x03,
LOGOUT: 0x04
};
/**
* @typedef {Object} MailboxObject
* @global
* @property {String} path mailbox path
* @property {String} delimiter mailbox path delimiter, usually "." or "/"
* @property {Set<string>} flags list of flags for this mailbox
* @property {String} [specialUse] one of special-use flags (if applicable): "\All", "\Archive", "\Drafts", "\Flagged", "\Junk", "\Sent", "\Trash". Additionally INBOX has non-standard "\Inbox" flag set
* @property {Boolean} listed `true` if mailbox was found from the output of LIST command
* @property {Boolean} subscribed `true` if mailbox was found from the output of LSUB command
* @property {Set<string>} permanentFlags A Set of flags available to use in this mailbox. If it is not set or includes special flag "\\\*" then any flag can be used.
* @property {String} [mailboxId] unique mailbox ID if server has `OBJECTID` extension enabled
* @property {BigInt} [highestModseq] latest known modseq value if server has CONDSTORE or XYMHIGHESTMODSEQ enabled
* @property {String} [noModseq] if true then the server doesn't support the persistent storage of mod-sequences for the mailbox
* @property {BigInt} uidValidity Mailbox `UIDVALIDITY` value
* @property {Number} uidNext Next predicted UID
* @property {Number} exists Messages in this folder
*/
/**
* @typedef {Object} MailboxLockObject
* @global
* @property {String} path mailbox path
* @property {Function} release Release current lock
* @example
* let lock = await client.getMailboxLock('INBOX');
* try {
* // do something in the mailbox
* } finally {
* // use finally{} to make sure lock is released even if exception occurs
* lock.release();
* }
*/
/**
* Client and server identification object, where key is one of RFC2971 defined [data fields](https://tools.ietf.org/html/rfc2971#section-3.3) (but not limited to).
* @typedef {Object} IdInfoObject
* @global
* @property {String} [name] Name of the program
* @property {String} [version] Version number of the program
* @property {String} [os] Name of the operating system
* @property {String} [vendor] Vendor of the client/server
* @property {String} ['support-url'] URL to contact for support
* @property {Date} [date] Date program was released
*/
/**
* IMAP client class for accessing IMAP mailboxes
*
* @class
* @extends EventEmitter
*/
class ImapFlow extends EventEmitter {
/**
* Current module version as a static class property
* @property {String} version Module version
* @static
*/
static version = packageInfo.version;
/**
* @param {Object} options IMAP connection options
* @param {String} options.host Hostname of the IMAP server
* @param {Number} options.port Port number for the IMAP server
* @param {Boolean} [options.secure=false] Should the connection be established over TLS.
* If `false` then connection is upgraded to TLS using STARTTLS extension before authentication
* @param {String} [options.servername] Servername for SNI (or when host is set to an IP address)
* @param {Boolean} [options.disableCompression=false] if `true` then client does not try to use COMPRESS=DEFLATE extension
* @param {Object} options.auth Authentication options. Authentication is requested automatically during <code>connect()</code>
* @param {String} options.auth.user Usename
* @param {String} [options.auth.pass] Password, if using regular authentication
* @param {String} [options.auth.accessToken] OAuth2 Access Token, if using OAuth2 authentication
* @param {IdInfoObject} [options.clientInfo] Client identification info
* @param {Boolean} [options.disableAutoIdle=false] if `true` then IDLE is not started automatically. Useful if you only need to perform specific tasks over the connection
* @param {Object} [options.tls] Additional TLS options (see [Node.js TLS connect](https://nodejs.org/api/tls.html#tls_tls_connect_options_callback) for all available options)
* @param {Boolean} [options.tls.rejectUnauthorized=true] if `false` then client accepts self-signed and expired certificates from the server
* @param {String} [options.tls.minVersion=TLSv1.2] To improvde security you might need to use something newer, eg *'TLSv1.2'*
* @param {Number} [options.tls.minDHSize=1024] Minimum size of the DH parameter in bits to accept a TLS connection
* @param {Object} [options.logger] Custom logger instance with `debug(obj)`, `info(obj)`, `warn(obj)` and `error(obj)` methods. If not provided then ImapFlow logs to console using pino format. Can be disabled by setting to `false`
* @param {Boolean} [options.logRaw=false] If true then log data read from and written to socket encoded in base64
* @param {Boolean} [options.emitLogs=false] If `true` then in addition of sending data to logger, ImapFlow emits 'log' events with the same data
* @param {Boolean} [options.verifyOnly=false] If `true` then logs out automatically after successful authentication
* @param {String} [options.proxy] Optional proxy URL. Supports HTTP CONNECT (`http://`, `https://`) and SOCKS (`socks://`, `socks4://`, `socks5://`) proxies
* @param {Boolean} [options.qresync=false] If true, then enables QRESYNC support. EXPUNGE notifications will include `uid` property instead of `seq`
* @param {Number} [options.maxIdleTime] If set, then breaks and restarts IDLE every maxIdleTime ms
* @param {String} [options.missingIdleCommand="NOOP"] Which command to use if server does not support IDLE
* @param {Boolean} [options.disableBinary=false] If true, then ignores the BINARY extension when making FETCH and APPEND calls
* @param {Boolean} [options.disableAutoEnable] Do not enable supported extensions by default
* @param {Number} [options.connectionTimeout=90000] how many milliseconds to wait for the connection to establish (default is 90 seconds)
* @param {Number} [options.greetingTimeout=16000] how many milliseconds to wait for the greeting after connection is established (default is 16 seconds)
* @param {Number} [options.socketTimeout=300000] how many milliseconds of inactivity to allow (default is 5 minutes)
*/
constructor(options) {
super({ captureRejections: true });
this.options = options || {};
/**
* Instance ID for logs
* @type {String}
*/
this.id = this.options.id || this.getRandomId();
this.clientInfo = Object.assign(
{
name: packageInfo.name,
version: packageInfo.version,
vendor: 'Postal Systems',
'support-url': 'https://github.com/postalsys/imapflow/issues'
},
this.options.clientInfo || {}
);
/**
* Server identification info. Available after successful `connect()`.
* If server does not provide identification info then this value is `null`.
* @example
* await client.connect();
* console.log(client.serverInfo.vendor);
* @type {IdInfoObject|null}
*/
this.serverInfo = null; //updated by ID
this.log = this.getLogger();
/**
* Is the connection currently encrypted or not
* @type {Boolean}
*/
this.secureConnection = !!this.options.secure;
this.port = Number(this.options.port) || (this.secureConnection ? 993 : 110);
this.host = this.options.host || 'localhost';
this.servername = this.options.servername ? this.options.servername : !net.isIP(this.host) ? this.host : false;
if (typeof this.options.secure === 'undefined' && this.port === 993) {
// if secure option is not set but port is 465, then default to secure
this.secureConnection = true;
}
this.logRaw = this.options.logRaw;
this.streamer = new ImapStream({
logger: this.log,
cid: this.id,
logRaw: this.logRaw,
secureConnection: this.secureConnection
});
this.reading = false;
this.socket = false;
this.writeSocket = false;
this.states = states;
this.state = this.states.NOT_AUTHENTICATED;
this.lockCounter = 0;
this.currentLockId = 0;
this.tagCounter = 0;
this.requestTagMap = new Map();
this.requestQueue = [];
this.currentRequest = false;
this.writeBytesCounter = 0;
this.commandParts = [];
/**
* Active IMAP capabilities. Value is either `true` for togglabe capabilities (eg. `UIDPLUS`)
* or a number for capabilities with a value (eg. `APPENDLIMIT`)
* @type {Map<string, boolean|number>}
*/
this.capabilities = new Map();
this.authCapabilities = new Map();
this.rawCapabilities = null;
this.expectCapabilityUpdate = false; // force CAPABILITY after LOGIN
/**
* Enabled capabilities. Usually `CONDSTORE` and `UTF8=ACCEPT` if server supports these.
* @type {Set<string>}
*/
this.enabled = new Set();
/**
* Is the connection currently usable or not
* @type {Boolean}
*/
this.usable = false;
/**
* Currently authenticated user or `false` if mailbox is not open
* or `true` if connection was authenticated by PREAUTH
* @type {String|Boolean}
*/
this.authenticated = false;
/**
* Currently selected mailbox or `false` if mailbox is not open
* @type {MailboxObject|Boolean}
*/
this.mailbox = false;
this.currentSelectCommand = false;
/**
* Is current mailbox idling (`true`) or not (`false`)
* @type {Boolean}
*/
this.idling = false;
/**
* If `true` then in addition of sending data to logger, ImapFlow emits 'log' events with the same data
* @type {Boolean}
*/
this.emitLogs = !!this.options.emitLogs;
// ordering number for emitted logs
this.lo = 0;
this.untaggedHandlers = {};
this.sectionHandlers = {};
this.commands = imapCommands;
this.folders = new Map();
this.currentLock = false;
this.locks = [];
this.idRequested = false;
this.maxIdleTime = this.options.maxIdleTime || false;
this.missingIdleCommand = (this.options.missingIdleCommand || '').toString().toUpperCase().trim() || 'NOOP';
this.disableBinary = !!this.options.disableBinary;
this.streamer.on('error', err => {
if (['Z_BUF_ERROR', 'ECONNRESET', 'EPIPE', 'ETIMEDOUT', 'EHOSTUNREACH'].includes(err.code)) {
// just close the connection, usually nothing but noise
return setImmediate(() => this.close());
}
this.log.error({ err, cid: this.id });
setImmediate(() => this.close());
this.emitError(err);
});
}
emitError(err) {
this.emit('error', err);
}
getRandomId() {
let rid = BigInt('0x' + crypto.randomBytes(13).toString('hex')).toString(36);
if (rid.length < 20) {
rid = '0'.repeat(20 - rid.length) + rid;
} else if (rid.length > 20) {
rid = rid.substr(0, 20);
}
return rid;
}
write(chunk) {
if (this.socket.destroyed || this.state === this.states.LOGOUT) {
// do not write after connection end or logout
return;
}
if (this.writeSocket.destroyed) {
this.socket.emit('error', 'Write socket destroyed');
return;
}
let addLineBreak = !this.commandParts.length;
if (typeof chunk === 'string') {
if (addLineBreak) {
chunk += '\r\n';
}
chunk = Buffer.from(chunk, 'binary');
} else if (Buffer.isBuffer(chunk)) {
if (addLineBreak) {
chunk = Buffer.concat([chunk, Buffer.from('\r\n')]);
}
} else {
return false;
}
if (this.logRaw) {
this.log.trace({
src: 'c',
msg: 'write to socket',
data: chunk.toString('base64'),
compress: !!this._deflate,
secure: !!this.secureConnection,
cid: this.id
});
}
this.writeBytesCounter += chunk.length;
this.writeSocket.write(chunk);
}
stats(reset) {
let result = {
sent: this.writeBytesCounter || 0,
received: (this.streamer && this.streamer.readBytesCounter) || 0
};
if (reset) {
this.writeBytesCounter = 0;
if (this.streamer) {
this.streamer.readBytesCounter = 0;
}
}
return result;
}
async send(data) {
if (this.state === this.states.LOGOUT) {
// already logged out
if (data.tag) {
let request = this.requestTagMap.get(data.tag);
if (request) {
this.requestTagMap.delete(request.tag);
request.reject(new Error('Connection not available'));
}
}
return;
}
let compiled = await compiler(data, {
asArray: true,
literalMinus: this.capabilities.has('LITERAL-') || this.capabilities.has('LITERAL+')
});
this.commandParts = compiled;
let logCompiled = await compiler(data, {
isLogging: true
});
let options = data.options || {};
this.log.debug({ src: 's', msg: logCompiled.toString(), cid: this.id, comment: options.comment });
this.write(this.commandParts.shift());
if (typeof options.onSend === 'function') {
options.onSend();
}
}
async trySend() {
if (this.currentRequest || !this.requestQueue.length) {
return;
}
this.currentRequest = this.requestQueue.shift();
await this.send({
tag: this.currentRequest.tag,
command: this.currentRequest.command,
attributes: this.currentRequest.attributes,
options: this.currentRequest.options
});
}
async exec(command, attributes, options) {
if (this.socket.destroyed) {
let error = new Error('Connection closed');
error.code = 'EConnectionClosed';
throw error;
}
let tag = (++this.tagCounter).toString(16).toUpperCase();
options = options || {};
return new Promise((resolve, reject) => {
this.requestTagMap.set(tag, { command, attributes, options, resolve, reject });
this.requestQueue.push({ tag, command, attributes, options });
this.trySend().catch(err => {
this.requestTagMap.delete(tag);
reject(err);
});
});
}
getUntaggedHandler(command, attributes) {
if (/^[0-9]+$/.test(command)) {
let type = attributes && attributes.length && typeof attributes[0].value === 'string' ? attributes[0].value.toUpperCase() : false;
if (type) {
// EXISTS, EXPUNGE, RECENT, FETCH etc
command = type;
}
}
command = command.toUpperCase().trim();
if (this.currentRequest && this.currentRequest.options && this.currentRequest.options.untagged && this.currentRequest.options.untagged[command]) {
return this.currentRequest.options.untagged[command];
}
if (this.untaggedHandlers[command]) {
return this.untaggedHandlers[command];
}
}
getSectionHandler(key) {
if (this.sectionHandlers[key]) {
return this.sectionHandlers[key];
}
}
async reader() {
let data;
while ((data = this.streamer.read()) !== null) {
let parsed;
try {
parsed = await parser(data.payload, { literals: data.literals });
if (parsed.tag && !['*', '+'].includes(parsed.tag) && parsed.command) {
let payload = { response: parsed.command };
if (
parsed.attributes &&
parsed.attributes[0] &&
parsed.attributes[0].section &&
parsed.attributes[0].section[0] &&
parsed.attributes[0].section[0].type === 'ATOM'
) {
payload.code = parsed.attributes[0].section[0].value;
}
this.emit('response', payload);
}
} catch (err) {
// can not make sense of this
this.log.error({ src: 's', msg: data.payload.toString(), err, cid: this.id });
data.next();
continue;
}
let logCompiled = await compiler(parsed, {
isLogging: true
});
if (/^\d+$/.test(parsed.command) && parsed.attributes && parsed.attributes[0] && parsed.attributes[0].value === 'FETCH') {
// too many FETCH responses, might want to filter these out
this.log.trace({ src: 's', msg: logCompiled.toString(), cid: this.id, nullBytesRemoved: parsed.nullBytesRemoved });
} else {
this.log.debug({ src: 's', msg: logCompiled.toString(), cid: this.id, nullBytesRemoved: parsed.nullBytesRemoved });
}
if (parsed.tag === '+' && this.currentRequest && this.currentRequest.options && typeof this.currentRequest.options.onPlusTag === 'function') {
await this.currentRequest.options.onPlusTag(parsed);
data.next();
continue;
}
if (parsed.tag === '+' && this.commandParts.length) {
let content = this.commandParts.shift();
this.write(content);
this.log.debug({ src: 'c', msg: `(* ${content.length}B continuation *)`, cid: this.id });
data.next();
continue;
}
let section = parsed.attributes && parsed.attributes.length && parsed.attributes[0] && !parsed.attributes[0].value && parsed.attributes[0].section;
if (section && section.length && section[0].type === 'ATOM' && typeof section[0].value === 'string') {
let sectionHandler = this.getSectionHandler(section[0].value.toUpperCase().trim());
if (sectionHandler) {
await sectionHandler(section.slice(1));
}
}
if (parsed.tag === '*' && parsed.command) {
let untaggedHandler = this.getUntaggedHandler(parsed.command, parsed.attributes);
if (untaggedHandler) {
try {
await untaggedHandler(parsed);
} catch (err) {
this.log.warn({ err, cid: this.id });
data.next();
continue;
}
}
}
if (this.requestTagMap.has(parsed.tag)) {
let request = this.requestTagMap.get(parsed.tag);
this.requestTagMap.delete(parsed.tag);
if (this.currentRequest && this.currentRequest.tag === parsed.tag) {
// send next pending command
this.currentRequest = false;
await this.trySend();
}
switch (parsed.command.toUpperCase()) {
case 'OK':
case 'BYE':
await new Promise(resolve => request.resolve({ response: parsed, next: resolve }));
break;
case 'NO':
case 'BAD': {
let txt =
parsed.attributes &&
parsed.attributes
.filter(val => val.type === 'TEXT')
.map(val => val.value.trim())
.join(' ');
let err = new Error('Command failed');
err.response = parsed;
err.responseStatus = parsed.command.toUpperCase();
if (txt) {
err.responseText = txt;
let throttleDelay = false;
// MS365 throttling
// tag BAD Request is throttled. Suggested Backoff Time: 92415 milliseconds
if (/Request is throttled/i.test(txt) && /Backoff Time/i.test(txt)) {
let throttlingMatch = txt.match(/Backoff Time[:=\s]+(\d+)/i);
if (throttlingMatch && throttlingMatch[1] && !isNaN(throttlingMatch[1])) {
throttleDelay = Number(throttlingMatch[1]);
}
}
// Wait and return a throttling error
if (throttleDelay) {
err.code = 'ETHROTTLE';
err.throttleReset = throttleDelay;
let delayResponse = throttleDelay;
if (delayResponse > 5 * 60 * 1000) {
// max delay cap
delayResponse = 5 * 60 * 1000;
}
this.log.warn({ msg: 'Throttling detected', err, cid: this.id, throttleDelay, delayResponse });
await new Promise(r => setTimeout(r, delayResponse));
}
}
request.reject(err);
break;
}
default: {
let err = new Error('Invalid server response');
err.response = parsed;
request.reject(err);
break;
}
}
}
data.next();
}
}
setEventHandlers() {
this.socketReadable = () => {
if (!this.reading) {
this.reading = true;
this.reader()
.catch(err => this.log.error({ err, cid: this.id }))
.finally(() => {
this.reading = false;
});
}
};
this.streamer.on('readable', this.socketReadable);
}
setSocketHandlers() {
this._socketError =
this._socketError ||
(err => {
this.log.error({ err, cid: this.id });
setImmediate(() => this.close());
this.emitError(err);
});
this._socketClose =
this._socketClose ||
(() => {
this.close();
});
this._socketEnd =
this._socketEnd ||
(() => {
this.close();
});
this._socketTimeout =
this._socketTimeout ||
(() => {
if (this.idling) {
this.run('NOOP')
.then(() => this.idle())
.catch(this._socketError);
} else {
this.log.debug({ msg: 'Socket timeout', cid: this.id });
this.close();
}
});
this.socket.on('error', this._socketError);
this.socket.on('close', this._socketClose);
this.socket.on('end', this._socketEnd);
this.socket.on('tlsClientError', this._socketError);
this.socket.on('timeout', this._socketTimeout);
this.writeSocket.on('error', this._socketError);
}
clearSocketHandlers() {
if (this._socketError) {
this.socket.removeListener('error', this._socketError);
this.socket.removeListener('tlsClientError', this._socketError);
}
if (this._socketClose) {
this.socket.removeListener('close', this._socketClose);
}
if (this._socketEnd) {
this.socket.removeListener('end', this._socketEnd);
}
}
async startSession() {
await this.run('CAPABILITY');
if (this.capabilities.has('ID')) {
this.idRequested = await this.run('ID', this.clientInfo);
}
// try to use STARTTLS is possible
if (!this.secureConnection) {
await this.upgradeConnection();
}
let authenticated = await this.authenticate();
if (!authenticated) {
// nothing to do here
return await this.logout();
}
if (!this.idRequested && this.capabilities.has('ID')) {
// re-request ID after LOGIN
this.idRequested = await this.run('ID', this.clientInfo);
}
// Make sure we have namespace set. This should also throw if Exchange actually failed authentication
let nsResponse = await this.run('NAMESPACE');
if (nsResponse && nsResponse.error && nsResponse.status === 'BAD' && /User is authenticated but not connected/i.test(nsResponse.text)) {
// Not a NAMESPACE failure but authentication failure, so report as
this.authenticated = false;
let err = new Error('Authentication failed');
err.authenticationFailed = true;
err.response = nsResponse.text;
throw err;
}
if (this.options.verifyOnly) {
// List all folders and logout
if (this.options.includeMailboxes) {
this._mailboxList = await this.list();
}
return await this.logout();
}
// try to use compression (if supported)
if (!this.options.disableCompression) {
await this.compress();
}
if (!this.options.disableAutoEnable) {
// enable extensions if possible
await this.run('ENABLE', ['CONDSTORE', 'UTF8=ACCEPT'].concat(this.options.qresync ? 'QRESYNC' : []));
}
this.usable = true;
}
async compress() {
if (!(await this.run('COMPRESS'))) {
return; // was not able to negotiate compression
}
// create deflate/inflate streams
this._deflate = zlib.createDeflateRaw({
windowBits: 15
});
this._inflate = zlib.createInflateRaw();
// route incoming socket via inflate stream
this.socket.unpipe(this.streamer);
this.streamer.compress = true;
this.socket.pipe(this._inflate).pipe(this.streamer);
this._inflate.on('error', err => {
this.streamer.emit('error', err);
});
// route outgoing socket via deflate stream
this.writeSocket = new PassThrough();
this.writeSocket.destroySoon = () => {
try {
if (this.socket) {
this.socket.destroySoon();
}
this.writeSocket.end();
} catch (err) {
this.log.error({ err, info: 'Failed to destroy PassThrough socket', cid: this.id });
throw err;
}
};
Object.defineProperty(this.writeSocket, 'destroyed', {
get: () => this.socket.destroyed
});
// we need to force flush deflated data to socket so we can't
// use normal pipes for this.writeSocket -> this._deflate -> this.socket
let reading = false;
let readNext = () => {
reading = true;
let chunk;
while ((chunk = this.writeSocket.read()) !== null) {
if (this._deflate && this._deflate.write(chunk) === false) {
return this._deflate.once('drain', readNext);
}
}
// flush data to socket
if (this._deflate) {
this._deflate.flush();
}
reading = false;
};
this.writeSocket.on('readable', () => {
if (!reading) {
readNext();
}
});
this.writeSocket.on('error', err => {
this.socket.emit('error', err);
});
this._deflate.pipe(this.socket);
this._deflate.on('error', err => {
this.socket.emit('error', err);
});
}
async upgradeConnection() {
if (this.secureConnection) {
// already secure
return true;
}
if (!this.capabilities.has('STARTTLS')) {
// can not upgrade
return false;
}
this.expectCapabilityUpdate = true;
let canUpgrade = await this.run('STARTTLS');
if (!canUpgrade) {
return;
}
this.socket.unpipe(this.streamer);
let upgraded = await new Promise((resolve, reject) => {
let socketPlain = this.socket;
let opts = Object.assign(
{
socket: this.socket,
servername: this.servername,
port: this.port
},
this.options.tls || {}
);
this.clearSocketHandlers();
socketPlain.once('error', err => {
clearTimeout(this.connectTimeout);
if (!this.upgrading) {
// don't care anymore
return;
}
setImmediate(() => this.close());
this.upgrading = false;
reject(err);
});
this.upgradeTimeout = setTimeout(() => {
if (!this.upgrading) {
return;
}
setImmediate(() => this.close());
let err = new Error('Failed to upgrade connection in required time');
err.code = 'UPGRADE_TIMEOUT';
reject(err);
}, UPGRADE_TIMEOUT);
this.upgrading = true;
this.socket = tls.connect(opts, () => {
clearTimeout(this.upgradeTimeout);
if (this.isClosed) {
// not sure if this is possible?
return this.close();
}
this.secureConnection = true;
this.upgrading = false;
this.streamer.secureConnection = true;
this.socket.pipe(this.streamer);
this.tls = typeof this.socket.getCipher === 'function' ? this.socket.getCipher() : false;
if (this.tls) {
this.tls.authorized = this.socket.authorized;
this.log.info({
src: 'tls',
msg: 'Established TLS session',
cid: this.id,
authorized: this.tls.authorized,
algo: this.tls.standardName || this.tls.name,
version: this.tls.version
});
}
return resolve(true);
});
this.writeSocket = this.socket;
this.setSocketHandlers();
});
if (upgraded && this.expectCapabilityUpdate) {
await this.run('CAPABILITY');
}
return upgraded;
}
async setAuthenticationState() {
this.state = this.states.AUTHENTICATED;
this.authenticated = true;
if (this.expectCapabilityUpdate) {
// update capabilities
await this.run('CAPABILITY');
}
}
async authenticate() {
if (this.state !== this.states.NOT_AUTHENTICATED) {
// nothing to do here, usually happens with PREAUTH greeting
return this.state !== this.states.LOGOUT;
}
if (this.capabilities.has('LOGINDISABLED') || !this.options.auth) {
// can not log in
return false;
}
this.expectCapabilityUpdate = true;
if (this.options.auth.accessToken) {
this.authenticated = await this.run('AUTHENTICATE', this.options.auth.user, this.options.auth.accessToken);
} else if (this.options.auth.pass) {
this.authenticated = await this.run('LOGIN', this.options.auth.user, this.options.auth.pass);
}
if (this.authenticated) {
this.log.info({
src: 'auth',
msg: 'User authenticated',
cid: this.id,
user: this.options.auth.user
});
await this.setAuthenticationState();
return true;
}
return false;
}
async initialOK(message) {
this.greeting = (message.attributes || [])
.filter(entry => entry.type === 'TEXT')
.map(entry => entry.value)
.filter(entry => entry)
.join('');
clearTimeout(this.greetingTimeout);
this.untaggedHandlers.OK = null;
this.untaggedHandlers.PREAUTH = null;
if (this.isClosed) {
return;
}
// get out of current parsing "thread", so do not await for startSession
this.startSession()
.then(() => {
if (typeof this.initialResolve === 'function') {
let resolve = this.initialResolve;
this.initialResolve = false;
this.initialReject = false;
return resolve();
}
})
.catch(err => {
this.log.error({ err, cid: this.id });
if (typeof this.initialReject === 'function') {
clearTimeout(this.greetingTimeout);
let reject = this.initialReject;
this.initialResolve = false;
this.initialReject = false;
return reject(err);
}
setImmediate(() => this.close());
});
}
async initialPREAUTH() {
clearTimeout(this.greetingTimeout);
this.untaggedHandlers.OK = null;
this.untaggedHandlers.PREAUTH = null;
if (this.isClosed) {
return;
}
this.state = this.states.AUTHENTICATED;
// get out of current parsing "thread", so do not await for startSession
this.startSession()
.then(() => {
if (typeof this.initialResolve === 'function') {
let resolve = this.initialResolve;
this.initialResolve = false;
this.initialReject = false;
return resolve();
}
})