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