Just a little bit less debug logging
[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, 0);                     // 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                 NULL,
421                 msg->cm_fields[eenVelopeTo],
422                 sender,
423                 NULL,
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                         NULL,
480                         msg->cm_fields[eenVelopeTo],
481                         sender,
482                         NULL,
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 keep_message = 1;                   // Nonzero to keep the message in the inbox after processing, 0 to delete it.
505         int i;
506
507         syslog(LOG_DEBUG, "inboxrules: processing message #%ld which is higher than %ld, we are in %s", msgnum, ii->lastproc, CC->room.QRname);
508
509         if (ii->num_rules <= 0) {
510                 syslog(LOG_DEBUG, "inboxrules: rule set is empty");
511                 return;
512         }
513
514         for (i=0; i<ii->num_rules; ++i) {
515                 syslog(LOG_DEBUG, "inboxrules: processing rule %d is %s", i, field_keys[ ii->rules[i].compared_field ]);
516                 rule_activated = 0;
517
518                 // Before doing a field compare, check to see if we have the correct parts of the message in memory.
519
520                 switch(ii->rules[i].compared_field) {
521                         // These fields require loading only the top-level headers
522                         case field_from:                // From:
523                         case field_tocc:                // To: or Cc:
524                         case field_subject:             // Subject:
525                         case field_replyto:             // Reply-to:
526                         case field_listid:              // List-ID:
527                         case field_envto:               // Envelope-to:
528                         case field_envfrom:             // Return-path:
529                                 if (!headers_loaded) {
530                                         syslog(LOG_DEBUG, "inboxrules: loading headers for message %ld", msgnum);
531                                         msg = CtdlFetchMessage(msgnum, 0);
532                                         if (!msg) {
533                                                 return;
534                                         }
535                                         headers_loaded = 1;
536                                 }
537                                 break;
538                         // These fields are not stored as Citadel headers, and therefore require a full message load.
539                         case field_sender:
540                         case field_resentfrom:
541                         case field_resentto:
542                         case field_xmailer:
543                         case field_xspamflag:
544                         case field_xspamstatus:
545                                 if (!body_loaded) {
546                                         syslog(LOG_DEBUG, "inboxrules: loading all of message %ld", msgnum);
547                                         if (msg != NULL) {
548                                                 CM_Free(msg);
549                                         }
550                                         msg = CtdlFetchMessage(msgnum, 1);
551                                         if (!msg) {
552                                                 return;
553                                         }
554                                         headers_loaded = 1;
555                                         body_loaded = 1;
556                                 }
557                                 break;
558                         case field_size:
559                                 if (!metadata_loaded) {
560                                         syslog(LOG_DEBUG, "inboxrules: loading metadata for message %ld", msgnum);
561                                         GetMetaData(&smi, msgnum);
562                                         metadata_loaded = 1;
563                                 }
564                                 break;
565                         case field_all:
566                                 syslog(LOG_DEBUG, "inboxrules: this is an always-on rule");
567                                 break;
568                         default:
569                                 syslog(LOG_DEBUG, "inboxrules: unknown rule key");
570                 }
571
572                 // If the rule involves a field comparison, load the field to be compared.
573                 compare_me[0] = 0;
574                 switch(ii->rules[i].compared_field) {
575
576                         case field_from:                // From:
577                                 if (!IsEmptyStr(msg->cm_fields[erFc822Addr])) {
578                                         safestrncpy(compare_me, msg->cm_fields[erFc822Addr], sizeof compare_me);
579                                 }
580                                 break;
581                         case field_tocc:                // To: or Cc:
582                                 if (!IsEmptyStr(msg->cm_fields[eRecipient])) {
583                                         safestrncpy(compare_me, msg->cm_fields[eRecipient], sizeof compare_me);
584                                 }
585                                 if (!IsEmptyStr(msg->cm_fields[eCarbonCopY])) {
586                                         if (!IsEmptyStr(compare_me)) {
587                                                 strcat(compare_me, ",");
588                                         }
589                                         safestrncpy(&compare_me[strlen(compare_me)], msg->cm_fields[eCarbonCopY], (sizeof compare_me - strlen(compare_me)));
590                                 }
591                                 break;
592                         case field_subject:             // Subject:
593                                 if (!IsEmptyStr(msg->cm_fields[eMsgSubject])) {
594                                         safestrncpy(compare_me, msg->cm_fields[eMsgSubject], sizeof compare_me);
595                                 }
596                                 break;
597                         case field_replyto:             // Reply-to:
598                                 if (!IsEmptyStr(msg->cm_fields[eReplyTo])) {
599                                         safestrncpy(compare_me, msg->cm_fields[eReplyTo], sizeof compare_me);
600                                 }
601                                 break;
602                         case field_listid:              // List-ID:
603                                 if (!IsEmptyStr(msg->cm_fields[eListID])) {
604                                         safestrncpy(compare_me, msg->cm_fields[eListID], sizeof compare_me);
605                                 }
606                                 break;
607                         case field_envto:               // Envelope-to:
608                                 if (!IsEmptyStr(msg->cm_fields[eenVelopeTo])) {
609                                         safestrncpy(compare_me, msg->cm_fields[eenVelopeTo], sizeof compare_me);
610                                 }
611                                 break;
612                         case field_envfrom:             // Return-path:
613                                 if (!IsEmptyStr(msg->cm_fields[eMessagePath])) {
614                                         safestrncpy(compare_me, msg->cm_fields[eMessagePath], sizeof compare_me);
615                                 }
616                                 break;
617
618                         case field_sender:
619                         case field_resentfrom:
620                         case field_resentto:
621                         case field_xmailer:
622                         case field_xspamflag:
623                         case field_xspamstatus:
624
625                         default:
626                                 break;
627                 }
628
629                 // Message data to compare is loaded, now do something.
630                 switch(ii->rules[i].compared_field) {
631                         case field_from:                // From:
632                         case field_tocc:                // To: or Cc:
633                         case field_subject:             // Subject:
634                         case field_replyto:             // Reply-to:
635                         case field_listid:              // List-ID:
636                         case field_envto:               // Envelope-to:
637                         case field_envfrom:             // Return-path:
638                         case field_sender:
639                         case field_resentfrom:
640                         case field_resentto:
641                         case field_xmailer:
642                         case field_xspamflag:
643                         case field_xspamstatus:
644
645                                 // For all of the above fields, we can compare the field we've loaded into the buffer.
646                                 syslog(LOG_DEBUG, "Value of field to compare is: <%s>", compare_me);
647                                 switch(ii->rules[i].field_compare_op) {
648                                         case fcomp_contains:
649                                         case fcomp_matches:
650                                                 rule_activated = (bmstrcasestr(compare_me, ii->rules[i].compared_value) ? 1 : 0);
651                                                 break;
652                                         case fcomp_notcontains:
653                                         case fcomp_notmatches:
654                                                 rule_activated = (bmstrcasestr(compare_me, ii->rules[i].compared_value) ? 0 : 1);
655                                                 break;
656                                         case fcomp_is:
657                                                 rule_activated = (strcasecmp(compare_me, ii->rules[i].compared_value) ? 0 : 1);
658                                                 break;
659                                         case fcomp_isnot:
660                                                 rule_activated = (strcasecmp(compare_me, ii->rules[i].compared_value) ? 1 : 0);
661                                                 break;
662                                 }
663                                 break;
664
665                         case field_size:
666                                 rule_activated = 0;
667                                 switch(ii->rules[i].field_compare_op) {
668                                         case scomp_larger:
669                                                 rule_activated = ((smi.meta_rfc822_length > ii->rules[i].compared_size) ? 1 : 0);
670                                                 break;
671                                         case scomp_smaller:
672                                                 rule_activated = ((smi.meta_rfc822_length < ii->rules[i].compared_size) ? 1 : 0);
673                                                 break;
674                                 }
675                                 break;
676                         case field_all:                 // The "all messages" rule ALWAYS triggers
677                                 rule_activated = 1;
678                                 break;
679                         default:                        // no matches, fall through and do nothing
680                                 syslog(LOG_WARNING, "inboxrules: an unknown field comparison was encountered");
681                                 rule_activated = 0;
682                                 break;
683                 }
684
685                 // If the rule matched, perform the requested action.
686                 if (rule_activated) {
687                         syslog(LOG_DEBUG, "inboxrules: rule activated");
688
689                         // Perform the requested action
690                         switch(ii->rules[i].action) {
691                                 case action_keep:
692                                         keep_message = 1;
693                                         break;
694                                 case action_discard:
695                                         keep_message = 0;
696                                         break;
697                                 case action_reject:
698                                         inbox_do_reject(&ii->rules[i], msg);
699                                         keep_message = 0;
700                                         break;
701                                 case action_fileinto:
702                                         keep_message = inbox_do_fileinto(&ii->rules[i], msgnum);
703                                         break;
704                                 case action_redirect:
705                                         keep_message = inbox_do_redirect(&ii->rules[i], msgnum);
706                                         break;
707                                 case action_vacation:
708                                         inbox_do_vacation(&ii->rules[i], msg);
709                                         keep_message = 1;
710                                         break;
711                         }
712
713                         // Now perform the "final" action (anything other than "stop" means continue)
714                         if (ii->rules[i].final_action == final_stop) {
715                                 syslog(LOG_DEBUG, "inboxrules: stop processing");
716                                 i = ii->num_rules + 1;                                  // throw us out of scope to stop
717                         }
718
719
720                 }
721                 else {
722                         syslog(LOG_DEBUG, "inboxrules: rule not activated");
723                 }
724         }
725
726         if (msg != NULL) {              // Delete the copy of the message that is currently in memory.  We don't need it anymore.
727                 CM_Free(msg);
728         }
729
730         if (!keep_message) {            // Delete the copy of the message that is currently in the inbox, if rules dictated that.
731                 syslog(LOG_DEBUG, "inboxrules: delete %ld from inbox", msgnum);
732                 CtdlDeleteMessages(CC->room.QRname, &msgnum, 1, "");                    // we're in the inbox already
733         }
734
735         ii->lastproc = msgnum;          // make note of the last message we processed, so we don't scan the whole inbox again
736 }
737
738
739 /*
740  * A user account is identified as requring inbox processing.
741  * Do it.
742  */
743 void do_inbox_processing_for_user(long usernum) {
744         struct CtdlMessage *msg;
745         struct inboxrules *ii;
746         char roomname[ROOMNAMELEN];
747         char username[64];
748
749         if (CtdlGetUserByNumber(&CC->user, usernum) != 0) {     // grab the user record
750                 return;                                         // and bail out if we were given an invalid user
751         }
752
753         strcpy(username, CC->user.fullname);                    // save the user name so we can fetch it later and lock it
754
755         if (CC->user.msgnum_inboxrules <= 0) {
756                 return;                                         // this user has no inbox rules
757         }
758
759         msg = CtdlFetchMessage(CC->user.msgnum_inboxrules, 1);
760         if (msg == NULL) {
761                 return;                                         // config msgnum is set but that message does not exist
762         }
763
764         ii = deserialize_inbox_rules(msg->cm_fields[eMesageText]);
765         CM_Free(msg);
766
767         if (ii == NULL) {
768                 return;                                         // config message exists but body is null
769         }
770
771         if (ii->lastproc > CC->user.lastproc_inboxrules) {      // There might be a "last message processed" number left over
772                 CC->user.lastproc_inboxrules = ii->lastproc;    // in the ruleset from a previous version.  Use this if it is
773         }                                                       // a higher number.
774         else {
775                 ii->lastproc = CC->user.lastproc_inboxrules;
776         }
777
778         long original_lastproc = ii->lastproc;
779         syslog(LOG_DEBUG, "inboxrules: for %s, messages newer than %ld", CC->user.fullname, original_lastproc);
780
781         // Go to the user's inbox room and process all new messages
782         snprintf(roomname, sizeof roomname, "%010ld.%s", usernum, MAILROOM);
783         if (CtdlGetRoom(&CC->room, roomname) == 0) {
784                 CtdlForEachMessage(MSGS_GT, ii->lastproc, NULL, NULL, NULL, inbox_do_msg, (void *) ii);
785         }
786
787         // Record the number of the last message we processed
788         if (ii->lastproc > original_lastproc) {
789                 CtdlGetUserLock(&CC->user, username);
790                 CC->user.lastproc_inboxrules = ii->lastproc;    // Avoid processing the entire inbox next time
791                 CtdlPutUserLock(&CC->user);
792         }
793
794         // And free the memory.
795         free_inbox_rules(ii);
796 }
797
798
799 /*
800  * Here is an array of users (by number) who have received messages in their inbox and may require processing.
801  */
802 long *users_requiring_inbox_processing = NULL;
803 int num_urip = 0;
804 int num_urip_alloc = 0;
805
806
807 /*
808  * Perform inbox processing for all rooms which require it
809  */
810 void perform_inbox_processing(void) {
811         if (num_urip == 0) {
812                 return;                                                                                 // no action required
813         }
814
815         for (int i=0; i<num_urip; ++i) {
816                 do_inbox_processing_for_user(users_requiring_inbox_processing[i]);
817         }
818
819         free(users_requiring_inbox_processing);
820         users_requiring_inbox_processing = NULL;
821         num_urip = 0;
822         num_urip_alloc = 0;
823 }
824
825
826 /*
827  * This function is called after a message is saved to a room.
828  * If it's someone's inbox, we have to check for inbox rules
829  */
830 int serv_inboxrules_roomhook(struct ctdlroom *room) {
831
832         // Is this someone's inbox?
833         if (!strcasecmp(&room->QRname[11], MAILROOM)) {
834                 long usernum = atol(room->QRname);
835                 if (usernum > 0) {
836
837                         // first check to see if this user is already on the list
838                         if (num_urip > 0) {
839                                 for (int i=0; i<=num_urip; ++i) {
840                                         if (users_requiring_inbox_processing[i] == usernum) {           // already on the list!
841                                                 return(0);
842                                         }
843                                 }
844                         }
845
846                         // make room if we need to
847                         if (num_urip_alloc == 0) {
848                                 num_urip_alloc = 100;
849                                 users_requiring_inbox_processing = malloc(sizeof(long) * num_urip_alloc);
850                         }
851                         else if (num_urip >= num_urip_alloc) {
852                                 num_urip_alloc += 100;
853                                 users_requiring_inbox_processing = realloc(users_requiring_inbox_processing, (sizeof(long) * num_urip_alloc));
854                         }
855                         
856                         // now add the user to the list
857                         users_requiring_inbox_processing[num_urip++] = usernum;
858                 }
859         }
860
861         // No errors are possible from this function.
862         return(0);
863 }
864
865
866
867 /*
868  * Get InBox Rules
869  *
870  * This is a client-facing function which fetches the user's inbox rules -- it omits all lines containing anything other than a rule.
871  * 
872  * hmmmmm ... should we try to rebuild this in terms of deserialize_inbox_rules() instread?
873  */
874 void cmd_gibr(char *argbuf) {
875
876         if (CtdlAccessCheck(ac_logged_in)) return;
877
878         cprintf("%d inbox rules for %s\n", LISTING_FOLLOWS, CC->user.fullname);
879
880         struct CtdlMessage *msg = CtdlFetchMessage(CC->user.msgnum_inboxrules, 1);
881         if (msg != NULL) {
882                 if (!CM_IsEmpty(msg, eMesageText)) {
883                         char *token; 
884                         char *rest = msg->cm_fields[eMesageText];
885                         while ((token = strtok_r(rest, "\n", &rest))) {
886
887                                 // for backwards compatibility, "# WEBCIT_RULE" is an alias for "rule" 
888                                 if (!strncasecmp(token, "# WEBCIT_RULE|", 14)) {
889                                         strcpy(token, "rule|"); 
890                                         strcpy(&token[5], &token[14]);
891                                 }
892
893                                 // Output only lines containing rules.
894                                 if (!strncasecmp(token, "rule|", 5)) {
895                                         cprintf("%s\n", token); 
896                                 }
897                                 else {
898                                         cprintf("# invalid rule found : %s\n", token);
899                                 }
900                         }
901                 }
902                 CM_Free(msg);
903         }
904         cprintf("000\n");
905 }
906
907
908 /*
909  * Rewrite the rule set to disk after it has been modified
910  * Called by cmd_pibr()
911  * Returns the msgnum of the new rules message
912  */
913 void rewrite_rules_to_disk(const char *new_config) {
914         long old_msgnum = CC->user.msgnum_inboxrules;
915         char userconfigroomname[ROOMNAMELEN];
916         CtdlMailboxName(userconfigroomname, sizeof userconfigroomname, &CC->user, USERCONFIGROOM);
917         long new_msgnum = quickie_message("Citadel", NULL, NULL, userconfigroomname, new_config, FMT_RFC822, "inbox rules configuration");
918         CtdlGetUserLock(&CC->user, CC->curr_user);
919         CC->user.msgnum_inboxrules = new_msgnum;                // Now we know where to get the rules next time
920         CC->user.lastproc_inboxrules = new_msgnum;              // Avoid processing the entire inbox next time
921         CtdlPutUserLock(&CC->user);
922         if (old_msgnum > 0) {
923                 syslog(LOG_DEBUG, "Deleting old message %ld from %s", old_msgnum, userconfigroomname);
924                 CtdlDeleteMessages(userconfigroomname, &old_msgnum, 1, "");
925         }
926 }
927
928
929 /*
930  * Put InBox Rules
931  *
932  * User transmits the new inbox rules for the account.  They are inserted into the account, replacing the ones already there.
933  */
934 void cmd_pibr(char *argbuf) {
935         if (CtdlAccessCheck(ac_logged_in)) return;
936
937         unbuffer_output();
938         cprintf("%d send new rules\n", SEND_LISTING);
939         char *newrules = CtdlReadMessageBody(HKEY("000"), CtdlGetConfigLong("c_maxmsglen"), NULL, 0);
940         StrBuf *NewConfig = NewStrBufPlain("Content-type: application/x-citadel-sieve-config; charset=UTF-8\nContent-transfer-encoding: 8bit\n\n", -1);
941
942         char *token; 
943         char *rest = newrules;
944         while ((token = strtok_r(rest, "\n", &rest))) {
945                 // Accept only lines containing rules
946                 if (!strncasecmp(token, "rule|", 5)) {
947                         StrBufAppendBufPlain(NewConfig, token, -1, 0);
948                         StrBufAppendBufPlain(NewConfig, HKEY("\n"), 0);
949                 }
950         }
951         free(newrules);
952         rewrite_rules_to_disk(ChrPtr(NewConfig));
953         FreeStrBuf(&NewConfig);
954 }
955
956
957 CTDL_MODULE_INIT(sieve)
958 {
959         if (!threading)
960         {
961                 CtdlRegisterProtoHook(cmd_gibr, "GIBR", "Get InBox Rules");
962                 CtdlRegisterProtoHook(cmd_pibr, "PIBR", "Put InBox Rules");
963                 CtdlRegisterRoomHook(serv_inboxrules_roomhook);
964                 CtdlRegisterSessionHook(perform_inbox_processing, EVT_HOUSE, PRIO_HOUSE + 10);
965         }
966         
967         /* return our module name for the log */
968         return "inboxrules";
969 }