fixed error: 'for' loop initial declarations are only allowed in C99 or C11 mode
[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                         int t = 0;
222                         for (t=0; t<nt; ++t) {
223                                 extract_token(rtoken, decoded_rule, t, '|', sizeof(rtoken));
224                                 striplt(rtoken);
225                                 switch(t) {
226                                         case 1:                                                         // field to compare
227                                                 for (i=0; i<=field_all; ++i) {
228                                                         if (!strcasecmp(rtoken, field_keys[i])) {
229                                                                 new_rule->compared_field = i;
230                                                         }
231                                                 }
232                                                 break;
233                                         case 2:                                                         // field comparison operation
234                                                 for (i=0; i<=fcomp_notmatches; ++i) {
235                                                         if (!strcasecmp(rtoken, fcomp_keys[i])) {
236                                                                 new_rule->field_compare_op = i;
237                                                         }
238                                                 }
239                                                 break;
240                                         case 3:                                                         // field comparison value
241                                                 safestrncpy(new_rule->compared_value, rtoken, sizeof(new_rule->compared_value));
242                                                 break;
243                                         case 4:                                                         // size comparison operation
244                                                 for (i=0; i<=scomp_smaller; ++i) {
245                                                         if (!strcasecmp(rtoken, scomp_keys[i])) {
246                                                                 new_rule->size_compare_op = i;
247                                                         }
248                                                 }
249                                                 break;
250                                         case 5:                                                         // size comparison value
251                                                 new_rule->compared_size = atol(rtoken);
252                                                 break;
253                                         case 6:                                                         // action
254                                                 for (i=0; i<=action_vacation; ++i) {
255                                                         if (!strcasecmp(rtoken, action_keys[i])) {
256                                                                 new_rule->action = i;
257                                                         }
258                                                 }
259                                                 break;
260                                         case 7:                                                         // file into (target room)
261                                                 safestrncpy(new_rule->file_into, rtoken, sizeof(new_rule->file_into));
262                                                 break;
263                                         case 8:                                                         // redirect to (target address)
264                                                 safestrncpy(new_rule->redirect_to, rtoken, sizeof(new_rule->redirect_to));
265                                                 break;
266                                         case 9:                                                         // autoreply message
267                                                 safestrncpy(new_rule->autoreply_message, rtoken, sizeof(new_rule->autoreply_message));
268                                                 break;
269                                         case 10:                                                        // final_action;
270                                                 for (i=0; i<=final_stop; ++i) {
271                                                         if (!strcasecmp(rtoken, final_keys[i])) {
272                                                                 new_rule->final_action = i;
273                                                         }
274                                                 }
275                                                 break;
276                                         default:
277                                                 break;
278                                 }
279                         }
280                         free(decoded_rule);
281                 }
282
283                 // "lastproc" indicates the newest message number in the inbox that was previously processed by our inbox rules.
284                 // This is a legacy location for this value and will only be used if it's the only one present.
285                 else if (!strncasecmp(token, "lastproc|", 5)) {
286                         ibr->lastproc = atol(&token[9]);
287                 }
288
289                 // Lines which do not contain a recognizable token must be IGNORED.  These lines may be left over
290                 // from a previous version and will disappear when we rewrite the config.
291
292         }
293
294         free(sr);               // free our copy of the source buffer that has now been trashed with null bytes...
295         return(ibr);            // and return our complex data type to the caller.
296 }
297
298
299 // Perform the "fileinto" action (save the message in another room)
300 // Returns: 1 or 0 to tell the caller to keep (1) or delete (0) the inbox copy of the message.
301 //
302 int inbox_do_fileinto(struct irule *rule, long msgnum) {
303         char *dest_folder = rule->file_into;
304         char original_room_name[ROOMNAMELEN];
305         char foldername[ROOMNAMELEN];
306         int c;
307
308         // Situations where we want to just keep the message in the inbox:
309         if (
310                 (IsEmptyStr(dest_folder))                       // no destination room was specified
311                 || (!strcasecmp(dest_folder, "INBOX"))          // fileinto inbox is the same as keep
312                 || (!strcasecmp(dest_folder, MAILROOM))         // fileinto "Mail" is the same as keep
313         ) {
314                 return(1);                                      // don't delete the inbox copy if this failed
315         }
316
317         // Remember what room we came from
318         safestrncpy(original_room_name, CC->room.QRname, sizeof original_room_name);
319
320         // First try a mailbox name match (check personal mail folders first)
321         strcpy(foldername, original_room_name);                                 // This keeps the user namespace of the inbox
322         snprintf(&foldername[10], sizeof(foldername)-10, ".%s", dest_folder);   // And this tacks on the target room name
323         c = CtdlGetRoom(&CC->room, foldername);
324
325         // Then a regular room name match (public and private rooms)
326         if (c != 0) {
327                 safestrncpy(foldername, dest_folder, sizeof foldername);
328                 c = CtdlGetRoom(&CC->room, foldername);
329         }
330
331         if (c != 0) {
332                 syslog(LOG_WARNING, "inboxrules: target <%s> does not exist", dest_folder);
333                 return(1);                                      // don't delete the inbox copy if this failed
334         }
335
336         // Yes, we actually have to go there
337         CtdlUserGoto(NULL, 0, 0, NULL, NULL, NULL, NULL);
338
339         c = CtdlSaveMsgPointersInRoom(NULL, &msgnum, 1, 0, NULL, 0);
340
341         // Go back to the room we came from
342         if (strcasecmp(original_room_name, CC->room.QRname)) {
343                 CtdlUserGoto(original_room_name, 0, 0, NULL, NULL, NULL, NULL);
344         }
345
346         return(0);                                              // delete the inbox copy
347 }
348
349
350 // Perform the "redirect" action (divert the message to another email address)
351 // Returns: 1 or 0 to tell the caller to keep (1) or delete (0) the inbox copy of the message.
352 //
353 int inbox_do_redirect(struct irule *rule, long msgnum) {
354         if (IsEmptyStr(rule->redirect_to)) {
355                 syslog(LOG_WARNING, "inboxrules: inbox_do_redirect() invalid recipient <%s>", rule->redirect_to);
356                 return(1);                                      // don't delete the inbox copy if this failed
357         }
358
359         recptypes *valid = validate_recipients(rule->redirect_to, NULL, 0);
360         if (valid == NULL) {
361                 syslog(LOG_WARNING, "inboxrules: inbox_do_redirect() invalid recipient <%s>", rule->redirect_to);
362                 return(1);                                      // don't delete the inbox copy if this failed
363         }
364         if (valid->num_error > 0) {
365                 free_recipients(valid);
366                 syslog(LOG_WARNING, "inboxrules: inbox_do_redirect() invalid recipient <%s>", rule->redirect_to);
367                 return(1);                                      // don't delete the inbox copy if this failed
368         }
369
370         struct CtdlMessage *msg = CtdlFetchMessage(msgnum, 1);
371         if (msg == NULL) {
372                 free_recipients(valid);
373                 syslog(LOG_WARNING, "inboxrules: cannot reload message %ld for forwarding", msgnum);
374                 return(1);                                      // don't delete the inbox copy if this failed
375         }
376
377         CtdlSubmitMsg(msg, valid, NULL);                        // send the message to the new recipient
378         free_recipients(valid);
379         CM_Free(msg);
380         return(0);                                              // delete the inbox copy
381 }
382
383
384 /*
385  * Perform the "reject" action (delete the message, and tell the sender we deleted it)
386  */
387 void inbox_do_reject(struct irule *rule, struct CtdlMessage *msg) {
388         syslog(LOG_DEBUG, "inbox_do_reject: sender: <%s>, reject", msg->cm_fields[erFc822Addr]);
389
390         // If we can't determine who sent the message, reject silently.
391         char *sender;
392         if (!IsEmptyStr(msg->cm_fields[eMessagePath])) {
393                 sender = msg->cm_fields[eMessagePath];
394         }
395         else if (!IsEmptyStr(msg->cm_fields[erFc822Addr])) {
396                 sender = msg->cm_fields[erFc822Addr];
397         }
398         else {
399                 return;
400         }
401
402         // Assemble the reject message.
403         char *reject_text = malloc(strlen(rule->autoreply_message) + 1024);
404         if (reject_text == NULL) {
405                 return;
406         }
407         sprintf(reject_text, 
408                 "Content-type: text/plain\n"
409                 "\n"
410                 "The message was refused by the recipient's mail filtering program.\n"
411                 "The reason given was as follows:\n"
412                 "\n"
413                 "%s\n"
414                 "\n"
415         ,
416                 rule->autoreply_message
417         );
418
419         // Deliver the message
420         quickie_message(
421                 " ",
422                 msg->cm_fields[eenVelopeTo],
423                 sender,
424                 MAILROOM,
425                 reject_text,
426                 FMT_RFC822,
427                 "Delivery status notification"
428         );
429         free(reject_text);
430 }
431
432
433 /*
434  * Perform the "vacation" action (send an automatic response)
435  */
436 void inbox_do_vacation(struct irule *rule, struct CtdlMessage *msg) {
437         syslog(LOG_DEBUG, "inbox_do_vacation: sender: <%s>, vacation", msg->cm_fields[erFc822Addr]);
438
439         // If we can't determine who sent the message, no auto-reply can be sent.
440         char *sender;
441         if (!IsEmptyStr(msg->cm_fields[eMessagePath])) {
442                 sender = msg->cm_fields[eMessagePath];
443         }
444         else if (!IsEmptyStr(msg->cm_fields[erFc822Addr])) {
445                 sender = msg->cm_fields[erFc822Addr];
446         }
447         else {
448                 return;
449         }
450
451         // Avoid repeatedly sending auto-replies to the same correspondent over and over again by creating
452         // a hash of the user, correspondent, and reply text, and hitting the S_USETABLE database.
453         StrBuf *u = NewStrBuf();
454         StrBufPrintf(u, "vacation/%x/%x/%x",
455                 HashLittle(sender, strlen(sender)),
456                 HashLittle(msg->cm_fields[eenVelopeTo], msg->cm_lengths[eenVelopeTo]),
457                 HashLittle(rule->autoreply_message, strlen(rule->autoreply_message))
458         );
459         int already_seen = CheckIfAlreadySeen(u);
460         FreeStrBuf(&u);
461
462         if (!already_seen) {
463                 // Assemble the auto-reply message.
464                 StrBuf *reject_text = NewStrBuf();
465                 if (reject_text == NULL) {
466                         return;
467                 }
468
469                 StrBufPrintf(reject_text, 
470                         "Content-type: text/plain\n"
471                         "\n"
472                         "%s\n"
473                         "\n"
474                 ,
475                         rule->autoreply_message
476                 );
477         
478                 // Deliver the auto-reply.
479                 quickie_message(
480                         "",
481                         msg->cm_fields[eenVelopeTo],
482                         sender,
483                         MAILROOM,
484                         ChrPtr(reject_text),
485                         FMT_RFC822,
486                         "Delivery status notification"
487                 );
488                 FreeStrBuf(&reject_text);
489         }
490 }
491
492
493 /*
494  * Process a single message.  We know the room, the user, the rules, the message number, etc.
495  */
496 void inbox_do_msg(long msgnum, void *userdata) {
497         struct inboxrules *ii = (struct inboxrules *) userdata;
498         struct CtdlMessage *msg = NULL;         // If we are loading a message to process, put it here.
499         int headers_loaded = 0;                 // Did we load the headers yet?  Do it only once.
500         int body_loaded = 0;                    // Did we load the message body yet?  Do it only once.
501         int metadata_loaded = 0;                // Did we load the metadata yet?  Do it only once.
502         struct MetaData smi;                    // If we are loading the metadata to compare, put it here.
503         int rule_activated = 0;                 // On each rule, this is set if the compare succeeds and the rule activates.
504         char compare_me[SIZ];                   // On each rule, we will store the field to be compared here.
505         int compare_compound = 0;               // Set to 1 when we are comparing both display name and email address
506         int keep_message = 1;                   // Nonzero to keep the message in the inbox after processing, 0 to delete it.
507         int i;
508
509         syslog(LOG_DEBUG, "inboxrules: processing message #%ld which is higher than %ld, we are in %s", msgnum, ii->lastproc, CC->room.QRname);
510
511         if (ii->num_rules <= 0) {
512                 syslog(LOG_DEBUG, "inboxrules: rule set is empty");
513                 return;
514         }
515
516         for (i=0; i<ii->num_rules; ++i) {
517                 syslog(LOG_DEBUG, "inboxrules: processing rule %d is %s", i, field_keys[ ii->rules[i].compared_field ]);
518                 rule_activated = 0;
519
520                 // Before doing a field compare, check to see if we have the correct parts of the message in memory.
521
522                 switch(ii->rules[i].compared_field) {
523                         // These fields require loading only the top-level headers
524                         case field_from:                // From:
525                         case field_tocc:                // To: or Cc:
526                         case field_subject:             // Subject:
527                         case field_replyto:             // Reply-to:
528                         case field_listid:              // List-ID:
529                         case field_envto:               // Envelope-to:
530                         case field_envfrom:             // Return-path:
531                                 if (!headers_loaded) {
532                                         syslog(LOG_DEBUG, "inboxrules: loading headers for message %ld", msgnum);
533                                         msg = CtdlFetchMessage(msgnum, 0);
534                                         if (!msg) {
535                                                 return;
536                                         }
537                                         headers_loaded = 1;
538                                 }
539                                 break;
540                         // These fields are not stored as Citadel headers, and therefore require a full message load.
541                         case field_sender:
542                         case field_resentfrom:
543                         case field_resentto:
544                         case field_xmailer:
545                         case field_xspamflag:
546                         case field_xspamstatus:
547                                 if (!body_loaded) {
548                                         syslog(LOG_DEBUG, "inboxrules: loading all of message %ld", msgnum);
549                                         if (msg != NULL) {
550                                                 CM_Free(msg);
551                                         }
552                                         msg = CtdlFetchMessage(msgnum, 1);
553                                         if (!msg) {
554                                                 return;
555                                         }
556                                         headers_loaded = 1;
557                                         body_loaded = 1;
558                                 }
559                                 break;
560                         case field_size:
561                                 if (!metadata_loaded) {
562                                         syslog(LOG_DEBUG, "inboxrules: loading metadata for message %ld", msgnum);
563                                         GetMetaData(&smi, msgnum);
564                                         metadata_loaded = 1;
565                                 }
566                                 break;
567                         case field_all:
568                                 syslog(LOG_DEBUG, "inboxrules: this is an always-on rule");
569                                 break;
570                         default:
571                                 syslog(LOG_DEBUG, "inboxrules: unknown rule key");
572                 }
573
574                 // If the rule involves a field comparison, load the field to be compared.
575                 compare_me[0] = 0;
576                 compare_compound = 0;
577                 switch(ii->rules[i].compared_field) {
578                         case field_from:                // From:
579                                 if ( (!IsEmptyStr(msg->cm_fields[erFc822Addr])) && (!IsEmptyStr(msg->cm_fields[erFc822Addr])) ) {
580                                         snprintf(compare_me, sizeof compare_me, "%s|%s",
581                                                 msg->cm_fields[eAuthor],
582                                                 msg->cm_fields[erFc822Addr]
583                                         );
584                                         compare_compound = 1;           // there will be two fields to compare "name|address"
585                                 }
586                                 else if (!IsEmptyStr(msg->cm_fields[erFc822Addr])) {
587                                         safestrncpy(compare_me, msg->cm_fields[erFc822Addr], sizeof compare_me);
588                                 }
589                                 else if (!IsEmptyStr(msg->cm_fields[eAuthor])) {
590                                         safestrncpy(compare_me, msg->cm_fields[eAuthor], sizeof compare_me);
591                                 }
592                                 break;
593                         case field_tocc:                // To: or Cc:
594                                 if (!IsEmptyStr(msg->cm_fields[eRecipient])) {
595                                         safestrncpy(compare_me, msg->cm_fields[eRecipient], sizeof compare_me);
596                                 }
597                                 if (!IsEmptyStr(msg->cm_fields[eCarbonCopY])) {
598                                         if (!IsEmptyStr(compare_me)) {
599                                                 strcat(compare_me, ",");
600                                         }
601                                         safestrncpy(&compare_me[strlen(compare_me)], msg->cm_fields[eCarbonCopY], (sizeof compare_me - strlen(compare_me)));
602                                 }
603                                 break;
604                         case field_subject:             // Subject:
605                                 if (!IsEmptyStr(msg->cm_fields[eMsgSubject])) {
606                                         safestrncpy(compare_me, msg->cm_fields[eMsgSubject], sizeof compare_me);
607                                 }
608                                 break;
609                         case field_replyto:             // Reply-to:
610                                 if (!IsEmptyStr(msg->cm_fields[eReplyTo])) {
611                                         safestrncpy(compare_me, msg->cm_fields[eReplyTo], sizeof compare_me);
612                                 }
613                                 break;
614                         case field_listid:              // List-ID:
615                                 if (!IsEmptyStr(msg->cm_fields[eListID])) {
616                                         safestrncpy(compare_me, msg->cm_fields[eListID], sizeof compare_me);
617                                 }
618                                 break;
619                         case field_envto:               // Envelope-to:
620                                 if (!IsEmptyStr(msg->cm_fields[eenVelopeTo])) {
621                                         safestrncpy(compare_me, msg->cm_fields[eenVelopeTo], sizeof compare_me);
622                                 }
623                                 break;
624                         case field_envfrom:             // Return-path:
625                                 if (!IsEmptyStr(msg->cm_fields[eMessagePath])) {
626                                         safestrncpy(compare_me, msg->cm_fields[eMessagePath], sizeof compare_me);
627                                 }
628                                 break;
629
630                         case field_sender:
631                         case field_resentfrom:
632                         case field_resentto:
633                         case field_xmailer:
634                         case field_xspamflag:
635                         case field_xspamstatus:
636
637                         default:
638                                 break;
639                 }
640
641                 // Message data to compare is loaded, now do something.
642                 switch(ii->rules[i].compared_field) {
643                         case field_from:                // From:
644                         case field_tocc:                // To: or Cc:
645                         case field_subject:             // Subject:
646                         case field_replyto:             // Reply-to:
647                         case field_listid:              // List-ID:
648                         case field_envto:               // Envelope-to:
649                         case field_envfrom:             // Return-path:
650                         case field_sender:
651                         case field_resentfrom:
652                         case field_resentto:
653                         case field_xmailer:
654                         case field_xspamflag:
655                         case field_xspamstatus:
656
657                                 // For all of the above fields, we can compare the field we've loaded into the buffer.
658                                 syslog(LOG_DEBUG, "Value of field to compare is: <%s>", compare_me);
659                                 int substring_match = (bmstrcasestr(compare_me, ii->rules[i].compared_value) ? 1 : 0);
660                                 int exact_match = 0;
661                                 if (compare_compound) {
662                                         char *sep = strchr(compare_me, '|');
663                                         if (sep) {
664                                                 *sep = 0;
665                                                 exact_match =
666                                                         (strcasecmp(compare_me, ii->rules[i].compared_value) ? 0 : 1)
667                                                         + (strcasecmp(++sep, ii->rules[i].compared_value) ? 0 : 1)
668                                                 ;
669                                         }
670                                 }
671                                 else {
672                                         exact_match = (strcasecmp(compare_me, ii->rules[i].compared_value) ? 0 : 1);
673                                 }
674                                 syslog(LOG_DEBUG, "substring match: %d", substring_match);
675                                 syslog(LOG_DEBUG, "exact match: %d", exact_match);
676                                 switch(ii->rules[i].field_compare_op) {
677                                         case fcomp_contains:
678                                         case fcomp_matches:
679                                                 rule_activated = substring_match;
680                                                 break;
681                                         case fcomp_notcontains:
682                                         case fcomp_notmatches:
683                                                 rule_activated = !substring_match;
684                                                 break;
685                                         case fcomp_is:
686                                                 rule_activated = exact_match;
687                                                 break;
688                                         case fcomp_isnot:
689                                                 rule_activated = !exact_match;
690                                                 break;
691                                 }
692                                 break;
693
694                         case field_size:
695                                 rule_activated = 0;
696                                 switch(ii->rules[i].field_compare_op) {
697                                         case scomp_larger:
698                                                 rule_activated = ((smi.meta_rfc822_length > ii->rules[i].compared_size) ? 1 : 0);
699                                                 break;
700                                         case scomp_smaller:
701                                                 rule_activated = ((smi.meta_rfc822_length < ii->rules[i].compared_size) ? 1 : 0);
702                                                 break;
703                                 }
704                                 break;
705                         case field_all:                 // The "all messages" rule ALWAYS triggers
706                                 rule_activated = 1;
707                                 break;
708                         default:                        // no matches, fall through and do nothing
709                                 syslog(LOG_WARNING, "inboxrules: an unknown field comparison was encountered");
710                                 rule_activated = 0;
711                                 break;
712                 }
713
714                 // If the rule matched, perform the requested action.
715                 if (rule_activated) {
716                         syslog(LOG_DEBUG, "inboxrules: rule activated");
717
718                         // Perform the requested action
719                         switch(ii->rules[i].action) {
720                                 case action_keep:
721                                         keep_message = 1;
722                                         break;
723                                 case action_discard:
724                                         keep_message = 0;
725                                         break;
726                                 case action_reject:
727                                         inbox_do_reject(&ii->rules[i], msg);
728                                         keep_message = 0;
729                                         break;
730                                 case action_fileinto:
731                                         keep_message = inbox_do_fileinto(&ii->rules[i], msgnum);
732                                         break;
733                                 case action_redirect:
734                                         keep_message = inbox_do_redirect(&ii->rules[i], msgnum);
735                                         break;
736                                 case action_vacation:
737                                         inbox_do_vacation(&ii->rules[i], msg);
738                                         keep_message = 1;
739                                         break;
740                         }
741
742                         // Now perform the "final" action (anything other than "stop" means continue)
743                         if (ii->rules[i].final_action == final_stop) {
744                                 syslog(LOG_DEBUG, "inboxrules: stop processing");
745                                 i = ii->num_rules + 1;                                  // throw us out of scope to stop
746                         }
747
748
749                 }
750                 else {
751                         syslog(LOG_DEBUG, "inboxrules: rule not activated");
752                 }
753         }
754
755         if (msg != NULL) {              // Delete the copy of the message that is currently in memory.  We don't need it anymore.
756                 CM_Free(msg);
757         }
758
759         if (!keep_message) {            // Delete the copy of the message that is currently in the inbox, if rules dictated that.
760                 syslog(LOG_DEBUG, "inboxrules: delete %ld from inbox", msgnum);
761                 CtdlDeleteMessages(CC->room.QRname, &msgnum, 1, "");                    // we're in the inbox already
762         }
763
764         ii->lastproc = msgnum;          // make note of the last message we processed, so we don't scan the whole inbox again
765 }
766
767
768 /*
769  * A user account is identified as requring inbox processing.
770  * Do it.
771  */
772 void do_inbox_processing_for_user(long usernum) {
773         struct CtdlMessage *msg;
774         struct inboxrules *ii;
775         char roomname[ROOMNAMELEN];
776         char username[64];
777
778         if (CtdlGetUserByNumber(&CC->user, usernum) != 0) {     // grab the user record
779                 return;                                         // and bail out if we were given an invalid user
780         }
781
782         strcpy(username, CC->user.fullname);                    // save the user name so we can fetch it later and lock it
783
784         if (CC->user.msgnum_inboxrules <= 0) {
785                 return;                                         // this user has no inbox rules
786         }
787
788         msg = CtdlFetchMessage(CC->user.msgnum_inboxrules, 1);
789         if (msg == NULL) {
790                 return;                                         // config msgnum is set but that message does not exist
791         }
792
793         ii = deserialize_inbox_rules(msg->cm_fields[eMesageText]);
794         CM_Free(msg);
795
796         if (ii == NULL) {
797                 return;                                         // config message exists but body is null
798         }
799
800         if (ii->lastproc > CC->user.lastproc_inboxrules) {      // There might be a "last message processed" number left over
801                 CC->user.lastproc_inboxrules = ii->lastproc;    // in the ruleset from a previous version.  Use this if it is
802         }                                                       // a higher number.
803         else {
804                 ii->lastproc = CC->user.lastproc_inboxrules;
805         }
806
807         long original_lastproc = ii->lastproc;
808         syslog(LOG_DEBUG, "inboxrules: for %s, messages newer than %ld", CC->user.fullname, original_lastproc);
809
810         // Go to the user's inbox room and process all new messages
811         snprintf(roomname, sizeof roomname, "%010ld.%s", usernum, MAILROOM);
812         if (CtdlGetRoom(&CC->room, roomname) == 0) {
813                 CtdlForEachMessage(MSGS_GT, ii->lastproc, NULL, NULL, NULL, inbox_do_msg, (void *) ii);
814         }
815
816         // Record the number of the last message we processed
817         if (ii->lastproc > original_lastproc) {
818                 CtdlGetUserLock(&CC->user, username);
819                 CC->user.lastproc_inboxrules = ii->lastproc;    // Avoid processing the entire inbox next time
820                 CtdlPutUserLock(&CC->user);
821         }
822
823         // And free the memory.
824         free_inbox_rules(ii);
825 }
826
827
828 /*
829  * Here is an array of users (by number) who have received messages in their inbox and may require processing.
830  */
831 long *users_requiring_inbox_processing = NULL;
832 int num_urip = 0;
833 int num_urip_alloc = 0;
834
835
836 /*
837  * Perform inbox processing for all rooms which require it
838  */
839 void perform_inbox_processing(void) {
840         if (num_urip == 0) {
841                 return;                                                                                 // no action required
842         }
843
844         for (int i=0; i<num_urip; ++i) {
845                 do_inbox_processing_for_user(users_requiring_inbox_processing[i]);
846         }
847
848         free(users_requiring_inbox_processing);
849         users_requiring_inbox_processing = NULL;
850         num_urip = 0;
851         num_urip_alloc = 0;
852 }
853
854
855 /*
856  * This function is called after a message is saved to a room.
857  * If it's someone's inbox, we have to check for inbox rules
858  */
859 int serv_inboxrules_roomhook(struct ctdlroom *room) {
860
861         // Is this someone's inbox?
862         if (!strcasecmp(&room->QRname[11], MAILROOM)) {
863                 long usernum = atol(room->QRname);
864                 if (usernum > 0) {
865
866                         // first check to see if this user is already on the list
867                         if (num_urip > 0) {
868                                 for (int i=0; i<=num_urip; ++i) {
869                                         if (users_requiring_inbox_processing[i] == usernum) {           // already on the list!
870                                                 return(0);
871                                         }
872                                 }
873                         }
874
875                         // make room if we need to
876                         if (num_urip_alloc == 0) {
877                                 num_urip_alloc = 100;
878                                 users_requiring_inbox_processing = malloc(sizeof(long) * num_urip_alloc);
879                         }
880                         else if (num_urip >= num_urip_alloc) {
881                                 num_urip_alloc += 100;
882                                 users_requiring_inbox_processing = realloc(users_requiring_inbox_processing, (sizeof(long) * num_urip_alloc));
883                         }
884                         
885                         // now add the user to the list
886                         users_requiring_inbox_processing[num_urip++] = usernum;
887                 }
888         }
889
890         // No errors are possible from this function.
891         return(0);
892 }
893
894
895
896 /*
897  * Get InBox Rules
898  *
899  * This is a client-facing function which fetches the user's inbox rules -- it omits all lines containing anything other than a rule.
900  * 
901  * hmmmmm ... should we try to rebuild this in terms of deserialize_inbox_rules() instread?
902  */
903 void cmd_gibr(char *argbuf) {
904
905         if (CtdlAccessCheck(ac_logged_in)) return;
906
907         cprintf("%d inbox rules for %s\n", LISTING_FOLLOWS, CC->user.fullname);
908
909         struct CtdlMessage *msg = CtdlFetchMessage(CC->user.msgnum_inboxrules, 1);
910         if (msg != NULL) {
911                 if (!CM_IsEmpty(msg, eMesageText)) {
912                         char *token; 
913                         char *rest = msg->cm_fields[eMesageText];
914                         while ((token = strtok_r(rest, "\n", &rest))) {
915
916                                 // for backwards compatibility, "# WEBCIT_RULE" is an alias for "rule" 
917                                 if (!strncasecmp(token, "# WEBCIT_RULE|", 14)) {
918                                         strcpy(token, "rule|"); 
919                                         strcpy(&token[5], &token[14]);
920                                 }
921
922                                 // Output only lines containing rules.
923                                 if (!strncasecmp(token, "rule|", 5)) {
924                                         cprintf("%s\n", token); 
925                                 }
926                                 else {
927                                         cprintf("# invalid rule found : %s\n", token);
928                                 }
929                         }
930                 }
931                 CM_Free(msg);
932         }
933         cprintf("000\n");
934 }
935
936
937 /*
938  * Rewrite the rule set to disk after it has been modified
939  * Called by cmd_pibr()
940  * Returns the msgnum of the new rules message
941  */
942 void rewrite_rules_to_disk(const char *new_config) {
943         long old_msgnum = CC->user.msgnum_inboxrules;
944         char userconfigroomname[ROOMNAMELEN];
945         CtdlMailboxName(userconfigroomname, sizeof userconfigroomname, &CC->user, USERCONFIGROOM);
946         long new_msgnum = quickie_message("Citadel", NULL, NULL, userconfigroomname, new_config, FMT_RFC822, "inbox rules configuration");
947         CtdlGetUserLock(&CC->user, CC->curr_user);
948         CC->user.msgnum_inboxrules = new_msgnum;                // Now we know where to get the rules next time
949         CC->user.lastproc_inboxrules = new_msgnum;              // Avoid processing the entire inbox next time
950         CtdlPutUserLock(&CC->user);
951         if (old_msgnum > 0) {
952                 syslog(LOG_DEBUG, "Deleting old message %ld from %s", old_msgnum, userconfigroomname);
953                 CtdlDeleteMessages(userconfigroomname, &old_msgnum, 1, "");
954         }
955 }
956
957
958 /*
959  * Put InBox Rules
960  *
961  * User transmits the new inbox rules for the account.  They are inserted into the account, replacing the ones already there.
962  */
963 void cmd_pibr(char *argbuf) {
964         if (CtdlAccessCheck(ac_logged_in)) return;
965
966         unbuffer_output();
967         cprintf("%d send new rules\n", SEND_LISTING);
968         char *newrules = CtdlReadMessageBody(HKEY("000"), CtdlGetConfigLong("c_maxmsglen"), NULL, 0);
969         StrBuf *NewConfig = NewStrBufPlain("Content-type: application/x-citadel-sieve-config; charset=UTF-8\nContent-transfer-encoding: 8bit\n\n", -1);
970
971         char *token; 
972         char *rest = newrules;
973         while ((token = strtok_r(rest, "\n", &rest))) {
974                 // Accept only lines containing rules
975                 if (!strncasecmp(token, "rule|", 5)) {
976                         StrBufAppendBufPlain(NewConfig, token, -1, 0);
977                         StrBufAppendBufPlain(NewConfig, HKEY("\n"), 0);
978                 }
979         }
980         free(newrules);
981         rewrite_rules_to_disk(ChrPtr(NewConfig));
982         FreeStrBuf(&NewConfig);
983 }
984
985
986 CTDL_MODULE_INIT(sieve)
987 {
988         if (!threading)
989         {
990                 CtdlRegisterProtoHook(cmd_gibr, "GIBR", "Get InBox Rules");
991                 CtdlRegisterProtoHook(cmd_pibr, "PIBR", "Put InBox Rules");
992                 CtdlRegisterRoomHook(serv_inboxrules_roomhook);
993                 CtdlRegisterSessionHook(perform_inbox_processing, EVT_HOUSE, PRIO_HOUSE + 10);
994         }
995         
996         /* return our module name for the log */
997         return "inboxrules";
998 }