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