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