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-2015 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;
57 * Callback function to send libSieve trace messages to Citadel log facility
59 int ctdl_debug(sieve2_context_t *s, void *my)
61 syslog(LOG_DEBUG, "%s", sieve2_getvalue_string(s, "message"));
67 * Callback function to log script parsing errors
69 int ctdl_errparse(sieve2_context_t *s, void *my)
71 syslog(LOG_WARNING, "Error in script, line %d: %s",
72 sieve2_getvalue_int(s, "lineno"),
73 sieve2_getvalue_string(s, "message")
80 * Callback function to log script execution errors
82 int ctdl_errexec(sieve2_context_t *s, void *my)
84 syslog(LOG_WARNING, "Error executing script: %s",
85 sieve2_getvalue_string(s, "message")
92 * Callback function to redirect a message to a different folder
94 int ctdl_redirect(sieve2_context_t *s, void *my)
96 struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
97 struct CtdlMessage *msg = NULL;
98 recptypes *valid = NULL;
101 safestrncpy(recp, sieve2_getvalue_string(s, "address"), sizeof recp);
103 syslog(LOG_DEBUG, "Action is REDIRECT, recipient <%s>", recp);
105 valid = validate_recipients(recp, NULL, 0);
107 syslog(LOG_WARNING, "REDIRECT failed: bad recipient <%s>", recp);
108 return SIEVE2_ERROR_BADARGS;
110 if (valid->num_error > 0) {
111 syslog(LOG_WARNING, "REDIRECT failed: bad recipient <%s>", recp);
112 free_recipients(valid);
113 return SIEVE2_ERROR_BADARGS;
116 msg = CtdlFetchMessage(cs->msgnum, 1, 1);
118 syslog(LOG_WARNING, "REDIRECT failed: unable to fetch msg %ld", cs->msgnum);
119 free_recipients(valid);
120 return SIEVE2_ERROR_BADARGS;
123 CtdlSubmitMsg(msg, valid, NULL, 0);
124 cs->cancel_implicit_keep = 1;
125 free_recipients(valid);
132 * Callback function to indicate that a message *will* be kept in the inbox
134 int ctdl_keep(sieve2_context_t *s, void *my)
136 struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
138 syslog(LOG_DEBUG, "Action is KEEP");
141 cs->cancel_implicit_keep = 1;
147 * Callback function to file a message into a different mailbox
149 int ctdl_fileinto(sieve2_context_t *s, void *my)
151 struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
152 const char *dest_folder = sieve2_getvalue_string(s, "mailbox");
154 char foldername[256];
155 char original_room_name[ROOMNAMELEN];
157 syslog(LOG_DEBUG, "Action is FILEINTO, destination is <%s>", dest_folder);
159 /* FILEINTO 'INBOX' is the same thing as KEEP */
160 if ( (!strcasecmp(dest_folder, "INBOX")) || (!strcasecmp(dest_folder, MAILROOM)) ) {
162 cs->cancel_implicit_keep = 1;
166 /* Remember what room we came from */
167 safestrncpy(original_room_name, CC->room.QRname, sizeof original_room_name);
169 /* First try a mailbox name match (check personal mail folders first) */
170 snprintf(foldername, sizeof foldername, "%010ld.%s", cs->usernum, dest_folder);
171 c = CtdlGetRoom(&CC->room, foldername);
173 /* Then a regular room name match (public and private rooms) */
175 safestrncpy(foldername, dest_folder, sizeof foldername);
176 c = CtdlGetRoom(&CC->room, foldername);
180 syslog(LOG_WARNING, "FILEINTO failed: target <%s> does not exist", dest_folder);
181 return SIEVE2_ERROR_BADARGS;
184 /* Yes, we actually have to go there */
185 CtdlUserGoto(NULL, 0, 0, NULL, NULL, NULL, NULL);
187 c = CtdlSaveMsgPointersInRoom(NULL, &cs->msgnum, 1, 0, NULL, 0);
189 /* Go back to the room we came from */
190 if (strcasecmp(original_room_name, CC->room.QRname)) {
191 CtdlUserGoto(original_room_name, 0, 0, NULL, NULL, NULL, NULL);
195 cs->cancel_implicit_keep = 1;
199 return SIEVE2_ERROR_BADARGS;
205 * Callback function to indicate that a message should be discarded.
207 int ctdl_discard(sieve2_context_t *s, void *my)
209 struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
211 syslog(LOG_DEBUG, "Action is DISCARD");
213 /* Cancel the implicit keep. That's all there is to it. */
214 cs->cancel_implicit_keep = 1;
221 * Callback function to indicate that a message should be rejected
223 int ctdl_reject(sieve2_context_t *s, void *my)
225 struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
226 char *reject_text = NULL;
228 syslog(LOG_DEBUG, "Action is REJECT");
230 /* If we don't know who sent the message, do a DISCARD instead. */
231 if (IsEmptyStr(cs->sender)) {
232 syslog(LOG_INFO, "Unknown sender. Doing DISCARD instead of REJECT.");
233 return ctdl_discard(s, my);
236 /* Assemble the reject message. */
237 reject_text = malloc(strlen(sieve2_getvalue_string(s, "message")) + 1024);
238 if (reject_text == NULL) {
239 return SIEVE2_ERROR_FAIL;
243 "Content-type: text/plain\n"
245 "The message was refused by the recipient's mail filtering program.\n"
246 "The reason given was as follows:\n"
251 sieve2_getvalue_string(s, "message")
254 quickie_message( /* This delivers the message */
261 "Delivery status notification"
265 cs->cancel_implicit_keep = 1;
272 * Callback function to indicate that a vacation message should be generated
274 int ctdl_vacation(sieve2_context_t *s, void *my)
276 struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
277 struct sdm_vacation *vptr;
280 char *vacamsg_text = NULL;
281 char vacamsg_subject[1024];
283 syslog(LOG_DEBUG, "Action is VACATION");
285 message = sieve2_getvalue_string(s, "message");
286 if (message == NULL) return SIEVE2_ERROR_BADARGS;
288 if (sieve2_getvalue_string(s, "subject") != NULL) {
289 safestrncpy(vacamsg_subject, sieve2_getvalue_string(s, "subject"), sizeof vacamsg_subject);
292 snprintf(vacamsg_subject, sizeof vacamsg_subject, "Re: %s", cs->subject);
295 days = sieve2_getvalue_int(s, "days");
296 if (days < 1) days = 1;
297 if (days > MAX_VACATION) days = MAX_VACATION;
299 /* Check to see whether we've already alerted this sender that we're on vacation. */
300 for (vptr = cs->u->first_vacation; vptr != NULL; vptr = vptr->next) {
301 if (!strcasecmp(vptr->fromaddr, cs->sender)) {
302 if ( (time(NULL) - vptr->timestamp) < (days * 86400) ) {
303 syslog(LOG_DEBUG, "Already alerted <%s> recently.", cs->sender);
309 /* Assemble the reject message. */
310 vacamsg_text = malloc(strlen(message) + 1024);
311 if (vacamsg_text == NULL) {
312 return SIEVE2_ERROR_FAIL;
315 sprintf(vacamsg_text,
316 "Content-type: text/plain charset=utf-8\n"
324 quickie_message( /* This delivers the message */
336 /* Now update the list to reflect the fact that we've alerted this sender.
337 * If they're already in the list, just update the timestamp.
339 for (vptr = cs->u->first_vacation; vptr != NULL; vptr = vptr->next) {
340 if (!strcasecmp(vptr->fromaddr, cs->sender)) {
341 vptr->timestamp = time(NULL);
346 /* If we get to this point, create a new record.
348 vptr = malloc(sizeof(struct sdm_vacation));
349 memset(vptr, 0, sizeof(struct sdm_vacation));
350 vptr->timestamp = time(NULL);
351 safestrncpy(vptr->fromaddr, cs->sender, sizeof vptr->fromaddr);
352 vptr->next = cs->u->first_vacation;
353 cs->u->first_vacation = vptr;
360 * Callback function to parse addresses per local system convention
361 * It is disabled because we don't support subaddresses.
364 int ctdl_getsubaddress(sieve2_context_t *s, void *my)
366 struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
368 /* libSieve does not take ownership of the memory used here. But, since we
369 * are just pointing to locations inside a struct which we are going to free
372 sieve2_setvalue_string(s, "user", cs->recp_user);
373 sieve2_setvalue_string(s, "detail", "");
374 sieve2_setvalue_string(s, "localpart", cs->recp_user);
375 sieve2_setvalue_string(s, "domain", cs->recp_node);
382 * Callback function to parse message envelope
384 int ctdl_getenvelope(sieve2_context_t *s, void *my)
386 struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
388 syslog(LOG_DEBUG, "Action is GETENVELOPE");
389 syslog(LOG_DEBUG, "EnvFrom: %s", cs->envelope_from);
390 syslog(LOG_DEBUG, "EnvTo: %s", cs->envelope_to);
392 if (cs->envelope_from != NULL) {
393 if ((cs->envelope_from[0] != '@')&&(cs->envelope_from[strlen(cs->envelope_from)-1] != '@')) {
394 sieve2_setvalue_string(s, "from", cs->envelope_from);
397 sieve2_setvalue_string(s, "from", "invalid_envelope_from@example.org");
401 sieve2_setvalue_string(s, "from", "null_envelope_from@example.org");
405 if (cs->envelope_to != NULL) {
406 if ((cs->envelope_to[0] != '@') && (cs->envelope_to[strlen(cs->envelope_to)-1] != '@')) {
407 sieve2_setvalue_string(s, "to", cs->envelope_to);
410 sieve2_setvalue_string(s, "to", "invalid_envelope_to@example.org");
414 sieve2_setvalue_string(s, "to", "null_envelope_to@example.org");
422 * Callback function to fetch message body
423 * (Uncomment the code if we implement this extension)
425 int ctdl_getbody(sieve2_context_t *s, void *my)
427 return SIEVE2_ERROR_UNSUPPORTED;
434 * Callback function to fetch message size
436 int ctdl_getsize(sieve2_context_t *s, void *my)
438 struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
441 GetMetaData(&smi, cs->msgnum);
443 if (smi.meta_rfc822_length > 0L) {
444 sieve2_setvalue_int(s, "size", (int)smi.meta_rfc822_length);
448 return SIEVE2_ERROR_UNSUPPORTED;
453 * Return a pointer to the active Sieve script.
454 * (Caller does NOT own the memory and should not free the returned pointer.)
456 char *get_active_script(struct sdm_userdata *u) {
457 struct sdm_script *sptr;
459 for (sptr=u->first_script; sptr!=NULL; sptr=sptr->next) {
460 if (sptr->script_active > 0) {
461 syslog(LOG_DEBUG, "get_active_script() is using script '%s'", sptr->script_name);
462 return(sptr->script_content);
466 syslog(LOG_DEBUG, "get_active_script() found no active script");
472 * Callback function to retrieve the sieve script
474 int ctdl_getscript(sieve2_context_t *s, void *my) {
475 struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
477 char *active_script = get_active_script(cs->u);
478 if (active_script != NULL) {
479 sieve2_setvalue_string(s, "script", active_script);
483 return SIEVE2_ERROR_GETSCRIPT;
487 * Callback function to retrieve message headers
489 int ctdl_getheaders(sieve2_context_t *s, void *my) {
491 struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
493 syslog(LOG_DEBUG, "ctdl_getheaders() was called");
494 sieve2_setvalue_string(s, "allheaders", cs->rfc822headers);
501 * Add a room to the list of those rooms which potentially require sieve processing
503 void sieve_queue_room(struct ctdlroom *which_room) {
504 struct RoomProcList *ptr;
506 ptr = (struct RoomProcList *) malloc(sizeof (struct RoomProcList));
507 if (ptr == NULL) return;
509 safestrncpy(ptr->name, which_room->QRname, sizeof ptr->name);
510 begin_critical_section(S_SIEVELIST);
511 ptr->next = sieve_list;
513 end_critical_section(S_SIEVELIST);
514 syslog(LOG_DEBUG, "<%s> queued for Sieve processing", which_room->QRname);
520 * Perform sieve processing for one message (called by sieve_do_room() for each message)
522 void sieve_do_msg(long msgnum, void *userdata) {
523 struct sdm_userdata *u = (struct sdm_userdata *) userdata;
524 sieve2_context_t *sieve2_context;
525 struct ctdl_sieve my;
527 struct CtdlMessage *msg;
529 size_t headers_len = 0;
534 syslog(LOG_EMERG, "Can't process message <%ld> without userdata!", msgnum);
538 sieve2_context = u->sieve2_context;
540 syslog(LOG_DEBUG, "Performing sieve processing on msg <%ld>", msgnum);
543 * Make sure you include message body so you can get those second-level headers ;)
545 msg = CtdlFetchMessage(msgnum, 1, 1);
546 if (msg == NULL) return;
549 * Grab the message headers so we can feed them to libSieve.
550 * Use HEADERS_ONLY rather than HEADERS_FAST in order to include second-level headers.
552 CC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
553 CtdlOutputPreLoadedMsg(msg, MT_RFC822, HEADERS_ONLY, 0, 1, 0);
554 headers_len = StrLength(CC->redirect_buffer);
555 my.rfc822headers = SmashStrBuf(&CC->redirect_buffer);
558 * libSieve clobbers the stack if it encounters badly formed
559 * headers. Sanitize our headers by stripping nonprintable
562 for (i=0; i<headers_len; ++i) {
563 if (!isascii(my.rfc822headers[i])) {
564 my.rfc822headers[i] = '_';
568 my.keep = 0; /* Set to 1 to declare an *explicit* keep */
569 my.cancel_implicit_keep = 0; /* Some actions will cancel the implicit keep */
570 my.usernum = atol(CC->room.QRname); /* Keep track of the owner of the room's namespace */
571 my.msgnum = msgnum; /* Keep track of the message number in our local store */
572 my.u = u; /* Hand off a pointer to the rest of this info */
574 /* Keep track of the recipient so we can do handling based on it later */
575 process_rfc822_addr(msg->cm_fields[eRecipient], my.recp_user, my.recp_node, my.recp_name);
577 /* Keep track of the sender so we can use it for REJECT and VACATION responses */
578 if (!CM_IsEmpty(msg, erFc822Addr)) {
579 safestrncpy(my.sender, msg->cm_fields[erFc822Addr], sizeof my.sender);
581 else if ( (!CM_IsEmpty(msg, eAuthor)) && (!CM_IsEmpty(msg, eNodeName)) ) {
582 snprintf(my.sender, sizeof my.sender, "%s@%s", msg->cm_fields[eAuthor], msg->cm_fields[eNodeName]);
584 else if (!CM_IsEmpty(msg, eAuthor)) {
585 safestrncpy(my.sender, msg->cm_fields[eAuthor], sizeof my.sender);
588 strcpy(my.sender, "");
591 /* Keep track of the subject so we can use it for VACATION responses */
592 if (!CM_IsEmpty(msg, eMsgSubject)) {
593 safestrncpy(my.subject, msg->cm_fields[eMsgSubject], sizeof my.subject);
596 strcpy(my.subject, "");
599 /* Keep track of the envelope-from address (use body-from if not found) */
600 if (!CM_IsEmpty(msg, eMessagePath)) {
601 safestrncpy(my.envelope_from, msg->cm_fields[eMessagePath], sizeof my.envelope_from);
602 stripallbut(my.envelope_from, '<', '>');
604 else if (!CM_IsEmpty(msg, erFc822Addr)) {
605 safestrncpy(my.envelope_from, msg->cm_fields[erFc822Addr], sizeof my.envelope_from);
606 stripallbut(my.envelope_from, '<', '>');
609 strcpy(my.envelope_from, "");
612 len = strlen(my.envelope_from);
613 for (i=0; i<len; ++i) {
614 if (isspace(my.envelope_from[i])) my.envelope_from[i] = '_';
616 if (haschar(my.envelope_from, '@') == 0) {
617 strcat(my.envelope_from, "@");
618 strcat(my.envelope_from, CtdlGetConfigStr("c_fqdn"));
621 /* Keep track of the envelope-to address (use body-to if not found) */
622 if (!CM_IsEmpty(msg, eenVelopeTo)) {
623 safestrncpy(my.envelope_to, msg->cm_fields[eenVelopeTo], sizeof my.envelope_to);
624 stripallbut(my.envelope_to, '<', '>');
626 else if (!CM_IsEmpty(msg, eRecipient)) {
627 safestrncpy(my.envelope_to, msg->cm_fields[eRecipient], sizeof my.envelope_to);
628 if (!CM_IsEmpty(msg, eDestination)) {
629 strcat(my.envelope_to, "@");
630 strcat(my.envelope_to, msg->cm_fields[eDestination]);
632 stripallbut(my.envelope_to, '<', '>');
635 strcpy(my.envelope_to, "");
638 len = strlen(my.envelope_to);
639 for (i=0; i<len; ++i) {
640 if (isspace(my.envelope_to[i])) my.envelope_to[i] = '_';
642 if (haschar(my.envelope_to, '@') == 0) {
643 strcat(my.envelope_to, "@");
644 strcat(my.envelope_to, CtdlGetConfigStr("c_fqdn"));
649 syslog(LOG_DEBUG, "Calling sieve2_execute()");
650 res = sieve2_execute(sieve2_context, &my);
651 if (res != SIEVE2_OK) {
652 syslog(LOG_CRIT, "sieve2_execute() returned %d: %s", res, sieve2_errstr(res));
655 free(my.rfc822headers);
656 my.rfc822headers = NULL;
659 * Delete the message from the inbox unless either we were told not to, or
660 * if no other action was successfully taken.
662 if ( (!my.keep) && (my.cancel_implicit_keep) ) {
663 syslog(LOG_DEBUG, "keep is 0 -- deleting message from inbox");
664 CtdlDeleteMessages(CC->room.QRname, &msgnum, 1, "");
667 syslog(LOG_DEBUG, "Completed sieve processing on msg <%ld>", msgnum);
668 u->lastproc = msgnum;
676 * Given the on-disk representation of our Sieve config, load
677 * it into an in-memory data structure.
679 void parse_sieve_config(char *conf, struct sdm_userdata *u) {
683 struct sdm_script *sptr;
684 struct sdm_vacation *vptr;
687 while (c = ptr, ptr = bmstrcasestr(ptr, CTDLSIEVECONFIGSEPARATOR), ptr != NULL) {
689 ptr += strlen(CTDLSIEVECONFIGSEPARATOR);
691 extract_token(keyword, c, 0, '|', sizeof keyword);
693 if (!strcasecmp(keyword, "lastproc")) {
694 u->lastproc = extract_long(c, 1);
697 else if (!strcasecmp(keyword, "script")) {
698 sptr = malloc(sizeof(struct sdm_script));
699 extract_token(sptr->script_name, c, 1, '|', sizeof sptr->script_name);
700 sptr->script_active = extract_int(c, 2);
701 remove_token(c, 0, '|');
702 remove_token(c, 0, '|');
703 remove_token(c, 0, '|');
704 sptr->script_content = strdup(c);
705 sptr->next = u->first_script;
706 u->first_script = sptr;
709 else if (!strcasecmp(keyword, "vacation")) {
711 if (c != NULL) while (vacrec=c, c=strchr(c, '\n'), (c != NULL)) {
716 if (strncasecmp(vacrec, "vacation|", 9)) {
717 vptr = malloc(sizeof(struct sdm_vacation));
718 extract_token(vptr->fromaddr, vacrec, 0, '|', sizeof vptr->fromaddr);
719 vptr->timestamp = extract_long(vacrec, 1);
720 vptr->next = u->first_vacation;
721 u->first_vacation = vptr;
726 /* ignore unknown keywords */
731 * We found the Sieve configuration for this user.
732 * Now do something with it.
734 void get_sieve_config_backend(long msgnum, void *userdata) {
735 struct sdm_userdata *u = (struct sdm_userdata *) userdata;
736 struct CtdlMessage *msg;
740 u->config_msgnum = msgnum;
741 msg = CtdlFetchMessage(msgnum, 1, 1);
743 u->config_msgnum = (-1) ;
747 CM_GetAsField(msg, eMesageText, &conf, &conflen);
752 parse_sieve_config(conf, u);
760 * Write our citadel sieve config back to disk
762 * (Set yes_write_to_disk to nonzero to make it actually write the config;
763 * otherwise it just frees the data structures.)
765 void rewrite_ctdl_sieve_config(struct sdm_userdata *u, int yes_write_to_disk) {
767 struct sdm_script *sptr;
768 struct sdm_vacation *vptr;
770 text = NewStrBufPlain(NULL, SIZ);
772 "Content-type: application/x-citadel-sieve-config\n"
774 CTDLSIEVECONFIGSEPARATOR
776 CTDLSIEVECONFIGSEPARATOR
781 while (u->first_script != NULL) {
782 StrBufAppendPrintf(text,
783 "script|%s|%d|%s" CTDLSIEVECONFIGSEPARATOR,
784 u->first_script->script_name,
785 u->first_script->script_active,
786 u->first_script->script_content
788 sptr = u->first_script;
789 u->first_script = u->first_script->next;
790 free(sptr->script_content);
794 if (u->first_vacation != NULL) {
796 StrBufAppendPrintf(text, "vacation|\n");
797 while (u->first_vacation != NULL) {
798 if ( (time(NULL) - u->first_vacation->timestamp) < (MAX_VACATION * 86400)) {
799 StrBufAppendPrintf(text, "%s|%ld\n",
800 u->first_vacation->fromaddr,
801 u->first_vacation->timestamp
804 vptr = u->first_vacation;
805 u->first_vacation = u->first_vacation->next;
808 StrBufAppendPrintf(text, CTDLSIEVECONFIGSEPARATOR);
811 if (yes_write_to_disk)
813 /* Save the config */
814 quickie_message("Citadel", NULL, NULL, u->config_roomname,
817 "Sieve configuration"
820 /* And delete the old one */
821 if (u->config_msgnum > 0) {
822 CtdlDeleteMessages(u->config_roomname, &u->config_msgnum, 1, "");
832 * This is our callback registration table for libSieve.
834 sieve2_callback_t ctdl_sieve_callbacks[] = {
835 { SIEVE2_ACTION_REJECT, ctdl_reject },
836 { SIEVE2_ACTION_VACATION, ctdl_vacation },
837 { SIEVE2_ERRCALL_PARSE, ctdl_errparse },
838 { SIEVE2_ERRCALL_RUNTIME, ctdl_errexec },
839 { SIEVE2_ACTION_FILEINTO, ctdl_fileinto },
840 { SIEVE2_ACTION_REDIRECT, ctdl_redirect },
841 { SIEVE2_ACTION_DISCARD, ctdl_discard },
842 { SIEVE2_ACTION_KEEP, ctdl_keep },
843 { SIEVE2_SCRIPT_GETSCRIPT, ctdl_getscript },
844 { SIEVE2_DEBUG_TRACE, ctdl_debug },
845 { SIEVE2_MESSAGE_GETALLHEADERS, ctdl_getheaders },
846 { SIEVE2_MESSAGE_GETSIZE, ctdl_getsize },
847 { SIEVE2_MESSAGE_GETENVELOPE, ctdl_getenvelope },
849 * These actions are unsupported by Citadel so we don't declare them.
851 { SIEVE2_ACTION_NOTIFY, ctdl_notify },
852 { SIEVE2_MESSAGE_GETSUBADDRESS, ctdl_getsubaddress },
853 { SIEVE2_MESSAGE_GETBODY, ctdl_getbody },
861 * Perform sieve processing for a single room
863 void sieve_do_room(char *roomname) {
865 struct sdm_userdata u;
866 sieve2_context_t *sieve2_context = NULL; /* Context for sieve parser */
867 int res; /* Return code from libsieve calls */
868 long orig_lastproc = 0;
870 memset(&u, 0, sizeof u);
872 /* See if the user who owns this 'mailbox' has any Sieve scripts that
875 snprintf(u.config_roomname, sizeof u.config_roomname, "%010ld.%s", atol(roomname), USERCONFIGROOM);
876 if (CtdlGetRoom(&CC->room, u.config_roomname) != 0) {
877 syslog(LOG_DEBUG, "<%s> does not exist. No processing is required.", u.config_roomname);
882 * Find the sieve scripts and control record and do something
884 u.config_msgnum = (-1);
885 CtdlForEachMessage(MSGS_LAST, 1, NULL, SIEVECONFIG, NULL,
886 get_sieve_config_backend, (void *)&u );
888 if (u.config_msgnum < 0) {
889 syslog(LOG_DEBUG, "No Sieve rules exist. No processing is required.");
894 * Check to see whether the script is empty and should not be processed.
895 * A script is considered non-empty if it contains at least one semicolon.
898 (get_active_script(&u) == NULL)
899 || (strchr(get_active_script(&u), ';') == NULL)
901 syslog(LOG_DEBUG, "Sieve script is empty. No processing is required.");
905 syslog(LOG_DEBUG, "Rules found. Performing Sieve processing for <%s>", roomname);
907 if (CtdlGetRoom(&CC->room, roomname) != 0) {
908 syslog(LOG_CRIT, "ERROR: cannot load <%s>", roomname);
912 /* Initialize the Sieve parser */
914 res = sieve2_alloc(&sieve2_context);
915 if (res != SIEVE2_OK) {
916 syslog(LOG_CRIT, "sieve2_alloc() returned %d: %s", res, sieve2_errstr(res));
920 res = sieve2_callbacks(sieve2_context, ctdl_sieve_callbacks);
921 if (res != SIEVE2_OK) {
922 syslog(LOG_CRIT, "sieve2_callbacks() returned %d: %s", res, sieve2_errstr(res));
926 /* Validate the script */
928 struct ctdl_sieve my; /* dummy ctdl_sieve struct just to pass "u" slong */
929 memset(&my, 0, sizeof my);
931 res = sieve2_validate(sieve2_context, &my);
932 if (res != SIEVE2_OK) {
933 syslog(LOG_CRIT, "sieve2_validate() returned %d: %s", res, sieve2_errstr(res));
937 /* Do something useful */
938 u.sieve2_context = sieve2_context;
939 orig_lastproc = u.lastproc;
940 CtdlForEachMessage(MSGS_GT, u.lastproc, NULL, NULL, NULL,
946 res = sieve2_free(&sieve2_context);
947 if (res != SIEVE2_OK) {
948 syslog(LOG_CRIT, "sieve2_free() returned %d: %s", res, sieve2_errstr(res));
951 /* Rewrite the config if we have to */
952 rewrite_ctdl_sieve_config(&u, (u.lastproc > orig_lastproc) ) ;
957 * Perform sieve processing for all rooms which require it
959 void perform_sieve_processing(void) {
960 struct RoomProcList *ptr = NULL;
962 if (sieve_list != NULL) {
963 syslog(LOG_DEBUG, "Begin Sieve processing");
964 while (sieve_list != NULL) {
965 char spoolroomname[ROOMNAMELEN];
966 safestrncpy(spoolroomname, sieve_list->name, sizeof spoolroomname);
967 begin_critical_section(S_SIEVELIST);
969 /* pop this record off the list */
971 sieve_list = sieve_list->next;
974 /* invalidate any duplicate entries to prevent double processing */
975 for (ptr=sieve_list; ptr!=NULL; ptr=ptr->next) {
976 if (!strcasecmp(ptr->name, spoolroomname)) {
981 end_critical_section(S_SIEVELIST);
982 if (spoolroomname[0] != 0) {
983 sieve_do_room(spoolroomname);
990 void msiv_load(struct sdm_userdata *u) {
991 char hold_rm[ROOMNAMELEN];
993 strcpy(hold_rm, CC->room.QRname); /* save current room */
995 /* Take a spin through the user's personal address book */
996 if (CtdlGetRoom(&CC->room, USERCONFIGROOM) == 0) {
998 u->config_msgnum = (-1);
999 strcpy(u->config_roomname, CC->room.QRname);
1000 CtdlForEachMessage(MSGS_LAST, 1, NULL, SIEVECONFIG, NULL,
1001 get_sieve_config_backend, (void *)u );
1005 if (strcmp(CC->room.QRname, hold_rm)) {
1006 CtdlGetRoom(&CC->room, hold_rm); /* return to saved room */
1010 void msiv_store(struct sdm_userdata *u, int yes_write_to_disk) {
1012 * Initialise the sieve configs last processed message number.
1013 * We don't need to get the highest message number for the users inbox since the systems
1014 * highest message number will be higher than that and loer than this scripts message number
1015 * This prevents this new script from processing any old messages in the inbox.
1016 * Most importantly it will prevent vacation messages being sent to lots of old messages
1019 u->lastproc = CtdlGetCurrentMessageNumber();
1020 rewrite_ctdl_sieve_config(u, yes_write_to_disk);
1025 * Select the active script.
1026 * (Set script_name to an empty string to disable all scripts)
1028 * Returns 0 on success or nonzero for error.
1030 int msiv_setactive(struct sdm_userdata *u, char *script_name) {
1032 struct sdm_script *s;
1034 /* First see if the supplied value is ok */
1036 if (IsEmptyStr(script_name)) {
1040 for (s=u->first_script; s!=NULL; s=s->next) {
1041 if (!strcasecmp(s->script_name, script_name)) {
1047 if (!ok) return(-1);
1049 /* Now set the active script */
1050 for (s=u->first_script; s!=NULL; s=s->next) {
1051 if (!strcasecmp(s->script_name, script_name)) {
1052 s->script_active = 1;
1055 s->script_active = 0;
1064 * Fetch a script by name.
1066 * Returns NULL if the named script was not found, or a pointer to the script
1067 * if it was found. NOTE: the caller does *not* own the memory returned by
1068 * this function. Copy it if you need to keep it.
1070 char *msiv_getscript(struct sdm_userdata *u, char *script_name) {
1071 struct sdm_script *s;
1073 for (s=u->first_script; s!=NULL; s=s->next) {
1074 if (!strcasecmp(s->script_name, script_name)) {
1075 if (s->script_content != NULL) {
1076 return (s->script_content);
1086 * Delete a script by name.
1088 * Returns 0 if the script was deleted.
1089 * 1 if the script was not found.
1090 * 2 if the script cannot be deleted because it is active.
1092 int msiv_deletescript(struct sdm_userdata *u, char *script_name) {
1093 struct sdm_script *s = NULL;
1094 struct sdm_script *script_to_delete = NULL;
1096 for (s=u->first_script; s!=NULL; s=s->next) {
1097 if (!strcasecmp(s->script_name, script_name)) {
1098 script_to_delete = s;
1099 if (s->script_active) {
1105 if (script_to_delete == NULL) return(1);
1107 if (u->first_script == script_to_delete) {
1108 u->first_script = u->first_script->next;
1110 else for (s=u->first_script; s!=NULL; s=s->next) {
1111 if (s->next == script_to_delete) {
1112 s->next = s->next->next;
1116 free(script_to_delete->script_content);
1117 free(script_to_delete);
1123 * Add or replace a new script.
1124 * NOTE: after this function returns, "u" owns the memory that "script_content"
1127 void msiv_putscript(struct sdm_userdata *u, char *script_name, char *script_content) {
1129 struct sdm_script *s, *sptr;
1131 for (s=u->first_script; s!=NULL; s=s->next) {
1132 if (!strcasecmp(s->script_name, script_name)) {
1133 if (s->script_content != NULL) {
1134 free(s->script_content);
1136 s->script_content = script_content;
1141 if (replaced == 0) {
1142 sptr = malloc(sizeof(struct sdm_script));
1143 safestrncpy(sptr->script_name, script_name, sizeof sptr->script_name);
1144 sptr->script_content = script_content;
1145 sptr->script_active = 0;
1146 sptr->next = u->first_script;
1147 u->first_script = sptr;
1154 * Citadel protocol to manage sieve scripts.
1155 * This is basically a simplified (read: doesn't resemble IMAP) version
1156 * of the 'managesieve' protocol.
1158 void cmd_msiv(char *argbuf) {
1160 struct sdm_userdata u;
1161 char script_name[256];
1162 char *script_content = NULL;
1163 struct sdm_script *s;
1165 int changes_made = 0;
1167 memset(&u, 0, sizeof(struct sdm_userdata));
1169 if (CtdlAccessCheck(ac_logged_in)) return;
1170 extract_token(subcmd, argbuf, 0, '|', sizeof subcmd);
1173 if (!strcasecmp(subcmd, "putscript")) {
1174 extract_token(script_name, argbuf, 1, '|', sizeof script_name);
1175 if (!IsEmptyStr(script_name)) {
1176 cprintf("%d Transmit script now\n", SEND_LISTING);
1177 script_content = CtdlReadMessageBody(HKEY("000"), CtdlGetConfigLong("c_maxmsglen"), NULL, 0, 0);
1178 msiv_putscript(&u, script_name, script_content);
1182 cprintf("%d Invalid script name.\n", ERROR + ILLEGAL_VALUE);
1186 else if (!strcasecmp(subcmd, "listscripts")) {
1187 cprintf("%d Scripts:\n", LISTING_FOLLOWS);
1188 for (s=u.first_script; s!=NULL; s=s->next) {
1189 if (s->script_content != NULL) {
1190 cprintf("%s|%d|\n", s->script_name, s->script_active);
1196 else if (!strcasecmp(subcmd, "setactive")) {
1197 extract_token(script_name, argbuf, 1, '|', sizeof script_name);
1198 if (msiv_setactive(&u, script_name) == 0) {
1199 cprintf("%d ok\n", CIT_OK);
1203 cprintf("%d Script '%s' does not exist.\n",
1204 ERROR + ILLEGAL_VALUE,
1210 else if (!strcasecmp(subcmd, "getscript")) {
1211 extract_token(script_name, argbuf, 1, '|', sizeof script_name);
1212 script_content = msiv_getscript(&u, script_name);
1213 if (script_content != NULL) {
1216 cprintf("%d Script:\n", LISTING_FOLLOWS);
1217 script_len = strlen(script_content);
1218 client_write(script_content, script_len);
1219 if (script_content[script_len-1] != '\n') {
1225 cprintf("%d Invalid script name.\n", ERROR + ILLEGAL_VALUE);
1229 else if (!strcasecmp(subcmd, "deletescript")) {
1230 extract_token(script_name, argbuf, 1, '|', sizeof script_name);
1231 i = msiv_deletescript(&u, script_name);
1233 cprintf("%d ok\n", CIT_OK);
1237 cprintf("%d Script '%s' does not exist.\n",
1238 ERROR + ILLEGAL_VALUE,
1243 cprintf("%d Script '%s' is active and cannot be deleted.\n",
1244 ERROR + ILLEGAL_VALUE,
1249 cprintf("%d unknown error\n", ERROR);
1254 cprintf("%d Invalid subcommand\n", ERROR + CMD_NOT_SUPPORTED);
1257 msiv_store(&u, changes_made);
1262 void ctdl_sieve_init(void) {
1264 sieve2_context_t *sieve2_context = NULL;
1268 * We don't really care about dumping the entire credits to the log
1269 * every time the server is initialized. The documentation will suffice
1270 * for that purpose. We are making a call to sieve2_credits() in order
1271 * to demonstrate that we have successfully linked in to libsieve.
1273 cred = strdup(sieve2_credits());
1274 if (cred == NULL) return;
1276 if (strlen(cred) > 60) {
1277 strcpy(&cred[55], "...");
1280 syslog(LOG_INFO, "%s",cred);
1283 /* Briefly initialize a Sieve parser instance just so we can list the
1284 * extensions that are available.
1286 res = sieve2_alloc(&sieve2_context);
1287 if (res != SIEVE2_OK) {
1288 syslog(LOG_CRIT, "sieve2_alloc() returned %d: %s", res, sieve2_errstr(res));
1292 res = sieve2_callbacks(sieve2_context, ctdl_sieve_callbacks);
1293 if (res != SIEVE2_OK) {
1294 syslog(LOG_CRIT, "sieve2_callbacks() returned %d: %s", res, sieve2_errstr(res));
1298 msiv_extensions = strdup(sieve2_listextensions(sieve2_context));
1299 syslog(LOG_INFO, "Extensions: %s", msiv_extensions);
1301 BAIL: res = sieve2_free(&sieve2_context);
1302 if (res != SIEVE2_OK) {
1303 syslog(LOG_CRIT, "sieve2_free() returned %d: %s", res, sieve2_errstr(res));
1308 void cleanup_sieve(void)
1310 struct RoomProcList *ptr, *ptr2;
1312 if (msiv_extensions != NULL)
1313 free(msiv_extensions);
1314 msiv_extensions = NULL;
1316 begin_critical_section(S_SIEVELIST);
1318 while (ptr != NULL) {
1324 end_critical_section(S_SIEVELIST);
1327 int serv_sieve_room(struct ctdlroom *room)
1329 if (!strcasecmp(&room->QRname[11], MAILROOM)) {
1330 sieve_queue_room(room);
1335 CTDL_MODULE_INIT(sieve)
1340 CtdlRegisterProtoHook(cmd_msiv, "MSIV", "Manage Sieve scripts");
1341 CtdlRegisterRoomHook(serv_sieve_room);
1342 CtdlRegisterSessionHook(perform_sieve_processing, EVT_HOUSE, PRIO_HOUSE + 10);
1343 CtdlRegisterCleanupHook(cleanup_sieve);
1346 /* return our module name for the log */