]> code.citadel.org Git - citadel.git/blob - citadel/serv_sieve.c
serv_sieve: when no envelope-to field is present, copy
[citadel.git] / citadel / serv_sieve.c
1 /*
2  * $Id$
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 = 1;
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         lprintf(CTDL_DEBUG, "<%s> queued for Sieve processing\n", which_room->QRname);
486 }
487
488
489
490 /*
491  * Perform sieve processing for one message (called by sieve_do_room() for each message)
492  */
493 void sieve_do_msg(long msgnum, void *userdata) {
494         struct sdm_userdata *u = (struct sdm_userdata *) userdata;
495         sieve2_context_t *sieve2_context = u->sieve2_context;
496         struct ctdl_sieve my;
497         int res;
498         struct CtdlMessage *msg;
499         int i;
500         size_t headers_len = 0;
501
502         lprintf(CTDL_DEBUG, "Performing sieve processing on msg <%ld>\n", msgnum);
503
504         msg = CtdlFetchMessage(msgnum, 0);
505         if (msg == NULL) return;
506
507         /*
508          * Grab the message headers so we can feed them to libSieve.
509          */
510         CC->redirect_buffer = malloc(SIZ);
511         CC->redirect_len = 0;
512         CC->redirect_alloc = SIZ;
513         CtdlOutputPreLoadedMsg(msg, MT_RFC822, HEADERS_ONLY, 0, 1);
514         my.rfc822headers = CC->redirect_buffer;
515         headers_len = CC->redirect_len;
516         CC->redirect_buffer = NULL;
517         CC->redirect_len = 0;
518         CC->redirect_alloc = 0;
519
520         /*
521          * libSieve clobbers the stack if it encounters badly formed
522          * headers.  Sanitize our headers by stripping nonprintable
523          * characters.
524          */
525         for (i=0; i<headers_len; ++i) {
526                 if (!isascii(my.rfc822headers[i])) {
527                         my.rfc822headers[i] = '_';
528                 }
529         }
530
531         my.keep = 0;                            /* Set to 1 to declare an *explicit* keep */
532         my.cancel_implicit_keep = 0;            /* Some actions will cancel the implicit keep */
533         my.usernum = atol(CC->room.QRname);     /* Keep track of the owner of the room's namespace */
534         my.msgnum = msgnum;                     /* Keep track of the message number in our local store */
535         my.u = u;                               /* Hand off a pointer to the rest of this info */
536
537         /* Keep track of the recipient so we can do handling based on it later */
538         process_rfc822_addr(msg->cm_fields['R'], my.recp_user, my.recp_node, my.recp_name);
539
540         /* Keep track of the sender so we can use it for REJECT and VACATION responses */
541         if (msg->cm_fields['F'] != NULL) {
542                 safestrncpy(my.sender, msg->cm_fields['F'], sizeof my.sender);
543         }
544         else if ( (msg->cm_fields['A'] != NULL) && (msg->cm_fields['N'] != NULL) ) {
545                 snprintf(my.sender, sizeof my.sender, "%s@%s", msg->cm_fields['A'], msg->cm_fields['N']);
546         }
547         else if (msg->cm_fields['A'] != NULL) {
548                 safestrncpy(my.sender, msg->cm_fields['A'], sizeof my.sender);
549         }
550         else {
551                 strcpy(my.sender, "");
552         }
553
554         /* Keep track of the subject so we can use it for VACATION responses */
555         if (msg->cm_fields['U'] != NULL) {
556                 safestrncpy(my.subject, msg->cm_fields['U'], sizeof my.subject);
557         }
558         else {
559                 strcpy(my.subject, "");
560         }
561
562         /* Keep track of the envelope-from address (use body-from if not found) */
563         if (msg->cm_fields['P'] != NULL) {
564                 safestrncpy(my.envelope_from, msg->cm_fields['P'], sizeof my.envelope_from);
565         }
566         else if (msg->cm_fields['F'] != NULL) {
567                 safestrncpy(my.envelope_from, msg->cm_fields['F'], sizeof my.envelope_from);
568         }
569         else {
570                 strcpy(my.envelope_from, "");
571         }
572
573         /* Keep track of the envelope-to address (use body-to if not found) */
574         if (msg->cm_fields['V'] != NULL) {
575                 safestrncpy(my.envelope_to, msg->cm_fields['V'], sizeof my.envelope_to);
576         }
577         else if (msg->cm_fields['R'] != NULL) {
578                 safestrncpy(my.envelope_to, msg->cm_fields['R'], sizeof my.envelope_to);
579                 if (msg->cm_fields['D'] != NULL) {
580                         strcat(my.envelope_to, "@");
581                         strcat(my.envelope_to, msg->cm_fields['D']);
582                 }
583         }
584         else {
585                 strcpy(my.envelope_to, "");
586         }
587
588         CtdlFreeMessage(msg);
589
590         sieve2_setvalue_string(sieve2_context, "allheaders", my.rfc822headers);
591         
592         lprintf(CTDL_DEBUG, "Calling sieve2_execute()\n");
593         res = sieve2_execute(sieve2_context, &my);
594         if (res != SIEVE2_OK) {
595                 lprintf(CTDL_CRIT, "sieve2_execute() returned %d: %s\n", res, sieve2_errstr(res));
596         }
597
598         free(my.rfc822headers);
599         my.rfc822headers = NULL;
600
601         /*
602          * Delete the message from the inbox unless either we were told not to, or
603          * if no other action was successfully taken.
604          */
605         if ( (!my.keep) && (my.cancel_implicit_keep) ) {
606                 lprintf(CTDL_DEBUG, "keep is 0 -- deleting message from inbox\n");
607                 CtdlDeleteMessages(CC->room.QRname, &msgnum, 1, "");
608         }
609
610         lprintf(CTDL_DEBUG, "Completed sieve processing on msg <%ld>\n", msgnum);
611         u->lastproc = msgnum;
612
613         return;
614 }
615
616
617
618 /*
619  * Given the on-disk representation of our Sieve config, load
620  * it into an in-memory data structure.
621  */
622 void parse_sieve_config(char *conf, struct sdm_userdata *u) {
623         char *ptr;
624         char *c, *vacrec;
625         char keyword[256];
626         struct sdm_script *sptr;
627         struct sdm_vacation *vptr;
628
629         ptr = conf;
630         while (c = ptr, ptr = bmstrcasestr(ptr, CTDLSIEVECONFIGSEPARATOR), ptr != NULL) {
631                 *ptr = 0;
632                 ptr += strlen(CTDLSIEVECONFIGSEPARATOR);
633
634                 extract_token(keyword, c, 0, '|', sizeof keyword);
635
636                 if (!strcasecmp(keyword, "lastproc")) {
637                         u->lastproc = extract_long(c, 1);
638                 }
639
640                 else if (!strcasecmp(keyword, "script")) {
641                         sptr = malloc(sizeof(struct sdm_script));
642                         extract_token(sptr->script_name, c, 1, '|', sizeof sptr->script_name);
643                         sptr->script_active = extract_int(c, 2);
644                         remove_token(c, 0, '|');
645                         remove_token(c, 0, '|');
646                         remove_token(c, 0, '|');
647                         sptr->script_content = strdup(c);
648                         sptr->next = u->first_script;
649                         u->first_script = sptr;
650                 }
651
652                 else if (!strcasecmp(keyword, "vacation")) {
653
654                         if (c != NULL) while (vacrec=c, c=strchr(c, '\n'), (c != NULL)) {
655
656                                 *c = 0;
657                                 ++c;
658
659                                 if (strncasecmp(vacrec, "vacation|", 9)) {
660                                         vptr = malloc(sizeof(struct sdm_vacation));
661                                         extract_token(vptr->fromaddr, vacrec, 0, '|', sizeof vptr->fromaddr);
662                                         vptr->timestamp = extract_long(vacrec, 1);
663                                         vptr->next = u->first_vacation;
664                                         u->first_vacation = vptr;
665                                 }
666                         }
667                 }
668
669                 /* ignore unknown keywords */
670         }
671 }
672
673 /*
674  * We found the Sieve configuration for this user.
675  * Now do something with it.
676  */
677 void get_sieve_config_backend(long msgnum, void *userdata) {
678         struct sdm_userdata *u = (struct sdm_userdata *) userdata;
679         struct CtdlMessage *msg;
680         char *conf;
681
682         u->config_msgnum = msgnum;
683         msg = CtdlFetchMessage(msgnum, 1);
684         if (msg == NULL) {
685                 u->config_msgnum = (-1) ;
686                 return;
687         }
688
689         conf = msg->cm_fields['M'];
690         msg->cm_fields['M'] = NULL;
691         CtdlFreeMessage(msg);
692
693         if (conf != NULL) {
694                 parse_sieve_config(conf, u);
695                 free(conf);
696         }
697
698 }
699
700
701 /* 
702  * Write our citadel sieve config back to disk
703  * 
704  * (Set yes_write_to_disk to nonzero to make it actually write the config;
705  * otherwise it just frees the data structures.)
706  */
707 void rewrite_ctdl_sieve_config(struct sdm_userdata *u, int yes_write_to_disk) {
708         char *text;
709         struct sdm_script *sptr;
710         struct sdm_vacation *vptr;
711         size_t tsize;
712
713         text = malloc(1024);
714         tsize = 1024;
715         snprintf(text, 1024,
716                 "Content-type: application/x-citadel-sieve-config\n"
717                 "\n"
718                 CTDLSIEVECONFIGSEPARATOR
719                 "lastproc|%ld"
720                 CTDLSIEVECONFIGSEPARATOR
721         ,
722                 u->lastproc
723         );
724
725         while (u->first_script != NULL) {
726                 size_t tlen;
727                 tlen = strlen(text);
728                 tsize = tlen + strlen(u->first_script->script_content) +256;
729                 text = realloc(text, tsize);
730                 sprintf(&text[strlen(text)], "script|%s|%d|%s" CTDLSIEVECONFIGSEPARATOR,
731                         u->first_script->script_name,
732                         u->first_script->script_active,
733                         u->first_script->script_content
734                 );
735                 sptr = u->first_script;
736                 u->first_script = u->first_script->next;
737                 free(sptr->script_content);
738                 free(sptr);
739         }
740
741         if (u->first_vacation != NULL) {
742
743                 tsize = strlen(text) + 256;
744                 for (vptr = u->first_vacation; vptr != NULL; vptr = vptr->next) {
745                         tsize += strlen(vptr->fromaddr + 32);
746                 }
747                 text = realloc(text, tsize);
748
749                 sprintf(&text[strlen(text)], "vacation|\n");
750                 while (u->first_vacation != NULL) {
751                         if ( (time(NULL) - u->first_vacation->timestamp) < (MAX_VACATION * 86400)) {
752                                 sprintf(&text[strlen(text)], "%s|%ld\n",
753                                         u->first_vacation->fromaddr,
754                                         u->first_vacation->timestamp
755                                 );
756                         }
757                         vptr = u->first_vacation;
758                         u->first_vacation = u->first_vacation->next;
759                         free(vptr);
760                 }
761                 sprintf(&text[strlen(text)], CTDLSIEVECONFIGSEPARATOR);
762         }
763
764         /* Save the config */
765         quickie_message("Citadel", NULL, NULL, u->config_roomname,
766                         text,
767                         4,
768                         "Sieve configuration"
769         );
770         
771         free (text);
772         /* And delete the old one */
773         if (u->config_msgnum > 0) {
774                 CtdlDeleteMessages(u->config_roomname, &u->config_msgnum, 1, "");
775         }
776
777 }
778
779
780 /*
781  * This is our callback registration table for libSieve.
782  */
783 sieve2_callback_t ctdl_sieve_callbacks[] = {
784         { SIEVE2_ACTION_REJECT,         ctdl_reject             },
785         { SIEVE2_ACTION_VACATION,       ctdl_vacation           },
786         { SIEVE2_ERRCALL_PARSE,         ctdl_errparse           },
787         { SIEVE2_ERRCALL_RUNTIME,       ctdl_errexec            },
788         { SIEVE2_ACTION_FILEINTO,       ctdl_fileinto           },
789         { SIEVE2_ACTION_REDIRECT,       ctdl_redirect           },
790         { SIEVE2_ACTION_DISCARD,        ctdl_discard            },
791         { SIEVE2_ACTION_KEEP,           ctdl_keep               },
792         { SIEVE2_SCRIPT_GETSCRIPT,      ctdl_getscript          },
793         { SIEVE2_DEBUG_TRACE,           ctdl_debug              },
794         { SIEVE2_MESSAGE_GETALLHEADERS, ctdl_getheaders         },
795         { SIEVE2_MESSAGE_GETSIZE,       ctdl_getsize            },
796         { SIEVE2_MESSAGE_GETENVELOPE,   ctdl_getenvelope        },
797 /*
798  * These actions are unsupported by Citadel so we don't declare them.
799  *
800         { SIEVE2_ACTION_NOTIFY,         ctdl_notify             },
801         { SIEVE2_MESSAGE_GETSUBADDRESS, ctdl_getsubaddress      },
802         { SIEVE2_MESSAGE_GETBODY,       ctdl_getbody            },
803  *
804  */
805         { 0 }
806 };
807
808
809 /*
810  * Perform sieve processing for a single room
811  */
812 void sieve_do_room(char *roomname) {
813         
814         struct sdm_userdata u;
815         sieve2_context_t *sieve2_context = NULL;        /* Context for sieve parser */
816         int res;                                        /* Return code from libsieve calls */
817         long orig_lastproc = 0;
818
819         memset(&u, 0, sizeof u);
820
821         /* See if the user who owns this 'mailbox' has any Sieve scripts that
822          * require execution.
823          */
824         snprintf(u.config_roomname, sizeof u.config_roomname, "%010ld.%s", atol(roomname), USERCONFIGROOM);
825         if (getroom(&CC->room, u.config_roomname) != 0) {
826                 lprintf(CTDL_DEBUG, "<%s> does not exist.  No processing is required.\n", u.config_roomname);
827                 return;
828         }
829
830         /*
831          * Find the sieve scripts and control record and do something
832          */
833         u.config_msgnum = (-1);
834         CtdlForEachMessage(MSGS_LAST, 1, NULL, SIEVECONFIG, NULL,
835                 get_sieve_config_backend, (void *)&u );
836
837         if (u.config_msgnum < 0) {
838                 lprintf(CTDL_DEBUG, "No Sieve rules exist.  No processing is required.\n");
839                 return;
840         }
841
842         lprintf(CTDL_DEBUG, "Rules found.  Performing Sieve processing for <%s>\n", roomname);
843
844         if (getroom(&CC->room, roomname) != 0) {
845                 lprintf(CTDL_CRIT, "ERROR: cannot load <%s>\n", roomname);
846                 return;
847         }
848
849         /* Initialize the Sieve parser */
850         
851         res = sieve2_alloc(&sieve2_context);
852         if (res != SIEVE2_OK) {
853                 lprintf(CTDL_CRIT, "sieve2_alloc() returned %d: %s\n", res, sieve2_errstr(res));
854                 return;
855         }
856
857         res = sieve2_callbacks(sieve2_context, ctdl_sieve_callbacks);
858         if (res != SIEVE2_OK) {
859                 lprintf(CTDL_CRIT, "sieve2_callbacks() returned %d: %s\n", res, sieve2_errstr(res));
860                 goto BAIL;
861         }
862
863         /* Validate the script */
864
865         struct ctdl_sieve my;           /* dummy ctdl_sieve struct just to pass "u" slong */
866         memset(&my, 0, sizeof my);
867         my.u = &u;
868         res = sieve2_validate(sieve2_context, &my);
869         if (res != SIEVE2_OK) {
870                 lprintf(CTDL_CRIT, "sieve2_validate() returned %d: %s\n", res, sieve2_errstr(res));
871                 goto BAIL;
872         }
873
874         /* Do something useful */
875         u.sieve2_context = sieve2_context;
876         orig_lastproc = u.lastproc;
877         CtdlForEachMessage(MSGS_GT, u.lastproc, NULL, NULL, NULL,
878                 sieve_do_msg,
879                 (void *) &u
880         );
881
882 BAIL:
883         res = sieve2_free(&sieve2_context);
884         if (res != SIEVE2_OK) {
885                 lprintf(CTDL_CRIT, "sieve2_free() returned %d: %s\n", res, sieve2_errstr(res));
886         }
887
888         /* Rewrite the config if we have to */
889         rewrite_ctdl_sieve_config(&u, (u.lastproc > orig_lastproc) ) ;
890 }
891
892
893 /*
894  * Perform sieve processing for all rooms which require it
895  */
896 void perform_sieve_processing(void) {
897         struct RoomProcList *ptr = NULL;
898
899         if (sieve_list != NULL) {
900                 lprintf(CTDL_DEBUG, "Begin Sieve processing\n");
901                 while (sieve_list != NULL) {
902                         char spoolroomname[ROOMNAMELEN];
903                         safestrncpy(spoolroomname, sieve_list->name, sizeof spoolroomname);
904                         begin_critical_section(S_SIEVELIST);
905
906                         /* pop this record off the list */
907                         ptr = sieve_list;
908                         sieve_list = sieve_list->next;
909                         free(ptr);
910
911                         /* invalidate any duplicate entries to prevent double processing */
912                         for (ptr=sieve_list; ptr!=NULL; ptr=ptr->next) {
913                                 if (!strcasecmp(ptr->name, spoolroomname)) {
914                                         ptr->name[0] = 0;
915                                 }
916                         }
917
918                         end_critical_section(S_SIEVELIST);
919                         if (spoolroomname[0] != 0) {
920                                 sieve_do_room(spoolroomname);
921                         }
922                 }
923         }
924 }
925
926
927 void msiv_load(struct sdm_userdata *u) {
928         char hold_rm[ROOMNAMELEN];
929
930         strcpy(hold_rm, CC->room.QRname);       /* save current room */
931
932         /* Take a spin through the user's personal address book */
933         if (getroom(&CC->room, USERCONFIGROOM) == 0) {
934         
935                 u->config_msgnum = (-1);
936                 strcpy(u->config_roomname, CC->room.QRname);
937                 CtdlForEachMessage(MSGS_LAST, 1, NULL, SIEVECONFIG, NULL,
938                         get_sieve_config_backend, (void *)u );
939
940         }
941
942         if (strcmp(CC->room.QRname, hold_rm)) {
943                 getroom(&CC->room, hold_rm);    /* return to saved room */
944         }
945 }
946
947 void msiv_store(struct sdm_userdata *u, int yes_write_to_disk) {
948         rewrite_ctdl_sieve_config(u, yes_write_to_disk);
949 }
950
951
952 /*
953  * Select the active script.
954  * (Set script_name to an empty string to disable all scripts)
955  * 
956  * Returns 0 on success or nonzero for error.
957  */
958 int msiv_setactive(struct sdm_userdata *u, char *script_name) {
959         int ok = 0;
960         struct sdm_script *s;
961
962         /* First see if the supplied value is ok */
963
964         if (strlen(script_name) == 0) {
965                 ok = 1;
966         }
967         else {
968                 for (s=u->first_script; s!=NULL; s=s->next) {
969                         if (!strcasecmp(s->script_name, script_name)) {
970                                 ok = 1;
971                         }
972                 }
973         }
974
975         if (!ok) return(-1);
976
977         /* Now set the active script */
978         for (s=u->first_script; s!=NULL; s=s->next) {
979                 if (!strcasecmp(s->script_name, script_name)) {
980                         s->script_active = 1;
981                 }
982                 else {
983                         s->script_active = 0;
984                 }
985         }
986         
987         return(0);
988 }
989
990
991 /*
992  * Fetch a script by name.
993  *
994  * Returns NULL if the named script was not found, or a pointer to the script
995  * if it was found.   NOTE: the caller does *not* own the memory returned by
996  * this function.  Copy it if you need to keep it.
997  */
998 char *msiv_getscript(struct sdm_userdata *u, char *script_name) {
999         struct sdm_script *s;
1000
1001         for (s=u->first_script; s!=NULL; s=s->next) {
1002                 if (!strcasecmp(s->script_name, script_name)) {
1003                         if (s->script_content != NULL) {
1004                                 return (s->script_content);
1005                         }
1006                 }
1007         }
1008
1009         return(NULL);
1010 }
1011
1012
1013 /*
1014  * Delete a script by name.
1015  *
1016  * Returns 0 if the script was deleted.
1017  *       1 if the script was not found.
1018  *       2 if the script cannot be deleted because it is active.
1019  */
1020 int msiv_deletescript(struct sdm_userdata *u, char *script_name) {
1021         struct sdm_script *s = NULL;
1022         struct sdm_script *script_to_delete = NULL;
1023
1024         for (s=u->first_script; s!=NULL; s=s->next) {
1025                 if (!strcasecmp(s->script_name, script_name)) {
1026                         script_to_delete = s;
1027                         if (s->script_active) {
1028                                 return(2);
1029                         }
1030                 }
1031         }
1032
1033         if (script_to_delete == NULL) return(1);
1034
1035         if (u->first_script == script_to_delete) {
1036                 u->first_script = u->first_script->next;
1037         }
1038         else for (s=u->first_script; s!=NULL; s=s->next) {
1039                 if (s->next == script_to_delete) {
1040                         s->next = s->next->next;
1041                 }
1042         }
1043
1044         free(script_to_delete->script_content);
1045         free(script_to_delete);
1046         return(0);
1047 }
1048
1049
1050 /*
1051  * Add or replace a new script.  
1052  * NOTE: after this function returns, "u" owns the memory that "script_content"
1053  * was pointing to.
1054  */
1055 void msiv_putscript(struct sdm_userdata *u, char *script_name, char *script_content) {
1056         int replaced = 0;
1057         struct sdm_script *s, *sptr;
1058
1059         for (s=u->first_script; s!=NULL; s=s->next) {
1060                 if (!strcasecmp(s->script_name, script_name)) {
1061                         if (s->script_content != NULL) {
1062                                 free(s->script_content);
1063                         }
1064                         s->script_content = script_content;
1065                         replaced = 1;
1066                 }
1067         }
1068
1069         if (replaced == 0) {
1070                 sptr = malloc(sizeof(struct sdm_script));
1071                 safestrncpy(sptr->script_name, script_name, sizeof sptr->script_name);
1072                 sptr->script_content = script_content;
1073                 sptr->script_active = 0;
1074                 sptr->next = u->first_script;
1075                 u->first_script = sptr;
1076         }
1077 }
1078
1079
1080
1081 /*
1082  * Citadel protocol to manage sieve scripts.
1083  * This is basically a simplified (read: doesn't resemble IMAP) version
1084  * of the 'managesieve' protocol.
1085  */
1086 void cmd_msiv(char *argbuf) {
1087         char subcmd[256];
1088         struct sdm_userdata u;
1089         char script_name[256];
1090         char *script_content = NULL;
1091         struct sdm_script *s;
1092         int i;
1093         int changes_made = 0;
1094
1095         memset(&u, 0, sizeof(struct sdm_userdata));
1096
1097         if (CtdlAccessCheck(ac_logged_in)) return;
1098         extract_token(subcmd, argbuf, 0, '|', sizeof subcmd);
1099         msiv_load(&u);
1100
1101         if (!strcasecmp(subcmd, "putscript")) {
1102                 extract_token(script_name, argbuf, 1, '|', sizeof script_name);
1103                 if (strlen(script_name) > 0) {
1104                         cprintf("%d Transmit script now\n", SEND_LISTING);
1105                         script_content = CtdlReadMessageBody("000", config.c_maxmsglen, NULL, 0);
1106                         msiv_putscript(&u, script_name, script_content);
1107                         changes_made = 1;
1108                 }
1109                 else {
1110                         cprintf("%d Invalid script name.\n", ERROR + ILLEGAL_VALUE);
1111                 }
1112         }       
1113         
1114         else if (!strcasecmp(subcmd, "listscripts")) {
1115                 cprintf("%d Scripts:\n", LISTING_FOLLOWS);
1116                 for (s=u.first_script; s!=NULL; s=s->next) {
1117                         if (s->script_content != NULL) {
1118                                 cprintf("%s|%d|\n", s->script_name, s->script_active);
1119                         }
1120                 }
1121                 cprintf("000\n");
1122         }
1123
1124         else if (!strcasecmp(subcmd, "setactive")) {
1125                 extract_token(script_name, argbuf, 1, '|', sizeof script_name);
1126                 if (msiv_setactive(&u, script_name) == 0) {
1127                         cprintf("%d ok\n", CIT_OK);
1128                         changes_made = 1;
1129                 }
1130                 else {
1131                         cprintf("%d Script '%s' does not exist.\n",
1132                                 ERROR + ILLEGAL_VALUE,
1133                                 script_name
1134                         );
1135                 }
1136         }
1137
1138         else if (!strcasecmp(subcmd, "getscript")) {
1139                 extract_token(script_name, argbuf, 1, '|', sizeof script_name);
1140                 script_content = msiv_getscript(&u, script_name);
1141                 if (script_content != NULL) {
1142                         int script_len;
1143
1144                         cprintf("%d Script:\n", LISTING_FOLLOWS);
1145                         script_len = strlen(script_content);
1146                         client_write(script_content, script_len);
1147                         if (script_content[script_len-1] != '\n') {
1148                                 cprintf("\n");
1149                         }
1150                         cprintf("000\n");
1151                 }
1152                 else {
1153                         cprintf("%d Invalid script name.\n", ERROR + ILLEGAL_VALUE);
1154                 }
1155         }
1156
1157         else if (!strcasecmp(subcmd, "deletescript")) {
1158                 extract_token(script_name, argbuf, 1, '|', sizeof script_name);
1159                 i = msiv_deletescript(&u, script_name);
1160                 if (i == 0) {
1161                         cprintf("%d ok\n", CIT_OK);
1162                         changes_made = 1;
1163                 }
1164                 else if (i == 1) {
1165                         cprintf("%d Script '%s' does not exist.\n",
1166                                 ERROR + ILLEGAL_VALUE,
1167                                 script_name
1168                         );
1169                 }
1170                 else if (i == 2) {
1171                         cprintf("%d Script '%s' is active and cannot be deleted.\n",
1172                                 ERROR + ILLEGAL_VALUE,
1173                                 script_name
1174                         );
1175                 }
1176                 else {
1177                         cprintf("%d unknown error\n", ERROR);
1178                 }
1179         }
1180
1181         else {
1182                 cprintf("%d Invalid subcommand\n", ERROR + CMD_NOT_SUPPORTED);
1183         }
1184
1185         msiv_store(&u, changes_made);
1186 }
1187
1188
1189
1190 void ctdl_sieve_init(void) {
1191         char *cred = NULL;
1192         sieve2_context_t *sieve2_context = NULL;
1193         int res;
1194
1195         /*
1196          *      We don't really care about dumping the entire credits to the log
1197          *      every time the server is initialized.  The documentation will suffice
1198          *      for that purpose.  We are making a call to sieve2_credits() in order
1199          *      to demonstrate that we have successfully linked in to libsieve.
1200          */
1201         cred = strdup(sieve2_credits());
1202         if (cred == NULL) return;
1203
1204         if (strlen(cred) > 60) {
1205                 strcpy(&cred[55], "...");
1206         }
1207
1208         lprintf(CTDL_INFO, "%s\n",cred);
1209         free(cred);
1210
1211         /* Briefly initialize a Sieve parser instance just so we can list the
1212          * extensions that are available.
1213          */
1214         res = sieve2_alloc(&sieve2_context);
1215         if (res != SIEVE2_OK) {
1216                 lprintf(CTDL_CRIT, "sieve2_alloc() returned %d: %s\n", res, sieve2_errstr(res));
1217                 return;
1218         }
1219
1220         res = sieve2_callbacks(sieve2_context, ctdl_sieve_callbacks);
1221         if (res != SIEVE2_OK) {
1222                 lprintf(CTDL_CRIT, "sieve2_callbacks() returned %d: %s\n", res, sieve2_errstr(res));
1223                 goto BAIL;
1224         }
1225
1226         msiv_extensions = strdup(sieve2_listextensions(sieve2_context));
1227         lprintf(CTDL_INFO, "Extensions: %s\n", msiv_extensions);
1228
1229 BAIL:   res = sieve2_free(&sieve2_context);
1230         if (res != SIEVE2_OK) {
1231                 lprintf(CTDL_CRIT, "sieve2_free() returned %d: %s\n", res, sieve2_errstr(res));
1232         }
1233
1234 }
1235
1236 int serv_sieve_room(struct ctdlroom *room)
1237 {
1238         if (!strcasecmp(&room->QRname[11], MAILROOM)) {
1239                 sieve_queue_room(room);
1240         }
1241         return 0;
1242 }
1243
1244
1245 char *serv_sieve_init(void)
1246 {
1247         ctdl_sieve_init();
1248         CtdlRegisterProtoHook(cmd_msiv, "MSIV", "Manage Sieve scripts");
1249         CtdlRegisterRoomHook(serv_sieve_room);
1250         return "$Id$";
1251 }
1252
1253 #else   /* HAVE_LIBSIEVE */
1254
1255 char *serv_sieve_init(void)
1256 {
1257         lprintf(CTDL_INFO, "This server is missing libsieve.  Mailbox filtering will be disabled.\n");
1258
1259         /* return our Subversion id for the Log */
1260         return "$Id$";
1261 }
1262
1263 #endif  /* HAVE_LIBSIEVE */