960393d96dfcde2065b05959f794f63284996ec3
[citadel.git] / citadel / modules / sieve / serv_sieve.c
1 /*
2  * $Id$
3  *
4  * This module glues libSieve to the Citadel server in order to implement
5  * the Sieve mailbox filtering language (RFC 3028).
6  *
7  * Copyright (c) 2007-2009 by the citadel.org team
8  *
9  *  This program is free software; you can redistribute it and/or modify
10  *  it under the terms of the GNU General Public License as published by
11  *  the Free Software Foundation; either version 3 of the License, or
12  *  (at your option) any later version.
13  *
14  *  This program is distributed in the hope that it will be useful,
15  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
16  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  *  GNU General Public License for more details.
18  *
19  *  You should have received a copy of the GNU General Public License
20  *  along with this program; if not, write to the Free Software
21  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22  */
23
24 #include "sysdep.h"
25 #include <stdlib.h>
26 #include <unistd.h>
27 #include <stdio.h>
28 #include <fcntl.h>
29 #include <ctype.h>
30 #include <pwd.h>
31 #include <errno.h>
32 #include <sys/types.h>
33
34 #if TIME_WITH_SYS_TIME
35 # include <sys/time.h>
36 # include <time.h>
37 #else
38 # if HAVE_SYS_TIME_H
39 #  include <sys/time.h>
40 # else
41 #  include <time.h>
42 # endif
43 #endif
44
45 #include <sys/wait.h>
46 #include <string.h>
47 #include <limits.h>
48 #include <libcitadel.h>
49 #include "citadel.h"
50 #include "server.h"
51 #include "citserver.h"
52 #include "support.h"
53 #include "config.h"
54 #include "policy.h"
55 #include "database.h"
56 #include "msgbase.h"
57 #include "internet_addressing.h"
58 #include "ctdl_module.h"
59 #include "serv_sieve.h"
60
61 struct RoomProcList *sieve_list = NULL;
62 char *msiv_extensions = NULL;
63
64
65 /*
66  * Callback function to send libSieve trace messages to Citadel log facility
67  */
68 int ctdl_debug(sieve2_context_t *s, void *my)
69 {
70         CtdlLogPrintf(CTDL_DEBUG, "Sieve: %s\n", sieve2_getvalue_string(s, "message"));
71         return SIEVE2_OK;
72 }
73
74
75 /*
76  * Callback function to log script parsing errors
77  */
78 int ctdl_errparse(sieve2_context_t *s, void *my)
79 {
80         CtdlLogPrintf(CTDL_WARNING, "Error in script, line %d: %s\n",
81                 sieve2_getvalue_int(s, "lineno"),
82                 sieve2_getvalue_string(s, "message")
83         );
84         return SIEVE2_OK;
85 }
86
87
88 /*
89  * Callback function to log script execution errors
90  */
91 int ctdl_errexec(sieve2_context_t *s, void *my)
92 {
93         CtdlLogPrintf(CTDL_WARNING, "Error executing script: %s\n",
94                 sieve2_getvalue_string(s, "message")
95         );
96         return SIEVE2_OK;
97 }
98
99
100 /*
101  * Callback function to redirect a message to a different folder
102  */
103 int ctdl_redirect(sieve2_context_t *s, void *my)
104 {
105         struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
106         struct CtdlMessage *msg = NULL;
107         struct recptypes *valid = NULL;
108         char recp[256];
109
110         safestrncpy(recp, sieve2_getvalue_string(s, "address"), sizeof recp);
111
112         CtdlLogPrintf(CTDL_DEBUG, "Action is REDIRECT, recipient <%s>\n", recp);
113
114         valid = validate_recipients(recp, NULL, 0);
115         if (valid == NULL) {
116                 CtdlLogPrintf(CTDL_WARNING, "REDIRECT failed: bad recipient <%s>\n", recp);
117                 return SIEVE2_ERROR_BADARGS;
118         }
119         if (valid->num_error > 0) {
120                 CtdlLogPrintf(CTDL_WARNING, "REDIRECT failed: bad recipient <%s>\n", recp);
121                 free_recipients(valid);
122                 return SIEVE2_ERROR_BADARGS;
123         }
124
125         msg = CtdlFetchMessage(cs->msgnum, 1);
126         if (msg == NULL) {
127                 CtdlLogPrintf(CTDL_WARNING, "REDIRECT failed: unable to fetch msg %ld\n", cs->msgnum);
128                 free_recipients(valid);
129                 return SIEVE2_ERROR_BADARGS;
130         }
131
132         CtdlSubmitMsg(msg, valid, NULL, 0);
133         cs->cancel_implicit_keep = 1;
134         free_recipients(valid);
135         CtdlFreeMessage(msg);
136         return SIEVE2_OK;
137 }
138
139
140 /*
141  * Callback function to indicate that a message *will* be kept in the inbox
142  */
143 int ctdl_keep(sieve2_context_t *s, void *my)
144 {
145         struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
146         
147         CtdlLogPrintf(CTDL_DEBUG, "Action is KEEP\n");
148
149         cs->keep = 1;
150         cs->cancel_implicit_keep = 1;
151         return SIEVE2_OK;
152 }
153
154
155 /*
156  * Callback function to file a message into a different mailbox
157  */
158 int ctdl_fileinto(sieve2_context_t *s, void *my)
159 {
160         struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
161         const char *dest_folder = sieve2_getvalue_string(s, "mailbox");
162         int c;
163         char foldername[256];
164         char original_room_name[ROOMNAMELEN];
165
166         CtdlLogPrintf(CTDL_DEBUG, "Action is FILEINTO, destination is <%s>\n", dest_folder);
167
168         /* FILEINTO 'INBOX' is the same thing as KEEP */
169         if ( (!strcasecmp(dest_folder, "INBOX")) || (!strcasecmp(dest_folder, MAILROOM)) ) {
170                 cs->keep = 1;
171                 cs->cancel_implicit_keep = 1;
172                 return SIEVE2_OK;
173         }
174
175         /* Remember what room we came from */
176         safestrncpy(original_room_name, CC->room.QRname, sizeof original_room_name);
177
178         /* First try a mailbox name match (check personal mail folders first) */
179         snprintf(foldername, sizeof foldername, "%010ld.%s", cs->usernum, dest_folder);
180         c = CtdlGetRoom(&CC->room, foldername);
181
182         /* Then a regular room name match (public and private rooms) */
183         if (c != 0) {
184                 safestrncpy(foldername, dest_folder, sizeof foldername);
185                 c = CtdlGetRoom(&CC->room, foldername);
186         }
187
188         if (c != 0) {
189                 CtdlLogPrintf(CTDL_WARNING, "FILEINTO failed: target <%s> does not exist\n", dest_folder);
190                 return SIEVE2_ERROR_BADARGS;
191         }
192
193         /* Yes, we actually have to go there */
194         CtdlUserGoto(NULL, 0, 0, NULL, NULL);
195
196         c = CtdlSaveMsgPointersInRoom(NULL, &cs->msgnum, 1, 0, NULL);
197
198         /* Go back to the room we came from */
199         if (strcasecmp(original_room_name, CC->room.QRname)) {
200                 CtdlUserGoto(original_room_name, 0, 0, NULL, NULL);
201         }
202
203         if (c == 0) {
204                 cs->cancel_implicit_keep = 1;
205                 return SIEVE2_OK;
206         }
207         else {
208                 return SIEVE2_ERROR_BADARGS;
209         }
210 }
211
212
213 /*
214  * Callback function to indicate that a message should be discarded.
215  */
216 int ctdl_discard(sieve2_context_t *s, void *my)
217 {
218         struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
219
220         CtdlLogPrintf(CTDL_DEBUG, "Action is DISCARD\n");
221
222         /* Cancel the implicit keep.  That's all there is to it. */
223         cs->cancel_implicit_keep = 1;
224         return SIEVE2_OK;
225 }
226
227
228
229 /*
230  * Callback function to indicate that a message should be rejected
231  */
232 int ctdl_reject(sieve2_context_t *s, void *my)
233 {
234         struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
235         char *reject_text = NULL;
236
237         CtdlLogPrintf(CTDL_DEBUG, "Action is REJECT\n");
238
239         /* If we don't know who sent the message, do a DISCARD instead. */
240         if (IsEmptyStr(cs->sender)) {
241                 CtdlLogPrintf(CTDL_INFO, "Unknown sender.  Doing DISCARD instead of REJECT.\n");
242                 return ctdl_discard(s, my);
243         }
244
245         /* Assemble the reject message. */
246         reject_text = malloc(strlen(sieve2_getvalue_string(s, "message")) + 1024);
247         if (reject_text == NULL) {
248                 return SIEVE2_ERROR_FAIL;
249         }
250
251         sprintf(reject_text, 
252                 "Content-type: text/plain\n"
253                 "\n"
254                 "The message was refused by the recipient's mail filtering program.\n"
255                 "The reason given was as follows:\n"
256                 "\n"
257                 "%s\n"
258                 "\n"
259         ,
260                 sieve2_getvalue_string(s, "message")
261         );
262
263         quickie_message(        /* This delivers the message */
264                 NULL,
265                 cs->envelope_to,
266                 cs->sender,
267                 NULL,
268                 reject_text,
269                 FMT_RFC822,
270                 "Delivery status notification"
271         );
272
273         free(reject_text);
274         cs->cancel_implicit_keep = 1;
275         return SIEVE2_OK;
276 }
277
278
279
280 /*
281  * Callback function to indicate that a vacation message should be generated
282  */
283 int ctdl_vacation(sieve2_context_t *s, void *my)
284 {
285         struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
286         struct sdm_vacation *vptr;
287         int days = 1;
288         const char *message;
289         char *vacamsg_text = NULL;
290         char vacamsg_subject[1024];
291
292         CtdlLogPrintf(CTDL_DEBUG, "Action is VACATION\n");
293
294         message = sieve2_getvalue_string(s, "message");
295         if (message == NULL) return SIEVE2_ERROR_BADARGS;
296
297         if (sieve2_getvalue_string(s, "subject") != NULL) {
298                 safestrncpy(vacamsg_subject, sieve2_getvalue_string(s, "subject"), sizeof vacamsg_subject);
299         }
300         else {
301                 snprintf(vacamsg_subject, sizeof vacamsg_subject, "Re: %s", cs->subject);
302         }
303
304         days = sieve2_getvalue_int(s, "days");
305         if (days < 1) days = 1;
306         if (days > MAX_VACATION) days = MAX_VACATION;
307
308         /* Check to see whether we've already alerted this sender that we're on vacation. */
309         for (vptr = cs->u->first_vacation; vptr != NULL; vptr = vptr->next) {
310                 if (!strcasecmp(vptr->fromaddr, cs->sender)) {
311                         if ( (time(NULL) - vptr->timestamp) < (days * 86400) ) {
312                                 CtdlLogPrintf(CTDL_DEBUG, "Already alerted <%s> recently.\n", cs->sender);
313                                 return SIEVE2_OK;
314                         }
315                 }
316         }
317
318         /* Assemble the reject message. */
319         vacamsg_text = malloc(strlen(message) + 1024);
320         if (vacamsg_text == NULL) {
321                 return SIEVE2_ERROR_FAIL;
322         }
323
324         sprintf(vacamsg_text, 
325                 "Content-type: text/plain\n"
326                 "\n"
327                 "%s\n"
328                 "\n"
329         ,
330                 message
331         );
332
333         quickie_message(        /* This delivers the message */
334                 NULL,
335                 cs->envelope_to,
336                 cs->sender,
337                 NULL,
338                 vacamsg_text,
339                 FMT_RFC822,
340                 vacamsg_subject
341         );
342
343         free(vacamsg_text);
344
345         /* Now update the list to reflect the fact that we've alerted this sender.
346          * If they're already in the list, just update the timestamp.
347          */
348         for (vptr = cs->u->first_vacation; vptr != NULL; vptr = vptr->next) {
349                 if (!strcasecmp(vptr->fromaddr, cs->sender)) {
350                         vptr->timestamp = time(NULL);
351                         return SIEVE2_OK;
352                 }
353         }
354
355         /* If we get to this point, create a new record.
356          */
357         vptr = malloc(sizeof(struct sdm_vacation));
358         vptr->timestamp = time(NULL);
359         safestrncpy(vptr->fromaddr, cs->sender, sizeof vptr->fromaddr);
360         vptr->next = cs->u->first_vacation;
361         cs->u->first_vacation = vptr;
362
363         return SIEVE2_OK;
364 }
365
366
367 /*
368  * Callback function to parse addresses per local system convention
369  * It is disabled because we don't support subaddresses.
370  */
371 #if 0
372 int ctdl_getsubaddress(sieve2_context_t *s, void *my)
373 {
374         struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
375
376         /* libSieve does not take ownership of the memory used here.  But, since we
377          * are just pointing to locations inside a struct which we are going to free
378          * later, we're ok.
379          */
380         sieve2_setvalue_string(s, "user", cs->recp_user);
381         sieve2_setvalue_string(s, "detail", "");
382         sieve2_setvalue_string(s, "localpart", cs->recp_user);
383         sieve2_setvalue_string(s, "domain", cs->recp_node);
384         return SIEVE2_OK;
385 }
386 #endif
387
388
389 /*
390  * Callback function to parse message envelope
391  */
392 int ctdl_getenvelope(sieve2_context_t *s, void *my)
393 {
394         struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
395
396         CtdlLogPrintf(CTDL_DEBUG, "Action is GETENVELOPE\nEnvFrom: %s\n  EnvTo: %s\n",
397                 cs->envelope_from, cs->envelope_to);
398
399         if (cs->envelope_from != NULL) {
400                 if ((cs->envelope_from[0] != '@')&&(cs->envelope_from[strlen(cs->envelope_from)-1] != '@')) {
401                         sieve2_setvalue_string(s, "from", cs->envelope_from);
402                 }
403                 else {
404                         sieve2_setvalue_string(s, "from", "invalid_envelope_from@example.org");
405                 }
406         }
407         else {
408                 sieve2_setvalue_string(s, "from", "null_envelope_from@example.org");
409         }
410
411
412         if (cs->envelope_to != NULL) {
413                 if ((cs->envelope_to[0] != '@') && (cs->envelope_to[strlen(cs->envelope_to)-1] != '@')) {
414                         sieve2_setvalue_string(s, "to", cs->envelope_to);
415                 }
416                 else {
417                         sieve2_setvalue_string(s, "to", "invalid_envelope_to@example.org");
418                 }
419         }
420         else {
421                 sieve2_setvalue_string(s, "to", "null_envelope_to@example.org");
422         }
423
424         return SIEVE2_OK;
425 }
426
427
428 /*
429  * Callback function to fetch message body
430  * (Uncomment the code if we implement this extension)
431  *
432 int ctdl_getbody(sieve2_context_t *s, void *my)
433 {
434         return SIEVE2_ERROR_UNSUPPORTED;
435 }
436  *
437  */
438
439
440 /*
441  * Callback function to fetch message size
442  */
443 int ctdl_getsize(sieve2_context_t *s, void *my)
444 {
445         struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
446         struct MetaData smi;
447
448         GetMetaData(&smi, cs->msgnum);
449         
450         if (smi.meta_rfc822_length > 0L) {
451                 sieve2_setvalue_int(s, "size", (int)smi.meta_rfc822_length);
452                 return SIEVE2_OK;
453         }
454
455         return SIEVE2_ERROR_UNSUPPORTED;
456 }
457
458
459 /*
460  * Callback function to retrieve the sieve script
461  */
462 int ctdl_getscript(sieve2_context_t *s, void *my) {
463         struct sdm_script *sptr;
464         struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
465
466         for (sptr=cs->u->first_script; sptr!=NULL; sptr=sptr->next) {
467                 if (sptr->script_active > 0) {
468                         CtdlLogPrintf(CTDL_DEBUG, "ctdl_getscript() is using script '%s'\n", sptr->script_name);
469                         sieve2_setvalue_string(s, "script", sptr->script_content);
470                         return SIEVE2_OK;
471                 }
472         }
473                 
474         CtdlLogPrintf(CTDL_DEBUG, "ctdl_getscript() found no active script\n");
475         return SIEVE2_ERROR_GETSCRIPT;
476 }
477
478 /*
479  * Callback function to retrieve message headers
480  */
481 int ctdl_getheaders(sieve2_context_t *s, void *my) {
482
483         struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
484
485         CtdlLogPrintf(CTDL_DEBUG, "ctdl_getheaders() was called\n");
486         sieve2_setvalue_string(s, "allheaders", cs->rfc822headers);
487         return SIEVE2_OK;
488 }
489
490
491
492 /*
493  * Add a room to the list of those rooms which potentially require sieve processing
494  */
495 void sieve_queue_room(struct ctdlroom *which_room) {
496         struct RoomProcList *ptr;
497
498         ptr = (struct RoomProcList *) malloc(sizeof (struct RoomProcList));
499         if (ptr == NULL) return;
500
501         safestrncpy(ptr->name, which_room->QRname, sizeof ptr->name);
502         begin_critical_section(S_SIEVELIST);
503         ptr->next = sieve_list;
504         sieve_list = ptr;
505         end_critical_section(S_SIEVELIST);
506         CtdlLogPrintf(CTDL_DEBUG, "<%s> queued for Sieve processing\n", which_room->QRname);
507 }
508
509
510
511 /*
512  * Perform sieve processing for one message (called by sieve_do_room() for each message)
513  */
514 void sieve_do_msg(long msgnum, void *userdata) {
515         struct sdm_userdata *u = (struct sdm_userdata *) userdata;
516         sieve2_context_t *sieve2_context;
517         struct ctdl_sieve my;
518         int res;
519         struct CtdlMessage *msg;
520         int i;
521         size_t headers_len = 0;
522         int len = 0;
523
524         if (u == NULL)
525         {
526                 CtdlLogPrintf(CTDL_EMERG, "Can't process message <%ld> without userdata!\n", msgnum);
527                 return;
528         }
529
530         sieve2_context = u->sieve2_context;
531
532         CtdlLogPrintf(CTDL_DEBUG, "Performing sieve processing on msg <%ld>\n", msgnum);
533
534         /*
535          * Make sure you include message body so you can get those second-level headers ;)
536          */
537         msg = CtdlFetchMessage(msgnum, 1);
538         if (msg == NULL) return;
539
540         /*
541          * Grab the message headers so we can feed them to libSieve.
542          * Use HEADERS_ONLY rather than HEADERS_FAST in order to include second-level headers.
543          */
544         CC->redirect_buffer = malloc(SIZ);
545         CC->redirect_len = 0;
546         CC->redirect_alloc = SIZ;
547         CtdlOutputPreLoadedMsg(msg, MT_RFC822, HEADERS_ONLY, 0, 1, 0);
548         my.rfc822headers = CC->redirect_buffer;
549         headers_len = CC->redirect_len;
550         CC->redirect_buffer = NULL;
551         CC->redirect_len = 0;
552         CC->redirect_alloc = 0;
553
554         /*
555          * libSieve clobbers the stack if it encounters badly formed
556          * headers.  Sanitize our headers by stripping nonprintable
557          * characters.
558          */
559         for (i=0; i<headers_len; ++i) {
560                 if (!isascii(my.rfc822headers[i])) {
561                         my.rfc822headers[i] = '_';
562                 }
563         }
564
565         my.keep = 0;                            /* Set to 1 to declare an *explicit* keep */
566         my.cancel_implicit_keep = 0;            /* Some actions will cancel the implicit keep */
567         my.usernum = atol(CC->room.QRname);     /* Keep track of the owner of the room's namespace */
568         my.msgnum = msgnum;                     /* Keep track of the message number in our local store */
569         my.u = u;                               /* Hand off a pointer to the rest of this info */
570
571         /* Keep track of the recipient so we can do handling based on it later */
572         process_rfc822_addr(msg->cm_fields['R'], my.recp_user, my.recp_node, my.recp_name);
573
574         /* Keep track of the sender so we can use it for REJECT and VACATION responses */
575         if (msg->cm_fields['F'] != NULL) {
576                 safestrncpy(my.sender, msg->cm_fields['F'], sizeof my.sender);
577         }
578         else if ( (msg->cm_fields['A'] != NULL) && (msg->cm_fields['N'] != NULL) ) {
579                 snprintf(my.sender, sizeof my.sender, "%s@%s", msg->cm_fields['A'], msg->cm_fields['N']);
580         }
581         else if (msg->cm_fields['A'] != NULL) {
582                 safestrncpy(my.sender, msg->cm_fields['A'], 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 (msg->cm_fields['U'] != NULL) {
590                 safestrncpy(my.subject, msg->cm_fields['U'], 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 (msg->cm_fields['P'] != NULL) {
598                 safestrncpy(my.envelope_from, msg->cm_fields['P'], sizeof my.envelope_from);
599                 stripallbut(my.envelope_from, '<', '>');
600         }
601         else if (msg->cm_fields['F'] != NULL) {
602                 safestrncpy(my.envelope_from, msg->cm_fields['F'], 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, config.c_fqdn);
616         }
617
618         /* Keep track of the envelope-to address (use body-to if not found) */
619         if (msg->cm_fields['V'] != NULL) {
620                 safestrncpy(my.envelope_to, msg->cm_fields['V'], sizeof my.envelope_to);
621                 stripallbut(my.envelope_to, '<', '>');
622         }
623         else if (msg->cm_fields['R'] != NULL) {
624                 safestrncpy(my.envelope_to, msg->cm_fields['R'], sizeof my.envelope_to);
625                 if (msg->cm_fields['D'] != NULL) {
626                         strcat(my.envelope_to, "@");
627                         strcat(my.envelope_to, msg->cm_fields['D']);
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, config.c_fqdn);
642         }
643
644         CtdlFreeMessage(msg);
645
646         sieve2_setvalue_string(sieve2_context, "allheaders", my.rfc822headers);
647         
648         CtdlLogPrintf(CTDL_DEBUG, "Calling sieve2_execute()\n");
649         res = sieve2_execute(sieve2_context, &my);
650         if (res != SIEVE2_OK) {
651                 CtdlLogPrintf(CTDL_CRIT, "sieve2_execute() returned %d: %s\n", res, sieve2_errstr(res));
652         }
653
654         free(my.rfc822headers);
655         my.rfc822headers = NULL;
656
657         /*
658          * Delete the message from the inbox unless either we were told not to, or
659          * if no other action was successfully taken.
660          */
661         if ( (!my.keep) && (my.cancel_implicit_keep) ) {
662                 CtdlLogPrintf(CTDL_DEBUG, "keep is 0 -- deleting message from inbox\n");
663                 CtdlDeleteMessages(CC->room.QRname, &msgnum, 1, "");
664         }
665
666         CtdlLogPrintf(CTDL_DEBUG, "Completed sieve processing on msg <%ld>\n", msgnum);
667         u->lastproc = msgnum;
668
669         return;
670 }
671
672
673
674 /*
675  * Given the on-disk representation of our Sieve config, load
676  * it into an in-memory data structure.
677  */
678 void parse_sieve_config(char *conf, struct sdm_userdata *u) {
679         char *ptr;
680         char *c, *vacrec;
681         char keyword[256];
682         struct sdm_script *sptr;
683         struct sdm_vacation *vptr;
684
685         ptr = conf;
686         while (c = ptr, ptr = bmstrcasestr(ptr, CTDLSIEVECONFIGSEPARATOR), ptr != NULL) {
687                 *ptr = 0;
688                 ptr += strlen(CTDLSIEVECONFIGSEPARATOR);
689
690                 extract_token(keyword, c, 0, '|', sizeof keyword);
691
692                 if (!strcasecmp(keyword, "lastproc")) {
693                         u->lastproc = extract_long(c, 1);
694                 }
695
696                 else if (!strcasecmp(keyword, "script")) {
697                         sptr = malloc(sizeof(struct sdm_script));
698                         extract_token(sptr->script_name, c, 1, '|', sizeof sptr->script_name);
699                         sptr->script_active = extract_int(c, 2);
700                         remove_token(c, 0, '|');
701                         remove_token(c, 0, '|');
702                         remove_token(c, 0, '|');
703                         sptr->script_content = strdup(c);
704                         sptr->next = u->first_script;
705                         u->first_script = sptr;
706                 }
707
708                 else if (!strcasecmp(keyword, "vacation")) {
709
710                         if (c != NULL) while (vacrec=c, c=strchr(c, '\n'), (c != NULL)) {
711
712                                 *c = 0;
713                                 ++c;
714
715                                 if (strncasecmp(vacrec, "vacation|", 9)) {
716                                         vptr = malloc(sizeof(struct sdm_vacation));
717                                         extract_token(vptr->fromaddr, vacrec, 0, '|', sizeof vptr->fromaddr);
718                                         vptr->timestamp = extract_long(vacrec, 1);
719                                         vptr->next = u->first_vacation;
720                                         u->first_vacation = vptr;
721                                 }
722                         }
723                 }
724
725                 /* ignore unknown keywords */
726         }
727 }
728
729 /*
730  * We found the Sieve configuration for this user.
731  * Now do something with it.
732  */
733 void get_sieve_config_backend(long msgnum, void *userdata) {
734         struct sdm_userdata *u = (struct sdm_userdata *) userdata;
735         struct CtdlMessage *msg;
736         char *conf;
737
738         u->config_msgnum = msgnum;
739         msg = CtdlFetchMessage(msgnum, 1);
740         if (msg == NULL) {
741                 u->config_msgnum = (-1) ;
742                 return;
743         }
744
745         conf = msg->cm_fields['M'];
746         msg->cm_fields['M'] = NULL;
747         CtdlFreeMessage(msg);
748
749         if (conf != NULL) {
750                 parse_sieve_config(conf, u);
751                 free(conf);
752         }
753
754 }
755
756
757 /* 
758  * Write our citadel sieve config back to disk
759  * 
760  * (Set yes_write_to_disk to nonzero to make it actually write the config;
761  * otherwise it just frees the data structures.)
762  */
763 void rewrite_ctdl_sieve_config(struct sdm_userdata *u, int yes_write_to_disk) {
764         char *text;
765         struct sdm_script *sptr;
766         struct sdm_vacation *vptr;
767         size_t tsize;
768
769         text = malloc(1024);
770         tsize = 1024;
771         snprintf(text, 1024,
772                 "Content-type: application/x-citadel-sieve-config\n"
773                 "\n"
774                 CTDLSIEVECONFIGSEPARATOR
775                 "lastproc|%ld"
776                 CTDLSIEVECONFIGSEPARATOR
777         ,
778                 u->lastproc
779         );
780
781         while (u->first_script != NULL) {
782                 size_t tlen;
783                 tlen = strlen(text);
784                 tsize = tlen + strlen(u->first_script->script_content) +256;
785                 text = realloc(text, tsize);
786                 sprintf(&text[strlen(text)], "script|%s|%d|%s" CTDLSIEVECONFIGSEPARATOR,
787                         u->first_script->script_name,
788                         u->first_script->script_active,
789                         u->first_script->script_content
790                 );
791                 sptr = u->first_script;
792                 u->first_script = u->first_script->next;
793                 free(sptr->script_content);
794                 free(sptr);
795         }
796
797         if (u->first_vacation != NULL) {
798
799                 tsize = strlen(text) + 256;
800                 for (vptr = u->first_vacation; vptr != NULL; vptr = vptr->next) {
801                         tsize += strlen(vptr->fromaddr + 32);
802                 }
803                 text = realloc(text, tsize);
804
805                 sprintf(&text[strlen(text)], "vacation|\n");
806                 while (u->first_vacation != NULL) {
807                         if ( (time(NULL) - u->first_vacation->timestamp) < (MAX_VACATION * 86400)) {
808                                 sprintf(&text[strlen(text)], "%s|%ld\n",
809                                         u->first_vacation->fromaddr,
810                                         u->first_vacation->timestamp
811                                 );
812                         }
813                         vptr = u->first_vacation;
814                         u->first_vacation = u->first_vacation->next;
815                         free(vptr);
816                 }
817                 sprintf(&text[strlen(text)], CTDLSIEVECONFIGSEPARATOR);
818         }
819
820         if (yes_write_to_disk)
821         {
822                 /* Save the config */
823                 quickie_message("Citadel", NULL, NULL, u->config_roomname,
824                                 text,
825                                 4,
826                                 "Sieve configuration"
827                 );
828                 
829                 /* And delete the old one */
830                 if (u->config_msgnum > 0) {
831                         CtdlDeleteMessages(u->config_roomname, &u->config_msgnum, 1, "");
832                 }
833         }
834
835         free (text);
836
837 }
838
839
840 /*
841  * This is our callback registration table for libSieve.
842  */
843 sieve2_callback_t ctdl_sieve_callbacks[] = {
844         { SIEVE2_ACTION_REJECT,         ctdl_reject             },
845         { SIEVE2_ACTION_VACATION,       ctdl_vacation           },
846         { SIEVE2_ERRCALL_PARSE,         ctdl_errparse           },
847         { SIEVE2_ERRCALL_RUNTIME,       ctdl_errexec            },
848         { SIEVE2_ACTION_FILEINTO,       ctdl_fileinto           },
849         { SIEVE2_ACTION_REDIRECT,       ctdl_redirect           },
850         { SIEVE2_ACTION_DISCARD,        ctdl_discard            },
851         { SIEVE2_ACTION_KEEP,           ctdl_keep               },
852         { SIEVE2_SCRIPT_GETSCRIPT,      ctdl_getscript          },
853         { SIEVE2_DEBUG_TRACE,           ctdl_debug              },
854         { SIEVE2_MESSAGE_GETALLHEADERS, ctdl_getheaders         },
855         { SIEVE2_MESSAGE_GETSIZE,       ctdl_getsize            },
856         { SIEVE2_MESSAGE_GETENVELOPE,   ctdl_getenvelope        },
857 /*
858  * These actions are unsupported by Citadel so we don't declare them.
859  *
860         { SIEVE2_ACTION_NOTIFY,         ctdl_notify             },
861         { SIEVE2_MESSAGE_GETSUBADDRESS, ctdl_getsubaddress      },
862         { SIEVE2_MESSAGE_GETBODY,       ctdl_getbody            },
863  *
864  */
865         { 0 }
866 };
867
868
869 /*
870  * Perform sieve processing for a single room
871  */
872 void sieve_do_room(char *roomname) {
873         
874         struct sdm_userdata u;
875         sieve2_context_t *sieve2_context = NULL;        /* Context for sieve parser */
876         int res;                                        /* Return code from libsieve calls */
877         long orig_lastproc = 0;
878
879         memset(&u, 0, sizeof u);
880
881         /* See if the user who owns this 'mailbox' has any Sieve scripts that
882          * require execution.
883          */
884         snprintf(u.config_roomname, sizeof u.config_roomname, "%010ld.%s", atol(roomname), USERCONFIGROOM);
885         if (CtdlGetRoom(&CC->room, u.config_roomname) != 0) {
886                 CtdlLogPrintf(CTDL_DEBUG, "<%s> does not exist.  No processing is required.\n", u.config_roomname);
887                 return;
888         }
889
890         /*
891          * Find the sieve scripts and control record and do something
892          */
893         u.config_msgnum = (-1);
894         CtdlForEachMessage(MSGS_LAST, 1, NULL, SIEVECONFIG, NULL,
895                 get_sieve_config_backend, (void *)&u );
896
897         if (u.config_msgnum < 0) {
898                 CtdlLogPrintf(CTDL_DEBUG, "No Sieve rules exist.  No processing is required.\n");
899                 return;
900         }
901
902         CtdlLogPrintf(CTDL_DEBUG, "Rules found.  Performing Sieve processing for <%s>\n", roomname);
903
904         if (CtdlGetRoom(&CC->room, roomname) != 0) {
905                 CtdlLogPrintf(CTDL_CRIT, "ERROR: cannot load <%s>\n", roomname);
906                 return;
907         }
908
909         /* Initialize the Sieve parser */
910         
911         res = sieve2_alloc(&sieve2_context);
912         if (res != SIEVE2_OK) {
913                 CtdlLogPrintf(CTDL_CRIT, "sieve2_alloc() returned %d: %s\n", res, sieve2_errstr(res));
914                 return;
915         }
916
917         res = sieve2_callbacks(sieve2_context, ctdl_sieve_callbacks);
918         if (res != SIEVE2_OK) {
919                 CtdlLogPrintf(CTDL_CRIT, "sieve2_callbacks() returned %d: %s\n", 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                 CtdlLogPrintf(CTDL_CRIT, "sieve2_validate() returned %d: %s\n", 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                 CtdlLogPrintf(CTDL_CRIT, "sieve2_free() returned %d: %s\n", 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                 CtdlLogPrintf(CTDL_DEBUG, "Begin Sieve processing\n");
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("000", config.c_maxmsglen, NULL, 0, 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         CtdlLogPrintf(CTDL_INFO, "%s\n",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                 CtdlLogPrintf(CTDL_CRIT, "sieve2_alloc() returned %d: %s\n", res, sieve2_errstr(res));
1286                 return;
1287         }
1288
1289         res = sieve2_callbacks(sieve2_context, ctdl_sieve_callbacks);
1290         if (res != SIEVE2_OK) {
1291                 CtdlLogPrintf(CTDL_CRIT, "sieve2_callbacks() returned %d: %s\n", res, sieve2_errstr(res));
1292                 goto BAIL;
1293         }
1294
1295         msiv_extensions = strdup(sieve2_listextensions(sieve2_context));
1296         CtdlLogPrintf(CTDL_INFO, "Extensions: %s\n", msiv_extensions);
1297
1298 BAIL:   res = sieve2_free(&sieve2_context);
1299         if (res != SIEVE2_OK) {
1300                 CtdlLogPrintf(CTDL_CRIT, "sieve2_free() returned %d: %s\n", res, sieve2_errstr(res));
1301         }
1302
1303 }
1304
1305 int serv_sieve_room(struct ctdlroom *room)
1306 {
1307         if (!strcasecmp(&room->QRname[11], MAILROOM)) {
1308                 sieve_queue_room(room);
1309         }
1310         return 0;
1311 }
1312
1313 CTDL_MODULE_INIT(sieve)
1314 {
1315         if (!threading)
1316         {
1317
1318                 ctdl_sieve_init();
1319                 CtdlRegisterProtoHook(cmd_msiv, "MSIV", "Manage Sieve scripts");
1320                 CtdlRegisterRoomHook(serv_sieve_room);
1321                 CtdlRegisterSessionHook(perform_sieve_processing, EVT_HOUSE);
1322         }
1323         
1324         /* return our Subversion id for the Log */
1325         return "$Id$";
1326 }
1327