File: lda-sieve-plugin.c

package info (click to toggle)
dovecot 1%3A1.2.15-7
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 30,252 kB
  • ctags: 19,837
  • sloc: ansic: 191,438; sh: 21,091; makefile: 3,330; cpp: 526; perl: 108; xml: 44
file content (721 lines) | stat: -rw-r--r-- 17,565 bytes parent folder | download | duplicates (2)
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
/* Copyright (c) 2002-2010 Dovecot Sieve authors, see the included COPYING file
 */

#include "lib.h"
#include "str.h"
#include "array.h"
#include "home-expand.h"
#include "deliver.h"
#include "duplicate.h"
#include "smtp-client.h"
#include "imap-utf7.h"
#include "eacces-error.h"

#include "sieve.h"

#include "lda-sieve-plugin.h"

#include <stdlib.h>
#include <sys/stat.h>
#include <dirent.h>

/*
 * Configuration
 */

#define SIEVE_SCRIPT_PATH "~/.dovecot.sieve"

#define LDA_SIEVE_MAX_USER_ERRORS 10
#define LDA_SIEVE_MAX_SYSTEM_ERRORS 100

/*
 * Global variables
 */

static deliver_mail_func_t *next_deliver_mail;

static bool lda_sieve_debug = FALSE;

/*
 * Settings management
 */

static const char *lda_sieve_get_homedir
(void *context ATTR_UNUSED)
{
	return getenv("HOME");
}

static const char *lda_sieve_get_setting
(void *context ATTR_UNUSED, const char *identifier)
{
	return getenv(t_str_ucase(identifier));
}

static const struct sieve_environment lda_sieve_env = {
	lda_sieve_get_homedir,
	lda_sieve_get_setting
};

/*
 * Mail transmission
 */

static void *lda_sieve_smtp_open(const char *destination,
	const char *return_path, FILE **file_r)
{
	return (void *) smtp_client_open(destination, return_path, file_r);
}

static bool lda_sieve_smtp_close(void *handle)
{
	struct smtp_client *smtp_client = (struct smtp_client *) handle;

	return ( smtp_client_close(smtp_client) == 0 );
}

/*
 * Plugin implementation
 */

struct lda_sieve_run_context {
	struct sieve_instance *svinst;

	const char *const *script_files;
	unsigned int script_count;

	const char *user_script;
	const char *main_script;

	const struct sieve_message_data *msgdata;
	const struct sieve_script_env *scriptenv;

	struct sieve_error_handler *user_ehandler;
	struct sieve_error_handler *master_ehandler;
	const char *userlog;
};

static const char *lda_sieve_get_personal_path(void)
{
	const char *script_path, *home;

	home = getenv("HOME");

	/* userdb may specify Sieve path */
	script_path = getenv("SIEVE");
	if (script_path != NULL) {
		if (*script_path == '\0') {
			/* disabled */
			if ( lda_sieve_debug )
				sieve_sys_info("empty script path, disabled");
			return NULL;
		}

		script_path = home_expand(script_path);

		if (*script_path != '/' && *script_path != '\0') {
			/* relative path. change to absolute. */
			script_path = t_strconcat(getenv("HOME"), "/",
						  script_path, NULL);
		}
	} else {
		if (home == NULL) {
			sieve_sys_error(
				"path to user's main active personal script is unknown. "
				"See http://wiki.dovecot.org/LDA/Sieve/Dovecot#configuration");
			return NULL;
		}

		script_path = home_expand(SIEVE_SCRIPT_PATH);
	}

	return script_path;
}

static const char *lda_sieve_get_default_path(void)
{
	const char *script_path;

	/* Use global script path, if one exists */
	script_path = getenv("SIEVE_GLOBAL_PATH");
	if (script_path == NULL) {
		/* For backwards compatibility */
		script_path = getenv("GLOBAL_SCRIPT_PATH");
	}

	return script_path;
}

