forked from haraka/Haraka
-
Notifications
You must be signed in to change notification settings - Fork 0
/
connection.js
1926 lines (1813 loc) · 68.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
const dns = require('dns');
const fs = require('fs');
const net = require('net');
const os = require('os');
const path = require('path');
// npm libs
const ipaddr = require('ipaddr.js');
const config = require('haraka-config');
const constants = require('haraka-constants');
const net_utils = require('haraka-net-utils');
const Notes = require('haraka-notes');
const utils = require('haraka-utils');
const { Address } = require('address-rfc2821');
const ResultStore = require('haraka-results');
// Haraka libs
const logger = require('./logger');
const trans = require('./transaction');
const plugins = require('./plugins');
const rfc1869 = require('./rfc1869');
const outbound = require('./outbound');
const states = constants.connection.state;
// Load HAProxy hosts into an object for fast lookups
// as this list is checked on every new connection.
let haproxy_hosts_ipv4 = [];
let haproxy_hosts_ipv6 = [];
function loadHAProxyHosts () {
const hosts = config.get('haproxy_hosts', 'list', loadHAProxyHosts);
const new_ipv4_hosts = [];
const new_ipv6_hosts = [];
for (let i=0; i<hosts.length; i++) {
const 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();
class Connection {
constructor (client, server, cfg) {
this.client = client;
this.server = server;
this.cfg = cfg;
this.local = { // legacy property locations
ip: null, // c.local_ip
port: null, // c.local_port
host: net_utils.get_primary_host_name(),
info: 'Haraka',
};
this.remote = {
ip: null, // c.remote_ip
port: null, // c.remote_port
host: null, // c.remote_host
info: null, // c.remote_info
closed: false, // c.remote_closed
is_private: false,
is_local: false,
};
this.hello = {
host: null, // c.hello_host
verb: null, // c.greeting
};
this.tls = {
enabled: false, // c.using_tls
advertised: false, // c.notes.tls_enabled
verified: false,
cipher: {},
};
this.proxy = {
allowed: false, // c.proxy
ip: null, // c.haproxy_ip
type: null,
timer: null, // c.proxy_timer
};
this.set('tls', 'enabled', (!!server.has_tls));
this.current_data = null;
this.current_line = null;
this.state = states.PAUSE;
this.encoding = 'utf8';
this.prev_state = null;
this.loop_code = null;
this.loop_msg = null;
this.uuid = utils.uuid();
this.notes = new Notes();
this.transaction = null;
this.tran_count = 0;
this.capabilities = null;
this.ehlo_hello_message = config.get('ehlo_hello_message') || 'Haraka is at your service.';
this.connection_close_message = config.get('connection_close_message') || 'closing connection. Have a jolly good day.';
this.banner_includes_uuid = !!config.get('banner_includes_uuid');
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.hooks_to_run = [];
this.start_time = Date.now();
this.last_reject = '';
this.max_bytes = parseInt(config.get('databytes')) || 0;
this.max_mime_parts = parseInt(config.get('max_mime_parts')) || 1000;
this.totalbytes = 0;
this.rcpt_count = {
accept: 0,
tempfail: 0,
reject: 0,
};
this.msg_count = {
accept: 0,
tempfail: 0,
reject: 0,
};
this.max_line_length = parseInt(config.get('max_line_length')) || 512;
this.max_data_line_length = parseInt(config.get('max_data_line_length')) || 992;
this.results = new ResultStore(this);
this.errors = 0;
this.last_rcpt_msg = null;
this.hook = null;
if (this.cfg.headers.show_version) {
const hpj = JSON.parse(fs.readFileSync(path.join(__dirname, 'package.json')));
this.local.info += `/${hpj.version}`;
}
Connection.setupClient(this);
}
static setupClient (self) {
const ip = self.client.remoteAddress;
if (!ip) {
self.logdebug('setupClient got no IP address for this connection!');
self.client.destroy();
return;
}
const local_addr = self.server.address();
self.set('local', 'ip', ipaddr.process(self.client.localAddress || local_addr.address).toString());
self.set('local', 'port', (self.client.localPort || local_addr.port));
self.results.add({name: 'local'}, self.local);
self.set('remote', 'ip', ipaddr.process(ip).toString());
self.set('remote', 'port', self.client.remotePort);
self.results.add({name: 'remote'}, self.remote);
self.lognotice( 'connect', {
ip: self.remote.ip,
port: self.remote.port,
local_ip: self.local.ip,
local_port: self.local.port
});
if (!self.client.on) return;
const log_data = {ip: self.remote.ip}
if (self.remote.host) log_data.host = self.remote.host
self.client.on('end', () => {
if (self.state >= states.DISCONNECTING) return;
self.remote.closed = true;
self.loginfo('client half closed connection', log_data);
self.fail();
});
self.client.on('close', has_error => {
if (self.state >= states.DISCONNECTING) return;
self.remote.closed = true;
self.loginfo('client dropped connection', log_data);
self.fail();
});
self.client.on('error', err => {
if (self.state >= states.DISCONNECTING) return;
self.loginfo(`client connection error: ${err}`, log_data);
self.fail();
});
self.client.on('timeout', () => {
// FIN has sent, when timeout just destroy socket
if (self.state >= states.DISCONNECTED) {
self.client.destroy();
self.loginfo(`timeout, destroy socket (state:${self.state})`)
return;
}
if (self.state >= states.DISCONNECTING) return;
self.respond(421, 'timeout', () => {
self.fail('client connection timed out', log_data);
});
});
self.client.on('data', data => {
self.process_data(data);
});
const ha_list = net.isIPv6(self.remote.ip) ? haproxy_hosts_ipv6 : haproxy_hosts_ipv4;
if (ha_list.some((element, index, array) => {
return ipaddr.parse(self.remote.ip).match(element[0], element[1]);
})) {
self.proxy.allowed = true;
// Wait for PROXY command
self.proxy.timer = setTimeout(() => {
self.respond(421, 'PROXY timeout',() => {
self.disconnect();
});
}, 30 * 1000);
}
else {
plugins.run_hooks('connect_init', self);
}
}
setTLS (obj) {
this.set('hello', 'host', undefined);
this.set('tls', 'enabled', true);
const options = ['cipher','verified','verifyError','peerCertificate'];
options.forEach(t => {
if (obj[t] === undefined) return;
this.set('tls', t, obj[t]);
})
// prior to 2017-07, authorized and verified were both used. Verified
// seems to be the more common and has the property updated in the
// tls object. However, authorized has been up-to-date in the notes. Store
// in both, for backwards compatibility.
this.notes.tls = {
authorized: obj.verified, // legacy name
authorizationError: obj.verifyError,
cipher: obj.cipher,
peerCertificate: obj.peerCertificate,
}
}
set (prop_str, val) {
if (arguments.length === 3) {
prop_str = `${arguments[0]}.${arguments[1]}`;
val = arguments[2];
}
const path_parts = prop_str.split('.');
let loc = this;
for (let i=0; i < path_parts.length; i++) {
const part = path_parts[i];
if (part === "__proto__" || part === "constructor") continue;
// while another part remains
if (i < (path_parts.length - 1)) {
if (loc[part] === undefined) loc[part] = {}; // initialize
loc = loc[part]; // descend
continue;
}
// last part, so assign the value
loc[part] = val;
}
// Set is_private, is_local automatically when remote.ip is set
if (prop_str === 'remote.ip') {
this.set('remote.is_local', net_utils.is_local_ip(this.remote.ip));
if (this.remote.is_local) {
this.set('remote.is_private', true);
}
else {
this.set('remote.is_private', net_utils.is_private_ipv4(this.remote.ip));
}
}
// sunset 3.0.0
if (prop_str === 'hello.verb') {
this.greeting = val;
}
else if (prop_str === 'tls.enabled') {
this.using_tls = val;
}
else if (prop_str === 'proxy.ip') {
this.haproxy_ip = val;
}
else {
const legacy_name = prop_str.split('.').join('_');
this[legacy_name] = val;
}
// /sunset
}
get (prop_str) {
return prop_str.split('.').reduce((prev, curr) => {
return prev ? prev[curr] : undefined
}, this)
}
set relaying (val) {
if (this.transaction) {
this.transaction._relaying = val;
}
else {
this._relaying = val;
}
}
get relaying () {
if (this.transaction && '_relaying' in this.transaction) return this.transaction._relaying;
return this._relaying;
}
process_line (line) {
if (this.state >= states.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.DATA) {
if (logger.would_log(logger.LOGDATA)) {
this.logdata(`C: ${line}`);
}
this.accumulate_data(line);
return;
}
this.current_line = line.toString(this.encoding).replace(/\r?\n/, '');
if (logger.would_log(logger.LOGPROTOCOL)) {
this.logprotocol(`C: ${this.current_line}`, {'state': this.state});
}
// Check for non-ASCII characters
/* eslint no-control-regex: 0 */
if (/[^\x00-\x7F]/.test(this.current_line)) {
// See if this is a TLS handshake
const buf = Buffer.from(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 if (this.hello.verb == 'HELO') {
return this.respond(501, 'Syntax error (8-bit characters not allowed)');
}
}
if (this.state === states.CMD) {
this.state = states.PAUSE_SMTP;
const matches = /^([^ ]*)( +(.*))?$/.exec(this.current_line);
if (!matches) {
return plugins.run_hooks('unrecognized_command',
this, [this.current_line]);
}
const cmd = matches[1];
const method = `cmd_${cmd.toLowerCase()}`;
const remaining = matches[3] || '';
if (this[method]) {
try {
this[method](remaining);
}
catch (err) {
if (err.stack) {
this.logerror(`${method} failed: ${err}`);
err.stack.split("\n").forEach(this.logerror);
}
else {
this.logerror(`${method} failed: ${err}`);
}
this.respond(421, "Internal Server Error", () => {
this.disconnect();
});
}
}
else {
// unrecognized command
plugins.run_hooks('unrecognized_command', this, [ cmd, remaining ]);
}
}
else if (this.state === states.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}`);
}
}
process_data (data) {
if (this.state >= states.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
const buf = Buffer.concat(
[ this.current_data, data ],
(this.current_data.length + data.length)
);
this.current_data = buf;
}
this._process_data();
}
_process_data () {
// We *must* detect disconnected connections here as the state
// only transitions to states.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.DISCONNECTING) return;
let maxlength;
if (this.state === states.PAUSE_DATA || this.state === states.DATA) {
maxlength = this.max_data_line_length;
}
else {
maxlength = this.max_line_length;
}
let offset;
while (this.current_data && ((offset = utils.indexOfLF(this.current_data, maxlength)) !== -1)) {
if (this.state === states.PAUSE_DATA) {
return;
}
let this_line = this.current_data.slice(0, offset+1);
// Hack: bypass this code to allow HAProxy's PROXY extension
const proxyStart = this.proxy.allowed && /^PROXY /.test(this_line);
if (this.state === states.PAUSE && proxyStart) {
if (this.proxy.timer) clearTimeout(this.proxy.timer);
this.state = states.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.PAUSE || this.state === states.PAUSE_SMTP) && !this.esmtp) {
// Allow EHLO/HELO to be pipelined with PROXY
if (this.proxy.allowed && /^(?: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;
setImmediate(() => { this._process_data() });
break;
}
else if ((this.state === states.PAUSE || this.state === states.PAUSE_SMTP) && this.esmtp) {
let valid = true;
const 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.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;
setImmediate(() => { this._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) &&
(utils.indexOfLF(this.current_data, maxlength) === -1)) {
if (this.state !== states.DATA && this.state !== states.PAUSE_DATA) {
// In command mode, reject:
this.client.pause();
this.current_data = null;
return this.respond(521, "Command line too long", () => {
this.disconnect();
});
}
else {
this.loginfo(`DATA line length (${this.current_data.length}) exceeds limit of ${maxlength} bytes`);
this.transaction.notes.data_line_length_exceeded = true;
const b = Buffer.concat([
this.current_data.slice(0, maxlength - 2),
Buffer.from("\r\n ", 'utf8'),
this.current_data.slice(maxlength - 2)
], this.current_data.length + 3);
this.current_data = b;
return this._process_data();
}
}
}
respond (code, msg, func) {
let uuid = '';
let messages;
if (this.state === states.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)) {
messages = msg.toString().split(/\n/);
}
else {
messages = msg.slice();
}
messages = messages.filter((msg2) => {
return /\S/.test(msg2);
});
// Multiline AUTH PLAIN as in RFC-4954 page 8.
if (code === 334 && !messages.length) {
messages = [' '];
}
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);
}
}
}
let mess;
let buf = '';
const hostname = os.hostname().split('.').shift();
const _uuid = uuid ? `[${uuid}@${hostname}] ` : '';
while ((mess = messages.shift())) {
const line = `${code}${(messages.length ? "-" : " ")}${_uuid}${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.LOOP) {
this.state = states.CMD;
}
// Run optional closure before handling and further commands
if (func) func();
// Process any buffered commands (PIPELINING)
this._process_data();
}
fail (err, err_data) {
if (err) this.logwarn(err, err_data);
this.hooks_to_run = [];
this.disconnect();
}
disconnect () {
if (this.state >= states.DISCONNECTING) return;
this.state = states.DISCONNECTING;
this.current_data = null; // don't process any more data we have already received
this.reset_transaction(() => {
plugins.run_hooks('disconnect', this);
});
}
disconnect_respond () {
const 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.tls.enabled ? '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.results.add({name: 'disconnect'}, {
duration: (Date.now() - this.start_time)/1000,
});
this.lognotice('disconnect', logdetail);
this.state = states.DISCONNECTED;
this.client.end();
}
get_capabilities () {
return [];
}
tran_uuid () {
this.tran_count++;
return `${this.uuid}.${this.tran_count}`;
}
reset_transaction (cb) {
this.results.add({name: 'reset'}, {
duration: (Date.now() - this.start_time)/1000,
});
if (this.transaction && this.transaction.resetting === false) {
// Pause connection to allow the hook to complete
this.pause();
this.transaction.resetting = true;
plugins.run_hooks('reset_transaction', this, cb);
}
else {
this.transaction = null;
if (cb) cb();
}
}
reset_transaction_respond (retval, msg, cb) {
if (this.transaction) {
this.transaction.message_stream.destroy();
this.transaction = null;
}
if (cb) cb();
// Allow the connection to continue
this.resume();
}
init_transaction (cb) {
this.reset_transaction(() => {
this.transaction = trans.createTransaction(this.tran_uuid(), this.cfg);
// Catch any errors from the message_stream
this.transaction.message_stream.on('error', (err) => {
this.logcrit(`message_stream error: ${err.message}`);
this.respond('421', 'Internal Server Error', () => {
this.disconnect();
});
});
this.transaction.results = new ResultStore(this);
if (cb) cb();
});
}
loop_respond (code, msg) {
if (this.state >= states.DISCONNECTING) return;
this.state = states.LOOP;
this.loop_code = code;
this.loop_msg = msg;
this.respond(code, msg);
}
pause () {
if (this.state >= states.DISCONNECTING) return;
this.client.pause();
if (this.state !== states.PAUSE_DATA) this.prev_state = this.state;
this.state = states.PAUSE_DATA;
}
resume () {
if (this.state >= states.DISCONNECTING) return;
this.client.resume();
if (this.prev_state) {
this.state = this.prev_state;
this.prev_state = null;
}
setImmediate(() => this._process_data());
}
/////////////////////////////////////////////////////////////////////////////
// SMTP Responses
connect_init_respond (retval, msg) {
// retval and message are ignored
this.logdebug('running connect_init_respond');
plugins.run_hooks('lookup_rdns', this);
}
lookup_rdns_respond (retval, msg) {
switch (retval) {
case constants.ok:
this.set('remote', 'host', (msg || 'Unknown'));
this.set('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", () => {
this.disconnect();
});
break;
case constants.denysoft:
this.loop_respond(421, msg || "rDNS Temporary Failure");
break;
case constants.denysoftdisconnect:
this.respond(421, msg || "rDNS Temporary Failure", () => {
this.disconnect();
});
break;
default:
// BUG: dns.reverse throws on invalid input (and sometimes valid
// input nodejs/node#47847). Also throws when empty results
try {
dns.reverse(this.remote.ip, (err, domains) => {
this.rdns_response(err, domains);
})
}
catch (err) {
this.rdns_response(err, []);
}
}
}
rdns_response (err, domains) {
if (err) {
switch (err.code) {
case dns.NXDOMAIN:
case dns.NOTFOUND:
this.set('remote', 'host', 'NXDOMAIN');
break;
default:
this.set('remote', 'host', 'DNSERROR');
break;
}
}
else {
this.set('remote', 'host', (domains[0] || 'Unknown'));
this.results.add({name: 'remote'}, this.remote);
}
this.set('remote', 'info', this.remote.info || this.remote.host);
plugins.run_hooks('connect', this);
}
unrecognized_command_respond (retval, msg) {
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:
case constants.denysoftdisconnect:
this.respond(retval === constants.denydisconnect ? 521 : 421, msg || "Unrecognized command", () => {
this.disconnect();
});
break;
default:
this.errors++;
this.respond(500, msg || "Unrecognized command");
}
}
connect_respond (retval, msg) {
// 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", () => {
this.disconnect();
});
break;
case constants.denysoft:
this.loop_respond(421, msg || "Come back later");
break;
case constants.denysoftdisconnect:
this.respond(421, msg || "Come back later", () => {
this.disconnect();
});
break;
default: {
let greeting = config.get('smtpgreeting', 'list');
if (greeting.length) {
// RFC5321 section 4.2
// Hostname/domain should appear after the 220
greeting[0] = `${this.local.host} ESMTP ${greeting[0]}`;
if (this.banner_includes_uuid) {
greeting[0] += ` (${this.uuid})`;
}
}
else {
greeting = `${this.local.host} ESMTP ${this.local.info} ready`;
if (this.banner_includes_uuid) {
greeting += ` (${this.uuid})`;
}
}
this.respond(220, msg || greeting);
}
}
}
get_remote (prop) {
switch (this.remote[prop]) {
case 'NXDOMAIN':
case 'DNSERROR':
case '':
case undefined:
case null:
return `[${this.remote.ip}]`;
default:
return `${this.remote[prop]} [${this.remote.ip}]`;
}
}
helo_respond (retval, msg) {
switch (retval) {
case constants.deny:
this.respond(550, msg || "HELO denied", () => {
this.set('hello', 'verb', null);
this.set('hello', 'host', null);
});
break;
case constants.denydisconnect:
this.respond(550, msg || "HELO denied", () => {
this.disconnect();
});
break;
case constants.denysoft:
this.respond(450, msg || "HELO denied", () => {
this.set('hello', 'verb', null);
this.set('hello', 'host', null);
});
break;
case constants.denysoftdisconnect:
this.respond(450, msg || "HELO denied", () => {
this.disconnect();
});
break;
default:
// RFC5321 section 4.1.1.1
// Hostname/domain should appear after 250
this.respond(250, `${this.local.host} Hello ${this.get_remote('host')}${this.ehlo_hello_message}`);
}
}
ehlo_respond (retval, msg) {
switch (retval) {
case constants.deny:
this.respond(550, msg || "EHLO denied", () => {
this.set('hello', 'verb', null);
this.set('hello', 'host', null);
});
break;
case constants.denydisconnect:
this.respond(550, msg || "EHLO denied", () => {
this.disconnect();
});
break;
case constants.denysoft:
this.respond(450, msg || "EHLO denied", () => {
this.set('hello', 'verb', null);
this.set('hello', 'host', null);
});
break;
case constants.denysoftdisconnect:
this.respond(450, msg || "EHLO denied", () => {
this.disconnect();
});
break;
default: {
// RFC5321 section 4.1.1.1
// Hostname/domain should appear after 250
const response = [
`${this.local.host} Hello ${this.get_remote('host')}${this.ehlo_hello_message}`,
"PIPELINING",
"8BITMIME",
];
if (this.cfg.main.smtputf8) {
response.push("SMTPUTF8");
}
response.push(`SIZE ${this.max_bytes}`);
this.capabilities = response;
plugins.run_hooks('capabilities', this);
this.esmtp = true;
}
}
}
capabilities_respond (retval, msg) {
this.respond(250, this.capabilities);
}
quit_respond (retval, msg) {
this.respond(221, msg || `${this.local.host} ${this.connection_close_message}`, () => {
this.disconnect();
});
}
vrfy_respond (retval, msg) {
switch (retval) {
case constants.deny:
this.respond(550, msg || "Access Denied", () => {
this.reset_transaction();
});
break;
case constants.denydisconnect:
this.respond(550, msg || "Access Denied", () => {
this.disconnect();
});
break;
case constants.denysoft:
this.respond(450, msg || "Lookup Failed", () => {
this.reset_transaction();
});
break;
case constants.denysoftdisconnect:
this.respond(450, msg || "Lookup Failed", () => {
this.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...");
}
}
noop_respond (retval, msg) {
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", () => {
this.disconnect();
});
break;
default:
this.respond(250, "OK");
}
}
rset_respond (retval, msg) {
this.respond(250, "OK", () => {
this.reset_transaction();
})
}
mail_respond (retval, msg) {
const self = this;
if (!this.transaction) {
this.logerror("mail_respond found no transaction!");
return;
}
const sender = this.transaction.mail_from;
const dmsg = `sender ${sender.format()}`;
this.lognotice(
dmsg,
{
'code': constants.translate(retval),
'msg': (msg || ''),
}
);
function store_results (action) {
let addr = sender.format();
if (addr.length > 2) { // all but null sender
addr = addr.substr(1, addr.length -2); // trim off < >
}
self.transaction.results.add({name: 'mail_from'}, {