Removed some debugging messages we no longer need.
[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 "tools.h"
46
47 #ifdef HAVE_LIBSIEVE
48
49 #include "serv_sieve.h"
50
51 struct RoomProcList *sieve_list = NULL;
52
53
54 /*
55  * Callback function to send libSieve trace messages to Citadel log facility
56  * Set ctdl_libsieve_debug=1 to see extremely verbose libSieve trace
57  */
58 int ctdl_debug(sieve2_context_t *s, void *my)
59 {
60         static int ctdl_libsieve_debug = 0;
61
62         if (ctdl_libsieve_debug) {
63                 lprintf(CTDL_DEBUG, "Sieve: level [%d] module [%s] file [%s] function [%s]\n",
64                         sieve2_getvalue_int(s, "level"),
65                         sieve2_getvalue_string(s, "module"),
66                         sieve2_getvalue_string(s, "file"),
67                         sieve2_getvalue_string(s, "function"));
68                 lprintf(CTDL_DEBUG, "       message [%s]\n",
69                         sieve2_getvalue_string(s, "message"));
70         }
71         return SIEVE2_OK;
72 }
73
74
75 /*
76  * Callback function to log script parsing errors
77  */
78 int ctdl_errparse(sieve2_context_t *s, void *my)
79 {
80         lprintf(CTDL_WARNING, "Error in script, line %d: %s\n",
81                 sieve2_getvalue_int(s, "lineno"),
82                 sieve2_getvalue_string(s, "message")
83         );
84         return SIEVE2_OK;
85 }
86
87
88 /*
89  * Callback function to log script execution errors
90  */
91 int ctdl_errexec(sieve2_context_t *s, void *my)
92 {
93         lprintf(CTDL_WARNING, "Error executing script: %s\n",
94                 sieve2_getvalue_string(s, "message")
95         );
96         return SIEVE2_OK;
97 }
98
99
100 /*
101  * Callback function to redirect a message to a different folder
102  */
103 int ctdl_redirect(sieve2_context_t *s, void *my)
104 {
105         struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
106         struct CtdlMessage *msg = NULL;
107         struct recptypes *valid = NULL;
108         char recp[256];
109
110         safestrncpy(recp, sieve2_getvalue_string(s, "address"), sizeof recp);
111
112         lprintf(CTDL_DEBUG, "Action is REDIRECT, recipient <%s>\n", recp);
113
114         valid = validate_recipients(recp);
115         if (valid == NULL) {
116                 lprintf(CTDL_WARNING, "REDIRECT failed: bad recipient <%s>\n", recp);
117                 return SIEVE2_ERROR_BADARGS;
118         }
119         if (valid->num_error > 0) {
120                 lprintf(CTDL_WARNING, "REDIRECT failed: bad recipient <%s>\n", recp);
121                 free(valid);
122                 return SIEVE2_ERROR_BADARGS;
123         }
124
125         msg = CtdlFetchMessage(cs->msgnum, 1);
126         if (msg == NULL) {
127                 lprintf(CTDL_WARNING, "REDIRECT failed: unable to fetch msg %ld\n", cs->msgnum);
128                 free(valid);
129                 return SIEVE2_ERROR_BADARGS;
130         }
131
132         CtdlSubmitMsg(msg, valid, NULL);
133         cs->actiontaken = 1;
134         free(valid);
135         CtdlFreeMessage(msg);
136         return SIEVE2_OK;
137 }
138
139
140 /*
141  * Callback function to indicate that a message *will* be kept in the inbox
142  */
143 int ctdl_keep(sieve2_context_t *s, void *my)
144 {
145         struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
146         
147         lprintf(CTDL_DEBUG, "Action is KEEP\n");
148
149         cs->keep = 1;
150         cs->actiontaken = 1;
151         return SIEVE2_OK;
152 }
153
154
155 /*
156  * Callback function to file a message into a different mailbox
157  */
158 int ctdl_fileinto(sieve2_context_t *s, void *my)
159 {
160         struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
161         const char *dest_folder = sieve2_getvalue_string(s, "mailbox");
162         int c;
163         char foldername[256];
164         char original_room_name[ROOMNAMELEN];
165
166         lprintf(CTDL_DEBUG, "Action is FILEINTO, destination is <%s>\n", dest_folder);
167
168         /* FILEINTO 'INBOX' is the same thing as KEEP */
169         if ( (!strcasecmp(dest_folder, "INBOX")) || (!strcasecmp(dest_folder, MAILROOM)) ) {
170                 cs->keep = 1;
171                 cs->actiontaken = 1;
172                 return SIEVE2_OK;
173         }
174
175         /* Remember what room we came from */
176         safestrncpy(original_room_name, CC->room.QRname, sizeof original_room_name);
177
178         /* First try a mailbox name match (check personal mail folders first) */
179         snprintf(foldername, sizeof foldername, "%010ld.%s", cs->usernum, dest_folder);
180         c = getroom(&CC->room, foldername);
181
182         /* Then a regular room name match (public and private rooms) */
183         if (c < 0) {
184                 safestrncpy(foldername, dest_folder, sizeof foldername);
185                 c = getroom(&CC->room, foldername);
186         }
187
188         if (c < 0) {
189                 lprintf(CTDL_WARNING, "FILEINTO failed: target <%s> does not exist\n", dest_folder);
190                 return SIEVE2_ERROR_BADARGS;
191         }
192
193         /* Yes, we actually have to go there */
194         usergoto(NULL, 0, 0, NULL, NULL);
195
196         c = CtdlSaveMsgPointersInRoom(NULL, &cs->msgnum, 1, 0, NULL);
197
198         /* Go back to the room we came from */
199         if (strcasecmp(original_room_name, CC->room.QRname)) {
200                 usergoto(original_room_name, 0, 0, NULL, NULL);
201         }
202
203         if (c == 0) {
204                 cs->actiontaken = 1;
205                 return SIEVE2_OK;
206         }
207         else {
208                 return SIEVE2_ERROR_BADARGS;
209         }
210 }
211
212
213 /*
214  * Callback function to indicate that a message should be rejected
215  * FIXME implement this
216  */
217 int ctdl_reject(sieve2_context_t *s, void *my)
218 {
219         lprintf(CTDL_DEBUG, "Action is REJECT\n");
220         return SIEVE2_ERROR_UNSUPPORTED;
221 }
222
223
224 /*
225  * Callback function to indicate that the user should be notified
226  * FIXME implement this
227  */
228 int ctdl_notify(sieve2_context_t *s, void *my)
229 {
230         lprintf(CTDL_DEBUG, "Action is NOTIFY\n");
231         return SIEVE2_ERROR_UNSUPPORTED;
232 }
233
234
235 /*
236  * Callback function to indicate that a vacation message should be generated
237  * FIXME implement this
238  */
239 int ctdl_vacation(sieve2_context_t *s, void *my)
240 {
241         lprintf(CTDL_DEBUG, "Action is VACATION\n");
242         return SIEVE2_ERROR_UNSUPPORTED;
243 }
244
245
246 /*
247  * Callback function to parse addresses per local system convention
248  * FIXME implement this
249  */
250 int ctdl_getsubaddress(sieve2_context_t *s, void *my)
251 {
252         return SIEVE2_ERROR_UNSUPPORTED;
253 }
254
255
256 /*
257  * Callback function to parse message envelope
258  * FIXME implement this
259  */
260 int ctdl_getenvelope(sieve2_context_t *s, void *my)
261 {
262         return SIEVE2_ERROR_UNSUPPORTED;
263 }
264
265
266 /*
267  * Callback function to fetch message body
268  * FIXME implement this
269  */
270 int ctdl_getbody(sieve2_context_t *s, void *my)
271 {
272         return SIEVE2_ERROR_UNSUPPORTED;
273 }
274
275
276 /*
277  * Callback function to fetch message size
278  * FIXME implement this
279  */
280 int ctdl_getsize(sieve2_context_t *s, void *my)
281 {
282         return SIEVE2_ERROR_UNSUPPORTED;
283 }
284
285
286 /*
287  * Callback function to indicate that a message should be discarded.
288  */
289 int ctdl_discard(sieve2_context_t *s, void *my)
290 {
291         struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
292
293         lprintf(CTDL_DEBUG, "Action is DISCARD\n");
294
295         /* Yes, this is really all there is to it.  Since we are not setting "keep" to 1,
296          * the message will be discarded because "some other action" was successfully taken.
297          */
298         cs->actiontaken = 1;
299         return SIEVE2_OK;
300 }
301
302
303
304 /*
305  * Callback function to retrieve the sieve script
306  */
307 int ctdl_getscript(sieve2_context_t *s, void *my) {
308         struct sdm_script *sptr;
309         struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
310
311         for (sptr=cs->u->first_script; sptr!=NULL; sptr=sptr->next) {
312                 if (sptr->script_active > 0) {
313                         lprintf(CTDL_DEBUG, "ctdl_getscript() is using script '%s'\n", sptr->script_name);
314                         sieve2_setvalue_string(s, "script", sptr->script_content);
315                         return SIEVE2_OK;
316                 }
317         }
318                 
319         lprintf(CTDL_DEBUG, "ctdl_getscript() found no active script\n");
320         return SIEVE2_ERROR_GETSCRIPT;
321 }
322
323 /*
324  * Callback function to retrieve message headers
325  */
326 int ctdl_getheaders(sieve2_context_t *s, void *my) {
327
328         struct ctdl_sieve *cs = (struct ctdl_sieve *)my;
329
330         lprintf(CTDL_DEBUG, "ctdl_getheaders() was called\n");
331
332         sieve2_setvalue_string(s, "allheaders", cs->rfc822headers);
333         return SIEVE2_OK;
334 }
335
336
337
338 /*
339  * Add a room to the list of those rooms which potentially require sieve processing
340  */
341 void sieve_queue_room(struct ctdlroom *which_room) {
342         struct RoomProcList *ptr;
343
344         ptr = (struct RoomProcList *) malloc(sizeof (struct RoomProcList));
345         if (ptr == NULL) return;
346
347         safestrncpy(ptr->name, which_room->QRname, sizeof ptr->name);
348         begin_critical_section(S_SIEVELIST);
349         ptr->next = sieve_list;
350         sieve_list = ptr;
351         end_critical_section(S_SIEVELIST);
352 }
353
354
355
356 /*
357  * Perform sieve processing for one message (called by sieve_do_room() for each message)
358  */
359 void sieve_do_msg(long msgnum, void *userdata) {
360         struct sdm_userdata *u = (struct sdm_userdata *) userdata;
361         sieve2_context_t *sieve2_context = u->sieve2_context;
362         struct ctdl_sieve my;
363         int res;
364
365         lprintf(CTDL_DEBUG, "Performing sieve processing on msg <%ld>\n", msgnum);
366
367         CC->redirect_buffer = malloc(SIZ);
368         CC->redirect_len = 0;
369         CC->redirect_alloc = SIZ;
370         CtdlOutputMsg(msgnum, MT_RFC822, HEADERS_ONLY, 0, 1, NULL);
371         my.rfc822headers = CC->redirect_buffer;
372         CC->redirect_buffer = NULL;
373         CC->redirect_len = 0;
374         CC->redirect_alloc = 0;
375
376         my.keep = 0;            /* Don't keep a copy in the inbox unless a callback tells us to do so */
377         my.actiontaken = 0;     /* Keep track of whether any actions were successfully taken */
378         my.usernum = atol(CC->room.QRname);     /* Keep track of the owner of the room's namespace */
379         my.msgnum = msgnum;     /* Keep track of the message number in our local store */
380         my.u = u;               /* Hand off a pointer to the rest of this info */
381
382         sieve2_setvalue_string(sieve2_context, "allheaders", my.rfc822headers);
383         
384         lprintf(CTDL_DEBUG, "Calling sieve2_execute()\n");
385         res = sieve2_execute(sieve2_context, &my);
386         if (res != SIEVE2_OK) {
387                 lprintf(CTDL_CRIT, "sieve2_execute() returned %d: %s\n", res, sieve2_errstr(res));
388         }
389
390         free(my.rfc822headers);
391         my.rfc822headers = NULL;
392
393         /*
394          * Delete the message from the inbox unless either we were told not to, or
395          * if no other action was successfully taken.
396          */
397         if ( (!my.keep) && (my.actiontaken) ) {
398                 lprintf(CTDL_DEBUG, "keep is 0 -- deleting message from inbox\n");
399                 CtdlDeleteMessages(CC->room.QRname, &msgnum, 1, "", 0);
400         }
401
402         lprintf(CTDL_DEBUG, "Completed sieve processing on msg <%ld>\n", msgnum);
403         u->lastproc = msgnum;
404
405         return;
406 }
407
408
409
410 /*
411  * Given the on-disk representation of our Sieve config, load
412  * it into an in-memory data structure.
413  */
414 void parse_sieve_config(char *conf, struct sdm_userdata *u) {
415         char *ptr;
416         char *c;
417         char keyword[256];
418         struct sdm_script *sptr;
419
420         ptr = conf;
421         while (c = ptr, ptr = bmstrcasestr(ptr, CTDLSIEVECONFIGSEPARATOR), ptr != NULL) {
422                 *ptr = 0;
423                 ptr += strlen(CTDLSIEVECONFIGSEPARATOR);
424
425                 extract_token(keyword, c, 0, '|', sizeof keyword);
426
427                 if (!strcasecmp(keyword, "lastproc")) {
428                         u->lastproc = extract_long(c, 1);
429                 }
430
431                 else if (!strcasecmp(keyword, "script")) {
432                         sptr = malloc(sizeof(struct sdm_script));
433                         extract_token(sptr->script_name, c, 1, '|', sizeof sptr->script_name);
434                         sptr->script_active = extract_int(c, 2);
435                         remove_token(c, 0, '|');
436                         remove_token(c, 0, '|');
437                         remove_token(c, 0, '|');
438                         sptr->script_content = strdup(c);
439                         sptr->next = u->first_script;
440                         u->first_script = sptr;
441                 }
442
443                 /* ignore unknown keywords */
444         }
445 }
446
447 /*
448  * We found the Sieve configuration for this user.
449  * Now do something with it.
450  */
451 void get_sieve_config_backend(long msgnum, void *userdata) {
452         struct sdm_userdata *u = (struct sdm_userdata *) userdata;
453         struct CtdlMessage *msg;
454         char *conf;
455
456         u->config_msgnum = msgnum;
457         msg = CtdlFetchMessage(msgnum, 1);
458         if (msg == NULL) {
459                 u->config_msgnum = (-1) ;
460                 return;
461         }
462
463         conf = msg->cm_fields['M'];
464         msg->cm_fields['M'] = NULL;
465         CtdlFreeMessage(msg);
466
467         if (conf != NULL) {
468                 parse_sieve_config(conf, u);
469                 free(conf);
470         }
471
472 }
473
474
475 /* 
476  * Write our citadel sieve config back to disk
477  */
478 void rewrite_ctdl_sieve_config(struct sdm_userdata *u) {
479         char *text;
480         struct sdm_script *sptr;
481
482
483         text = malloc(1024);
484         snprintf(text, 1024,
485                 "Content-type: application/x-citadel-sieve-config\n"
486                 "\n"
487                 CTDLSIEVECONFIGSEPARATOR
488                 "lastproc|%ld"
489                 CTDLSIEVECONFIGSEPARATOR
490         ,
491                 u->lastproc
492         );
493
494         while (u->first_script != NULL) {
495                 text = realloc(text, strlen(text) + strlen(u->first_script->script_content) + 256);
496                 sprintf(&text[strlen(text)], "script|%s|%d|%s" CTDLSIEVECONFIGSEPARATOR,
497                         u->first_script->script_name,
498                         u->first_script->script_active,
499                         u->first_script->script_content
500                 );
501                 sptr = u->first_script;
502                 u->first_script = u->first_script->next;
503                 free(sptr->script_content);
504                 free(sptr);
505         }
506
507         /* Save the config */
508         quickie_message("Citadel", NULL, u->config_roomname,
509                         text,
510                         4,
511                         "Sieve configuration"
512         );
513
514         /* And delete the old one */
515         if (u->config_msgnum > 0) {
516                 CtdlDeleteMessages(u->config_roomname, &u->config_msgnum, 1, "", 0);
517         }
518
519 }
520
521
522
523 /*
524  * Perform sieve processing for a single room
525  */
526 void sieve_do_room(char *roomname) {
527         
528         struct sdm_userdata u;
529         sieve2_context_t *sieve2_context = NULL;        /* Context for sieve parser */
530         int res;                                        /* Return code from libsieve calls */
531         long orig_lastproc = 0;
532
533         memset(&u, 0, sizeof u);
534
535         /*
536          * This is our callback registration table for libSieve.
537          */
538         sieve2_callback_t ctdl_sieve_callbacks[] = {
539                 { SIEVE2_ACTION_REJECT,         ctdl_reject             },
540                 { SIEVE2_ACTION_NOTIFY,         ctdl_notify             },
541                 { SIEVE2_ACTION_VACATION,       ctdl_vacation           },
542                 { SIEVE2_ERRCALL_PARSE,         ctdl_errparse           },
543                 { SIEVE2_ERRCALL_RUNTIME,       ctdl_errexec            },
544                 { SIEVE2_ACTION_FILEINTO,       ctdl_fileinto           },
545                 { SIEVE2_ACTION_REDIRECT,       ctdl_redirect           },
546                 { SIEVE2_ACTION_DISCARD,        ctdl_discard            },
547                 { SIEVE2_ACTION_KEEP,           ctdl_keep               },
548                 { SIEVE2_SCRIPT_GETSCRIPT,      ctdl_getscript          },
549                 { SIEVE2_DEBUG_TRACE,           ctdl_debug              },
550                 { SIEVE2_MESSAGE_GETALLHEADERS, ctdl_getheaders         },
551                 { SIEVE2_MESSAGE_GETSUBADDRESS, ctdl_getsubaddress      },
552                 { SIEVE2_MESSAGE_GETENVELOPE,   ctdl_getenvelope        },
553                 { SIEVE2_MESSAGE_GETBODY,       ctdl_getbody            },
554                 { SIEVE2_MESSAGE_GETSIZE,       ctdl_getsize            },
555                 { 0 }
556         };
557
558         /* See if the user who owns this 'mailbox' has any Sieve scripts that
559          * require execution.
560          */
561         snprintf(u.config_roomname, sizeof u.config_roomname, "%010ld.%s", atol(roomname), SIEVERULES);
562         if (getroom(&CC->room, u.config_roomname) != 0) {
563                 lprintf(CTDL_DEBUG, "<%s> does not exist.  No processing is required.\n", u.config_roomname);
564                 return;
565         }
566
567         /*
568          * Find the sieve scripts and control record and do something
569          */
570         u.config_msgnum = (-1);
571         CtdlForEachMessage(MSGS_LAST, 1, NULL, SIEVECONFIG, NULL,
572                 get_sieve_config_backend, (void *)&u );
573
574         if (u.config_msgnum < 0) {
575                 lprintf(CTDL_DEBUG, "No Sieve rules exist.  No processing is required.\n");
576                 return;
577         }
578
579         lprintf(CTDL_DEBUG, "Rules found.  Performing Sieve processing for <%s>\n", roomname);
580
581         if (getroom(&CC->room, roomname) != 0) {
582                 lprintf(CTDL_CRIT, "ERROR: cannot load <%s>\n", roomname);
583                 return;
584         }
585
586         /* Initialize the Sieve parser */
587         
588         res = sieve2_alloc(&sieve2_context);
589         if (res != SIEVE2_OK) {
590                 lprintf(CTDL_CRIT, "sieve2_alloc() returned %d: %s\n", res, sieve2_errstr(res));
591                 return;
592         }
593
594         res = sieve2_callbacks(sieve2_context, ctdl_sieve_callbacks);
595         if (res != SIEVE2_OK) {
596                 lprintf(CTDL_CRIT, "sieve2_callbacks() returned %d: %s\n", res, sieve2_errstr(res));
597                 goto BAIL;
598         }
599
600         /* Validate the script */
601
602         struct ctdl_sieve my;           /* dummy ctdl_sieve struct just to pass "u" slong */
603         memset(&my, 0, sizeof my);
604         my.u = &u;
605         res = sieve2_validate(sieve2_context, &my);
606         if (res != SIEVE2_OK) {
607                 lprintf(CTDL_CRIT, "sieve2_validate() returned %d: %s\n", res, sieve2_errstr(res));
608                 goto BAIL;
609         }
610
611         /* Do something useful */
612         u.sieve2_context = sieve2_context;
613         orig_lastproc = u.lastproc;
614         CtdlForEachMessage(MSGS_GT, u.lastproc, NULL, NULL, NULL,
615                 sieve_do_msg,
616                 (void *) &u
617         );
618
619 BAIL:
620         res = sieve2_free(&sieve2_context);
621         if (res != SIEVE2_OK) {
622                 lprintf(CTDL_CRIT, "sieve2_free() returned %d: %s\n", res, sieve2_errstr(res));
623         }
624
625         /* Rewrite the config if we have to */
626         if (u.lastproc > orig_lastproc) {
627                 rewrite_ctdl_sieve_config(&u);
628         }
629 }
630
631
632 /*
633  * Perform sieve processing for all rooms which require it
634  */
635 void perform_sieve_processing(void) {
636         struct RoomProcList *ptr = NULL;
637
638         if (sieve_list != NULL) {
639                 lprintf(CTDL_DEBUG, "Begin Sieve processing\n");
640                 while (sieve_list != NULL) {
641                         char spoolroomname[ROOMNAMELEN];
642                         safestrncpy(spoolroomname, sieve_list->name, sizeof spoolroomname);
643                         begin_critical_section(S_SIEVELIST);
644
645                         /* pop this record off the list */
646                         ptr = sieve_list;
647                         sieve_list = sieve_list->next;
648                         free(ptr);
649
650                         /* invalidate any duplicate entries to prevent double processing */
651                         for (ptr=sieve_list; ptr!=NULL; ptr=ptr->next) {
652                                 if (!strcasecmp(ptr->name, spoolroomname)) {
653                                         ptr->name[0] = 0;
654                                 }
655                         }
656
657                         end_critical_section(S_SIEVELIST);
658                         if (spoolroomname[0] != 0) {
659                                 sieve_do_room(spoolroomname);
660                         }
661                 }
662         }
663 }
664
665
666 void msiv_load(struct sdm_userdata *u) {
667         char hold_rm[ROOMNAMELEN];
668
669         strcpy(hold_rm, CC->room.QRname);       /* save current room */
670
671         /* Take a spin through the user's personal address book */
672         if (getroom(&CC->room, SIEVERULES) == 0) {
673         
674                 u->config_msgnum = (-1);
675                 strcpy(u->config_roomname, CC->room.QRname);
676                 CtdlForEachMessage(MSGS_LAST, 1, NULL, SIEVECONFIG, NULL,
677                         get_sieve_config_backend, (void *)u );
678
679         }
680
681         if (strcmp(CC->room.QRname, hold_rm)) {
682                 getroom(&CC->room, hold_rm);    /* return to saved room */
683         }
684 }
685
686 void msiv_store(struct sdm_userdata *u) {
687         rewrite_ctdl_sieve_config(u);
688 }
689
690
691 /*
692  * Select the active script.
693  * (Set script_name to an empty string to disable all scripts)
694  * 
695  * Returns 0 on success or nonzero for error.
696  */
697 int msiv_setactive(struct sdm_userdata *u, char *script_name) {
698         int ok = 0;
699         struct sdm_script *s;
700
701         /* First see if the supplied value is ok */
702
703         if (strlen(script_name) == 0) {
704                 ok = 1;
705         }
706         else {
707                 for (s=u->first_script; s!=NULL; s=s->next) {
708                         if (!strcasecmp(s->script_name, script_name)) {
709                                 ok = 1;
710                         }
711                 }
712         }
713
714         if (!ok) return(-1);
715
716         /* Now set the active script */
717         for (s=u->first_script; s!=NULL; s=s->next) {
718                 if (!strcasecmp(s->script_name, script_name)) {
719                         s->script_active = 1;
720                 }
721                 else {
722                         s->script_active = 0;
723                 }
724         }
725         
726         return(0);
727 }
728
729
730 /*
731  * Fetch a script by name.
732  *
733  * Returns NULL if the named script was not found, or a pointer to the script
734  * if it was found.   NOTE: the caller does *not* own the memory returned by
735  * this function.  Copy it if you need to keep it.
736  */
737 char *msiv_getscript(struct sdm_userdata *u, char *script_name) {
738         struct sdm_script *s;
739
740         for (s=u->first_script; s!=NULL; s=s->next) {
741                 if (!strcasecmp(s->script_name, script_name)) {
742                         if (s->script_content != NULL) {
743                                 return (s->script_content);
744                         }
745                 }
746         }
747
748         return(NULL);
749 }
750
751
752
753 /*
754  * Add or replace a new script.  
755  * NOTE: after this function returns, "u" owns the memory that "script_content"
756  * was pointing to.
757  */
758 void msiv_putscript(struct sdm_userdata *u, char *script_name, char *script_content) {
759         int replaced = 0;
760         struct sdm_script *s, *sptr;
761
762         for (s=u->first_script; s!=NULL; s=s->next) {
763                 if (!strcasecmp(s->script_name, script_name)) {
764                         if (s->script_content != NULL) {
765                                 free(s->script_content);
766                         }
767                         s->script_content = script_content;
768                         replaced = 1;
769                 }
770         }
771
772         if (replaced == 0) {
773                 sptr = malloc(sizeof(struct sdm_script));
774                 safestrncpy(sptr->script_name, script_name, sizeof sptr->script_name);
775                 sptr->script_content = script_content;
776                 sptr->script_active = 0;
777                 sptr->next = u->first_script;
778                 u->first_script = sptr;
779         }
780 }
781
782
783 /*
784  * Citadel protocol to manage sieve scripts.
785  * This is basically a simplified (read: doesn't resemble IMAP) version
786  * of the 'managesieve' protocol.
787  */
788 void cmd_msiv(char *argbuf) {
789         char subcmd[256];
790         struct sdm_userdata u;
791         char script_name[256];
792         char *script_content = NULL;
793         struct sdm_script *s;
794
795         memset(&u, 0, sizeof(struct sdm_userdata));
796
797         if (CtdlAccessCheck(ac_logged_in)) return;
798         extract_token(subcmd, argbuf, 0, '|', sizeof subcmd);
799         msiv_load(&u);
800
801         if (!strcasecmp(subcmd, "putscript")) {
802                 extract_token(script_name, argbuf, 1, '|', sizeof script_name);
803                 if (strlen(script_name) > 0) {
804                         cprintf("%d Transmit script now\n", SEND_LISTING);
805                         script_content = CtdlReadMessageBody("000", config.c_maxmsglen, NULL, 0);
806                         msiv_putscript(&u, script_name, script_content);
807                 }
808                 else {
809                         cprintf("%d Invalid script name.\n", ERROR + ILLEGAL_VALUE);
810                 }
811         }       
812         
813         else if (!strcasecmp(subcmd, "listscripts")) {
814                 cprintf("%d Scripts:\n", LISTING_FOLLOWS);
815                 for (s=u.first_script; s!=NULL; s=s->next) {
816                         if (s->script_content != NULL) {
817                                 cprintf("%s|%d|\n", s->script_name, s->script_active);
818                         }
819                 }
820                 cprintf("000\n");
821         }
822
823         else if (!strcasecmp(subcmd, "setactive")) {
824                 extract_token(script_name, argbuf, 1, '|', sizeof script_name);
825                 if (msiv_setactive(&u, script_name) == 0) {
826                         cprintf("%d ok\n", CIT_OK);
827                 }
828                 else {
829                         cprintf("%d Script '%s' does not exist.\n",
830                                 ERROR + ILLEGAL_VALUE,
831                                 script_name
832                         );
833                 }
834         }
835
836         else if (!strcasecmp(subcmd, "getscript")) {
837                 extract_token(script_name, argbuf, 1, '|', sizeof script_name);
838                 script_content = msiv_getscript(&u, script_name);
839                 if (script_content != NULL) {
840                         cprintf("%d Script:\n", SEND_LISTING);
841                         cprintf("%s000\n", script_content);
842                 }
843                 else {
844                         cprintf("%d Invalid script name.\n", ERROR + ILLEGAL_VALUE);
845                 }
846         }
847
848         else if (!strcasecmp(subcmd, "deletescript")) {
849                 /* FIXME */
850         }
851
852         else {
853                 cprintf("%d Invalid subcommand\n", ERROR + CMD_NOT_SUPPORTED);
854         }
855
856         msiv_store(&u);
857 }
858
859
860
861 /*
862  *      We don't really care about dumping the entire credits to the log
863  *      every time the server is initialized.  The documentation will suffice
864  *      for that purpose.  We are making a call to sieve2_credits() in order
865  *      to demonstrate that we have successfully linked in to libsieve.
866  */
867 void log_the_sieve2_credits(void) {
868         char *cred = NULL;
869
870         cred = strdup(sieve2_credits());
871         if (cred == NULL) return;
872
873         if (strlen(cred) > 60) {
874                 strcpy(&cred[55], "...");
875         }
876
877         lprintf(CTDL_INFO, "%s\n",cred);
878         free(cred);
879 }
880
881
882
883 char *serv_sieve_init(void)
884 {
885         log_the_sieve2_credits();
886         CtdlRegisterProtoHook(cmd_msiv, "MSIV", "Manage Sieve scripts");
887         return "$Id: serv_sieve.c 3850 2005-09-13 14:00:24Z ajc $";
888 }
889
890 #else   /* HAVE_LIBSIEVE */
891
892 char *serv_sieve_init(void)
893 {
894         lprintf(CTDL_INFO, "This server is missing libsieve.  Mailbox filtering will be disabled.\n");
895         return "$Id: serv_sieve.c 3850 2005-09-13 14:00:24Z ajc $";
896 }
897
898 #endif  /* HAVE_LIBSIEVE */