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