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