* Reference count adjustments are now deferred by queuing
[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(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(valid);
133                 return SIEVE2_ERROR_BADARGS;
134         }
135
136         CtdlSubmitMsg(msg, valid, NULL);
137         cs->cancel_implicit_keep = 1;
138         free(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         free(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
704
705         text = malloc(1024);
706         snprintf(text, 1024,
707                 "Content-type: application/x-citadel-sieve-config\n"
708                 "\n"
709                 CTDLSIEVECONFIGSEPARATOR
710                 "lastproc|%ld"
711                 CTDLSIEVECONFIGSEPARATOR
712         ,
713                 u->lastproc
714         );
715
716         while (u->first_script != NULL) {
717                 text = realloc(text, strlen(text) + strlen(u->first_script->script_content) + 256);
718                 sprintf(&text[strlen(text)], "script|%s|%d|%s" CTDLSIEVECONFIGSEPARATOR,
719                         u->first_script->script_name,
720                         u->first_script->script_active,
721                         u->first_script->script_content
722                 );
723                 sptr = u->first_script;
724                 u->first_script = u->first_script->next;
725                 free(sptr->script_content);
726                 free(sptr);
727         }
728
729         if (u->first_vacation != NULL) {
730
731                 size_t realloc_len = strlen(text) + 256;
732                 for (vptr = u->first_vacation; vptr != NULL; vptr = vptr->next) {
733                         realloc_len += strlen(vptr->fromaddr + 32);
734                 }
735                 text = realloc(text, realloc_len);
736
737                 sprintf(&text[strlen(text)], "vacation|\n");
738                 while (u->first_vacation != NULL) {
739                         if ( (time(NULL) - u->first_vacation->timestamp) < (MAX_VACATION * 86400)) {
740                                 sprintf(&text[strlen(text)], "%s|%ld\n",
741                                         u->first_vacation->fromaddr,
742                                         u->first_vacation->timestamp
743                                 );
744                         }
745                         vptr = u->first_vacation;
746                         u->first_vacation = u->first_vacation->next;
747                         free(vptr);
748                 }
749                 sprintf(&text[strlen(text)], CTDLSIEVECONFIGSEPARATOR);
750         }
751
752         /* Save the config */
753         quickie_message("Citadel", NULL, NULL, u->config_roomname,
754                         text,
755                         4,
756                         "Sieve configuration"
757         );
758
759         /* And delete the old one */
760         if (u->config_msgnum > 0) {
761                 CtdlDeleteMessages(u->config_roomname, &u->config_msgnum, 1, "");
762         }
763
764 }
765
766
767 /*
768  * This is our callback registration table for libSieve.
769  */
770 sieve2_callback_t ctdl_sieve_callbacks[] = {
771         { SIEVE2_ACTION_REJECT,         ctdl_reject             },
772         { SIEVE2_ACTION_VACATION,       ctdl_vacation           },
773         { SIEVE2_ERRCALL_PARSE,         ctdl_errparse           },
774         { SIEVE2_ERRCALL_RUNTIME,       ctdl_errexec            },
775         { SIEVE2_ACTION_FILEINTO,       ctdl_fileinto           },
776         { SIEVE2_ACTION_REDIRECT,       ctdl_redirect           },
777         { SIEVE2_ACTION_DISCARD,        ctdl_discard            },
778         { SIEVE2_ACTION_KEEP,           ctdl_keep               },
779         { SIEVE2_SCRIPT_GETSCRIPT,      ctdl_getscript          },
780         { SIEVE2_DEBUG_TRACE,           ctdl_debug              },
781         { SIEVE2_MESSAGE_GETALLHEADERS, ctdl_getheaders         },
782         { SIEVE2_MESSAGE_GETSIZE,       ctdl_getsize            },
783         { SIEVE2_MESSAGE_GETENVELOPE,   ctdl_getenvelope        },
784 /*
785  * These actions are unsupported by Citadel so we don't declare them.
786  *
787         { SIEVE2_ACTION_NOTIFY,         ctdl_notify             },
788         { SIEVE2_MESSAGE_GETSUBADDRESS, ctdl_getsubaddress      },
789         { SIEVE2_MESSAGE_GETBODY,       ctdl_getbody            },
790  *
791  */
792         { 0 }
793 };
794
795
796 /*
797  * Perform sieve processing for a single room
798  */
799 void sieve_do_room(char *roomname) {
800         
801         struct sdm_userdata u;
802         sieve2_context_t *sieve2_context = NULL;        /* Context for sieve parser */
803         int res;                                        /* Return code from libsieve calls */
804         long orig_lastproc = 0;
805
806         memset(&u, 0, sizeof u);
807
808         /* See if the user who owns this 'mailbox' has any Sieve scripts that
809          * require execution.
810          */
811         snprintf(u.config_roomname, sizeof u.config_roomname, "%010ld.%s", atol(roomname), USERCONFIGROOM);
812         if (getroom(&CC->room, u.config_roomname) != 0) {
813                 lprintf(CTDL_DEBUG, "<%s> does not exist.  No processing is required.\n", u.config_roomname);
814                 return;
815         }
816
817         /*
818          * Find the sieve scripts and control record and do something
819          */
820         u.config_msgnum = (-1);
821         CtdlForEachMessage(MSGS_LAST, 1, NULL, SIEVECONFIG, NULL,
822                 get_sieve_config_backend, (void *)&u );
823
824         if (u.config_msgnum < 0) {
825                 lprintf(CTDL_DEBUG, "No Sieve rules exist.  No processing is required.\n");
826                 return;
827         }
828
829         lprintf(CTDL_DEBUG, "Rules found.  Performing Sieve processing for <%s>\n", roomname);
830
831         if (getroom(&CC->room, roomname) != 0) {
832                 lprintf(CTDL_CRIT, "ERROR: cannot load <%s>\n", roomname);
833                 return;
834         }
835
836         /* Initialize the Sieve parser */
837         
838         res = sieve2_alloc(&sieve2_context);
839         if (res != SIEVE2_OK) {
840                 lprintf(CTDL_CRIT, "sieve2_alloc() returned %d: %s\n", res, sieve2_errstr(res));
841                 return;
842         }
843
844         res = sieve2_callbacks(sieve2_context, ctdl_sieve_callbacks);
845         if (res != SIEVE2_OK) {
846                 lprintf(CTDL_CRIT, "sieve2_callbacks() returned %d: %s\n", res, sieve2_errstr(res));
847                 goto BAIL;
848         }
849
850         /* Validate the script */
851
852         struct ctdl_sieve my;           /* dummy ctdl_sieve struct just to pass "u" slong */
853         memset(&my, 0, sizeof my);
854         my.u = &u;
855         res = sieve2_validate(sieve2_context, &my);
856         if (res != SIEVE2_OK) {
857                 lprintf(CTDL_CRIT, "sieve2_validate() returned %d: %s\n", res, sieve2_errstr(res));
858                 goto BAIL;
859         }
860
861         /* Do something useful */
862         u.sieve2_context = sieve2_context;
863         orig_lastproc = u.lastproc;
864         CtdlForEachMessage(MSGS_GT, u.lastproc, NULL, NULL, NULL,
865                 sieve_do_msg,
866                 (void *) &u
867         );
868
869 BAIL:
870         res = sieve2_free(&sieve2_context);
871         if (res != SIEVE2_OK) {
872                 lprintf(CTDL_CRIT, "sieve2_free() returned %d: %s\n", res, sieve2_errstr(res));
873         }
874
875         /* Rewrite the config if we have to */
876         rewrite_ctdl_sieve_config(&u, (u.lastproc > orig_lastproc) ) ;
877 }
878
879
880 /*
881  * Perform sieve processing for all rooms which require it
882  */
883 void perform_sieve_processing(void) {
884         struct RoomProcList *ptr = NULL;
885
886         if (sieve_list != NULL) {
887                 lprintf(CTDL_DEBUG, "Begin Sieve processing\n");
888                 while (sieve_list != NULL) {
889                         char spoolroomname[ROOMNAMELEN];
890                         safestrncpy(spoolroomname, sieve_list->name, sizeof spoolroomname);
891                         begin_critical_section(S_SIEVELIST);
892
893                         /* pop this record off the list */
894                         ptr = sieve_list;
895                         sieve_list = sieve_list->next;
896                         free(ptr);
897
898                         /* invalidate any duplicate entries to prevent double processing */
899                         for (ptr=sieve_list; ptr!=NULL; ptr=ptr->next) {
900                                 if (!strcasecmp(ptr->name, spoolroomname)) {
901                                         ptr->name[0] = 0;
902                                 }
903                         }
904
905                         end_critical_section(S_SIEVELIST);
906                         if (spoolroomname[0] != 0) {
907                                 sieve_do_room(spoolroomname);
908                         }
909                 }
910         }
911 }
912
913
914 void msiv_load(struct sdm_userdata *u) {
915         char hold_rm[ROOMNAMELEN];
916
917         strcpy(hold_rm, CC->room.QRname);       /* save current room */
918
919         /* Take a spin through the user's personal address book */
920         if (getroom(&CC->room, USERCONFIGROOM) == 0) {
921         
922                 u->config_msgnum = (-1);
923                 strcpy(u->config_roomname, CC->room.QRname);
924                 CtdlForEachMessage(MSGS_LAST, 1, NULL, SIEVECONFIG, NULL,
925                         get_sieve_config_backend, (void *)u );
926
927         }
928
929         if (strcmp(CC->room.QRname, hold_rm)) {
930                 getroom(&CC->room, hold_rm);    /* return to saved room */
931         }
932 }
933
934 void msiv_store(struct sdm_userdata *u, int yes_write_to_disk) {
935         rewrite_ctdl_sieve_config(u, yes_write_to_disk);
936 }
937
938
939 /*
940  * Select the active script.
941  * (Set script_name to an empty string to disable all scripts)
942  * 
943  * Returns 0 on success or nonzero for error.
944  */
945 int msiv_setactive(struct sdm_userdata *u, char *script_name) {
946         int ok = 0;
947         struct sdm_script *s;
948
949         /* First see if the supplied value is ok */
950
951         if (strlen(script_name) == 0) {
952                 ok = 1;
953         }
954         else {
955                 for (s=u->first_script; s!=NULL; s=s->next) {
956                         if (!strcasecmp(s->script_name, script_name)) {
957                                 ok = 1;
958                         }
959                 }
960         }
961
962         if (!ok) return(-1);
963
964         /* Now set the active script */
965         for (s=u->first_script; s!=NULL; s=s->next) {
966                 if (!strcasecmp(s->script_name, script_name)) {
967                         s->script_active = 1;
968                 }
969                 else {
970                         s->script_active = 0;
971                 }
972         }
973         
974         return(0);
975 }
976
977
978 /*
979  * Fetch a script by name.
980  *
981  * Returns NULL if the named script was not found, or a pointer to the script
982  * if it was found.   NOTE: the caller does *not* own the memory returned by
983  * this function.  Copy it if you need to keep it.
984  */
985 char *msiv_getscript(struct sdm_userdata *u, char *script_name) {
986         struct sdm_script *s;
987
988         for (s=u->first_script; s!=NULL; s=s->next) {
989                 if (!strcasecmp(s->script_name, script_name)) {
990                         if (s->script_content != NULL) {
991                                 return (s->script_content);
992                         }
993                 }
994         }
995
996         return(NULL);
997 }
998
999
1000 /*
1001  * Delete a script by name.
1002  *
1003  * Returns 0 if the script was deleted.
1004  *       1 if the script was not found.
1005  *       2 if the script cannot be deleted because it is active.
1006  */
1007 int msiv_deletescript(struct sdm_userdata *u, char *script_name) {
1008         struct sdm_script *s = NULL;
1009         struct sdm_script *script_to_delete = NULL;
1010
1011         for (s=u->first_script; s!=NULL; s=s->next) {
1012                 if (!strcasecmp(s->script_name, script_name)) {
1013                         script_to_delete = s;
1014                         if (s->script_active) {
1015                                 return(2);
1016                         }
1017                 }
1018         }
1019
1020         if (script_to_delete == NULL) return(1);
1021
1022         if (u->first_script == script_to_delete) {
1023                 u->first_script = u->first_script->next;
1024         }
1025         else for (s=u->first_script; s!=NULL; s=s->next) {
1026                 if (s->next == script_to_delete) {
1027                         s->next = s->next->next;
1028                 }
1029         }
1030
1031         free(script_to_delete->script_content);
1032         free(script_to_delete);
1033         return(0);
1034 }
1035
1036
1037 /*
1038  * Add or replace a new script.  
1039  * NOTE: after this function returns, "u" owns the memory that "script_content"
1040  * was pointing to.
1041  */
1042 void msiv_putscript(struct sdm_userdata *u, char *script_name, char *script_content) {
1043         int replaced = 0;
1044         struct sdm_script *s, *sptr;
1045
1046         for (s=u->first_script; s!=NULL; s=s->next) {
1047                 if (!strcasecmp(s->script_name, script_name)) {
1048                         if (s->script_content != NULL) {
1049                                 free(s->script_content);
1050                         }
1051                         s->script_content = script_content;
1052                         replaced = 1;
1053                 }
1054         }
1055
1056         if (replaced == 0) {
1057                 sptr = malloc(sizeof(struct sdm_script));
1058                 safestrncpy(sptr->script_name, script_name, sizeof sptr->script_name);
1059                 sptr->script_content = script_content;
1060                 sptr->script_active = 0;
1061                 sptr->next = u->first_script;
1062                 u->first_script = sptr;
1063         }
1064 }
1065
1066
1067
1068 /*
1069  * Citadel protocol to manage sieve scripts.
1070  * This is basically a simplified (read: doesn't resemble IMAP) version
1071  * of the 'managesieve' protocol.
1072  */
1073 void cmd_msiv(char *argbuf) {
1074         char subcmd[256];
1075         struct sdm_userdata u;
1076         char script_name[256];
1077         char *script_content = NULL;
1078         struct sdm_script *s;
1079         int i;
1080         int changes_made = 0;
1081
1082         memset(&u, 0, sizeof(struct sdm_userdata));
1083
1084         if (CtdlAccessCheck(ac_logged_in)) return;
1085         extract_token(subcmd, argbuf, 0, '|', sizeof subcmd);
1086         msiv_load(&u);
1087
1088         if (!strcasecmp(subcmd, "putscript")) {
1089                 extract_token(script_name, argbuf, 1, '|', sizeof script_name);
1090                 if (strlen(script_name) > 0) {
1091                         cprintf("%d Transmit script now\n", SEND_LISTING);
1092                         script_content = CtdlReadMessageBody("000", config.c_maxmsglen, NULL, 0);
1093                         msiv_putscript(&u, script_name, script_content);
1094                         changes_made = 1;
1095                 }
1096                 else {
1097                         cprintf("%d Invalid script name.\n", ERROR + ILLEGAL_VALUE);
1098                 }
1099         }       
1100         
1101         else if (!strcasecmp(subcmd, "listscripts")) {
1102                 cprintf("%d Scripts:\n", LISTING_FOLLOWS);
1103                 for (s=u.first_script; s!=NULL; s=s->next) {
1104                         if (s->script_content != NULL) {
1105                                 cprintf("%s|%d|\n", s->script_name, s->script_active);
1106                         }
1107                 }
1108                 cprintf("000\n");
1109         }
1110
1111         else if (!strcasecmp(subcmd, "setactive")) {
1112                 extract_token(script_name, argbuf, 1, '|', sizeof script_name);
1113                 if (msiv_setactive(&u, script_name) == 0) {
1114                         cprintf("%d ok\n", CIT_OK);
1115                         changes_made = 1;
1116                 }
1117                 else {
1118                         cprintf("%d Script '%s' does not exist.\n",
1119                                 ERROR + ILLEGAL_VALUE,
1120                                 script_name
1121                         );
1122                 }
1123         }
1124
1125         else if (!strcasecmp(subcmd, "getscript")) {
1126                 extract_token(script_name, argbuf, 1, '|', sizeof script_name);
1127                 script_content = msiv_getscript(&u, script_name);
1128                 if (script_content != NULL) {
1129                         int script_len;
1130
1131                         cprintf("%d Script:\n", LISTING_FOLLOWS);
1132                         script_len = strlen(script_content);
1133                         client_write(script_content, script_len);
1134                         if (script_content[script_len-1] != '\n') {
1135                                 cprintf("\n");
1136                         }
1137                         cprintf("000\n");
1138                 }
1139                 else {
1140                         cprintf("%d Invalid script name.\n", ERROR + ILLEGAL_VALUE);
1141                 }
1142         }
1143
1144         else if (!strcasecmp(subcmd, "deletescript")) {
1145                 extract_token(script_name, argbuf, 1, '|', sizeof script_name);
1146                 i = msiv_deletescript(&u, script_name);
1147                 if (i == 0) {
1148                         cprintf("%d ok\n", CIT_OK);
1149                         changes_made = 1;
1150                 }
1151                 else if (i == 1) {
1152                         cprintf("%d Script '%s' does not exist.\n",
1153                                 ERROR + ILLEGAL_VALUE,
1154                                 script_name
1155                         );
1156                 }
1157                 else if (i == 2) {
1158                         cprintf("%d Script '%s' is active and cannot be deleted.\n",
1159                                 ERROR + ILLEGAL_VALUE,
1160                                 script_name
1161                         );
1162                 }
1163                 else {
1164                         cprintf("%d unknown error\n", ERROR);
1165                 }
1166         }
1167
1168         else {
1169                 cprintf("%d Invalid subcommand\n", ERROR + CMD_NOT_SUPPORTED);
1170         }
1171
1172         msiv_store(&u, changes_made);
1173 }
1174
1175
1176
1177 void ctdl_sieve_init(void) {
1178         char *cred = NULL;
1179         sieve2_context_t *sieve2_context = NULL;
1180         int res;
1181
1182         /*
1183          *      We don't really care about dumping the entire credits to the log
1184          *      every time the server is initialized.  The documentation will suffice
1185          *      for that purpose.  We are making a call to sieve2_credits() in order
1186          *      to demonstrate that we have successfully linked in to libsieve.
1187          */
1188         cred = strdup(sieve2_credits());
1189         if (cred == NULL) return;
1190
1191         if (strlen(cred) > 60) {
1192                 strcpy(&cred[55], "...");
1193         }
1194
1195         lprintf(CTDL_INFO, "%s\n",cred);
1196         free(cred);
1197
1198         /* Briefly initialize a Sieve parser instance just so we can list the
1199          * extensions that are available.
1200          */
1201         res = sieve2_alloc(&sieve2_context);
1202         if (res != SIEVE2_OK) {
1203                 lprintf(CTDL_CRIT, "sieve2_alloc() returned %d: %s\n", res, sieve2_errstr(res));
1204                 return;
1205         }
1206
1207         res = sieve2_callbacks(sieve2_context, ctdl_sieve_callbacks);
1208         if (res != SIEVE2_OK) {
1209                 lprintf(CTDL_CRIT, "sieve2_callbacks() returned %d: %s\n", res, sieve2_errstr(res));
1210                 goto BAIL;
1211         }
1212
1213         msiv_extensions = strdup(sieve2_listextensions(sieve2_context));
1214         lprintf(CTDL_INFO, "Extensions: %s\n", msiv_extensions);
1215
1216 BAIL:   res = sieve2_free(&sieve2_context);
1217         if (res != SIEVE2_OK) {
1218                 lprintf(CTDL_CRIT, "sieve2_free() returned %d: %s\n", res, sieve2_errstr(res));
1219         }
1220
1221 }
1222
1223
1224
1225 char *serv_sieve_init(void)
1226 {
1227         ctdl_sieve_init();
1228         CtdlRegisterProtoHook(cmd_msiv, "MSIV", "Manage Sieve scripts");
1229         return "$Id: serv_sieve.c 3850 2005-09-13 14:00:24Z ajc $";
1230 }
1231
1232 #else   /* HAVE_LIBSIEVE */
1233
1234 char *serv_sieve_init(void)
1235 {
1236         lprintf(CTDL_INFO, "This server is missing libsieve.  Mailbox filtering will be disabled.\n");
1237         return "$Id: serv_sieve.c 3850 2005-09-13 14:00:24Z ajc $";
1238 }
1239
1240 #endif  /* HAVE_LIBSIEVE */