-
-
Notifications
You must be signed in to change notification settings - Fork 661
/
plugins.js
616 lines (533 loc) · 19.3 KB
/
plugins.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
'use strict';
// load all defined plugins
// node built-ins
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
// npm modules
exports.config = require('haraka-config');
const constants = require('haraka-constants');
// local modules
const logger = require('./logger');
exports.registered_hooks = {};
exports.registered_plugins = {};
exports.plugin_list = [];
let order = 0;
class Plugin {
constructor (name) {
this.name = name;
this.base = {};
this.timeout = get_timeout(name);
this._get_plugin_path();
this.config = this._get_config();
this.hooks = {};
}
haraka_require (name) {
return require(`./${name}`);
}
core_require (name) {
return this.haraka_require(name);
}
_get_plugin_path () {
/* From https://github.com/haraka/Haraka/pull/1278#issuecomment-168856528
In Development mode, or install via a plain "git clone":
Plain plugin in plugins/ folder
Plugin in a folder in plugins/<name>/ folder. Contains a package.json.
Plugin in node_modules. Contains a package.json file.
In "installed" mode (via haraka -i <path>):
Plain plugin in <path>/plugins/ folder
Plugin in a folder in <path>/plugins/<name>/folder. (same concept as above)
Plugin in <path>/node_modules. Contains a package.json file.
Core plugin in <core_haraka_dir>/plugins/ folder
Plugin in a folder in <core_haraka_dir>/plugins/<name>/ folder. (same concept as above)
Plugin in <core_haraka_dir>/node_modules.
*/
this.hasPackageJson = false;
const name = this.name.startsWith('haraka-plugin-') ? this.name.substr(14) : this.name;
if (this.name !== name) this.name = name;
let paths = [];
if (process.env.HARAKA) {
// Installed mode - started via bin/haraka
paths = paths.concat(plugin_search_paths(process.env.HARAKA, name));
// permit local "folder" plugins (/$name/package.json) (see #1649)
paths.push(
path.resolve(process.env.HARAKA, 'plugins', name, 'package.json'),
path.resolve(process.env.HARAKA, 'node_modules', name, 'package.json')
);
}
// development mode
paths = paths.concat(plugin_search_paths(__dirname, name));
for (const pp of paths) {
if (this.plugin_path) continue;
try {
fs.statSync(pp);
this.plugin_path = pp;
if (path.basename(pp) === 'package.json') {
this.hasPackageJson = true;
}
}
catch (ignore) {}
}
}
_get_config () {
if (this.hasPackageJson) {
// It's a package/folder plugin - look in plugin folder for defaults,
// haraka/config folder for overrides
return exports.config.module_config(
path.dirname(this.plugin_path),
process.env.HARAKA || __dirname
);
}
if (process.env.HARAKA) {
// Plain .js file, installed mode - look in core folder for defaults,
// install dir for overrides
return exports.config.module_config(__dirname, process.env.HARAKA);
}
if (process.env.HARAKA_TEST_DIR) {
return exports.config.module_config(process.env.HARAKA_TEST_DIR);
}
// Plain .js file, git mode - just look in this folder
return exports.config.module_config(__dirname);
}
register_hook (hook_name, method_name, priority) {
priority = parseInt(priority);
if (!priority) priority = 0;
if (priority > 100) priority = 100;
if (priority < -100) priority = -100;
if (!Array.isArray(exports.registered_hooks[hook_name])) {
exports.registered_hooks[hook_name] = [];
}
exports.registered_hooks[hook_name].push({
plugin: this.name,
method: method_name,
priority,
timeout: this.timeout,
order: order++
});
this.hooks[hook_name] = this.hooks[hook_name] || [];
this.hooks[hook_name].push(method_name);
plugins.logdebug(`registered hook ${hook_name} to ${this.name}.${method_name} priority ${priority}`);
}
register () {} // noop
inherits (parent_name) {
const parent_plugin = plugins._load_and_compile_plugin(parent_name);
for (const method in parent_plugin) {
if (!this[method]) {
this[method] = parent_plugin[method];
}
}
if (parent_plugin.register) {
parent_plugin.register.call(this);
}
this.base[parent_name] = parent_plugin;
}
_make_custom_require () {
return module => {
if (this.hasPackageJson) {
const mod = require(module);
constants.import(global);
global.server = plugins.server;
return mod;
}
if (module === './config') {
return this.config;
}
if (!/^\./.test(module)) {
return require(module);
}
if (fs.existsSync(path.join(__dirname, `${module}.js`)) ||
fs.existsSync(path.join(__dirname, module))) {
return require(module);
}
return require(path.join(path.dirname(this.plugin_path), module));
};
}
_get_code (pp) {
if (this.hasPackageJson) {
let packageDir = path.dirname(pp);
if (/^win(32|64)/.test(process.platform)) {
// escape the c:\path\back\slashes else they disappear
packageDir = packageDir.replace(/\\/g, '\\\\');
}
return `var _p = require("${packageDir}"); for (var k in _p) { exports[k] = _p[k] }`;
}
try {
return `"use strict";${fs.readFileSync(pp)}`;
}
catch (err) {
if (exports.config.get('smtp.ini').main.ignore_bad_plugins) {
plugins.logcrit(`Loading ${this.name} failed: ${err}`);
return;
}
throw `Loading plugin ${this.name} failed: ${err}`;
}
}
_compile () {
const pp = this.plugin_path;
const code = this._get_code(pp);
if (!code) return;
const sandbox = {
require: this._make_custom_require(),
__filename: pp,
__dirname: path.dirname(pp),
exports: this,
setTimeout,
clearTimeout,
setInterval,
clearInterval,
process,
Buffer,
Math,
server: plugins.server,
setImmediate
};
if (this.hasPackageJson) {
delete sandbox.__filename;
}
constants.import(sandbox);
try {
vm.runInNewContext(code, sandbox, pp);
}
catch (err) {
plugins.logcrit(`compiling '${this.name}' failed`);
if (exports.config.get('smtp.ini').main.ignore_bad_plugins) {
plugins.logcrit(`Loading '${this.name}' failed: ${err.message} - skipping`);
return;
}
throw err; // default is to re-throw and stop Haraka
}
}
}
exports.shutdown_plugins = () => {
for (const i in exports.registered_plugins) {
if (exports.registered_plugins[i].shutdown) {
exports.registered_plugins[i].shutdown();
}
}
}
process.on('message', msg => {
if (msg.event && msg.event == 'plugins.shutdown') {
plugins.loginfo("Shutting down");
exports.shutdown_plugins();
}
});
function plugin_search_paths (prefix, name) {
return [
path.resolve(prefix, 'plugins', `${name}.js`),
path.resolve(prefix, 'node_modules', `haraka-plugin-${name}`, 'package.json'),
path.resolve(prefix, '..', `haraka-plugin-${name}`, 'package.json')
];
}
function get_timeout (name) {
let timeout = parseFloat((exports.config.get(`${name}.timeout`)));
if (isNaN(timeout)) {
plugins.logdebug(`no timeout in ${name}.timeout`);
timeout = parseFloat(exports.config.get('plugin_timeout'));
}
if (isNaN(timeout)) {
plugins.logdebug('no timeout in plugin_timeout');
timeout = 30;
}
plugins.logdebug(`plugin ${name} timeout is: ${timeout}s`);
return timeout;
}
logger.add_log_methods(Plugin)
const plugins = exports;
logger.add_log_methods(plugins, 'plugins')
plugins.Plugin = Plugin;
plugins.load_plugins = override => {
plugins.logdebug('Loading');
let plugin_list;
if (override) {
if (!Array.isArray(override)) override = [ override ];
plugin_list = override;
}
else {
plugin_list = exports.config.get('plugins', 'list');
}
for (let plugin of plugin_list) {
if (plugin.startsWith('haraka-plugin-')) plugin = plugin.substr(14)
if (plugins.deprecated[plugin]) {
plugins.lognotice(`${plugin} has been replaced by '${plugins.deprecated[plugin]}'. Please update config/plugins`)
plugins.load_plugin(plugins.deprecated[plugin]);
}
else {
plugins.load_plugin(plugin);
}
}
plugins.plugin_list = Object.keys(plugins.registered_plugins);
// Sort registered_hooks by priority
for (const hook of Object.keys(plugins.registered_hooks)) {
plugins.registered_hooks[hook].sort((a, b) => {
if (a.priority < b.priority) return -1;
if (a.priority > b.priority) return 1;
if (a.priority == b.priority) {
if (a.order > b.order) return 1;
return -1;
}
return 0;
});
}
logger.dump_logs(); // now logging plugins are loaded.
}
plugins.deprecated = {
'auth/auth_ldap' : 'auth-ldap',
'backscatterer' : 'dns-list',
'connect.asn' : 'asn',
'connect.fcrdns' : 'fcrdns',
'connect.geoip' : 'geoip',
'connect.p0f' : 'p0f',
'connect.rdns_access' : 'access',
'data.nomsgid' : 'headers',
'data.noreceived' : 'headers',
'data.rfc5322_header_checks': 'headers',
'data.headers' : 'headers',
'dkim_sign' : 'dkim',
'dkim_verify' : 'dkim',
'data.uribl' : 'uribl',
'dnsbl' : 'dns-list',
'dnswl' : 'dns-list',
'log.syslog' : 'syslog',
'mail_from.access' : 'access',
'mail_from.blocklist' : 'access',
'mail_from.nobounces' : 'bounce',
'max_unrecognized_commands' : 'limit',
'rate_limit' : 'limit',
'rcpt_to.access' : 'access',
'rcpt_to.blocklist' : 'access',
'rcpt_to.ldap' : 'rcpt-ldap',
'rcpt_to.max_count' : 'limit',
'rcpt_to.qmail_deliverable' : 'qmail-deliverable',
'rdns.regexp' : 'access',
'relay_acl' : 'relay',
'relay_all' : 'relay',
'relay_force_routing' : 'relay',
}
plugins.load_plugin = name => {
plugins.loginfo(`loading ${name}`);
const plugin = plugins._load_and_compile_plugin(name);
if (plugin) {
plugins._register_plugin(plugin);
}
plugins.registered_plugins[name] = plugin;
}
// Set in server.js; initialized to empty object
// to prevent it from blowing up any unit tests.
plugins.server = { notes: {} };
plugins._load_and_compile_plugin = name => {
const plugin = new Plugin(name);
if (!plugin.plugin_path) {
const err = `Loading plugin ${plugin.name} failed: No plugin with this name found`;
if (exports.config.get('smtp.ini').main.ignore_bad_plugins) {
plugins.logcrit(err);
return;
}
throw err;
}
plugin._compile();
return plugin;
}
plugins._register_plugin = plugin => {
plugin.register();
// register any hook_blah methods.
for (const method in plugin) {
const result = method.match(/^hook_(\w+)\b/);
if (result) {
plugin.register_hook(result[1], method);
}
}
}
plugins.run_hooks = (hook, object, params) => {
if (client_disconnected(object) && !is_required_hook(hook)) {
object.logdebug(`aborting ${hook} hook`);
return;
}
if (hook !== 'log') object.logdebug(`running ${hook} hooks`);
if (is_required_hook(hook) && object.current_hook) {
object.current_hook[2](); // call cancel function
}
if (!is_required_hook(hook) && hook !== 'deny' &&
object.hooks_to_run && object.hooks_to_run.length) {
throw new Error('We are already running hooks! Fatal error!');
}
if (hook === 'deny') {
// Save the hooks_to_run list so that we can run any remaining
// plugins on the previous hook once this hook is complete.
object.saved_hooks_to_run = object.hooks_to_run;
}
object.hooks_to_run = [];
if (plugins.registered_hooks[hook]) {
for (const item of plugins.registered_hooks[hook]) {
const plugin = plugins.registered_plugins[item.plugin];
object.hooks_to_run.push([plugin, item.method]);
}
}
plugins.run_next_hook(hook, object, params);
}
plugins.run_next_hook = (hook, object, params) => {
if (client_disconnected(object) && !is_required_hook(hook)) {
object.logdebug(`aborting ${hook} hook`);
return;
}
let called_once = false;
let timeout_id;
let timed_out = false;
let cancelled = false;
let item;
function cancel () {
if (timeout_id) clearTimeout(timeout_id);
cancelled = true;
}
function callback (retval, msg) {
if (timeout_id) clearTimeout(timeout_id);
object.current_hook = null;
if (cancelled) return; // This hook has been cancelled
// Bail if client has disconnected
if (client_disconnected(object) && !is_required_hook(hook)) {
object.logdebug(`ignoring ${item[0].name} plugin callback`);
return;
}
if (called_once && hook !== 'log') {
if (!timed_out) {
object.logerror(`${item[0].name} plugin ran callback ` +
`multiple times - ignoring subsequent calls`);
// Write a stack trace to the log to aid debugging
object.logerror((new Error()).stack);
}
return;
}
called_once = true;
if (!retval) retval = constants.cont;
log_run_item(item, hook, retval, object, params, msg);
if (object.hooks_to_run.length !== 0) {
if (retval === constants.cont) {
return plugins.run_next_hook(hook, object, params);
}
if (hook === 'connect_init' || hook === 'disconnect') {
// these hooks ignore retval and always run for every plugin
return plugins.run_next_hook(hook, object, params);
}
}
const respond_method = `${hook}_respond`;
if (item && is_deny_retval(retval) && hook.substr(0,5) !== 'init_') {
object.deny_respond = get_denyfn(object, hook, params, retval, msg, respond_method);
plugins.run_hooks('deny', object, [retval, msg, item[0].name, item[1], params, hook]);
}
else {
object.hooks_to_run = [];
object[respond_method](retval, msg, params);
}
}
if (!object.hooks_to_run.length) return callback();
// shift the next one off the stack and run it.
item = object.hooks_to_run.shift();
item.push(cancel);
if (hook !== 'log' && item[0].timeout) {
timeout_id = setTimeout(() => {
timed_out = true;
object.logcrit(`Plugin ${item[0].name} timed out on hook ${hook} - make sure it calls the callback`);
callback(constants.denysoft, 'plugin timeout');
}, item[0].timeout * 1000);
}
if (hook !== 'log') {
object.logdebug(`running ${hook} hook in ${item[0].name} plugin`);
}
if (object.transaction?.notes.skip_plugins.includes(item[0].name)) {
object.logdebug(`skipping ${item[0].name}_${hook} by request in notes`);
return callback();
}
try {
object.current_hook = item;
object.hook = hook;
item[0][ item[1] ].call(item[0], callback, object, params);
}
catch (err) {
if (hook !== 'log') {
object.logcrit(`Plugin ${item[0].name} failed: ${(err.stack || err)}`);
}
callback();
}
}
function client_disconnected (object) {
if (object.constructor.name === 'Connection' &&
object.state >= constants.connection.state.DISCONNECTING) {
object.logdebug('client has disconnected');
return true;
}
return false;
}
function is_required_hook (hook) {
// Hooks that must always run
switch (hook) {
case 'reset_transaction':
case 'disconnect':
case 'log':
return true;
default:
return false;
}
}
function log_run_item (item, hook, retval, object, params, msg) {
if (!item) return;
if (hook === 'log') return;
let log = 'logdebug';
const is_not_cont = (retval !== constants.cont &&
logger.would_log(logger.LOGINFO));
if (is_not_cont) log = 'loginfo';
if (is_not_cont || logger.would_log(logger.LOGDEBUG)) {
object[log]({
hook,
'plugin' : item[0].name,
'function' : item[1],
'params' : ((params) ? ((typeof params === 'string') ? params : params[0]) : ''),
'retval' : constants.translate(retval),
'msg' : sanitize(msg),
});
}
}
function sanitize (msg) {
if (!msg) return ''
if (typeof msg === 'string') return msg
if (typeof msg === 'object') {
if (msg.constructor.name === 'DSN') return msg.reply
const sanitized = { ...msg }; // copy the message
for (const priv of ['password','auth_pass']) {
delete sanitized[priv]
}
return JSON.stringify(sanitized)
}
logger.logerror(`what is ${msg} (typeof ${typeof msg})?`)
}
function is_deny_retval (val) {
switch (val) {
case constants.deny:
case constants.denysoft:
case constants.denydisconnect:
case constants.denysoftdisconnect:
return true;
}
return false;
}
function get_denyfn (object, hook, params, retval, msg, respond_method) {
return (deny_retval, deny_msg) => {
switch (deny_retval) {
case constants.ok:
// Override rejection
object.loginfo(`deny(soft?) overriden by deny hook${(deny_msg ? ': deny_msg' : '')}`);
// Restore hooks_to_run with saved copy so that
// any other plugins on this hook can also run.
if (object.saved_hooks_to_run.length > 0) {
object.hooks_to_run = object.saved_hooks_to_run;
plugins.run_next_hook(hook, object, params);
}
else {
object[respond_method](constants.cont, deny_msg, params);
}
break;
default:
object.saved_hooks_to_run = [];
object.hooks_to_run = [];
object[respond_method](retval, msg, params);
}
};
}