30f64baab4098cdc413eac298823968a3fb11501
[citadel.git] / citadel / modules / sieve / serv_sieve.c
1 /*
2  * This module glues libSieve to the Citadel server in order to implement
3  * the Sieve mailbox filtering language (RFC 3028).
4  *
5  * Copyright (c) 1987-2018 by the citadel.org team
6  *
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.
9  *
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.
14  */
15
16 #include "sysdep.h"
17 #include <stdlib.h>
18 #include <unistd.h>
19 #include <stdio.h>
20 #include <fcntl.h>
21 #include <ctype.h>
22 #include <pwd.h>
23 #include <errno.h>
24 #include <sys/types.h>
25
26 #if TIME_WITH_SYS_TIME
27 # include <sys/time.h>
28 # include <time.h>
29 #else
30 # if HAVE_SYS_TIME_H
31 #  include <sys/time.h>
32 # else
33 #  include <time.h>
34 # endif
35 #endif
36
37 #include <sys/wait.h>
38 #include <string.h>
39 #include <limits.h>
40 #include <libcitadel.h>
41 #include "citadel.h"
42 #include "server.h"
43 #include "citserver.h"
44 #include "support.h"
45 #include "config.h"
46 #include "database.h"
47 #include "msgbase.h"
48 #include "internet_addressing.h"
49 #include "ctdl_module.h"
50 #include "serv_sieve.h"
51
52 struct RoomProcList *sieve_list = NULL;
53 char *msiv_extensions = NULL;
54
55
56 /*
57  * Callback function to send libSieve trace messages to Citadel log facility
58  */
59 int ctdl_debug(sieve2_context_t *s, void *my)
60 {
61         syslog(LOG_DEBUG, "%s", sieve2_getvalue_string(s, "message"));
62         return SIEVE2_OK;
63 }
64
65
66 /*
67  * Callback function to log script parsing errors
68  */
69 int ctdl_errparse(sieve2_context_t *s, void *my)
70 {
71         syslog(LOG_WARNING, "Error in script, line %d: %s",
72                   sieve2_getvalue_int(s, "lineno"),
73                   sieve2_getvalue_string(s, "message")
74         );
75         return SIEVE2_OK;
76 }
77
78
79 /*
80  * Callback function to log script execution errors
81  */
82 int ctdl_errexec(sieve2_context_t *s, void *my)
83 {
84         syslog(LOG_WARNING, "Error executing script: %s",
85                   sieve2_getvalue_string(s, "message")
86                 );
87         return SIEVE2_OK;
88 }
89
90
91 /*
92  * Callback function to redirect a message to a different folder
93  */
94 int ctdl_redirect(sieve2_context_t *s, void *my)
95 {
96         struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
97         struct CtdlMessage *msg = NULL;
98         recptypes *valid = NULL;
99         char recp[256];
100
101         safestrncpy(recp, sieve2_getvalue_string(s, "address"), sizeof recp);
102
103         syslog(LOG_DEBUG, "Action is REDIRECT, recipient <%s>", recp);
104
105         valid = validate_recipients(recp, NULL, 0);
106         if (valid == NULL) {
107                 syslog(LOG_WARNING, "REDIRECT failed: bad recipient <%s>", recp);
108                 return SIEVE2_ERROR_BADARGS;
109         }
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;
114         }
115
116         msg = CtdlFetchMessage(cs->msgnum, 1, 1);
117         if (msg == NULL) {
118                 syslog(LOG_WARNING, "REDIRECT failed: unable to fetch msg %ld", cs->msgnum);
119                 free_recipients(valid);
120                 return SIEVE2_ERROR_BADARGS;
121         }
122
123         CtdlSubmitMsg(msg, valid, NULL, 0);
124         cs->cancel_implicit_keep = 1;
125         free_recipients(valid);
126         CM_Free(msg);
127         return SIEVE2_OK;
128 }
129
130
131 /*
132  * Callback function to indicate that a message *will* be kept in the inbox
133  */
134 int ctdl_keep(sieve2_context_t *s, void *my)
135 {
136         struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
137         
138         syslog(LOG_DEBUG, "Action is KEEP");
139
140         cs->keep = 1;
141         cs->cancel_implicit_keep = 1;
142         return SIEVE2_OK;
143 }
144
145
146 /*
147  * Callback function to file a message into a different mailbox
148  */
149 int ctdl_fileinto(sieve2_context_t *s, void *my)
150 {
151         struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
152         const char *dest_folder = sieve2_getvalue_string(s, "mailbox");
153         int c;
154         char foldername[256];
155         char original_room_name[ROOMNAMELEN];
156
157         syslog(LOG_DEBUG, "Action is FILEINTO, destination is <%s>", dest_folder);
158
159         /* FILEINTO 'INBOX' is the same thing as KEEP */
160         if ( (!strcasecmp(dest_folder, "INBOX")) || (!strcasecmp(dest_folder, MAILROOM)) ) {
161                 cs->keep = 1;
162                 cs->cancel_implicit_keep = 1;
163                 return SIEVE2_OK;
164         }
165
166         /* Remember what room we came from */
167         safestrncpy(original_room_name, CC->room.QRname, sizeof original_room_name);
168
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);
172
173         /* Then a regular room name match (public and private rooms) */
174         if (c != 0) {
175                 safestrncpy(foldername, dest_folder, sizeof foldername);
176                 c = CtdlGetRoom(&CC->room, foldername);
177         }
178
179         if (c != 0) {
180                 syslog(LOG_WARNING, "FILEINTO failed: target <%s> does not exist", dest_folder);
181                 return SIEVE2_ERROR_BADARGS;
182         }
183
184         /* Yes, we actually have to go there */
185         CtdlUserGoto(NULL, 0, 0, NULL, NULL, NULL, NULL);
186
187         c = CtdlSaveMsgPointersInRoom(NULL, &cs->msgnum, 1, 0, NULL, 0);
188
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);
192         }
193
194         if (c == 0) {
195                 cs->cancel_implicit_keep = 1;
196                 return SIEVE2_OK;
197         }
198         else {
199                 return SIEVE2_ERROR_BADARGS;
200         }
201 }
202
203
204 /*
205  * Callback function to indicate that a message should be discarded.
206  */
207 int ctdl_discard(sieve2_context_t *s, void *my)
208 {
209         struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
210
211         syslog(LOG_DEBUG, "Action is DISCARD");
212
213         /* Cancel the implicit keep.  That's all there is to it. */
214         cs->cancel_implicit_keep = 1;
215         return SIEVE2_OK;
216 }
217
218
219
220 /*
221  * Callback function to indicate that a message should be rejected
222  */
223 int ctdl_reject(sieve2_context_t *s, void *my)
224 {
225         struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
226         char *reject_text = NULL;
227
228         syslog(LOG_DEBUG, "Action is REJECT");
229
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);
234         }
235
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;
240         }
241
242         sprintf(reject_text, 
243                 "Content-type: text/plain\n"
244                 "\n"
245                 "The message was refused by the recipient's mail filtering program.\n"
246                 "The reason given was as follows:\n"
247                 "\n"
248                 "%s\n"
249                 "\n"
250         ,
251                 sieve2_getvalue_string(s, "message")
252         );
253
254         quickie_message(        /* This delivers the message */
255                 NULL,
256                 cs->envelope_to,
257                 cs->sender,
258                 NULL,
259                 reject_text,
260                 FMT_RFC822,
261                 "Delivery status notification"
262         );
263
264         free(reject_text);
265         cs->cancel_implicit_keep = 1;
266         return SIEVE2_OK;
267 }
268
269
270
271 /*
272  * Callback function to indicate that a vacation message should be generated
273  */
274 int ctdl_vacation(sieve2_context_t *s, void *my)
275 {
276         struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
277         struct sdm_vacation *vptr;
278         int days = 1;
279         const char *message;
280         char *vacamsg_text = NULL;
281         char vacamsg_subject[1024];
282
283         syslog(LOG_DEBUG, "Action is VACATION");
284
285         message = sieve2_getvalue_string(s, "message");
286         if (message == NULL) return SIEVE2_ERROR_BADARGS;
287
288         if (sieve2_getvalue_string(s, "subject") != NULL) {
289                 safestrncpy(vacamsg_subject, sieve2_getvalue_string(s, "subject"), sizeof vacamsg_subject);
290         }
291         else {
292                 snprintf(vacamsg_subject, sizeof vacamsg_subject, "Re: %s", cs->subject);
293         }
294
295         days = sieve2_getvalue_int(s, "days");
296         if (days < 1) days = 1;
297         if (days > MAX_VACATION) days = MAX_VACATION;
298
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);
304                                 return SIEVE2_OK;
305                         }
306                 }
307         }
308
309         /* Assemble the reject message. */
310         vacamsg_text = malloc(strlen(message) + 1024);
311         if (vacamsg_text == NULL) {
312                 return SIEVE2_ERROR_FAIL;
313         }
314
315         sprintf(vacamsg_text, 
316                 "Content-type: text/plain charset=utf-8\n"
317                 "\n"
318                 "%s\n"
319                 "\n"
320         ,
321                 message
322         );
323
324         quickie_message(        /* This delivers the message */
325                 NULL,
326                 cs->envelope_to,
327                 cs->sender,
328                 NULL,
329                 vacamsg_text,
330                 FMT_RFC822,
331                 vacamsg_subject
332         );
333
334         free(vacamsg_text);
335
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.
338          */
339         for (vptr = cs->u->first_vacation; vptr != NULL; vptr = vptr->next) {
340                 if (!strcasecmp(vptr->fromaddr, cs->sender)) {
341                         vptr->timestamp = time(NULL);
342                         return SIEVE2_OK;
343                 }
344         }
345
346         /* If we get to this point, create a new record.
347          */
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;
354
355         return SIEVE2_OK;
356 }
357
358
359 /*
360  * Callback function to parse addresses per local system convention
361  * It is disabled because we don't support subaddresses.
362  */
363 #if 0
364 int ctdl_getsubaddress(sieve2_context_t *s, void *my)
365 {
366         struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
367
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
370          * later, we're ok.
371          */
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);
376         return SIEVE2_OK;
377 }
378 #endif
379
380
381 /*
382  * Callback function to parse message envelope
383  */
384 int ctdl_getenvelope(sieve2_context_t *s, void *my)
385 {
386         struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
387
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);
391
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);
395                 }
396                 else {
397                         sieve2_setvalue_string(s, "from", "invalid_envelope_from@example.org");
398                 }
399         }
400         else {
401                 sieve2_setvalue_string(s, "from", "null_envelope_from@example.org");
402         }
403
404
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);
408                 }
409                 else {
410                         sieve2_setvalue_string(s, "to", "invalid_envelope_to@example.org");
411                 }
412         }
413         else {
414                 sieve2_setvalue_string(s, "to", "null_envelope_to@example.org");
415         }
416
417         return SIEVE2_OK;
418 }
419
420
421 /*
422  * Callback function to fetch message body
423  * (Uncomment the code if we implement this extension)
424  *
425 int ctdl_getbody(sieve2_context_t *s, void *my)
426 {
427         return SIEVE2_ERROR_UNSUPPORTED;
428 }
429  *
430  */
431
432
433 /*
434  * Callback function to fetch message size
435  */
436 int ctdl_getsize(sieve2_context_t *s, void *my)
437 {
438         struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
439         struct MetaData smi;
440
441         GetMetaData(&smi, cs->msgnum);
442         
443         if (smi.meta_rfc822_length > 0L) {
444                 sieve2_setvalue_int(s, "size", (int)smi.meta_rfc822_length);
445                 return SIEVE2_OK;
446         }
447
448         return SIEVE2_ERROR_UNSUPPORTED;
449 }
450
451
452 /*
453  * Return a pointer to the active Sieve script.
454  * (Caller does NOT own the memory and should not free the returned pointer.)
455  */
456 char *get_active_script(struct sdm_userdata *u) {
457         struct sdm_script *sptr;
458
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);
463                 }
464         }
465
466         syslog(LOG_DEBUG, "get_active_script() found no active script");
467         return(NULL);
468 }
469
470
471 /*
472  * Callback function to retrieve the sieve script
473  */
474 int ctdl_getscript(sieve2_context_t *s, void *my) {
475         struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
476
477         char *active_script = get_active_script(cs->u);
478         if (active_script != NULL) {
479                 sieve2_setvalue_string(s, "script", active_script);
480                 return SIEVE2_OK;
481         }
482
483         return SIEVE2_ERROR_GETSCRIPT;
484 }
485
486 /*
487  * Callback function to retrieve message headers
488  */
489 int ctdl_getheaders(sieve2_context_t *s, void *my) {
490
491         struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
492
493         syslog(LOG_DEBUG, "ctdl_getheaders() was called");
494         sieve2_setvalue_string(s, "allheaders", cs->rfc822headers);
495         return SIEVE2_OK;
496 }
497
498
499
500 /*
501  * Add a room to the list of those rooms which potentially require sieve processing
502  */
503 void sieve_queue_room(struct ctdlroom *which_room) {
504         struct RoomProcList *ptr;
505
506         ptr = (struct RoomProcList *) malloc(sizeof (struct RoomProcList));
507         if (ptr == NULL) return;
508
509         safestrncpy(ptr->name, which_room->QRname, sizeof ptr->name);
510         begin_critical_section(S_SIEVELIST);
511         ptr->next = sieve_list;
512         sieve_list = ptr;
513         end_critical_section(S_SIEVELIST);
514         syslog(LOG_DEBUG, "<%s> queued for Sieve processing", which_room->QRname);
515 }
516
517
518
519 /*
520  * Perform sieve processing for one message (called by sieve_do_room() for each message)
521  */
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;
526         int res;
527         struct CtdlMessage *msg;
528         int i;
529         size_t headers_len = 0;
530         int len = 0;
531
532         if (u == NULL)
533         {
534                 syslog(LOG_EMERG, "Can't process message <%ld> without userdata!", msgnum);
535                 return;
536         }
537
538         sieve2_context = u->sieve2_context;
539
540         syslog(LOG_DEBUG, "Performing sieve processing on msg <%ld>", msgnum);
541
542         /*
543          * Make sure you include message body so you can get those second-level headers ;)
544          */
545         msg = CtdlFetchMessage(msgnum, 1, 1);
546         if (msg == NULL) return;
547
548         /*
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.
551          */
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);
556
557         /*
558          * libSieve clobbers the stack if it encounters badly formed
559          * headers.  Sanitize our headers by stripping nonprintable
560          * characters.
561          */
562         for (i=0; i<headers_len; ++i) {
563                 if (!isascii(my.rfc822headers[i])) {
564                         my.rfc822headers[i] = '_';
565                 }
566         }
567
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 */
573
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);
576
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);
580         }
581         else if (!CM_IsEmpty(msg, eAuthor)) {
582                 safestrncpy(my.sender, msg->cm_fields[eAuthor], sizeof my.sender);
583         }
584         else {
585                 strcpy(my.sender, "");
586         }
587
588         /* Keep track of the subject so we can use it for VACATION responses */
589         if (!CM_IsEmpty(msg, eMsgSubject)) {
590                 safestrncpy(my.subject, msg->cm_fields[eMsgSubject], sizeof my.subject);
591         }
592         else {
593                 strcpy(my.subject, "");
594         }
595
596         /* Keep track of the envelope-from address (use body-from if not found) */
597         if (!CM_IsEmpty(msg, eMessagePath)) {
598                 safestrncpy(my.envelope_from, msg->cm_fields[eMessagePath], sizeof my.envelope_from);
599                 stripallbut(my.envelope_from, '<', '>');
600         }
601         else if (!CM_IsEmpty(msg, erFc822Addr)) {
602                 safestrncpy(my.envelope_from, msg->cm_fields[erFc822Addr], sizeof my.envelope_from);
603                 stripallbut(my.envelope_from, '<', '>');
604         }
605         else {
606                 strcpy(my.envelope_from, "");
607         }
608
609         len = strlen(my.envelope_from);
610         for (i=0; i<len; ++i) {
611                 if (isspace(my.envelope_from[i])) my.envelope_from[i] = '_';
612         }
613         if (haschar(my.envelope_from, '@') == 0) {
614                 strcat(my.envelope_from, "@");
615                 strcat(my.envelope_from, CtdlGetConfigStr("c_fqdn"));
616         }
617
618         /* Keep track of the envelope-to address (use body-to if not found) */
619         if (!CM_IsEmpty(msg, eenVelopeTo)) {
620                 safestrncpy(my.envelope_to, msg->cm_fields[eenVelopeTo], sizeof my.envelope_to);
621                 stripallbut(my.envelope_to, '<', '>');
622         }
623         else if (!CM_IsEmpty(msg, eRecipient)) {
624                 safestrncpy(my.envelope_to, msg->cm_fields[eRecipient], sizeof my.envelope_to);
625                 if (!CM_IsEmpty(msg, eDestination)) {
626                         strcat(my.envelope_to, "@");
627                         strcat(my.envelope_to, msg->cm_fields[eDestination]);
628                 }
629                 stripallbut(my.envelope_to, '<', '>');
630         }
631         else {
632                 strcpy(my.envelope_to, "");
633         }
634
635         len = strlen(my.envelope_to);
636         for (i=0; i<len; ++i) {
637                 if (isspace(my.envelope_to[i])) my.envelope_to[i] = '_';
638         }
639         if (haschar(my.envelope_to, '@') == 0) {
640                 strcat(my.envelope_to, "@");
641                 strcat(my.envelope_to, CtdlGetConfigStr("c_fqdn"));
642         }
643
644         CM_Free(msg);
645         
646         syslog(LOG_DEBUG, "Calling sieve2_execute()");
647         res = sieve2_execute(sieve2_context, &my);
648         if (res != SIEVE2_OK) {
649                 syslog(LOG_CRIT, "sieve2_execute() returned %d: %s", res, sieve2_errstr(res));
650         }
651
652         free(my.rfc822headers);
653         my.rfc822headers = NULL;
654
655         /*
656          * Delete the message from the inbox unless either we were told not to, or
657          * if no other action was successfully taken.
658          */
659         if ( (!my.keep) && (my.cancel_implicit_keep) ) {
660                 syslog(LOG_DEBUG, "keep is 0 -- deleting message from inbox");
661                 CtdlDeleteMessages(CC->room.QRname, &msgnum, 1, "");
662         }
663
664         syslog(LOG_DEBUG, "Completed sieve processing on msg <%ld>", msgnum);
665         u->lastproc = msgnum;
666
667         return;
668 }
669
670
671
672 /*
673  * Given the on-disk representation of our Sieve config, load
674  * it into an in-memory data structure.
675  */
676 void parse_sieve_config(char *conf, struct sdm_userdata *u) {
677         char *ptr;
678         char *c, *vacrec;
679         char keyword[256];
680         struct sdm_script *sptr;
681         struct sdm_vacation *vptr;
682
683         ptr = conf;
684         while (c = ptr, ptr = bmstrcasestr(ptr, CTDLSIEVECONFIGSEPARATOR), ptr != NULL) {
685                 *ptr = 0;
686                 ptr += strlen(CTDLSIEVECONFIGSEPARATOR);
687
688                 extract_token(keyword, c, 0, '|', sizeof keyword);
689
690                 if (!strcasecmp(keyword, "lastproc")) {
691                         u->lastproc = extract_long(c, 1);
692                 }
693
694                 else if (!strcasecmp(keyword, "script")) {
695                         sptr = malloc(sizeof(struct sdm_script));
696                         extract_token(sptr->script_name, c, 1, '|', sizeof sptr->script_name);
697                         sptr->script_active = extract_int(c, 2);
698                         remove_token(c, 0, '|');
699                         remove_token(c, 0, '|');
700                         remove_token(c, 0, '|');
701                         sptr->script_content = strdup(c);
702                         sptr->next = u->first_script;
703                         u->first_script = sptr;
704                 }
705
706                 else if (!strcasecmp(keyword, "vacation")) {
707
708                         if (c != NULL) while (vacrec=c, c=strchr(c, '\n'), (c != NULL)) {
709
710                                 *c = 0;
711                                 ++c;
712
713                                 if (strncasecmp(vacrec, "vacation|", 9)) {
714                                         vptr = malloc(sizeof(struct sdm_vacation));
715                                         extract_token(vptr->fromaddr, vacrec, 0, '|', sizeof vptr->fromaddr);
716                                         vptr->timestamp = extract_long(vacrec, 1);
717                                         vptr->next = u->first_vacation;
718                                         u->first_vacation = vptr;
719                                 }
720                         }
721                 }
722
723                 /* ignore unknown keywords */
724         }
725 }
726
727 /*
728  * We found the Sieve configuration for this user.
729  * Now do something with it.
730  */
731 void get_sieve_config_backend(long msgnum, void *userdata) {
732         struct sdm_userdata *u = (struct sdm_userdata *) userdata;
733         struct CtdlMessage *msg;
734         char *conf;
735         long conflen;
736
737         u->config_msgnum = msgnum;
738         msg = CtdlFetchMessage(msgnum, 1, 1);
739         if (msg == NULL) {
740                 u->config_msgnum = (-1) ;
741                 return;
742         }
743
744         CM_GetAsField(msg, eMesageText, &conf, &conflen);
745
746         CM_Free(msg);
747
748         if (conf != NULL) {
749                 parse_sieve_config(conf, u);
750                 free(conf);
751         }
752
753 }
754
755
756 /* 
757  * Write our citadel sieve config back to disk
758  * 
759  * (Set yes_write_to_disk to nonzero to make it actually write the config;
760  * otherwise it just frees the data structures.)
761  */
762 void rewrite_ctdl_sieve_config(struct sdm_userdata *u, int yes_write_to_disk) {
763         StrBuf *text;
764         struct sdm_script *sptr;
765         struct sdm_vacation *vptr;
766         
767         text = NewStrBufPlain(NULL, SIZ);
768         StrBufPrintf(text,
769                      "Content-type: application/x-citadel-sieve-config\n"
770                      "\n"
771                      CTDLSIEVECONFIGSEPARATOR
772                      "lastproc|%ld"
773                      CTDLSIEVECONFIGSEPARATOR
774                      ,
775                      u->lastproc
776                 );
777
778         while (u->first_script != NULL) {
779                 StrBufAppendPrintf(text,
780                                    "script|%s|%d|%s" CTDLSIEVECONFIGSEPARATOR,
781                                    u->first_script->script_name,
782                                    u->first_script->script_active,
783                                    u->first_script->script_content
784                         );
785                 sptr = u->first_script;
786                 u->first_script = u->first_script->next;
787                 free(sptr->script_content);
788                 free(sptr);
789         }
790
791         if (u->first_vacation != NULL) {
792
793                 StrBufAppendPrintf(text, "vacation|\n");
794                 while (u->first_vacation != NULL) {
795                         if ( (time(NULL) - u->first_vacation->timestamp) < (MAX_VACATION * 86400)) {
796                                 StrBufAppendPrintf(text, "%s|%ld\n",
797                                                    u->first_vacation->fromaddr,
798                                                    u->first_vacation->timestamp
799                                         );
800                         }
801                         vptr = u->first_vacation;
802                         u->first_vacation = u->first_vacation->next;
803                         free(vptr);
804                 }
805                 StrBufAppendPrintf(text, CTDLSIEVECONFIGSEPARATOR);
806         }
807
808         if (yes_write_to_disk)
809         {
810                 /* Save the config */
811                 quickie_message("Citadel", NULL, NULL, u->config_roomname,
812                                 ChrPtr(text),
813                                 4,
814                                 "Sieve configuration"
815                 );
816                 
817                 /* And delete the old one */
818                 if (u->config_msgnum > 0) {
819                         CtdlDeleteMessages(u->config_roomname, &u->config_msgnum, 1, "");
820                 }
821         }
822
823         FreeStrBuf (&text);
824
825 }
826
827
828 /*
829  * This is our callback registration table for libSieve.
830  */
831 sieve2_callback_t ctdl_sieve_callbacks[] = {
832         { SIEVE2_ACTION_REJECT,         ctdl_reject             },
833         { SIEVE2_ACTION_VACATION,       ctdl_vacation           },
834         { SIEVE2_ERRCALL_PARSE,         ctdl_errparse           },
835         { SIEVE2_ERRCALL_RUNTIME,       ctdl_errexec            },
836         { SIEVE2_ACTION_FILEINTO,       ctdl_fileinto           },
837         { SIEVE2_ACTION_REDIRECT,       ctdl_redirect           },
838         { SIEVE2_ACTION_DISCARD,        ctdl_discard            },
839         { SIEVE2_ACTION_KEEP,           ctdl_keep               },
840         { SIEVE2_SCRIPT_GETSCRIPT,      ctdl_getscript          },
841         { SIEVE2_DEBUG_TRACE,           ctdl_debug              },
842         { SIEVE2_MESSAGE_GETALLHEADERS, ctdl_getheaders         },
843         { SIEVE2_MESSAGE_GETSIZE,       ctdl_getsize            },
844         { SIEVE2_MESSAGE_GETENVELOPE,   ctdl_getenvelope        },
845 /*
846  * These actions are unsupported by Citadel so we don't declare them.
847  *
848         { SIEVE2_ACTION_NOTIFY,         ctdl_notify             },
849         { SIEVE2_MESSAGE_GETSUBADDRESS, ctdl_getsubaddress      },
850         { SIEVE2_MESSAGE_GETBODY,       ctdl_getbody            },
851  *
852  */
853         { 0 }
854 };
855
856
857 /*
858  * Perform sieve processing for a single room
859  */
860 void sieve_do_room(char *roomname) {
861         
862         struct sdm_userdata u;
863         sieve2_context_t *sieve2_context = NULL;        /* Context for sieve parser */
864         int res;                                        /* Return code from libsieve calls */
865         long orig_lastproc = 0;
866
867         memset(&u, 0, sizeof u);
868
869         /* See if the user who owns this 'mailbox' has any Sieve scripts that
870          * require execution.
871          */
872         snprintf(u.config_roomname, sizeof u.config_roomname, "%010ld.%s", atol(roomname), USERCONFIGROOM);
873         if (CtdlGetRoom(&CC->room, u.config_roomname) != 0) {
874                 syslog(LOG_DEBUG, "<%s> does not exist.  No processing is required.", u.config_roomname);
875                 return;
876         }
877
878         /*
879          * Find the sieve scripts and control record and do something
880          */
881         u.config_msgnum = (-1);
882         CtdlForEachMessage(MSGS_LAST, 1, NULL, SIEVECONFIG, NULL,
883                 get_sieve_config_backend, (void *)&u );
884
885         if (u.config_msgnum < 0) {
886                 syslog(LOG_DEBUG, "No Sieve rules exist.  No processing is required.");
887                 return;
888         }
889
890         /*
891          * Check to see whether the script is empty and should not be processed.
892          * A script is considered non-empty if it contains at least one semicolon.
893          */
894         if (
895                 (get_active_script(&u) == NULL)
896                 || (strchr(get_active_script(&u), ';') == NULL)
897         ) {
898                 syslog(LOG_DEBUG, "Sieve script is empty.  No processing is required.");
899                 return;
900         }
901
902         syslog(LOG_DEBUG, "Rules found.  Performing Sieve processing for <%s>", roomname);
903
904         if (CtdlGetRoom(&CC->room, roomname) != 0) {
905                 syslog(LOG_CRIT, "ERROR: cannot load <%s>", roomname);
906                 return;
907         }
908
909         /* Initialize the Sieve parser */
910         
911         res = sieve2_alloc(&sieve2_context);
912         if (res != SIEVE2_OK) {
913                 syslog(LOG_CRIT, "sieve2_alloc() returned %d: %s", res, sieve2_errstr(res));
914                 return;
915         }
916
917         res = sieve2_callbacks(sieve2_context, ctdl_sieve_callbacks);
918         if (res != SIEVE2_OK) {
919                 syslog(LOG_CRIT, "sieve2_callbacks() returned %d: %s", res, sieve2_errstr(res));
920                 goto BAIL;
921         }
922
923         /* Validate the script */
924
925         struct ctdl_sieve my;           /* dummy ctdl_sieve struct just to pass "u" slong */
926         memset(&my, 0, sizeof my);
927         my.u = &u;
928         res = sieve2_validate(sieve2_context, &my);
929         if (res != SIEVE2_OK) {
930                 syslog(LOG_CRIT, "sieve2_validate() returned %d: %s", res, sieve2_errstr(res));
931                 goto BAIL;
932         }
933
934         /* Do something useful */
935         u.sieve2_context = sieve2_context;
936         orig_lastproc = u.lastproc;
937         CtdlForEachMessage(MSGS_GT, u.lastproc, NULL, NULL, NULL,
938                 sieve_do_msg,
939                 (void *) &u
940         );
941
942 BAIL:
943         res = sieve2_free(&sieve2_context);
944         if (res != SIEVE2_OK) {
945                 syslog(LOG_CRIT, "sieve2_free() returned %d: %s", res, sieve2_errstr(res));
946         }
947
948         /* Rewrite the config if we have to */
949         rewrite_ctdl_sieve_config(&u, (u.lastproc > orig_lastproc) ) ;
950 }
951
952
953 /*
954  * Perform sieve processing for all rooms which require it
955  */
956 void perform_sieve_processing(void) {
957         struct RoomProcList *ptr = NULL;
958
959         if (sieve_list != NULL) {
960                 syslog(LOG_DEBUG, "Begin Sieve processing");
961                 while (sieve_list != NULL) {
962                         char spoolroomname[ROOMNAMELEN];
963                         safestrncpy(spoolroomname, sieve_list->name, sizeof spoolroomname);
964                         begin_critical_section(S_SIEVELIST);
965
966                         /* pop this record off the list */
967                         ptr = sieve_list;
968                         sieve_list = sieve_list->next;
969                         free(ptr);
970
971                         /* invalidate any duplicate entries to prevent double processing */
972                         for (ptr=sieve_list; ptr!=NULL; ptr=ptr->next) {
973                                 if (!strcasecmp(ptr->name, spoolroomname)) {
974                                         ptr->name[0] = 0;
975                                 }
976                         }
977
978                         end_critical_section(S_SIEVELIST);
979                         if (spoolroomname[0] != 0) {
980                                 sieve_do_room(spoolroomname);
981                         }
982                 }
983         }
984 }
985
986
987 void msiv_load(struct sdm_userdata *u) {
988         char hold_rm[ROOMNAMELEN];
989
990         strcpy(hold_rm, CC->room.QRname);       /* save current room */
991
992         /* Take a spin through the user's personal address book */
993         if (CtdlGetRoom(&CC->room, USERCONFIGROOM) == 0) {
994         
995                 u->config_msgnum = (-1);
996                 strcpy(u->config_roomname, CC->room.QRname);
997                 CtdlForEachMessage(MSGS_LAST, 1, NULL, SIEVECONFIG, NULL,
998                         get_sieve_config_backend, (void *)u );
999
1000         }
1001
1002         if (strcmp(CC->room.QRname, hold_rm)) {
1003                 CtdlGetRoom(&CC->room, hold_rm);    /* return to saved room */
1004         }
1005 }
1006
1007 void msiv_store(struct sdm_userdata *u, int yes_write_to_disk) {
1008 /*
1009  * Initialise the sieve configs last processed message number.
1010  * We don't need to get the highest message number for the users inbox since the systems
1011  * highest message number will be higher than that and loer than this scripts message number
1012  * This prevents this new script from processing any old messages in the inbox.
1013  * Most importantly it will prevent vacation messages being sent to lots of old messages
1014  * in the inbox.
1015  */
1016         u->lastproc = CtdlGetCurrentMessageNumber();
1017         rewrite_ctdl_sieve_config(u, yes_write_to_disk);
1018 }
1019
1020
1021 /*
1022  * Select the active script.
1023  * (Set script_name to an empty string to disable all scripts)
1024  * 
1025  * Returns 0 on success or nonzero for error.
1026  */
1027 int msiv_setactive(struct sdm_userdata *u, char *script_name) {
1028         int ok = 0;
1029         struct sdm_script *s;
1030
1031         /* First see if the supplied value is ok */
1032
1033         if (IsEmptyStr(script_name)) {
1034                 ok = 1;
1035         }
1036         else {
1037                 for (s=u->first_script; s!=NULL; s=s->next) {
1038                         if (!strcasecmp(s->script_name, script_name)) {
1039                                 ok = 1;
1040                         }
1041                 }
1042         }
1043
1044         if (!ok) return(-1);
1045
1046         /* Now set the active script */
1047         for (s=u->first_script; s!=NULL; s=s->next) {
1048                 if (!strcasecmp(s->script_name, script_name)) {
1049                         s->script_active = 1;
1050                 }
1051                 else {
1052                         s->script_active = 0;
1053                 }
1054         }
1055         
1056         return(0);
1057 }
1058
1059
1060 /*
1061  * Fetch a script by name.
1062  *
1063  * Returns NULL if the named script was not found, or a pointer to the script
1064  * if it was found.   NOTE: the caller does *not* own the memory returned by
1065  * this function.  Copy it if you need to keep it.
1066  */
1067 char *msiv_getscript(struct sdm_userdata *u, char *script_name) {
1068         struct sdm_script *s;
1069
1070         for (s=u->first_script; s!=NULL; s=s->next) {
1071                 if (!strcasecmp(s->script_name, script_name)) {
1072                         if (s->script_content != NULL) {
1073                                 return (s->script_content);
1074                         }
1075                 }
1076         }
1077
1078         return(NULL);
1079 }
1080
1081
1082 /*
1083  * Delete a script by name.
1084  *
1085  * Returns 0 if the script was deleted.
1086  *       1 if the script was not found.
1087  *       2 if the script cannot be deleted because it is active.
1088  */
1089 int msiv_deletescript(struct sdm_userdata *u, char *script_name) {
1090         struct sdm_script *s = NULL;
1091         struct sdm_script *script_to_delete = NULL;
1092
1093         for (s=u->first_script; s!=NULL; s=s->next) {
1094                 if (!strcasecmp(s->script_name, script_name)) {
1095                         script_to_delete = s;
1096                         if (s->script_active) {
1097                                 return(2);
1098                         }
1099                 }
1100         }
1101
1102         if (script_to_delete == NULL) return(1);
1103
1104         if (u->first_script == script_to_delete) {
1105                 u->first_script = u->first_script->next;
1106         }
1107         else for (s=u->first_script; s!=NULL; s=s->next) {
1108                 if (s->next == script_to_delete) {
1109                         s->next = s->next->next;
1110                 }
1111         }
1112
1113         free(script_to_delete->script_content);
1114         free(script_to_delete);
1115         return(0);
1116 }
1117
1118
1119 /*
1120  * Add or replace a new script.  
1121  * NOTE: after this function returns, "u" owns the memory that "script_content"
1122  * was pointing to.
1123  */
1124 void msiv_putscript(struct sdm_userdata *u, char *script_name, char *script_content) {
1125         int replaced = 0;
1126         struct sdm_script *s, *sptr;
1127
1128         for (s=u->first_script; s!=NULL; s=s->next) {
1129                 if (!strcasecmp(s->script_name, script_name)) {
1130                         if (s->script_content != NULL) {
1131                                 free(s->script_content);
1132                         }
1133                         s->script_content = script_content;
1134                         replaced = 1;
1135                 }
1136         }
1137
1138         if (replaced == 0) {
1139                 sptr = malloc(sizeof(struct sdm_script));
1140                 safestrncpy(sptr->script_name, script_name, sizeof sptr->script_name);
1141                 sptr->script_content = script_content;
1142                 sptr->script_active = 0;
1143                 sptr->next = u->first_script;
1144                 u->first_script = sptr;
1145         }
1146 }
1147
1148
1149
1150 /*
1151  * Citadel protocol to manage sieve scripts.
1152  * This is basically a simplified (read: doesn't resemble IMAP) version
1153  * of the 'managesieve' protocol.
1154  */
1155 void cmd_msiv(char *argbuf) {
1156         char subcmd[256];
1157         struct sdm_userdata u;
1158         char script_name[256];
1159         char *script_content = NULL;
1160         struct sdm_script *s;
1161         int i;
1162         int changes_made = 0;
1163
1164         memset(&u, 0, sizeof(struct sdm_userdata));
1165
1166         if (CtdlAccessCheck(ac_logged_in)) return;
1167         extract_token(subcmd, argbuf, 0, '|', sizeof subcmd);
1168         msiv_load(&u);
1169
1170         if (!strcasecmp(subcmd, "putscript")) {
1171                 extract_token(script_name, argbuf, 1, '|', sizeof script_name);
1172                 if (!IsEmptyStr(script_name)) {
1173                         cprintf("%d Transmit script now\n", SEND_LISTING);
1174                         script_content = CtdlReadMessageBody(HKEY("000"), CtdlGetConfigLong("c_maxmsglen"), NULL, 0);
1175                         msiv_putscript(&u, script_name, script_content);
1176                         changes_made = 1;
1177                 }
1178                 else {
1179                         cprintf("%d Invalid script name.\n", ERROR + ILLEGAL_VALUE);
1180                 }
1181         }       
1182         
1183         else if (!strcasecmp(subcmd, "listscripts")) {
1184                 cprintf("%d Scripts:\n", LISTING_FOLLOWS);
1185                 for (s=u.first_script; s!=NULL; s=s->next) {
1186                         if (s->script_content != NULL) {
1187                                 cprintf("%s|%d|\n", s->script_name, s->script_active);
1188                         }
1189                 }
1190                 cprintf("000\n");
1191         }
1192
1193         else if (!strcasecmp(subcmd, "setactive")) {
1194                 extract_token(script_name, argbuf, 1, '|', sizeof script_name);
1195                 if (msiv_setactive(&u, script_name) == 0) {
1196                         cprintf("%d ok\n", CIT_OK);
1197                         changes_made = 1;
1198                 }
1199                 else {
1200                         cprintf("%d Script '%s' does not exist.\n",
1201                                 ERROR + ILLEGAL_VALUE,
1202                                 script_name
1203                         );
1204                 }
1205         }
1206
1207         else if (!strcasecmp(subcmd, "getscript")) {
1208                 extract_token(script_name, argbuf, 1, '|', sizeof script_name);
1209                 script_content = msiv_getscript(&u, script_name);
1210                 if (script_content != NULL) {
1211                         int script_len;
1212
1213                         cprintf("%d Script:\n", LISTING_FOLLOWS);
1214                         script_len = strlen(script_content);
1215                         client_write(script_content, script_len);
1216                         if (script_content[script_len-1] != '\n') {
1217                                 cprintf("\n");
1218                         }
1219                         cprintf("000\n");
1220                 }
1221                 else {
1222                         cprintf("%d Invalid script name.\n", ERROR + ILLEGAL_VALUE);
1223                 }
1224         }
1225
1226         else if (!strcasecmp(subcmd, "deletescript")) {
1227                 extract_token(script_name, argbuf, 1, '|', sizeof script_name);
1228                 i = msiv_deletescript(&u, script_name);
1229                 if (i == 0) {
1230                         cprintf("%d ok\n", CIT_OK);
1231                         changes_made = 1;
1232                 }
1233                 else if (i == 1) {
1234                         cprintf("%d Script '%s' does not exist.\n",
1235                                 ERROR + ILLEGAL_VALUE,
1236                                 script_name
1237                         );
1238                 }
1239                 else if (i == 2) {
1240                         cprintf("%d Script '%s' is active and cannot be deleted.\n",
1241                                 ERROR + ILLEGAL_VALUE,
1242                                 script_name
1243                         );
1244                 }
1245                 else {
1246                         cprintf("%d unknown error\n", ERROR);
1247                 }
1248         }
1249
1250         else {
1251                 cprintf("%d Invalid subcommand\n", ERROR + CMD_NOT_SUPPORTED);
1252         }
1253
1254         msiv_store(&u, changes_made);
1255 }
1256
1257
1258
1259 void ctdl_sieve_init(void) {
1260         char *cred = NULL;
1261         sieve2_context_t *sieve2_context = NULL;
1262         int res;
1263
1264         /*
1265          *      We don't really care about dumping the entire credits to the log
1266          *      every time the server is initialized.  The documentation will suffice
1267          *      for that purpose.  We are making a call to sieve2_credits() in order
1268          *      to demonstrate that we have successfully linked in to libsieve.
1269          */
1270         cred = strdup(sieve2_credits());
1271         if (cred == NULL) return;
1272
1273         if (strlen(cred) > 60) {
1274                 strcpy(&cred[55], "...");
1275         }
1276
1277         syslog(LOG_INFO, "%s",cred);
1278         free(cred);
1279
1280         /* Briefly initialize a Sieve parser instance just so we can list the
1281          * extensions that are available.
1282          */
1283         res = sieve2_alloc(&sieve2_context);
1284         if (res != SIEVE2_OK) {
1285                 syslog(LOG_CRIT, "sieve2_alloc() returned %d: %s", res, sieve2_errstr(res));
1286                 return;
1287         }
1288
1289         res = sieve2_callbacks(sieve2_context, ctdl_sieve_callbacks);
1290         if (res != SIEVE2_OK) {
1291                 syslog(LOG_CRIT, "sieve2_callbacks() returned %d: %s", res, sieve2_errstr(res));
1292                 goto BAIL;
1293         }
1294
1295         msiv_extensions = strdup(sieve2_listextensions(sieve2_context));
1296         syslog(LOG_INFO, "Extensions: %s", msiv_extensions);
1297
1298 BAIL:   res = sieve2_free(&sieve2_context);
1299         if (res != SIEVE2_OK) {
1300                 syslog(LOG_CRIT, "sieve2_free() returned %d: %s", res, sieve2_errstr(res));
1301         }
1302
1303 }
1304
1305 void cleanup_sieve(void)
1306 {
1307         struct RoomProcList *ptr, *ptr2;
1308
1309         if (msiv_extensions != NULL)
1310                 free(msiv_extensions);
1311         msiv_extensions = NULL;
1312
1313         begin_critical_section(S_SIEVELIST);
1314         ptr=sieve_list;
1315         while (ptr != NULL) {
1316                 ptr2 = ptr->next;
1317                 free(ptr);
1318                 ptr = ptr2;
1319         }
1320         sieve_list = NULL;
1321         end_critical_section(S_SIEVELIST);
1322 }
1323
1324 int serv_sieve_room(struct ctdlroom *room)
1325 {
1326         if (!strcasecmp(&room->QRname[11], MAILROOM)) {
1327                 sieve_queue_room(room);
1328         }
1329         return 0;
1330 }
1331
1332 CTDL_MODULE_INIT(sieve)
1333 {
1334         if (!threading)
1335         {
1336                 ctdl_sieve_init();
1337                 CtdlRegisterProtoHook(cmd_msiv, "MSIV", "Manage Sieve scripts");
1338                 CtdlRegisterRoomHook(serv_sieve_room);
1339                 CtdlRegisterSessionHook(perform_sieve_processing, EVT_HOUSE, PRIO_HOUSE + 10);
1340                 CtdlRegisterCleanupHook(cleanup_sieve);
1341         }
1342         
1343         /* return our module name for the log */
1344         return "sieve";
1345 }
1346