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