forked from haraka/Haraka
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
350 lines (293 loc) · 10.6 KB
/
index.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
'use strict';
const fs = require('fs');
const path = require('path');
const async = require('async');
const { Address } = require('address-rfc2821');
const config = require('haraka-config');
const constants = require('haraka-constants');
const net_utils = require('haraka-net-utils');
const utils = require('haraka-utils');
const ResultStore = require('haraka-results');
const logger = require('../logger');
const trans = require('../transaction');
const plugins = require('../plugins');
const FsyncWriteStream = require('./fsync_writestream');
const obc = require('./config');
const queuelib = require('./queue');
const HMailItem = require('./hmail');
const TODOItem = require('./todo');
const _qfile = exports.qfile = require('./qfile');
const { queue_dir, temp_fail_queue, delivery_queue } = queuelib;
exports.temp_fail_queue = temp_fail_queue;
exports.delivery_queue = delivery_queue;
exports.net_utils = net_utils;
exports.config = config;
exports.get_stats = queuelib.get_stats;
exports.list_queue = queuelib.list_queue;
exports.stat_queue = queuelib.stat_queue;
exports.scan_queue_pids = queuelib.scan_queue_pids;
exports.flush_queue = queuelib.flush_queue;
exports.load_pid_queue = queuelib.load_pid_queue;
exports.ensure_queue_dir = queuelib.ensure_queue_dir;
exports.load_queue = queuelib.load_queue;
exports.stats = queuelib.stats;
process.on('message', msg => {
if (!msg.event) return
if (msg.event === 'outbound.load_pid_queue') {
exports.load_pid_queue(msg.data);
return;
}
if (msg.event === 'outbound.flush_queue') {
exports.flush_queue(msg.domain, process.pid);
return;
}
if (msg.event === 'outbound.shutdown') {
logger.loginfo("[outbound] Shutting down temp fail queue");
temp_fail_queue.shutdown();
return;
}
// ignores the message
});
exports.send_email = function () {
if (arguments.length === 2) {
logger.logdebug("[outbound] Sending email as a transaction");
return this.send_trans_email(arguments[0], arguments[1]);
}
let from = arguments[0];
let to = arguments[1];
let contents = arguments[2];
const next = arguments[3];
const options = arguments[4] || {};
const dot_stuffed = options.dot_stuffed ? options.dot_stuffed : false;
const notes = options.notes ? options.notes : null;
const origin = options.origin ? options.origin : null;
logger.loginfo("[outbound] Sending email via params", origin);
const transaction = trans.createTransaction();
logger.loginfo(`[outbound] Created transaction: ${transaction.uuid}`, origin);
//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 (let 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') {
let match;
while ((match = utils.line_regexp.exec(contents))) {
let 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(Buffer.from(line));
contents = contents.substr(match[1].length);
if (contents.length === 0) {
break;
}
}
}
else {
// Assume a stream
return stream_line_reader(contents, transaction, 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();
// Allow for the removal of Message-Id and/or Date headers which
// is useful when resending mail from a quarantine.
if (options.remove_msgid) {
transaction.remove_header('Message-Id');
}
if (options.remove_date) {
transaction.remove_header('Date');
}
this.send_trans_email(transaction, next);
}
function stream_line_reader (stream, transaction, cb) {
let current_data = '';
function process_data (data) {
current_data += data.toString();
let results;
while ((results = utils.line_regexp.exec(current_data))) {
const this_line = results[1];
current_data = current_data.slice(this_line.length);
if (!(current_data.length || this_line.length)) {
return;
}
transaction.add_data(Buffer.from(this_line));
}
}
function process_end () {
if (current_data.length) {
transaction.add_data(Buffer.from(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);
}
function get_deliveries (transaction) {
const deliveries = [];
if (obc.cfg.always_split) {
logger.logdebug({name: "outbound"}, "always split");
transaction.rcpt_to.forEach(rcpt => {
deliveries.push({domain: rcpt.host, rcpts: [ rcpt ]});
});
return deliveries;
}
// First get each domain
const recips = {};
transaction.rcpt_to.forEach(rcpt => {
const domain = rcpt.host;
if (!recips[domain]) { recips[domain] = []; }
recips[domain].push(rcpt);
});
Object.keys(recips).forEach(domain => {
deliveries.push({domain, 'rcpts': recips[domain]});
});
return deliveries;
}
exports.send_trans_email = function (transaction, next) {
// add 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}@${net_utils.get_primary_host_name()}>`);
}
if (!transaction.header.get_all('Date').length) {
logger.loginfo("[outbound] Adding missing Date header");
transaction.add_header('Date', utils.date_to_str(new Date()));
}
if (obc.cfg.received_header !== 'disabled') {
transaction.add_leading_header('Received', `(${obc.cfg.received_header}); ${utils.date_to_str(new Date())}`);
}
const connection = { transaction };
logger.add_log_methods(connection);
if (!transaction.results) {
logger.logdebug('adding results store');
transaction.results = new ResultStore(connection);
}
connection.pre_send_trans_email_respond = retval => {
const deliveries = get_deliveries(transaction);
const hmails = [];
const ok_paths = [];
let todo_index = 1;
async.forEachSeries(deliveries, (deliv, cb) => {
const todo = new TODOItem(deliv.domain, deliv.rcpts, transaction);
todo.uuid = `${todo.uuid}.${todo_index}`;
todo_index++;
this.process_delivery(ok_paths, todo, hmails, cb);
},
(err) => {
if (err) {
for (let i=0, l=ok_paths.length; i<l; i++) {
fs.unlink(ok_paths[i], () => {});
}
transaction.results.add({ name: 'outbound'}, { err });
if (next) next(constants.denysoft, err);
return;
}
for (const hmail of hmails) {
delivery_queue.push(hmail);
}
transaction.results.add({ name: 'outbound'}, { pass: "queued" });
if (next) {
next(constants.ok, `Message Queued (${transaction.uuid})`);
}
});
}
plugins.run_hooks('pre_send_trans_email', connection);
}
exports.process_delivery = function (ok_paths, todo, hmails, cb) {
logger.loginfo(`[outbound] Transaction delivery for domain: ${todo.domain}`);
const fname = _qfile.name();
const tmp_path = path.join(queue_dir, `${_qfile.platformDOT}${fname}`);
const ws = new FsyncWriteStream(tmp_path, { flags: constants.WRITE_EXCL });
ws.on('close', () => {
const dest_path = path.join(queue_dir, fname);
fs.rename(tmp_path, dest_path, err => {
if (err) {
logger.logerror(`[outbound] Unable to rename tmp file!: ${err}`);
fs.unlink(tmp_path, () => {});
cb("Queue error");
}
else {
hmails.push(new HMailItem (fname, dest_path, todo.notes));
ok_paths.push(dest_path);
cb();
}
})
})
ws.on('error', err => {
logger.logerror(`[outbound] Unable to write queue file (${fname}): ${err}`);
ws.destroy();
fs.unlink(tmp_path, () => {});
cb("Queueing failed");
})
this.build_todo(todo, ws, () => {
todo.message_stream.pipe(ws, { line_endings: '\r\n', dot_stuffing: true, ending_dot: false });
});
}
exports.build_todo = (todo, ws, write_more) => {
const todo_str = `\n${JSON.stringify(todo, exclude_from_json, '\t')}\n`
const todo_len = Buffer.byteLength(todo_str)
const buf = Buffer.alloc(4 + todo_len);
buf.writeUInt32BE(todo_len, 0);
buf.write(todo_str, 4);
const continue_writing = ws.write(buf);
if (continue_writing) {
process.nextTick(write_more);
return
}
ws.once('drain', 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;
}
}
// exported for testability
exports.TODOItem = TODOItem;
exports.HMailItem = HMailItem;
exports.lookup_mx = require('./mx_lookup').lookup_mx;