Removed an unused parameter from CtdlSubmitMsg(). Why was it even there?
[citadel.git] / citadel / modules / inboxrules / serv_inboxrules.c
1 /*
2  * Inbox handling rules
3  *
4  * Copyright (c) 1987-2020 by the citadel.org team
5  *
6  * This program is open source software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 3.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  */
14
15 #include "sysdep.h"
16 #include <stdlib.h>
17 #include <unistd.h>
18 #include <stdio.h>
19 #include <fcntl.h>
20 #include <ctype.h>
21 #include <pwd.h>
22 #include <errno.h>
23 #include <sys/types.h>
24
25 #if TIME_WITH_SYS_TIME
26 # include <sys/time.h>
27 # include <time.h>
28 #else
29 # if HAVE_SYS_TIME_H
30 #  include <sys/time.h>
31 # else
32 #  include <time.h>
33 # endif
34 #endif
35
36 #include <sys/wait.h>
37 #include <string.h>
38 #include <limits.h>
39 #include <libcitadel.h>
40 #include "citadel.h"
41 #include "server.h"
42 #include "citserver.h"
43 #include "support.h"
44 #include "config.h"
45 #include "database.h"
46 #include "msgbase.h"
47 #include "internet_addressing.h"
48 #include "ctdl_module.h"
49
50
51 /*
52  * The next sections are enums and keys that drive the serialize/deserialize functions for the inbox rules/state configuration.
53  */
54
55 // Fields to be compared
56 enum {
57         field_from,             
58         field_tocc,             
59         field_subject,  
60         field_replyto,  
61         field_sender,   
62         field_resentfrom,       
63         field_resentto, 
64         field_envfrom,  
65         field_envto,    
66         field_xmailer,  
67         field_xspamflag,        
68         field_xspamstatus,      
69         field_listid,   
70         field_size,             
71         field_all
72 };
73 char *field_keys[] = {
74         "from",
75         "tocc",
76         "subject",
77         "replyto",
78         "sender",
79         "resentfrom",
80         "resentto",
81         "envfrom",
82         "envto",
83         "xmailer",
84         "xspamflag",
85         "xspamstatus",
86         "listid",
87         "size",
88         "all"
89 };
90
91 // Field comparison operators
92 enum {
93         fcomp_contains,
94         fcomp_notcontains,
95         fcomp_is,
96         fcomp_isnot,
97         fcomp_matches,
98         fcomp_notmatches
99 };
100 char *fcomp_keys[] = {
101         "contains",
102         "notcontains",
103         "is",
104         "isnot",
105         "matches",
106         "notmatches"
107 };
108
109 // Actions
110 enum {
111         action_keep,
112         action_discard,
113         action_reject,
114         action_fileinto,
115         action_redirect,
116         action_vacation
117 };
118 char *action_keys[] = {
119         "keep",
120         "discard",
121         "reject",
122         "fileinto",
123         "redirect",
124         "vacation"
125 };
126
127 // Size comparison operators
128 enum {
129         scomp_larger,
130         scomp_smaller
131 };
132 char *scomp_keys[] = {
133         "larger",
134         "smaller"
135 };
136
137 // Final actions
138 enum {
139         final_continue,
140         final_stop
141 };
142 char *final_keys[] = {
143         "continue",
144         "stop"
145 };
146
147 // This data structure represents ONE inbox rule within the configuration.
148 struct irule {
149         int compared_field;
150         int field_compare_op;
151         char compared_value[128];
152         int size_compare_op;
153         long compared_size;
154         int action;
155         char file_into[ROOMNAMELEN];
156         char redirect_to[1024];
157         char autoreply_message[SIZ];
158         int final_action;
159 };
160
161 // This data structure represents the entire inbox rules configuration AND current state for a single user.
162 struct inboxrules {
163         long lastproc;
164         int num_rules;
165         struct irule *rules;
166 };
167
168
169 // Destructor for 'struct inboxrules'
170 void free_inbox_rules(struct inboxrules *ibr) {
171         free(ibr->rules);
172         free(ibr);
173 }
174
175
176 // Constructor for 'struct inboxrules' that deserializes the configuration from text input.
177 struct inboxrules *deserialize_inbox_rules(char *serialized_rules) {
178         int i;
179
180         if (!serialized_rules) {
181                 return NULL;
182         }
183
184         /* Make a copy of the supplied buffer because we're going to shit all over it with strtok_r() */
185         char *sr = strdup(serialized_rules);
186         if (!sr) {
187                 return NULL;
188         }
189
190         struct inboxrules *ibr = malloc(sizeof(struct inboxrules));
191         if (ibr == NULL) {
192                 return NULL;
193         }
194         memset(ibr, 0, sizeof(struct inboxrules));
195
196         char *token; 
197         char *rest = sr;
198         while ((token = strtok_r(rest, "\n", &rest))) {
199
200                 // For backwards compatibility, "# WEBCIT_RULE" is an alias for "rule".
201                 // Prior to version 930, WebCit converted its rules to Sieve scripts, but saved the rules as comments for later re-editing.
202                 // Now, the rules hidden in the comments become the real rules.
203                 if (!strncasecmp(token, "# WEBCIT_RULE|", 14)) {
204                         strcpy(token, "rule|"); 
205                         strcpy(&token[5], &token[14]);
206                 }
207
208                 // Lines containing actual rules are double-serialized with Base64.  It seemed like a good idea at the time :(
209                 if (!strncasecmp(token, "rule|", 5)) {
210                         remove_token(&token[5], 0, '|');
211                         char *decoded_rule = malloc(strlen(token));
212                         CtdlDecodeBase64(decoded_rule, &token[5], strlen(&token[5]));
213                         ibr->num_rules++;
214                         ibr->rules = realloc(ibr->rules, (sizeof(struct irule) * ibr->num_rules));
215                         struct irule *new_rule = &ibr->rules[ibr->num_rules - 1];
216                         memset(new_rule, 0, sizeof(struct irule));
217
218                         // We have a rule , now parse it
219                         char rtoken[SIZ];
220                         int nt = num_tokens(decoded_rule, '|');
221                         for (int t=0; t<nt; ++t) {
222                                 extract_token(rtoken, decoded_rule, t, '|', sizeof(rtoken));
223                                 striplt(rtoken);
224                                 switch(t) {
225                                         case 1:                                                         // field to compare
226                                                 for (i=0; i<=field_all; ++i) {
227                                                         if (!strcasecmp(rtoken, field_keys[i])) {
228                                                                 new_rule->compared_field = i;
229                                                         }
230                                                 }
231                                                 break;
232                                         case 2:                                                         // field comparison operation
233                                                 for (i=0; i<=fcomp_notmatches; ++i) {
234                                                         if (!strcasecmp(rtoken, fcomp_keys[i])) {
235                                                                 new_rule->field_compare_op = i;
236                                                         }
237                                                 }
238                                                 break;
239                                         case 3:                                                         // field comparison value
240                                                 safestrncpy(new_rule->compared_value, rtoken, sizeof(new_rule->compared_value));
241                                                 break;
242                                         case 4:                                                         // size comparison operation
243                                                 for (i=0; i<=scomp_smaller; ++i) {
244                                                         if (!strcasecmp(rtoken, scomp_keys[i])) {
245                                                                 new_rule->size_compare_op = i;
246                                                         }
247                                                 }
248                                                 break;
249                                         case 5:                                                         // size comparison value
250                                                 new_rule->compared_size = atol(rtoken);
251                                                 break;
252                                         case 6:                                                         // action
253                                                 for (i=0; i<=action_vacation; ++i) {
254                                                         if (!strcasecmp(rtoken, action_keys[i])) {
255                                                                 new_rule->action = i;
256                                                         }
257                                                 }
258                                                 break;
259                                         case 7:                                                         // file into (target room)
260                                                 safestrncpy(new_rule->file_into, rtoken, sizeof(new_rule->file_into));
261                                                 break;
262                                         case 8:                                                         // redirect to (target address)
263                                                 safestrncpy(new_rule->redirect_to, rtoken, sizeof(new_rule->redirect_to));
264                                                 break;
265                                         case 9:                                                         // autoreply message
266                                                 safestrncpy(new_rule->autoreply_message, rtoken, sizeof(new_rule->autoreply_message));
267                                                 break;
268                                         case 10:                                                        // final_action;
269                                                 for (i=0; i<=final_stop; ++i) {
270                                                         if (!strcasecmp(rtoken, final_keys[i])) {
271                                                                 new_rule->final_action = i;
272                                                         }
273                                                 }
274                                                 break;
275                                         default:
276                                                 break;
277                                 }
278                         }
279                         free(decoded_rule);
280                 }
281
282                 // "lastproc" indicates the newest message number in the inbox that was previously processed by our inbox rules.
283                 // This is a legacy location for this value and will only be used if it's the only one present.
284                 else if (!strncasecmp(token, "lastproc|", 5)) {
285                         ibr->lastproc = atol(&token[9]);
286                 }
287
288                 // Lines which do not contain a recognizable token must be IGNORED.  These lines may be left over
289                 // from a previous version and will disappear when we rewrite the config.
290
291         }
292
293         free(sr);               // free our copy of the source buffer that has now been trashed with null bytes...
294         return(ibr);            // and return our complex data type to the caller.
295 }
296
297
298 // Perform the "fileinto" action (save the message in another room)
299 // Returns: 1 or 0 to tell the caller to keep (1) or delete (0) the inbox copy of the message.
300 //
301 int inbox_do_fileinto(struct irule *rule, long msgnum) {
302         char *dest_folder = rule->file_into;
303         char original_room_name[ROOMNAMELEN];
304         char foldername[ROOMNAMELEN];
305         int c;
306
307         // Situations where we want to just keep the message in the inbox:
308         if (
309                 (IsEmptyStr(dest_folder))                       // no destination room was specified
310                 || (!strcasecmp(dest_folder, "INBOX"))          // fileinto inbox is the same as keep
311                 || (!strcasecmp(dest_folder, MAILROOM))         // fileinto "Mail" is the same as keep
312         ) {
313                 return(1);                                      // don't delete the inbox copy if this failed
314         }
315
316         // Remember what room we came from
317         safestrncpy(original_room_name, CC->room.QRname, sizeof original_room_name);
318
319         // First try a mailbox name match (check personal mail folders first)
320         strcpy(foldername, original_room_name);                                 // This keeps the user namespace of the inbox
321         snprintf(&foldername[10], sizeof(foldername)-10, ".%s", dest_folder);   // And this tacks on the target room name
322         c = CtdlGetRoom(&CC->room, foldername);
323
324         // Then a regular room name match (public and private rooms)
325         if (c != 0) {
326                 safestrncpy(foldername, dest_folder, sizeof foldername);
327                 c = CtdlGetRoom(&CC->room, foldername);
328         }
329
330         if (c != 0) {
331                 syslog(LOG_WARNING, "inboxrules: target <%s> does not exist", dest_folder);
332                 return(1);                                      // don't delete the inbox copy if this failed
333         }
334
335         // Yes, we actually have to go there
336         CtdlUserGoto(NULL, 0, 0, NULL, NULL, NULL, NULL);
337
338         c = CtdlSaveMsgPointersInRoom(NULL, &msgnum, 1, 0, NULL, 0);
339
340         // Go back to the room we came from
341         if (strcasecmp(original_room_name, CC->room.QRname)) {
342                 CtdlUserGoto(original_room_name, 0, 0, NULL, NULL, NULL, NULL);
343         }
344
345         return(0);                                              // delete the inbox copy
346 }
347
348
349 // Perform the "redirect" action (divert the message to another email address)
350 // Returns: 1 or 0 to tell the caller to keep (1) or delete (0) the inbox copy of the message.
351 //
352 int inbox_do_redirect(struct irule *rule, long msgnum) {
353         if (IsEmptyStr(rule->redirect_to)) {
354                 syslog(LOG_WARNING, "inboxrules: inbox_do_redirect() invalid recipient <%s>", rule->redirect_to);
355                 return(1);                                      // don't delete the inbox copy if this failed
356         }
357
358         recptypes *valid = validate_recipients(rule->redirect_to, NULL, 0);
359         if (valid == NULL) {
360                 syslog(LOG_WARNING, "inboxrules: inbox_do_redirect() invalid recipient <%s>", rule->redirect_to);
361                 return(1);                                      // don't delete the inbox copy if this failed
362         }
363         if (valid->num_error > 0) {
364                 free_recipients(valid);
365                 syslog(LOG_WARNING, "inboxrules: inbox_do_redirect() invalid recipient <%s>", rule->redirect_to);
366                 return(1);                                      // don't delete the inbox copy if this failed
367         }
368
369         struct CtdlMessage *msg = CtdlFetchMessage(msgnum, 1);
370         if (msg == NULL) {
371                 free_recipients(valid);
372                 syslog(LOG_WARNING, "inboxrules: cannot reload message %ld for forwarding", msgnum);
373                 return(1);                                      // don't delete the inbox copy if this failed
374         }
375
376         CtdlSubmitMsg(msg, valid, NULL);                        // send the message to the new recipient
377         free_recipients(valid);
378         CM_Free(msg);
379         return(0);                                              // delete the inbox copy
380 }
381
382
383 /*
384  * Perform the "reject" action (delete the message, and tell the sender we deleted it)
385  */
386 void inbox_do_reject(struct irule *rule, struct CtdlMessage *msg) {
387         syslog(LOG_DEBUG, "inbox_do_reject: sender: <%s>, reject", msg->cm_fields[erFc822Addr]);
388
389         // If we can't determine who sent the message, reject silently.
390         char *sender;
391         if (!IsEmptyStr(msg->cm_fields[eMessagePath])) {
392                 sender = msg->cm_fields[eMessagePath];
393         }
394         else if (!IsEmptyStr(msg->cm_fields[erFc822Addr])) {
395                 sender = msg->cm_fields[erFc822Addr];
396         }
397         else {
398                 return;
399         }
400
401         // Assemble the reject message.
402         char *reject_text = malloc(strlen(rule->autoreply_message) + 1024);
403         if (reject_text == NULL) {
404                 return;
405         }
406         sprintf(reject_text, 
407                 "Content-type: text/plain\n"
408                 "\n"
409                 "The message was refused by the recipient's mail filtering program.\n"
410                 "The reason given was as follows:\n"
411                 "\n"
412                 "%s\n"
413                 "\n"
414         ,
415                 rule->autoreply_message
416         );
417
418         // Deliver the message
419         quickie_message(
420                 " ",
421                 msg->cm_fields[eenVelopeTo],
422                 sender,
423                 MAILROOM,
424                 reject_text,
425                 FMT_RFC822,
426                 "Delivery status notification"
427         );
428         free(reject_text);
429 }
430
431
432 /*
433  * Perform the "vacation" action (send an automatic response)
434  */
435 void inbox_do_vacation(struct irule *rule, struct CtdlMessage *msg) {
436         syslog(LOG_DEBUG, "inbox_do_vacation: sender: <%s>, vacation", msg->cm_fields[erFc822Addr]);
437
438         // If we can't determine who sent the message, no auto-reply can be sent.
439         char *sender;
440         if (!IsEmptyStr(msg->cm_fields[eMessagePath])) {
441                 sender = msg->cm_fields[eMessagePath];
442         }
443         else if (!IsEmptyStr(msg->cm_fields[erFc822Addr])) {
444                 sender = msg->cm_fields[erFc822Addr];
445         }
446         else {
447                 return;
448         }
449
450         // Avoid repeatedly sending auto-replies to the same correspondent over and over again by creating
451         // a hash of the user, correspondent, and reply text, and hitting the S_USETABLE database.
452         StrBuf *u = NewStrBuf();
453         StrBufPrintf(u, "vacation/%x/%x/%x",
454                 HashLittle(sender, strlen(sender)),
455                 HashLittle(msg->cm_fields[eenVelopeTo], msg->cm_lengths[eenVelopeTo]),
456                 HashLittle(rule->autoreply_message, strlen(rule->autoreply_message))
457         );
458         int already_seen = CheckIfAlreadySeen(u);
459         FreeStrBuf(&u);
460
461         if (!already_seen) {
462                 // Assemble the auto-reply message.
463                 StrBuf *reject_text = NewStrBuf();
464                 if (reject_text == NULL) {
465                         return;
466                 }
467
468                 StrBufPrintf(reject_text, 
469                         "Content-type: text/plain\n"
470                         "\n"
471                         "%s\n"
472                         "\n"
473                 ,
474                         rule->autoreply_message
475                 );
476         
477                 // Deliver the auto-reply.
478                 quickie_message(
479                         "",
480                         msg->cm_fields[eenVelopeTo],
481                         sender,
482                         MAILROOM,
483                         ChrPtr(reject_text),
484                         FMT_RFC822,
485                         "Delivery status notification"
486                 );
487                 FreeStrBuf(&reject_text);
488         }
489 }
490
491
492 /*
493  * Process a single message.  We know the room, the user, the rules, the message number, etc.
494  */
495 void inbox_do_msg(long msgnum, void *userdata) {
496         struct inboxrules *ii = (struct inboxrules *) userdata;
497         struct CtdlMessage *msg = NULL;         // If we are loading a message to process, put it here.
498         int headers_loaded = 0;                 // Did we load the headers yet?  Do it only once.
499         int body_loaded = 0;                    // Did we load the message body yet?  Do it only once.
500         int metadata_loaded = 0;                // Did we load the metadata yet?  Do it only once.
501         struct MetaData smi;                    // If we are loading the metadata to compare, put it here.
502         int rule_activated = 0;                 // On each rule, this is set if the compare succeeds and the rule activates.
503         char compare_me[SIZ];                   // On each rule, we will store the field to be compared here.
504         int compare_compound = 0;               // Set to 1 when we are comparing both display name and email address
505         int keep_message = 1;                   // Nonzero to keep the message in the inbox after processing, 0 to delete it.
506         int i;
507
508         syslog(LOG_DEBUG, "inboxrules: processing message #%ld which is higher than %ld, we are in %s", msgnum, ii->lastproc, CC->room.QRname);
509
510         if (ii->num_rules <= 0) {
511                 syslog(LOG_DEBUG, "inboxrules: rule set is empty");
512                 return;
513         }
514
515         for (i=0; i<ii->num_rules; ++i) {
516                 syslog(LOG_DEBUG, "inboxrules: processing rule %d is %s", i, field_keys[ ii->rules[i].compared_field ]);
517                 rule_activated = 0;
518
519                 // Before doing a field compare, check to see if we have the correct parts of the message in memory.
520
521                 switch(ii->rules[i].compared_field) {
522                         // These fields require loading only the top-level headers
523                         case field_from:                // From:
524                         case field_tocc:                // To: or Cc:
525                         case field_subject:             // Subject:
526                         case field_replyto:             // Reply-to:
527                         case field_listid:              // List-ID:
528                         case field_envto:               // Envelope-to:
529                         case field_envfrom:             // Return-path:
530                                 if (!headers_loaded) {
531                                         syslog(LOG_DEBUG, "inboxrules: loading headers for message %ld", msgnum);
532                                         msg = CtdlFetchMessage(msgnum, 0);
533                                         if (!msg) {
534                                                 return;
535                                         }
536                                         headers_loaded = 1;
537                                 }
538                                 break;
539                         // These fields are not stored as Citadel headers, and therefore require a full message load.
540                         case field_sender:
541                         case field_resentfrom:
542                         case field_resentto:
543                         case field_xmailer:
544                         case field_xspamflag:
545                         case field_xspamstatus:
546                                 if (!body_loaded) {
547                                         syslog(LOG_DEBUG, "inboxrules: loading all of message %ld", msgnum);
548                                         if (msg != NULL) {
549                                                 CM_Free(msg);
550                                         }
551                                         msg = CtdlFetchMessage(msgnum, 1);
552                                         if (!msg) {
553                                                 return;
554                                         }
555                                         headers_loaded = 1;
556                                         body_loaded = 1;
557                                 }
558                                 break;
559                         case field_size:
560                                 if (!metadata_loaded) {
561                                         syslog(LOG_DEBUG, "inboxrules: loading metadata for message %ld", msgnum);
562                                         GetMetaData(&smi, msgnum);
563                                         metadata_loaded = 1;
564                                 }
565                                 break;
566                         case field_all:
567                                 syslog(LOG_DEBUG, "inboxrules: this is an always-on rule");
568                                 break;
569                         default:
570                                 syslog(LOG_DEBUG, "inboxrules: unknown rule key");
571                 }
572
573                 // If the rule involves a field comparison, load the field to be compared.
574                 compare_me[0] = 0;
575                 compare_compound = 0;
576                 switch(ii->rules[i].compared_field) {
577                         case field_from:                // From:
578                                 if ( (!IsEmptyStr(msg->cm_fields[erFc822Addr])) && (!IsEmptyStr(msg->cm_fields[erFc822Addr])) ) {
579                                         snprintf(compare_me, sizeof compare_me, "%s|%s",
580                                                 msg->cm_fields[eAuthor],
581                                                 msg->cm_fields[erFc822Addr]
582                                         );
583                                         compare_compound = 1;           // there will be two fields to compare "name|address"
584                                 }
585                                 else if (!IsEmptyStr(msg->cm_fields[erFc822Addr])) {
586                                         safestrncpy(compare_me, msg->cm_fields[erFc822Addr], sizeof compare_me);
587                                 }
588                                 else if (!IsEmptyStr(msg->cm_fields[eAuthor])) {
589                                         safestrncpy(compare_me, msg->cm_fields[eAuthor], sizeof compare_me);
590                                 }
591                                 break;
592                         case field_tocc:                // To: or Cc:
593                                 if (!IsEmptyStr(msg->cm_fields[eRecipient])) {
594                                         safestrncpy(compare_me, msg->cm_fields[eRecipient], sizeof compare_me);
595                                 }
596                                 if (!IsEmptyStr(msg->cm_fields[eCarbonCopY])) {
597                                         if (!IsEmptyStr(compare_me)) {
598                                                 strcat(compare_me, ",");
599                                         }
600                                         safestrncpy(&compare_me[strlen(compare_me)], msg->cm_fields[eCarbonCopY], (sizeof compare_me - strlen(compare_me)));
601                                 }
602                                 break;
603                         case field_subject:             // Subject:
604                                 if (!IsEmptyStr(msg->cm_fields[eMsgSubject])) {
605                                         safestrncpy(compare_me, msg->cm_fields[eMsgSubject], sizeof compare_me);
606                                 }
607                                 break;
608                         case field_replyto:             // Reply-to:
609                                 if (!IsEmptyStr(msg->cm_fields[eReplyTo])) {
610                                         safestrncpy(compare_me, msg->cm_fields[eReplyTo], sizeof compare_me);
611                                 }
612                                 break;
613                         case field_listid:              // List-ID:
614                                 if (!IsEmptyStr(msg->cm_fields[eListID])) {
615                                         safestrncpy(compare_me, msg->cm_fields[eListID], sizeof compare_me);
616                                 }
617                                 break;
618                         case field_envto:               // Envelope-to:
619                                 if (!IsEmptyStr(msg->cm_fields[eenVelopeTo])) {
620                                         safestrncpy(compare_me, msg->cm_fields[eenVelopeTo], sizeof compare_me);
621                                 }
622                                 break;
623                         case field_envfrom:             // Return-path:
624                                 if (!IsEmptyStr(msg->cm_fields[eMessagePath])) {
625                                         safestrncpy(compare_me, msg->cm_fields[eMessagePath], sizeof compare_me);
626                                 }
627                                 break;
628
629                         case field_sender:
630                         case field_resentfrom:
631                         case field_resentto:
632                         case field_xmailer:
633                         case field_xspamflag:
634                         case field_xspamstatus:
635
636                         default:
637                                 break;
638                 }
639
640                 // Message data to compare is loaded, now do something.
641                 switch(ii->rules[i].compared_field) {
642                         case field_from:                // From:
643                         case field_tocc:                // To: or Cc:
644                         case field_subject:             // Subject:
645                         case field_replyto:             // Reply-to:
646                         case field_listid:              // List-ID:
647                         case field_envto:               // Envelope-to:
648                         case field_envfrom:             // Return-path:
649                         case field_sender:
650                         case field_resentfrom:
651                         case field_resentto:
652                         case field_xmailer:
653                         case field_xspamflag:
654                         case field_xspamstatus:
655
656                                 // For all of the above fields, we can compare the field we've loaded into the buffer.
657                                 syslog(LOG_DEBUG, "Value of field to compare is: <%s>", compare_me);
658                                 int substring_match = (bmstrcasestr(compare_me, ii->rules[i].compared_value) ? 1 : 0);
659                                 int exact_match = 0;
660                                 if (compare_compound) {
661                                         char *sep = strchr(compare_me, '|');
662                                         if (sep) {
663                                                 *sep = 0;
664                                                 exact_match =
665                                                         (strcasecmp(compare_me, ii->rules[i].compared_value) ? 0 : 1)
666                                                         + (strcasecmp(++sep, ii->rules[i].compared_value) ? 0 : 1)
667                                                 ;
668                                         }
669                                 }
670                                 else {
671                                         exact_match = (strcasecmp(compare_me, ii->rules[i].compared_value) ? 0 : 1);
672                                 }
673                                 syslog(LOG_DEBUG, "substring match: %d", substring_match);
674                                 syslog(LOG_DEBUG, "exact match: %d", exact_match);
675                                 switch(ii->rules[i].field_compare_op) {
676                                         case fcomp_contains:
677                                         case fcomp_matches:
678                                                 rule_activated = substring_match;
679                                                 break;
680                                         case fcomp_notcontains:
681                                         case fcomp_notmatches:
682                                                 rule_activated = !substring_match;
683                                                 break;
684                                         case fcomp_is:
685                                                 rule_activated = exact_match;
686                                                 break;
687                                         case fcomp_isnot:
688                                                 rule_activated = !exact_match;
689                                                 break;
690                                 }
691                                 break;
692
693                         case field_size:
694                                 rule_activated = 0;
695                                 switch(ii->rules[i].field_compare_op) {
696                                         case scomp_larger:
697                                                 rule_activated = ((smi.meta_rfc822_length > ii->rules[i].compared_size) ? 1 : 0);
698                                                 break;
699                                         case scomp_smaller:
700                                                 rule_activated = ((smi.meta_rfc822_length < ii->rules[i].compared_size) ? 1 : 0);
701                                                 break;
702                                 }
703                                 break;
704                         case field_all:                 // The "all messages" rule ALWAYS triggers
705                                 rule_activated = 1;
706                                 break;
707                         default:                        // no matches, fall through and do nothing
708                                 syslog(LOG_WARNING, "inboxrules: an unknown field comparison was encountered");
709                                 rule_activated = 0;
710                                 break;
711                 }
712
713                 // If the rule matched, perform the requested action.
714                 if (rule_activated) {
715                         syslog(LOG_DEBUG, "inboxrules: rule activated");
716
717                         // Perform the requested action
718                         switch(ii->rules[i].action) {
719                                 case action_keep:
720                                         keep_message = 1;
721                                         break;
722                                 case action_discard:
723                                         keep_message = 0;
724                                         break;
725                                 case action_reject:
726                                         inbox_do_reject(&ii->rules[i], msg);
727                                         keep_message = 0;
728                                         break;
729                                 case action_fileinto:
730                                         keep_message = inbox_do_fileinto(&ii->rules[i], msgnum);
731                                         break;
732                                 case action_redirect:
733                                         keep_message = inbox_do_redirect(&ii->rules[i], msgnum);
734                                         break;
735                                 case action_vacation:
736                                         inbox_do_vacation(&ii->rules[i], msg);
737                                         keep_message = 1;
738                                         break;
739                         }
740
741                         // Now perform the "final" action (anything other than "stop" means continue)
742                         if (ii->rules[i].final_action == final_stop) {
743                                 syslog(LOG_DEBUG, "inboxrules: stop processing");
744                                 i = ii->num_rules + 1;                                  // throw us out of scope to stop
745                         }
746
747
748                 }
749                 else {
750                         syslog(LOG_DEBUG, "inboxrules: rule not activated");
751                 }
752         }
753
754         if (msg != NULL) {              // Delete the copy of the message that is currently in memory.  We don't need it anymore.
755                 CM_Free(msg);
756         }
757
758         if (!keep_message) {            // Delete the copy of the message that is currently in the inbox, if rules dictated that.
759                 syslog(LOG_DEBUG, "inboxrules: delete %ld from inbox", msgnum);
760                 CtdlDeleteMessages(CC->room.QRname, &msgnum, 1, "");                    // we're in the inbox already
761         }
762
763         ii->lastproc = msgnum;          // make note of the last message we processed, so we don't scan the whole inbox again
764 }
765
766
767 /*
768  * A user account is identified as requring inbox processing.
769  * Do it.
770  */
771 void do_inbox_processing_for_user(long usernum) {
772         struct CtdlMessage *msg;
773         struct inboxrules *ii;
774         char roomname[ROOMNAMELEN];
775         char username[64];
776
777         if (CtdlGetUserByNumber(&CC->user, usernum) != 0) {     // grab the user record
778                 return;                                         // and bail out if we were given an invalid user
779         }
780
781         strcpy(username, CC->user.fullname);                    // save the user name so we can fetch it later and lock it
782
783         if (CC->user.msgnum_inboxrules <= 0) {
784                 return;                                         // this user has no inbox rules
785         }
786
787         msg = CtdlFetchMessage(CC->user.msgnum_inboxrules, 1);
788         if (msg == NULL) {
789                 return;                                         // config msgnum is set but that message does not exist
790         }
791
792         ii = deserialize_inbox_rules(msg->cm_fields[eMesageText]);
793         CM_Free(msg);
794
795         if (ii == NULL) {
796                 return;                                         // config message exists but body is null
797         }
798
799         if (ii->lastproc > CC->user.lastproc_inboxrules) {      // There might be a "last message processed" number left over
800                 CC->user.lastproc_inboxrules = ii->lastproc;    // in the ruleset from a previous version.  Use this if it is
801         }                                                       // a higher number.
802         else {
803                 ii->lastproc = CC->user.lastproc_inboxrules;
804         }
805
806         long original_lastproc = ii->lastproc;
807         syslog(LOG_DEBUG, "inboxrules: for %s, messages newer than %ld", CC->user.fullname, original_lastproc);
808
809         // Go to the user's inbox room and process all new messages
810         snprintf(roomname, sizeof roomname, "%010ld.%s", usernum, MAILROOM);
811         if (CtdlGetRoom(&CC->room, roomname) == 0) {
812                 CtdlForEachMessage(MSGS_GT, ii->lastproc, NULL, NULL, NULL, inbox_do_msg, (void *) ii);
813         }
814
815         // Record the number of the last message we processed
816         if (ii->lastproc > original_lastproc) {
817                 CtdlGetUserLock(&CC->user, username);
818                 CC->user.lastproc_inboxrules = ii->lastproc;    // Avoid processing the entire inbox next time
819                 CtdlPutUserLock(&CC->user);
820         }
821
822         // And free the memory.
823         free_inbox_rules(ii);
824 }
825
826
827 /*
828  * Here is an array of users (by number) who have received messages in their inbox and may require processing.
829  */
830 long *users_requiring_inbox_processing = NULL;
831 int num_urip = 0;
832 int num_urip_alloc = 0;
833
834
835 /*
836  * Perform inbox processing for all rooms which require it
837  */
838 void perform_inbox_processing(void) {
839         if (num_urip == 0) {
840                 return;                                                                                 // no action required
841         }
842
843         for (int i=0; i<num_urip; ++i) {
844                 do_inbox_processing_for_user(users_requiring_inbox_processing[i]);
845         }
846
847         free(users_requiring_inbox_processing);
848         users_requiring_inbox_processing = NULL;
849         num_urip = 0;
850         num_urip_alloc = 0;
851 }
852
853
854 /*
855  * This function is called after a message is saved to a room.
856  * If it's someone's inbox, we have to check for inbox rules
857  */
858 int serv_inboxrules_roomhook(struct ctdlroom *room) {
859
860         // Is this someone's inbox?
861         if (!strcasecmp(&room->QRname[11], MAILROOM)) {
862                 long usernum = atol(room->QRname);
863                 if (usernum > 0) {
864
865                         // first check to see if this user is already on the list
866                         if (num_urip > 0) {
867                                 for (int i=0; i<=num_urip; ++i) {
868                                         if (users_requiring_inbox_processing[i] == usernum) {           // already on the list!
869                                                 return(0);
870                                         }
871                                 }
872                         }
873
874                         // make room if we need to
875                         if (num_urip_alloc == 0) {
876                                 num_urip_alloc = 100;
877                                 users_requiring_inbox_processing = malloc(sizeof(long) * num_urip_alloc);
878                         }
879                         else if (num_urip >= num_urip_alloc) {
880                                 num_urip_alloc += 100;
881                                 users_requiring_inbox_processing = realloc(users_requiring_inbox_processing, (sizeof(long) * num_urip_alloc));
882                         }
883                         
884                         // now add the user to the list
885                         users_requiring_inbox_processing[num_urip++] = usernum;
886                 }
887         }
888
889         // No errors are possible from this function.
890         return(0);
891 }
892
893
894
895 /*
896  * Get InBox Rules
897  *
898  * This is a client-facing function which fetches the user's inbox rules -- it omits all lines containing anything other than a rule.
899  * 
900  * hmmmmm ... should we try to rebuild this in terms of deserialize_inbox_rules() instread?
901  */
902 void cmd_gibr(char *argbuf) {
903
904         if (CtdlAccessCheck(ac_logged_in)) return;
905
906         cprintf("%d inbox rules for %s\n", LISTING_FOLLOWS, CC->user.fullname);
907
908         struct CtdlMessage *msg = CtdlFetchMessage(CC->user.msgnum_inboxrules, 1);
909         if (msg != NULL) {
910                 if (!CM_IsEmpty(msg, eMesageText)) {
911                         char *token; 
912                         char *rest = msg->cm_fields[eMesageText];
913                         while ((token = strtok_r(rest, "\n", &rest))) {
914
915                                 // for backwards compatibility, "# WEBCIT_RULE" is an alias for "rule" 
916                                 if (!strncasecmp(token, "# WEBCIT_RULE|", 14)) {
917                                         strcpy(token, "rule|"); 
918                                         strcpy(&token[5], &token[14]);
919                                 }
920
921                                 // Output only lines containing rules.
922                                 if (!strncasecmp(token, "rule|", 5)) {
923                                         cprintf("%s\n", token); 
924                                 }
925                                 else {
926                                         cprintf("# invalid rule found : %s\n", token);
927                                 }
928                         }
929                 }
930                 CM_Free(msg);
931         }
932         cprintf("000\n");
933 }
934
935
936 /*
937  * Rewrite the rule set to disk after it has been modified
938  * Called by cmd_pibr()
939  * Returns the msgnum of the new rules message
940  */
941 void rewrite_rules_to_disk(const char *new_config) {
942         long old_msgnum = CC->user.msgnum_inboxrules;
943         char userconfigroomname[ROOMNAMELEN];
944         CtdlMailboxName(userconfigroomname, sizeof userconfigroomname, &CC->user, USERCONFIGROOM);
945         long new_msgnum = quickie_message("Citadel", NULL, NULL, userconfigroomname, new_config, FMT_RFC822, "inbox rules configuration");
946         CtdlGetUserLock(&CC->user, CC->curr_user);
947         CC->user.msgnum_inboxrules = new_msgnum;                // Now we know where to get the rules next time
948         CC->user.lastproc_inboxrules = new_msgnum;              // Avoid processing the entire inbox next time
949         CtdlPutUserLock(&CC->user);
950         if (old_msgnum > 0) {
951                 syslog(LOG_DEBUG, "Deleting old message %ld from %s", old_msgnum, userconfigroomname);
952                 CtdlDeleteMessages(userconfigroomname, &old_msgnum, 1, "");
953         }
954 }
955
956
957 /*
958  * Put InBox Rules
959  *
960  * User transmits the new inbox rules for the account.  They are inserted into the account, replacing the ones already there.
961  */
962 void cmd_pibr(char *argbuf) {
963         if (CtdlAccessCheck(ac_logged_in)) return;
964
965         unbuffer_output();
966         cprintf("%d send new rules\n", SEND_LISTING);
967         char *newrules = CtdlReadMessageBody(HKEY("000"), CtdlGetConfigLong("c_maxmsglen"), NULL, 0);
968         StrBuf *NewConfig = NewStrBufPlain("Content-type: application/x-citadel-sieve-config; charset=UTF-8\nContent-transfer-encoding: 8bit\n\n", -1);
969
970         char *token; 
971         char *rest = newrules;
972         while ((token = strtok_r(rest, "\n", &rest))) {
973                 // Accept only lines containing rules
974                 if (!strncasecmp(token, "rule|", 5)) {
975                         StrBufAppendBufPlain(NewConfig, token, -1, 0);
976                         StrBufAppendBufPlain(NewConfig, HKEY("\n"), 0);
977                 }
978         }
979         free(newrules);
980         rewrite_rules_to_disk(ChrPtr(NewConfig));
981         FreeStrBuf(&NewConfig);
982 }
983
984
985 CTDL_MODULE_INIT(sieve)
986 {
987         if (!threading)
988         {
989                 CtdlRegisterProtoHook(cmd_gibr, "GIBR", "Get InBox Rules");
990                 CtdlRegisterProtoHook(cmd_pibr, "PIBR", "Put InBox Rules");
991                 CtdlRegisterRoomHook(serv_inboxrules_roomhook);
992                 CtdlRegisterSessionHook(perform_inbox_processing, EVT_HOUSE, PRIO_HOUSE + 10);
993         }
994         
995         /* return our module name for the log */
996         return "inboxrules";
997 }