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