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