This repository has been archived by the owner on Nov 3, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
imap.js
2220 lines (2073 loc) · 77.1 KB
/
imap.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
define('imap',['require','exports','module','util','rdcommon/log','net','tls','events','mailparser/mailparser'],function(require, exports, module) {
var util = require('util'), $log = require('rdcommon/log'),
net = require('net'), tls = require('tls'),
EventEmitter = require('events').EventEmitter,
mailparser = require('mailparser/mailparser');
var emptyFn = function() {}, CRLF = '\r\n',
CRLF_BUFFER = Buffer(CRLF),
STATES = {
NOCONNECT: 0,
NOAUTH: 1,
AUTH: 2,
BOXSELECTING: 3,
BOXSELECTED: 4
}, BOX_ATTRIBS = ['NOINFERIORS', 'NOSELECT', 'MARKED', 'UNMARKED'],
MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
'Oct', 'Nov', 'Dec'],
reFetch = /^\* (\d+) FETCH [\s\S]+? \{(\d+)\}$/,
reDate = /^(\d{2})-(.{3})-(\d{4})$/,
reDateTime = /^(\d{2})-(.{3})-(\d{4}) (\d{2}):(\d{2}):(\d{2}) ([+-]\d{4})$/,
HOUR_MILLIS = 60 * 60 * 1000, MINUTE_MILLIS = 60 * 1000;
const CHARCODE_RBRACE = ('}').charCodeAt(0),
CHARCODE_ASTERISK = ('*').charCodeAt(0),
CHARCODE_RPAREN = (')').charCodeAt(0);
var setTimeoutFunc = window.setTimeout.bind(window),
clearTimeoutFunc = window.clearTimeout.bind(window);
exports.TEST_useTimeoutFuncs = function(setFunc, clearFunc) {
setTimeoutFunc = setFunc;
clearTimeoutFunc = clearFunc;
};
/**
* A buffer for us to assemble buffers so the back-end doesn't fragment them.
* This is safe for mozTCPSocket's buffer usage because the buffer is always
* consumed synchronously. This is not necessarily safe under other semantics.
*/
var gSendBuf = new Uint8Array(2000);
function singleArgParseInt(x) {
return parseInt(x, 10);
}
/**
* Parses (UTC) IMAP dates into UTC timestamps. IMAP dates are DD-Mon-YYYY.
*/
function parseImapDate(dstr) {
var match = reDate.exec(dstr);
if (!match)
throw new Error("Not a good IMAP date: " + dstr);
var day = parseInt(match[1], 10),
zeroMonth = MONTHS.indexOf(match[2]),
year = parseInt(match[3], 10);
return Date.UTC(year, zeroMonth, day);
}
/**
* Modified utf-7 detecting regexp for use by `decodeModifiedUtf7`.
*/
const RE_MUTF7 = /&([^-]*)-/g,
RE_COMMA = /,/g;
/**
* Decode the modified utf-7 representation used to encode mailbox names to
* lovely unicode.
*
* Notes:
* - '&' enters mutf-7 mode, '-' exits it (and exiting is required!), but '&-'
* encodes a '&' rather than * a zero-length string.
* - ',' is used instead of '/' for the base64 encoding
*
* Learn all about it at:
* https://tools.ietf.org/html/rfc3501#section-5.1.3
*/
function decodeModifiedUtf7(encoded) {
return encoded.replace(
RE_MUTF7,
function replacer(fullMatch, b64data) {
// &- encodes &
if (!b64data.length)
return '&';
// we use a funky base64 where ',' is used instead of '/'...
b64data = b64data.replace(RE_COMMA, '/');
// The base-64 encoded utf-16 gets converted into a buffer holding the
// utf-16 encoded bits.
var u16data = new Buffer(b64data, 'base64');
// and this actually decodes the utf-16 into a JS string.
return u16data.toString('utf-16be');
});
}
exports.decodeModifiedUtf7 = decodeModifiedUtf7;
/**
* Parses IMAP date-times into UTC timestamps. IMAP date-times are
* "DD-Mon-YYYY HH:MM:SS +ZZZZ"
*/
function parseImapDateTime(dstr) {
var match = reDateTime.exec(dstr);
if (!match)
throw new Error("Not a good IMAP date-time: " + dstr);
var day = parseInt(match[1], 10),
zeroMonth = MONTHS.indexOf(match[2]),
year = parseInt(match[3], 10),
hours = parseInt(match[4], 10),
minutes = parseInt(match[5], 10),
seconds = parseInt(match[6], 10),
// figure the timestamp before the zone stuff. We don't
timestamp = Date.UTC(year, zeroMonth, day, hours, minutes, seconds),
// to reduce string garbage creation, we use one string. (we have to
// play math games no matter what, anyways.)
zoneDelta = parseInt(match[7], 10),
zoneHourDelta = Math.floor(zoneDelta / 100),
// (the negative sign sticks around through the mod operation)
zoneMinuteDelta = zoneDelta % 100;
// ex: GMT-0700 means 7 hours behind, so we need to add 7 hours, aka
// subtract negative 7 hours.
timestamp -= zoneHourDelta * HOUR_MILLIS + zoneMinuteDelta * MINUTE_MILLIS;
return timestamp;
}
function formatImapDateTime(date) {
var s;
s = ((date.getDate() < 10) ? ' ' : '') + date.getDate() + '-' +
MONTHS[date.getMonth()] + '-' +
date.getFullYear() + ' ' +
('0'+date.getHours()).slice(-2) + ':' +
('0'+date.getMinutes()).slice(-2) + ':' +
('0'+date.getSeconds()).slice(-2) +
((date.getTimezoneOffset() > 0) ? ' -' : ' +' ) +
('0'+(Math.abs(date.getTimezoneOffset()) / 60)).slice(-2) +
('0'+(Math.abs(date.getTimezoneOffset()) % 60)).slice(-2);
return s;
}
var IDLE_NONE = 1,
IDLE_WAIT = 2,
IDLE_READY = 3,
DONE_WAIT = 4;
function ImapConnection (options) {
if (!(this instanceof ImapConnection))
return new ImapConnection(options);
EventEmitter.call(this);
this._options = {
username: '',
password: '',
host: 'localhost',
port: 143,
secure: false,
connTimeout: 10000, // connection timeout in msecs
_logParent: null
};
this._state = {
status: STATES.NOCONNECT,
conn: null,
curId: 0,
requests: [],
numCapRecvs: 0,
isReady: false,
isIdle: true,
tmrKeepalive: null,
tmoKeepalive: 10000,
tmrConn: null,
curData: null,
// Because 0-length literals are a possibility, use null to represent no
// expected data.
curExpected: null,
curXferred: 0,
box: {
_uidnext: 0,
_flags: [],
_newKeywords: false,
validity: 0,
// undefined when unknown, null is nomodseq, string of the actual
// highestmodseq once retrieved.
highestModSeq: undefined,
keywords: [],
permFlags: [],
name: null,
messages: { total: 0, new: 0 }
},
ext: {
// Capability-specific state info
idle: {
MAX_WAIT: 1740000, // 29 mins in ms
state: IDLE_NONE,
timeWaited: 0 // ms
}
}
};
this._options = extend(true, this._options, options);
// The Date.now thing is to assign a random/unique value as a logging stop-gap
this._LOG = (this._options._logParent ? LOGFAB.ImapProtoConn(this, this._options._logParent, Date.now() % 1000) : null);
if (this._LOG) this._LOG.created();
this.delim = null;
this.namespaces = { personal: [], other: [], shared: [] };
this.capabilities = [];
this.enabledCapabilities = [];
};
util.inherits(ImapConnection, EventEmitter);
exports.ImapConnection = ImapConnection;
ImapConnection.prototype.hasCapability = function(name) {
return this.capabilities.indexOf(name) !== -1;
};
ImapConnection.prototype.connect = function(loginCb) {
var self = this,
fnInit = function() {
// First get pre-auth capabilities, including server-supported auth
// mechanisms
self._send('CAPABILITY', null, function() {
// Next, attempt to login
var checkedNS = false;
var redo = function(err, reentry) {
if (err) {
loginCb(err);
return;
}
// Next, get the list of available namespaces if supported
if (!checkedNS && self.capabilities.indexOf('NAMESPACE') > -1) {
// Re-enter this function after we've obtained the available
// namespaces
checkedNS = true;
self._send('NAMESPACE', null, redo);
return;
}
// Lastly, get the top-level mailbox hierarchy delimiter used by the
// server
self._send('LIST "" ""', null, loginCb);
};
self._login(redo);
});
};
loginCb = loginCb || emptyFn;
this._reset();
if (this._LOG) this._LOG.connect(this._options.host, this._options.port);
this._state.conn = (this._options.crypto ? tls : net).connect(
this._options.port, this._options.host);
this._state.tmrConn = setTimeoutFunc(this._fnTmrConn.bind(this, loginCb),
this._options.connTimeout);
this._state.conn.on('connect', function() {
if (self._LOG) self._LOG.connected();
clearTimeoutFunc(self._state.tmrConn);
self._state.status = STATES.NOAUTH;
/*
We will need to add support for node-like starttls emulation on top of TCPSocket
once TCPSocket supports starttls (see also bug 784816).
if (self._options.crypto === 'starttls') {
self._send('STARTTLS', function() {
starttls(self, function() {
if (!self.authorized)
throw new Error("starttls failed");
fnInit();
});
});
return;
}
*/
fnInit();
});
this._state.conn.on('data', function(buffer) {
try {
processData(buffer);
}
catch (ex) {
console.error('Explosion while processing data', ex);
if ('stack' in ex)
console.error('Stack:', ex.stack);
throw ex;
}
});
/**
* Process up to one thing. Generally:
* - If we are processing a literal, we make sure we have the data for the
* whole literal, then we process it.
* - If we are not in a literal, we buffer until we have one newline.
* - If we have leftover data, we invoke ourselves in a quasi-tail-recursive
* fashion or in subsequent ticks. It's not clear that the logic that
* defers to future ticks is sound.
*/
function processData(data) {
if (data.length === 0) return;
var idxCRLF = null, literalInfo;
// - Accumulate data until newlines when not in a literal
if (self._state.curExpected === null) {
// no newline, append and bail
if ((idxCRLF = bufferIndexOfCRLF(data, 0)) === -1) {
if (self._state.curData)
self._state.curData = bufferAppend(self._state.curData, data);
else
self._state.curData = data;
return;
}
// yes newline, use the buffered up data and new data
// (note: data may now contain more than one line's worth of data!)
if (self._state.curData && self._state.curData.length) {
data = bufferAppend(self._state.curData, data);
self._state.curData = null;
}
}
// -- Literal
// Don't mess with incoming data if it's part of a literal
if (self._state.curExpected !== null) {
var curReq = self._state.requests[0];
if (!curReq._done) {
var chunk = data;
self._state.curXferred += data.length;
if (self._state.curXferred > self._state.curExpected) {
var pos = data.length
- (self._state.curXferred - self._state.curExpected),
extra = data.slice(pos);
if (pos > 0)
chunk = data.slice(0, pos);
else
chunk = undefined;
data = extra;
curReq._done = 1;
}
if (chunk && chunk.length) {
if (self._LOG) self._LOG.data(chunk.length, chunk);
if (curReq._msgtype === 'headers') {
chunk.copy(self._state.curData, curReq.curPos, 0);
curReq.curPos += chunk.length;
}
else
curReq._msg.emit('data', chunk);
}
}
if (curReq._done) {
var restDesc;
if (curReq._done === 1) {
if (curReq._msgtype === 'headers')
curReq._headers = self._state.curData.toString('ascii');
self._state.curData = null;
curReq._done = true;
}
if (self._state.curData)
self._state.curData = bufferAppend(self._state.curData, data);
else
self._state.curData = data;
idxCRLF = bufferIndexOfCRLF(self._state.curData);
if (idxCRLF && self._state.curData[idxCRLF - 1] === CHARCODE_RPAREN) {
if (idxCRLF > 1) {
// eat up to, but not including, the right paren
restDesc = self._state.curData.toString('ascii', 0, idxCRLF - 1)
.trim();
if (restDesc.length)
curReq._desc += ' ' + restDesc;
}
parseFetch(curReq._desc, curReq._headers, curReq._msg);
data = self._state.curData.slice(idxCRLF + 2);
curReq._done = false;
self._state.curXferred = 0;
self._state.curExpected = null;
self._state.curData = null;
curReq._msg.emit('end', curReq._msg);
// XXX we could just change the next else to not be an else, and then
// this conditional is not required and we can just fall out. (The
// expected check === 0 may need to be reinstated, however.)
if (data.length && data[0] === CHARCODE_ASTERISK) {
processData(data);
return;
}
} else // ??? no right-paren, keep accumulating data? this seems wrong.
return;
} else // not done, keep accumulating data
return;
}
// -- Fetch w/literal
// (More specifically, we were not in a literal, let's see if this line is
// a fetch result line that starts a literal. We want to minimize
// conversion to a string, as there used to be a naive conversion here that
// chewed up a lot of processor by converting all of data rather than
// just the current line.)
else if (data[0] === CHARCODE_ASTERISK) {
var strdata;
idxCRLF = bufferIndexOfCRLF(data, 0);
if (data[idxCRLF - 1] === CHARCODE_RBRACE &&
(literalInfo =
(strdata = data.toString('ascii', 0, idxCRLF)).match(reFetch))) {
self._state.curExpected = parseInt(literalInfo[2], 10);
var curReq = self._state.requests[0],
type = /BODY\[(.*)\](?:\<\d+\>)?/.exec(strdata),
msg = new ImapMessage(),
desc = strdata.substring(strdata.indexOf('(')+1).trim();
msg.seqno = parseInt(literalInfo[1], 10);
type = type[1];
curReq._desc = desc;
curReq._msg = msg;
curReq._fetcher.emit('message', msg);
curReq._msgtype = (type.indexOf('HEADER') === 0 ? 'headers' : 'body');
// This library buffers headers, so allocate a buffer to hold the literal.
if (curReq._msgtype === 'headers') {
self._state.curData = new Buffer(self._state.curExpected);
curReq.curPos = 0;
}
if (self._LOG) self._LOG.data(strdata.length, strdata);
// (If it's not headers, then it's body, and we generate 'data' events.)
processData(data.slice(idxCRLF + 2));
return;
}
}
if (data.length === 0)
return;
data = customBufferSplitCRLF(data);
// Defer any extra server responses found in the incoming data
for (var i=1,len=data.length; i<len; ++i) {
process.nextTick(processData.bind(null, data[i]));
}
data = data[0].toString('ascii');
if (self._LOG) self._LOG.data(data.length, data);
data = stringExplode(data, ' ', 3);
// -- Untagged server responses
if (data[0] === '*') {
if (self._state.status === STATES.NOAUTH) {
if (data[1] === 'PREAUTH') { // the server pre-authenticated us
self._state.status = STATES.AUTH;
if (self._state.numCapRecvs === 0)
self._state.numCapRecvs = 1;
} else if (data[1] === 'NO' || data[1] === 'BAD' || data[1] === 'BYE') {
if (self._LOG && data[1] === 'BAD')
self._LOG.bad(data[2]);
self._state.conn.end();
return;
}
if (!self._state.isReady)
self._state.isReady = true;
// Restrict the type of server responses when unauthenticated
if (data[1] !== 'CAPABILITY' && data[1] !== 'ALERT')
return;
}
switch (data[1]) {
case 'CAPABILITY':
if (self._state.numCapRecvs < 2)
self._state.numCapRecvs++;
self.capabilities = data[2].split(' ').map(up);
break;
// Feedback from the ENABLE command.
case 'ENABLED':
self.enabledCapabilities = self.enabledCapabilities.concat(
data[2].split(' '));
self.enabledCapabilities.sort();
break;
// The system-defined flags for this mailbox; during SELECT/EXAMINE
case 'FLAGS':
if (self._state.status === STATES.BOXSELECTING) {
self._state.box._flags = data[2].substr(1, data[2].length-2)
.split(' ').map(function(flag) {
return flag.substr(1);
});
}
break;
case 'OK':
if ((result = /^\[ALERT\] (.*)$/i.exec(data[2])))
self.emit('alert', result[1]);
else if (self._state.status === STATES.BOXSELECTING) {
var result;
if ((result = /^\[UIDVALIDITY (\d+)\]/i.exec(data[2])))
self._state.box.validity = result[1];
else if ((result = /^\[UIDNEXT (\d+)\]/i.exec(data[2])))
self._state.box._uidnext = parseInt(result[1]);
// Flags the client can change permanently. If \* is included, it
// means we can make up new keywords.
else if ((result = /^\[PERMANENTFLAGS \((.*)\)\]/i.exec(data[2]))) {
self._state.box.permFlags = result[1].split(' ');
var idx;
if ((idx = self._state.box.permFlags.indexOf('\\*')) > -1) {
self._state.box._newKeywords = true;
self._state.box.permFlags.splice(idx, 1);
}
self._state.box.keywords = self._state.box.permFlags
.filter(function(flag) {
return (flag[0] !== '\\');
});
for (var i=0; i<self._state.box.keywords.length; i++)
self._state.box.permFlags.splice(self._state.box.permFlags.indexOf(self._state.box.keywords[i]), 1);
self._state.box.permFlags = self._state.box.permFlags
.map(function(flag) {
return flag.substr(1);
});
}
else if ((result = /^\[HIGHESTMODSEQ (\d+)\]/i.exec(data[2]))) {
// Kept as a string since it may be a full 64-bit value.
self._state.box.highestModSeq = result[1];
}
// The server does not support mod sequences for the folder.
else if ((result = /^\[NOMODSEQ\]/i.exec(data[2]))) {
self._state.box.highestModSeq = null;
}
}
break;
case 'NAMESPACE':
parseNamespaces(data[2], self.namespaces);
break;
case 'SEARCH':
self._state.requests[0].args.push(
(data[2] === undefined || data[2].length === 0)
? [] : data[2].trim().split(' ').map(singleArgParseInt));
break;
case 'LIST':
case 'XLIST':
var result;
if (self.delim === null &&
(result = /^\(\\No[sS]elect(?:[^)]*)\) (.+?) .*$/.exec(data[2])))
self.delim = (result[1] === 'NIL'
? false
: result[1].substring(1, result[1].length - 1));
else if (self.delim !== null) {
if (self._state.requests[0].args.length === 0)
self._state.requests[0].args.push({});
result = /^\((.*)\) (.+?) "?([^"]+)"?$/.exec(data[2]);
var box = {
displayName: null,
attribs: result[1].split(' ').map(function(attrib) {
return attrib.substr(1).toUpperCase();
}),
delim: (result[2] === 'NIL'
? false : result[2].substring(1, result[2].length-1)),
children: null,
parent: null
},
name = result[3],
curChildren = self._state.requests[0].args[0];
if (name[0] === '"' && name[name.length-1] === '"')
name = name.substring(1, name.length - 1);
if (box.delim) {
var path = name.split(box.delim).filter(isNotEmpty),
parent = null;
name = path.pop();
for (var i=0,len=path.length; i<len; i++) {
if (!curChildren[path[i]])
curChildren[path[i]] = { delim: box.delim };
if (!curChildren[path[i]].children)
curChildren[path[i]].children = {};
parent = curChildren[path[i]];
curChildren = curChildren[path[i]].children;
}
box.parent = parent;
}
box.displayName = decodeModifiedUtf7(name);
if (curChildren[name])
box.children = curChildren[name].children;
curChildren[name] = box;
}
break;
// QRESYNC (when successful) generates a "VANISHED (EARLIER) uids"
// payload to tell us about deleted/expunged messages when selecting
// a folder.
// It will also generate untagged VANISHED updates as the result of an
// expunge on this connection or other connections (for this folder).
case 'VANISHED':
var earlier = false;
if (data[2].lastIndexOf('(EARLIER) ', 0) === 0) {
earlier = true;
data[2] = data[2].substring(10);
}
// Using vanished because the existing 'deleted' event uses sequence
// numbers.
self.emit('vanished', parseUIDListString(data[2]), earlier);
break;
default:
if (/^\d+$/.test(data[1])) {
var isUnsolicited = (self._state.requests[0] &&
self._state.requests[0].command.indexOf('NOOP') > -1) ||
(self._state.isIdle && self._state.ext.idle.state === IDLE_READY);
switch (data[2]) {
case 'EXISTS':
// mailbox total message count
var prev = self._state.box.messages.total,
now = parseInt(data[1]);
self._state.box.messages.total = now;
if (self._state.status !== STATES.BOXSELECTING && now > prev) {
self._state.box.messages.new = now-prev;
self.emit('mail', self._state.box.messages.new); // new mail
}
break;
case 'RECENT':
// messages marked with the \Recent flag (i.e. new messages)
self._state.box.messages.new = parseInt(data[1]);
break;
case 'EXPUNGE':
// confirms permanent deletion of a single message
if (self._state.box.messages.total > 0)
self._state.box.messages.total--;
if (isUnsolicited)
self.emit('deleted', parseInt(data[1], 10));
break;
default:
// fetches without header or body (part) retrievals
if (/^FETCH/.test(data[2])) {
var msg = new ImapMessage();
parseFetch(data[2].substring(data[2].indexOf("(")+1,
data[2].lastIndexOf(")")),
"", msg);
msg.seqno = parseInt(data[1], 10);
if (self._state.requests.length &&
self._state.requests[0].command.indexOf('FETCH') > -1) {
var curReq = self._state.requests[0];
curReq._fetcher.emit('message', msg);
msg.emit('end');
} else if (isUnsolicited)
self.emit('msgupdate', msg);
}
}
}
}
} else if (data[0][0] === 'A' || data[0] === '+') {
// Tagged server response or continuation response
if (data[0] === '+' && self._state.ext.idle.state === IDLE_WAIT) {
self._state.ext.idle.state = IDLE_READY;
return process.nextTick(function() { self._send(); });
}
var sendBox = false;
clearTimeoutFunc(self._state.tmrKeepalive);
if (self._state.status === STATES.BOXSELECTING) {
if (data[1] === 'OK') {
sendBox = true;
self._state.status = STATES.BOXSELECTED;
} else {
self._state.status = STATES.AUTH;
self._resetBox();
}
}
// XXX there is an edge case here where we LOGOUT and the server sends
// "* BYE" "AXX LOGOUT OK" and the close event gets processed (probably
// because of the BYE and the fact that we don't nextTick a lot for the
// moz logic) and _reset() nukes the requests before we see the LOGOUT,
// which we do end up seeing. So just bail in that case.
if (self._state.requests.length === 0) {
return;
}
if (self._state.requests[0].command.indexOf('RENAME') > -1) {
self._state.box.name = self._state.box._newName;
delete self._state.box._newName;
sendBox = true;
}
if (typeof self._state.requests[0].callback === 'function') {
var err = null;
var args = self._state.requests[0].args,
cmd = self._state.requests[0].command;
if (data[0] === '+') {
if (cmd.indexOf('APPEND') !== 0) {
err = new Error('Unexpected continuation');
err.type = 'continuation';
err.serverResponse = '';
err.request = cmd;
} else
return self._state.requests[0].callback();
} else if (data[1] !== 'OK') {
err = new Error('Error while executing request: ' + data[2]);
err.type = data[1];
err.serverResponse = data[2];
err.request = cmd;
} else if (self._state.status === STATES.BOXSELECTED) {
if (sendBox) // SELECT, EXAMINE, RENAME
args.unshift(self._state.box);
// According to RFC 3501, UID commands do not give errors for
// non-existant user-supplied UIDs, so give the callback empty results
// if we unexpectedly received no untagged responses.
else if ((cmd.indexOf('UID FETCH') === 0
|| cmd.indexOf('UID SEARCH') === 0
) && args.length === 0)
args.unshift([]);
}
args.unshift(err);
self._state.requests[0].callback.apply({}, args);
}
var recentReq = self._state.requests.shift();
if (!recentReq) {
// We expect this to happen in the case where our callback above
// resulted in our connection being killed. So just bail in that case.
if (self._state.status === STATES.NOCONNECT)
return;
// This is unexpected and bad. Log a poor man's error for now.
console.error('IMAP: Somehow no recentReq for data:', data);
return;
}
var recentCmd = recentReq.command;
if (self._LOG) self._LOG.cmd_end(recentReq.prefix, recentCmd, /^LOGIN$/.test(recentCmd) ? '***BLEEPING OUT LOGON***' : recentReq.cmddata);
if (self._state.requests.length === 0
&& recentCmd !== 'LOGOUT') {
if (self._state.status === STATES.BOXSELECTED &&
self.capabilities.indexOf('IDLE') > -1) {
// According to RFC 2177, we should re-IDLE at least every 29
// minutes to avoid disconnection by the server
self._send('IDLE', null, undefined, undefined, true);
}
self._state.tmrKeepalive = setTimeoutFunc(function() {
if (self._state.isIdle) {
if (self._state.ext.idle.state === IDLE_READY) {
self._state.ext.idle.timeWaited += self._state.tmoKeepalive;
if (self._state.ext.idle.timeWaited >= self._state.ext.idle.MAX_WAIT)
// restart IDLE
self._send('IDLE', null, undefined, undefined, true);
} else if (self.capabilities.indexOf('IDLE') === -1)
self._noop();
}
}, self._state.tmoKeepalive);
} else
process.nextTick(function() { self._send(); });
self._state.isIdle = true;
} else if (data[0] === 'IDLE') {
if (self._state.requests.length)
process.nextTick(function() { self._send(); });
self._state.isIdle = false;
self._state.ext.idle.state = IDLE_NONE;
self._state.ext.idle.timeWaited = 0;
} else {
if (self._LOG)
self._LOG.unknownResponse(data[0], data[1], data[2]);
// unknown response
}
};
this._state.conn.on('close', function onClose() {
self._reset();
if (this._LOG) this._LOG.closed();
self.emit('close');
});
this._state.conn.on('error', function(err) {
try {
var errType;
// (only do error probing on things we can safely use 'in' on)
if (err && typeof(err) === 'object') {
// detect an nsISSLStatus instance by an unusual property.
if ('isNotValidAtThisTime' in err) {
err = new Error('SSL error');
errType = err.type = 'bad-security';
}
}
clearTimeoutFunc(self._state.tmrConn);
if (self._state.status === STATES.NOCONNECT) {
var connErr = new Error('Unable to connect. Reason: ' + err);
connErr.type = errType || 'unresponsive-server';
connErr.serverResponse = '';
loginCb(connErr);
}
self.emit('error', err);
if (this._LOG) this._LOG.connError(err);
}
catch(ex) {
console.error("Error in imap onerror:", ex);
throw ex;
}
});
};
/**
* Aggressively shutdown the connection, ideally so that no further callbacks
* are invoked.
*/
ImapConnection.prototype.die = function() {
// NB: there's still a lot of events that could happen, but this is only
// being used by unit tests right now.
if (this._state.conn) {
this._state.conn.removeAllListeners();
this._state.conn.end();
}
this._reset();
this._LOG.__die();
};
ImapConnection.prototype.isAuthenticated = function() {
return this._state.status >= STATES.AUTH;
};
ImapConnection.prototype.logout = function(cb) {
if (this._state.status >= STATES.NOAUTH)
this._send('LOGOUT', null, cb);
else
throw new Error('Not connected');
};
/**
* Enable one or more optional capabilities. This is additive and there's no
* way to un-enable things once enabled. So enable(["a", "b"]), followed by
* enable(["c"]) is the same as enable(["a", "b", "c"]).
*
* http://tools.ietf.org/html/rfc5161
*/
ImapConnection.prototype.enable = function(capabilities, cb) {
if (this._state.status < STATES.AUTH)
throw new Error('Not connected or authenticated');
this._send('ENABLE ' + capabilities.join(' '), cb || emptyFn);
};
ImapConnection.prototype.openBox = function(name, readOnly, cb) {
if (this._state.status < STATES.AUTH)
throw new Error('Not connected or authenticated');
if (this._state.status === STATES.BOXSELECTED)
this._resetBox();
if (cb === undefined) {
if (readOnly === undefined)
cb = emptyFn;
else
cb = readOnly;
readOnly = false;
}
var self = this;
function dispatchFunc() {
self._state.status = STATES.BOXSELECTING;
self._state.box.name = name;
}
this._send((readOnly ? 'EXAMINE' : 'SELECT'), ' "' + escape(name) + '"', cb,
dispatchFunc);
};
/**
* SELECT/EXAMINE a box using the QRESYNC extension. The last known UID
* validity and last known modification sequence are required. The set of
* known UIDs is optional.
*/
ImapConnection.prototype.qresyncBox = function(name, readOnly,
uidValidity, modSeq,
knownUids,
cb) {
if (this._state.status < STATES.AUTH)
throw new Error('Not connected or authenticated');
if (this.enabledCapabilities.indexOf('QRESYNC') === -1)
throw new Error('QRESYNC is not enabled');
if (this._state.status === STATES.BOXSELECTED)
this._resetBox();
if (cb === undefined) {
if (readOnly === undefined)
cb = emptyFn;
else
cb = readOnly;
readOnly = false;
}
var self = this;
function dispatchFunc() {
self._state.status = STATES.BOXSELECTING;
self._state.box.name = name;
}
this._send((readOnly ? 'EXAMINE' : 'SELECT') + ' "' + escape(name) + '"' +
' (QRESYNC (' + uidValidity + ' ' + modSeq +
(knownUids ? (' ' + knownUids) : '') + '))', cb, dispatchFunc);
};
// also deletes any messages in this box marked with \Deleted
ImapConnection.prototype.closeBox = function(cb) {
var self = this;
if (this._state.status !== STATES.BOXSELECTED)
throw new Error('No mailbox is currently selected');
this._send('CLOSE', null, function(err) {
if (!err) {
self._state.status = STATES.AUTH;
self._resetBox();
}
cb(err);
});
};
ImapConnection.prototype.removeDeleted = function(cb) {
if (this._state.status !== STATES.BOXSELECTED)
throw new Error('No mailbox is currently selected');
cb = arguments[arguments.length-1];
this._send('EXPUNGE', null, cb);
};
ImapConnection.prototype.getBoxes = function(namespace, searchSpec, cb) {
cb = arguments[arguments.length-1];
if (arguments.length < 2)
namespace = '';
if (arguments.length < 3)
searchSpec = '*';
var cmd, cmddata = ' "' + escape(namespace) + '" "' +
escape(searchSpec) + '"';
// Favor special-use over XLIST
if (this.capabilities.indexOf('SPECIAL-USE') !== -1) {
cmd = 'LIST';
cmddata += ' RETURN (SPECIAL-USE)';
}
else if (this.capabilities.indexOf('XLIST') !== -1) {
cmd = 'XLIST';
}
else {
cmd = 'LIST';
}
this._send(cmd, cmddata, cb);
};
ImapConnection.prototype.addBox = function(name, cb) {
cb = arguments[arguments.length-1];
if (typeof name !== 'string' || name.length === 0)
throw new Error('Mailbox name must be a string describing the full path'
+ ' of a new mailbox to be created');
this._send('CREATE', ' "' + escape(name) + '"', cb);
};
ImapConnection.prototype.delBox = function(name, cb) {
cb = arguments[arguments.length-1];
if (typeof name !== 'string' || name.length === 0)
throw new Error('Mailbox name must be a string describing the full path'
+ ' of an existing mailbox to be deleted');
this._send('DELETE', ' "' + escape(name) + '"', cb);
};
ImapConnection.prototype.renameBox = function(oldname, newname, cb) {
cb = arguments[arguments.length-1];
if (typeof oldname !== 'string' || oldname.length === 0)
throw new Error('Old mailbox name must be a string describing the full path'
+ ' of an existing mailbox to be renamed');
else if (typeof newname !== 'string' || newname.length === 0)
throw new Error('New mailbox name must be a string describing the full path'
+ ' of a new mailbox to be renamed to');
if (this._state.status === STATES.BOXSELECTED
&& oldname === this._state.box.name && oldname !== 'INBOX')
this._state.box._newName = oldname;
this._send('RENAME', ' "' + escape(oldname) + '" "' + escape(newname) + '"', cb);
};
ImapConnection.prototype.search = function(options, cb) {
this._search('UID ', options, cb);
};
ImapConnection.prototype._search = function(which, options, cb) {
if (this._state.status !== STATES.BOXSELECTED)
throw new Error('No mailbox is currently selected');
if (!Array.isArray(options))
throw new Error('Expected array for search options');
this._send(which + 'SEARCH',
buildSearchQuery(options, this.capabilities), cb);
};
ImapConnection.prototype.append = function(data, options, cb) {
if (typeof options === 'function') {
cb = options;
options = {};
}
options = options || {};
if (!('mailbox' in options)) {
if (this._state.status !== STATES.BOXSELECTED)
throw new Error('No mailbox specified or currently selected');
else
options.mailbox = this._state.box.name;
}
var cmd = ' "'+escape(options.mailbox)+'"';
if ('flags' in options) {
if (!Array.isArray(options.flags))
options.flags = Array(options.flags);
cmd += " (\\"+options.flags.join(' \\')+")";
}
if ('date' in options) {
if (!(options.date instanceof Date))
throw new Error('Expected null or Date object for date');
cmd += ' "' + formatImapDateTime(options.date) + '"';
}
cmd += ' {';
cmd += (Buffer.isBuffer(data) ? data.length : Buffer.byteLength(data));
cmd += '}';
var self = this, step = 1;
this._send('APPEND', cmd, function(err) {
if (err || step++ === 2)
return cb(err);
if (typeof(data) === 'string') {
self._state.conn.send(Buffer(data + CRLF));
}
else {
self._state.conn.write(data);
self._state.conn.write(CRLF_BUFFER);
}