forked from haraka/Haraka
-
Notifications
You must be signed in to change notification settings - Fork 0
/
outbound.js
2302 lines (2069 loc) · 82.1 KB
/
outbound.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';
var dns = require('dns');
var events = require('events');
var fs = require('fs');
var path = require('path');
var net = require('net');
var util = require('util');
var async = require('async');
var Address = require('address-rfc2821').Address;
var constants = require('haraka-constants');
var generic_pool = require('generic-pool');
var net_utils = require('haraka-net-utils');
var utils = require('haraka-utils');
var ResultStore = require('haraka-results');
var sock = require('./line_socket');
var logger = require('./logger');
var config = require('./config');
var trans = require('./transaction');
var plugins = require('./plugins');
var TimerQueue = require('./timer_queue');
var Header = require('./mailheader').Header;
var DSN = require('./dsn');
var FsyncWriteStream = require('./fsync_writestream');
var server = require('./server');
var core_consts = require('constants');
var WRITE_EXCL = core_consts.O_CREAT | core_consts.O_TRUNC | core_consts.O_WRONLY | core_consts.O_EXCL;
var my_hostname = require('os').hostname().replace(/\\/, '\\057').replace(/:/, '\\072');
var queue_dir;
if (config.get('queue_dir')) {
queue_dir = path.resolve(config.get('queue_dir'));
}
else if (process.env.HARAKA) {
queue_dir = path.resolve(process.env.HARAKA, 'queue');
}
else {
queue_dir = path.resolve('tests', 'test-queue');
}
var cfg;
var platformDOT = ((['win32','win64'].indexOf( process.platform ) !== -1) ? '' : '__tmp__') + '.';
exports.load_config = function () {
cfg = config.get('outbound.ini', {
booleans: [
'-disabled',
'-always_split',
'+enable_tls',
'-ipv6_enabled',
],
}, function () {
exports.load_config();
}).main;
// legacy config file support. Remove in Haraka 4.0
if (!cfg.disabled && config.get('outbound.disabled')) {
cfg.disabled = true;
}
if (!cfg.enable_tls && config.get('outbound.enable_tls')) {
cfg.enable_tls = true;
}
if (!cfg.maxTempFailures) {
cfg.maxTempFailures = config.get('outbound.maxTempFailures') || 13;
}
if (!cfg.concurrency_max) {
cfg.concurrency_max = config.get('outbound.concurrency_max') || 10000;
}
if (!cfg.connect_timeout) {
cfg.connect_timeout = 30;
}
if (cfg.pool_timeout === undefined) {
cfg.pool_timeout = 50;
}
if (!cfg.pool_concurrency_max) {
cfg.pool_concurrency_max = 10;
}
if (!cfg.ipv6_enabled && config.get('outbound.ipv6_enabled')) {
cfg.ipv6_enabled = true;
}
if (!cfg.received_header) {
cfg.received_header = config.get('outbound.received_header') || 'Haraka outbound';
}
};
exports.load_config();
exports.net_utils = net_utils;
exports.config = config;
var load_queue = async.queue(function (file, cb) {
var hmail = new HMailItem(file, path.join(queue_dir, file));
exports._add_file(hmail);
hmail.once('ready', cb);
}, cfg.concurrency_max);
var in_progress = 0;
var delivery_queue = async.queue(function (hmail, cb) {
in_progress++;
hmail.next_cb = function () {
in_progress--;
cb();
};
hmail.send();
}, cfg.concurrency_max);
var temp_fail_queue = new TimerQueue();
var queue_count = 0;
exports.get_stats = function () {
return in_progress + '/' + delivery_queue.length() + '/' + temp_fail_queue.length();
};
exports.list_queue = function (cb) {
this._load_cur_queue(null, "_list_file", cb);
};
exports.stat_queue = function (cb) {
var self = this;
this._load_cur_queue(null, "_stat_file", function (err) {
if (err) return cb(err);
return cb(null, self.stats());
});
};
exports.scan_queue_pids = function (cb) {
// Under cluster, this is called first by the master so
// we create the queue directory if it doesn't exist.
this.ensure_queue_dir();
fs.readdir(queue_dir, function (err, files) {
if (err) {
logger.logerror("[outbound] Failed to load queue directory (" + queue_dir + "): " + err);
return cb(err);
}
var pids = {};
files.forEach(function (file) {
if (/^\./.test(file)) {
// dot-file...
logger.logwarn("[outbound] Removing left over dot-file: " + file);
return fs.unlink(file, function () {});
}
var parts = _qfile.parts(file);
if (!parts) {
logger.logerror("[outbound] Unrecognized file in queue directory: " + queue_dir + '/' + file);
return;
}
pids[parts.pid] = true;
});
return cb(null, Object.keys(pids));
});
};
process.on('message', function (msg) {
if (msg.event && msg.event === 'outbound.load_pid_queue') {
exports.load_pid_queue(msg.data);
return;
}
if (msg.event && msg.event === 'outbound.flush_queue') {
exports.flush_queue(msg.domain, process.pid);
return;
}
if (msg.event && msg.event == 'outbound.shutdown') {
logger.loginfo("[outbound] Shutting down temp fail queue");
exports.drain_pools();
temp_fail_queue.shutdown();
return;
}
if (msg.event && msg.event === 'outbound.drain_pools') {
exports.drain_pools();
return;
}
// ignores the message
});
exports.drain_pools = function () {
if (!server.notes.pool || Object.keys(server.notes.pool).length == 0) {
return logger.logdebug("[outbound] Drain pools: No pools available");
}
for (var p in server.notes.pool) {
logger.logdebug("[outbound] Drain pools: Draining SMTP connection pool " + p);
server.notes.pool[p].drain(function () {
if (!server.notes.pool[p]) return;
server.notes.pool[p].destroyAllNow();
});
}
logger.logdebug("[outbound] Drain pools: Pools shut down");
}
exports.flush_queue = function (domain, pid) {
if (domain) {
exports.list_queue(function (err, qlist) {
if (err) return logger.logerror("Failed to load queue: " + err);
qlist.forEach(function (todo) {
if (todo.domain.toLowerCase() != domain.toLowerCase()) return;
if (pid && todo.pid != pid) return;
// console.log("requeue: ", todo);
delivery_queue.push(new HMailItem(todo.file, todo.full_path));
});
})
}
else {
temp_fail_queue.drain();
}
};
exports.load_pid_queue = function (pid) {
logger.loginfo("[outbound] Loading queue for pid: " + pid);
this.load_queue(pid);
};
exports.ensure_queue_dir = function () {
// No reason not to do this stuff syncronously -
// this code is only run at start-up.
if (fs.existsSync(queue_dir)) return;
logger.logdebug("[outbound] Creating queue directory " + queue_dir);
try {
fs.mkdirSync(queue_dir, 493); // 493 == 0755
}
catch (err) {
if (err.code !== 'EEXIST') {
logger.logerror("Error creating queue directory: " + err);
throw err;
}
}
};
exports.load_queue = function (pid) {
// Initialise and load queue
// This function is called first when not running under cluster,
// so we create the queue directory if it doesn't already exist.
this.ensure_queue_dir();
this._load_cur_queue(pid, "_add_file");
};
exports._load_cur_queue = function (pid, cb_name, cb) {
var self = this;
logger.loginfo("[outbound] Loading outbound queue from ", queue_dir);
fs.readdir(queue_dir, function (err, files) {
if (err) {
return logger.logerror("Failed to load queue directory (" +
queue_dir + "): " + err);
}
self.cur_time = new Date(); // set once so we're not calling it a lot
self.load_queue_files(pid, cb_name, files, cb);
});
};
exports.load_queue_files = function (pid, cb_name, files, callback) {
var self = this;
if (files.length === 0) return;
if (cfg.disabled && cb_name === '_add_file') {
// try again in 1 second if delivery is disabled
setTimeout(function () {
exports.load_queue_files(pid, cb_name, files, callback);
}, 1000);
return;
}
if (pid) {
// Pre-scan to rename PID files to my PID:
logger.loginfo("[outbound] Grabbing queue files for pid: " + pid);
async.eachLimit(files, 200, function (file, cb) {
var parts = _qfile.parts(file);
if (parts && parts.pid === parseInt(pid)) {
var next_process = parts.next_attempt;
// maintain some original details for the rename
var new_filename = _qfile.name({
arrival : parts.arrival,
uid : parts.uid,
next_attempt : parts.next_attempt,
attempts : parts.attempts,
});
// logger.loginfo("new_filename: ", new_filename);
fs.rename(path.join(queue_dir, file), path.join(queue_dir, new_filename), function (err) {
if (err) {
logger.logerror("Unable to rename queue file: " + file +
" to " + new_filename + " : " + err);
return cb();
}
if (next_process <= self.cur_time) {
load_queue.push(new_filename);
}
else {
temp_fail_queue.add(next_process - self.cur_time, function () {
load_queue.push(new_filename);
});
}
cb();
});
}
else if (/^\./.test(file)) {
// dot-file...
logger.logwarn("Removing left over dot-file: " + file);
return fs.unlink(path.join(queue_dir, file), function (err) {
if (err) {
logger.logerror("Error removing dot-file: " + file + ": " + err);
}
cb();
});
}
else {
// Do this because otherwise we blow the stack
async.setImmediate(cb);
}
}, function (err) {
if (err) {
// no error cases yet, but log anyway
logger.logerror("Error fixing up queue files: " + err);
}
logger.loginfo("Done fixing up old PID queue files");
logger.loginfo(delivery_queue.length() + " files in my delivery queue");
logger.loginfo(load_queue.length() + " files in my load queue");
logger.loginfo(temp_fail_queue.length() + " files in my temp fail queue");
if (callback) callback();
});
}
else {
logger.loginfo("Loading the queue...");
var good_file = function (file) {
if (/^\./.test(file)) {
logger.logwarn("Removing left over dot-file: " + file);
fs.unlink(path.join(queue_dir, file), function (err) {
if (err) console.error(err);
});
return false;
}
if (!_qfile.parts(file)) {
logger.logerror("Unrecognized file in queue folder: " + file);
return false;
}
return true;
}
async.mapSeries(files.filter(good_file), function (file, cb) {
// logger.logdebug("Loading queue file: " + file);
if (cb_name === '_add_file') {
var parts = _qfile.parts(file);
var next_process = parts.next_attempt;
if (next_process <= self.cur_time) {
logger.logdebug("File needs processing now");
load_queue.push(file);
}
else {
logger.logdebug("File needs processing later: " + (next_process - self.cur_time) + "ms");
temp_fail_queue.add(next_process - self.cur_time, function () { load_queue.push(file);});
}
cb();
}
else {
self[cb_name](file, cb);
}
}, callback);
}
};
exports._add_file = function (hmail) {
if (hmail.next_process < this.cur_time) {
delivery_queue.push(hmail);
}
else {
temp_fail_queue.add(hmail.next_process - this.cur_time, function () {
delivery_queue.push(hmail);
});
}
};
exports._list_file = function (file, cb) {
var tl_reader = fs.createReadStream(path.join(queue_dir, file), {start: 0, end: 3});
tl_reader.on('error', function (err) {
console.error("Error reading queue file: " + file + ":", err);
});
tl_reader.once('data', function (buf) {
// I'm making the assumption here we won't ever read less than 4 bytes
// as no filesystem on the planet should be that dumb...
tl_reader.destroy();
var todo_len = (buf[0] << 24) + (buf[1] << 16) + (buf[2] << 8) + buf[3];
var td_reader = fs.createReadStream(path.join(queue_dir, file), {encoding: 'utf8', start: 4, end: todo_len + 3});
var todo = '';
td_reader.on('data', function (str) {
todo += str;
if (Buffer.byteLength(todo) === todo_len) {
// we read everything
var todo_struct = JSON.parse(todo);
todo_struct.rcpt_to = todo_struct.rcpt_to.map(function (a) { return new Address (a); });
todo_struct.mail_from = new Address (todo_struct.mail_from);
todo_struct.file = file;
todo_struct.full_path = path.join(queue_dir, file);
var parts = _qfile.parts(file);
todo_struct.pid = (parts && parts.pid) || null;
cb(null, todo_struct);
}
});
td_reader.on('end', function () {
if (Buffer.byteLength(todo) !== todo_len) {
console.error("Didn't find right amount of data in todo for file:", file);
return cb();
}
});
});
};
exports._stat_file = function (file, cb) {
queue_count++;
cb();
};
exports.stats = function () {
// TODO: output more data here
var results = {
queue_dir: queue_dir,
queue_count: queue_count,
};
return results;
};
var QFILECOUNTER = 0;
var _qfile = exports.qfile = {
// File Name Format: $arrival_$nextattempt_$attempts_$pid_$uniquetag_$counter_$host
name : function (overrides) {
var o = overrides || {};
var time = _qfile.time();
return [
o.arrival || time,
o.next_attempt || time,
o.attempts || 0,
o.pid || process.pid,
o.uid || _qfile.rnd_unique(),
_qfile.next_counter(),
o.host || my_hostname
].join('_');
},
time : function () {
return new Date().getTime();
},
next_counter: function () {
QFILECOUNTER = (QFILECOUNTER < 10000)?QFILECOUNTER+1:0;
return QFILECOUNTER;
},
rnd_unique: function (len) {
len = len || 6;
var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var result = [];
for (var i = len; i > 0; --i){
result.push(chars[Math.floor(Math.random() * chars.length)]);
}
return result.join('');
},
parts : function (filename) {
if (!filename){
throw new Error("No filename provided");
}
var PARTS_EXPECTED_OLD = 4;
var PARTS_EXPECTED_CURRENT = 7;
var p = filename.split('_');
// bail on unknown split lengths
if (p.length !== PARTS_EXPECTED_OLD
&& p.length !== PARTS_EXPECTED_CURRENT){
return null;
}
var time = _qfile.time();
if (p.length === PARTS_EXPECTED_OLD){
// parse the previous string structure
// $nextattempt_$attempts_$pid_$uniq.$host
// 1484878079415_0_12345_8888.mta1.example.com
// var fn_re = /^(\d+)_(\d+)_(\d+)(_\d+\..*)$/
// match[1] = $nextattempt
// match[2] = $attempts
// match[3] = $pid
// match[4] = $uniq.$my_hostname
var fn_re = /^(\d+)_(\d+)_(\d+)_(\d+)\.(.*)$/;
var match = filename.match(fn_re);
if (!match){
return null;
}
p = match.slice(1); // grab the capture groups minus the pattern
p.splice(3,1,_qfile.rnd_unique(),_qfile.next_counter()); // add a fresh UID and counter
p.unshift(time); // prepend current timestamp -- potentially inaccurate, but non-critical and shortlived
}
return {
arrival : parseInt(p[0]),
next_attempt : parseInt(p[1]),
attempts : parseInt(p[2]),
pid : parseInt(p[3]),
uid : p[4],
counter : parseInt(p[5]),
host : p[6],
age : time - parseInt(p[0])
};
}
};
exports.send_email = function () {
if (arguments.length === 2) {
logger.loginfo("[outbound] Sending email as a transaction");
return this.send_trans_email(arguments[0], arguments[1]);
}
var from = arguments[0];
var to = arguments[1];
var contents = arguments[2];
var next = arguments[3];
var options = arguments[4];
var dot_stuffed = ((options && options.dot_stuffed) ? options.dot_stuffed : false);
var notes = ((options && options.notes) ? options.notes : null);
logger.loginfo("[outbound] Sending email via params");
var transaction = trans.createTransaction();
logger.loginfo("[outbound] Created transaction: " + transaction.uuid);
//Adding notes passed as parameter
if (notes) {
transaction.notes = notes;
}
// set MAIL FROM address, and parse if it's not an Address object
if (from instanceof Address) {
transaction.mail_from = from;
}
else {
try {
from = new Address(from);
}
catch (err) {
return next(constants.deny, "Malformed from: " + err);
}
transaction.mail_from = from;
}
// Make sure to is an array
if (!(Array.isArray(to))) {
// turn into an array
to = [ to ];
}
if (to.length === 0) {
return next(constants.deny, "No recipients for email");
}
// Set RCPT TO's, and parse each if it's not an Address object.
for (var i=0,l=to.length; i < l; i++) {
if (!(to[i] instanceof Address)) {
try {
to[i] = new Address(to[i]);
}
catch (err) {
return next(constants.deny,
"Malformed to address (" + to[i] + "): " + err);
}
}
}
transaction.rcpt_to = to;
// Set data_lines to lines in contents
if (typeof contents == 'string') {
var match;
while ((match = utils.line_regexp.exec(contents))) {
var line = match[1];
line = line.replace(/\r?\n?$/, '\r\n'); // make sure it ends in \r\n
if (dot_stuffed === false && line.length >= 3 && line.substr(0,1) === '.') {
line = "." + line;
}
transaction.add_data(new Buffer(line));
contents = contents.substr(match[1].length);
if (contents.length === 0) {
break;
}
}
}
else {
// Assume a stream
return stream_line_reader(contents, transaction, function (err) {
if (err) {
return next(constants.denysoft, "Error from stream line reader: " + err);
}
exports.send_trans_email(transaction, next);
});
}
transaction.message_stream.add_line_end();
this.send_trans_email(transaction, next);
};
function stream_line_reader (stream, transaction, cb) {
var current_data = '';
function process_data (data) {
current_data += data.toString();
var results;
while ((results = utils.line_regexp.exec(current_data))) {
var this_line = results[1];
current_data = current_data.slice(this_line.length);
if (!(current_data.length || this_line.length)) {
return;
}
transaction.add_data(new Buffer(this_line));
}
}
function process_end () {
if (current_data.length) {
transaction.add_data(new Buffer(current_data));
}
current_data = '';
transaction.message_stream.add_line_end();
cb();
}
stream.on('data', process_data);
stream.once('end', process_end);
stream.once('error', cb);
}
exports.send_trans_email = function (transaction, next) {
var self = this;
// add in potentially missing headers
if (!transaction.header.get_all('Message-Id').length) {
logger.loginfo("[outbound] Adding missing Message-Id header");
transaction.add_header('Message-Id', '<' + transaction.uuid + '@' + config.get('me') + '>');
}
if (!transaction.header.get_all('Date').length) {
logger.loginfo("[outbound] Adding missing Date header");
transaction.add_header('Date', utils.date_to_str(new Date()));
}
transaction.add_leading_header('Received', '('+cfg.received_header+'); ' + utils.date_to_str(new Date()));
var connection = {
transaction: transaction,
};
logger.add_log_methods(connection);
transaction.results = transaction.results || new ResultStore(connection);
connection.pre_send_trans_email_respond = function (retval) {
var deliveries = [];
var always_split = cfg.always_split;
if (always_split) {
this.logdebug({name: "outbound"}, "always split");
transaction.rcpt_to.forEach(function (rcpt) {
deliveries.push({domain: rcpt.host, rcpts: [ rcpt ]});
});
}
else {
// First get each domain
var recips = {};
transaction.rcpt_to.forEach(function (rcpt) {
var domain = rcpt.host;
if (!recips[domain]) { recips[domain] = []; }
recips[domain].push(rcpt);
});
Object.keys(recips).forEach(function (domain) {
deliveries.push({'domain': domain, 'rcpts': recips[domain]});
});
}
var hmails = [];
var ok_paths = [];
var todo_index = 1;
async.forEachSeries(deliveries, function (deliv, cb) {
var todo = new TODOItem(deliv.domain, deliv.rcpts, transaction);
todo.uuid = todo.uuid + '.' + todo_index;
todo_index++;
self.process_delivery(ok_paths, todo, hmails, cb);
},
function (err) {
if (err) {
for (var i=0,l=ok_paths.length; i<l; i++) {
fs.unlink(ok_paths[i], function () {});
}
if (next) next(constants.denysoft, err);
return;
}
for (var j=0; j<hmails.length; j++) {
var hmail = hmails[j];
delivery_queue.push(hmail);
}
if (next) {
next(constants.ok, "Message Queued");
}
});
}
plugins.run_hooks('pre_send_trans_email', connection);
};
exports.process_delivery = function (ok_paths, todo, hmails, cb) {
var self = this;
logger.loginfo("[outbound] Processing domain: " + todo.domain);
var fname = _qfile.name();
var tmp_path = path.join(queue_dir, platformDOT + fname);
var ws = new FsyncWriteStream(tmp_path, { flags: WRITE_EXCL });
ws.on('close', function () {
var dest_path = path.join(queue_dir, fname);
fs.rename(tmp_path, dest_path, function (err) {
if (err) {
logger.logerror("[outbound] Unable to rename tmp file!: " + err);
fs.unlink(tmp_path, function () {});
cb("Queue error");
}
else {
hmails.push(new HMailItem (fname, dest_path, todo.notes));
ok_paths.push(dest_path);
cb();
}
});
});
ws.on('error', function (err) {
logger.logerror("[outbound] Unable to write queue file (" + fname + "): " + err);
ws.destroy();
fs.unlink(tmp_path, function () {});
cb("Queueing failed");
});
self.build_todo(todo, ws, function () {
todo.message_stream.pipe(ws, { line_endings: '\r\n', dot_stuffing: true, ending_dot: false });
});
};
exports.build_todo = function (todo, ws, write_more) {
// Replacer function to exclude items from the queue file header
function exclude_from_json (key, value) {
switch (key) {
case 'message_stream':
return undefined;
default:
return value;
}
}
var todo_str = new Buffer(JSON.stringify(todo, exclude_from_json));
// since JS has no pack() we have to manually write the bytes of a long
var todo_length = new Buffer(4);
var todo_l = todo_str.length;
todo_length[3] = todo_l & 0xff;
todo_length[2] = (todo_l >> 8) & 0xff;
todo_length[1] = (todo_l >> 16) & 0xff;
todo_length[0] = (todo_l >> 24) & 0xff;
var buf = Buffer.concat([todo_length, todo_str], todo_str.length + 4);
var continue_writing = ws.write(buf);
if (continue_writing) return write_more();
ws.once('drain', write_more);
};
exports.split_to_new_recipients = function (hmail, recipients, response, cb) {
var self = this;
if (recipients.length === hmail.todo.rcpt_to.length) {
// Split to new for no reason - increase refcount and return self
hmail.refcount++;
return cb(hmail);
}
var fname = _qfile.name();
var tmp_path = path.join(queue_dir, platformDOT + fname);
var ws = new FsyncWriteStream(tmp_path, { flags: WRITE_EXCL });
var err_handler = function (err, location) {
logger.logerror("[outbound] Error while splitting to new recipients (" + location + "): " + err);
hmail.todo.rcpt_to.forEach(function (rcpt) {
hmail.extend_rcpt_with_dsn(rcpt, DSN.sys_unspecified("Error splitting to new recipients: " + err));
});
hmail.bounce("Error splitting to new recipients: " + err);
};
ws.on('error', function (err) { err_handler(err, "tmp file writer");});
var writing = false;
var write_more = function () {
if (writing) return;
writing = true;
var rs = hmail.data_stream();
rs.pipe(ws, {end: false});
rs.on('error', function (err) {
err_handler(err, "hmail.data_stream reader");
});
rs.on('end', function () {
ws.on('close', function () {
var dest_path = path.join(queue_dir, fname);
fs.rename(tmp_path, dest_path, function (err) {
if (err) {
err_handler(err, "tmp file rename");
}
else {
var split_mail = new HMailItem (fname, dest_path);
split_mail.once('ready', function () {
cb(split_mail);
});
}
});
});
ws.destroySoon();
return;
});
};
ws.on('error', function (err) {
logger.logerror("[outbound] Unable to write queue file (" + fname + "): " + err);
ws.destroy();
hmail.todo.rcpt_to.forEach(function (rcpt) {
hmail.extend_rcpt_with_dsn(rcpt, DSN.sys_unspecified("Error re-queueing some recipients: " + err));
});
hmail.bounce("Error re-queueing some recipients: " + err);
});
var new_todo = JSON.parse(JSON.stringify(hmail.todo));
new_todo.rcpt_to = recipients;
self.build_todo(new_todo, ws, write_more);
};
exports.get_tls_options = function (mx) {
var tls_options = exports.net_utils.tls_ini_section_with_defaults('outbound');
tls_options.servername = mx.exchange;
if (tls_options.key) {
if (Array.isArray(tls_options.key)) {
tls_options.key = tls_options.key[0];
}
tls_options.key = exports.config.get(tls_options.key, 'binary');
}
if (tls_options.dhparam) {
tls_options.dhparam = exports.config.get(tls_options.dhparam, 'binary');
}
if (tls_options.cert) {
if (Array.isArray(tls_options.cert)) {
tls_options.cert = tls_options.cert[0];
}
tls_options.cert = exports.config.get(tls_options.cert, 'binary');
}
return tls_options;
};
// TODOItem - queue file header data
function TODOItem (domain, recipients, transaction) {
this.queue_time = Date.now();
this.domain = domain;
this.rcpt_to = recipients;
this.mail_from = transaction.mail_from;
this.message_stream = transaction.message_stream;
this.notes = transaction.notes;
this.uuid = transaction.uuid;
return this;
}
// exported for testability
exports.TODOItem = TODOItem;
/////////////////////////////////////////////////////////////////////////////
// HMailItem - encapsulates an individual outbound mail item
var dummy_func = function () {};
function HMailItem (filename, filePath, notes) {
events.EventEmitter.call(this);
var parts = _qfile.parts(filename);
if (!parts) {
throw new Error("Bad filename: " + filename);
}
this.path = filePath;
this.filename = filename;
this.next_process = parts.next_attempt;
this.num_failures = parts.attempts;
this.pid = parts.pid;
this.notes = notes || {};
this.refcount = 1;
this.todo = null;
this.file_size = 0;
this.next_cb = dummy_func;
this.bounce_error = null;
this.hook = null;
this.size_file();
}
util.inherits(HMailItem, events.EventEmitter);
exports.HMailItem = HMailItem;
logger.add_log_methods(HMailItem.prototype, "outbound");
HMailItem.prototype.data_stream = function () {
return fs.createReadStream(this.path, {start: this.data_start, end: this.file_size});
};
HMailItem.prototype.size_file = function () {
var self = this;
fs.stat(self.path, function (err, stats) {
if (err) {
// we are fucked... guess I need somewhere for this to go
self.logerror("Error obtaining file size: " + err);
self.temp_fail("Error obtaining file size");
}
else {
self.file_size = stats.size;
self.read_todo();
}
});
};
HMailItem.prototype.read_todo = function () {
var self = this;
var tl_reader = fs.createReadStream(self.path, {start: 0, end: 3});
tl_reader.on('error', function (err) {
self.logerror("Error reading queue file: " + self.path + ": " + err);
return self.temp_fail("Error reading queue file: " + err);
});
tl_reader.once('data', function (buf) {
// I'm making the assumption here we won't ever read less than 4 bytes
// as no filesystem on the planet should be that dumb...
tl_reader.destroy();
var todo_len = (buf[0] << 24) + (buf[1] << 16) + (buf[2] << 8) + buf[3];
var td_reader = fs.createReadStream(self.path, {encoding: 'utf8', start: 4, end: todo_len + 3});
self.data_start = todo_len + 4;
var todo = '';
td_reader.on('data', function (str) {
todo += str;
if (Buffer.byteLength(todo) === todo_len) {
// we read everything
self.todo = JSON.parse(todo);
self.todo.rcpt_to = self.todo.rcpt_to.map(function (a) { return new Address (a); });
self.todo.mail_from = new Address (self.todo.mail_from);
self.emit('ready');
}
});
td_reader.on('end', function () {
if (Buffer.byteLength(todo) !== todo_len) {
self.logcrit("Didn't find right amount of data in todo!");
fs.rename(self.path, path.join(queue_dir, "error." + self.filename), function (err) {
if (err) {
self.logerror("Error creating error file after todo read failure (" + self.filename + "): " + err);
}
});
self.emit('error', "Didn't find right amount of data in todo!"); // Note nothing picks this up yet
}
});
});
};
HMailItem.prototype.send = function () {
if (cfg.disabled) {
// try again in 1 second if delivery is disabled
this.logdebug("delivery disabled temporarily. Retrying in 1s.");
var hmail = this;
setTimeout(function () { hmail.send(); }, 1000);
return;
}
if (!this.todo) {
var self = this;
this.once('ready', function () { self._send(); });
}
else {
this._send();
}
};
HMailItem.prototype._send = function () {
plugins.run_hooks('send_email', this);
};
HMailItem.prototype.send_email_respond = function (retval, delay_seconds) {
if (retval === constants.delay) {