wildduck/lmtp.js

296 lines
8.6 KiB
JavaScript
Raw Normal View History

'use strict';
2017-04-13 02:59:30 +08:00
// Simple LMTP server that accepts all messages for valid recipients
2017-07-16 19:37:33 +08:00
const config = require('wild-config');
const log = require('npmlog');
2017-10-18 17:42:51 +08:00
const ObjectID = require('mongodb').ObjectID;
const SMTPServer = require('smtp-server').SMTPServer;
const tools = require('./lib/tools');
const MessageHandler = require('./lib/message-handler');
2017-10-18 17:42:51 +08:00
const FilterHandler = require('./lib/filter-handler');
const db = require('./lib/db');
const certs = require('./lib/certs');
let messageHandler;
2017-10-18 17:42:51 +08:00
let filterHandler;
let spamChecks, spamHeaderKeys;
config.on('reload', () => {
2017-10-18 17:42:51 +08:00
spamChecks = prepareSpamChecks(config.spamHeader);
spamHeaderKeys = spamChecks.map(check => check.key);
2017-10-18 17:42:51 +08:00
if (filterHandler) {
filterHandler.spamChecks = spamChecks;
filterHandler.spamHeaderKeys = spamHeaderKeys;
}
log.info('LMTP', 'Configuration reloaded');
});
2017-04-12 19:52:29 +08:00
const serverOptions = {
lmtp: true,
// log to console
logger: {
info(...args) {
args.shift();
2017-04-12 19:52:29 +08:00
log.info('LMTP', ...args);
},
debug(...args) {
args.shift();
2017-04-12 19:52:29 +08:00
log.silly('LMTP', ...args);
},
error(...args) {
args.shift();
2017-04-12 19:52:29 +08:00
log.error('LMTP', ...args);
}
},
2017-09-11 03:53:12 +08:00
name: config.lmtp.name || false,
// not required but nice-to-have
2017-07-27 16:47:32 +08:00
banner: config.lmtp.banner || 'Welcome to Wild Duck Mail Server',
2017-09-11 03:53:12 +08:00
disabledCommands: ['AUTH'].concat(config.lmtp.disableSTARTTLS ? 'STARTTLS' : []),
2017-03-30 01:06:09 +08:00
onMailFrom(address, session, callback) {
// reset session entries
2017-04-12 19:52:29 +08:00
session.users = [];
2017-03-30 01:06:09 +08:00
2017-04-12 19:52:29 +08:00
// accept alls sender addresses
2017-03-30 01:06:09 +08:00
return callback();
},
// Validate RCPT TO envelope address. Example allows all addresses that do not start with 'deny'
// If this method is not set, all addresses are allowed
onRcptTo(rcpt, session, callback) {
let originalRecipient = tools.normalizeAddress(rcpt.address);
let recipient = originalRecipient.replace(/\+[^@]*@/, '@');
db.users.collection('addresses').findOne({
2017-07-31 15:59:18 +08:00
addrview: recipient.substr(0, recipient.indexOf('@')).replace(/\./g, '') + recipient.substr(recipient.indexOf('@'))
}, (err, address) => {
if (err) {
2017-04-12 19:52:29 +08:00
log.error('LMTP', err);
return callback(new Error('Database error'));
}
if (!address) {
return callback(new Error('Unknown recipient'));
}
db.users.collection('users').findOne({
_id: address.user
2017-04-14 04:30:39 +08:00
}, {
fields: {
2017-05-08 00:00:04 +08:00
name: true,
forwards: true,
2017-05-07 20:09:14 +08:00
forward: true,
2017-05-08 00:00:04 +08:00
targetUrl: true,
autoreply: true,
encryptMessages: true,
pubKey: true
2017-04-14 04:30:39 +08:00
}
}, (err, user) => {
if (err) {
2017-04-12 19:52:29 +08:00
log.error('LMTP', err);
return callback(new Error('Database error'));
}
2017-03-28 01:53:13 +08:00
if (!user) {
return callback(new Error('Unknown recipient'));
}
if (!session.users) {
2017-04-12 19:52:29 +08:00
session.users = [];
}
2017-04-12 19:52:29 +08:00
session.users.push({
recipient: originalRecipient,
2017-04-14 04:30:39 +08:00
user
});
callback();
});
});
},
// Handle message stream
onData(stream, session, callback) {
let chunks = [];
let chunklen = 0;
2017-04-13 16:35:39 +08:00
stream.on('readable', () => {
let chunk;
2017-04-13 16:35:39 +08:00
while ((chunk = stream.read()) !== null) {
2017-04-12 19:52:29 +08:00
chunks.push(chunk);
chunklen += chunk.length;
}
});
stream.once('error', err => {
2017-04-12 19:52:29 +08:00
log.error('LMTP', err);
callback(new Error('Error reading from stream'));
});
2017-04-13 16:35:39 +08:00
stream.once('end', () => {
2017-06-03 14:51:58 +08:00
let sender = tools.normalizeAddress((session.envelope.mailFrom && session.envelope.mailFrom.address) || '');
2017-04-12 19:52:29 +08:00
let responses = [];
let users = session.users;
let stored = 0;
2017-04-13 16:35:39 +08:00
2017-10-18 17:42:51 +08:00
let transactionId = new ObjectID();
let prepared = false;
let storeNext = () => {
if (stored >= users.length) {
2017-04-12 20:21:38 +08:00
return callback(null, responses.map(r => r.response));
}
2017-04-12 19:52:29 +08:00
let rcptData = users[stored++];
let recipient = rcptData.recipient;
2017-09-16 00:11:42 +08:00
let userData = rcptData.user;
2017-04-12 19:52:29 +08:00
2017-09-16 00:11:42 +08:00
let response = responses.filter(r => r.userData === userData);
2017-04-12 19:52:29 +08:00
if (response.length) {
responses.push(response[0]);
return storeNext();
}
2017-10-18 17:42:51 +08:00
filterHandler.process(
{
mimeTree: prepared && prepared.mimeTree,
maildata: prepared && prepared.maildata,
2017-10-18 17:42:51 +08:00
user: userData,
sender,
recipient,
chunks,
chunklen,
meta: {
transactionId,
source: 'MX',
2017-10-18 17:42:51 +08:00
from: sender,
2017-10-20 18:43:44 +08:00
to: [recipient],
2017-10-18 17:42:51 +08:00
origin: session.remoteAddress,
originhost: session.clientHostname,
transhost: session.hostNameAppearsAs,
transtype: session.transmissionType,
2017-10-20 18:43:44 +08:00
time: new Date()
2017-10-18 17:42:51 +08:00
}
},
(err, response, preparedResponse) => {
if (err) {
2017-10-18 17:42:51 +08:00
// ???
}
2017-10-18 17:42:51 +08:00
if (response) {
responses.push(response);
}
if (!prepared && preparedResponse) {
prepared = preparedResponse;
}
2017-10-18 17:42:51 +08:00
setImmediate(storeNext);
}
);
};
storeNext();
});
}
2017-04-12 19:52:29 +08:00
};
certs.loadTLSOptions(serverOptions, 'lmtp');
2017-04-12 19:52:29 +08:00
const server = new SMTPServer(serverOptions);
certs.registerReload(server, 'lmtp');
module.exports = done => {
2017-04-12 19:52:29 +08:00
if (!config.lmtp.enabled) {
return setImmediate(() => done(null, false));
}
2017-10-18 17:42:51 +08:00
spamChecks = prepareSpamChecks(config.spamHeader);
spamHeaderKeys = spamChecks.map(check => check.key);
2017-08-07 02:25:10 +08:00
messageHandler = new MessageHandler({
database: db.database,
users: db.users,
redis: db.redis,
gridfs: db.gridfs,
attachments: config.attachments
2017-08-07 02:25:10 +08:00
});
2017-10-18 17:42:51 +08:00
filterHandler = new FilterHandler({
database: db.database,
users: db.users,
redis: db.redis,
messageHandler,
spamHeaderKeys,
spamChecks
});
let started = false;
server.on('error', err => {
if (!started) {
started = true;
return done(err);
}
2017-04-12 19:52:29 +08:00
log.error('LMTP', err);
});
2017-04-12 19:52:29 +08:00
server.listen(config.lmtp.port, config.lmtp.host, () => {
if (started) {
return server.close();
}
started = true;
done(null, server);
});
};
2017-04-16 02:59:27 +08:00
2017-10-18 17:42:51 +08:00
function prepareSpamChecks(spamHeader) {
return (Array.isArray(spamHeader) ? spamHeader : [].concat(spamHeader || []))
.map(header => {
if (!header) {
return false;
}
// If only a single header key is specified, check if it matches Yes
if (typeof header === 'string') {
header = {
key: header,
value: '^yes',
target: '\\Junk'
};
}
let key = (header.key || '')
.toString()
.trim()
.toLowerCase();
let value = (header.value || '').toString().trim();
try {
if (value) {
value = new RegExp(value, 'i');
value.isRegex = true;
}
} catch (E) {
value = false;
log.error('LMTP', 'Failed loading spam header rule %s. %s', JSON.stringify(header.value), E.message);
}
if (!key || !value) {
return false;
}
let target = (header.target || '').toString().trim() || 'INBOX';
return {
key,
value,
target
};
})
.filter(check => check);
}