static void lda_sieve_multiscript_get_scriptfiles
(const char *script_path, ARRAY_TYPE(const_string) *scriptfiles)
{
	struct sieve_directory *sdir = sieve_directory_open(script_path);

	if ( sdir != NULL ) {
		const char *file;

		while ( (file=sieve_directory_get_scriptfile(sdir)) != NULL ) {
			const char *const *scripts;
			unsigned int count, i;

			/* Insert into sorted array */

			scripts = array_get(scriptfiles, &count);
			for ( i = 0; i < count; i++ ) {
				if ( strcmp(file, scripts[i]) < 0 )
					break;
			}

			if ( i == count )
				array_append(scriptfiles, &file, 1);
			else
				array_insert(scriptfiles, i, &file, 1);
		}

		sieve_directory_close(&sdir);
	}
}

static int lda_sieve_open
(struct lda_sieve_run_context *srctx, unsigned int script_index,
	struct sieve_binary **sbin)
{
	struct sieve_instance *svinst = srctx->svinst;
	const char *script_path = srctx->script_files[script_index];
	const char *script_name =
		( script_path == srctx->main_script ? "main_script" : NULL );
	struct sieve_error_handler *ehandler;
	bool exists = TRUE;
	int ret = 0;

	if ( script_path == srctx->user_script )
		ehandler = srctx->user_ehandler;
	else
		ehandler = srctx->master_ehandler;

	if ( lda_sieve_debug )
		sieve_sys_info("opening script %s", script_path);

	sieve_error_handler_reset(ehandler);

	if ( (*sbin=sieve_open(svinst, script_path, script_name, ehandler, &exists))
		== NULL ) {

		ret = sieve_get_errors(ehandler) > 0 ? -1 : 0;

		if ( !exists && ret == 0 ) {
			if ( lda_sieve_debug )
				sieve_sys_info("script file %s is missing", script_path);
		} else {
			if ( script_path == srctx->user_script && srctx->userlog != NULL ) {
				sieve_sys_error
					("failed to open script %s "
						"(view logfile %s for more information)",
						script_path, srctx->userlog);
			} else {
				sieve_sys_error
					("failed to open script %s",
						script_path);
			}
		}

		return ret;
	}

	return 1;
}

static struct sieve_binary *lda_sieve_recompile
(struct lda_sieve_run_context *srctx, unsigned int script_index)
{
	struct sieve_instance *svinst = srctx->svinst;
	const char *script_path = srctx->script_files[script_index];
    const char *script_name =
		( script_path == srctx->main_script ? "main_script" : NULL );
    struct sieve_error_handler *ehandler;
	struct sieve_binary *sbin;

	/* Warn */

	sieve_sys_warning("encountered corrupt binary: recompiling script %s",
		script_path);

	/* Recompile */

	if ( script_path == srctx->user_script )
		ehandler = srctx->user_ehandler;
	else
		ehandler = srctx->master_ehandler;

	if ( (sbin=sieve_compile
		(svinst, script_path, script_name, ehandler)) == NULL ) {

		if ( script_path == srctx->user_script && srctx->userlog != NULL ) {
			sieve_sys_error
				("failed to re-compile script %s "
					"(view logfile %s for more information)",
					script_path, srctx->userlog);
		} else {
			sieve_sys_error
				("failed to re-compile script %s", script_path);
		}

		return NULL;
	}

	return sbin;
}

static int lda_sieve_handle_exec_status(const char *script_path, int status)
{
	int ret;

	switch ( status ) {
	case SIEVE_EXEC_FAILURE:
		sieve_sys_error
			("execution of script %s failed, but implicit keep was successful",
				script_path);
		ret = 1;
		break;
	case SIEVE_EXEC_BIN_CORRUPT:
		sieve_sys_error
			("!!BUG!!: binary compiled from %s is still corrupt; "
				"bailing out and reverting to default delivery",
				script_path);
		ret = -1;
		break;
	case SIEVE_EXEC_KEEP_FAILED:
		sieve_sys_error
			("script %s failed with unsuccessful implicit keep", script_path);
		ret = -1;
		break;
	default:
		ret = status > 0 ? 1 : -1;
		break;
	}

	return ret;
}

