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