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 struct 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);
137 CtdlFreeMessage(msg);
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['R'], 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 (msg->cm_fields['F'] != NULL) {
590 safestrncpy(my.sender, msg->cm_fields['F'], sizeof my.sender);
592 else if ( (msg->cm_fields['A'] != NULL) && (msg->cm_fields['N'] != NULL) ) {
593 snprintf(my.sender, sizeof my.sender, "%s@%s", msg->cm_fields['A'], msg->cm_fields['N']);
595 else if (msg->cm_fields['A'] != NULL) {
596 safestrncpy(my.sender, msg->cm_fields['A'], sizeof my.sender);
599 strcpy(my.sender, "");
602 /* Keep track of the subject so we can use it for VACATION responses */
603 if (msg->cm_fields['U'] != NULL) {
604 safestrncpy(my.subject, msg->cm_fields['U'], sizeof my.subject);
607 strcpy(my.subject, "");
610 /* Keep track of the envelope-from address (use body-from if not found) */
611 if (msg->cm_fields['P'] != NULL) {
612 safestrncpy(my.envelope_from, msg->cm_fields['P'], sizeof my.envelope_from);
613 stripallbut(my.envelope_from, '<', '>');
615 else if (msg->cm_fields['F'] != NULL) {
616 safestrncpy(my.envelope_from, msg->cm_fields['F'], 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 (msg->cm_fields['V'] != NULL) {
634 safestrncpy(my.envelope_to, msg->cm_fields['V'], sizeof my.envelope_to);
635 stripallbut(my.envelope_to, '<', '>');
637 else if (msg->cm_fields['R'] != NULL) {
638 safestrncpy(my.envelope_to, msg->cm_fields['R'], sizeof my.envelope_to);
639 if (msg->cm_fields['D'] != NULL) {
640 strcat(my.envelope_to, "@");
641 strcat(my.envelope_to, msg->cm_fields['D']);
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);
658 CtdlFreeMessage(msg);
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;
750 u->config_msgnum = msgnum;
751 msg = CtdlFetchMessage(msgnum, 1);
753 u->config_msgnum = (-1) ;
757 conf = msg->cm_fields['M'];
758 msg->cm_fields['M'] = NULL;
759 CtdlFreeMessage(msg);
762 parse_sieve_config(conf, u);
770 * Write our citadel sieve config back to disk
772 * (Set yes_write_to_disk to nonzero to make it actually write the config;
773 * otherwise it just frees the data structures.)
775 void rewrite_ctdl_sieve_config(struct sdm_userdata *u, int yes_write_to_disk) {
777 struct sdm_script *sptr;
778 struct sdm_vacation *vptr;
780 text = NewStrBufPlain(NULL, SIZ);
782 "Content-type: application/x-citadel-sieve-config\n"
784 CTDLSIEVECONFIGSEPARATOR
786 CTDLSIEVECONFIGSEPARATOR
791 while (u->first_script != NULL) {
792 StrBufAppendPrintf(text,
793 "script|%s|%d|%s" CTDLSIEVECONFIGSEPARATOR,
794 u->first_script->script_name,
795 u->first_script->script_active,
796 u->first_script->script_content
798 sptr = u->first_script;
799 u->first_script = u->first_script->next;
800 free(sptr->script_content);
804 if (u->first_vacation != NULL) {
806 StrBufAppendPrintf(text, "vacation|\n");
807 while (u->first_vacation != NULL) {
808 if ( (time(NULL) - u->first_vacation->timestamp) < (MAX_VACATION * 86400)) {
809 StrBufAppendPrintf(text, "%s|%ld\n",
810 u->first_vacation->fromaddr,
811 u->first_vacation->timestamp
814 vptr = u->first_vacation;
815 u->first_vacation = u->first_vacation->next;
818 StrBufAppendPrintf(text, CTDLSIEVECONFIGSEPARATOR);
821 if (yes_write_to_disk)
823 /* Save the config */
824 quickie_message("Citadel", NULL, NULL, u->config_roomname,
827 "Sieve configuration"
830 /* And delete the old one */
831 if (u->config_msgnum > 0) {
832 CtdlDeleteMessages(u->config_roomname, &u->config_msgnum, 1, "");
842 * This is our callback registration table for libSieve.
844 sieve2_callback_t ctdl_sieve_callbacks[] = {
845 { SIEVE2_ACTION_REJECT, ctdl_reject },
846 { SIEVE2_ACTION_VACATION, ctdl_vacation },
847 { SIEVE2_ERRCALL_PARSE, ctdl_errparse },
848 { SIEVE2_ERRCALL_RUNTIME, ctdl_errexec },
849 { SIEVE2_ACTION_FILEINTO, ctdl_fileinto },
850 { SIEVE2_ACTION_REDIRECT, ctdl_redirect },
851 { SIEVE2_ACTION_DISCARD, ctdl_discard },
852 { SIEVE2_ACTION_KEEP, ctdl_keep },
853 { SIEVE2_SCRIPT_GETSCRIPT, ctdl_getscript },
854 { SIEVE2_DEBUG_TRACE, ctdl_debug },
855 { SIEVE2_MESSAGE_GETALLHEADERS, ctdl_getheaders },
856 { SIEVE2_MESSAGE_GETSIZE, ctdl_getsize },
857 { SIEVE2_MESSAGE_GETENVELOPE, ctdl_getenvelope },
859 * These actions are unsupported by Citadel so we don't declare them.
861 { SIEVE2_ACTION_NOTIFY, ctdl_notify },
862 { SIEVE2_MESSAGE_GETSUBADDRESS, ctdl_getsubaddress },
863 { SIEVE2_MESSAGE_GETBODY, ctdl_getbody },
871 * Perform sieve processing for a single room
873 void sieve_do_room(char *roomname) {
875 struct sdm_userdata u;
876 sieve2_context_t *sieve2_context = NULL; /* Context for sieve parser */
877 int res; /* Return code from libsieve calls */
878 long orig_lastproc = 0;
880 memset(&u, 0, sizeof u);
882 /* See if the user who owns this 'mailbox' has any Sieve scripts that
885 snprintf(u.config_roomname, sizeof u.config_roomname, "%010ld.%s", atol(roomname), USERCONFIGROOM);
886 if (CtdlGetRoom(&CC->room, u.config_roomname) != 0) {
887 SV_syslog(LOG_DEBUG, "<%s> does not exist. No processing is required.", u.config_roomname);
892 * Find the sieve scripts and control record and do something
894 u.config_msgnum = (-1);
895 CtdlForEachMessage(MSGS_LAST, 1, NULL, SIEVECONFIG, NULL,
896 get_sieve_config_backend, (void *)&u );
898 if (u.config_msgnum < 0) {
899 SVM_syslog(LOG_DEBUG, "No Sieve rules exist. No processing is required.");
904 * Check to see whether the script is empty and should not be processed.
905 * A script is considered non-empty if it contains at least one semicolon.
908 (get_active_script(&u) == NULL)
909 || (strchr(get_active_script(&u), ';') == NULL)
911 SVM_syslog(LOG_DEBUG, "Sieve script is empty. No processing is required.");
915 SV_syslog(LOG_DEBUG, "Rules found. Performing Sieve processing for <%s>", roomname);
917 if (CtdlGetRoom(&CC->room, roomname) != 0) {
918 SV_syslog(LOG_CRIT, "ERROR: cannot load <%s>", roomname);
922 /* Initialize the Sieve parser */
924 res = sieve2_alloc(&sieve2_context);
925 if (res != SIEVE2_OK) {
926 SV_syslog(LOG_CRIT, "sieve2_alloc() returned %d: %s", res, sieve2_errstr(res));
930 res = sieve2_callbacks(sieve2_context, ctdl_sieve_callbacks);
931 if (res != SIEVE2_OK) {
932 SV_syslog(LOG_CRIT, "sieve2_callbacks() returned %d: %s", res, sieve2_errstr(res));
936 /* Validate the script */
938 struct ctdl_sieve my; /* dummy ctdl_sieve struct just to pass "u" slong */
939 memset(&my, 0, sizeof my);
941 res = sieve2_validate(sieve2_context, &my);
942 if (res != SIEVE2_OK) {
943 SV_syslog(LOG_CRIT, "sieve2_validate() returned %d: %s", res, sieve2_errstr(res));
947 /* Do something useful */
948 u.sieve2_context = sieve2_context;
949 orig_lastproc = u.lastproc;
950 CtdlForEachMessage(MSGS_GT, u.lastproc, NULL, NULL, NULL,
956 res = sieve2_free(&sieve2_context);
957 if (res != SIEVE2_OK) {
958 SV_syslog(LOG_CRIT, "sieve2_free() returned %d: %s", res, sieve2_errstr(res));
961 /* Rewrite the config if we have to */
962 rewrite_ctdl_sieve_config(&u, (u.lastproc > orig_lastproc) ) ;
967 * Perform sieve processing for all rooms which require it
969 void perform_sieve_processing(void) {
970 struct RoomProcList *ptr = NULL;
972 if (sieve_list != NULL) {
973 SVM_syslog(LOG_DEBUG, "Begin Sieve processing");
974 while (sieve_list != NULL) {
975 char spoolroomname[ROOMNAMELEN];
976 safestrncpy(spoolroomname, sieve_list->name, sizeof spoolroomname);
977 begin_critical_section(S_SIEVELIST);
979 /* pop this record off the list */
981 sieve_list = sieve_list->next;
984 /* invalidate any duplicate entries to prevent double processing */
985 for (ptr=sieve_list; ptr!=NULL; ptr=ptr->next) {
986 if (!strcasecmp(ptr->name, spoolroomname)) {
991 end_critical_section(S_SIEVELIST);
992 if (spoolroomname[0] != 0) {
993 sieve_do_room(spoolroomname);
1000 void msiv_load(struct sdm_userdata *u) {
1001 char hold_rm[ROOMNAMELEN];
1003 strcpy(hold_rm, CC->room.QRname); /* save current room */
1005 /* Take a spin through the user's personal address book */
1006 if (CtdlGetRoom(&CC->room, USERCONFIGROOM) == 0) {
1008 u->config_msgnum = (-1);
1009 strcpy(u->config_roomname, CC->room.QRname);
1010 CtdlForEachMessage(MSGS_LAST, 1, NULL, SIEVECONFIG, NULL,
1011 get_sieve_config_backend, (void *)u );
1015 if (strcmp(CC->room.QRname, hold_rm)) {
1016 CtdlGetRoom(&CC->room, hold_rm); /* return to saved room */
1020 void msiv_store(struct sdm_userdata *u, int yes_write_to_disk) {
1022 * Initialise the sieve configs last processed message number.
1023 * We don't need to get the highest message number for the users inbox since the systems
1024 * highest message number will be higher than that and loer than this scripts message number
1025 * This prevents this new script from processing any old messages in the inbox.
1026 * Most importantly it will prevent vacation messages being sent to lots of old messages
1029 u->lastproc = CtdlGetCurrentMessageNumber();
1030 rewrite_ctdl_sieve_config(u, yes_write_to_disk);
1035 * Select the active script.
1036 * (Set script_name to an empty string to disable all scripts)
1038 * Returns 0 on success or nonzero for error.
1040 int msiv_setactive(struct sdm_userdata *u, char *script_name) {
1042 struct sdm_script *s;
1044 /* First see if the supplied value is ok */
1046 if (IsEmptyStr(script_name)) {
1050 for (s=u->first_script; s!=NULL; s=s->next) {
1051 if (!strcasecmp(s->script_name, script_name)) {
1057 if (!ok) return(-1);
1059 /* Now set the active script */
1060 for (s=u->first_script; s!=NULL; s=s->next) {
1061 if (!strcasecmp(s->script_name, script_name)) {
1062 s->script_active = 1;
1065 s->script_active = 0;
1074 * Fetch a script by name.
1076 * Returns NULL if the named script was not found, or a pointer to the script
1077 * if it was found. NOTE: the caller does *not* own the memory returned by
1078 * this function. Copy it if you need to keep it.
1080 char *msiv_getscript(struct sdm_userdata *u, char *script_name) {
1081 struct sdm_script *s;
1083 for (s=u->first_script; s!=NULL; s=s->next) {
1084 if (!strcasecmp(s->script_name, script_name)) {
1085 if (s->script_content != NULL) {
1086 return (s->script_content);
1096 * Delete a script by name.
1098 * Returns 0 if the script was deleted.
1099 * 1 if the script was not found.
1100 * 2 if the script cannot be deleted because it is active.
1102 int msiv_deletescript(struct sdm_userdata *u, char *script_name) {
1103 struct sdm_script *s = NULL;
1104 struct sdm_script *script_to_delete = NULL;
1106 for (s=u->first_script; s!=NULL; s=s->next) {
1107 if (!strcasecmp(s->script_name, script_name)) {
1108 script_to_delete = s;
1109 if (s->script_active) {
1115 if (script_to_delete == NULL) return(1);
1117 if (u->first_script == script_to_delete) {
1118 u->first_script = u->first_script->next;
1120 else for (s=u->first_script; s!=NULL; s=s->next) {
1121 if (s->next == script_to_delete) {
1122 s->next = s->next->next;
1126 free(script_to_delete->script_content);
1127 free(script_to_delete);
1133 * Add or replace a new script.
1134 * NOTE: after this function returns, "u" owns the memory that "script_content"
1137 void msiv_putscript(struct sdm_userdata *u, char *script_name, char *script_content) {
1139 struct sdm_script *s, *sptr;
1141 for (s=u->first_script; s!=NULL; s=s->next) {
1142 if (!strcasecmp(s->script_name, script_name)) {
1143 if (s->script_content != NULL) {
1144 free(s->script_content);
1146 s->script_content = script_content;
1151 if (replaced == 0) {
1152 sptr = malloc(sizeof(struct sdm_script));
1153 safestrncpy(sptr->script_name, script_name, sizeof sptr->script_name);
1154 sptr->script_content = script_content;
1155 sptr->script_active = 0;
1156 sptr->next = u->first_script;
1157 u->first_script = sptr;
1164 * Citadel protocol to manage sieve scripts.
1165 * This is basically a simplified (read: doesn't resemble IMAP) version
1166 * of the 'managesieve' protocol.
1168 void cmd_msiv(char *argbuf) {
1170 struct sdm_userdata u;
1171 char script_name[256];
1172 char *script_content = NULL;
1173 struct sdm_script *s;
1175 int changes_made = 0;
1177 memset(&u, 0, sizeof(struct sdm_userdata));
1179 if (CtdlAccessCheck(ac_logged_in)) return;
1180 extract_token(subcmd, argbuf, 0, '|', sizeof subcmd);
1183 if (!strcasecmp(subcmd, "putscript")) {
1184 extract_token(script_name, argbuf, 1, '|', sizeof script_name);
1185 if (!IsEmptyStr(script_name)) {
1186 cprintf("%d Transmit script now\n", SEND_LISTING);
1187 script_content = CtdlReadMessageBody(HKEY("000"), config.c_maxmsglen, NULL, 0, 0);
1188 msiv_putscript(&u, script_name, script_content);
1192 cprintf("%d Invalid script name.\n", ERROR + ILLEGAL_VALUE);
1196 else if (!strcasecmp(subcmd, "listscripts")) {
1197 cprintf("%d Scripts:\n", LISTING_FOLLOWS);
1198 for (s=u.first_script; s!=NULL; s=s->next) {
1199 if (s->script_content != NULL) {
1200 cprintf("%s|%d|\n", s->script_name, s->script_active);
1206 else if (!strcasecmp(subcmd, "setactive")) {
1207 extract_token(script_name, argbuf, 1, '|', sizeof script_name);
1208 if (msiv_setactive(&u, script_name) == 0) {
1209 cprintf("%d ok\n", CIT_OK);
1213 cprintf("%d Script '%s' does not exist.\n",
1214 ERROR + ILLEGAL_VALUE,
1220 else if (!strcasecmp(subcmd, "getscript")) {
1221 extract_token(script_name, argbuf, 1, '|', sizeof script_name);
1222 script_content = msiv_getscript(&u, script_name);
1223 if (script_content != NULL) {
1226 cprintf("%d Script:\n", LISTING_FOLLOWS);
1227 script_len = strlen(script_content);
1228 client_write(script_content, script_len);
1229 if (script_content[script_len-1] != '\n') {
1235 cprintf("%d Invalid script name.\n", ERROR + ILLEGAL_VALUE);
1239 else if (!strcasecmp(subcmd, "deletescript")) {
1240 extract_token(script_name, argbuf, 1, '|', sizeof script_name);
1241 i = msiv_deletescript(&u, script_name);
1243 cprintf("%d ok\n", CIT_OK);
1247 cprintf("%d Script '%s' does not exist.\n",
1248 ERROR + ILLEGAL_VALUE,
1253 cprintf("%d Script '%s' is active and cannot be deleted.\n",
1254 ERROR + ILLEGAL_VALUE,
1259 cprintf("%d unknown error\n", ERROR);
1264 cprintf("%d Invalid subcommand\n", ERROR + CMD_NOT_SUPPORTED);
1267 msiv_store(&u, changes_made);
1272 void ctdl_sieve_init(void) {
1274 sieve2_context_t *sieve2_context = NULL;
1278 * We don't really care about dumping the entire credits to the log
1279 * every time the server is initialized. The documentation will suffice
1280 * for that purpose. We are making a call to sieve2_credits() in order
1281 * to demonstrate that we have successfully linked in to libsieve.
1283 cred = strdup(sieve2_credits());
1284 if (cred == NULL) return;
1286 if (strlen(cred) > 60) {
1287 strcpy(&cred[55], "...");
1290 SV_syslog(LOG_INFO, "%s",cred);
1293 /* Briefly initialize a Sieve parser instance just so we can list the
1294 * extensions that are available.
1296 res = sieve2_alloc(&sieve2_context);
1297 if (res != SIEVE2_OK) {
1298 SV_syslog(LOG_CRIT, "sieve2_alloc() returned %d: %s", res, sieve2_errstr(res));
1302 res = sieve2_callbacks(sieve2_context, ctdl_sieve_callbacks);
1303 if (res != SIEVE2_OK) {
1304 SV_syslog(LOG_CRIT, "sieve2_callbacks() returned %d: %s", res, sieve2_errstr(res));
1308 msiv_extensions = strdup(sieve2_listextensions(sieve2_context));
1309 SV_syslog(LOG_INFO, "Extensions: %s", msiv_extensions);
1311 BAIL: res = sieve2_free(&sieve2_context);
1312 if (res != SIEVE2_OK) {
1313 SV_syslog(LOG_CRIT, "sieve2_free() returned %d: %s", res, sieve2_errstr(res));
1318 void cleanup_sieve(void)
1320 struct RoomProcList *ptr, *ptr2;
1322 if (msiv_extensions != NULL)
1323 free(msiv_extensions);
1324 msiv_extensions = NULL;
1326 begin_critical_section(S_SIEVELIST);
1328 while (ptr != NULL) {
1334 end_critical_section(S_SIEVELIST);
1337 int serv_sieve_room(struct ctdlroom *room)
1339 if (!strcasecmp(&room->QRname[11], MAILROOM)) {
1340 sieve_queue_room(room);
1345 void LogSieveDebugEnable(const int n)
1347 SieveDebugEnable = n;
1349 CTDL_MODULE_INIT(sieve)
1353 CtdlRegisterDebugFlagHook(HKEY("sieve"), LogSieveDebugEnable, &SieveDebugEnable);
1355 CtdlRegisterProtoHook(cmd_msiv, "MSIV", "Manage Sieve scripts");
1356 CtdlRegisterRoomHook(serv_sieve_room);
1357 CtdlRegisterSessionHook(perform_sieve_processing, EVT_HOUSE, PRIO_HOUSE + 10);
1358 CtdlRegisterCleanupHook(cleanup_sieve);
1361 /* return our module name for the log */