static int lda_sieve_singlescript_execute
(struct lda_sieve_run_context *srctx)
{
	const char *script_file = srctx->script_files[0];
	bool user_script = ( script_file == srctx->user_script );
	struct sieve_error_handler *ehandler;
	struct sieve_binary *sbin;
	int ret;

	/* Open the script */

	if ( (ret=lda_sieve_open(srctx, 0, &sbin)) <= 0 )
		return ret;

	/* Execute */

	if ( lda_sieve_debug )
		sieve_sys_info("executing compiled script %s", script_file);

	if ( user_script ) {
		ehandler = srctx->user_ehandler;
		sieve_error_handler_copy_masterlog(ehandler, TRUE);
	} else {
		ehandler = srctx->master_ehandler;
	}

	ret = sieve_execute(sbin, srctx->msgdata, srctx->scriptenv, ehandler, NULL);

	sieve_error_handler_copy_masterlog(ehandler, FALSE);

	/* Recompile if corrupt binary */

	if ( ret == SIEVE_EXEC_BIN_CORRUPT ) {
		/* Close corrupt script */

		sieve_close(&sbin);

		/* Recompile */

		if ( (sbin=lda_sieve_recompile(srctx, 0)) == NULL ) {
			return -1;
		}

		/* Execute again */

		if ( user_script )
		sieve_error_handler_copy_masterlog(ehandler, TRUE);

		ret = sieve_execute(sbin, srctx->msgdata, srctx->scriptenv, ehandler, NULL);

		sieve_error_handler_copy_masterlog(ehandler, FALSE);

		/* Save new version */

		if ( ret != SIEVE_EXEC_BIN_CORRUPT )
			sieve_save(sbin, NULL);
	}

	sieve_close(&sbin);

	/* Report status */
	return lda_sieve_handle_exec_status(script_file, ret);
}

static int lda_sieve_multiscript_execute
(struct lda_sieve_run_context *srctx)
{
	struct sieve_instance *svinst = srctx->svinst;
	const char *const *scripts = srctx->script_files;
	unsigned int count = srctx->script_count;
	struct sieve_multiscript *mscript;
	struct sieve_error_handler *ehandler = srctx->master_ehandler;
	const char *last_script = NULL;
	bool user_script = FALSE;
	unsigned int i;
	int ret = 1;
	bool more = TRUE;

	/* Start execution */

	mscript = sieve_multiscript_start_execute
		(svinst, srctx->msgdata, srctx->scriptenv);

	/* Execute scripts before main script */

	for ( i = 0; i < count && more; i++ ) {
		struct sieve_binary *sbin = NULL;
		const char *script_file = scripts[i];
		bool final = ( i == count - 1 );

		user_script = ( script_file == srctx->user_script );
		last_script = script_file;

		if ( user_script )
			ehandler = srctx->user_ehandler;
		else
			ehandler = srctx->master_ehandler;

		/* Open */

		if ( (ret=lda_sieve_open(srctx, i, &sbin)) <= 0 )
			break;

		/* Execute */

		if ( user_script )
			sieve_error_handler_copy_masterlog(ehandler, TRUE);

		more = sieve_multiscript_run(mscript, sbin, ehandler, final);

		sieve_error_handler_copy_masterlog(ehandler, FALSE);

		if ( !more ) {
			if ( sieve_multiscript_status(mscript) == SIEVE_EXEC_BIN_CORRUPT ) {
				/* Close corrupt script */

				sieve_close(&sbin);

				/* Recompile */

				if ( (sbin=lda_sieve_recompile(srctx, i))
					== NULL ) {
					ret = -1;
					break;
				}

				/* Execute again */

				if ( user_script )
					sieve_error_handler_copy_masterlog(ehandler, TRUE);

				more = sieve_multiscript_run(mscript, sbin, ehandler, final);

				sieve_error_handler_copy_masterlog(ehandler, FALSE);

				/* Save new version */

				if ( more &&
					sieve_multiscript_status(mscript) != SIEVE_EXEC_BIN_CORRUPT )
					sieve_save(sbin, NULL);
			}
		}

		sieve_close(&sbin);
	}

	/* Finish execution */

	if ( user_script )
		sieve_error_handler_copy_masterlog(ehandler, TRUE);

	ret = sieve_multiscript_finish(&mscript, ehandler, NULL);

	sieve_error_handler_copy_masterlog(ehandler, FALSE);

	return lda_sieve_handle_exec_status(last_script, ret);
}

