forked from mscdex/node-imap
/
imap.js
1564 lines (1458 loc) · 52.3 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
var util = require('util'), net = require('net'),
tls = require('tls'), EventEmitter = require('events').EventEmitter;
var emptyFn = function() {}, CRLF = '\r\n', debug=emptyFn,
STATES = {
NOCONNECT: 0,
NOAUTH: 1,
AUTH: 2,
BOXSELECTING: 3,
BOXSELECTED: 4
}, BOX_ATTRIBS = ['NOINFERIORS', 'NOSELECT', 'MARKED', 'UNMARKED'],
reFetch = /^\* \d+ FETCH .+? \{(\d+)\}\r\n/;
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
debug: false
};
this._state = {
status: STATES.NOCONNECT,
conn: null,
curId: 0,
requests: [],
numCapRecvs: 0,
isReady: false,
isIdle: true,
tmrKeepalive: null,
tmoKeepalive: 10000,
tmrConn: null,
curData: null,
curExpected: 0,
curXferred: 0,
capabilities: [],
box: {
_uidnext: 0,
_flags: [],
_newKeywords: false,
validity: 0,
keywords: [],
permFlags: [],
name: null,
messages: { total: 0, new: 0 }
},
ext: {
// Capability-specific state stuff
idle: {
MAX_WAIT: 1740000, // 29 mins in ms
sentIdle: false,
timeWaited: 0 // ms
}
}
};
this._options = extend(true, this._options, options);
if (typeof this._options.debug === 'function')
debug = this._options.debug;
this.delim = null;
this.namespaces = { personal: [], other: [], shared: [] };
};
util.inherits(ImapConnection, EventEmitter);
exports.ImapConnection = ImapConnection;
ImapConnection.prototype.connect = function(loginCb) {
var self = this,
fnInit = function() {
// First get pre-auth capabilities, including server-supported auth
// mechanisms
self._send('CAPABILITY', function() {
// Next, attempt to login
self._login(function(err, reentry) {
if (err) {
loginCb(err);
return;
}
// Next, get the list of available namespaces if supported
if (!reentry && self._state.capabilities.indexOf('NAMESPACE') > -1) {
var fnMe = arguments.callee;
// Re-enter this function after we've obtained the available
// namespaces
self._send('NAMESPACE', function(e) { fnMe.call(this, e, true); });
return;
}
// Lastly, get the top-level mailbox hierarchy delimiter used by the
// server
self._send('LIST "" ""', loginCb);
});
});
};
loginCb = loginCb || emptyFn;
this._reset();
this._state.conn = net.createConnection(this._options.port, this._options.host);
this._state.tmrConn = setTimeout(this._fnTmrConn.bind(this),
this._options.connTimeout, loginCb);
this._state.conn.setKeepAlive(true);
if (this._options.secure) {
// TODO: support STARTTLS
this._state.conn.cleartext = this._state.conn.setSecure();
this._state.conn.on('secure', function() {
debug('Secure connection made.');
});
//this._state.conn.cleartext.setEncoding('utf8');
} else {
//this._state.conn.setEncoding('utf8');
this._state.conn.cleartext = this._state.conn;
}
this._state.conn.on('connect', function() {
clearTimeout(self._state.tmrConn);
debug('Connected to host.');
self._state.conn.cleartext.write('');
self._state.status = STATES.NOAUTH;
});
this._state.conn.on('ready', function() {
fnInit();
});
this._state.conn.cleartext.on('data', function(data) {
if (data.length === 0) return;
var trailingCRLF = false, literalInfo;
debug('\n<<RECEIVED>>: ' + util.inspect(data.toString()) + '\n');
if (self._state.curExpected === 0) {
if (data.indexOf(CRLF) === -1) {
if (self._state.curData)
self._state.curData = self._state.curData.add(data);
else
self._state.curData = data;
return;
}
if (self._state.curData && self._state.curData.length) {
data = self._state.curData.add(data);
self._state.curData = null;
}
}
// Don't mess with incoming data if it's part of a literal
if (self._state.curExpected > 0) {
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 (curReq._msgtype === 'headers') {
self._state.curData.append(chunk, curReq.curPos);
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();
self._state.curData = null;
curReq._done = true;
}
if (self._state.curData)
self._state.curData = self._state.curData.add(data);
else
self._state.curData = data;
if (restDesc = self._state.curData.toString().match(/^(.*?)\)\r\n/)) {
if (restDesc[1]) {
restDesc[1] = restDesc[1].trim();
if (restDesc[1].length)
restDesc[1] = ' ' + restDesc[1];
} else
restDesc[1] = '';
parseFetch(curReq._desc + restDesc[1], curReq._headers, curReq._msg);
data = self._state.curData.slice(self._state.curData.indexOf(CRLF)
+ 2);
curReq._done = false;
self._state.curXferred = 0;
self._state.curExpected = 0;
self._state.curData = null;
curReq._msg.emit('end');
if (data.length && data[0] === 42/* '*' */) {
self._state.conn.cleartext.emit('data', data);
return;
}
} else
return;
} else
return;
} else if (self._state.curExpected === 0
&& (literalInfo = data.toString().match(reFetch))) {
self._state.curExpected = parseInt(literalInfo[1], 10);
var idxCRLF = data.indexOf(CRLF),
curReq = self._state.requests[0],
type = /BODY\[(.*)\](?:\<\d+\>)?/
.exec(data.toString().substring(0, idxCRLF)),
msg = new ImapMessage(),
desc = data.toString().substring(data.indexOf('(')+1, idxCRLF).trim();
type = type[1];
curReq._desc = desc;
curReq._msg = msg;
curReq._fetcher.emit('message', msg);
curReq._msgtype = (type.indexOf('HEADER') === 0 ? 'headers' : 'body');
if (curReq._msgtype === 'headers') {
self._state.curData = new Buffer(self._state.curExpected);
curReq.curPos = 0;
}
self._state.conn.cleartext.emit('data', data.slice(idxCRLF + 2));
return;
}
if (data.length === 0)
return;
var endsInCRLF = (data[data.length-2] === 13 && data[data.length-1] === 10);
data = data.split(CRLF);
// Defer any extra server responses found in the incoming data
if (data.length > 1) {
for (var i=1,len=data.length; i<len; ++i) {
(function(line, isLast) {
process.nextTick(function() {
var needsCRLF = !isLast || (isLast && endsInCRLF),
b = new Buffer(needsCRLF ? line.length + 2 : line.length);
line.copy(b, 0, 0);
if (needsCRLF) {
b[b.length-2] = 13;
b[b.length-1] = 10;
}
self._state.conn.cleartext.emit('data', b);
});
})(data[i], i === len-1);
}
}
data = data[0].toString().explode(' ', 3);
if (data[0] === '*') { // Untagged server response
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') {
self._state.conn.end();
return;
}
if (!self._state.isReady) {
self._state.isReady = true;
self._state.conn.emit('ready');
}
// 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._state.capabilities = data[2].split(' ').map(up);
break;
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 = result[1];
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);
});
}
}
break;
case 'NAMESPACE':
parseNamespaces(data[2], self.namespaces);
break;
case 'SEARCH':
self._state.requests[0].args.push(typeof data[2] === 'undefined'
|| data[2].length === 0
? [] : data[2].split(' '));
break;
/*case 'STATUS':
var result = /UIDNEXT ([\d]+)\)$/.exec(data[2]);
self._state.requests[0].args.push(parseInt(result[1]));
break;*/
case 'LIST':
var result;
if (self.delim === null
&& (result = /^\(\\Noselect\) (.+?) ".*"$/.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 = {
attribs: result[1].split(' ').map(function(attrib) {
return attrib.substr(1).toUpperCase();
}).filter(function(attrib) {
return (BOX_ATTRIBS.indexOf(attrib) > -1);
}),
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 (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]] = {};
if (!curChildren[path[i]].children)
curChildren[path[i]].children = {};
parent = curChildren[path[i]];
curChildren = curChildren[path[i]].children;
}
box.parent = parent;
}
curChildren[name] = box;
}
break;
default:
if (/^\d+$/.test(data[1])) {
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--;
break;
default:
// fetches without header or body (part) retrievals
if (/^FETCH/.test(data[2])) {
var curReq = self._state.requests[0],
msg = new ImapMessage();
parseFetch(data[2].substring(data[2].indexOf("(")+1,
data[2].lastIndexOf(")")),
"", msg);
curReq._fetcher.emit('message', msg);
msg.emit('end');
}
}
}
}
} else if (data[0].indexOf('A') === 0) { // Tagged server response
var sendBox = false;
clearTimeout(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();
}
}
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[1] !== 'OK') {
err = new Error('Error while executing request: ' + data[2]);
err.type = data[1];
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 recentCmd = self._state.requests[0].command;
self._state.requests.shift();
if (self._state.requests.length === 0
&& recentCmd !== 'LOGOUT') {
if (self._state.status === STATES.BOXSELECTED &&
self._state.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', undefined, true);
}
self._state.tmrKeepalive = setTimeout(function() {
if (self._state.isIdle) {
if (self._state.ext.idle.sentIdle) {
self._state.ext.idle.timeWaited += self._state.tmoKeepalive;
if (self._state.ext.idle.timeWaited >= self._state.ext.idle.MAX_WAIT)
self._send('IDLE', undefined, true); // restart IDLE
} else
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 > 0)
process.nextTick(function() { self._send(); });
self._state.isIdle = false;
} else {
// unknown response
}
});
this._state.conn.on('end', function() {
self._reset();
debug('FIN packet received. Disconnecting...');
self.emit('end');
});
this._state.conn.on('error', function(err) {
clearTimeout(self._state.tmrConn);
if (self._state.status === STATES.NOCONNECT)
loginCb(new Error('Unable to connect. Reason: ' + err));
self.emit('error', err);
debug('Error occurred: ' + err);
});
this._state.conn.on('close', function(had_error) {
self._reset();
debug('Connection forcefully closed.');
self.emit('close', had_error);
});
};
ImapConnection.prototype.isAuthenticated = function() {
return this._state.status >= STATES.AUTH;
};
ImapConnection.prototype.logout = function(cb) {
if (this._state.status >= STATES.NOAUTH)
this._send('LOGOUT', cb);
else
throw new Error('Not connected');
};
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 (typeof cb === 'undefined') {
if(typeof readOnly === 'undefined') {
cb = emptyFn;
} else {
cb = readOnly;
}
readOnly = false;
}
this._state.status = STATES.BOXSELECTING;
this._state.box.name = name;
this._send((readOnly ? 'EXAMINE' : 'SELECT') + ' "' + escape(name) + '"', cb);
};
// 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', 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', cb);
};
ImapConnection.prototype.getBoxes = function(namespace, cb) {
cb = arguments[arguments.length-1];
if (arguments.length !== 2)
namespace = '';
this._send('LIST "' + escape(namespace) + '" "*"', 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) {
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('UID SEARCH' + buildSearchQuery(options), cb);
};
ImapConnection.prototype.fetch = function(uids, options) {
if (this._state.status !== STATES.BOXSELECTED)
throw new Error('No mailbox is currently selected');
if (typeof uids === undefined || typeof uids === null
|| (Array.isArray(uids) && uids.length === 0))
throw new Error('Nothing to fetch');
if (!Array.isArray(uids))
uids = [uids];
try {
validateUIDList(uids);
} catch(e) {
throw e;
}
var opts = {
markSeen: false,
request: {
struct: true,
headers: true, // \_______ at most one of these can be used for any given
// _______ fetch request
body: false // /
}
}, toFetch, bodyRange = '', self = this;
if (typeof options !== 'object')
options = {};
extend(true, opts, options);
if (!Array.isArray(opts.request.headers)) {
if (Array.isArray(opts.request.body)) {
var rangeInfo;
if (opts.request.body.length !== 2)
throw new Error("Expected Array of length 2 for body byte range");
else if (typeof opts.request.body[1] !== 'string'
|| !(rangeInfo = /^([\d]+)\-([\d]+)$/.exec(opts.request.body[1]))
|| parseInt(rangeInfo[1]) >= parseInt(rangeInfo[2]))
throw new Error("Invalid body byte range format");
bodyRange = '<' + parseInt(rangeInfo[1]) + '.' + parseInt(rangeInfo[2])
+ '>';
opts.request.body = opts.request.body[0];
}
if (typeof opts.request.headers === 'boolean'
&& opts.request.headers === true) {
// fetches headers only
toFetch = 'HEADER';
} else if (typeof opts.request.body === 'boolean'
&& opts.request.body === true) {
// fetches the whole entire message text (minus the headers), including
// all message parts
toFetch = 'TEXT';
} else if (typeof opts.request.body === 'string') {
if (opts.request.body.toUpperCase() === 'FULL') {
// fetches the whole entire message (including the headers)
toFetch = '';
} else if (/^([\d]+[\.]{0,1})*[\d]+$/.test(opts.request.body)) {
// specific message part identifier, e.g. '1', '2', '1.1', '1.2', etc
toFetch = opts.request.body;
} else
throw new Error("Invalid body partID format");
}
} else {
// fetch specific headers only
toFetch = 'HEADER.FIELDS (' + opts.request.headers.join(' ').toUpperCase()
+ ')';
}
this._send('UID FETCH ' + uids.join(',') + ' (FLAGS INTERNALDATE'
+ (opts.request.struct ? ' BODYSTRUCTURE' : '')
+ (typeof toFetch === 'string' ? ' BODY'
+ (!opts.markSeen ? '.PEEK' : '')
+ '[' + toFetch + ']' + bodyRange : '') + ')', function(e) {
var fetcher = self._state.requests[0]._fetcher;
if (e && fetcher)
fetcher.emit('error', e);
else if (e && !fetcher)
self.emit('error', e);
else if (fetcher)
fetcher.emit('end');
});
var imapFetcher = new ImapFetch();
this._state.requests[this._state.requests.length-1]._fetcher = imapFetcher;
return imapFetcher;
};
ImapConnection.prototype.addFlags = function(uids, flags, cb) {
try {
this._store(uids, flags, true, cb);
} catch (err) {
throw err;
}
};
ImapConnection.prototype.delFlags = function(uids, flags, cb) {
try {
this._store(uids, flags, false, cb);
} catch (err) {
throw err;
}
};
ImapConnection.prototype.addKeywords = function(uids, flags, cb) {
if (!self._state.box._newKeywords)
throw new Error('This mailbox does not allow new keywords to be added');
try {
this._store(uids, flags, true, cb);
} catch (err) {
throw err;
}
};
ImapConnection.prototype.delKeywords = function(uids, flags, cb) {
try {
this._store(uids, flags, false, cb);
} catch (err) {
throw err;
}
};
ImapConnection.prototype.copy = function(uids, boxTo, cb) {
if (this._state.status !== STATES.BOXSELECTED)
throw new Error('No mailbox is currently selected');
if (!Array.isArray(uids))
uids = [uids];
try {
validateUIDList(uids);
} catch(e) {
throw e;
}
this._send('UID COPY ' + uids.join(',') + ' "' + escape(boxTo) + '"', cb);
};
ImapConnection.prototype.move = function(uids, boxTo, cb) {
var self = this;
if (this._state.status !== STATES.BOXSELECTED)
throw new Error('No mailbox is currently selected');
if (self._state.box.permFlags.indexOf('Deleted') === -1) {
throw new Error('Cannot move message: '
+ 'server does not allow deletion of messages');
} else {
self.copy(uids, boxTo, function(err, reentryCount, deletedUIDs, counter) {
if (err) {
cb(err);
return;
}
var fnMe = arguments.callee;
counter = counter || 0;
// Make sure we don't expunge any messages marked as Deleted except the
// one we are moving
if (typeof reentryCount === 'undefined') {
self.search(['DELETED'], function(e, result) {
fnMe.call(this, e, 1, result);
});
} else if (reentryCount === 1) {
if (counter < deletedUIDs.length) {
self.delFlags(deletedUIDs[counter], 'DELETED', function(e) {
process.nextTick(function() {
fnMe.call(this, e, reentryCount, deletedUIDs, counter+1);
});
});
} else
fnMe.call(this, err, reentryCount+1, deletedUIDs);
} else if (reentryCount === 2) {
self.addFlags(uids, 'Deleted', function(e) {
fnMe.call(this, e, reentryCount+1, deletedUIDs);
});
} else if (reentryCount === 3) {
self.removeDeleted(function(e) {
fnMe.call(this, e, reentryCount+1, deletedUIDs);
});
} else if (reentryCount === 4) {
if (counter < deletedUIDs.length) {
self.addFlags(deletedUIDs[counter], 'DELETED', function(e) {
process.nextTick(function() {
fnMe.call(this, e, reentryCount, deletedUIDs, counter+1);
});
});
} else
cb();
}
});
}
};
/****** Private Functions ******/
ImapConnection.prototype._fnTmrConn = function(loginCb) {
loginCb(new Error('Connection timed out'));
this._state.conn.destroy();
}
ImapConnection.prototype._store = function(uids, flags, isAdding, cb) {
var isKeywords = (arguments.callee.caller === this.addKeywords
|| arguments.callee.caller === this.delKeywords);
if (this._state.status !== STATES.BOXSELECTED)
throw new Error('No mailbox is currently selected');
if (typeof uids === 'undefined')
throw new Error('The message ID(s) must be specified');
if (!Array.isArray(uids))
uids = [uids];
try {
validateUIDList(uids);
} catch(e) {
throw e;
}
if ((!Array.isArray(flags) && typeof flags !== 'string')
|| (Array.isArray(flags) && flags.length === 0))
throw new Error((isKeywords ? 'Keywords' : 'Flags')
+ ' argument must be a string or a non-empty Array');
if (!Array.isArray(flags))
flags = [flags];
for (var i=0; i<flags.length; i++) {
if (!isKeywords) {
if (this._state.box.permFlags.indexOf(flags[i]) === -1
|| flags[i] === '\\*' || flags[i] === '*')
throw new Error('The flag "' + flags[i]
+ '" is not allowed by the server for this mailbox');
} else {
// keyword contains any char except control characters (%x00-1F and %x7F)
// and: '(', ')', '{', ' ', '%', '*', '\', '"', ']'
if (/[\(\)\{\\\"\]\%\*\x00-\x20\x7F]/.test(flags[i])) {
throw new Error('The keyword "' + flags[i]
+ '" contains invalid characters');
}
}
}
if (!isKeywords)
flags = flags.map(function(flag) {return '\\' + flag;})
flags = flags.join(' ');
cb = arguments[arguments.length-1];
this._send('UID STORE ' + uids.join(',') + ' ' + (isAdding ? '+' : '-')
+ 'FLAGS.SILENT (' + flags + ')', cb);
};
ImapConnection.prototype._login = function(cb) {
var self = this,
fnReturn = function(err) {
if (!err) {
self._state.status = STATES.AUTH;
if (self._state.numCapRecvs !== 2) {
// fetch post-auth server capabilities if they were not
// automatically provided after login
self._send('CAPABILITY', cb);
return;
}
}
cb(err);
};
if (this._state.status === STATES.NOAUTH) {
if (typeof this._state.capabilities.LOGINDISABLED !== 'undefined') {
cb(new Error('Logging in is disabled on this server'));
return;
}
//if (typeof this._state.capabilities['AUTH=PLAIN'] !== 'undefined') {
this._send('LOGIN "' + escape(this._options.username) + '" "'
+ escape(this._options.password) + '"', fnReturn);
/*} else {
cb(new Error('Unsupported authentication mechanism(s) detected. '
+ 'Unable to login.'));
return;
}*/
}
};
ImapConnection.prototype._reset = function() {
clearTimeout(this._state.tmrKeepalive);
clearTimeout(this._state.tmrConn);
this._state.status = STATES.NOCONNECT;
this._state.numCapRecvs = 0;
this._state.requests = [];
this._state.capabilities = [];
this._state.isIdle = true;
this._state.isReady = false;
this.namespaces = { personal: [], other: [], shared: [] };
this.delim = null;
this._resetBox();
};
ImapConnection.prototype._resetBox = function() {
this._state.box._uidnext = 0;
this._state.box.validity = 0;
this._state.box._flags = [];
this._state.box._newKeywords = false;
this._state.box.permFlags = [];
this._state.box.keywords = [];
this._state.box.name = null;
this._state.box.messages.total = 0;
this._state.box.messages.new = 0;
};
ImapConnection.prototype._noop = function() {
if (this._state.status >= STATES.AUTH)
this._send('NOOP');
};
ImapConnection.prototype._send = function(cmdstr, cb, bypass) {
if (typeof cmdstr !== 'undefined' && !bypass)
this._state.requests.push({ command: cmdstr, callback: cb, args: [] });
if ((typeof cmdstr === 'undefined' && this._state.requests.length) ||
this._state.requests.length === 1 || bypass) {
var prefix = '', cmd = (bypass ? cmdstr : this._state.requests[0].command);
clearTimeout(this._state.tmrKeepalive);
if (this._state.ext.idle.sentIdle && cmd !== 'DONE') {
this._send('DONE', undefined, true);
this._state.ext.idle.sentIdle = false;
this._state.ext.idle.timeWaited = 0;
return;
} else if (cmd === 'IDLE') {
// we use a different prefix to differentiate and disregard the tagged
// response the server will send us when we issue DONE
prefix = 'IDLE ';
this._state.ext.idle.sentIdle = true;
}
if (cmd !== 'IDLE' && cmd !== 'DONE')
prefix = 'A' + ++this._state.curId + ' ';
this._state.conn.cleartext.write(prefix + cmd + CRLF);
debug('\n<<SENT>>: ' + prefix + cmd + '\n');
}
};
function ImapMessage() {}
util.inherits(ImapMessage, EventEmitter);
function ImapFetch() {}
util.inherits(ImapFetch, EventEmitter);
/****** Utility Functions ******/
function buildSearchQuery(options, isOrChild) {
var searchargs = '',
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
'Oct', 'Nov', 'Dec'];
for (var i=0,len=options.length; i<len; i++) {
var criteria = (isOrChild ? options : options[i]),
args = null,
modifier = (isOrChild ? '' : ' ');
if (typeof criteria === 'string')
criteria = criteria.toUpperCase();
else if (Array.isArray(criteria)) {
if (criteria.length > 1)
args = criteria.slice(1);
if (criteria.length > 0)
criteria = criteria[0].toUpperCase();
} else
throw new Error('Unexpected search option data type. '
+ 'Expected string or array. Got: ' + typeof criteria);
if (criteria === 'OR') {
if (args.length !== 2)
throw new Error('OR must have exactly two arguments');
searchargs += ' OR (' + buildSearchQuery(args[0], true) + ') ('
+ buildSearchQuery(args[1], true) + ')'
} else {
if (criteria[0] === '!') {
modifier += 'NOT ';
criteria = criteria.substr(1);
}
switch(criteria) {
case 'ANSWERED':
case 'DELETED':
case 'DRAFT':
case 'FLAGGED':
case 'NEW':
case 'SEEN':
case 'RECENT':
case 'OLD':
case 'UNANSWERED':
case 'UNDELETED':
case 'UNDRAFT':
case 'UNFLAGGED':
case 'UNSEEN':
searchargs += modifier + criteria;
break;
case 'BCC':
case 'BODY':
case 'CC':
case 'FROM':
case 'SUBJECT':
case 'TEXT':
case 'TO':
if (!args || args.length !== 1)
throw new Error('Incorrect number of arguments for search option: '
+ criteria);
searchargs += modifier + criteria + ' "' + escape(''+args[0]) + '"';
break;
case 'BEFORE':
case 'ON':
case 'SENTBEFORE':
case 'SENTON':
case 'SENTSINCE':
case 'SINCE':
if (!args || args.length !== 1)
throw new Error('Incorrect number of arguments for search option: '
+ criteria);
else if (!(args[0] instanceof Date)) {
if ((args[0] = new Date(args[0])).toString() === 'Invalid Date')
throw new Error('Search option argument must be a Date object'
+ ' or a parseable date string');
}
searchargs += modifier + criteria + ' ' + args[0].getDate() + '-'
+ months[args[0].getMonth()] + '-'
+ args[0].getFullYear();
break;
case 'KEYWORD':
case 'UNKEYWORD':
if (!args || args.length !== 1)