* checking a pointer is useless if you dereference it in advance.
[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 <libcitadel.h>
35 #include "citadel.h"
36 #include "server.h"
37 #include "citserver.h"
38 #include "support.h"
39 #include "config.h"
40 #include "room_ops.h"
41 #include "policy.h"
42 #include "database.h"
43 #include "msgbase.h"
44 #include "internet_addressing.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, NULL, 0);
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\nEnvFrom: %s\n  EnvTo: %s\n",
390                 cs->envelope_from, 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                         lprintf(CTDL_DEBUG, "ctdl_getscript() is using script '%s'\n", sptr->script_name);
462                         sieve2_setvalue_string(s, "script", sptr->script_content);
463                         return SIEVE2_OK;
464                 }
465         }
466                 
467         lprintf(CTDL_DEBUG, "ctdl_getscript() found no active script\n");
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         lprintf(CTDL_DEBUG, "ctdl_getheaders() was called\n");
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         lprintf(CTDL_DEBUG, "<%s> queued for Sieve processing\n", 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 (userdata == NULL)
518         {
519                 lprintf(CTDL_EMERG, "Cant process Message <%ld>without Userdata!\n", msgnum);
520                 return;
521         }
522
523         sieve2_context = u->sieve2_context;
524
525         lprintf(CTDL_DEBUG, "Performing sieve processing on msg <%ld>\n", msgnum);
526
527         msg = CtdlFetchMessage(msgnum, 0);
528         if (msg == NULL) return;
529
530         /*
531          * Grab the message headers so we can feed them to libSieve.
532          */
533         CC->redirect_buffer = malloc(SIZ);
534         CC->redirect_len = 0;
535         CC->redirect_alloc = SIZ;
536         CtdlOutputPreLoadedMsg(msg, MT_RFC822, HEADERS_ONLY, 0, 1);
537         my.rfc822headers = CC->redirect_buffer;
538         headers_len = CC->redirect_len;
539         CC->redirect_buffer = NULL;
540         CC->redirect_len = 0;
541         CC->redirect_alloc = 0;
542
543         /*
544          * libSieve clobbers the stack if it encounters badly formed
545          * headers.  Sanitize our headers by stripping nonprintable
546          * characters.
547          */
548         for (i=0; i<headers_len; ++i) {
549                 if (!isascii(my.rfc822headers[i])) {
550                         my.rfc822headers[i] = '_';
551                 }
552         }
553
554         my.keep = 0;                            /* Set to 1 to declare an *explicit* keep */
555         my.cancel_implicit_keep = 0;            /* Some actions will cancel the implicit keep */
556         my.usernum = atol(CC->room.QRname);     /* Keep track of the owner of the room's namespace */
557         my.msgnum = msgnum;                     /* Keep track of the message number in our local store */
558         my.u = u;                               /* Hand off a pointer to the rest of this info */
559
560         /* Keep track of the recipient so we can do handling based on it later */
561         process_rfc822_addr(msg->cm_fields['R'], my.recp_user, my.recp_node, my.recp_name);
562
563         /* Keep track of the sender so we can use it for REJECT and VACATION responses */
564         if (msg->cm_fields['F'] != NULL) {
565                 safestrncpy(my.sender, msg->cm_fields['F'], sizeof my.sender);
566         }
567         else if ( (msg->cm_fields['A'] != NULL) && (msg->cm_fields['N'] != NULL) ) {
568                 snprintf(my.sender, sizeof my.sender, "%s@%s", msg->cm_fields['A'], msg->cm_fields['N']);
569         }
570         else if (msg->cm_fields['A'] != NULL) {
571                 safestrncpy(my.sender, msg->cm_fields['A'], sizeof my.sender);
572         }
573         else {
574                 strcpy(my.sender, "");
575         }
576
577         /* Keep track of the subject so we can use it for VACATION responses */
578         if (msg->cm_fields['U'] != NULL) {
579                 safestrncpy(my.subject, msg->cm_fields['U'], sizeof my.subject);
580         }
581         else {
582                 strcpy(my.subject, "");
583         }
584
585         /* Keep track of the envelope-from address (use body-from if not found) */
586         if (msg->cm_fields['P'] != NULL) {
587                 safestrncpy(my.envelope_from, msg->cm_fields['P'], sizeof my.envelope_from);
588                 stripallbut(my.envelope_from, '<', '>');
589         }
590         else if (msg->cm_fields['F'] != NULL) {
591                 safestrncpy(my.envelope_from, msg->cm_fields['F'], sizeof my.envelope_from);
592                 stripallbut(my.envelope_from, '<', '>');
593         }
594         else {
595                 strcpy(my.envelope_from, "");
596         }
597
598         len = strlen(my.envelope_from);
599         for (i=0; i<len; ++i) {
600                 if (isspace(my.envelope_from[i])) my.envelope_from[i] = '_';
601         }
602         if (haschar(my.envelope_from, '@') == 0) {
603                 strcat(my.envelope_from, "@");
604                 strcat(my.envelope_from, config.c_fqdn);
605         }
606
607         /* Keep track of the envelope-to address (use body-to if not found) */
608         if (msg->cm_fields['V'] != NULL) {
609                 safestrncpy(my.envelope_to, msg->cm_fields['V'], sizeof my.envelope_to);
610                 stripallbut(my.envelope_to, '<', '>');
611         }
612         else if (msg->cm_fields['R'] != NULL) {
613                 safestrncpy(my.envelope_to, msg->cm_fields['R'], sizeof my.envelope_to);
614                 if (msg->cm_fields['D'] != NULL) {
615                         strcat(my.envelope_to, "@");
616                         strcat(my.envelope_to, msg->cm_fields['D']);
617                 }
618                 stripallbut(my.envelope_to, '<', '>');
619         }
620         else {
621                 strcpy(my.envelope_to, "");
622         }
623
624         len = strlen(my.envelope_to);
625         for (i=0; i<len; ++i) {
626                 if (isspace(my.envelope_to[i])) my.envelope_to[i] = '_';
627         }
628         if (haschar(my.envelope_to, '@') == 0) {
629                 strcat(my.envelope_to, "@");
630                 strcat(my.envelope_to, config.c_fqdn);
631         }
632
633         CtdlFreeMessage(msg);
634
635         sieve2_setvalue_string(sieve2_context, "allheaders", my.rfc822headers);
636         
637         lprintf(CTDL_DEBUG, "Calling sieve2_execute()\n");
638         res = sieve2_execute(sieve2_context, &my);
639         if (res != SIEVE2_OK) {
640                 lprintf(CTDL_CRIT, "sieve2_execute() returned %d: %s\n", res, sieve2_errstr(res));
641         }
642
643         free(my.rfc822headers);
644         my.rfc822headers = NULL;
645
646         /*
647          * Delete the message from the inbox unless either we were told not to, or
648          * if no other action was successfully taken.
649          */
650         if ( (!my.keep) && (my.cancel_implicit_keep) ) {
651                 lprintf(CTDL_DEBUG, "keep is 0 -- deleting message from inbox\n");
652                 CtdlDeleteMessages(CC->room.QRname, &msgnum, 1, "");
653         }
654
655         lprintf(CTDL_DEBUG, "Completed sieve processing on msg <%ld>\n", msgnum);
656         u->lastproc = msgnum;
657
658         return;
659 }
660
661
662
663 /*
664  * Given the on-disk representation of our Sieve config, load
665  * it into an in-memory data structure.
666  */
667 void parse_sieve_config(char *conf, struct sdm_userdata *u) {
668         char *ptr;
669         char *c, *vacrec;
670         char keyword[256];
671         struct sdm_script *sptr;
672         struct sdm_vacation *vptr;
673
674         ptr = conf;
675         while (c = ptr, ptr = bmstrcasestr(ptr, CTDLSIEVECONFIGSEPARATOR), ptr != NULL) {
676                 *ptr = 0;
677                 ptr += strlen(CTDLSIEVECONFIGSEPARATOR);
678
679                 extract_token(keyword, c, 0, '|', sizeof keyword);
680
681                 if (!strcasecmp(keyword, "lastproc")) {
682                         u->lastproc = extract_long(c, 1);
683                 }
684
685                 else if (!strcasecmp(keyword, "script")) {
686                         sptr = malloc(sizeof(struct sdm_script));
687                         extract_token(sptr->script_name, c, 1, '|', sizeof sptr->script_name);
688                         sptr->script_active = extract_int(c, 2);
689                         remove_token(c, 0, '|');
690                         remove_token(c, 0, '|');
691                         remove_token(c, 0, '|');
692                         sptr->script_content = strdup(c);
693                         sptr->next = u->first_script;
694                         u->first_script = sptr;
695                 }
696
697                 else if (!strcasecmp(keyword, "vacation")) {
698
699                         if (c != NULL) while (vacrec=c, c=strchr(c, '\n'), (c != NULL)) {
700
701                                 *c = 0;
702                                 ++c;
703
704                                 if (strncasecmp(vacrec, "vacation|", 9)) {
705                                         vptr = malloc(sizeof(struct sdm_vacation));
706                                         extract_token(vptr->fromaddr, vacrec, 0, '|', sizeof vptr->fromaddr);
707                                         vptr->timestamp = extract_long(vacrec, 1);
708                                         vptr->next = u->first_vacation;
709                                         u->first_vacation = vptr;
710                                 }
711                         }
712                 }
713
714                 /* ignore unknown keywords */
715         }
716 }
717
718 /*
719  * We found the Sieve configuration for this user.
720  * Now do something with it.
721  */
722 void get_sieve_config_backend(long msgnum, void *userdata) {
723         struct sdm_userdata *u = (struct sdm_userdata *) userdata;
724         struct CtdlMessage *msg;
725         char *conf;
726
727         u->config_msgnum = msgnum;
728         msg = CtdlFetchMessage(msgnum, 1);
729         if (msg == NULL) {
730                 u->config_msgnum = (-1) ;
731                 return;
732         }
733
734         conf = msg->cm_fields['M'];
735         msg->cm_fields['M'] = NULL;
736         CtdlFreeMessage(msg);
737
738         if (conf != NULL) {
739                 parse_sieve_config(conf, u);
740                 free(conf);
741         }
742
743 }
744
745
746 /* 
747  * Write our citadel sieve config back to disk
748  * 
749  * (Set yes_write_to_disk to nonzero to make it actually write the config;
750  * otherwise it just frees the data structures.)
751  */
752 void rewrite_ctdl_sieve_config(struct sdm_userdata *u, int yes_write_to_disk) {
753         char *text;
754         struct sdm_script *sptr;
755         struct sdm_vacation *vptr;
756         size_t tsize;
757
758         text = malloc(1024);
759         tsize = 1024;
760         snprintf(text, 1024,
761                 "Content-type: application/x-citadel-sieve-config\n"
762                 "\n"
763                 CTDLSIEVECONFIGSEPARATOR
764                 "lastproc|%ld"
765                 CTDLSIEVECONFIGSEPARATOR
766         ,
767                 u->lastproc
768         );
769
770         while (u->first_script != NULL) {
771                 size_t tlen;
772                 tlen = strlen(text);
773                 tsize = tlen + strlen(u->first_script->script_content) +256;
774                 text = realloc(text, tsize);
775                 sprintf(&text[strlen(text)], "script|%s|%d|%s" CTDLSIEVECONFIGSEPARATOR,
776                         u->first_script->script_name,
777                         u->first_script->script_active,
778                         u->first_script->script_content
779                 );
780                 sptr = u->first_script;
781                 u->first_script = u->first_script->next;
782                 free(sptr->script_content);
783                 free(sptr);
784         }
785
786         if (u->first_vacation != NULL) {
787
788                 tsize = strlen(text) + 256;
789                 for (vptr = u->first_vacation; vptr != NULL; vptr = vptr->next) {
790                         tsize += strlen(vptr->fromaddr + 32);
791                 }
792                 text = realloc(text, tsize);
793
794                 sprintf(&text[strlen(text)], "vacation|\n");
795                 while (u->first_vacation != NULL) {
796                         if ( (time(NULL) - u->first_vacation->timestamp) < (MAX_VACATION * 86400)) {
797                                 sprintf(&text[strlen(text)], "%s|%ld\n",
798                                         u->first_vacation->fromaddr,
799                                         u->first_vacation->timestamp
800                                 );
801                         }
802                         vptr = u->first_vacation;
803                         u->first_vacation = u->first_vacation->next;
804                         free(vptr);
805                 }
806                 sprintf(&text[strlen(text)], CTDLSIEVECONFIGSEPARATOR);
807         }
808
809         if (yes_write_to_disk)
810         {
811                 /* Save the config */
812                 quickie_message("Citadel", NULL, NULL, u->config_roomname,
813                                 text,
814                                 4,
815                                 "Sieve configuration"
816                 );
817                 
818                 /* And delete the old one */
819                 if (u->config_msgnum > 0) {
820                         CtdlDeleteMessages(u->config_roomname, &u->config_msgnum, 1, "");
821                 }
822         }
823
824         free (text);
825
826 }
827
828
829 /*
830  * This is our callback registration table for libSieve.
831  */
832 sieve2_callback_t ctdl_sieve_callbacks[] = {
833         { SIEVE2_ACTION_REJECT,         ctdl_reject             },
834         { SIEVE2_ACTION_VACATION,       ctdl_vacation           },
835         { SIEVE2_ERRCALL_PARSE,         ctdl_errparse           },
836         { SIEVE2_ERRCALL_RUNTIME,       ctdl_errexec            },
837         { SIEVE2_ACTION_FILEINTO,       ctdl_fileinto           },
838         { SIEVE2_ACTION_REDIRECT,       ctdl_redirect           },
839         { SIEVE2_ACTION_DISCARD,        ctdl_discard            },
840         { SIEVE2_ACTION_KEEP,           ctdl_keep               },
841         { SIEVE2_SCRIPT_GETSCRIPT,      ctdl_getscript          },
842         { SIEVE2_DEBUG_TRACE,           ctdl_debug              },
843         { SIEVE2_MESSAGE_GETALLHEADERS, ctdl_getheaders         },
844         { SIEVE2_MESSAGE_GETSIZE,       ctdl_getsize            },
845         { SIEVE2_MESSAGE_GETENVELOPE,   ctdl_getenvelope        },
846 /*
847  * These actions are unsupported by Citadel so we don't declare them.
848  *
849         { SIEVE2_ACTION_NOTIFY,         ctdl_notify             },
850         { SIEVE2_MESSAGE_GETSUBADDRESS, ctdl_getsubaddress      },
851         { SIEVE2_MESSAGE_GETBODY,       ctdl_getbody            },
852  *
853  */
854         { 0 }
855 };
856
857
858 /*
859  * Perform sieve processing for a single room
860  */
861 void sieve_do_room(char *roomname) {
862         
863         struct sdm_userdata u;
864         sieve2_context_t *sieve2_context = NULL;        /* Context for sieve parser */
865         int res;                                        /* Return code from libsieve calls */
866         long orig_lastproc = 0;
867
868         memset(&u, 0, sizeof u);
869
870         /* See if the user who owns this 'mailbox' has any Sieve scripts that
871          * require execution.
872          */
873         snprintf(u.config_roomname, sizeof u.config_roomname, "%010ld.%s", atol(roomname), USERCONFIGROOM);
874         if (getroom(&CC->room, u.config_roomname) != 0) {
875                 lprintf(CTDL_DEBUG, "<%s> does not exist.  No processing is required.\n", u.config_roomname);
876                 return;
877         }
878
879         /*
880          * Find the sieve scripts and control record and do something
881          */
882         u.config_msgnum = (-1);
883         CtdlForEachMessage(MSGS_LAST, 1, NULL, SIEVECONFIG, NULL,
884                 get_sieve_config_backend, (void *)&u );
885
886         if (u.config_msgnum < 0) {
887                 lprintf(CTDL_DEBUG, "No Sieve rules exist.  No processing is required.\n");
888                 return;
889         }
890
891         lprintf(CTDL_DEBUG, "Rules found.  Performing Sieve processing for <%s>\n", roomname);
892
893         if (getroom(&CC->room, roomname) != 0) {
894                 lprintf(CTDL_CRIT, "ERROR: cannot load <%s>\n", roomname);
895                 return;
896         }
897
898         /* Initialize the Sieve parser */
899         
900         res = sieve2_alloc(&sieve2_context);
901         if (res != SIEVE2_OK) {
902                 lprintf(CTDL_CRIT, "sieve2_alloc() returned %d: %s\n", res, sieve2_errstr(res));
903                 return;
904         }
905
906         res = sieve2_callbacks(sieve2_context, ctdl_sieve_callbacks);
907         if (res != SIEVE2_OK) {
908                 lprintf(CTDL_CRIT, "sieve2_callbacks() returned %d: %s\n", res, sieve2_errstr(res));
909                 goto BAIL;
910         }
911
912         /* Validate the script */
913
914         struct ctdl_sieve my;           /* dummy ctdl_sieve struct just to pass "u" slong */
915         memset(&my, 0, sizeof my);
916         my.u = &u;
917         res = sieve2_validate(sieve2_context, &my);
918         if (res != SIEVE2_OK) {
919                 lprintf(CTDL_CRIT, "sieve2_validate() returned %d: %s\n", res, sieve2_errstr(res));
920                 goto BAIL;
921         }
922
923         /* Do something useful */
924         u.sieve2_context = sieve2_context;
925         orig_lastproc = u.lastproc;
926         CtdlForEachMessage(MSGS_GT, u.lastproc, NULL, NULL, NULL,
927                 sieve_do_msg,
928                 (void *) &u
929         );
930
931 BAIL:
932         res = sieve2_free(&sieve2_context);
933         if (res != SIEVE2_OK) {
934                 lprintf(CTDL_CRIT, "sieve2_free() returned %d: %s\n", res, sieve2_errstr(res));
935         }
936
937         /* Rewrite the config if we have to */
938         rewrite_ctdl_sieve_config(&u, (u.lastproc > orig_lastproc) ) ;
939 }
940
941
942 /*
943  * Perform sieve processing for all rooms which require it
944  */
945 void perform_sieve_processing(void) {
946         struct RoomProcList *ptr = NULL;
947
948         if (sieve_list != NULL) {
949                 lprintf(CTDL_DEBUG, "Begin Sieve processing\n");
950                 while (sieve_list != NULL) {
951                         char spoolroomname[ROOMNAMELEN];
952                         safestrncpy(spoolroomname, sieve_list->name, sizeof spoolroomname);
953                         begin_critical_section(S_SIEVELIST);
954
955                         /* pop this record off the list */
956                         ptr = sieve_list;
957                         sieve_list = sieve_list->next;
958                         free(ptr);
959
960                         /* invalidate any duplicate entries to prevent double processing */
961                         for (ptr=sieve_list; ptr!=NULL; ptr=ptr->next) {
962                                 if (!strcasecmp(ptr->name, spoolroomname)) {
963                                         ptr->name[0] = 0;
964                                 }
965                         }
966
967                         end_critical_section(S_SIEVELIST);
968                         if (spoolroomname[0] != 0) {
969                                 sieve_do_room(spoolroomname);
970                         }
971                 }
972         }
973 }
974
975
976 void msiv_load(struct sdm_userdata *u) {
977         char hold_rm[ROOMNAMELEN];
978
979         strcpy(hold_rm, CC->room.QRname);       /* save current room */
980
981         /* Take a spin through the user's personal address book */
982         if (getroom(&CC->room, USERCONFIGROOM) == 0) {
983         
984                 u->config_msgnum = (-1);
985                 strcpy(u->config_roomname, CC->room.QRname);
986                 CtdlForEachMessage(MSGS_LAST, 1, NULL, SIEVECONFIG, NULL,
987                         get_sieve_config_backend, (void *)u );
988
989         }
990
991         if (strcmp(CC->room.QRname, hold_rm)) {
992                 getroom(&CC->room, hold_rm);    /* return to saved room */
993         }
994 }
995
996 void msiv_store(struct sdm_userdata *u, int yes_write_to_disk) {
997         rewrite_ctdl_sieve_config(u, yes_write_to_disk);
998 }
999
1000
1001 /*
1002  * Select the active script.
1003  * (Set script_name to an empty string to disable all scripts)
1004  * 
1005  * Returns 0 on success or nonzero for error.
1006  */
1007 int msiv_setactive(struct sdm_userdata *u, char *script_name) {
1008         int ok = 0;
1009         struct sdm_script *s;
1010
1011         /* First see if the supplied value is ok */
1012
1013         if (IsEmptyStr(script_name)) {
1014                 ok = 1;
1015         }
1016         else {
1017                 for (s=u->first_script; s!=NULL; s=s->next) {
1018                         if (!strcasecmp(s->script_name, script_name)) {
1019                                 ok = 1;
1020                         }
1021                 }
1022         }
1023
1024         if (!ok) return(-1);
1025
1026         /* Now set the active script */
1027         for (s=u->first_script; s!=NULL; s=s->next) {
1028                 if (!strcasecmp(s->script_name, script_name)) {
1029                         s->script_active = 1;
1030                 }
1031                 else {
1032                         s->script_active = 0;
1033                 }
1034         }
1035         
1036         return(0);
1037 }
1038
1039
1040 /*
1041  * Fetch a script by name.
1042  *
1043  * Returns NULL if the named script was not found, or a pointer to the script
1044  * if it was found.   NOTE: the caller does *not* own the memory returned by
1045  * this function.  Copy it if you need to keep it.
1046  */
1047 char *msiv_getscript(struct sdm_userdata *u, char *script_name) {
1048         struct sdm_script *s;
1049
1050         for (s=u->first_script; s!=NULL; s=s->next) {
1051                 if (!strcasecmp(s->script_name, script_name)) {
1052                         if (s->script_content != NULL) {
1053                                 return (s->script_content);
1054                         }
1055                 }
1056         }
1057
1058         return(NULL);
1059 }
1060
1061
1062 /*
1063  * Delete a script by name.
1064  *
1065  * Returns 0 if the script was deleted.
1066  *       1 if the script was not found.
1067  *       2 if the script cannot be deleted because it is active.
1068  */
1069 int msiv_deletescript(struct sdm_userdata *u, char *script_name) {
1070         struct sdm_script *s = NULL;
1071         struct sdm_script *script_to_delete = NULL;
1072
1073         for (s=u->first_script; s!=NULL; s=s->next) {
1074                 if (!strcasecmp(s->script_name, script_name)) {
1075                         script_to_delete = s;
1076                         if (s->script_active) {
1077                                 return(2);
1078                         }
1079                 }
1080         }
1081
1082         if (script_to_delete == NULL) return(1);
1083
1084         if (u->first_script == script_to_delete) {
1085                 u->first_script = u->first_script->next;
1086         }
1087         else for (s=u->first_script; s!=NULL; s=s->next) {
1088                 if (s->next == script_to_delete) {
1089                         s->next = s->next->next;
1090                 }
1091         }
1092
1093         free(script_to_delete->script_content);
1094         free(script_to_delete);
1095         return(0);
1096 }
1097
1098
1099 /*
1100  * Add or replace a new script.  
1101  * NOTE: after this function returns, "u" owns the memory that "script_content"
1102  * was pointing to.
1103  */
1104 void msiv_putscript(struct sdm_userdata *u, char *script_name, char *script_content) {
1105         int replaced = 0;
1106         struct sdm_script *s, *sptr;
1107
1108         for (s=u->first_script; s!=NULL; s=s->next) {
1109                 if (!strcasecmp(s->script_name, script_name)) {
1110                         if (s->script_content != NULL) {
1111                                 free(s->script_content);
1112                         }
1113                         s->script_content = script_content;
1114                         replaced = 1;
1115                 }
1116         }
1117
1118         if (replaced == 0) {
1119                 sptr = malloc(sizeof(struct sdm_script));
1120                 safestrncpy(sptr->script_name, script_name, sizeof sptr->script_name);
1121                 sptr->script_content = script_content;
1122                 sptr->script_active = 0;
1123                 sptr->next = u->first_script;
1124                 u->first_script = sptr;
1125         }
1126 }
1127
1128
1129
1130 /*
1131  * Citadel protocol to manage sieve scripts.
1132  * This is basically a simplified (read: doesn't resemble IMAP) version
1133  * of the 'managesieve' protocol.
1134  */
1135 void cmd_msiv(char *argbuf) {
1136         char subcmd[256];
1137         struct sdm_userdata u;
1138         char script_name[256];
1139         char *script_content = NULL;
1140         struct sdm_script *s;
1141         int i;
1142         int changes_made = 0;
1143
1144         memset(&u, 0, sizeof(struct sdm_userdata));
1145
1146         if (CtdlAccessCheck(ac_logged_in)) return;
1147         extract_token(subcmd, argbuf, 0, '|', sizeof subcmd);
1148         msiv_load(&u);
1149
1150         if (!strcasecmp(subcmd, "putscript")) {
1151                 extract_token(script_name, argbuf, 1, '|', sizeof script_name);
1152                 if (!IsEmptyStr(script_name)) {
1153                         cprintf("%d Transmit script now\n", SEND_LISTING);
1154                         script_content = CtdlReadMessageBody("000", config.c_maxmsglen, NULL, 0, 0);
1155                         msiv_putscript(&u, script_name, script_content);
1156                         changes_made = 1;
1157                 }
1158                 else {
1159                         cprintf("%d Invalid script name.\n", ERROR + ILLEGAL_VALUE);
1160                 }
1161         }       
1162         
1163         else if (!strcasecmp(subcmd, "listscripts")) {
1164                 cprintf("%d Scripts:\n", LISTING_FOLLOWS);
1165                 for (s=u.first_script; s!=NULL; s=s->next) {
1166                         if (s->script_content != NULL) {
1167                                 cprintf("%s|%d|\n", s->script_name, s->script_active);
1168                         }
1169                 }
1170                 cprintf("000\n");
1171         }
1172
1173         else if (!strcasecmp(subcmd, "setactive")) {
1174                 extract_token(script_name, argbuf, 1, '|', sizeof script_name);
1175                 if (msiv_setactive(&u, script_name) == 0) {
1176                         cprintf("%d ok\n", CIT_OK);
1177                         changes_made = 1;
1178                 }
1179                 else {
1180                         cprintf("%d Script '%s' does not exist.\n",
1181                                 ERROR + ILLEGAL_VALUE,
1182                                 script_name
1183                         );
1184                 }
1185         }
1186
1187         else if (!strcasecmp(subcmd, "getscript")) {
1188                 extract_token(script_name, argbuf, 1, '|', sizeof script_name);
1189                 script_content = msiv_getscript(&u, script_name);
1190                 if (script_content != NULL) {
1191                         int script_len;
1192
1193                         cprintf("%d Script:\n", LISTING_FOLLOWS);
1194                         script_len = strlen(script_content);
1195                         client_write(script_content, script_len);
1196                         if (script_content[script_len-1] != '\n') {
1197                                 cprintf("\n");
1198                         }
1199                         cprintf("000\n");
1200                 }
1201                 else {
1202                         cprintf("%d Invalid script name.\n", ERROR + ILLEGAL_VALUE);
1203                 }
1204         }
1205
1206         else if (!strcasecmp(subcmd, "deletescript")) {
1207                 extract_token(script_name, argbuf, 1, '|', sizeof script_name);
1208                 i = msiv_deletescript(&u, script_name);
1209                 if (i == 0) {
1210                         cprintf("%d ok\n", CIT_OK);
1211                         changes_made = 1;
1212                 }
1213                 else if (i == 1) {
1214                         cprintf("%d Script '%s' does not exist.\n",
1215                                 ERROR + ILLEGAL_VALUE,
1216                                 script_name
1217                         );
1218                 }
1219                 else if (i == 2) {
1220                         cprintf("%d Script '%s' is active and cannot be deleted.\n",
1221                                 ERROR + ILLEGAL_VALUE,
1222                                 script_name
1223                         );
1224                 }
1225                 else {
1226                         cprintf("%d unknown error\n", ERROR);
1227                 }
1228         }
1229
1230         else {
1231                 cprintf("%d Invalid subcommand\n", ERROR + CMD_NOT_SUPPORTED);
1232         }
1233
1234         msiv_store(&u, changes_made);
1235 }
1236
1237
1238
1239 void ctdl_sieve_init(void) {
1240         char *cred = NULL;
1241         sieve2_context_t *sieve2_context = NULL;
1242         int res;
1243
1244         /*
1245          *      We don't really care about dumping the entire credits to the log
1246          *      every time the server is initialized.  The documentation will suffice
1247          *      for that purpose.  We are making a call to sieve2_credits() in order
1248          *      to demonstrate that we have successfully linked in to libsieve.
1249          */
1250         cred = strdup(sieve2_credits());
1251         if (cred == NULL) return;
1252
1253         if (strlen(cred) > 60) {
1254                 strcpy(&cred[55], "...");
1255         }
1256
1257         lprintf(CTDL_INFO, "%s\n",cred);
1258         free(cred);
1259
1260         /* Briefly initialize a Sieve parser instance just so we can list the
1261          * extensions that are available.
1262          */
1263         res = sieve2_alloc(&sieve2_context);
1264         if (res != SIEVE2_OK) {
1265                 lprintf(CTDL_CRIT, "sieve2_alloc() returned %d: %s\n", res, sieve2_errstr(res));
1266                 return;
1267         }
1268
1269         res = sieve2_callbacks(sieve2_context, ctdl_sieve_callbacks);
1270         if (res != SIEVE2_OK) {
1271                 lprintf(CTDL_CRIT, "sieve2_callbacks() returned %d: %s\n", res, sieve2_errstr(res));
1272                 goto BAIL;
1273         }
1274
1275         msiv_extensions = strdup(sieve2_listextensions(sieve2_context));
1276         lprintf(CTDL_INFO, "Extensions: %s\n", msiv_extensions);
1277
1278 BAIL:   res = sieve2_free(&sieve2_context);
1279         if (res != SIEVE2_OK) {
1280                 lprintf(CTDL_CRIT, "sieve2_free() returned %d: %s\n", res, sieve2_errstr(res));
1281         }
1282
1283 }
1284
1285 int serv_sieve_room(struct ctdlroom *room)
1286 {
1287         if (!strcasecmp(&room->QRname[11], MAILROOM)) {
1288                 sieve_queue_room(room);
1289         }
1290         return 0;
1291 }
1292
1293 #endif  /* HAVE_LIBSIEVE */
1294
1295 CTDL_MODULE_INIT(sieve)
1296 {
1297         if (!threading)
1298         {
1299 #ifdef HAVE_LIBSIEVE
1300
1301                 ctdl_sieve_init();
1302                 CtdlRegisterProtoHook(cmd_msiv, "MSIV", "Manage Sieve scripts");
1303
1304                 CtdlRegisterRoomHook(serv_sieve_room);
1305
1306                 CtdlRegisterSessionHook(perform_sieve_processing, EVT_HOUSE);
1307
1308 #else   /* HAVE_LIBSIEVE */
1309
1310                 lprintf(CTDL_INFO, "This server is missing libsieve.  Mailbox filtering will be disabled.\n");
1311
1312 #endif  /* HAVE_LIBSIEVE */
1313         }
1314         
1315         /* return our Subversion id for the Log */
1316         return "$Id$";
1317 }
1318