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