2 * $Id: serv_sieve.c 3850 2005-09-13 14:00:24Z ajc $
4 * This module glues libSieve to the Citadel server in order to implement
5 * the Sieve mailbox filtering language (RFC 3028).
7 * This code is released under the terms of the GNU General Public License.
18 #include <sys/types.h>
20 #if TIME_WITH_SYS_TIME
21 # include <sys/time.h>
25 # include <sys/time.h>
36 #include "sysdep_decls.h"
37 #include "citserver.h"
40 #include "serv_extensions.h"
49 #include "serv_sieve.h"
51 struct RoomProcList *sieve_list = NULL;
55 * Callback function to send libSieve trace messages to Citadel log facility
56 * Set ctdl_libsieve_debug=1 to see extremely verbose libSieve trace
58 int ctdl_debug(sieve2_context_t *s, void *my)
60 static int ctdl_libsieve_debug = 0;
62 if (ctdl_libsieve_debug) {
63 lprintf(CTDL_DEBUG, "Sieve: level [%d] module [%s] file [%s] function [%s]\n",
64 sieve2_getvalue_int(s, "level"),
65 sieve2_getvalue_string(s, "module"),
66 sieve2_getvalue_string(s, "file"),
67 sieve2_getvalue_string(s, "function"));
68 lprintf(CTDL_DEBUG, " message [%s]\n",
69 sieve2_getvalue_string(s, "message"));
76 * Callback function to log script parsing errors
78 int ctdl_errparse(sieve2_context_t *s, void *my)
80 lprintf(CTDL_WARNING, "Error in script, line %d: %s\n",
81 sieve2_getvalue_int(s, "lineno"),
82 sieve2_getvalue_string(s, "message")
89 * Callback function to log script execution errors
91 int ctdl_errexec(sieve2_context_t *s, void *my)
93 lprintf(CTDL_WARNING, "Error executing script: %s\n",
94 sieve2_getvalue_string(s, "message")
101 * Callback function to redirect a message to a different folder
103 int ctdl_redirect(sieve2_context_t *s, void *my)
105 struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
106 struct CtdlMessage *msg = NULL;
107 struct recptypes *valid = NULL;
110 safestrncpy(recp, sieve2_getvalue_string(s, "address"), sizeof recp);
112 lprintf(CTDL_DEBUG, "Action is REDIRECT, recipient <%s>\n", recp);
114 valid = validate_recipients(recp);
116 lprintf(CTDL_WARNING, "REDIRECT failed: bad recipient <%s>\n", recp);
117 return SIEVE2_ERROR_BADARGS;
119 if (valid->num_error > 0) {
120 lprintf(CTDL_WARNING, "REDIRECT failed: bad recipient <%s>\n", recp);
122 return SIEVE2_ERROR_BADARGS;
125 msg = CtdlFetchMessage(cs->msgnum, 1);
127 lprintf(CTDL_WARNING, "REDIRECT failed: unable to fetch msg %ld\n", cs->msgnum);
129 return SIEVE2_ERROR_BADARGS;
132 CtdlSubmitMsg(msg, valid, NULL);
135 CtdlFreeMessage(msg);
141 * Callback function to indicate that a message *will* be kept in the inbox
143 int ctdl_keep(sieve2_context_t *s, void *my)
145 struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
147 lprintf(CTDL_DEBUG, "Action is KEEP\n");
156 * Callback function to file a message into a different mailbox
158 int ctdl_fileinto(sieve2_context_t *s, void *my)
160 struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
161 const char *dest_folder = sieve2_getvalue_string(s, "mailbox");
163 char foldername[256];
164 char original_room_name[ROOMNAMELEN];
166 lprintf(CTDL_DEBUG, "Action is FILEINTO, destination is <%s>\n", dest_folder);
168 /* FILEINTO 'INBOX' is the same thing as KEEP */
169 if ( (!strcasecmp(dest_folder, "INBOX")) || (!strcasecmp(dest_folder, MAILROOM)) ) {
175 /* Remember what room we came from */
176 safestrncpy(original_room_name, CC->room.QRname, sizeof original_room_name);
178 /* First try a mailbox name match (check personal mail folders first) */
179 snprintf(foldername, sizeof foldername, "%010ld.%s", cs->usernum, dest_folder);
180 c = getroom(&CC->room, foldername);
182 /* Then a regular room name match (public and private rooms) */
184 safestrncpy(foldername, dest_folder, sizeof foldername);
185 c = getroom(&CC->room, foldername);
189 lprintf(CTDL_WARNING, "FILEINTO failed: target <%s> does not exist\n", dest_folder);
190 return SIEVE2_ERROR_BADARGS;
193 /* Yes, we actually have to go there */
194 usergoto(NULL, 0, 0, NULL, NULL);
196 c = CtdlSaveMsgPointersInRoom(NULL, &cs->msgnum, 1, 0, NULL);
198 /* Go back to the room we came from */
199 if (strcasecmp(original_room_name, CC->room.QRname)) {
200 usergoto(original_room_name, 0, 0, NULL, NULL);
208 return SIEVE2_ERROR_BADARGS;
214 * Callback function to indicate that a message should be rejected
215 * FIXME implement this
217 int ctdl_reject(sieve2_context_t *s, void *my)
219 lprintf(CTDL_DEBUG, "Action is REJECT\n");
220 return SIEVE2_ERROR_UNSUPPORTED;
225 * Callback function to indicate that the user should be notified
226 * FIXME implement this
228 int ctdl_notify(sieve2_context_t *s, void *my)
230 lprintf(CTDL_DEBUG, "Action is NOTIFY\n");
231 return SIEVE2_ERROR_UNSUPPORTED;
236 * Callback function to indicate that a vacation message should be generated
237 * FIXME implement this
239 int ctdl_vacation(sieve2_context_t *s, void *my)
241 lprintf(CTDL_DEBUG, "Action is VACATION\n");
242 return SIEVE2_ERROR_UNSUPPORTED;
247 * Callback function to parse addresses per local system convention
248 * FIXME implement this
250 int ctdl_getsubaddress(sieve2_context_t *s, void *my)
252 return SIEVE2_ERROR_UNSUPPORTED;
257 * Callback function to parse message envelope
258 * FIXME implement this
260 int ctdl_getenvelope(sieve2_context_t *s, void *my)
262 return SIEVE2_ERROR_UNSUPPORTED;
267 * Callback function to fetch message body
268 * FIXME implement this
270 int ctdl_getbody(sieve2_context_t *s, void *my)
272 return SIEVE2_ERROR_UNSUPPORTED;
277 * Callback function to fetch message size
278 * FIXME implement this
280 int ctdl_getsize(sieve2_context_t *s, void *my)
282 return SIEVE2_ERROR_UNSUPPORTED;
287 * Callback function to indicate that a message should be discarded.
289 int ctdl_discard(sieve2_context_t *s, void *my)
291 struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
293 lprintf(CTDL_DEBUG, "Action is DISCARD\n");
295 /* Yes, this is really all there is to it. Since we are not setting "keep" to 1,
296 * the message will be discarded because "some other action" was successfully taken.
305 * Callback function to retrieve the sieve script
307 int ctdl_getscript(sieve2_context_t *s, void *my) {
308 struct sdm_script *sptr;
309 struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
311 lprintf(CTDL_DEBUG, "ctdl_getscript() was called. config_msgnum=%ld config_lastproc=%ld\n",
312 cs->u->config_msgnum, cs->u->lastproc
315 for (sptr=cs->u->first_script; sptr!=NULL; sptr=sptr->next) {
316 lprintf(CTDL_DEBUG, "Can we use script '%s' ? %s.\n",
318 ( (sptr->script_active > 0) ? "yes" : "no" )
320 if (sptr->script_active > 0) {
321 lprintf(CTDL_DEBUG, "ctdl_getscript() is using script '%s'\n", sptr->script_name);
322 sieve2_setvalue_string(s, "script", sptr->script_content);
327 lprintf(CTDL_DEBUG, "ctdl_getscript() found no active script\n");
328 return SIEVE2_ERROR_GETSCRIPT;
332 * Callback function to retrieve message headers
334 int ctdl_getheaders(sieve2_context_t *s, void *my) {
336 struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
338 lprintf(CTDL_DEBUG, "ctdl_getheaders() was called\n");
340 sieve2_setvalue_string(s, "allheaders", cs->rfc822headers);
347 * Add a room to the list of those rooms which potentially require sieve processing
349 void sieve_queue_room(struct ctdlroom *which_room) {
350 struct RoomProcList *ptr;
352 ptr = (struct RoomProcList *) malloc(sizeof (struct RoomProcList));
353 if (ptr == NULL) return;
355 safestrncpy(ptr->name, which_room->QRname, sizeof ptr->name);
356 begin_critical_section(S_SIEVELIST);
357 ptr->next = sieve_list;
359 end_critical_section(S_SIEVELIST);
365 * Perform sieve processing for one message (called by sieve_do_room() for each message)
367 void sieve_do_msg(long msgnum, void *userdata) {
368 struct sdm_userdata *u = (struct sdm_userdata *) userdata;
369 sieve2_context_t *sieve2_context = u->sieve2_context;
370 struct ctdl_sieve my;
373 lprintf(CTDL_DEBUG, "Performing sieve processing on msg <%ld>\n", msgnum);
375 CC->redirect_buffer = malloc(SIZ);
376 CC->redirect_len = 0;
377 CC->redirect_alloc = SIZ;
378 CtdlOutputMsg(msgnum, MT_RFC822, HEADERS_ONLY, 0, 1, NULL);
379 my.rfc822headers = CC->redirect_buffer;
380 CC->redirect_buffer = NULL;
381 CC->redirect_len = 0;
382 CC->redirect_alloc = 0;
384 my.keep = 0; /* Don't keep a copy in the inbox unless a callback tells us to do so */
385 my.actiontaken = 0; /* Keep track of whether any actions were successfully taken */
386 my.usernum = atol(CC->room.QRname); /* Keep track of the owner of the room's namespace */
387 my.msgnum = msgnum; /* Keep track of the message number in our local store */
388 my.u = u; /* Hand off a pointer to the rest of this info */
390 sieve2_setvalue_string(sieve2_context, "allheaders", my.rfc822headers);
392 lprintf(CTDL_DEBUG, "Calling sieve2_execute()\n");
393 res = sieve2_execute(sieve2_context, &my);
394 if (res != SIEVE2_OK) {
395 lprintf(CTDL_CRIT, "sieve2_execute() returned %d: %s\n", res, sieve2_errstr(res));
398 free(my.rfc822headers);
399 my.rfc822headers = NULL;
402 * Delete the message from the inbox unless either we were told not to, or
403 * if no other action was successfully taken.
405 if ( (!my.keep) && (my.actiontaken) ) {
406 lprintf(CTDL_DEBUG, "keep is 0 -- deleting message from inbox\n");
407 CtdlDeleteMessages(CC->room.QRname, &msgnum, 1, "", 0);
410 lprintf(CTDL_DEBUG, "Completed sieve processing on msg <%ld>\n", msgnum);
411 u->lastproc = msgnum;
419 * Given the on-disk representation of our Sieve config, load
420 * it into an in-memory data structure.
422 void parse_sieve_config(char *conf, struct sdm_userdata *u) {
426 struct sdm_script *sptr;
429 while (c = ptr, ptr = bmstrcasestr(ptr, CTDLSIEVECONFIGSEPARATOR), ptr != NULL) {
431 ptr += strlen(CTDLSIEVECONFIGSEPARATOR);
433 extract_token(keyword, c, 0, '|', sizeof keyword);
434 lprintf(CTDL_DEBUG, "CONFIG: <%s>\n", keyword);
436 if (!strcasecmp(keyword, "lastproc")) {
437 u->lastproc = extract_long(c, 1);
440 else if (!strcasecmp(keyword, "script")) {
441 sptr = malloc(sizeof(struct sdm_script));
442 extract_token(sptr->script_name, c, 1, '|', sizeof sptr->script_name);
443 sptr->script_active = extract_int(c, 2);
444 remove_token(c, 0, '|');
445 remove_token(c, 0, '|');
446 remove_token(c, 0, '|');
447 sptr->script_content = strdup(c);
448 sptr->next = u->first_script;
449 u->first_script = sptr;
452 /* ignore unknown keywords */
454 lprintf(CTDL_DEBUG, "done parsing config\n");
458 * We found the Sieve configuration for this user.
459 * Now do something with it.
461 void get_sieve_config_backend(long msgnum, void *userdata) {
462 struct sdm_userdata *u = (struct sdm_userdata *) userdata;
463 struct CtdlMessage *msg;
466 u->config_msgnum = msgnum;
467 msg = CtdlFetchMessage(msgnum, 1);
469 u->config_msgnum = (-1) ;
473 conf = msg->cm_fields['M'];
474 msg->cm_fields['M'] = NULL;
475 CtdlFreeMessage(msg);
478 parse_sieve_config(conf, u);
486 * Write our citadel sieve config back to disk
488 void rewrite_ctdl_sieve_config(struct sdm_userdata *u) {
490 struct sdm_script *sptr;
495 "Content-type: application/x-citadel-sieve-config\n"
497 CTDLSIEVECONFIGSEPARATOR
499 CTDLSIEVECONFIGSEPARATOR
504 while (u->first_script != NULL) {
505 text = realloc(text, strlen(text) + strlen(u->first_script->script_content) + 256);
506 sprintf(&text[strlen(text)], "script|%s|%d|%s" CTDLSIEVECONFIGSEPARATOR,
507 u->first_script->script_name,
508 u->first_script->script_active,
509 u->first_script->script_content
511 sptr = u->first_script;
512 u->first_script = u->first_script->next;
513 free(sptr->script_content);
517 /* Save the config */
518 quickie_message("Citadel", NULL, u->config_roomname,
521 "Sieve configuration"
524 /* And delete the old one */
525 if (u->config_msgnum > 0) {
526 CtdlDeleteMessages(u->config_roomname, &u->config_msgnum, 1, "", 0);
534 * Perform sieve processing for a single room
536 void sieve_do_room(char *roomname) {
538 struct sdm_userdata u;
539 sieve2_context_t *sieve2_context = NULL; /* Context for sieve parser */
540 int res; /* Return code from libsieve calls */
541 long orig_lastproc = 0;
543 memset(&u, 0, sizeof u);
546 * This is our callback registration table for libSieve.
548 sieve2_callback_t ctdl_sieve_callbacks[] = {
549 { SIEVE2_ACTION_REJECT, ctdl_reject },
550 { SIEVE2_ACTION_NOTIFY, ctdl_notify },
551 { SIEVE2_ACTION_VACATION, ctdl_vacation },
552 { SIEVE2_ERRCALL_PARSE, ctdl_errparse },
553 { SIEVE2_ERRCALL_RUNTIME, ctdl_errexec },
554 { SIEVE2_ACTION_FILEINTO, ctdl_fileinto },
555 { SIEVE2_ACTION_REDIRECT, ctdl_redirect },
556 { SIEVE2_ACTION_DISCARD, ctdl_discard },
557 { SIEVE2_ACTION_KEEP, ctdl_keep },
558 { SIEVE2_SCRIPT_GETSCRIPT, ctdl_getscript },
559 { SIEVE2_DEBUG_TRACE, ctdl_debug },
560 { SIEVE2_MESSAGE_GETALLHEADERS, ctdl_getheaders },
561 { SIEVE2_MESSAGE_GETSUBADDRESS, ctdl_getsubaddress },
562 { SIEVE2_MESSAGE_GETENVELOPE, ctdl_getenvelope },
563 { SIEVE2_MESSAGE_GETBODY, ctdl_getbody },
564 { SIEVE2_MESSAGE_GETSIZE, ctdl_getsize },
568 /* See if the user who owns this 'mailbox' has any Sieve scripts that
571 snprintf(u.config_roomname, sizeof u.config_roomname, "%010ld.%s", atol(roomname), SIEVERULES);
572 if (getroom(&CC->room, u.config_roomname) != 0) {
573 lprintf(CTDL_DEBUG, "<%s> does not exist. No processing is required.\n", u.config_roomname);
578 * Find the sieve scripts and control record and do something
580 u.config_msgnum = (-1);
581 CtdlForEachMessage(MSGS_LAST, 1, NULL, SIEVECONFIG, NULL,
582 get_sieve_config_backend, (void *)&u );
584 if (u.config_msgnum < 0) {
585 lprintf(CTDL_DEBUG, "No Sieve rules exist. No processing is required.\n");
589 lprintf(CTDL_DEBUG, "Rules found. Performing Sieve processing for <%s>\n", roomname);
591 if (getroom(&CC->room, roomname) != 0) {
592 lprintf(CTDL_CRIT, "ERROR: cannot load <%s>\n", roomname);
596 /* Initialize the Sieve parser */
598 res = sieve2_alloc(&sieve2_context);
599 if (res != SIEVE2_OK) {
600 lprintf(CTDL_CRIT, "sieve2_alloc() returned %d: %s\n", res, sieve2_errstr(res));
604 res = sieve2_callbacks(sieve2_context, ctdl_sieve_callbacks);
605 if (res != SIEVE2_OK) {
606 lprintf(CTDL_CRIT, "sieve2_callbacks() returned %d: %s\n", res, sieve2_errstr(res));
610 /* Validate the script */
612 struct ctdl_sieve my; /* dummy ctdl_sieve struct just to pass "u" slong */
613 memset(&my, 0, sizeof my);
615 res = sieve2_validate(sieve2_context, &my);
616 if (res != SIEVE2_OK) {
617 lprintf(CTDL_CRIT, "sieve2_validate() returned %d: %s\n", res, sieve2_errstr(res));
621 /* Do something useful */
622 u.sieve2_context = sieve2_context;
623 orig_lastproc = u.lastproc;
624 CtdlForEachMessage(MSGS_GT, u.lastproc, NULL, NULL, NULL,
630 res = sieve2_free(&sieve2_context);
631 if (res != SIEVE2_OK) {
632 lprintf(CTDL_CRIT, "sieve2_free() returned %d: %s\n", res, sieve2_errstr(res));
635 /* Rewrite the config if we have to */
636 if (u.lastproc > orig_lastproc) {
637 rewrite_ctdl_sieve_config(&u);
643 * Perform sieve processing for all rooms which require it
645 void perform_sieve_processing(void) {
646 struct RoomProcList *ptr = NULL;
648 if (sieve_list != NULL) {
649 lprintf(CTDL_DEBUG, "Begin Sieve processing\n");
650 while (sieve_list != NULL) {
651 char spoolroomname[ROOMNAMELEN];
652 safestrncpy(spoolroomname, sieve_list->name, sizeof spoolroomname);
653 begin_critical_section(S_SIEVELIST);
655 /* pop this record off the list */
657 sieve_list = sieve_list->next;
660 /* invalidate any duplicate entries to prevent double processing */
661 for (ptr=sieve_list; ptr!=NULL; ptr=ptr->next) {
662 if (!strcasecmp(ptr->name, spoolroomname)) {
667 end_critical_section(S_SIEVELIST);
668 if (spoolroomname[0] != 0) {
669 sieve_do_room(spoolroomname);
676 void msiv_load(struct sdm_userdata *u) {
677 char hold_rm[ROOMNAMELEN];
679 strcpy(hold_rm, CC->room.QRname); /* save current room */
681 /* Take a spin through the user's personal address book */
682 if (getroom(&CC->room, SIEVERULES) == 0) {
684 u->config_msgnum = (-1);
685 strcpy(u->config_roomname, CC->room.QRname);
686 CtdlForEachMessage(MSGS_LAST, 1, NULL, SIEVECONFIG, NULL,
687 get_sieve_config_backend, (void *)u );
691 if (strcmp(CC->room.QRname, hold_rm)) {
692 getroom(&CC->room, hold_rm); /* return to saved room */
696 void msiv_store(struct sdm_userdata *u) {
697 rewrite_ctdl_sieve_config(u);
702 * Fetch a script by name.
704 * Returns NULL if the named script was not found, or a pointer to the script
705 * if it was found. NOTE: the caller does *not* own the memory returned by
706 * this function. Copy it if you need to keep it.
708 char *msiv_getscript(struct sdm_userdata *u, char *script_name) {
709 struct sdm_script *s;
711 for (s=u->first_script; s!=NULL; s=s->next) {
712 if (!strcasecmp(s->script_name, script_name)) {
713 if (s->script_content != NULL) {
714 return (s->script_content);
725 * Add or replace a new script.
726 * NOTE: after this function returns, "u" owns the memory that "script_content"
729 void msiv_putscript(struct sdm_userdata *u, char *script_name, char *script_content) {
731 struct sdm_script *s, *sptr;
733 for (s=u->first_script; s!=NULL; s=s->next) {
734 if (!strcasecmp(s->script_name, script_name)) {
735 if (s->script_content != NULL) {
736 free(s->script_content);
738 s->script_content = script_content;
744 sptr = malloc(sizeof(struct sdm_script));
745 safestrncpy(sptr->script_name, script_name, sizeof sptr->script_name);
746 sptr->script_content = script_content;
747 sptr->script_active = 0;
748 sptr->next = u->first_script;
749 u->first_script = sptr;
755 * Citadel protocol to manage sieve scripts.
756 * This is basically a simplified (read: doesn't resemble IMAP) version
757 * of the 'managesieve' protocol.
759 void cmd_msiv(char *argbuf) {
761 struct sdm_userdata u;
762 char script_name[256];
763 char *script_content = NULL;
765 memset(&u, 0, sizeof(struct sdm_userdata));
767 if (CtdlAccessCheck(ac_logged_in)) return;
768 extract_token(subcmd, argbuf, 0, '|', sizeof subcmd);
771 if (!strcasecmp(subcmd, "putscript")) {
772 extract_token(script_name, argbuf, 1, '|', sizeof script_name);
773 if (strlen(script_name) > 0) {
774 cprintf("%d Transmit script now\n", SEND_LISTING);
775 script_content = CtdlReadMessageBody("000", config.c_maxmsglen, NULL, 0);
776 msiv_putscript(&u, script_name, script_content);
779 cprintf("%d Invalid script name.\n", ERROR + ILLEGAL_VALUE);
783 else if (!strcasecmp(subcmd, "listscripts")) {
786 else if (!strcasecmp(subcmd, "setactive")) {
789 else if (!strcasecmp(subcmd, "getscript")) {
790 extract_token(script_name, argbuf, 1, '|', sizeof script_name);
791 script_content = msiv_getscript(&u, script_name);
792 if (script_content != NULL) {
793 cprintf("%d Script:\n", SEND_LISTING);
794 cprintf("%s000\n", script_content);
797 cprintf("%d Invalid script name.\n", ERROR + ILLEGAL_VALUE);
801 else if (!strcasecmp(subcmd, "deletescript")) {
805 cprintf("%d Invalid subcommand\n", ERROR + CMD_NOT_SUPPORTED);
814 * We don't really care about dumping the entire credits to the log
815 * every time the server is initialized. The documentation will suffice
816 * for that purpose. We are making a call to sieve2_credits() in order
817 * to demonstrate that we have successfully linked in to libsieve.
819 void log_the_sieve2_credits(void) {
822 cred = strdup(sieve2_credits());
823 if (cred == NULL) return;
825 if (strlen(cred) > 60) {
826 strcpy(&cred[55], "...");
829 lprintf(CTDL_INFO, "%s\n",cred);
835 char *serv_sieve_init(void)
837 log_the_sieve2_credits();
838 CtdlRegisterProtoHook(cmd_msiv, "MSIV", "Manage Sieve scripts");
839 return "$Id: serv_sieve.c 3850 2005-09-13 14:00:24Z ajc $";
842 #else /* HAVE_LIBSIEVE */
844 char *serv_sieve_init(void)
846 lprintf(CTDL_INFO, "This server is missing libsieve. Mailbox filtering will be disabled.\n");
847 return "$Id: serv_sieve.c 3850 2005-09-13 14:00:24Z ajc $";
850 #endif /* HAVE_LIBSIEVE */