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