static int lda_sieve_run
(struct mail_namespace *namespaces, struct mail *mail,
	const char *user_script, const char *default_script,
	const ARRAY_TYPE (const_string) *scripts_before,
	const ARRAY_TYPE (const_string) *scripts_after,
	const char *destaddr, const char *username, const char *mailbox,
	struct mail_storage **storage_r)
{
	ARRAY_TYPE (const_string) scripts;
	struct sieve_instance *svinst;
	struct lda_sieve_run_context srctx;
	struct sieve_message_data msgdata;
	struct sieve_script_env scriptenv;
	struct sieve_exec_status estatus;
	const char *extensions = NULL;
        string_t *mailbox_utf8;
	int ret = 0;

	*storage_r = NULL;

	/* Initialize Sieve engine */
	svinst = sieve_init(&lda_sieve_env, NULL);

	extensions = getenv("SIEVE_EXTENSIONS");
	if ( extensions != NULL ) {
		sieve_set_extensions(svinst, extensions);
	}

	/* Initialize */

	memset(&srctx, 0, sizeof(srctx));
	srctx.svinst = svinst;

	/* Compose execution sequence */

	t_array_init(&scripts, 32);

	array_append_array(&scripts, scripts_before);

	if ( user_script != NULL ) {
		array_append(&scripts, &user_script, 1);
		srctx.user_script = user_script;
		srctx.main_script = user_script;
	} else if ( default_script != NULL ) {
		array_append(&scripts, &default_script, 1);
		srctx.user_script = NULL;
		srctx.main_script = default_script;
	} else {
		srctx.user_script = NULL;
        srctx.main_script = NULL;
	}

	array_append_array(&scripts, scripts_after);

	/* Create error handlers */

	if ( user_script != NULL ) {
		srctx.userlog = t_strconcat(user_script, ".log", NULL);
		srctx.user_ehandler = sieve_logfile_ehandler_create
			(srctx.userlog, LDA_SIEVE_MAX_USER_ERRORS);
	}

	srctx.master_ehandler =
		sieve_master_ehandler_create(LDA_SIEVE_MAX_SYSTEM_ERRORS);
	sieve_error_handler_accept_infolog(srctx.master_ehandler, TRUE);

	/* Collect necessary message data */

	memset(&msgdata, 0, sizeof(msgdata));

	msgdata.mail = mail;
	msgdata.return_path = deliver_get_return_address(mail);
	msgdata.to_address = destaddr;
	msgdata.auth_user = username;
	(void)mail_get_first_header(mail, "Message-ID", &msgdata.id);

	srctx.msgdata = &msgdata;

	/* Convert mutf7 mailbox name to UTF-8 */

	mailbox_utf8 = t_str_new(128);
	if (imap_utf7_to_utf8(mailbox, mailbox_utf8) < 0) {
		str_truncate(mailbox_utf8, 0);
		str_append(mailbox_utf8, mailbox);
	}

	/* Compose script execution environment */

	memset(&scriptenv, 0, sizeof(scriptenv));
	memset(&estatus, 0, sizeof(estatus));

	scriptenv.action_log_format = deliver_set->log_format;
	scriptenv.default_mailbox = str_c(mailbox_utf8);
	scriptenv.mailbox_autocreate = deliver_set->mailbox_autocreate;
	scriptenv.mailbox_autosubscribe = deliver_set->mailbox_autosubscribe;
	scriptenv.namespaces = namespaces;
	scriptenv.username = username;
	scriptenv.hostname = deliver_set->hostname;
	scriptenv.postmaster_address = deliver_set->postmaster_address;
	scriptenv.smtp_open = lda_sieve_smtp_open;
	scriptenv.smtp_close = lda_sieve_smtp_close;
	scriptenv.duplicate_mark = duplicate_mark;
	scriptenv.duplicate_check = duplicate_check;
	scriptenv.exec_status = &estatus;

	srctx.scriptenv = &scriptenv;

	/* Assign script sequence */

	srctx.script_files = array_get(&scripts, &srctx.script_count);

	/* Execute script(s) */

	if ( srctx.script_count == 1 )
		ret = lda_sieve_singlescript_execute(&srctx);
	else
		ret = lda_sieve_multiscript_execute(&srctx);

	/* Record status */

	tried_default_save = estatus.tried_default_save;
	*storage_r = estatus.last_storage;

	/* Clean up */

