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