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