	if ( srctx.user_ehandler != NULL )
		sieve_error_handler_unref(&srctx.user_ehandler);
	sieve_error_handler_unref(&srctx.master_ehandler);

	/* Deinitialize Sieve engine */
	sieve_deinit(&svinst);

	return ret;
}

static int lda_sieve_deliver_mail
(struct mail_namespace *namespaces, struct mail_storage **storage_r,
	struct mail *mail, const char *destaddr, const char *mailbox)
{
	const char *user_script, *default_script, *sieve_before, *sieve_after;
	ARRAY_TYPE (const_string) scripts_before;
	ARRAY_TYPE (const_string) scripts_after;
	int ret = 0;

	*storage_r = NULL;

	T_BEGIN {
		struct stat st;

		/* Find the personal script to execute */

		user_script = lda_sieve_get_personal_path();
		default_script = lda_sieve_get_default_path();

		if ( user_script != NULL && stat(user_script, &st) < 0 ) {
			switch ( errno ) {
			case ENOENT:
				if (getenv("DEBUG") != NULL)
					sieve_sys_info("user's script path %s doesn't exist "
						"(using global script path in stead)", user_script);
				break;
			case EACCES:
				sieve_sys_error("failed to stat user's sieve script: %s "
					"(using global script path in stead)",
                    eacces_error_get("stat", user_script));
                break;
			default:
				sieve_sys_error("failed to stat user's sieve script: "
					"stat(%s) failed: %m (using global script path in stead)",
					user_script);
				break;
			}

			user_script = NULL;
		}

		if ( lda_sieve_debug ) {
			const char *script = user_script == NULL ? default_script : user_script;

			if ( script == NULL )
				sieve_sys_info("user has no valid personal script");
			else
				sieve_sys_info("using sieve path for user's script: %s", script);
		}

		/* Check for multiscript */

		t_array_init(&scripts_before, 16);
		t_array_init(&scripts_after, 16);

		sieve_before = getenv("SIEVE_BEFORE");
		sieve_after = getenv("SIEVE_AFTER");

		if ( sieve_before != NULL && *sieve_before != '\0' ) {
			lda_sieve_multiscript_get_scriptfiles(sieve_before, &scripts_before);
		}

		if ( sieve_after != NULL && *sieve_after != '\0' ) {
			lda_sieve_multiscript_get_scriptfiles(sieve_after, &scripts_after);
		}

		if ( lda_sieve_debug ) {
			const char *const *scriptfiles;
			unsigned int count, i;

			scriptfiles = array_get(&scripts_before, &count);
			for ( i = 0; i < count; i ++ ) {
				sieve_sys_info("executed before user's script(%d): %s", i+1, scriptfiles[i]);
			}

			scriptfiles = array_get(&scripts_after, &count);
			for ( i = 0; i < count; i ++ ) {
				sieve_sys_info("executed after user's script(%d): %s", i+1, scriptfiles[i]);
			}
		}

		/* Check whether there are any scripts to execute */

		if ( array_count(&scripts_before) == 0 && array_count(&scripts_after) == 0 &&
			user_script == NULL && default_script == NULL ) {
			if ( lda_sieve_debug )
				sieve_sys_info("no scripts to execute: reverting to default delivery.");

			/* No error, but no delivery by this plugin either. A return value of <= 0 for a
			 * deliver plugin is is considered a failure. In deliver itself, saved_mail and
			 * tried_default_save remain unset, meaning that deliver will then attempt the
			 * default delivery. We return 0 to signify the lack of a real error.
			 */
			ret = 0;
		} else {
			/* Run the script(s) */

			ret = lda_sieve_run
				(namespaces, mail, user_script,	default_script,
					&scripts_before, &scripts_after,
					destaddr, getenv("USER"), mailbox, storage_r);
		}

	} T_END;

	return ret;
}

/*
 * Plugin interface
 */

const char *sieve_plugin_version = PACKAGE_VERSION;

void sieve_plugin_init(void)
{
	/* Debug mode */
	lda_sieve_debug = getenv("DEBUG");

	/* Hook into the delivery process */
	next_deliver_mail = deliver_mail;
	deliver_mail = lda_sieve_deliver_mail;
}

void sieve_plugin_deinit(void)
{
	/* Remove hook */
	deliver_mail = next_deliver_mail;
}