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