2 * This module glues libSieve to the Citadel server in order to implement
3 * the Sieve mailbox filtering language (RFC 3028).
5 * Copyright (c) 1987-2012 by the citadel.org team
7 * This program is open source software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License version 3.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
24 #include <sys/types.h>
26 #if TIME_WITH_SYS_TIME
27 # include <sys/time.h>
31 # include <sys/time.h>
40 #include <libcitadel.h>
43 #include "citserver.h"
48 #include "internet_addressing.h"
49 #include "ctdl_module.h"
50 #include "serv_sieve.h"
52 struct RoomProcList *sieve_list = NULL;
53 char *msiv_extensions = NULL;
54 int SieveDebugEnable = 0;
56 #define DBGLOG(LEVEL) if ((LEVEL != LOG_DEBUG) || (SieveDebugEnable != 0))
58 #define SV_syslog(LEVEL, FORMAT, ...) \
59 DBGLOG(LEVEL) syslog(LEVEL, \
60 "Sieve: " FORMAT, __VA_ARGS__)
62 #define SVM_syslog(LEVEL, FORMAT) \
63 DBGLOG(LEVEL) syslog(LEVEL, \
68 * Callback function to send libSieve trace messages to Citadel log facility
70 int ctdl_debug(sieve2_context_t *s, void *my)
72 SV_syslog(LOG_DEBUG, "%s", sieve2_getvalue_string(s, "message"));
78 * Callback function to log script parsing errors
80 int ctdl_errparse(sieve2_context_t *s, void *my)
82 SV_syslog(LOG_WARNING, "Error in script, line %d: %s",
83 sieve2_getvalue_int(s, "lineno"),
84 sieve2_getvalue_string(s, "message")
91 * Callback function to log script execution errors
93 int ctdl_errexec(sieve2_context_t *s, void *my)
95 SV_syslog(LOG_WARNING, "Error executing script: %s",
96 sieve2_getvalue_string(s, "message")
103 * Callback function to redirect a message to a different folder
105 int ctdl_redirect(sieve2_context_t *s, void *my)
107 struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
108 struct CtdlMessage *msg = NULL;
109 recptypes *valid = NULL;
112 safestrncpy(recp, sieve2_getvalue_string(s, "address"), sizeof recp);
114 SV_syslog(LOG_DEBUG, "Action is REDIRECT, recipient <%s>", recp);
116 valid = validate_recipients(recp, NULL, 0);
118 SV_syslog(LOG_WARNING, "REDIRECT failed: bad recipient <%s>", recp);
119 return SIEVE2_ERROR_BADARGS;
121 if (valid->num_error > 0) {
122 SV_syslog(LOG_WARNING, "REDIRECT failed: bad recipient <%s>", recp);
123 free_recipients(valid);
124 return SIEVE2_ERROR_BADARGS;
127 msg = CtdlFetchMessage(cs->msgnum, 1);
129 SV_syslog(LOG_WARNING, "REDIRECT failed: unable to fetch msg %ld", cs->msgnum);
130 free_recipients(valid);
131 return SIEVE2_ERROR_BADARGS;
134 CtdlSubmitMsg(msg, valid, NULL, 0);
135 cs->cancel_implicit_keep = 1;
136 free_recipients(valid);
143 * Callback function to indicate that a message *will* be kept in the inbox
145 int ctdl_keep(sieve2_context_t *s, void *my)
147 struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
149 SVM_syslog(LOG_DEBUG, "Action is KEEP");
152 cs->cancel_implicit_keep = 1;
158 * Callback function to file a message into a different mailbox
160 int ctdl_fileinto(sieve2_context_t *s, void *my)
162 struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
163 const char *dest_folder = sieve2_getvalue_string(s, "mailbox");
165 char foldername[256];
166 char original_room_name[ROOMNAMELEN];
168 SV_syslog(LOG_DEBUG, "Action is FILEINTO, destination is <%s>", dest_folder);
170 /* FILEINTO 'INBOX' is the same thing as KEEP */
171 if ( (!strcasecmp(dest_folder, "INBOX")) || (!strcasecmp(dest_folder, MAILROOM)) ) {
173 cs->cancel_implicit_keep = 1;
177 /* Remember what room we came from */
178 safestrncpy(original_room_name, CC->room.QRname, sizeof original_room_name);
180 /* First try a mailbox name match (check personal mail folders first) */
181 snprintf(foldername, sizeof foldername, "%010ld.%s", cs->usernum, dest_folder);
182 c = CtdlGetRoom(&CC->room, foldername);
184 /* Then a regular room name match (public and private rooms) */
186 safestrncpy(foldername, dest_folder, sizeof foldername);
187 c = CtdlGetRoom(&CC->room, foldername);
191 SV_syslog(LOG_WARNING, "FILEINTO failed: target <%s> does not exist", dest_folder);
192 return SIEVE2_ERROR_BADARGS;
195 /* Yes, we actually have to go there */
196 CtdlUserGoto(NULL, 0, 0, NULL, NULL);
198 c = CtdlSaveMsgPointersInRoom(NULL, &cs->msgnum, 1, 0, NULL, 0);
200 /* Go back to the room we came from */
201 if (strcasecmp(original_room_name, CC->room.QRname)) {
202 CtdlUserGoto(original_room_name, 0, 0, NULL, NULL);
206 cs->cancel_implicit_keep = 1;
210 return SIEVE2_ERROR_BADARGS;
216 * Callback function to indicate that a message should be discarded.
218 int ctdl_discard(sieve2_context_t *s, void *my)
220 struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
222 SVM_syslog(LOG_DEBUG, "Action is DISCARD");
224 /* Cancel the implicit keep. That's all there is to it. */
225 cs->cancel_implicit_keep = 1;
232 * Callback function to indicate that a message should be rejected
234 int ctdl_reject(sieve2_context_t *s, void *my)
236 struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
237 char *reject_text = NULL;
239 SVM_syslog(LOG_DEBUG, "Action is REJECT");
241 /* If we don't know who sent the message, do a DISCARD instead. */
242 if (IsEmptyStr(cs->sender)) {
243 SVM_syslog(LOG_INFO, "Unknown sender. Doing DISCARD instead of REJECT.");
244 return ctdl_discard(s, my);
247 /* Assemble the reject message. */
248 reject_text = malloc(strlen(sieve2_getvalue_string(s, "message")) + 1024);
249 if (reject_text == NULL) {
250 return SIEVE2_ERROR_FAIL;
254 "Content-type: text/plain\n"
256 "The message was refused by the recipient's mail filtering program.\n"
257 "The reason given was as follows:\n"
262 sieve2_getvalue_string(s, "message")
265 quickie_message( /* This delivers the message */
272 "Delivery status notification"
276 cs->cancel_implicit_keep = 1;
283 * Callback function to indicate that a vacation message should be generated
285 int ctdl_vacation(sieve2_context_t *s, void *my)
287 struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
288 struct sdm_vacation *vptr;
291 char *vacamsg_text = NULL;
292 char vacamsg_subject[1024];
294 SVM_syslog(LOG_DEBUG, "Action is VACATION");
296 message = sieve2_getvalue_string(s, "message");
297 if (message == NULL) return SIEVE2_ERROR_BADARGS;
299 if (sieve2_getvalue_string(s, "subject") != NULL) {
300 safestrncpy(vacamsg_subject, sieve2_getvalue_string(s, "subject"), sizeof vacamsg_subject);
303 snprintf(vacamsg_subject, sizeof vacamsg_subject, "Re: %s", cs->subject);
306 days = sieve2_getvalue_int(s, "days");
307 if (days < 1) days = 1;
308 if (days > MAX_VACATION) days = MAX_VACATION;
310 /* Check to see whether we've already alerted this sender that we're on vacation. */
311 for (vptr = cs->u->first_vacation; vptr != NULL; vptr = vptr->next) {
312 if (!strcasecmp(vptr->fromaddr, cs->sender)) {
313 if ( (time(NULL) - vptr->timestamp) < (days * 86400) ) {
314 SV_syslog(LOG_DEBUG, "Already alerted <%s> recently.", cs->sender);
320 /* Assemble the reject message. */
321 vacamsg_text = malloc(strlen(message) + 1024);
322 if (vacamsg_text == NULL) {
323 return SIEVE2_ERROR_FAIL;
326 sprintf(vacamsg_text,
327 "Content-type: text/plain charset=utf-8\n"
335 quickie_message( /* This delivers the message */
347 /* Now update the list to reflect the fact that we've alerted this sender.
348 * If they're already in the list, just update the timestamp.
350 for (vptr = cs->u->first_vacation; vptr != NULL; vptr = vptr->next) {
351 if (!strcasecmp(vptr->fromaddr, cs->sender)) {
352 vptr->timestamp = time(NULL);
357 /* If we get to this point, create a new record.
359 vptr = malloc(sizeof(struct sdm_vacation));
360 memset(vptr, 0, sizeof(struct sdm_vacation));
361 vptr->timestamp = time(NULL);
362 safestrncpy(vptr->fromaddr, cs->sender, sizeof vptr->fromaddr);
363 vptr->next = cs->u->first_vacation;
364 cs->u->first_vacation = vptr;
371 * Callback function to parse addresses per local system convention
372 * It is disabled because we don't support subaddresses.
375 int ctdl_getsubaddress(sieve2_context_t *s, void *my)
377 struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
379 /* libSieve does not take ownership of the memory used here. But, since we
380 * are just pointing to locations inside a struct which we are going to free
383 sieve2_setvalue_string(s, "user", cs->recp_user);
384 sieve2_setvalue_string(s, "detail", "");
385 sieve2_setvalue_string(s, "localpart", cs->recp_user);
386 sieve2_setvalue_string(s, "domain", cs->recp_node);
393 * Callback function to parse message envelope
395 int ctdl_getenvelope(sieve2_context_t *s, void *my)
397 struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
399 SVM_syslog(LOG_DEBUG, "Action is GETENVELOPE");
400 SV_syslog(LOG_DEBUG, "EnvFrom: %s", cs->envelope_from);
401 SV_syslog(LOG_DEBUG, "EnvTo: %s", cs->envelope_to);
403 if (cs->envelope_from != NULL) {
404 if ((cs->envelope_from[0] != '@')&&(cs->envelope_from[strlen(cs->envelope_from)-1] != '@')) {
405 sieve2_setvalue_string(s, "from", cs->envelope_from);
408 sieve2_setvalue_string(s, "from", "invalid_envelope_from@example.org");
412 sieve2_setvalue_string(s, "from", "null_envelope_from@example.org");
416 if (cs->envelope_to != NULL) {
417 if ((cs->envelope_to[0] != '@') && (cs->envelope_to[strlen(cs->envelope_to)-1] != '@')) {
418 sieve2_setvalue_string(s, "to", cs->envelope_to);
421 sieve2_setvalue_string(s, "to", "invalid_envelope_to@example.org");
425 sieve2_setvalue_string(s, "to", "null_envelope_to@example.org");
433 * Callback function to fetch message body
434 * (Uncomment the code if we implement this extension)
436 int ctdl_getbody(sieve2_context_t *s, void *my)
438 return SIEVE2_ERROR_UNSUPPORTED;
445 * Callback function to fetch message size
447 int ctdl_getsize(sieve2_context_t *s, void *my)
449 struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
452 GetMetaData(&smi, cs->msgnum);
454 if (smi.meta_rfc822_length > 0L) {
455 sieve2_setvalue_int(s, "size", (int)smi.meta_rfc822_length);
459 return SIEVE2_ERROR_UNSUPPORTED;
464 * Return a pointer to the active Sieve script.
465 * (Caller does NOT own the memory and should not free the returned pointer.)
467 char *get_active_script(struct sdm_userdata *u) {
468 struct sdm_script *sptr;
470 for (sptr=u->first_script; sptr!=NULL; sptr=sptr->next) {
471 if (sptr->script_active > 0) {
472 SV_syslog(LOG_DEBUG, "get_active_script() is using script '%s'", sptr->script_name);
473 return(sptr->script_content);
477 SVM_syslog(LOG_DEBUG, "get_active_script() found no active script");
483 * Callback function to retrieve the sieve script
485 int ctdl_getscript(sieve2_context_t *s, void *my) {
486 struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
488 char *active_script = get_active_script(cs->u);
489 if (active_script != NULL) {
490 sieve2_setvalue_string(s, "script", active_script);
494 return SIEVE2_ERROR_GETSCRIPT;
498 * Callback function to retrieve message headers
500 int ctdl_getheaders(sieve2_context_t *s, void *my) {
502 struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
504 SVM_syslog(LOG_DEBUG, "ctdl_getheaders() was called");
505 sieve2_setvalue_string(s, "allheaders", cs->rfc822headers);
512 * Add a room to the list of those rooms which potentially require sieve processing
514 void sieve_queue_room(struct ctdlroom *which_room) {
515 struct RoomProcList *ptr;
517 ptr = (struct RoomProcList *) malloc(sizeof (struct RoomProcList));
518 if (ptr == NULL) return;
520 safestrncpy(ptr->name, which_room->QRname, sizeof ptr->name);
521 begin_critical_section(S_SIEVELIST);
522 ptr->next = sieve_list;
524 end_critical_section(S_SIEVELIST);
525 SV_syslog(LOG_DEBUG, "<%s> queued for Sieve processing", which_room->QRname);
531 * Perform sieve processing for one message (called by sieve_do_room() for each message)
533 void sieve_do_msg(long msgnum, void *userdata) {
534 struct sdm_userdata *u = (struct sdm_userdata *) userdata;
535 sieve2_context_t *sieve2_context;
536 struct ctdl_sieve my;
538 struct CtdlMessage *msg;
540 size_t headers_len = 0;
545 SV_syslog(LOG_EMERG, "Can't process message <%ld> without userdata!", msgnum);
549 sieve2_context = u->sieve2_context;
551 SV_syslog(LOG_DEBUG, "Performing sieve processing on msg <%ld>", msgnum);
554 * Make sure you include message body so you can get those second-level headers ;)
556 msg = CtdlFetchMessage(msgnum, 1);
557 if (msg == NULL) return;
560 * Grab the message headers so we can feed them to libSieve.
561 * Use HEADERS_ONLY rather than HEADERS_FAST in order to include second-level headers.
563 CC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
564 CtdlOutputPreLoadedMsg(msg, MT_RFC822, HEADERS_ONLY, 0, 1, 0);
565 headers_len = StrLength(CC->redirect_buffer);
566 my.rfc822headers = SmashStrBuf(&CC->redirect_buffer);
569 * libSieve clobbers the stack if it encounters badly formed
570 * headers. Sanitize our headers by stripping nonprintable
573 for (i=0; i<headers_len; ++i) {
574 if (!isascii(my.rfc822headers[i])) {
575 my.rfc822headers[i] = '_';
579 my.keep = 0; /* Set to 1 to declare an *explicit* keep */
580 my.cancel_implicit_keep = 0; /* Some actions will cancel the implicit keep */
581 my.usernum = atol(CC->room.QRname); /* Keep track of the owner of the room's namespace */
582 my.msgnum = msgnum; /* Keep track of the message number in our local store */
583 my.u = u; /* Hand off a pointer to the rest of this info */
585 /* Keep track of the recipient so we can do handling based on it later */
586 process_rfc822_addr(msg->cm_fields[eRecipient], my.recp_user, my.recp_node, my.recp_name);
588 /* Keep track of the sender so we can use it for REJECT and VACATION responses */
589 if (!CM_IsEmpty(msg, erFc822Addr)) {
590 safestrncpy(my.sender, msg->cm_fields[erFc822Addr], sizeof my.sender);
592 else if ( (!CM_IsEmpty(msg, eAuthor)) && (!CM_IsEmpty(msg, eNodeName)) ) {
593 snprintf(my.sender, sizeof my.sender, "%s@%s", msg->cm_fields[eAuthor], msg->cm_fields[eNodeName]);
595 else if (!CM_IsEmpty(msg, eAuthor)) {
596 safestrncpy(my.sender, msg->cm_fields[eAuthor], sizeof my.sender);
599 strcpy(my.sender, "");
602 /* Keep track of the subject so we can use it for VACATION responses */
603 if (!CM_IsEmpty(msg, eMsgSubject)) {
604 safestrncpy(my.subject, msg->cm_fields[eMsgSubject], sizeof my.subject);
607 strcpy(my.subject, "");
610 /* Keep track of the envelope-from address (use body-from if not found) */
611 if (!CM_IsEmpty(msg, eMessagePath)) {
612 safestrncpy(my.envelope_from, msg->cm_fields[eMessagePath], sizeof my.envelope_from);
613 stripallbut(my.envelope_from, '<', '>');
615 else if (!CM_IsEmpty(msg, erFc822Addr)) {
616 safestrncpy(my.envelope_from, msg->cm_fields[erFc822Addr], sizeof my.envelope_from);
617 stripallbut(my.envelope_from, '<', '>');
620 strcpy(my.envelope_from, "");
623 len = strlen(my.envelope_from);
624 for (i=0; i<len; ++i) {
625 if (isspace(my.envelope_from[i])) my.envelope_from[i] = '_';
627 if (haschar(my.envelope_from, '@') == 0) {
628 strcat(my.envelope_from, "@");
629 strcat(my.envelope_from, config.c_fqdn);
632 /* Keep track of the envelope-to address (use body-to if not found) */
633 if (!CM_IsEmpty(msg, eenVelopeTo)) {
634 safestrncpy(my.envelope_to, msg->cm_fields[eenVelopeTo], sizeof my.envelope_to);
635 stripallbut(my.envelope_to, '<', '>');
637 else if (!CM_IsEmpty(msg, eRecipient)) {
638 safestrncpy(my.envelope_to, msg->cm_fields[eRecipient], sizeof my.envelope_to);
639 if (!CM_IsEmpty(msg, eDestination)) {
640 strcat(my.envelope_to, "@");
641 strcat(my.envelope_to, msg->cm_fields[eDestination]);
643 stripallbut(my.envelope_to, '<', '>');
646 strcpy(my.envelope_to, "");
649 len = strlen(my.envelope_to);
650 for (i=0; i<len; ++i) {
651 if (isspace(my.envelope_to[i])) my.envelope_to[i] = '_';
653 if (haschar(my.envelope_to, '@') == 0) {
654 strcat(my.envelope_to, "@");
655 strcat(my.envelope_to, config.c_fqdn);
660 SVM_syslog(LOG_DEBUG, "Calling sieve2_execute()");
661 res = sieve2_execute(sieve2_context, &my);
662 if (res != SIEVE2_OK) {
663 SV_syslog(LOG_CRIT, "sieve2_execute() returned %d: %s", res, sieve2_errstr(res));
666 free(my.rfc822headers);
667 my.rfc822headers = NULL;
670 * Delete the message from the inbox unless either we were told not to, or
671 * if no other action was successfully taken.
673 if ( (!my.keep) && (my.cancel_implicit_keep) ) {
674 SVM_syslog(LOG_DEBUG, "keep is 0 -- deleting message from inbox");
675 CtdlDeleteMessages(CC->room.QRname, &msgnum, 1, "");
678 SV_syslog(LOG_DEBUG, "Completed sieve processing on msg <%ld>", msgnum);
679 u->lastproc = msgnum;
687 * Given the on-disk representation of our Sieve config, load
688 * it into an in-memory data structure.
690 void parse_sieve_config(char *conf, struct sdm_userdata *u) {
694 struct sdm_script *sptr;
695 struct sdm_vacation *vptr;
698 while (c = ptr, ptr = bmstrcasestr(ptr, CTDLSIEVECONFIGSEPARATOR), ptr != NULL) {
700 ptr += strlen(CTDLSIEVECONFIGSEPARATOR);
702 extract_token(keyword, c, 0, '|', sizeof keyword);
704 if (!strcasecmp(keyword, "lastproc")) {
705 u->lastproc = extract_long(c, 1);
708 else if (!strcasecmp(keyword, "script")) {
709 sptr = malloc(sizeof(struct sdm_script));
710 extract_token(sptr->script_name, c, 1, '|', sizeof sptr->script_name);
711 sptr->script_active = extract_int(c, 2);
712 remove_token(c, 0, '|');
713 remove_token(c, 0, '|');
714 remove_token(c, 0, '|');
715 sptr->script_content = strdup(c);
716 sptr->next = u->first_script;
717 u->first_script = sptr;
720 else if (!strcasecmp(keyword, "vacation")) {
722 if (c != NULL) while (vacrec=c, c=strchr(c, '\n'), (c != NULL)) {
727 if (strncasecmp(vacrec, "vacation|", 9)) {
728 vptr = malloc(sizeof(struct sdm_vacation));
729 extract_token(vptr->fromaddr, vacrec, 0, '|', sizeof vptr->fromaddr);
730 vptr->timestamp = extract_long(vacrec, 1);
731 vptr->next = u->first_vacation;
732 u->first_vacation = vptr;
737 /* ignore unknown keywords */
742 * We found the Sieve configuration for this user.
743 * Now do something with it.
745 void get_sieve_config_backend(long msgnum, void *userdata) {
746 struct sdm_userdata *u = (struct sdm_userdata *) userdata;
747 struct CtdlMessage *msg;
751 u->config_msgnum = msgnum;
752 msg = CtdlFetchMessage(msgnum, 1);
754 u->config_msgnum = (-1) ;
758 CM_GetAsField(msg, eMesageText, &conf, &conflen);
763 parse_sieve_config(conf, u);
771 * Write our citadel sieve config back to disk
773 * (Set yes_write_to_disk to nonzero to make it actually write the config;
774 * otherwise it just frees the data structures.)
776 void rewrite_ctdl_sieve_config(struct sdm_userdata *u, int yes_write_to_disk) {
778 struct sdm_script *sptr;
779 struct sdm_vacation *vptr;
781 text = NewStrBufPlain(NULL, SIZ);
783 "Content-type: application/x-citadel-sieve-config\n"
785 CTDLSIEVECONFIGSEPARATOR
787 CTDLSIEVECONFIGSEPARATOR
792 while (u->first_script != NULL) {
793 StrBufAppendPrintf(text,
794 "script|%s|%d|%s" CTDLSIEVECONFIGSEPARATOR,
795 u->first_script->script_name,
796 u->first_script->script_active,
797 u->first_script->script_content
799 sptr = u->first_script;
800 u->first_script = u->first_script->next;
801 free(sptr->script_content);
805 if (u->first_vacation != NULL) {
807 StrBufAppendPrintf(text, "vacation|\n");
808 while (u->first_vacation != NULL) {
809 if ( (time(NULL) - u->first_vacation->timestamp) < (MAX_VACATION * 86400)) {
810 StrBufAppendPrintf(text, "%s|%ld\n",
811 u->first_vacation->fromaddr,
812 u->first_vacation->timestamp
815 vptr = u->first_vacation;
816 u->first_vacation = u->first_vacation->next;
819 StrBufAppendPrintf(text, CTDLSIEVECONFIGSEPARATOR);
822 if (yes_write_to_disk)
824 /* Save the config */
825 quickie_message("Citadel", NULL, NULL, u->config_roomname,
828 "Sieve configuration"
831 /* And delete the old one */
832 if (u->config_msgnum > 0) {
833 CtdlDeleteMessages(u->config_roomname, &u->config_msgnum, 1, "");
843 * This is our callback registration table for libSieve.
845 sieve2_callback_t ctdl_sieve_callbacks[] = {
846 { SIEVE2_ACTION_REJECT, ctdl_reject },
847 { SIEVE2_ACTION_VACATION, ctdl_vacation },
848 { SIEVE2_ERRCALL_PARSE, ctdl_errparse },
849 { SIEVE2_ERRCALL_RUNTIME, ctdl_errexec },
850 { SIEVE2_ACTION_FILEINTO, ctdl_fileinto },
851 { SIEVE2_ACTION_REDIRECT, ctdl_redirect },
852 { SIEVE2_ACTION_DISCARD, ctdl_discard },
853 { SIEVE2_ACTION_KEEP, ctdl_keep },
854 { SIEVE2_SCRIPT_GETSCRIPT, ctdl_getscript },
855 { SIEVE2_DEBUG_TRACE, ctdl_debug },
856 { SIEVE2_MESSAGE_GETALLHEADERS, ctdl_getheaders },
857 { SIEVE2_MESSAGE_GETSIZE, ctdl_getsize },
858 { SIEVE2_MESSAGE_GETENVELOPE, ctdl_getenvelope },
860 * These actions are unsupported by Citadel so we don't declare them.
862 { SIEVE2_ACTION_NOTIFY, ctdl_notify },
863 { SIEVE2_MESSAGE_GETSUBADDRESS, ctdl_getsubaddress },
864 { SIEVE2_MESSAGE_GETBODY, ctdl_getbody },
872 * Perform sieve processing for a single room
874 void sieve_do_room(char *roomname) {
876 struct sdm_userdata u;
877 sieve2_context_t *sieve2_context = NULL; /* Context for sieve parser */
878 int res; /* Return code from libsieve calls */
879 long orig_lastproc = 0;
881 memset(&u, 0, sizeof u);
883 /* See if the user who owns this 'mailbox' has any Sieve scripts that
886 snprintf(u.config_roomname, sizeof u.config_roomname, "%010ld.%s", atol(roomname), USERCONFIGROOM);
887 if (CtdlGetRoom(&CC->room, u.config_roomname) != 0) {
888 SV_syslog(LOG_DEBUG, "<%s> does not exist. No processing is required.", u.config_roomname);
893 * Find the sieve scripts and control record and do something
895 u.config_msgnum = (-1);
896 CtdlForEachMessage(MSGS_LAST, 1, NULL, SIEVECONFIG, NULL,
897 get_sieve_config_backend, (void *)&u );
899 if (u.config_msgnum < 0) {
900 SVM_syslog(LOG_DEBUG, "No Sieve rules exist. No processing is required.");
905 * Check to see whether the script is empty and should not be processed.
906 * A script is considered non-empty if it contains at least one semicolon.
909 (get_active_script(&u) == NULL)
910 || (strchr(get_active_script(&u), ';') == NULL)
912 SVM_syslog(LOG_DEBUG, "Sieve script is empty. No processing is required.");
916 SV_syslog(LOG_DEBUG, "Rules found. Performing Sieve processing for <%s>", roomname);
918 if (CtdlGetRoom(&CC->room, roomname) != 0) {
919 SV_syslog(LOG_CRIT, "ERROR: cannot load <%s>", roomname);
923 /* Initialize the Sieve parser */
925 res = sieve2_alloc(&sieve2_context);
926 if (res != SIEVE2_OK) {
927 SV_syslog(LOG_CRIT, "sieve2_alloc() returned %d: %s", res, sieve2_errstr(res));
931 res = sieve2_callbacks(sieve2_context, ctdl_sieve_callbacks);
932 if (res != SIEVE2_OK) {
933 SV_syslog(LOG_CRIT, "sieve2_callbacks() returned %d: %s", res, sieve2_errstr(res));
937 /* Validate the script */
939 struct ctdl_sieve my; /* dummy ctdl_sieve struct just to pass "u" slong */
940 memset(&my, 0, sizeof my);
942 res = sieve2_validate(sieve2_context, &my);
943 if (res != SIEVE2_OK) {
944 SV_syslog(LOG_CRIT, "sieve2_validate() returned %d: %s", res, sieve2_errstr(res));
948 /* Do something useful */
949 u.sieve2_context = sieve2_context;
950 orig_lastproc = u.lastproc;
951 CtdlForEachMessage(MSGS_GT, u.lastproc, NULL, NULL, NULL,
957 res = sieve2_free(&sieve2_context);
958 if (res != SIEVE2_OK) {
959 SV_syslog(LOG_CRIT, "sieve2_free() returned %d: %s", res, sieve2_errstr(res));
962 /* Rewrite the config if we have to */
963 rewrite_ctdl_sieve_config(&u, (u.lastproc > orig_lastproc) ) ;
968 * Perform sieve processing for all rooms which require it
970 void perform_sieve_processing(void) {
971 struct RoomProcList *ptr = NULL;
973 if (sieve_list != NULL) {
974 SVM_syslog(LOG_DEBUG, "Begin Sieve processing");
975 while (sieve_list != NULL) {
976 char spoolroomname[ROOMNAMELEN];
977 safestrncpy(spoolroomname, sieve_list->name, sizeof spoolroomname);
978 begin_critical_section(S_SIEVELIST);
980 /* pop this record off the list */
982 sieve_list = sieve_list->next;
985 /* invalidate any duplicate entries to prevent double processing */
986 for (ptr=sieve_list; ptr!=NULL; ptr=ptr->next) {
987 if (!strcasecmp(ptr->name, spoolroomname)) {
992 end_critical_section(S_SIEVELIST);
993 if (spoolroomname[0] != 0) {
994 sieve_do_room(spoolroomname);
1001 void msiv_load(struct sdm_userdata *u) {
1002 char hold_rm[ROOMNAMELEN];
1004 strcpy(hold_rm, CC->room.QRname); /* save current room */
1006 /* Take a spin through the user's personal address book */
1007 if (CtdlGetRoom(&CC->room, USERCONFIGROOM) == 0) {
1009 u->config_msgnum = (-1);
1010 strcpy(u->config_roomname, CC->room.QRname);
1011 CtdlForEachMessage(MSGS_LAST, 1, NULL, SIEVECONFIG, NULL,
1012 get_sieve_config_backend, (void *)u );
1016 if (strcmp(CC->room.QRname, hold_rm)) {
1017 CtdlGetRoom(&CC->room, hold_rm); /* return to saved room */
1021 void msiv_store(struct sdm_userdata *u, int yes_write_to_disk) {
1023 * Initialise the sieve configs last processed message number.
1024 * We don't need to get the highest message number for the users inbox since the systems
1025 * highest message number will be higher than that and loer than this scripts message number
1026 * This prevents this new script from processing any old messages in the inbox.
1027 * Most importantly it will prevent vacation messages being sent to lots of old messages
1030 u->lastproc = CtdlGetCurrentMessageNumber();
1031 rewrite_ctdl_sieve_config(u, yes_write_to_disk);
1036 * Select the active script.
1037 * (Set script_name to an empty string to disable all scripts)
1039 * Returns 0 on success or nonzero for error.
1041 int msiv_setactive(struct sdm_userdata *u, char *script_name) {
1043 struct sdm_script *s;
1045 /* First see if the supplied value is ok */
1047 if (IsEmptyStr(script_name)) {
1051 for (s=u->first_script; s!=NULL; s=s->next) {
1052 if (!strcasecmp(s->script_name, script_name)) {
1058 if (!ok) return(-1);
1060 /* Now set the active script */
1061 for (s=u->first_script; s!=NULL; s=s->next) {
1062 if (!strcasecmp(s->script_name, script_name)) {
1063 s->script_active = 1;
1066 s->script_active = 0;
1075 * Fetch a script by name.
1077 * Returns NULL if the named script was not found, or a pointer to the script
1078 * if it was found. NOTE: the caller does *not* own the memory returned by
1079 * this function. Copy it if you need to keep it.
1081 char *msiv_getscript(struct sdm_userdata *u, char *script_name) {
1082 struct sdm_script *s;
1084 for (s=u->first_script; s!=NULL; s=s->next) {
1085 if (!strcasecmp(s->script_name, script_name)) {
1086 if (s->script_content != NULL) {
1087 return (s->script_content);
1097 * Delete a script by name.
1099 * Returns 0 if the script was deleted.
1100 * 1 if the script was not found.
1101 * 2 if the script cannot be deleted because it is active.
1103 int msiv_deletescript(struct sdm_userdata *u, char *script_name) {
1104 struct sdm_script *s = NULL;
1105 struct sdm_script *script_to_delete = NULL;
1107 for (s=u->first_script; s!=NULL; s=s->next) {
1108 if (!strcasecmp(s->script_name, script_name)) {
1109 script_to_delete = s;
1110 if (s->script_active) {
1116 if (script_to_delete == NULL) return(1);
1118 if (u->first_script == script_to_delete) {
1119 u->first_script = u->first_script->next;
1121 else for (s=u->first_script; s!=NULL; s=s->next) {
1122 if (s->next == script_to_delete) {
1123 s->next = s->next->next;
1127 free(script_to_delete->script_content);
1128 free(script_to_delete);
1134 * Add or replace a new script.
1135 * NOTE: after this function returns, "u" owns the memory that "script_content"
1138 void msiv_putscript(struct sdm_userdata *u, char *script_name, char *script_content) {
1140 struct sdm_script *s, *sptr;
1142 for (s=u->first_script; s!=NULL; s=s->next) {
1143 if (!strcasecmp(s->script_name, script_name)) {
1144 if (s->script_content != NULL) {
1145 free(s->script_content);
1147 s->script_content = script_content;
1152 if (replaced == 0) {
1153 sptr = malloc(sizeof(struct sdm_script));
1154 safestrncpy(sptr->script_name, script_name, sizeof sptr->script_name);
1155 sptr->script_content = script_content;
1156 sptr->script_active = 0;
1157 sptr->next = u->first_script;
1158 u->first_script = sptr;
1165 * Citadel protocol to manage sieve scripts.
1166 * This is basically a simplified (read: doesn't resemble IMAP) version
1167 * of the 'managesieve' protocol.
1169 void cmd_msiv(char *argbuf) {
1171 struct sdm_userdata u;
1172 char script_name[256];
1173 char *script_content = NULL;
1174 struct sdm_script *s;
1176 int changes_made = 0;
1178 memset(&u, 0, sizeof(struct sdm_userdata));
1180 if (CtdlAccessCheck(ac_logged_in)) return;
1181 extract_token(subcmd, argbuf, 0, '|', sizeof subcmd);
1184 if (!strcasecmp(subcmd, "putscript")) {
1185 extract_token(script_name, argbuf, 1, '|', sizeof script_name);
1186 if (!IsEmptyStr(script_name)) {
1187 cprintf("%d Transmit script now\n", SEND_LISTING);
1188 script_content = CtdlReadMessageBody(HKEY("000"), config.c_maxmsglen, NULL, 0, 0);
1189 msiv_putscript(&u, script_name, script_content);
1193 cprintf("%d Invalid script name.\n", ERROR + ILLEGAL_VALUE);
1197 else if (!strcasecmp(subcmd, "listscripts")) {
1198 cprintf("%d Scripts:\n", LISTING_FOLLOWS);
1199 for (s=u.first_script; s!=NULL; s=s->next) {
1200 if (s->script_content != NULL) {
1201 cprintf("%s|%d|\n", s->script_name, s->script_active);
1207 else if (!strcasecmp(subcmd, "setactive")) {
1208 extract_token(script_name, argbuf, 1, '|', sizeof script_name);
1209 if (msiv_setactive(&u, script_name) == 0) {
1210 cprintf("%d ok\n", CIT_OK);
1214 cprintf("%d Script '%s' does not exist.\n",
1215 ERROR + ILLEGAL_VALUE,
1221 else if (!strcasecmp(subcmd, "getscript")) {
1222 extract_token(script_name, argbuf, 1, '|', sizeof script_name);
1223 script_content = msiv_getscript(&u, script_name);
1224 if (script_content != NULL) {
1227 cprintf("%d Script:\n", LISTING_FOLLOWS);
1228 script_len = strlen(script_content);
1229 client_write(script_content, script_len);
1230 if (script_content[script_len-1] != '\n') {
1236 cprintf("%d Invalid script name.\n", ERROR + ILLEGAL_VALUE);
1240 else if (!strcasecmp(subcmd, "deletescript")) {
1241 extract_token(script_name, argbuf, 1, '|', sizeof script_name);
1242 i = msiv_deletescript(&u, script_name);
1244 cprintf("%d ok\n", CIT_OK);
1248 cprintf("%d Script '%s' does not exist.\n",
1249 ERROR + ILLEGAL_VALUE,
1254 cprintf("%d Script '%s' is active and cannot be deleted.\n",
1255 ERROR + ILLEGAL_VALUE,
1260 cprintf("%d unknown error\n", ERROR);
1265 cprintf("%d Invalid subcommand\n", ERROR + CMD_NOT_SUPPORTED);
1268 msiv_store(&u, changes_made);
1273 void ctdl_sieve_init(void) {
1275 sieve2_context_t *sieve2_context = NULL;
1279 * We don't really care about dumping the entire credits to the log
1280 * every time the server is initialized. The documentation will suffice
1281 * for that purpose. We are making a call to sieve2_credits() in order
1282 * to demonstrate that we have successfully linked in to libsieve.
1284 cred = strdup(sieve2_credits());
1285 if (cred == NULL) return;
1287 if (strlen(cred) > 60) {
1288 strcpy(&cred[55], "...");
1291 SV_syslog(LOG_INFO, "%s",cred);
1294 /* Briefly initialize a Sieve parser instance just so we can list the
1295 * extensions that are available.
1297 res = sieve2_alloc(&sieve2_context);
1298 if (res != SIEVE2_OK) {
1299 SV_syslog(LOG_CRIT, "sieve2_alloc() returned %d: %s", res, sieve2_errstr(res));
1303 res = sieve2_callbacks(sieve2_context, ctdl_sieve_callbacks);
1304 if (res != SIEVE2_OK) {
1305 SV_syslog(LOG_CRIT, "sieve2_callbacks() returned %d: %s", res, sieve2_errstr(res));
1309 msiv_extensions = strdup(sieve2_listextensions(sieve2_context));
1310 SV_syslog(LOG_INFO, "Extensions: %s", msiv_extensions);
1312 BAIL: res = sieve2_free(&sieve2_context);
1313 if (res != SIEVE2_OK) {
1314 SV_syslog(LOG_CRIT, "sieve2_free() returned %d: %s", res, sieve2_errstr(res));
1319 void cleanup_sieve(void)
1321 struct RoomProcList *ptr, *ptr2;
1323 if (msiv_extensions != NULL)
1324 free(msiv_extensions);
1325 msiv_extensions = NULL;
1327 begin_critical_section(S_SIEVELIST);
1329 while (ptr != NULL) {
1335 end_critical_section(S_SIEVELIST);
1338 int serv_sieve_room(struct ctdlroom *room)
1340 if (!strcasecmp(&room->QRname[11], MAILROOM)) {
1341 sieve_queue_room(room);
1346 void LogSieveDebugEnable(const int n)
1348 SieveDebugEnable = n;
1350 CTDL_MODULE_INIT(sieve)
1354 CtdlRegisterDebugFlagHook(HKEY("sieve"), LogSieveDebugEnable, &SieveDebugEnable);
1356 CtdlRegisterProtoHook(cmd_msiv, "MSIV", "Manage Sieve scripts");
1357 CtdlRegisterRoomHook(serv_sieve_room);
1358 CtdlRegisterSessionHook(perform_sieve_processing, EVT_HOUSE, PRIO_HOUSE + 10);
1359 CtdlRegisterCleanupHook(cleanup_sieve);
1362 /* return our module name for the log */