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