5a80cba1918351ceff4848187446c76b811df008
[citadel.git] / citadel / serv_sieve.c
1 /*
2  * $Id: serv_sieve.c 3850 2005-09-13 14:00:24Z ajc $
3  *
4  * This module glues libSieve to the Citadel server in order to implement
5  * the Sieve mailbox filtering language (RFC 3028).
6  *
7  * This code is released under the terms of the GNU General Public License. 
8  */
9
10 #include "sysdep.h"
11 #include <stdlib.h>
12 #include <unistd.h>
13 #include <stdio.h>
14 #include <fcntl.h>
15 #include <signal.h>
16 #include <pwd.h>
17 #include <errno.h>
18 #include <sys/types.h>
19
20 #if TIME_WITH_SYS_TIME
21 # include <sys/time.h>
22 # include <time.h>
23 #else
24 # if HAVE_SYS_TIME_H
25 #  include <sys/time.h>
26 # else
27 #  include <time.h>
28 # endif
29 #endif
30
31 #include <sys/wait.h>
32 #include <string.h>
33 #include <limits.h>
34 #include "citadel.h"
35 #include "server.h"
36 #include "sysdep_decls.h"
37 #include "citserver.h"
38 #include "support.h"
39 #include "config.h"
40 #include "serv_extensions.h"
41 #include "room_ops.h"
42 #include "policy.h"
43 #include "database.h"
44 #include "msgbase.h"
45 #include "internet_addressing.h"
46 #include "tools.h"
47
48 #ifdef HAVE_LIBSIEVE
49
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  * Set ctdl_libsieve_debug=1 to see extremely verbose libSieve trace
59  */
60 int ctdl_debug(sieve2_context_t *s, void *my)
61 {
62         static int ctdl_libsieve_debug = 0;
63
64         if (ctdl_libsieve_debug) {
65 /*
66                 lprintf(CTDL_DEBUG, "Sieve: level [%d] module [%s] file [%s] function [%s]\n",
67                         sieve2_getvalue_int(s, "level"),
68                         sieve2_getvalue_string(s, "module"),
69                         sieve2_getvalue_string(s, "file"),
70                         sieve2_getvalue_string(s, "function"));
71  */
72                 lprintf(CTDL_DEBUG, "Sieve: %s\n",
73                         sieve2_getvalue_string(s, "message"));
74         }
75         return SIEVE2_OK;
76 }
77
78
79 /*
80  * Callback function to log script parsing errors
81  */
82 int ctdl_errparse(sieve2_context_t *s, void *my)
83 {
84         lprintf(CTDL_WARNING, "Error in script, line %d: %s\n",
85                 sieve2_getvalue_int(s, "lineno"),
86                 sieve2_getvalue_string(s, "message")
87         );
88         return SIEVE2_OK;
89 }
90
91
92 /*
93  * Callback function to log script execution errors
94  */
95 int ctdl_errexec(sieve2_context_t *s, void *my)
96 {
97         lprintf(CTDL_WARNING, "Error executing script: %s\n",
98                 sieve2_getvalue_string(s, "message")
99         );
100         return SIEVE2_OK;
101 }
102
103
104 /*
105  * Callback function to redirect a message to a different folder
106  */
107 int ctdl_redirect(sieve2_context_t *s, void *my)
108 {
109         struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
110         struct CtdlMessage *msg = NULL;
111         struct recptypes *valid = NULL;
112         char recp[256];
113
114         safestrncpy(recp, sieve2_getvalue_string(s, "address"), sizeof recp);
115
116         lprintf(CTDL_DEBUG, "Action is REDIRECT, recipient <%s>\n", recp);
117
118         valid = validate_recipients(recp);
119         if (valid == NULL) {
120                 lprintf(CTDL_WARNING, "REDIRECT failed: bad recipient <%s>\n", recp);
121                 return SIEVE2_ERROR_BADARGS;
122         }
123         if (valid->num_error > 0) {
124                 lprintf(CTDL_WARNING, "REDIRECT failed: bad recipient <%s>\n", recp);
125                 free(valid);
126                 return SIEVE2_ERROR_BADARGS;
127         }
128
129         msg = CtdlFetchMessage(cs->msgnum, 1);
130         if (msg == NULL) {
131                 lprintf(CTDL_WARNING, "REDIRECT failed: unable to fetch msg %ld\n", cs->msgnum);
132                 free(valid);
133                 return SIEVE2_ERROR_BADARGS;
134         }
135
136         CtdlSubmitMsg(msg, valid, NULL);
137         cs->cancel_implicit_keep = 1;
138         free(valid);
139         CtdlFreeMessage(msg);
140         return SIEVE2_OK;
141 }
142
143
144 /*
145  * Callback function to indicate that a message *will* be kept in the inbox
146  */
147 int ctdl_keep(sieve2_context_t *s, void *my)
148 {
149         struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
150         
151         lprintf(CTDL_DEBUG, "Action is KEEP\n");
152
153         cs->keep = 1;
154         cs->cancel_implicit_keep = 1;
155         return SIEVE2_OK;
156 }
157
158
159 /*
160  * Callback function to file a message into a different mailbox
161  */
162 int ctdl_fileinto(sieve2_context_t *s, void *my)
163 {
164         struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
165         const char *dest_folder = sieve2_getvalue_string(s, "mailbox");
166         int c;
167         char foldername[256];
168         char original_room_name[ROOMNAMELEN];
169
170         lprintf(CTDL_DEBUG, "Action is FILEINTO, destination is <%s>\n", dest_folder);
171
172         /* FILEINTO 'INBOX' is the same thing as KEEP */
173         if ( (!strcasecmp(dest_folder, "INBOX")) || (!strcasecmp(dest_folder, MAILROOM)) ) {
174                 cs->keep = 1;
175                 cs->cancel_implicit_keep = 1;
176                 return SIEVE2_OK;
177         }
178
179         /* Remember what room we came from */
180         safestrncpy(original_room_name, CC->room.QRname, sizeof original_room_name);
181
182         /* First try a mailbox name match (check personal mail folders first) */
183         snprintf(foldername, sizeof foldername, "%010ld.%s", cs->usernum, dest_folder);
184         c = getroom(&CC->room, foldername);
185
186         /* Then a regular room name match (public and private rooms) */
187         if (c < 0) {
188                 safestrncpy(foldername, dest_folder, sizeof foldername);
189                 c = getroom(&CC->room, foldername);
190         }
191
192         if (c < 0) {
193                 lprintf(CTDL_WARNING, "FILEINTO failed: target <%s> does not exist\n", dest_folder);
194                 return SIEVE2_ERROR_BADARGS;
195         }
196
197         /* Yes, we actually have to go there */
198         usergoto(NULL, 0, 0, NULL, NULL);
199
200         c = CtdlSaveMsgPointersInRoom(NULL, &cs->msgnum, 1, 0, NULL);
201
202         /* Go back to the room we came from */
203         if (strcasecmp(original_room_name, CC->room.QRname)) {
204                 usergoto(original_room_name, 0, 0, NULL, NULL);
205         }
206
207         if (c == 0) {
208                 cs->cancel_implicit_keep = 1;
209                 return SIEVE2_OK;
210         }
211         else {
212                 return SIEVE2_ERROR_BADARGS;
213         }
214 }
215
216
217 /*
218  * Callback function to indicate that a message should be discarded.
219  */
220 int ctdl_discard(sieve2_context_t *s, void *my)
221 {
222         struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
223
224         lprintf(CTDL_DEBUG, "Action is DISCARD\n");
225
226         /* Cancel the implicit keep.  That's all there is to it. */
227         cs->cancel_implicit_keep = 1;
228         return SIEVE2_OK;
229 }
230
231
232
233 /*
234  * Callback function to indicate that a message should be rejected
235  */
236 int ctdl_reject(sieve2_context_t *s, void *my)
237 {
238         struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
239         char *reject_text = NULL;
240
241         lprintf(CTDL_DEBUG, "Action is REJECT\n");
242
243         /* If we don't know who sent the message, do a DISCARD instead. */
244         if (strlen(cs->sender) == 0) {
245                 lprintf(CTDL_INFO, "Unknown sender.  Doing DISCARD instead of REJECT.\n");
246                 return ctdl_discard(s, my);
247         }
248
249         /* Assemble the reject message. */
250         reject_text = malloc(strlen(sieve2_getvalue_string(s, "message")) + 1024);
251         if (reject_text == NULL) {
252                 return SIEVE2_ERROR_FAIL;
253         }
254
255         sprintf(reject_text, 
256                 "Content-type: text/plain\n"
257                 "\n"
258                 "The message was refused by the recipient's mail filtering program.\n"
259                 "The reason given was as follows:\n"
260                 "\n"
261                 "%s\n"
262                 "\n"
263         ,
264                 sieve2_getvalue_string(s, "message")
265         );
266
267         quickie_message(        /* This delivers the message */
268                 "Citadel",      /* FIXME make it myself */
269                 cs->sender,
270                 NULL,
271                 reject_text,
272                 FMT_RFC822,
273                 "Delivery status notification"
274         );
275
276         free(reject_text);
277         cs->cancel_implicit_keep = 1;
278         return SIEVE2_OK;
279 }
280
281
282
283 /*
284  * Callback function to indicate that a vacation message should be generated
285  */
286 int ctdl_vacation(sieve2_context_t *s, void *my)
287 {
288         struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
289         struct sdm_vacation *vptr;
290         int days = 1;
291         const char *message;
292         char *vacamsg_text = NULL;
293         char vacamsg_subject[1024];
294
295         lprintf(CTDL_DEBUG, "Action is VACATION\n");
296
297         message = sieve2_getvalue_string(s, "message");
298         if (message == NULL) return SIEVE2_ERROR_BADARGS;
299
300         if (sieve2_getvalue_string(s, "subject") != NULL) {
301                 safestrncpy(vacamsg_subject, sieve2_getvalue_string(s, "subject"), sizeof vacamsg_subject);
302         }
303         else {
304                 snprintf(vacamsg_subject, sizeof vacamsg_subject, "Re: %s", cs->subject);
305         }
306
307         days = sieve2_getvalue_int(s, "days");
308         if (days < 1) days = 1;
309         if (days > MAX_VACATION) days = MAX_VACATION;
310
311         /* Check to see whether we've already alerted this sender that we're on vacation. */
312         for (vptr = cs->u->first_vacation; vptr != NULL; vptr = vptr->next) {
313                 if (!strcasecmp(vptr->fromaddr, cs->sender)) {
314                         if ( (time(NULL) - vptr->timestamp) < (days * 86400) ) {
315                                 lprintf(CTDL_DEBUG, "Already alerted <%s> recently.\n", cs->sender);
316                                 return SIEVE2_OK;
317                         }
318                 }
319         }
320
321         /* Assemble the reject message. */
322         vacamsg_text = malloc(strlen(message) + 1024);
323         if (vacamsg_text == NULL) {
324                 return SIEVE2_ERROR_FAIL;
325         }
326
327         sprintf(vacamsg_text, 
328                 "Content-type: text/plain\n"
329                 "\n"
330                 "%s\n"
331                 "\n"
332         ,
333                 message
334         );
335
336         quickie_message(        /* This delivers the message */
337                 "Citadel",      /* FIXME make it myself */
338                 cs->sender,
339                 NULL,
340                 vacamsg_text,
341                 FMT_RFC822,
342                 vacamsg_subject
343         );
344
345         free(vacamsg_text);
346
347         /* Now update the list to reflect the fact that we've alerted this sender.
348          * If they're already in the list, just update the timestamp.
349          */
350         for (vptr = cs->u->first_vacation; vptr != NULL; vptr = vptr->next) {
351                 if (!strcasecmp(vptr->fromaddr, cs->sender)) {
352                         vptr->timestamp = time(NULL);
353                         return SIEVE2_OK;
354                 }
355         }
356
357         /* If we get to this point, create a new record.
358          */
359         vptr = malloc(sizeof(struct sdm_vacation));
360         vptr->timestamp = time(NULL);
361         safestrncpy(vptr->fromaddr, cs->sender, sizeof vptr->fromaddr);
362         vptr->next = cs->u->first_vacation;
363         cs->u->first_vacation = vptr;
364
365         return SIEVE2_OK;
366 }
367
368
369 /*
370  * Callback function to parse addresses per local system convention
371  * It is disabled because we don't support subaddresses.
372  */
373 #if 0
374 int ctdl_getsubaddress(sieve2_context_t *s, void *my)
375 {
376         struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
377
378         /* libSieve does not take ownership of the memory used here.  But, since we
379          * are just pointing to locations inside a struct which we are going to free
380          * later, we're ok.
381          */
382         sieve2_setvalue_string(s, "user", cs->recp_user);
383         sieve2_setvalue_string(s, "detail", "");
384         sieve2_setvalue_string(s, "localpart", cs->recp_user);
385         sieve2_setvalue_string(s, "domain", cs->recp_node);
386         return SIEVE2_OK;
387 }
388 #endif
389
390
391 /*
392  * Callback function to parse message envelope
393  */
394 int ctdl_getenvelope(sieve2_context_t *s, void *my)
395 {
396         struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
397
398         lprintf(CTDL_DEBUG, "Action is GETENVELOPE\n");
399         sieve2_setvalue_string(s, "to", cs->envelope_to);
400         sieve2_setvalue_string(s, "from", cs->envelope_from);
401         return SIEVE2_OK;
402 }
403
404
405 /*
406  * Callback function to fetch message body
407  * FIXME implement this
408  */
409 #if 0
410 int ctdl_getbody(sieve2_context_t *s, void *my)
411 {
412         return SIEVE2_ERROR_UNSUPPORTED;
413 }
414 #endif
415
416
417 /*
418  * Callback function to fetch message size
419  */
420 int ctdl_getsize(sieve2_context_t *s, void *my)
421 {
422         struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
423         struct MetaData smi;
424
425         GetMetaData(&smi, cs->msgnum);
426         
427         if (smi.meta_rfc822_length > 0L) {
428                 sieve2_setvalue_int(s, "size", (int)smi.meta_rfc822_length);
429                 return SIEVE2_OK;
430         }
431
432         return SIEVE2_ERROR_UNSUPPORTED;
433 }
434
435
436 /*
437  * Callback function to retrieve the sieve script
438  */
439 int ctdl_getscript(sieve2_context_t *s, void *my) {
440         struct sdm_script *sptr;
441         struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
442
443         for (sptr=cs->u->first_script; sptr!=NULL; sptr=sptr->next) {
444                 if (sptr->script_active > 0) {
445                         lprintf(CTDL_DEBUG, "ctdl_getscript() is using script '%s'\n", sptr->script_name);
446                         sieve2_setvalue_string(s, "script", sptr->script_content);
447                         return SIEVE2_OK;
448                 }
449         }
450                 
451         lprintf(CTDL_DEBUG, "ctdl_getscript() found no active script\n");
452         return SIEVE2_ERROR_GETSCRIPT;
453 }
454
455 /*
456  * Callback function to retrieve message headers
457  */
458 int ctdl_getheaders(sieve2_context_t *s, void *my) {
459
460         struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
461
462         lprintf(CTDL_DEBUG, "ctdl_getheaders() was called\n");
463
464         sieve2_setvalue_string(s, "allheaders", cs->rfc822headers);
465         return SIEVE2_OK;
466 }
467
468
469
470 /*
471  * Add a room to the list of those rooms which potentially require sieve processing
472  */
473 void sieve_queue_room(struct ctdlroom *which_room) {
474         struct RoomProcList *ptr;
475
476         ptr = (struct RoomProcList *) malloc(sizeof (struct RoomProcList));
477         if (ptr == NULL) return;
478
479         safestrncpy(ptr->name, which_room->QRname, sizeof ptr->name);
480         begin_critical_section(S_SIEVELIST);
481         ptr->next = sieve_list;
482         sieve_list = ptr;
483         end_critical_section(S_SIEVELIST);
484 }
485
486
487
488 /*
489  * Perform sieve processing for one message (called by sieve_do_room() for each message)
490  */
491 void sieve_do_msg(long msgnum, void *userdata) {
492         struct sdm_userdata *u = (struct sdm_userdata *) userdata;
493         sieve2_context_t *sieve2_context = u->sieve2_context;
494         struct ctdl_sieve my;
495         int res;
496         struct CtdlMessage *msg;
497
498         lprintf(CTDL_DEBUG, "Performing sieve processing on msg <%ld>\n", msgnum);
499
500         msg = CtdlFetchMessage(msgnum, 0);
501         if (msg == NULL) return;
502
503         CC->redirect_buffer = malloc(SIZ);
504         CC->redirect_len = 0;
505         CC->redirect_alloc = SIZ;
506         CtdlOutputPreLoadedMsg(msg, MT_RFC822, HEADERS_ONLY, 0, 1);
507         my.rfc822headers = CC->redirect_buffer;
508         CC->redirect_buffer = NULL;
509         CC->redirect_len = 0;
510         CC->redirect_alloc = 0;
511
512         my.keep = 0;                            /* Set to 1 to declare an *explicit* keep */
513         my.cancel_implicit_keep = 0;            /* Some actions will cancel the implicit keep */
514         my.usernum = atol(CC->room.QRname);     /* Keep track of the owner of the room's namespace */
515         my.msgnum = msgnum;                     /* Keep track of the message number in our local store */
516         my.u = u;                               /* Hand off a pointer to the rest of this info */
517
518         /* Keep track of the recipient so we can do handling based on it later */
519         process_rfc822_addr(msg->cm_fields['R'], my.recp_user, my.recp_node, my.recp_name);
520
521         /* Keep track of the sender so we can use it for REJECT and VACATION responses */
522         if (msg->cm_fields['F'] != NULL) {
523                 safestrncpy(my.sender, msg->cm_fields['F'], sizeof my.sender);
524         }
525         else if ( (msg->cm_fields['A'] != NULL) && (msg->cm_fields['N'] != NULL) ) {
526                 snprintf(my.sender, sizeof my.sender, "%s@%s", msg->cm_fields['A'], msg->cm_fields['N']);
527         }
528         else if (msg->cm_fields['A'] != NULL) {
529                 safestrncpy(my.sender, msg->cm_fields['A'], sizeof my.sender);
530         }
531         else {
532                 strcpy(my.sender, "");
533         }
534
535         /* Keep track of the subject so we can use it for VACATION responses */
536         if (msg->cm_fields['U'] != NULL) {
537                 safestrncpy(my.subject, msg->cm_fields['U'], sizeof my.subject);
538         }
539         else {
540                 strcpy(my.subject, "");
541         }
542
543         /* Keep track of the envelope-from address (use body-from if not found) */
544         if (msg->cm_fields['P'] != NULL) {
545                 safestrncpy(my.envelope_from, msg->cm_fields['P'], sizeof my.envelope_from);
546         }
547         else if (msg->cm_fields['F'] != NULL) {
548                 safestrncpy(my.envelope_from, msg->cm_fields['F'], sizeof my.envelope_from);
549         }
550         else {
551                 strcpy(my.envelope_from, "");
552         }
553
554         /* Keep track of the envelope-to address */
555         if (msg->cm_fields['V'] != NULL) {
556                 safestrncpy(my.envelope_to, msg->cm_fields['V'], sizeof my.envelope_to);
557         }
558         else {
559                 strcpy(my.envelope_to, "");
560         }
561
562         free(msg);
563
564         sieve2_setvalue_string(sieve2_context, "allheaders", my.rfc822headers);
565         
566         lprintf(CTDL_DEBUG, "Calling sieve2_execute()\n");
567         res = sieve2_execute(sieve2_context, &my);
568         if (res != SIEVE2_OK) {
569                 lprintf(CTDL_CRIT, "sieve2_execute() returned %d: %s\n", res, sieve2_errstr(res));
570         }
571
572         free(my.rfc822headers);
573         my.rfc822headers = NULL;
574
575         /*
576          * Delete the message from the inbox unless either we were told not to, or
577          * if no other action was successfully taken.
578          */
579         if ( (!my.keep) && (my.cancel_implicit_keep) ) {
580                 lprintf(CTDL_DEBUG, "keep is 0 -- deleting message from inbox\n");
581                 CtdlDeleteMessages(CC->room.QRname, &msgnum, 1, "", 0);
582         }
583
584         lprintf(CTDL_DEBUG, "Completed sieve processing on msg <%ld>\n", msgnum);
585         u->lastproc = msgnum;
586
587         return;
588 }
589
590
591
592 /*
593  * Given the on-disk representation of our Sieve config, load
594  * it into an in-memory data structure.
595  */
596 void parse_sieve_config(char *conf, struct sdm_userdata *u) {
597         char *ptr;
598         char *c, *vacrec;
599         char keyword[256];
600         struct sdm_script *sptr;
601         struct sdm_vacation *vptr;
602
603         ptr = conf;
604         while (c = ptr, ptr = bmstrcasestr(ptr, CTDLSIEVECONFIGSEPARATOR), ptr != NULL) {
605                 *ptr = 0;
606                 ptr += strlen(CTDLSIEVECONFIGSEPARATOR);
607
608                 extract_token(keyword, c, 0, '|', sizeof keyword);
609
610                 if (!strcasecmp(keyword, "lastproc")) {
611                         u->lastproc = extract_long(c, 1);
612                 }
613
614                 else if (!strcasecmp(keyword, "script")) {
615                         sptr = malloc(sizeof(struct sdm_script));
616                         extract_token(sptr->script_name, c, 1, '|', sizeof sptr->script_name);
617                         sptr->script_active = extract_int(c, 2);
618                         remove_token(c, 0, '|');
619                         remove_token(c, 0, '|');
620                         remove_token(c, 0, '|');
621                         sptr->script_content = strdup(c);
622                         sptr->next = u->first_script;
623                         u->first_script = sptr;
624                 }
625
626                 else if (!strcasecmp(keyword, "vacation")) {
627
628                         if (c != NULL) while (vacrec=c, c=strchr(c, '\n'), (c != NULL)) {
629
630                                 *c = 0;
631                                 ++c;
632
633                                 if (strncasecmp(vacrec, "vacation|", 9)) {
634                                         vptr = malloc(sizeof(struct sdm_vacation));
635                                         extract_token(vptr->fromaddr, vacrec, 0, '|', sizeof vptr->fromaddr);
636                                         vptr->timestamp = extract_long(vacrec, 1);
637                                         vptr->next = u->first_vacation;
638                                         u->first_vacation = vptr;
639                                 }
640                         }
641                 }
642
643                 /* ignore unknown keywords */
644         }
645 }
646
647 /*
648  * We found the Sieve configuration for this user.
649  * Now do something with it.
650  */
651 void get_sieve_config_backend(long msgnum, void *userdata) {
652         struct sdm_userdata *u = (struct sdm_userdata *) userdata;
653         struct CtdlMessage *msg;
654         char *conf;
655
656         u->config_msgnum = msgnum;
657         msg = CtdlFetchMessage(msgnum, 1);
658         if (msg == NULL) {
659                 u->config_msgnum = (-1) ;
660                 return;
661         }
662
663         conf = msg->cm_fields['M'];
664         msg->cm_fields['M'] = NULL;
665         CtdlFreeMessage(msg);
666
667         if (conf != NULL) {
668                 parse_sieve_config(conf, u);
669                 free(conf);
670         }
671
672 }
673
674
675 /* 
676  * Write our citadel sieve config back to disk
677  */
678 void rewrite_ctdl_sieve_config(struct sdm_userdata *u) {
679         char *text;
680         struct sdm_script *sptr;
681         struct sdm_vacation *vptr;
682
683
684         text = malloc(1024);
685         snprintf(text, 1024,
686                 "Content-type: application/x-citadel-sieve-config\n"
687                 "\n"
688                 CTDLSIEVECONFIGSEPARATOR
689                 "lastproc|%ld"
690                 CTDLSIEVECONFIGSEPARATOR
691         ,
692                 u->lastproc
693         );
694
695         while (u->first_script != NULL) {
696                 text = realloc(text, strlen(text) + strlen(u->first_script->script_content) + 256);
697                 sprintf(&text[strlen(text)], "script|%s|%d|%s" CTDLSIEVECONFIGSEPARATOR,
698                         u->first_script->script_name,
699                         u->first_script->script_active,
700                         u->first_script->script_content
701                 );
702                 sptr = u->first_script;
703                 u->first_script = u->first_script->next;
704                 free(sptr->script_content);
705                 free(sptr);
706         }
707
708         if (u->first_vacation != NULL) {
709
710                 size_t realloc_len = strlen(text) + 256;
711                 for (vptr = u->first_vacation; vptr != NULL; vptr = vptr->next) {
712                         realloc_len += strlen(vptr->fromaddr + 32);
713                 }
714                 text = realloc(text, realloc_len);
715
716                 sprintf(&text[strlen(text)], "vacation|\n");
717                 while (u->first_vacation != NULL) {
718                         if ( (time(NULL) - u->first_vacation->timestamp) < (MAX_VACATION * 86400)) {
719                                 sprintf(&text[strlen(text)], "%s|%ld\n",
720                                         u->first_vacation->fromaddr,
721                                         u->first_vacation->timestamp
722                                 );
723                         }
724                         vptr = u->first_vacation;
725                         u->first_vacation = u->first_vacation->next;
726                         free(vptr);
727                 }
728                 sprintf(&text[strlen(text)], CTDLSIEVECONFIGSEPARATOR);
729         }
730
731         /* Save the config */
732         quickie_message("Citadel", NULL, u->config_roomname,
733                         text,
734                         4,
735                         "Sieve configuration"
736         );
737
738         /* And delete the old one */
739         if (u->config_msgnum > 0) {
740                 CtdlDeleteMessages(u->config_roomname, &u->config_msgnum, 1, "", 0);
741         }
742
743 }
744
745
746 /*
747  * This is our callback registration table for libSieve.
748  */
749 sieve2_callback_t ctdl_sieve_callbacks[] = {
750         { SIEVE2_ACTION_REJECT,         ctdl_reject             },
751         { SIEVE2_ACTION_VACATION,       ctdl_vacation           },
752         { SIEVE2_ERRCALL_PARSE,         ctdl_errparse           },
753         { SIEVE2_ERRCALL_RUNTIME,       ctdl_errexec            },
754         { SIEVE2_ACTION_FILEINTO,       ctdl_fileinto           },
755         { SIEVE2_ACTION_REDIRECT,       ctdl_redirect           },
756         { SIEVE2_ACTION_DISCARD,        ctdl_discard            },
757         { SIEVE2_ACTION_KEEP,           ctdl_keep               },
758         { SIEVE2_SCRIPT_GETSCRIPT,      ctdl_getscript          },
759         { SIEVE2_DEBUG_TRACE,           ctdl_debug              },
760         { SIEVE2_MESSAGE_GETALLHEADERS, ctdl_getheaders         },
761         { SIEVE2_MESSAGE_GETSIZE,       ctdl_getsize            },
762         { SIEVE2_MESSAGE_GETENVELOPE,   ctdl_getenvelope        },
763 /*
764  * These actions are unsupported by Citadel so we don't declare them.
765  *
766         { SIEVE2_ACTION_NOTIFY,         ctdl_notify             },
767         { SIEVE2_MESSAGE_GETSUBADDRESS, ctdl_getsubaddress      },
768         { SIEVE2_MESSAGE_GETBODY,       ctdl_getbody            },
769  *
770  */
771         { 0 }
772 };
773
774
775 /*
776  * Perform sieve processing for a single room
777  */
778 void sieve_do_room(char *roomname) {
779         
780         struct sdm_userdata u;
781         sieve2_context_t *sieve2_context = NULL;        /* Context for sieve parser */
782         int res;                                        /* Return code from libsieve calls */
783         long orig_lastproc = 0;
784
785         memset(&u, 0, sizeof u);
786
787         /* See if the user who owns this 'mailbox' has any Sieve scripts that
788          * require execution.
789          */
790         snprintf(u.config_roomname, sizeof u.config_roomname, "%010ld.%s", atol(roomname), USERCONFIGROOM);
791         if (getroom(&CC->room, u.config_roomname) != 0) {
792                 lprintf(CTDL_DEBUG, "<%s> does not exist.  No processing is required.\n", u.config_roomname);
793                 return;
794         }
795
796         /*
797          * Find the sieve scripts and control record and do something
798          */
799         u.config_msgnum = (-1);
800         CtdlForEachMessage(MSGS_LAST, 1, NULL, SIEVECONFIG, NULL,
801                 get_sieve_config_backend, (void *)&u );
802
803         if (u.config_msgnum < 0) {
804                 lprintf(CTDL_DEBUG, "No Sieve rules exist.  No processing is required.\n");
805                 return;
806         }
807
808         lprintf(CTDL_DEBUG, "Rules found.  Performing Sieve processing for <%s>\n", roomname);
809
810         if (getroom(&CC->room, roomname) != 0) {
811                 lprintf(CTDL_CRIT, "ERROR: cannot load <%s>\n", roomname);
812                 return;
813         }
814
815         /* Initialize the Sieve parser */
816         
817         res = sieve2_alloc(&sieve2_context);
818         if (res != SIEVE2_OK) {
819                 lprintf(CTDL_CRIT, "sieve2_alloc() returned %d: %s\n", res, sieve2_errstr(res));
820                 return;
821         }
822
823         res = sieve2_callbacks(sieve2_context, ctdl_sieve_callbacks);
824         if (res != SIEVE2_OK) {
825                 lprintf(CTDL_CRIT, "sieve2_callbacks() returned %d: %s\n", res, sieve2_errstr(res));
826                 goto BAIL;
827         }
828
829         /* Validate the script */
830
831         struct ctdl_sieve my;           /* dummy ctdl_sieve struct just to pass "u" slong */
832         memset(&my, 0, sizeof my);
833         my.u = &u;
834         res = sieve2_validate(sieve2_context, &my);
835         if (res != SIEVE2_OK) {
836                 lprintf(CTDL_CRIT, "sieve2_validate() returned %d: %s\n", res, sieve2_errstr(res));
837                 goto BAIL;
838         }
839
840         /* Do something useful */
841         u.sieve2_context = sieve2_context;
842         orig_lastproc = u.lastproc;
843         CtdlForEachMessage(MSGS_GT, u.lastproc, NULL, NULL, NULL,
844                 sieve_do_msg,
845                 (void *) &u
846         );
847
848 BAIL:
849         res = sieve2_free(&sieve2_context);
850         if (res != SIEVE2_OK) {
851                 lprintf(CTDL_CRIT, "sieve2_free() returned %d: %s\n", res, sieve2_errstr(res));
852         }
853
854         /* Rewrite the config if we have to */
855         if (u.lastproc > orig_lastproc) {
856                 rewrite_ctdl_sieve_config(&u);
857         }
858 }
859
860
861 /*
862  * Perform sieve processing for all rooms which require it
863  */
864 void perform_sieve_processing(void) {
865         struct RoomProcList *ptr = NULL;
866
867         if (sieve_list != NULL) {
868                 lprintf(CTDL_DEBUG, "Begin Sieve processing\n");
869                 while (sieve_list != NULL) {
870                         char spoolroomname[ROOMNAMELEN];
871                         safestrncpy(spoolroomname, sieve_list->name, sizeof spoolroomname);
872                         begin_critical_section(S_SIEVELIST);
873
874                         /* pop this record off the list */
875                         ptr = sieve_list;
876                         sieve_list = sieve_list->next;
877                         free(ptr);
878
879                         /* invalidate any duplicate entries to prevent double processing */
880                         for (ptr=sieve_list; ptr!=NULL; ptr=ptr->next) {
881                                 if (!strcasecmp(ptr->name, spoolroomname)) {
882                                         ptr->name[0] = 0;
883                                 }
884                         }
885
886                         end_critical_section(S_SIEVELIST);
887                         if (spoolroomname[0] != 0) {
888                                 sieve_do_room(spoolroomname);
889                         }
890                 }
891         }
892 }
893
894
895 void msiv_load(struct sdm_userdata *u) {
896         char hold_rm[ROOMNAMELEN];
897
898         strcpy(hold_rm, CC->room.QRname);       /* save current room */
899
900         /* Take a spin through the user's personal address book */
901         if (getroom(&CC->room, USERCONFIGROOM) == 0) {
902         
903                 u->config_msgnum = (-1);
904                 strcpy(u->config_roomname, CC->room.QRname);
905                 CtdlForEachMessage(MSGS_LAST, 1, NULL, SIEVECONFIG, NULL,
906                         get_sieve_config_backend, (void *)u );
907
908         }
909
910         if (strcmp(CC->room.QRname, hold_rm)) {
911                 getroom(&CC->room, hold_rm);    /* return to saved room */
912         }
913 }
914
915 void msiv_store(struct sdm_userdata *u) {
916         rewrite_ctdl_sieve_config(u);
917 }
918
919
920 /*
921  * Select the active script.
922  * (Set script_name to an empty string to disable all scripts)
923  * 
924  * Returns 0 on success or nonzero for error.
925  */
926 int msiv_setactive(struct sdm_userdata *u, char *script_name) {
927         int ok = 0;
928         struct sdm_script *s;
929
930         /* First see if the supplied value is ok */
931
932         if (strlen(script_name) == 0) {
933                 ok = 1;
934         }
935         else {
936                 for (s=u->first_script; s!=NULL; s=s->next) {
937                         if (!strcasecmp(s->script_name, script_name)) {
938                                 ok = 1;
939                         }
940                 }
941         }
942
943         if (!ok) return(-1);
944
945         /* Now set the active script */
946         for (s=u->first_script; s!=NULL; s=s->next) {
947                 if (!strcasecmp(s->script_name, script_name)) {
948                         s->script_active = 1;
949                 }
950                 else {
951                         s->script_active = 0;
952                 }
953         }
954         
955         return(0);
956 }
957
958
959 /*
960  * Fetch a script by name.
961  *
962  * Returns NULL if the named script was not found, or a pointer to the script
963  * if it was found.   NOTE: the caller does *not* own the memory returned by
964  * this function.  Copy it if you need to keep it.
965  */
966 char *msiv_getscript(struct sdm_userdata *u, char *script_name) {
967         struct sdm_script *s;
968
969         for (s=u->first_script; s!=NULL; s=s->next) {
970                 if (!strcasecmp(s->script_name, script_name)) {
971                         if (s->script_content != NULL) {
972                                 return (s->script_content);
973                         }
974                 }
975         }
976
977         return(NULL);
978 }
979
980
981 /*
982  * Delete a script by name.
983  *
984  * Returns 0 if the script was deleted.
985  *       1 if the script was not found.
986  *       2 if the script cannot be deleted because it is active.
987  */
988 int msiv_deletescript(struct sdm_userdata *u, char *script_name) {
989         struct sdm_script *s = NULL;
990         struct sdm_script *script_to_delete = NULL;
991
992         for (s=u->first_script; s!=NULL; s=s->next) {
993                 if (!strcasecmp(s->script_name, script_name)) {
994                         script_to_delete = s;
995                         if (s->script_active) {
996                                 return(2);
997                         }
998                 }
999         }
1000
1001         if (script_to_delete == NULL) return(1);
1002
1003         if (u->first_script == script_to_delete) {
1004                 u->first_script = u->first_script->next;
1005         }
1006         else for (s=u->first_script; s!=NULL; s=s->next) {
1007                 if (s->next == script_to_delete) {
1008                         s->next = s->next->next;
1009                 }
1010         }
1011
1012         free(script_to_delete->script_content);
1013         free(script_to_delete);
1014         return(0);
1015 }
1016
1017
1018 /*
1019  * Add or replace a new script.  
1020  * NOTE: after this function returns, "u" owns the memory that "script_content"
1021  * was pointing to.
1022  */
1023 void msiv_putscript(struct sdm_userdata *u, char *script_name, char *script_content) {
1024         int replaced = 0;
1025         struct sdm_script *s, *sptr;
1026
1027         for (s=u->first_script; s!=NULL; s=s->next) {
1028                 if (!strcasecmp(s->script_name, script_name)) {
1029                         if (s->script_content != NULL) {
1030                                 free(s->script_content);
1031                         }
1032                         s->script_content = script_content;
1033                         replaced = 1;
1034                 }
1035         }
1036
1037         if (replaced == 0) {
1038                 sptr = malloc(sizeof(struct sdm_script));
1039                 safestrncpy(sptr->script_name, script_name, sizeof sptr->script_name);
1040                 sptr->script_content = script_content;
1041                 sptr->script_active = 0;
1042                 sptr->next = u->first_script;
1043                 u->first_script = sptr;
1044         }
1045 }
1046
1047
1048
1049 /*
1050  * Citadel protocol to manage sieve scripts.
1051  * This is basically a simplified (read: doesn't resemble IMAP) version
1052  * of the 'managesieve' protocol.
1053  */
1054 void cmd_msiv(char *argbuf) {
1055         char subcmd[256];
1056         struct sdm_userdata u;
1057         char script_name[256];
1058         char *script_content = NULL;
1059         struct sdm_script *s;
1060         int i;
1061
1062         memset(&u, 0, sizeof(struct sdm_userdata));
1063
1064         if (CtdlAccessCheck(ac_logged_in)) return;
1065         extract_token(subcmd, argbuf, 0, '|', sizeof subcmd);
1066         msiv_load(&u);
1067
1068         if (!strcasecmp(subcmd, "putscript")) {
1069                 extract_token(script_name, argbuf, 1, '|', sizeof script_name);
1070                 if (strlen(script_name) > 0) {
1071                         cprintf("%d Transmit script now\n", SEND_LISTING);
1072                         script_content = CtdlReadMessageBody("000", config.c_maxmsglen, NULL, 0);
1073                         msiv_putscript(&u, script_name, script_content);
1074                 }
1075                 else {
1076                         cprintf("%d Invalid script name.\n", ERROR + ILLEGAL_VALUE);
1077                 }
1078         }       
1079         
1080         else if (!strcasecmp(subcmd, "listscripts")) {
1081                 cprintf("%d Scripts:\n", LISTING_FOLLOWS);
1082                 for (s=u.first_script; s!=NULL; s=s->next) {
1083                         if (s->script_content != NULL) {
1084                                 cprintf("%s|%d|\n", s->script_name, s->script_active);
1085                         }
1086                 }
1087                 cprintf("000\n");
1088         }
1089
1090         else if (!strcasecmp(subcmd, "setactive")) {
1091                 extract_token(script_name, argbuf, 1, '|', sizeof script_name);
1092                 if (msiv_setactive(&u, script_name) == 0) {
1093                         cprintf("%d ok\n", CIT_OK);
1094                 }
1095                 else {
1096                         cprintf("%d Script '%s' does not exist.\n",
1097                                 ERROR + ILLEGAL_VALUE,
1098                                 script_name
1099                         );
1100                 }
1101         }
1102
1103         else if (!strcasecmp(subcmd, "getscript")) {
1104                 extract_token(script_name, argbuf, 1, '|', sizeof script_name);
1105                 script_content = msiv_getscript(&u, script_name);
1106                 if (script_content != NULL) {
1107                         cprintf("%d Script:\n", LISTING_FOLLOWS);
1108                         cprintf("%s000\n", script_content);
1109                 }
1110                 else {
1111                         cprintf("%d Invalid script name.\n", ERROR + ILLEGAL_VALUE);
1112                 }
1113         }
1114
1115         else if (!strcasecmp(subcmd, "deletescript")) {
1116                 extract_token(script_name, argbuf, 1, '|', sizeof script_name);
1117                 i = msiv_deletescript(&u, script_name);
1118                 if (i == 0) {
1119                         cprintf("%d ok\n", CIT_OK);
1120                 }
1121                 else if (i == 1) {
1122                         cprintf("%d Script '%s' does not exist.\n",
1123                                 ERROR + ILLEGAL_VALUE,
1124                                 script_name
1125                         );
1126                 }
1127                 else if (i == 2) {
1128                         cprintf("%d Script '%s' is active and cannot be deleted.\n",
1129                                 ERROR + ILLEGAL_VALUE,
1130                                 script_name
1131                         );
1132                 }
1133                 else {
1134                         cprintf("%d unknown error\n", ERROR);
1135                 }
1136         }
1137
1138         else {
1139                 cprintf("%d Invalid subcommand\n", ERROR + CMD_NOT_SUPPORTED);
1140         }
1141
1142         msiv_store(&u);
1143 }
1144
1145
1146
1147 void ctdl_sieve_init(void) {
1148         char *cred = NULL;
1149         sieve2_context_t *sieve2_context = NULL;
1150         int res;
1151
1152         /*
1153          *      We don't really care about dumping the entire credits to the log
1154          *      every time the server is initialized.  The documentation will suffice
1155          *      for that purpose.  We are making a call to sieve2_credits() in order
1156          *      to demonstrate that we have successfully linked in to libsieve.
1157          */
1158         cred = strdup(sieve2_credits());
1159         if (cred == NULL) return;
1160
1161         if (strlen(cred) > 60) {
1162                 strcpy(&cred[55], "...");
1163         }
1164
1165         lprintf(CTDL_INFO, "%s\n",cred);
1166         free(cred);
1167
1168         /* Briefly initialize a Sieve parser instance just so we can list the
1169          * extensions that are available.
1170          */
1171         res = sieve2_alloc(&sieve2_context);
1172         if (res != SIEVE2_OK) {
1173                 lprintf(CTDL_CRIT, "sieve2_alloc() returned %d: %s\n", res, sieve2_errstr(res));
1174                 return;
1175         }
1176
1177         res = sieve2_callbacks(sieve2_context, ctdl_sieve_callbacks);
1178         if (res != SIEVE2_OK) {
1179                 lprintf(CTDL_CRIT, "sieve2_callbacks() returned %d: %s\n", res, sieve2_errstr(res));
1180                 goto BAIL;
1181         }
1182
1183         msiv_extensions = strdup(sieve2_listextensions(sieve2_context));
1184         lprintf(CTDL_INFO, "Extensions: %s\n", msiv_extensions);
1185
1186 BAIL:   res = sieve2_free(&sieve2_context);
1187         if (res != SIEVE2_OK) {
1188                 lprintf(CTDL_CRIT, "sieve2_free() returned %d: %s\n", res, sieve2_errstr(res));
1189         }
1190
1191 }
1192
1193
1194
1195 char *serv_sieve_init(void)
1196 {
1197         ctdl_sieve_init();
1198         CtdlRegisterProtoHook(cmd_msiv, "MSIV", "Manage Sieve scripts");
1199         return "$Id: serv_sieve.c 3850 2005-09-13 14:00:24Z ajc $";
1200 }
1201
1202 #else   /* HAVE_LIBSIEVE */
1203
1204 char *serv_sieve_init(void)
1205 {
1206         lprintf(CTDL_INFO, "This server is missing libsieve.  Mailbox filtering will be disabled.\n");
1207         return "$Id: serv_sieve.c 3850 2005-09-13 14:00:24Z ajc $";
1208 }
1209
1210 #endif  /* HAVE_LIBSIEVE */