Minor cleanup to remove extensions we aren't going
[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         /* Yes, this is really all there is to it.  Since we are not setting "keep" to 1,
225          * the message will be discarded because "some other action" was successfully taken.
226          */
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",
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  * FIXME implement this
286  */
287 int ctdl_vacation(sieve2_context_t *s, void *my)
288 {
289         lprintf(CTDL_DEBUG, "Action is VACATION\n");
290         return SIEVE2_ERROR_UNSUPPORTED;
291 }
292
293
294 /*
295  * Callback function to parse addresses per local system convention
296  * It is disabled because we don't support subaddresses.
297  */
298 #if 0
299 int ctdl_getsubaddress(sieve2_context_t *s, void *my)
300 {
301         struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
302
303         /* libSieve does not take ownership of the memory used here.  But, since we
304          * are just pointing to locations inside a struct which we are going to free
305          * later, we're ok.
306          */
307         sieve2_setvalue_string(s, "user", cs->recp_user);
308         sieve2_setvalue_string(s, "detail", "");
309         sieve2_setvalue_string(s, "localpart", cs->recp_user);
310         sieve2_setvalue_string(s, "domain", cs->recp_node);
311         return SIEVE2_OK;
312 }
313 #endif
314
315
316 /*
317  * Callback function to parse message envelope
318  */
319 #if 0
320 int ctdl_getenvelope(sieve2_context_t *s, void *my)
321 {
322         return SIEVE2_ERROR_UNSUPPORTED;
323 }
324 #endif
325
326
327 /*
328  * Callback function to fetch message body
329  * FIXME implement this
330  */
331 #if 0
332 int ctdl_getbody(sieve2_context_t *s, void *my)
333 {
334         return SIEVE2_ERROR_UNSUPPORTED;
335 }
336 #endif
337
338
339 /*
340  * Callback function to fetch message size
341  */
342 int ctdl_getsize(sieve2_context_t *s, void *my)
343 {
344         struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
345         struct MetaData smi;
346
347         GetMetaData(&smi, cs->msgnum);
348         
349         if (smi.meta_rfc822_length > 0L) {
350                 sieve2_setvalue_int(s, "size", (int)smi.meta_rfc822_length);
351                 return SIEVE2_OK;
352         }
353
354         return SIEVE2_ERROR_UNSUPPORTED;
355 }
356
357
358 /*
359  * Callback function to retrieve the sieve script
360  */
361 int ctdl_getscript(sieve2_context_t *s, void *my) {
362         struct sdm_script *sptr;
363         struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
364
365         for (sptr=cs->u->first_script; sptr!=NULL; sptr=sptr->next) {
366                 if (sptr->script_active > 0) {
367                         lprintf(CTDL_DEBUG, "ctdl_getscript() is using script '%s'\n", sptr->script_name);
368                         sieve2_setvalue_string(s, "script", sptr->script_content);
369                         return SIEVE2_OK;
370                 }
371         }
372                 
373         lprintf(CTDL_DEBUG, "ctdl_getscript() found no active script\n");
374         return SIEVE2_ERROR_GETSCRIPT;
375 }
376
377 /*
378  * Callback function to retrieve message headers
379  */
380 int ctdl_getheaders(sieve2_context_t *s, void *my) {
381
382         struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
383
384         lprintf(CTDL_DEBUG, "ctdl_getheaders() was called\n");
385
386         sieve2_setvalue_string(s, "allheaders", cs->rfc822headers);
387         return SIEVE2_OK;
388 }
389
390
391
392 /*
393  * Add a room to the list of those rooms which potentially require sieve processing
394  */
395 void sieve_queue_room(struct ctdlroom *which_room) {
396         struct RoomProcList *ptr;
397
398         ptr = (struct RoomProcList *) malloc(sizeof (struct RoomProcList));
399         if (ptr == NULL) return;
400
401         safestrncpy(ptr->name, which_room->QRname, sizeof ptr->name);
402         begin_critical_section(S_SIEVELIST);
403         ptr->next = sieve_list;
404         sieve_list = ptr;
405         end_critical_section(S_SIEVELIST);
406 }
407
408
409
410 /*
411  * Perform sieve processing for one message (called by sieve_do_room() for each message)
412  */
413 void sieve_do_msg(long msgnum, void *userdata) {
414         struct sdm_userdata *u = (struct sdm_userdata *) userdata;
415         sieve2_context_t *sieve2_context = u->sieve2_context;
416         struct ctdl_sieve my;
417         int res;
418         struct CtdlMessage *msg;
419
420         lprintf(CTDL_DEBUG, "Performing sieve processing on msg <%ld>\n", msgnum);
421
422         msg = CtdlFetchMessage(msgnum, 0);
423         if (msg == NULL) return;
424
425         CC->redirect_buffer = malloc(SIZ);
426         CC->redirect_len = 0;
427         CC->redirect_alloc = SIZ;
428         CtdlOutputPreLoadedMsg(msg, MT_RFC822, HEADERS_ONLY, 0, 1);
429         my.rfc822headers = CC->redirect_buffer;
430         CC->redirect_buffer = NULL;
431         CC->redirect_len = 0;
432         CC->redirect_alloc = 0;
433
434         my.keep = 0;                            /* Set to 1 to declare an *explicit* keep */
435         my.cancel_implicit_keep = 0;            /* Some actions will cancel the implicit keep */
436         my.usernum = atol(CC->room.QRname);     /* Keep track of the owner of the room's namespace */
437         my.msgnum = msgnum;                     /* Keep track of the message number in our local store */
438         my.u = u;                               /* Hand off a pointer to the rest of this info */
439
440         /* Keep track of the recipient so we can do handling based on it later */
441         process_rfc822_addr(msg->cm_fields['R'], my.recp_user, my.recp_node, my.recp_name);
442
443         /* Keep track of the sender so we can use it for REJECT and VACATION responses */
444         if (msg->cm_fields['F'] != NULL) {
445                 safestrncpy(my.sender, msg->cm_fields['F'], sizeof my.sender);
446         }
447         else if ( (msg->cm_fields['A'] != NULL) && (msg->cm_fields['N'] != NULL) ) {
448                 snprintf(my.sender, sizeof my.sender, "%s@%s", msg->cm_fields['A'], msg->cm_fields['N']);
449         }
450         else if (msg->cm_fields['A'] != NULL) {
451                 safestrncpy(my.sender, msg->cm_fields['A'], sizeof my.sender);
452         }
453         else {
454                 strcpy(my.sender, "");
455         }
456
457         free(msg);
458
459         sieve2_setvalue_string(sieve2_context, "allheaders", my.rfc822headers);
460         
461         lprintf(CTDL_DEBUG, "Calling sieve2_execute()\n");
462         res = sieve2_execute(sieve2_context, &my);
463         if (res != SIEVE2_OK) {
464                 lprintf(CTDL_CRIT, "sieve2_execute() returned %d: %s\n", res, sieve2_errstr(res));
465         }
466
467         free(my.rfc822headers);
468         my.rfc822headers = NULL;
469
470         /*
471          * Delete the message from the inbox unless either we were told not to, or
472          * if no other action was successfully taken.
473          */
474         if ( (!my.keep) && (my.cancel_implicit_keep) ) {
475                 lprintf(CTDL_DEBUG, "keep is 0 -- deleting message from inbox\n");
476                 CtdlDeleteMessages(CC->room.QRname, &msgnum, 1, "", 0);
477         }
478
479         lprintf(CTDL_DEBUG, "Completed sieve processing on msg <%ld>\n", msgnum);
480         u->lastproc = msgnum;
481
482         return;
483 }
484
485
486
487 /*
488  * Given the on-disk representation of our Sieve config, load
489  * it into an in-memory data structure.
490  */
491 void parse_sieve_config(char *conf, struct sdm_userdata *u) {
492         char *ptr;
493         char *c;
494         char keyword[256];
495         struct sdm_script *sptr;
496
497         ptr = conf;
498         while (c = ptr, ptr = bmstrcasestr(ptr, CTDLSIEVECONFIGSEPARATOR), ptr != NULL) {
499                 *ptr = 0;
500                 ptr += strlen(CTDLSIEVECONFIGSEPARATOR);
501
502                 extract_token(keyword, c, 0, '|', sizeof keyword);
503
504                 if (!strcasecmp(keyword, "lastproc")) {
505                         u->lastproc = extract_long(c, 1);
506                 }
507
508                 else if (!strcasecmp(keyword, "script")) {
509                         sptr = malloc(sizeof(struct sdm_script));
510                         extract_token(sptr->script_name, c, 1, '|', sizeof sptr->script_name);
511                         sptr->script_active = extract_int(c, 2);
512                         remove_token(c, 0, '|');
513                         remove_token(c, 0, '|');
514                         remove_token(c, 0, '|');
515                         sptr->script_content = strdup(c);
516                         sptr->next = u->first_script;
517                         u->first_script = sptr;
518                 }
519
520                 /* ignore unknown keywords */
521         }
522 }
523
524 /*
525  * We found the Sieve configuration for this user.
526  * Now do something with it.
527  */
528 void get_sieve_config_backend(long msgnum, void *userdata) {
529         struct sdm_userdata *u = (struct sdm_userdata *) userdata;
530         struct CtdlMessage *msg;
531         char *conf;
532
533         u->config_msgnum = msgnum;
534         msg = CtdlFetchMessage(msgnum, 1);
535         if (msg == NULL) {
536                 u->config_msgnum = (-1) ;
537                 return;
538         }
539
540         conf = msg->cm_fields['M'];
541         msg->cm_fields['M'] = NULL;
542         CtdlFreeMessage(msg);
543
544         if (conf != NULL) {
545                 parse_sieve_config(conf, u);
546                 free(conf);
547         }
548
549 }
550
551
552 /* 
553  * Write our citadel sieve config back to disk
554  */
555 void rewrite_ctdl_sieve_config(struct sdm_userdata *u) {
556         char *text;
557         struct sdm_script *sptr;
558
559
560         text = malloc(1024);
561         snprintf(text, 1024,
562                 "Content-type: application/x-citadel-sieve-config\n"
563                 "\n"
564                 CTDLSIEVECONFIGSEPARATOR
565                 "lastproc|%ld"
566                 CTDLSIEVECONFIGSEPARATOR
567         ,
568                 u->lastproc
569         );
570
571         while (u->first_script != NULL) {
572                 text = realloc(text, strlen(text) + strlen(u->first_script->script_content) + 256);
573                 sprintf(&text[strlen(text)], "script|%s|%d|%s" CTDLSIEVECONFIGSEPARATOR,
574                         u->first_script->script_name,
575                         u->first_script->script_active,
576                         u->first_script->script_content
577                 );
578                 sptr = u->first_script;
579                 u->first_script = u->first_script->next;
580                 free(sptr->script_content);
581                 free(sptr);
582         }
583
584         /* Save the config */
585         quickie_message("Citadel", NULL, u->config_roomname,
586                         text,
587                         4,
588                         "Sieve configuration"
589         );
590
591         /* And delete the old one */
592         if (u->config_msgnum > 0) {
593                 CtdlDeleteMessages(u->config_roomname, &u->config_msgnum, 1, "", 0);
594         }
595
596 }
597
598
599 /*
600  * This is our callback registration table for libSieve.
601  */
602 sieve2_callback_t ctdl_sieve_callbacks[] = {
603         { SIEVE2_ACTION_REJECT,         ctdl_reject             },
604         { SIEVE2_ACTION_VACATION,       ctdl_vacation           },
605         { SIEVE2_ERRCALL_PARSE,         ctdl_errparse           },
606         { SIEVE2_ERRCALL_RUNTIME,       ctdl_errexec            },
607         { SIEVE2_ACTION_FILEINTO,       ctdl_fileinto           },
608         { SIEVE2_ACTION_REDIRECT,       ctdl_redirect           },
609         { SIEVE2_ACTION_DISCARD,        ctdl_discard            },
610         { SIEVE2_ACTION_KEEP,           ctdl_keep               },
611         { SIEVE2_SCRIPT_GETSCRIPT,      ctdl_getscript          },
612         { SIEVE2_DEBUG_TRACE,           ctdl_debug              },
613         { SIEVE2_MESSAGE_GETALLHEADERS, ctdl_getheaders         },
614         { SIEVE2_MESSAGE_GETSIZE,       ctdl_getsize            },
615 /*
616  * These actions are unsupported by Citadel so we don't declare them.
617  *
618         { SIEVE2_ACTION_NOTIFY,         ctdl_notify             },
619         { SIEVE2_MESSAGE_GETSUBADDRESS, ctdl_getsubaddress      },
620         { SIEVE2_MESSAGE_GETENVELOPE,   ctdl_getenvelope        },
621         { SIEVE2_MESSAGE_GETBODY,       ctdl_getbody            },
622  *
623  */
624         { 0 }
625 };
626
627
628 /*
629  * Perform sieve processing for a single room
630  */
631 void sieve_do_room(char *roomname) {
632         
633         struct sdm_userdata u;
634         sieve2_context_t *sieve2_context = NULL;        /* Context for sieve parser */
635         int res;                                        /* Return code from libsieve calls */
636         long orig_lastproc = 0;
637
638         memset(&u, 0, sizeof u);
639
640         /* See if the user who owns this 'mailbox' has any Sieve scripts that
641          * require execution.
642          */
643         snprintf(u.config_roomname, sizeof u.config_roomname, "%010ld.%s", atol(roomname), SIEVERULES);
644         if (getroom(&CC->room, u.config_roomname) != 0) {
645                 lprintf(CTDL_DEBUG, "<%s> does not exist.  No processing is required.\n", u.config_roomname);
646                 return;
647         }
648
649         /*
650          * Find the sieve scripts and control record and do something
651          */
652         u.config_msgnum = (-1);
653         CtdlForEachMessage(MSGS_LAST, 1, NULL, SIEVECONFIG, NULL,
654                 get_sieve_config_backend, (void *)&u );
655
656         if (u.config_msgnum < 0) {
657                 lprintf(CTDL_DEBUG, "No Sieve rules exist.  No processing is required.\n");
658                 return;
659         }
660
661         lprintf(CTDL_DEBUG, "Rules found.  Performing Sieve processing for <%s>\n", roomname);
662
663         if (getroom(&CC->room, roomname) != 0) {
664                 lprintf(CTDL_CRIT, "ERROR: cannot load <%s>\n", roomname);
665                 return;
666         }
667
668         /* Initialize the Sieve parser */
669         
670         res = sieve2_alloc(&sieve2_context);
671         if (res != SIEVE2_OK) {
672                 lprintf(CTDL_CRIT, "sieve2_alloc() returned %d: %s\n", res, sieve2_errstr(res));
673                 return;
674         }
675
676         res = sieve2_callbacks(sieve2_context, ctdl_sieve_callbacks);
677         if (res != SIEVE2_OK) {
678                 lprintf(CTDL_CRIT, "sieve2_callbacks() returned %d: %s\n", res, sieve2_errstr(res));
679                 goto BAIL;
680         }
681
682         /* Validate the script */
683
684         struct ctdl_sieve my;           /* dummy ctdl_sieve struct just to pass "u" slong */
685         memset(&my, 0, sizeof my);
686         my.u = &u;
687         res = sieve2_validate(sieve2_context, &my);
688         if (res != SIEVE2_OK) {
689                 lprintf(CTDL_CRIT, "sieve2_validate() returned %d: %s\n", res, sieve2_errstr(res));
690                 goto BAIL;
691         }
692
693         /* Do something useful */
694         u.sieve2_context = sieve2_context;
695         orig_lastproc = u.lastproc;
696         CtdlForEachMessage(MSGS_GT, u.lastproc, NULL, NULL, NULL,
697                 sieve_do_msg,
698                 (void *) &u
699         );
700
701 BAIL:
702         res = sieve2_free(&sieve2_context);
703         if (res != SIEVE2_OK) {
704                 lprintf(CTDL_CRIT, "sieve2_free() returned %d: %s\n", res, sieve2_errstr(res));
705         }
706
707         /* Rewrite the config if we have to */
708         if (u.lastproc > orig_lastproc) {
709                 rewrite_ctdl_sieve_config(&u);
710         }
711 }
712
713
714 /*
715  * Perform sieve processing for all rooms which require it
716  */
717 void perform_sieve_processing(void) {
718         struct RoomProcList *ptr = NULL;
719
720         if (sieve_list != NULL) {
721                 lprintf(CTDL_DEBUG, "Begin Sieve processing\n");
722                 while (sieve_list != NULL) {
723                         char spoolroomname[ROOMNAMELEN];
724                         safestrncpy(spoolroomname, sieve_list->name, sizeof spoolroomname);
725                         begin_critical_section(S_SIEVELIST);
726
727                         /* pop this record off the list */
728                         ptr = sieve_list;
729                         sieve_list = sieve_list->next;
730                         free(ptr);
731
732                         /* invalidate any duplicate entries to prevent double processing */
733                         for (ptr=sieve_list; ptr!=NULL; ptr=ptr->next) {
734                                 if (!strcasecmp(ptr->name, spoolroomname)) {
735                                         ptr->name[0] = 0;
736                                 }
737                         }
738
739                         end_critical_section(S_SIEVELIST);
740                         if (spoolroomname[0] != 0) {
741                                 sieve_do_room(spoolroomname);
742                         }
743                 }
744         }
745 }
746
747
748 void msiv_load(struct sdm_userdata *u) {
749         char hold_rm[ROOMNAMELEN];
750
751         strcpy(hold_rm, CC->room.QRname);       /* save current room */
752
753         /* Take a spin through the user's personal address book */
754         if (getroom(&CC->room, SIEVERULES) == 0) {
755         
756                 u->config_msgnum = (-1);
757                 strcpy(u->config_roomname, CC->room.QRname);
758                 CtdlForEachMessage(MSGS_LAST, 1, NULL, SIEVECONFIG, NULL,
759                         get_sieve_config_backend, (void *)u );
760
761         }
762
763         if (strcmp(CC->room.QRname, hold_rm)) {
764                 getroom(&CC->room, hold_rm);    /* return to saved room */
765         }
766 }
767
768 void msiv_store(struct sdm_userdata *u) {
769         rewrite_ctdl_sieve_config(u);
770 }
771
772
773 /*
774  * Select the active script.
775  * (Set script_name to an empty string to disable all scripts)
776  * 
777  * Returns 0 on success or nonzero for error.
778  */
779 int msiv_setactive(struct sdm_userdata *u, char *script_name) {
780         int ok = 0;
781         struct sdm_script *s;
782
783         /* First see if the supplied value is ok */
784
785         if (strlen(script_name) == 0) {
786                 ok = 1;
787         }
788         else {
789                 for (s=u->first_script; s!=NULL; s=s->next) {
790                         if (!strcasecmp(s->script_name, script_name)) {
791                                 ok = 1;
792                         }
793                 }
794         }
795
796         if (!ok) return(-1);
797
798         /* Now set the active script */
799         for (s=u->first_script; s!=NULL; s=s->next) {
800                 if (!strcasecmp(s->script_name, script_name)) {
801                         s->script_active = 1;
802                 }
803                 else {
804                         s->script_active = 0;
805                 }
806         }
807         
808         return(0);
809 }
810
811
812 /*
813  * Fetch a script by name.
814  *
815  * Returns NULL if the named script was not found, or a pointer to the script
816  * if it was found.   NOTE: the caller does *not* own the memory returned by
817  * this function.  Copy it if you need to keep it.
818  */
819 char *msiv_getscript(struct sdm_userdata *u, char *script_name) {
820         struct sdm_script *s;
821
822         for (s=u->first_script; s!=NULL; s=s->next) {
823                 if (!strcasecmp(s->script_name, script_name)) {
824                         if (s->script_content != NULL) {
825                                 return (s->script_content);
826                         }
827                 }
828         }
829
830         return(NULL);
831 }
832
833
834 /*
835  * Delete a script by name.
836  *
837  * Returns 0 if the script was deleted.
838  *       1 if the script was not found.
839  *       2 if the script cannot be deleted because it is active.
840  */
841 int msiv_deletescript(struct sdm_userdata *u, char *script_name) {
842         struct sdm_script *s = NULL;
843         struct sdm_script *script_to_delete = NULL;
844
845         for (s=u->first_script; s!=NULL; s=s->next) {
846                 if (!strcasecmp(s->script_name, script_name)) {
847                         script_to_delete = s;
848                         if (s->script_active) {
849                                 return(2);
850                         }
851                 }
852         }
853
854         if (script_to_delete == NULL) return(1);
855
856         if (u->first_script == script_to_delete) {
857                 u->first_script = u->first_script->next;
858         }
859         else for (s=u->first_script; s!=NULL; s=s->next) {
860                 if (s->next == script_to_delete) {
861                         s->next = s->next->next;
862                 }
863         }
864
865         free(script_to_delete->script_content);
866         free(script_to_delete);
867         return(0);
868 }
869
870
871 /*
872  * Add or replace a new script.  
873  * NOTE: after this function returns, "u" owns the memory that "script_content"
874  * was pointing to.
875  */
876 void msiv_putscript(struct sdm_userdata *u, char *script_name, char *script_content) {
877         int replaced = 0;
878         struct sdm_script *s, *sptr;
879
880         for (s=u->first_script; s!=NULL; s=s->next) {
881                 if (!strcasecmp(s->script_name, script_name)) {
882                         if (s->script_content != NULL) {
883                                 free(s->script_content);
884                         }
885                         s->script_content = script_content;
886                         replaced = 1;
887                 }
888         }
889
890         if (replaced == 0) {
891                 sptr = malloc(sizeof(struct sdm_script));
892                 safestrncpy(sptr->script_name, script_name, sizeof sptr->script_name);
893                 sptr->script_content = script_content;
894                 sptr->script_active = 0;
895                 sptr->next = u->first_script;
896                 u->first_script = sptr;
897         }
898 }
899
900
901
902 /*
903  * Citadel protocol to manage sieve scripts.
904  * This is basically a simplified (read: doesn't resemble IMAP) version
905  * of the 'managesieve' protocol.
906  */
907 void cmd_msiv(char *argbuf) {
908         char subcmd[256];
909         struct sdm_userdata u;
910         char script_name[256];
911         char *script_content = NULL;
912         struct sdm_script *s;
913         int i;
914
915         memset(&u, 0, sizeof(struct sdm_userdata));
916
917         if (CtdlAccessCheck(ac_logged_in)) return;
918         extract_token(subcmd, argbuf, 0, '|', sizeof subcmd);
919         msiv_load(&u);
920
921         if (!strcasecmp(subcmd, "putscript")) {
922                 extract_token(script_name, argbuf, 1, '|', sizeof script_name);
923                 if (strlen(script_name) > 0) {
924                         cprintf("%d Transmit script now\n", SEND_LISTING);
925                         script_content = CtdlReadMessageBody("000", config.c_maxmsglen, NULL, 0);
926                         msiv_putscript(&u, script_name, script_content);
927                 }
928                 else {
929                         cprintf("%d Invalid script name.\n", ERROR + ILLEGAL_VALUE);
930                 }
931         }       
932         
933         else if (!strcasecmp(subcmd, "listscripts")) {
934                 cprintf("%d Scripts:\n", LISTING_FOLLOWS);
935                 for (s=u.first_script; s!=NULL; s=s->next) {
936                         if (s->script_content != NULL) {
937                                 cprintf("%s|%d|\n", s->script_name, s->script_active);
938                         }
939                 }
940                 cprintf("000\n");
941         }
942
943         else if (!strcasecmp(subcmd, "setactive")) {
944                 extract_token(script_name, argbuf, 1, '|', sizeof script_name);
945                 if (msiv_setactive(&u, script_name) == 0) {
946                         cprintf("%d ok\n", CIT_OK);
947                 }
948                 else {
949                         cprintf("%d Script '%s' does not exist.\n",
950                                 ERROR + ILLEGAL_VALUE,
951                                 script_name
952                         );
953                 }
954         }
955
956         else if (!strcasecmp(subcmd, "getscript")) {
957                 extract_token(script_name, argbuf, 1, '|', sizeof script_name);
958                 script_content = msiv_getscript(&u, script_name);
959                 if (script_content != NULL) {
960                         cprintf("%d Script:\n", SEND_LISTING);
961                         cprintf("%s000\n", script_content);
962                 }
963                 else {
964                         cprintf("%d Invalid script name.\n", ERROR + ILLEGAL_VALUE);
965                 }
966         }
967
968         else if (!strcasecmp(subcmd, "deletescript")) {
969                 extract_token(script_name, argbuf, 1, '|', sizeof script_name);
970                 i = msiv_deletescript(&u, script_name);
971                 if (i == 0) {
972                         cprintf("%d ok\n", CIT_OK);
973                 }
974                 else if (i == 1) {
975                         cprintf("%d Script '%s' does not exist.\n",
976                                 ERROR + ILLEGAL_VALUE,
977                                 script_name
978                         );
979                 }
980                 else if (i == 2) {
981                         cprintf("%d Script '%s' is active and cannot be deleted.\n",
982                                 ERROR + ILLEGAL_VALUE,
983                                 script_name
984                         );
985                 }
986                 else {
987                         cprintf("%d unknown error\n", ERROR);
988                 }
989         }
990
991         else {
992                 cprintf("%d Invalid subcommand\n", ERROR + CMD_NOT_SUPPORTED);
993         }
994
995         msiv_store(&u);
996 }
997
998
999
1000 void ctdl_sieve_init(void) {
1001         char *cred = NULL;
1002         sieve2_context_t *sieve2_context = NULL;
1003         int res;
1004
1005         /*
1006          *      We don't really care about dumping the entire credits to the log
1007          *      every time the server is initialized.  The documentation will suffice
1008          *      for that purpose.  We are making a call to sieve2_credits() in order
1009          *      to demonstrate that we have successfully linked in to libsieve.
1010          */
1011         cred = strdup(sieve2_credits());
1012         if (cred == NULL) return;
1013
1014         if (strlen(cred) > 60) {
1015                 strcpy(&cred[55], "...");
1016         }
1017
1018         lprintf(CTDL_INFO, "%s\n",cred);
1019         free(cred);
1020
1021         /* Briefly initialize a Sieve parser instance just so we can list the
1022          * extensions that are available.
1023          */
1024         res = sieve2_alloc(&sieve2_context);
1025         if (res != SIEVE2_OK) {
1026                 lprintf(CTDL_CRIT, "sieve2_alloc() returned %d: %s\n", res, sieve2_errstr(res));
1027                 return;
1028         }
1029
1030         res = sieve2_callbacks(sieve2_context, ctdl_sieve_callbacks);
1031         if (res != SIEVE2_OK) {
1032                 lprintf(CTDL_CRIT, "sieve2_callbacks() returned %d: %s\n", res, sieve2_errstr(res));
1033                 goto BAIL;
1034         }
1035
1036         msiv_extensions = strdup(sieve2_listextensions(sieve2_context));
1037         lprintf(CTDL_INFO, "Extensions: %s\n", msiv_extensions);
1038
1039 BAIL:   res = sieve2_free(&sieve2_context);
1040         if (res != SIEVE2_OK) {
1041                 lprintf(CTDL_CRIT, "sieve2_free() returned %d: %s\n", res, sieve2_errstr(res));
1042         }
1043
1044 }
1045
1046
1047
1048 char *serv_sieve_init(void)
1049 {
1050         ctdl_sieve_init();
1051         CtdlRegisterProtoHook(cmd_msiv, "MSIV", "Manage Sieve scripts");
1052         return "$Id: serv_sieve.c 3850 2005-09-13 14:00:24Z ajc $";
1053 }
1054
1055 #else   /* HAVE_LIBSIEVE */
1056
1057 char *serv_sieve_init(void)
1058 {
1059         lprintf(CTDL_INFO, "This server is missing libsieve.  Mailbox filtering will be disabled.\n");
1060         return "$Id: serv_sieve.c 3850 2005-09-13 14:00:24Z ajc $";
1061 }
1062
1063 #endif  /* HAVE_LIBSIEVE */