forked from haraka/Haraka
-
Notifications
You must be signed in to change notification settings - Fork 0
/
connection.js
1762 lines (1619 loc) · 57.9 KB
/
connection.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
// a single connection
// node.js built-in libs
var dns = require('dns');
var fs = require('fs');
var net = require('net');
var os = require('os');
var path = require('path');
// npm libs
var ipaddr = require('ipaddr.js');
// Haraka libs
var config = require('./config');
var logger = require('./logger');
var trans = require('./transaction');
var plugins = require('./plugins');
var constants = require('./constants');
var rfc1869 = require('./rfc1869');
var Address = require('./address').Address;
var uuid = require('./utils').uuid;
var outbound = require('./outbound');
var date_to_str = require('./utils').date_to_str;
var indexOfLF = require('./utils').indexOfLF;
var ResultStore = require('./result_store');
var hostname = (os.hostname().split(/\./))[0];
var version = JSON.parse(
fs.readFileSync(path.join(__dirname, 'package.json'))).version;
var line_regexp = /^([^\n]*\n)/;
var connection = exports;
var states = exports.states = {
STATE_CMD: 1,
STATE_LOOP: 2,
STATE_DATA: 3,
STATE_PAUSE: 4,
STATE_PAUSE_SMTP: 5,
STATE_PAUSE_DATA: 6,
STATE_DISCONNECTING: 99,
STATE_DISCONNECTED: 100,
};
// copy logger methods into Connection:
for (var key in logger) {
if (!/^log\w/.test(key)) continue;
Connection.prototype[key] = (function (key) {
return function () {
// pass the connection instance to logger
var args = [ this ];
for (var i=0, l=arguments.length; i<l; i++) {
args.push(arguments[i]);
}
logger[key].apply(logger, args);
};
})(key);
}
// Load HAProxy hosts into an object for fast lookups
// as this list is checked on every new connection.
var haproxy_hosts_ipv4 = [];
var haproxy_hosts_ipv6 = [];
function loadHAProxyHosts() {
var hosts = config.get('haproxy_hosts', 'list', loadHAProxyHosts);
var new_ipv4_hosts = [];
var new_ipv6_hosts = [];
for (var i=0; i<hosts.length; i++) {
var host = hosts[i].split(/\//);
if (net.isIPv6(host[0])) {
new_ipv6_hosts[i] =
[ipaddr.IPv6.parse(host[0]), parseInt(host[1] || 64)];
}
else {
new_ipv4_hosts[i] =
[ipaddr.IPv4.parse(host[0]), parseInt(host[1] || 32)];
}
}
haproxy_hosts_ipv4 = new_ipv4_hosts;
haproxy_hosts_ipv6 = new_ipv6_hosts;
}
loadHAProxyHosts();
function setupClient(self) {
var ip = self.client.remoteAddress;
if (!ip) {
self.logdebug('setupClient got no IP address for this connection!');
self.client.destroy();
return;
}
var local_addr = self.server.address();
if (local_addr && local_addr.address) {
self.local_ip = ipaddr.process(local_addr.address).toString();
self.local_port = local_addr.port;
}
self.remote_ip = ipaddr.process(ip).toString();
self.remote_port = self.client.remotePort;
self.lognotice('connect ip=' + self.remote_ip +
' port=' + self.remote_port +
' local_ip=' + self.local_ip + ' local_port=' + self.local_port);
var rhost = 'client ' + ((self.remote_host) ? self.remote_host + ' ' : '') +
'[' + self.remote_ip + ']';
self.client.on('end', function() {
if (self.state >= states.STATE_DISCONNECTING) return;
self.remote_close = true;
self.loginfo(rhost + ' half closed connection');
self.fail();
});
self.client.on('close', function(has_error) {
if (self.state >= states.STATE_DISCONNECTING) return;
self.remote_close = true;
self.loginfo(rhost + ' dropped connection');
self.fail();
});
self.client.on('error', function (err) {
if (self.state >= states.STATE_DISCONNECTING) return;
self.loginfo(rhost + ' connection error: ' + err);
self.fail();
});
self.client.on('timeout', function () {
if (self.state >= states.STATE_DISCONNECTING) return;
self.respond(421, 'timeout', function () {
self.fail(rhost + ' connection timed out');
});
});
self.client.on('data', function (data) {
self.process_data(data);
});
var ha_list = net.isIPv6(self.remote_ip) ?
haproxy_hosts_ipv6
: haproxy_hosts_ipv4;
if (ha_list.some(function (element, index, array) {
return ipaddr.parse(self.remote_ip).match(element[0], element[1]);
})) {
self.proxy = true;
// Wait for PROXY command
self.proxy_timer = setTimeout(function () {
self.respond(421, 'PROXY timeout', function () {
self.disconnect();
});
}, 30 * 1000);
}
else {
plugins.run_hooks('connect_init', self);
}
}
function Connection(client, server) {
this.client = client;
this.server = server;
this.local_ip = null;
this.local_port = null;
this.remote_ip = null;
this.remote_host = null;
this.remote_port = null;
this.remote_info = null;
this.current_data = null;
this.current_line = null;
this.greeting = null;
this.hello_host = null;
this.using_tls = server.has_tls ? true : false;
this.state = states.STATE_PAUSE;
this.prev_state = null;
this.loop_code = null;
this.loop_msg = null;
this.uuid = uuid();
this.notes = {};
this.transaction = null;
this.tran_count = 0;
this.capabilities = null;
this.banner_includes_uuid =
config.get('banner_includes_uuid') ? true : false;
this.deny_includes_uuid = config.get('deny_includes_uuid') || null;
this.early_talker = false;
this.pipelining = false;
this.relaying = false;
this.esmtp = false;
this.last_response = null;
this.remote_close = false;
this.hooks_to_run = [];
this.start_time = Date.now();
this.last_reject = '';
this.max_bytes = config.get('databytes');
this.totalbytes = 0;
this.rcpt_count = {
accept: 0,
tempfail: 0,
reject: 0,
};
this.msg_count = {
accept: 0,
tempfail: 0,
reject: 0,
};
this.proxy = false;
this.proxy_timer = false;
this.max_line_length = config.get('max_line_length') || 512;
this.max_data_line_length = config.get('max_data_line_length') || 992;
this.results = new ResultStore(this);
this.errors = 0;
this.last_rcpt_msg = null;
this.hook = null;
this.haproxy_ip = null;
setupClient(this);
}
exports.Connection = Connection;
exports.createConnection = function(client, server) {
var s = new Connection(client, server);
return s;
};
Connection.prototype.process_line = function (line) {
var self = this;
if (this.state >= states.STATE_DISCONNECTING) {
if (logger.would_log(logger.LOGPROTOCOL)) {
this.logprotocol("C: (after-disconnect): " +
this.current_line + ' state=' + this.state);
}
this.loginfo("data after disconnect from " + this.remote_ip);
return;
}
if (this.state === states.STATE_DATA) {
if (logger.would_log(logger.LOGDATA)) {
this.logdata("C: " + line);
}
this.accumulate_data(line);
return;
}
this.current_line = line.toString('binary').replace(/\r?\n/, '');
if (logger.would_log(logger.LOGPROTOCOL)) {
this.logprotocol("C: " + this.current_line + ' state=' + this.state);
}
// Check for non-ASCII characters
if (/[^\x00-\x7F]/.test(this.current_line)) {
// See if this is a TLS handshake
var buf = new Buffer(this.current_line.substr(0,3), 'binary');
if (buf[0] === 0x16 && buf[1] === 0x03 &&
(buf[2] === 0x00 || buf[2] === 0x01)) // SSLv3/TLS1.x format
{
// Nuke the current input buffer to prevent processing further input
this.current_data = null;
this.respond(501, 'SSL attempted over a non-SSL socket');
this.disconnect();
return;
}
else {
return this.respond(501, 'Syntax error (8-bit characters not allowed)');
}
}
if (this.state === states.STATE_CMD) {
this.state = states.STATE_PAUSE_SMTP;
var matches = /^([^ ]*)( +(.*))?$/.exec(this.current_line);
if (!matches) {
return plugins.run_hooks('unrecognized_command',
this, this.current_line);
}
var method = "cmd_" + matches[1].toLowerCase();
var remaining = matches[3] || '';
if (this[method]) {
try {
this[method](remaining);
}
catch (err) {
if (err.stack) {
var c = this;
c.logerror(method + " failed: " + err);
err.stack.split("\n").forEach(c.logerror);
}
else {
this.logerror(method + " failed: " + err);
}
this.respond(421, "Internal Server Error", function() {
self.disconnect();
});
}
}
else {
// unrecognised command
matches.splice(0,1);
matches.splice(1,1);
plugins.run_hooks('unrecognized_command', this, matches);
}
}
else if (this.state === states.STATE_LOOP) {
// Allow QUIT
if (this.current_line.toUpperCase() === 'QUIT') {
this.cmd_quit();
}
else {
this.respond(this.loop_code, this.loop_msg);
}
}
else {
throw new Error('unknown state ' + this.state);
}
};
Connection.prototype.process_data = function (data) {
if (this.state >= states.STATE_DISCONNECTING) {
this.logwarn("data after disconnect from " + this.remote_ip);
return;
}
if (!this.current_data || !this.current_data.length) {
this.current_data = data;
}
else {
// Data left over in buffer
var buf = Buffer.concat(
[ this.current_data, data ],
(this.current_data.length + data.length)
);
this.current_data = buf;
}
this._process_data();
};
Connection.prototype._process_data = function() {
var self = this;
// We *must* detect disconnected connections here as the state
// only transitions to states.STATE_CMD in the respond function below.
// Otherwise if multiple commands are pipelined and then the
// connection is dropped; we'll end up in the function forever.
if (this.state >= states.STATE_DISCONNECTING) return;
var maxlength;
if (this.state === states.STATE_PAUSE_DATA || this.state === states.STATE_DATA) {
maxlength = this.max_data_line_length;
}
else {
maxlength = this.max_line_length;
}
var offset;
while (this.current_data && ((offset = indexOfLF(this.current_data, maxlength)) !== -1)) {
if (this.state === states.STATE_PAUSE_DATA) {
return;
}
var this_line = this.current_data.slice(0, offset+1);
// Hack: bypass this code to allow HAProxy's PROXY extension
if (this.state === states.STATE_PAUSE && this.proxy && /^PROXY /.test(this_line)) {
if (this.proxy_timer) clearTimeout(this.proxy_timer);
this.state = states.STATE_CMD;
this.current_data = this.current_data.slice(this_line.length);
this.process_line(this_line);
}
// Detect early_talker but allow PIPELINING extension (ESMTP)
else if ((this.state === states.STATE_PAUSE || this.state === states.STATE_PAUSE_SMTP) && !this.esmtp) {
// Allow EHLO/HELO to be pipelined with PROXY
if (this.proxy && /^(?:EH|HE)LO /i.test(this_line)) return;
if (!this.early_talker) {
this_line = this_line.toString().replace(/\r?\n/,'');
this.logdebug('[early_talker] state=' + this.state + ' esmtp=' + this.esmtp + ' line="' + this_line + '"');
}
this.early_talker = true;
self._process_data();
break;
}
else if ((this.state === states.STATE_PAUSE || this.state === states.STATE_PAUSE_SMTP) && this.esmtp) {
var valid = true;
var cmd = this_line.toString('ascii').slice(0,4).toUpperCase();
switch (cmd) {
case 'RSET':
case 'MAIL':
case 'SEND':
case 'SOML':
case 'SAML':
case 'RCPT':
// These can be anywhere in the group
break;
default:
// Anything else *MUST* be the last command in the group
if (this_line.length !== this.current_data.length) {
valid = false;
}
break;
}
if (valid) {
// Valid PIPELINING
// We *don't want to process this yet otherwise the
// current_data buffer will be lost. The respond()
// function will call this function again once it
// has reset the state back to states.STATE_CMD and this
// ensures that we only process one command at a
// time.
this.pipelining = true;
this.logdebug('pipeline: ' + this_line);
}
else {
// Invalid pipeline sequence
// Treat this as early talker
if (!this.early_talker) {
this.logdebug('[early_talker] state=' + this.state +
' esmtp=' + this.esmtp + ' line="' + this_line + '"');
}
this.early_talker = true;
self._process_data();
}
break;
}
else {
this.current_data = this.current_data.slice(this_line.length);
this.process_line(this_line);
}
}
if (this.current_data && (this.current_data.length > maxlength) &&
(indexOfLF(this.current_data, maxlength) === -1)) {
if (this.state !== states.STATE_DATA &&
this.state !== states.STATE_PAUSE_DATA)
{
// In command mode, reject:
this.client.pause();
this.current_data = null;
return this.respond(521, "Command line too long", function () {
self.disconnect();
});
}
else {
this.loginfo('DATA line length (' + this.current_data.length + ') exceeds limit of ' + maxlength + ' bytes');
this.transaction.notes.data_line_length_exceeded = true;
var b = Buffer.concat([
this.current_data.slice(0, maxlength - 2),
new Buffer("\r\n ", 'utf8'),
this.current_data.slice(maxlength - 2)
], this.current_data.length + 3);
this.current_data = b;
return this._process_data();
}
}
};
Connection.prototype.respond = function(code, msg, func) {
var uuid = '';
var messages;
if (this.state === states.STATE_DISCONNECTED) {
if (func) func();
return;
}
// Check to see if DSN object was passed in
if (typeof msg === 'object' && msg.constructor.name === 'DSN') {
// Override
code = msg.code;
msg = msg.reply;
}
if (!(Array.isArray(msg))) {
// msg not an array, make it so:
messages = msg.toString().split(/\n/).filter(function (msg) {
return /\S/.test(msg);
});
} else {
// copy
messages = msg.slice().filter(function (msg) { return /\S/.test(msg);});
}
if (code >= 400) {
this.last_reject = code + ' ' + messages.join(' ');
if (this.deny_includes_uuid) {
uuid = (this.transaction || this).uuid;
if (this.deny_includes_uuid > 1) {
uuid = uuid.substr(0, this.deny_includes_uuid);
}
}
}
var mess;
var buf = '';
while (mess = messages.shift()) {
var line = code + (messages.length ? "-" : " ") +
(uuid ? '[' + uuid + '@' + hostname + '] ' : '' ) + mess;
this.logprotocol("S: " + line);
buf = buf + line + "\r\n";
}
try {
this.client.write(buf);
}
catch (err) {
return this.fail("Writing response: " + buf + " failed: " + err);
}
// Store the last response
this.last_response = buf;
// Don't change loop state
if (this.state !== states.STATE_LOOP) {
this.state = states.STATE_CMD;
}
// Run optional closure before handling and further commands
if (func) func();
// Process any buffered commands (PIPELINING)
this._process_data();
};
Connection.prototype.fail = function (err) {
if (err) this.logwarn(err);
this.hooks_to_run = [];
this.disconnect();
};
Connection.prototype.disconnect = function() {
if (this.state >= states.STATE_DISCONNECTING) return;
var self = this;
self.state = states.STATE_DISCONNECTING;
this.reset_transaction(function () {
plugins.run_hooks('disconnect', self);
});
};
Connection.prototype.disconnect_respond = function () {
var logdetail = [
'ip=' + this.remote_ip,
'rdns="' + ((this.remote_host) ? this.remote_host : '') + '"',
'helo="' + ((this.hello_host) ? this.hello_host : '') + '"',
'relay=' + (this.relaying ? 'Y' : 'N'),
'early=' + (this.early_talker ? 'Y' : 'N'),
'esmtp=' + (this.esmtp ? 'Y' : 'N'),
'tls=' + (this.using_tls ? 'Y' : 'N'),
'pipe=' + (this.pipelining ? 'Y' : 'N'),
'errors='+ this.errors,
'txns=' + this.tran_count,
'rcpts=' + this.rcpt_count.accept + '/' +
this.rcpt_count.tempfail + '/' +
this.rcpt_count.reject,
'msgs=' + this.msg_count.accept + '/' +
this.msg_count.tempfail + '/' +
this.msg_count.reject,
'bytes=' + this.totalbytes,
'lr="' + ((this.last_reject) ? this.last_reject : '') + '"',
'time=' + (Date.now() - this.start_time)/1000,
];
this.lognotice('disconnect ' + logdetail.join(' '));
this.state = states.STATE_DISCONNECTED;
this.client.end();
};
Connection.prototype.get_capabilities = function() {
var capabilities = [];
return capabilities;
};
Connection.prototype.tran_uuid = function () {
this.tran_count++;
return this.uuid + '.' + this.tran_count;
};
Connection.prototype.reset_transaction = function(cb) {
if (this.transaction && this.transaction.resetting === false) {
this.transaction.resetting = true;
plugins.run_hooks('reset_transaction', this, cb);
}
else {
this.transaction = null;
if (cb) cb();
}
};
Connection.prototype.reset_transaction_respond = function (retval, msg, cb) {
if (this.transaction) {
this.transaction.message_stream.destroy();
this.transaction = null;
}
if (cb) cb();
};
Connection.prototype.init_transaction = function(cb) {
var self = this;
this.reset_transaction(function () {
self.transaction = trans.createTransaction(self.tran_uuid());
// Catch any errors from the message_stream
self.transaction.message_stream.on('error', function (err) {
self.logcrit('message_stream error: ' + err.message);
self.respond('421', 'Internal Server Error', function () {
self.disconnect();
});
});
self.transaction.results = new ResultStore(self);
if (cb) cb();
});
};
Connection.prototype.loop_respond = function (code, msg) {
if (this.state >= states.STATE_DISCONNECTING) return;
this.state = states.STATE_LOOP;
this.loop_code = code;
this.loop_msg = msg;
this.respond(code, msg);
};
Connection.prototype.pause = function () {
var self = this;
if (self.state >= states.STATE_DISCONNECTING) return;
self.client.pause();
if (self.state !== states.STATE_PAUSE_DATA) self.prev_state = self.state;
self.state = states.STATE_PAUSE_DATA;
};
Connection.prototype.resume = function () {
var self = this;
if (self.state >= states.STATE_DISCONNECTING) return;
self.client.resume();
if (self.prev_state) {
self.state = self.prev_state;
self.prev_state = null;
}
process.nextTick(function () { self._process_data();});
};
/////////////////////////////////////////////////////////////////////////////
// SMTP Responses
Connection.prototype.connect_init_respond = function (retval, msg) {
// retval and message are ignored
this.logdebug('running connect_init_respond');
plugins.run_hooks('lookup_rdns', this);
};
Connection.prototype.lookup_rdns_respond = function (retval, msg) {
var self = this;
switch (retval) {
case constants.ok:
this.remote_host = msg || 'Unknown';
this.remote_info = this.remote_info || this.remote_host;
plugins.run_hooks('connect', this);
break;
case constants.deny:
this.loop_respond(554, msg || "rDNS Lookup Failed");
break;
case constants.denydisconnect:
case constants.disconnect:
this.respond(554, msg || "rDNS Lookup Failed", function () {
self.disconnect();
});
break;
case constants.denysoft:
this.loop_respond(421, msg || "rDNS Temporary Failure");
break;
case constants.denysoftdisconnect:
this.respond(421, msg || "rDNS Temporary Failure", function () {
self.disconnect();
});
break;
default:
dns.reverse(this.remote_ip, function(err, domains) {
self.rdns_response(err, domains);
});
}
};
Connection.prototype.rdns_response = function (err, domains) {
if (err) {
switch (err.code) {
case dns.NXDOMAIN: this.remote_host = 'NXDOMAIN'; break;
default: this.remote_host = 'DNSERROR'; break;
}
}
else {
this.remote_host = domains[0] || 'Unknown';
}
this.remote_info = this.remote_info || this.remote_host;
plugins.run_hooks('connect', this);
};
Connection.prototype.unrecognized_command_respond = function(retval, msg) {
var self = this;
switch (retval) {
case constants.ok:
// response already sent, cool...
break;
case constants.next_hook:
plugins.run_hooks(msg, this);
break;
case constants.deny:
this.respond(500, msg || "Unrecognized command");
break;
case constants.denydisconnect:
this.respond(521, msg || "Unrecognized command", function () {
self.disconnect();
});
break;
default:
this.errors++;
this.respond(500, msg || "Unrecognized command");
}
};
Connection.prototype.connect_respond = function(retval, msg) {
var self = this;
// RFC 5321 Section 4.3.2 states that the only valid SMTP codes here are:
// 220 = Service ready
// 554 = Transaction failed (no SMTP service here)
// 421 = Service shutting down and closing transmission channel
switch (retval) {
case constants.deny:
this.loop_respond(554, msg || "Your mail is not welcome here");
break;
case constants.denydisconnect:
case constants.disconnect:
this.respond(554, msg || "Your mail is not welcome here", function() {
self.disconnect();
});
break;
case constants.denysoft:
this.loop_respond(421, msg || "Come back later");
break;
case constants.denysoftdisconnect:
this.respond(421, msg || "Come back later", function() {
self.disconnect();
});
break;
default:
var greeting = config.get('smtpgreeting', 'list');
if (greeting.length) {
// RFC5321 section 4.2
// Hostname/domain should appear after the 220
greeting[0] = config.get('me') + ' ESMTP ' + greeting[0];
if (this.banner_includes_uuid) {
greeting[0] += ' (' + this.uuid + ')';
}
}
else {
greeting = config.get('me') + " ESMTP Haraka " + version + " ready";
if (this.banner_includes_uuid) {
greeting += ' (' + this.uuid + ')';
}
}
this.respond(220, msg || greeting);
}
};
Connection.prototype.helo_respond = function(retval, msg) {
var self = this;
switch (retval) {
case constants.deny:
this.respond(550, msg || "HELO denied", function() {
self.greeting = null;
self.hello_host = null;
});
break;
case constants.denydisconnect:
this.respond(550, msg || "HELO denied", function() {
self.disconnect();
});
break;
case constants.denysoft:
this.respond(450, msg || "HELO denied", function() {
self.greeting = null;
self.hello_host = null;
});
break;
case constants.denysoftdisconnect:
this.respond(450, msg || "HELO denied", function() {
self.disconnect();
});
break;
default:
// RFC5321 section 4.1.1.1
// Hostname/domain should appear after 250
this.respond(250, config.get('me') + " Hello " +
((this.remote_host && this.remote_host !== 'DNSERROR' &&
this.remote_host !== 'NXDOMAIN') ? this.remote_host + ' ' : '') +
"[" + this.remote_ip + "]" +
", Haraka is at your service.");
}
};
Connection.prototype.ehlo_respond = function(retval, msg) {
var self = this;
switch (retval) {
case constants.deny:
this.respond(550, msg || "EHLO denied", function() {
self.greeting = null;
self.hello_host = null;
});
break;
case constants.denydisconnect:
this.respond(550, msg || "EHLO denied", function() {
self.disconnect();
});
break;
case constants.denysoft:
this.respond(450, msg || "EHLO denied", function() {
self.greeting = null;
self.hello_host = null;
});
break;
case constants.denysoftdisconnect:
this.respond(450, msg || "EHLO denied", function () {
self.disconnect();
});
break;
default:
// RFC5321 section 4.1.1.1
// Hostname/domain should appear after 250
var response = [config.get('me') + " Hello " +
((this.remote_host && this.remote_host !== 'DNSERROR' &&
this.remote_host !== 'NXDOMAIN') ? this.remote_host + ' ' : '') +
"[" + this.remote_ip + "]" +
", Haraka is at your service.",
"PIPELINING",
"8BITMIME",
];
var databytes = parseInt(config.get('databytes')) || 0;
response.push("SIZE " + databytes);
this.capabilities = response;
plugins.run_hooks('capabilities', this);
this.esmtp = true;
}
};
Connection.prototype.capabilities_respond = function (retval, msg) {
this.respond(250, this.capabilities);
};
Connection.prototype.quit_respond = function(retval, msg) {
var self = this;
this.respond(221, msg || config.get('me') + " closing connection. Have a jolly good day.", function() {
self.disconnect();
});
};
Connection.prototype.vrfy_respond = function(retval, msg) {
var self = this;
switch (retval) {
case constants.deny:
this.respond(550, msg || "Access Denied", function() {
self.reset_transaction();
});
break;
case constants.denydisconnect:
this.respond(550, msg || "Access Denied", function() {
self.disconnect();
});
break;
case constants.denysoft:
this.respond(450, msg || "Lookup Failed", function() {
self.reset_transaction();
});
break;
case constants.denysoftdisconnect:
this.respond(450, msg || "Lookup Failed", function() {
self.disconnect();
});
break;
case constants.ok:
this.respond(250, msg || "User OK");
break;
default:
this.respond(252, "Just try sending a mail and we'll see how it turns out...");
}
};
Connection.prototype.noop_respond = function(retval, msg) {
var self = this;
switch (retval) {
case constants.deny:
this.respond(500, msg || "Stop wasting my time");
break;
case constants.denydisconnect:
this.respond(500, msg || "Stop wasting my time", function() {
self.disconnect();
});
break;
default:
this.respond(250, "OK");
}
};
Connection.prototype.rset_respond = function(retval, msg) {
// We ignore any plugin responses
var self = this;
this.respond(250, "OK", function() {
self.reset_transaction();
});
};
Connection.prototype.mail_respond = function(retval, msg) {
var self = this;
if (!this.transaction) {
this.logerror("mail_respond found no transaction!");
return;
}
var sender = this.transaction.mail_from;
var dmsg = "sender " + sender.format();
this.lognotice(dmsg + ' ' + [
'code=' + constants.translate(retval),
'msg="' + (msg || '') + '"',
].join(' '));
function store_results (action) {
var addr = sender.format();
if (addr.length > 2) { // all but null sender
addr = addr.substr(1, addr.length -2); // trim off < >
}
var res_as = {name: 'mail_from'};
self.transaction.results.add(res_as, {address: addr});
if (action !== 'accept') {
self.transaction.results.add(res_as, {
fail: msg,
code: constants.translate(retval),
});
}
}
switch (retval) {
case constants.deny:
this.respond(550, msg || dmsg + " denied", function() {
store_results('reject');
self.reset_transaction();
});
break;
case constants.denydisconnect:
this.respond(550, msg || dmsg + " denied", function() {
store_results('reject');
self.disconnect();
});
break;
case constants.denysoft:
this.respond(450, msg || dmsg + " denied", function() {
store_results('tempfail');
self.reset_transaction();
});
break;
case constants.denysoftdisconnect:
this.respond(450, msg || dmsg + " denied", function() {
store_results('tempfail');
self.disconnect();
});
break;
default:
store_results('accept');
this.respond(250, msg || dmsg + " OK");
}
};
Connection.prototype.rcpt_incr = function(rcpt, action, msg, retval) {
this.transaction.rcpt_count[action]++;
this.rcpt_count[action]++;
var addr = rcpt.format();
var recipient = {
address: addr.substr(1, addr.length -2),
};
if (msg && action !== 'accept') {
recipient.msg = msg;
recipient.code = constants.translate(retval);
recipient.action = action;
}
this.transaction.results.push({name: 'rcpt_to'}, {
recipient: recipient,
});
};
Connection.prototype.rcpt_ok_respond = function (retval, msg) {
var self = this;
if (!this.transaction) {
this.results.add(this, {err: 'rcpt_ok_respond found no transaction'});
return;
}
if (!msg) msg = this.last_rcpt_msg;
var rcpt = this.transaction.rcpt_to[this.transaction.rcpt_to.length - 1];
var dmsg = "recipient " + rcpt.format();
// Log OK instead of CONT as this hook only runs if hook_rcpt returns OK
this.lognotice(dmsg + ' ' + [
'code=' + constants.translate((retval === constants.cont ? constants.ok : retval)),
'msg="' + (msg || '') + '"',
'sender="' + this.transaction.mail_from.address() + '"',
].join(' '));
switch (retval) {
case constants.deny:
this.respond(550, msg || dmsg + " denied", function() {
self.rcpt_incr(rcpt, 'reject', msg, retval);
self.transaction.rcpt_to.pop();