-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimapservice.js
2338 lines (2157 loc) · 56.1 KB
/
imapservice.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
/*
* IMAP Server... whee!
* Refer to RFC 3501
*
* Copyright 2009, Stephen Hurd.
* Don't steal my code bitches.
*
* $Id: imapservice.js,v 1.74 2020/04/28 06:16:10 deuce Exp $
*/
load("sbbsdefs.js");
load("822header.js");
load("mime.js");
var sepchar="|";
var debug=false;
var debugRX=false;
// Global variables
const UnAuthenticated=0;
const Authenticated=1;
const Selected=2;
var state=UnAuthenticated;
var base;
var index={offsets:[],idx:{}};
var line;
var readonly=true;
var orig_ptrs={};
var msg_ptrs={};
var curr_status={exists:0,recent:0,unseen:0,uidnext:0,uidvalidity:0};
var saved_config={mail:{scan_ptr:0}};
var scan_ptr;
var cfgfile;
/**********************/
/* Encoding functions */
/**********************/
/*
* These encode at least as is passed (token/string/binary)
*/
function encode_binary(str)
{
return '{'+str.length+'}\r\n'+str;
}
function encode_string(str)
{
if(str=='')
return('""');
if(str.search(/[\r\n\x80-\xff]/)==-1) {
str=str.replace(/([\\\"])/g, "\\$1");
return '"'+str+'"';
}
return encode_binary(str);
}
function encode_token(str)
{
if(str=='')
return(encode_string(str));
if(str.search(/[\(\)\{ \x00-\x1F\*\%\"\\\]]/)==-1)
return str;
return(encode_string(str));
}
/*****************************/
/* Message header extensions */
/*****************************/
MsgBase.HeaderPrototype.get_from=function (force)
{
if(force===true)
delete this.from_header;
if(this.from_header==undefined) {
if(!this.from_net_type || this.from_net_addr.length==0) /* local message */
this.from_header = this.from + " <" + this.from.replace(/ /g,".").toLowerCase() + "@" + system.inetaddr + ">";
else if(!this.from_net_addr.length)
this.from_header = this.from;
else if(this.from_net_addr.indexOf('@')!=-1)
this.from_header = this.from+" <"+this.from_net_addr+">";
else
this.from_header = this.from+" <"+this.from.replace(/ /g,".").toLowerCase()+"@"+this.from_net_addr+">";
}
return(this.from_header);
};
MsgBase.HeaderPrototype.parse_headers=function(force)
{
if(force===true)
delete this.parsed_headers;
if(this.parsed_headers==undefined)
this.parsed_headers=parse_headers(this.get_rfc822_header(force));
return(this.parsed_headers);
};
MsgBase.HeaderPrototype.get_envelope=function (force)
{
function parse_header(header, is_addresses) {
var m2;
if(header==undefined || header.length==0)
return("NIL");
header=header.pop().replace(new RegExp("^"+abnf.field_name+abnf.WSP+"*:","i"),"");
header=header.replace(/\r\n$/,'');
header=strip_CFWS(header);
/* TODO: Use mime.js ABNF to parse this correctly */
if(is_addresses) {
if((m2=header.match(/^\s*(.*)\s+<([^@]*)@(.*)>\s*$/))!=null) {
m2[1]=m2[1].replace(/^"(.*)"$/, "$1");
return '(('+[encode_string(m2[1]), "NIL", encode_string(m2[2]), encode_string(m2[3])].join(" ")+'))';
}
else if((m2=header.match(/^\s*(.*)\s+<([^@]*)>\s*$/))!=null) {
m2[1]=m2[1].replace(/^"(.*)"$/, "$1");
return '(('+[encode_string(m2[1]), "NIL", encode_string(m2[2]), "NIL"].join(" ")+'))';
}
else if((m2=header.match(/^\s*<([^@]*)@(.*)>\s*$/))!=null) {
return '(('+["NIL", "NIL", encode_string(m2[1]), encode_string(m2[2])].join(" ")+'))';
}
else if((m2=header.match(/^\s*([^@]*)@(.*)\s*$/))!=null) {
return '(('+["NIL", "NIL", encode_string(m2[1]), encode_string(m2[2])].join(" ")+'))';
}
else
return '(('+[encode_string(header), "NIL", "NIL", "NIL"].join(" ")+'))';
}
else
return(encode_string(header));
}
var hdrs;
if(this.envelope==undefined) {
hdrs=this.parse_headers();
this.envelope=[];
this.envelope.push(parse_header(hdrs.date, false));
this.envelope.push(parse_header(hdrs.subject, false));
this.envelope.push(parse_header(hdrs.from, true));
this.envelope.push(parse_header(hdrs.sender, true));
this.envelope.push(parse_header(hdrs['reply-to'], true));
this.envelope.push(parse_header(hdrs.to, true));
this.envelope.push(parse_header(hdrs.cc, true));
this.envelope.push(parse_header(hdrs.bcc, true));
this.envelope.push(parse_header(hdrs['in-reply-to'], false));
this.envelope.push(parse_header(hdrs['message-id'], false));
}
return(this.envelope);
};
/***********************/
/* Debugging Functions */
/***********************/
function dump_obj(obj, name)
{
var i;
for(i in obj) {
if(typeof(obj[i])=='object')
dump_obj(obj[i], name+'['+i+']');
else
log(name+'['+i+']="'+obj[i]+'"');
}
}
function debug_log(line, rx)
{
if(debug)
log(line);
else if(rx && debugRX)
log(line);
}
/**************/
/* Socket I/O */
/**************/
function tagged(tag, msg, desc)
{
client.socket.send(tag+" "+msg+" "+desc+"\r\n");
debug_log("Send: "+tag+" "+msg+" "+desc, false);
}
function untagged(msg)
{
client.socket.send("* "+msg+"\r\n");
debug_log("Send: * "+msg.length+": "+msg, false);
}
/*************************************************************/
/* Fetch response generation... this is the tricky bit. :-) */
/*************************************************************/
function send_fetch_response(msgnum, fmat, uid)
{
var idx;
var resp='';
var sent_uid=false;
var i,j;
var hdr;
var rfc822={};
var objtype;
var m;
var re;
var tmp;
var sent_flags=false;
var seen_changed=false;
var envelope;
var mime;
var part;
var extension;
var tmp2;
/*
* Most of these functions just diddle variables in this function
*/
function get_header() {
if(hdr == undefined)
hdr=base.get_msg_header(msgnum, /* expand_fields: */false);
/* If that didn't work, make up a minimal useless header */
if (hdr == undefined) {
hdr = Object.create(MsgBase.HeaderPrototype);
hdr.netattr = 0;
hdr.when_imprted_time = 0;
hdr.when_imported_zone_offset = 0;
hdr.from="[email protected]";
hdr.to="[email protected]";
hdr.id="<DELETED>";
hdr.subject="<DELETED>";
hdr.date="<undefined>";
}
}
function get_rfc822_header() {
get_header();
rfc822.header=hdr.get_rfc822_header();
}
function get_rfc822_text() {
if(rfc822.text==undefined)
rfc822.text=base.get_msg_body(msgnum, true, true, true);
if(rfc822.text==undefined)
rfc822.text='';
}
function get_rfc822() {
get_rfc822_header();
get_rfc822_text();
}
function get_mime() {
if(mime==undefined) {
get_rfc822();
mime=parse_message(rfc822.header+rfc822.text);
}
}
function get_rfc822_size() {
get_rfc822();
rfc822.size=rfc822.header.length+rfc822.text.length;
}
/*
* Sets the seen flag on a message
*/
function set_seen_flag() {
if(readonly)
return;
if(base.subnum==-1) {
get_header();
if(!(hdr.attr & MSG_READ)) {
hdr.attr |= MSG_READ;
base.put_msg_header(msgnum, hdr);
index=read_index(base);
hdr=base.get_msg_header(msgnum, /* expand_fields: */false);
if(hdr.attr & MSG_READ)
seen_changed=true;
}
}
else {
lock_cfg();
read_cfg(index.code, false);
if(saved_config[index.code] == undefined)
saved_config[index.code] = {};
if(saved_config[index.code].Seen == undefined)
saved_config[index.code].Seen = {};
if(saved_config[index.code].Seen[msgnum] != 1)
seen_changed=true;
saved_config[index.code].Seen[msgnum]=1;
save_cfg(false);
apply_seen(index);
unlock_cfg();
idx.attr |= MSG_READ;
}
}
// Moves flags to the end...
function sort_format(a,b)
{
if(typeof(a)=='object')
a=0;
else {
if(a.substr(0,5).toUpperCase()=='FLAGS')
a=100;
else
a=0;
}
if(typeof(b)=='object')
b=0;
else {
if(b.substr(0,5).toUpperCase()=='FLAGS')
b=100;
else
b=0;
}
return a-b;
}
function get_mime_part(fmat) {
var m=fmat.match(/^BODY((?:\.PEEK)?)\[([^[\]]*)(?:\]\<([0-9]+)\.([0-9]+)\>)?/i);
var specifiers;
var i;
var tmp;
var part_name='';
function encode_binary_part(start, len, str)
{
if(start==undefined || start=='')
start=0;
else
start=parseInt(start,10);
if(len==undefined || len=='')
len=str.length;
else
len=parseInt(len,10);
return(encode_binary(str.substr(start,len)));
}
part=mime;
if(m==null)
return(undefined);
if(m[1].toUpperCase()!='.PEEK')
set_seen_flag();
part_name='BODY['+m[2]+']';
specifiers=m[2].split('.');
for(i=0; i<specifiers.length; i++) {
tmp=parseInt(specifiers[i], 10);
if(tmp > 0) {
if(part.mime != undefined && part.mime.parts != undefined && part.mime.parts[tmp-1]!=undefined) {
part=part.mime.parts[tmp-1];
}
}
else
break;
}
if(m[3]!=undefined && m[3]!='')
part_name += '<'+m[3]+'>';
switch(specifiers[i]) {
case 'HEADER':
if(specifiers[i+1]!=undefined) {
objtype='BODY['+specifiers.join('.');
return undefined;
}
else
return(part_name+" "+encode_binary_part(m[3],m[4],part.headers['::'].join('')+"\r\n")+' ');
case 'MIME':
return(part_name+" "+encode_binary_part(m[3],m[4],part.headers[':mime:'].join('')+"\r\n")+' ');
case '':
if(specifiers.length==1)
return(part_name+" "+encode_binary_part(m[3],m[4],part.headers['::'].join('')+'\r\n'+part.text)+' ');
// Fall-through
case undefined:
case 'TEXT':
return(part_name+' '+encode_binary_part(m[3],m[4],part.text)+' ');
}
}
function add_part(mime) {
var i;
var ret='(NIL) ';
if (mime.mime.parsed == undefined) {
log(LOG_WARNING, "MIME part was not actually parsed!");
return '';
}
if(mime.mime.parts != undefined) {
for(i in mime.mime.parts)
ret += add_part(mime.mime.parts[i]);
}
else
ret += encode_string(mime.mime.parsed['content-type'].vals[0])+" ";
ret += encode_string(mime.mime.parsed['content-type'].vals[1])+" ";
if(mime.mime.parsed['content-type'].attrs==undefined)
ret += 'NIL ';
else {
ret += '(';
for(i in mime.mime.parsed['content-type'].attrs) {
ret += encode_string(i)+" ";
ret += encode_string(mime.mime.parsed['content-type'].attrs[i])+" ";
}
ret=ret.replace(/ $/, ") ");
}
if(mime.mime.parsed['content-id']==undefined)
ret += 'NIL ';
else
ret += encode_string(mime.mime.parsed['content-id'].vals[0])+' ';
if(mime.mime.parsed['content-description']==undefined)
ret += 'NIL ';
else
ret += encode_string(mime.mime.parsed['content-description'].vals[0])+' ';
if(mime.mime.parsed['content-type'].vals[0]!='multipart') {
if(mime.mime.parsed['content-transfer-encoding']==undefined)
ret += 'NIL ';
else
ret += encode_string(mime.mime.parsed['content-transfer-encoding'].vals[0])+' ';
ret += encode_token(mime.text.length.toString())+' ';
}
if(mime.mime.parsed['content-type'].vals[0]=='text' || mime.mime.parsed['content-type'].vals[0]=='message') {
i=mime.text.split(/\x0d\x0a/);
ret=ret+encode_token(i.length.toString())+' ';
}
if(extension) {
// TODO Add extension data...
}
ret=ret.replace(/ $/, ') ');
return ret;
}
idx=index.idx[msgnum];
resp=idx.offset;
resp += " FETCH (";
fmat=fmat.sort(sort_format);
for(i in fmat) {
/*
* This bit is for when a paremeter includes a list.
* This list will be an object, so we need special handling
*/
if(typeof(fmat[i])=='object') {
// We already handled this I hope...
if(objtype == undefined)
continue;
if(objtype.search(/^BODY\[[0-9.]*HEADER\.FIELDS$/i)==0) {
tmp='';
for(j in fmat[i]) {
if(part.headers[fmat[i][j].toLowerCase()]!=undefined)
tmp += part.headers[fmat[i][j].toLowerCase()];
}
resp += objtype+" ("+fmat[i].join(" ")+")] "+encode_binary(tmp+"\r\n")+" ";
}
if(objtype.search(/^BODY\[[0-9.]*HEADER\.FIELDS\.NOT$/i)==0) {
tmp=eval(part.headers.toSource());
delete tmp['::'];
delete tmp[':mime:'];
for(j in fmat[i]) {
if(tmp[fmat[i][j].toLowerCase()]!=undefined)
delete tmp[fmat[i][j].toLowerCase()];
}
tmp2='';
for(j in tmp)
tmp2 += tmp[j];
resp += objtype+" ("+fmat[i].join(" ")+")] "+encode_binary(tmp2+"\r\n")+" ";
}
continue;
}
/*
* Handle the MIME stuff
*/
if(fmat[i].toUpperCase().substr(0,4)=='BODY') {
get_mime();
if((tmp=get_mime_part(fmat[i].toUpperCase()))==undefined) {
extension=true;
switch(fmat[i].toUpperCase()) {
case 'BODY':
extension=false;
case 'BODYSTRUCTURE':
resp += 'BODYSTRUCTURE '+add_part(mime);
break;
}
}
else
resp += tmp;
}
else {
switch(fmat[i].toUpperCase()) {
case 'FLAGS':
get_header();
resp += "FLAGS ("+calc_msgflags(idx.attr, hdr.netattr, base.subnum, msgnum, readonly)+") ";
sent_flags=true;
break;
case 'UID':
resp += "UID "+idx.number+" ";
sent_uid=true;
break;
case 'INTERNALDATE':
get_header();
resp += 'INTERNALDATE '+strftime('"%d-%b-%Y %H:%M:%S ', hdr.when_imported_time)+format('%+05d" ', hdr.when_imported_zone_offset);
break;
case 'RFC822.SIZE':
get_rfc822_size();
resp += "RFC822.SIZE "+rfc822.size+" ";
break;
case 'RFC822.TEXT':
set_seen_flag();
get_rfc822_text();
resp += fmat[i].replace(/\.PEEK/i,"").toUpperCase()+" "+encode_binary(rfc822.text)+" ";
break;
case 'RFC822.HEADER':
set_seen_flag();
get_rfc822_header();
resp += fmat[i].replace(/\.PEEK/i,"").toUpperCase()+" "+encode_binary(rfc822.header)+" ";
break;
case 'RFC822':
set_seen_flag();
get_rfc822();
resp += fmat[i].replace(/\.PEEK/i,"").toUpperCase()+" "+encode_binary(rfc822.header+rfc822.text)+" ";
break;
case 'ENVELOPE':
set_seen_flag();
get_header();
resp += 'ENVELOPE ('+hdr.get_envelope().join(" ")+') ';
break;
}
}
}
if(seen_changed && !sent_flags) {
get_header();
resp += "FLAGS ("+calc_msgflags(idx.attr, hdr.netattr, base.subnum, msgnum, readonly)+") ";
}
if(uid && !sent_uid)
resp += "UID "+idx.number+" ";
resp=resp.replace(/ $/,'');
resp += ")";
untagged(resp);
js.gc(false);
}
/*
* Parses a data items FETCH parameter for send_fetch_response()
*/
function parse_data_items(obj)
{
if(typeof(obj)=='string') {
switch(obj.toUpperCase()) {
case 'ALL':
obj=["FLAGS","INTERNALDATE","RFC822.SIZE","ENVELOPE"];
break;
case 'FAST':
obj=["FLAGS","INTERNALDATE","RFC822.SIZE"];
break;
case 'FULL':
obj=["FLAGS","INTERNALDATE","RFC822.SIZE","ENVELOPE","BODY"];
break;
default:
obj=[];
}
}
return(obj);
}
/*
* Returns an array of Message Numbers which correspond to the specified sets
*/
function parse_seq_set(set, uid) {
var response=[];
var chunks=set.split(/,/);
var chunk;
var range;
var i;
var max;
var idx;
var msgnum;
if(uid)
max=base.last_msg;
else
max=index.offsets.length;
for(chunk in chunks) {
range=chunks[chunk].split(/:/);
if(range.length == 1)
range.push(range[0]);
if(range[0]=='*')
range[0]=max;
if(range[1]=='*')
range[1]=max;
range[0]=parseInt(range[0],10);
range[1]=parseInt(range[1],10);
if(range[0] > range[1]) {
i=range[0];
range[0]=range[1];
range[1]=i;
}
for(i=range[0]; i<=range[1]; i++) {
msgnum=parseInt(i, 10);
if(!uid)
msgnum=index.offsets[msgnum-1];
if(msgnum==undefined || index.idx[msgnum]==undefined)
continue;
response.push(msgnum);
}
}
response=response.sort(function(a,b) { return a-b; });
for(i=0; i<response.length; i++) {
if(response[i]==response[i+1]) {
response.splice(i+1,1);
i--;
}
}
return(response);
}
function handle_command(command, args, defs)
{
if(defs[command] != undefined) {
if(defs[command].arguments != undefined) {
if(args.length-1 == defs[command].arguments) {
defs[command].handler(args);
return(true);
}
}
else if(defs[command].arguments_valid(args.length-1)) {
defs[command].handler(args);
return(true);
}
}
return false;
}
function parse_command(line)
{
function execute_line(args) {
if(args.length >= 2) {
command=args[1].toUpperCase();
args.splice(1,1);
if(handle_command(command, args, any_state_command_handlers))
return;
switch(state) {
case UnAuthenticated:
if(handle_command(command, args, unauthenticated_command_handlers))
return;
break;
case Authenticated:
if(handle_command(command, args, authenticated_command_handlers))
return;
break;
case Selected:
if(handle_command(command, args, selected_command_handlers))
return;
if(handle_command(command, args, authenticated_command_handlers))
return;
break;
}
}
// Ignore empty lines (Seamonkey sends these...)
if (args.length > 0)
tagged(args[0], "BAD", "Bad dog, no cookie.");
}
function parse_line() {
var at_start=true;
var in_quote=false;
var paren_depth=0;
var string_len;
var args=[];
var pos;
function parse_atom() {
var ret='';
while(line.length) {
switch(line.charAt(0)) {
case ')':
return(ret);
case ' ':
line=line.substr(1);
return(ret);
default:
ret += line.charAt(0);
line=line.substr(1);
break;
}
}
return(ret);
}
function parse_string()
{
var ret='';
line=line.replace(/^{([0-9]+)}$/, "$1");
client.socket.send("+ Give me more of that good stuff\r\n");
ret=client.socket.recv(parseInt(line));
line=client.socket.recvline(10240, 1800);
return(ret);
}
function parse_quotedstring() {
var ret='';
line=line.substr(1); // Remove leading "
while(line.length) {
switch(line.charAt(0)) {
case '"':
line=line.substr(1);
return(ret);
default:
ret += line.charAt(0);
line=line.substr(1);
break;
}
}
return(ret);
}
while(line.length) {
switch(line.charAt(0)) {
case '"':
args.push(parse_quotedstring());
break;
case ')':
line=line.substr(1);
return(args);
case '(':
line=line.substr(1);
args.push(parse_line());
break;
case '{':
args.push(parse_string());
break;
case ' ':
line=line.substr(1);
break;
default:
args.push(parse_atom());
break;
}
}
return(args);
}
send_updates();
return(execute_line(parse_line()));
}
// Command handling functions
var any_state_command_handlers = {
CAPABILITY:{
arguments:0,
handler:function (args) {
var tag=args[0];
if (client.socket.ssl_session)
untagged("CAPABILITY IMAP4rev1 AUTH=CRAM-MD5 AUTH=PLAIN CHILDREN IDLE UNSELECT");
else
untagged("CAPABILITY IMAP4rev1 AUTH=CRAM-MD5 LOGINDISABLED CHILDREN IDLE UNSELECT");
tagged(tag, "OK", "Capability completed, no STARTTLS support... deal with it.");
},
},
NOOP:{
arguments:0,
handler:function(args) {
var tag=args[0];
tagged(tag, "OK", "No operation performed... anything else you'd like me to not do?");
},
},
LOGOUT:{
arguments:0,
handler:function(args) {
var tag=args[0];
untagged("BYE I'll go now");
tagged(tag, "OK", "Thanks for stopping by.");
exit(0);
}
},
IDLE:{ // RFC2177
arguments:0,
handler:function(args) {
var tag=args[0];
var elapsed=0;
client.socket.send("+ Ooo, Idling... my favorite.\r\n");
while(1) {
line=client.socket.recvline(10240, 5);
if(line==null) {
elapsed += 5;
if (js.termianted) {
untagged("BYE server terminated.");
exit(0);
}
if(elapsed > 1800) {
untagged("BYE And I though *I* liked to idle!");
exit(0);
}
update_status();
}
else {
debug_log("DONE IDLE: '"+line+"'", true);
tagged(tag, "OK", "That was fun.");
return;
}
}
}
}
};
var unauthenticated_command_handlers = {
STARTTLS:{
arguments:0,
handler:function(args) {
var tag=args[0];
tagged(tag, "BAD", "I told you to deal with the lack of STARTTLS damnit!");
},
},
AUTHENTICATE:{
arguments:1,
handler:function(args) {
var tag=args[0];
var mechanism=args[1];
var line;
var args;
var challenge;
var un;
var u;
function hmac(k, text) {
var ik='', ok='', i;
var m;
if (k.length > 64)
k = base64_decode(md5_calc(k));
while (k.length < 64)
k = k + '\x00';
for (i=0; i<64; i++) {
ik += ascii(ascii(k[i]) ^ 0x36);
ok += ascii(ascii(k[i]) ^ 0x5C);
}
return md5_calc(ok + base64_decode(md5_calc(ik+text)), true);
}
function setcfg()
{
cfgfile=new File(format(system.data_dir+"user/%04d.imap", user.number));
if (!cfgfile.open(cfgfile.exists ? 'r+':'w+', true, 0)) {
tagged(tag, "NO", "Can't open imap state file");
return;
}
}
if(mechanism.toUpperCase()=="PLAIN") {
if (!client.socket.ssl_session) {
tagged(tag, "NO", "No AUTH for you.");
return;
}
client.socket.send("+\r\n");
line=client.socket.recvline(10240, 1800);
args=base64_decode(line).split(/\x00/);
if(!login(args[1],args[2])) {
tagged(tag, "NO", "No AUTH for you.");
return;
}
setcfg();
tagged(tag, "OK", "Howdy.");
state=Authenticated;
}
else if(mechanism.toUpperCase() == "CRAM-MD5") {
challenge = '<'+random(2147483647)+"."+time()+"@"+system.host_name+'>';
client.socket.send("+ "+base64_encode(challenge)+"\r\n");
line=client.socket.recvline(10240, 1800);
args=base64_decode(line).split(/ /);
un = system.matchuser(args[0], false);
if (un == 0) {
tagged(tag, "NO", "No AUTH for you.");
return;
}
u = new User(un);
if (u.number < 1) {
tagged(tag, "NO", "No AUTH for you.");
return;
}
// First, try as-stored...
if (args[1] === hmac(u.security.password, challenge)) {
setcfg();
login(u.alias, u.security.password);
tagged(tag, "OK", "Howdy.");
state=Authenticated;
return;
}
// Lower-case
if (args[1] === hmac(u.security.password.toLowerCase(), challenge)) {
setcfg();
login(u.alias, u.security.password);
tagged(tag, "OK", "Howdy.");
state=Authenticated;
return;
}
// Upper-case
if (args[1] === hmac(u.security.password.toUpperCase(), challenge)) {
setcfg();
login(u.alias, u.security.password);
tagged(tag, "OK", "Howdy.");
state=Authenticated;
return;
}
tagged(tag, "NO", "No AUTH for you.");
return;
}
else
tagged(tag, "NO", "No "+mechanism+" authenticate supported yet... give me a reason to do it and I'll think about it.");
},
},
LOGIN:{
arguments:2,
handler:function(args) {
var tag=args[0];
var usr=args[1];
var pass=args[2];
if (!client.socket.ssl_session) {
tagged(tag, "NO", "Basic RFC stuff here! A client implementation MUST NOT send a LOGIN command if the LOGINDISABLED capability is advertised.");
return;
}
if(!login(usr, pass)) {
tagged(tag, "NO", "No login for you.");
return;
}
cfgfile=new File(format(system.data_dir+"user/%04d.imap", user.number));
if (!cfgfile.open(cfgfile.exists ? 'r+':'w+', true, 0)) {
tagged(tag, "NO", "Can't open imap state file");
return;
}
tagged(tag, "OK", "Sure, come on in.");
state=Authenticated;
},
}
};
function sendflags(perm)
{
var flags="";
var pflags="";
flags=calc_msgflags(0xffff, 0xffff, base.subnum, base.last_msg, readonly);
pflags=calc_msgflags(0xffff, 0xffff, base.subnum, base.last_msg, readonly);
if(perm)
untagged("OK [PERMANENTFLAGS ("+pflags+")] Overkill!");
else
untagged("FLAGS ("+flags+") Overkill!");
}
function parse_flags(inflags)
{
var i;
var flags={attr:0, netattr:0};
for(i in inflags) {
switch(inflags[i].toUpperCase()) {
case '\\SEEN':
flags.attr |= MSG_READ;
break;
case '\\ANSWERED':
case 'REPLIED':
flags.attr |= MSG_REPLIED;
break;
case '\\FLAGGED':
case 'VALIDATED':
flags.attr |= MSG_VALIDATED;
break;
case '\\DELETED':
case 'DELETE':
flags.attr |= MSG_DELETE;
break;
case 'ANONYMOUS':
flags.attr |= MSG_ANONYMOUS;
break;
case 'KILLREAD':
flags.attr |= MSG_KILLREAD;
break;
case 'MODERATED':