2012-09-16 [mones] 3.8.1cvs60
[claws.git] / src / matcher.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 2002-2012 by the Claws Mail Team and Hiroyuki Yamamoto
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
17  * 
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #include "claws-features.h"
23 #endif
24
25 #include <glib.h>
26 #include <glib/gi18n.h>
27 #include <ctype.h>
28 #include <string.h>
29 #include <stdlib.h>
30 #include <errno.h>
31
32 #ifdef USE_PTHREAD
33 #include <pthread.h>
34 #endif
35
36 #include "defs.h"
37 #include "utils.h"
38 #include "procheader.h"
39 #include "matcher.h"
40 #include "matcher_parser.h"
41 #include "prefs_gtk.h"
42 #include "addr_compl.h"
43 #include "codeconv.h"
44 #include "quoted-printable.h"
45 #include "claws.h"
46 #include <ctype.h>
47 #include "prefs_common.h"
48 #include "log.h"
49 #include "tags.h"
50 #include "folder_item_prefs.h"
51
52 /*!
53  *\brief        Keyword lookup element
54  */
55 struct _MatchParser {
56         gint id;                /*!< keyword id */ 
57         gchar *str;             /*!< keyword */
58 };
59 typedef struct _MatchParser MatchParser;
60
61 /*!
62  *\brief        Table with strings and ids used by the lexer and
63  *              the parser. New keywords can be added here.
64  */
65 static const MatchParser matchparser_tab[] = {
66         /* msginfo flags */
67         {MATCHCRITERIA_ALL, "all"},
68         {MATCHCRITERIA_UNREAD, "unread"},
69         {MATCHCRITERIA_NOT_UNREAD, "~unread"},
70         {MATCHCRITERIA_NEW, "new"},
71         {MATCHCRITERIA_NOT_NEW, "~new"},
72         {MATCHCRITERIA_MARKED, "marked"},
73         {MATCHCRITERIA_NOT_MARKED, "~marked"},
74         {MATCHCRITERIA_DELETED, "deleted"},
75         {MATCHCRITERIA_NOT_DELETED, "~deleted"},
76         {MATCHCRITERIA_REPLIED, "replied"},
77         {MATCHCRITERIA_NOT_REPLIED, "~replied"},
78         {MATCHCRITERIA_FORWARDED, "forwarded"},
79         {MATCHCRITERIA_NOT_FORWARDED, "~forwarded"},
80         {MATCHCRITERIA_LOCKED, "locked"},
81         {MATCHCRITERIA_NOT_LOCKED, "~locked"},
82         {MATCHCRITERIA_COLORLABEL, "colorlabel"},
83         {MATCHCRITERIA_NOT_COLORLABEL, "~colorlabel"},
84         {MATCHCRITERIA_IGNORE_THREAD, "ignore_thread"},
85         {MATCHCRITERIA_NOT_IGNORE_THREAD, "~ignore_thread"},
86         {MATCHCRITERIA_WATCH_THREAD, "watch_thread"},
87         {MATCHCRITERIA_NOT_WATCH_THREAD, "~watch_thread"},
88         {MATCHCRITERIA_SPAM, "spam"},
89         {MATCHCRITERIA_NOT_SPAM, "~spam"},
90         {MATCHCRITERIA_HAS_ATTACHMENT, "has_attachment"},
91         {MATCHCRITERIA_HAS_NO_ATTACHMENT, "~has_attachment"},
92         {MATCHCRITERIA_SIGNED, "signed"},
93         {MATCHCRITERIA_NOT_SIGNED, "~signed"},
94
95         /* msginfo headers */
96         {MATCHCRITERIA_SUBJECT, "subject"},
97         {MATCHCRITERIA_NOT_SUBJECT, "~subject"},
98         {MATCHCRITERIA_FROM, "from"},
99         {MATCHCRITERIA_NOT_FROM, "~from"},
100         {MATCHCRITERIA_TO, "to"},
101         {MATCHCRITERIA_NOT_TO, "~to"},
102         {MATCHCRITERIA_CC, "cc"},
103         {MATCHCRITERIA_NOT_CC, "~cc"},
104         {MATCHCRITERIA_TO_OR_CC, "to_or_cc"},
105         {MATCHCRITERIA_NOT_TO_AND_NOT_CC, "~to_or_cc"},
106         {MATCHCRITERIA_TAG, "tag"},
107         {MATCHCRITERIA_NOT_TAG, "~tag"},
108         {MATCHCRITERIA_TAGGED, "tagged"},
109         {MATCHCRITERIA_NOT_TAGGED, "~tagged"},
110         {MATCHCRITERIA_AGE_GREATER, "age_greater"},
111         {MATCHCRITERIA_AGE_LOWER, "age_lower"},
112         {MATCHCRITERIA_NEWSGROUPS, "newsgroups"},
113         {MATCHCRITERIA_NOT_NEWSGROUPS, "~newsgroups"},
114         {MATCHCRITERIA_INREPLYTO, "inreplyto"},
115         {MATCHCRITERIA_NOT_INREPLYTO, "~inreplyto"},
116         {MATCHCRITERIA_REFERENCES, "references"},
117         {MATCHCRITERIA_NOT_REFERENCES, "~references"},
118         {MATCHCRITERIA_SCORE_GREATER, "score_greater"},
119         {MATCHCRITERIA_SCORE_LOWER, "score_lower"},
120         {MATCHCRITERIA_SCORE_EQUAL, "score_equal"},
121         {MATCHCRITERIA_PARTIAL, "partial"},
122         {MATCHCRITERIA_NOT_PARTIAL, "~partial"},
123         {MATCHCRITERIA_FOUND_IN_ADDRESSBOOK, "found_in_addressbook"},
124         {MATCHCRITERIA_NOT_FOUND_IN_ADDRESSBOOK, "~found_in_addressbook"},
125
126         {MATCHCRITERIA_SIZE_GREATER, "size_greater"},
127         {MATCHCRITERIA_SIZE_SMALLER, "size_smaller"},
128         {MATCHCRITERIA_SIZE_EQUAL,   "size_equal"},
129
130         /* content have to be read */
131         {MATCHCRITERIA_HEADER, "header"},
132         {MATCHCRITERIA_NOT_HEADER, "~header"},
133         {MATCHCRITERIA_HEADERS_PART, "headers_part"},
134         {MATCHCRITERIA_NOT_HEADERS_PART, "~headers_part"},
135         {MATCHCRITERIA_MESSAGE, "message"},
136         {MATCHCRITERIA_NOT_MESSAGE, "~message"},
137         {MATCHCRITERIA_BODY_PART, "body_part"},
138         {MATCHCRITERIA_NOT_BODY_PART, "~body_part"},
139         {MATCHCRITERIA_TEST, "test"},
140         {MATCHCRITERIA_NOT_TEST, "~test"},
141
142         /* match type */
143         {MATCHTYPE_MATCHCASE, "matchcase"},
144         {MATCHTYPE_MATCH, "match"},
145         {MATCHTYPE_REGEXPCASE, "regexpcase"},
146         {MATCHTYPE_REGEXP, "regexp"},
147
148         /* actions */
149         {MATCHACTION_SCORE, "score"},    /* for backward compatibility */
150         {MATCHACTION_MOVE, "move"},
151         {MATCHACTION_COPY, "copy"},
152         {MATCHACTION_DELETE, "delete"},
153         {MATCHACTION_MARK, "mark"},
154         {MATCHACTION_UNMARK, "unmark"},
155         {MATCHACTION_LOCK, "lock"},
156         {MATCHACTION_UNLOCK, "unlock"},
157         {MATCHACTION_MARK_AS_READ, "mark_as_read"},
158         {MATCHACTION_MARK_AS_UNREAD, "mark_as_unread"},
159         {MATCHACTION_MARK_AS_SPAM, "mark_as_spam"},
160         {MATCHACTION_MARK_AS_HAM, "mark_as_ham"},
161         {MATCHACTION_FORWARD, "forward"},
162         {MATCHACTION_FORWARD_AS_ATTACHMENT, "forward_as_attachment"},
163         {MATCHACTION_EXECUTE, "execute"},
164         {MATCHACTION_COLOR, "color"},
165         {MATCHACTION_REDIRECT, "redirect"},
166         {MATCHACTION_CHANGE_SCORE, "change_score"},
167         {MATCHACTION_SET_SCORE, "set_score"},
168         {MATCHACTION_STOP, "stop"},
169         {MATCHACTION_HIDE, "hide"},
170         {MATCHACTION_IGNORE, "ignore"},
171         {MATCHACTION_WATCH, "watch"},
172         {MATCHACTION_ADD_TO_ADDRESSBOOK, "add_to_addressbook"},
173         {MATCHACTION_SET_TAG, "set_tag"},
174         {MATCHACTION_UNSET_TAG, "unset_tag"},
175         {MATCHACTION_CLEAR_TAGS, "clear_tags"},
176 };
177
178 enum {
179         MATCH_ANY = 0,
180         MATCH_ALL = 1,
181         MATCH_ONE = 2
182 };
183
184 extern gboolean debug_filtering_session;
185
186 /*!
187  *\brief        Look up table with keywords defined in \sa matchparser_tab
188  */
189 static GHashTable *matchparser_hashtab;
190
191 /*!
192  *\brief        Translate keyword id to keyword string
193  *
194  *\param        id Id of keyword
195  *
196  *\return       const gchar * Keyword
197  */
198 const gchar *get_matchparser_tab_str(gint id)
199 {
200         gint i;
201
202         for (i = 0; i < sizeof matchparser_tab / sizeof matchparser_tab[0]; i++) {
203                 if (matchparser_tab[i].id == id)
204                         return matchparser_tab[i].str;
205         }
206         return NULL;
207 }
208
209 /*!
210  *\brief        Create keyword lookup table
211  */
212 static void create_matchparser_hashtab(void)
213 {
214         int i;
215         
216         if (matchparser_hashtab) return;
217         matchparser_hashtab = g_hash_table_new(g_str_hash, g_str_equal);
218         for (i = 0; i < sizeof matchparser_tab / sizeof matchparser_tab[0]; i++)
219                 g_hash_table_insert(matchparser_hashtab,
220                                     matchparser_tab[i].str,
221                                     (gpointer) &matchparser_tab[i]);
222 }
223
224 /*!
225  *\brief        Return a keyword id from a keyword string
226  *
227  *\param        str Keyword string
228  *
229  *\return       gint Keyword id
230  */
231 gint get_matchparser_tab_id(const gchar *str)
232 {
233         MatchParser *res;
234
235         if (NULL != (res = g_hash_table_lookup(matchparser_hashtab, str))) {
236                 return res->id;
237         } else
238                 return -1;
239 }
240
241 /* **************** data structure allocation **************** */
242
243 /*!
244  *\brief        Allocate a structure for a filtering / scoring
245  *              "condition" (a matcher structure)
246  *
247  *\param        criteria Criteria ID (MATCHCRITERIA_XXXX)
248  *\param        header Header string (if criteria is MATCHCRITERIA_HEADER
249                         or MATCHCRITERIA_FOUND_IN_ADDRESSBOOK)
250  *\param        matchtype Type of action (MATCHTYPE_XXX)
251  *\param        expr String value or expression to check
252  *\param        value Integer value to check
253  *
254  *\return       MatcherProp * Pointer to newly allocated structure
255  */
256 MatcherProp *matcherprop_new(gint criteria, const gchar *header,
257                               gint matchtype, const gchar *expr,
258                               int value)
259 {
260         MatcherProp *prop;
261
262         prop = g_new0(MatcherProp, 1);
263         prop->criteria = criteria;
264         prop->header = header != NULL ? g_strdup(header) : NULL;
265
266         prop->expr = expr != NULL ? g_strdup(expr) : NULL;
267
268         prop->matchtype = matchtype;
269         prop->preg = NULL;
270         prop->value = value;
271         prop->error = 0;
272
273         return prop;
274 }
275
276 /*!
277  *\brief        Free a matcher structure
278  *
279  *\param        prop Pointer to matcher structure allocated with
280  *              #matcherprop_new
281  */
282 void matcherprop_free(MatcherProp *prop)
283 {
284         g_free(prop->expr);
285         g_free(prop->header);
286         if (prop->preg != NULL) {
287                 regfree(prop->preg);
288                 g_free(prop->preg);
289         }
290         g_free(prop);
291 }
292
293 /*!
294  *\brief        Copy a matcher structure
295  *
296  *\param        src Matcher structure to copy
297  *
298  *\return       MatcherProp * Pointer to newly allocated matcher structure
299  */
300 MatcherProp *matcherprop_copy(const MatcherProp *src)
301 {
302         MatcherProp *prop = g_new0(MatcherProp, 1);
303         
304         prop->criteria = src->criteria;
305         prop->header = src->header ? g_strdup(src->header) : NULL;
306         prop->expr = src->expr ? g_strdup(src->expr) : NULL;
307         prop->matchtype = src->matchtype;
308         
309         prop->preg = NULL; /* will be re-evaluated */
310         prop->value = src->value;
311         prop->error = src->error;       
312         return prop;            
313 }
314
315 /* ************** match ******************************/
316
317 static gboolean match_with_addresses_in_addressbook
318         (MatcherProp *prop, GSList *address_list, gint type,
319          gchar* folderpath, gint match)
320 {
321         GSList *walk = NULL;
322         gboolean found = FALSE;
323         gchar *path = NULL;
324
325         cm_return_val_if_fail(address_list != NULL, FALSE);
326
327         debug_print("match_with_addresses_in_addressbook(%d, %s)\n",
328                                 g_slist_length(address_list), folderpath?folderpath:"(null)");
329
330         if (folderpath == NULL ||
331                 strcasecmp(folderpath, "Any") == 0 ||
332                 *folderpath == '\0')
333                 path = NULL;
334         else
335                 path = folderpath;
336         
337         start_address_completion(path);
338
339         for (walk = address_list; walk != NULL; walk = walk->next) {
340                 /* exact matching of email address */
341                 guint num_addr = complete_address(walk->data);
342                 found = FALSE;
343                 if (num_addr > 1) {
344                         /* skip first item (this is the search string itself) */
345                         int i = 1;
346                         for (; i < num_addr && !found; i++) {
347                                 gchar *addr = get_complete_address(i);
348                                 extract_address(addr);
349                                 if (strcasecmp(addr, walk->data) == 0) {
350                                         found = TRUE;
351
352                                         /* debug output */
353                                         if (debug_filtering_session
354                                                         && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
355                                                 log_print(LOG_DEBUG_FILTERING,
356                                                                 "address [ %s ] matches\n",
357                                                                 (gchar *)walk->data);
358                                         }
359                                 }
360                                 g_free(addr);
361                         }
362                 }
363                 /* debug output */
364                 if (debug_filtering_session
365                                 && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH
366                                 && !found) {
367                         log_print(LOG_DEBUG_FILTERING,
368                                         "address [ %s ] does NOT match\n",
369                                         (gchar *)walk->data);
370                 }
371                 g_free(walk->data);
372
373                 if (match == MATCH_ALL) {
374                         /* if matching all addresses, stop if one doesn't match */
375                         if (!found) {
376                                 /* debug output */
377                                 if (debug_filtering_session
378                                                 && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
379                                         log_print(LOG_DEBUG_FILTERING,
380                                                         "not all address match (matching all)\n");
381                                 }
382                                 break;
383                         }
384                 } else if (match == MATCH_ANY) {
385                         /* if matching any address, stop if one does match */
386                         if (found) {
387                                 /* debug output */
388                                 if (debug_filtering_session
389                                                 && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
390                                         log_print(LOG_DEBUG_FILTERING,
391                                                         "at least one address matches (matching any)\n");
392                                 }
393                                 break;
394                         }
395                 }
396                 /* MATCH_ONE: there should be only one loop iteration */
397         }
398
399         end_address_completion();
400         
401         return found;
402 }
403
404 /*!
405  *\brief        Find out if a string matches a condition
406  *
407  *\param        prop Matcher structure
408  *\param        str String to check 
409  *
410  *\return       gboolean TRUE if str matches the condition in the 
411  *              matcher structure
412  */
413 static gboolean matcherprop_string_match(MatcherProp *prop, const gchar *str,
414                                          const gchar *debug_context)
415 {
416         gchar *str1;
417         gchar *down_expr;
418         gboolean ret = FALSE;
419         gboolean should_free = FALSE;
420         if (str == NULL)
421                 return FALSE;
422
423         if (prop->matchtype == MATCHTYPE_REGEXPCASE ||
424             prop->matchtype == MATCHTYPE_MATCHCASE) {
425                 str1 = g_utf8_casefold(str, -1);
426                 down_expr = g_utf8_casefold(prop->expr, -1);
427                 should_free = TRUE;
428         } else {
429                 str1 = (gchar *)str;
430                 down_expr = (gchar *)prop->expr;
431                 should_free = FALSE;
432         }
433
434         switch (prop->matchtype) {
435         case MATCHTYPE_REGEXPCASE:
436         case MATCHTYPE_REGEXP:
437 #ifndef G_OS_WIN32
438                 if (!prop->preg && (prop->error == 0)) {
439                         prop->preg = g_new0(regex_t, 1);
440                         /* if regexp then don't use the escaped string */
441                         if (regcomp(prop->preg, down_expr,
442                                     REG_NOSUB | REG_EXTENDED
443                                     | ((prop->matchtype == MATCHTYPE_REGEXPCASE)
444                                     ? REG_ICASE : 0)) != 0) {
445                                 prop->error = 1;
446                                 g_free(prop->preg);
447                                 prop->preg = NULL;
448                         }
449                 }
450                 if (prop->preg == NULL) {
451                         ret = FALSE;
452                         goto free_strs;
453                 }
454                 
455                 if (regexec(prop->preg, str1, 0, NULL, 0) == 0)
456                         ret = TRUE;
457                 else
458                         ret = FALSE;
459
460                 /* debug output */
461                 if (debug_filtering_session
462                                 && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
463                         gchar *stripped = g_strdup(str);
464
465                         strretchomp(stripped);
466                         if (ret) {
467                                 log_print(LOG_DEBUG_FILTERING,
468                                                 "%s value [ %s ] matches regular expression [ %s ] (%s)\n",
469                                                 debug_context, stripped, prop->expr,
470                                                 prop->matchtype == MATCHTYPE_REGEXP ? _("Case sensitive"):_("Case insensitive"));
471                         } else {
472                                 log_print(LOG_DEBUG_FILTERING,
473                                                 "%s value [ %s ] does NOT match regular expression [ %s ] (%s)\n",
474                                                 debug_context, stripped, prop->expr,
475                                                 prop->matchtype == MATCHTYPE_REGEXP ? _("Case sensitive"):_("Case insensitive"));
476                         }
477                         g_free(stripped);
478                 }
479                 break;
480 #endif                  
481         case MATCHTYPE_MATCHCASE:
482         case MATCHTYPE_MATCH:
483                 ret = (strstr(str1, down_expr) != NULL);
484
485                 /* debug output */
486                 if (debug_filtering_session
487                                 && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
488                         gchar *stripped = g_strdup(str);
489
490                         strretchomp(stripped);
491                         if (ret) {
492                                 log_print(LOG_DEBUG_FILTERING,
493                                                 "%s value [ %s ] contains [ %s ] (%s)\n",
494                                                 debug_context, stripped, prop->expr,
495                                                 prop->matchtype == MATCHTYPE_MATCH ? _("Case sensitive"):_("Case insensitive"));
496                         } else {
497                                 log_print(LOG_DEBUG_FILTERING,
498                                                 "%s value [ %s ] does NOT contain [ %s ] (%s)\n",
499                                                 debug_context, stripped, prop->expr,
500                                                 prop->matchtype == MATCHTYPE_MATCH ? _("Case sensitive"):_("Case insensitive"));
501                         }
502                         g_free(stripped);
503                 }
504                 break;
505
506         default:
507                 break;
508         }
509         
510 free_strs:
511         if (should_free) {
512                 g_free(str1);
513                 g_free(down_expr);
514         }
515         return ret;
516 }
517
518 /*!
519  *\brief        Find out if a tag matches a condition
520  *
521  *\param        prop Matcher structure
522  *\param        msginfo message to check
523  *
524  *\return       gboolean TRUE if msginfo matches the condition in the 
525  *              matcher structure
526  */
527 static gboolean matcherprop_tag_match(MatcherProp *prop, MsgInfo *msginfo,
528                                          const gchar *debug_context)
529 {
530         gboolean ret = FALSE;
531         GSList *cur;
532
533         if (msginfo == NULL || msginfo->tags == NULL)
534                 return FALSE;
535
536         for (cur = msginfo->tags; cur; cur = cur->next) {
537                 const gchar *str = tags_get_tag(GPOINTER_TO_INT(cur->data));
538                 if (!str)
539                         continue;
540                 if (matcherprop_string_match(prop, str, debug_context)) {
541                         ret = TRUE;
542                         break;
543                 }
544         }
545         return ret;
546 }
547
548 /*!
549  *\brief        Find out if the string-ed list matches a condition
550  *
551  *\param        prop Matcher structure
552  *\param        list GSList of strings to check
553  *
554  *\return       gboolean TRUE if str matches the condition in the 
555  *              matcher structure
556  */
557 static gboolean matcherprop_list_match(MatcherProp *prop, const GSList *list,
558 const gchar *debug_context)
559 {
560         const GSList *cur;
561
562         for(cur = list; cur != NULL; cur = cur->next) {
563                 if (matcherprop_string_match(prop, (gchar *)cur->data, debug_context))
564                         return TRUE;
565         }
566         return FALSE;
567 }
568
569 static gboolean matcherprop_header_line_match(MatcherProp *prop, const gchar *hdr,
570                                               const gchar *str, const gchar *debug_context)
571 {
572         gchar *line = NULL;
573         gboolean res = FALSE;
574
575         if (hdr == NULL || str == NULL)
576                 return FALSE;
577
578         line = g_strdup_printf("%s %s", hdr, str);
579         res = matcherprop_string_match(prop, line, debug_context);
580         g_free(line);
581        
582         return res;
583 }
584
585 #ifdef USE_PTHREAD
586 typedef struct _thread_data {
587         const gchar *cmd;
588         gboolean done;
589 } thread_data;
590 #endif
591
592 #ifdef USE_PTHREAD
593 static void *matcher_test_thread(void *data)
594 {
595         thread_data *td = (thread_data *)data;
596         int result = -1;
597
598         pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
599         pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
600
601         result = system(td->cmd);
602         td->done = TRUE; /* let the caller thread join() */
603         return GINT_TO_POINTER(result);
604 }
605 #endif
606
607 /*!
608  *\brief        Execute a command defined in the matcher structure
609  *
610  *\param        prop Pointer to matcher structure
611  *\param        info Pointer to message info structure
612  *
613  *\return       gboolean TRUE if command was executed succesfully
614  */
615 static gboolean matcherprop_match_test(const MatcherProp *prop, 
616                                           MsgInfo *info)
617 {
618         gchar *file;
619         gchar *cmd;
620         gint retval;
621 #ifdef USE_PTHREAD
622         pthread_t pt;
623         pthread_attr_t pta;
624         thread_data *td = g_new0(thread_data, 1);
625         void *res = NULL;
626         time_t start_time = time(NULL);
627 #endif
628
629         file = procmsg_get_message_file(info);
630         if (file == NULL) {
631 #ifdef USE_PTHREAD
632                 g_free(td);
633 #endif
634                 return FALSE;
635         }
636         g_free(file);           
637
638         cmd = matching_build_command(prop->expr, info);
639         if (cmd == NULL) {
640 #ifdef USE_PTHREAD
641                 g_free(td);
642 #endif  
643                 return FALSE;
644 }
645
646 #ifdef USE_PTHREAD
647         /* debug output */
648         if (debug_filtering_session
649                         && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
650                 log_print(LOG_DEBUG_FILTERING,
651                                 "starting threaded command [ %s ]\n",
652                                 cmd);
653         }
654
655         td->cmd = cmd;
656         td->done = FALSE;
657         if (pthread_attr_init(&pta) != 0 ||
658             pthread_attr_setdetachstate(&pta, PTHREAD_CREATE_JOINABLE) != 0 ||
659             pthread_create(&pt, &pta, matcher_test_thread, td) != 0)
660                 retval = system(cmd);
661         else {
662                 debug_print("waiting for test thread\n");
663                 while(!td->done) {
664                         /* don't let the interface freeze while waiting */
665                         claws_do_idle();
666                         if (time(NULL) - start_time > 30) {
667                                 pthread_cancel(pt);
668                                 td->done = TRUE;
669                                 retval = -1;
670                         }
671                 }
672                 pthread_join(pt, &res);
673                 retval = GPOINTER_TO_INT(res);
674                 debug_print(" test thread returned %d\n", retval);
675         }
676         g_free(td);
677 #else
678         /* debug output */
679         if (debug_filtering_session
680                         && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
681                 log_print(LOG_DEBUG_FILTERING,
682                                 "starting synchronous command [ %s ]\n",
683                                 cmd);
684         }
685
686         retval = system(cmd);
687 #endif
688         debug_print("Command exit code: %d\n", retval);
689
690         /* debug output */
691         if (debug_filtering_session
692                         && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
693                 log_print(LOG_DEBUG_FILTERING,
694                                 "command returned [ %d ]\n",
695                                 retval);
696         }
697
698         g_free(cmd);
699         return (retval == 0);
700 }
701
702 /*!
703  *\brief        Check if a message matches the condition in a matcher
704  *              structure.
705  *
706  *\param        prop Pointer to matcher structure
707  *\param        info Pointer to message info
708  *
709  *\return       gboolean TRUE if a match
710  */
711 static gboolean matcherprop_match(MatcherProp *prop, 
712                                   MsgInfo *info)
713 {
714         time_t t;
715
716         switch(prop->criteria) {
717         case MATCHCRITERIA_ALL:
718                 return TRUE;
719         case MATCHCRITERIA_UNREAD:
720                 return MSG_IS_UNREAD(info->flags);
721         case MATCHCRITERIA_NOT_UNREAD:
722                 return !MSG_IS_UNREAD(info->flags);
723         case MATCHCRITERIA_NEW:
724                 return MSG_IS_NEW(info->flags);
725         case MATCHCRITERIA_NOT_NEW:
726                 return !MSG_IS_NEW(info->flags);
727         case MATCHCRITERIA_MARKED:
728                 return MSG_IS_MARKED(info->flags);
729         case MATCHCRITERIA_NOT_MARKED:
730                 return !MSG_IS_MARKED(info->flags);
731         case MATCHCRITERIA_DELETED:
732                 return MSG_IS_DELETED(info->flags);
733         case MATCHCRITERIA_NOT_DELETED:
734                 return !MSG_IS_DELETED(info->flags);
735         case MATCHCRITERIA_REPLIED:
736                 return MSG_IS_REPLIED(info->flags);
737         case MATCHCRITERIA_NOT_REPLIED:
738                 return !MSG_IS_REPLIED(info->flags);
739         case MATCHCRITERIA_FORWARDED:
740                 return MSG_IS_FORWARDED(info->flags);
741         case MATCHCRITERIA_NOT_FORWARDED:
742                 return !MSG_IS_FORWARDED(info->flags);
743         case MATCHCRITERIA_LOCKED:
744                 return MSG_IS_LOCKED(info->flags);
745         case MATCHCRITERIA_NOT_LOCKED:
746                 return !MSG_IS_LOCKED(info->flags);
747         case MATCHCRITERIA_SPAM:
748                 return MSG_IS_SPAM(info->flags);
749         case MATCHCRITERIA_NOT_SPAM:
750                 return !MSG_IS_SPAM(info->flags);
751         case MATCHCRITERIA_HAS_ATTACHMENT:
752                 return MSG_IS_WITH_ATTACHMENT(info->flags);
753         case MATCHCRITERIA_HAS_NO_ATTACHMENT:
754                 return !MSG_IS_WITH_ATTACHMENT(info->flags);
755         case MATCHCRITERIA_SIGNED:
756                 return MSG_IS_SIGNED(info->flags);
757         case MATCHCRITERIA_NOT_SIGNED:
758                 return !MSG_IS_SIGNED(info->flags);
759         case MATCHCRITERIA_COLORLABEL:
760         {
761                 gint color = MSG_GET_COLORLABEL_VALUE(info->flags);
762                 gboolean ret = (color == prop->value);
763
764                 /* debug output */
765                 if (debug_filtering_session
766                                 && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
767                         if (ret) {
768                                 log_print(LOG_DEBUG_FILTERING,
769                                                 "message color value [ %d ] matches color value [ %d ]\n",
770                                                 color, prop->value);
771                         } else {
772                                 log_print(LOG_DEBUG_FILTERING,
773                                                 "message color value [ %d ] does NOT match color value [ %d ]\n",
774                                                 color, prop->value);
775                         }
776                 }
777                 return ret;
778         }
779         case MATCHCRITERIA_NOT_COLORLABEL:
780         {
781                 gint color = MSG_GET_COLORLABEL_VALUE(info->flags);
782                 gboolean ret = (color != prop->value);
783
784                 /* debug output */
785                 if (debug_filtering_session
786                                 && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
787                         if (ret) {
788                                 log_print(LOG_DEBUG_FILTERING,
789                                                 "message color value [ %d ] matches color value [ %d ]\n",
790                                                 color, prop->value);
791                         } else {
792                                 log_print(LOG_DEBUG_FILTERING,
793                                                 "message color value [ %d ] does NOT match color value [ %d ]\n",
794                                                 color, prop->value);
795                         }
796                 }
797                 return ret;
798         }
799         case MATCHCRITERIA_IGNORE_THREAD:
800                 return MSG_IS_IGNORE_THREAD(info->flags);
801         case MATCHCRITERIA_NOT_IGNORE_THREAD:
802                 return !MSG_IS_IGNORE_THREAD(info->flags);
803         case MATCHCRITERIA_WATCH_THREAD:
804                 return MSG_IS_WATCH_THREAD(info->flags);
805         case MATCHCRITERIA_NOT_WATCH_THREAD:
806                 return !MSG_IS_WATCH_THREAD(info->flags);
807         case MATCHCRITERIA_SUBJECT:
808                 return matcherprop_string_match(prop, info->subject,
809                                                 prefs_common_translated_header_name("Subject:"));
810         case MATCHCRITERIA_NOT_SUBJECT:
811                 return !matcherprop_string_match(prop, info->subject,
812                                                 prefs_common_translated_header_name("Subject:"));
813         case MATCHCRITERIA_FROM:
814         case MATCHCRITERIA_NOT_FROM:
815         {
816                 gchar *context;
817                 gboolean ret;
818
819                 context = g_strdup_printf(_("%s header"), prefs_common_translated_header_name("From:"));
820                 ret = matcherprop_string_match(prop, info->from, context);
821                 g_free(context);
822                 return (prop->criteria == MATCHCRITERIA_FROM)? ret : !ret;
823         }
824         case MATCHCRITERIA_TO:
825         case MATCHCRITERIA_NOT_TO:
826         {
827                 gchar *context;
828                 gboolean ret;
829
830                 context = g_strdup_printf(_("%s header"), prefs_common_translated_header_name("To:"));
831                 ret = matcherprop_string_match(prop, info->to, context);
832                 g_free(context);
833                 return (prop->criteria == MATCHCRITERIA_TO)? ret : !ret;
834         }
835         case MATCHCRITERIA_CC:
836         case MATCHCRITERIA_NOT_CC:
837         {
838                 gchar *context;
839                 gboolean ret;
840
841                 context = g_strdup_printf(_("%s header"), prefs_common_translated_header_name("Cc:"));
842                 ret = matcherprop_string_match(prop, info->cc, context);
843                 g_free(context);
844                 return (prop->criteria == MATCHCRITERIA_CC)? ret : !ret;
845         }
846         case MATCHCRITERIA_TO_OR_CC:
847         {
848                 gchar *context1, *context2;
849                 gboolean ret;
850
851                 context1 = g_strdup_printf(_("%s header"), prefs_common_translated_header_name("To:"));
852                 context2 = g_strdup_printf(_("%s header"), prefs_common_translated_header_name("Cc:"));
853                 ret = matcherprop_string_match(prop, info->to, context1)
854                         || matcherprop_string_match(prop, info->cc, context2);
855                 g_free(context1);
856                 g_free(context2);
857                 return ret;
858         }
859         case MATCHCRITERIA_NOT_TO_AND_NOT_CC:
860         {
861                 gchar *context1, *context2;
862                 gboolean ret;
863
864                 context1 = g_strdup_printf(_("%s header"), prefs_common_translated_header_name("To:"));
865                 context2 = g_strdup_printf(_("%s header"), prefs_common_translated_header_name("Cc:"));
866                 ret = !(matcherprop_string_match(prop, info->to, context1)
867                         || matcherprop_string_match(prop, info->cc, context2));
868                 g_free(context1);
869                 g_free(context2);
870                 return ret;
871         }
872         case MATCHCRITERIA_TAG:
873         case MATCHCRITERIA_NOT_TAG:
874         {
875                 gboolean ret;
876
877                 ret = matcherprop_tag_match(prop, info, _("Tag"));
878                 return (prop->criteria == MATCHCRITERIA_TAG)? ret : !ret;
879         }
880         case MATCHCRITERIA_TAGGED:
881         case MATCHCRITERIA_NOT_TAGGED:
882         {
883                 gboolean ret;
884
885                 ret = (info->tags != NULL);
886                 return (prop->criteria == MATCHCRITERIA_TAGGED)? ret : !ret;
887         }
888         case MATCHCRITERIA_AGE_GREATER:
889         {
890                 gboolean ret;
891                 gint age;
892
893                 t = time(NULL);
894                 age = ((t - info->date_t) / (60 * 60 * 24));
895                 ret = (age >= prop->value);
896
897                 /* debug output */
898                 if (debug_filtering_session
899                                 && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
900                         if (ret) {
901                                 log_print(LOG_DEBUG_FILTERING,
902                                                 "message age [ %d ] is greater than [ %d ]\n",
903                                                 age, prop->value);
904                         } else {
905                                 log_print(LOG_DEBUG_FILTERING,
906                                                 "message age [ %d ] is not greater than [ %d ]\n",
907                                                 age, prop->value);
908                         }
909                 }
910                 return ret;
911         }
912         case MATCHCRITERIA_AGE_LOWER:
913         {
914                 gboolean ret;
915                 gint age;
916
917                 t = time(NULL);
918                 age = ((t - info->date_t) / (60 * 60 * 24));
919                 ret = (age < prop->value);
920
921                 /* debug output */
922                 if (debug_filtering_session
923                                 && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
924                         if (ret) {
925                                 log_print(LOG_DEBUG_FILTERING,
926                                                 "message age [ %d ] is lower than [ %d ]\n",
927                                                 age, prop->value);
928                         } else {
929                                 log_print(LOG_DEBUG_FILTERING,
930                                                 "message age [ %d ] is not lower than [ %d ]\n",
931                                                 age, prop->value);
932                         }
933                 }
934                 return ret;
935         }
936         case MATCHCRITERIA_SCORE_GREATER:
937         {
938                 gboolean ret = (info->score > prop->value);
939
940                 /* debug output */
941                 if (debug_filtering_session
942                                 && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
943                         if (ret) {
944                                 log_print(LOG_DEBUG_FILTERING,
945                                                 "message score [ %d ] is greater than [ %d ]\n",
946                                                 info->score, prop->value);
947                         } else {
948                                 log_print(LOG_DEBUG_FILTERING,
949                                                 "message score [ %d ] is not greater than [ %d ]\n",
950                                                 info->score, prop->value);
951                         }
952                 }
953                 return ret;
954         }
955         case MATCHCRITERIA_SCORE_LOWER:
956         {
957                 gboolean ret = (info->score < prop->value);
958
959                 /* debug output */
960                 if (debug_filtering_session
961                                 && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
962                         if (ret) {
963                                 log_print(LOG_DEBUG_FILTERING,
964                                                 "message score [ %d ] is lower than [ %d ]\n",
965                                                 info->score, prop->value);
966                         } else {
967                                 log_print(LOG_DEBUG_FILTERING,
968                                                 "message score [ %d ] is not lower than [ %d ]\n",
969                                                 info->score, prop->value);
970                         }
971                 }
972                 return ret;
973         }
974         case MATCHCRITERIA_SCORE_EQUAL:
975         {
976                 gboolean ret = (info->score == prop->value);
977
978                 /* debug output */
979                 if (debug_filtering_session
980                                 && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
981                         if (ret) {
982                                 log_print(LOG_DEBUG_FILTERING,
983                                                 "message score [ %d ] is equal to [ %d ]\n",
984                                                 info->score, prop->value);
985                         } else {
986                                 log_print(LOG_DEBUG_FILTERING,
987                                                 "message score [ %d ] is not equal to [ %d ]\n",
988                                                 info->score, prop->value);
989                         }
990                 }
991                 return ret;
992         }
993         case MATCHCRITERIA_SIZE_GREATER:
994         {
995                 /* FIXME: info->size is a goffset */
996                 gboolean ret = (info->size > (goffset) prop->value);
997
998                 /* debug output */
999                 if (debug_filtering_session
1000                                 && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
1001                         if (ret) {
1002                                 log_print(LOG_DEBUG_FILTERING,
1003                                                 "message size is greater than [ %d ]\n",
1004                                                 prop->value);
1005                         } else {
1006                                 log_print(LOG_DEBUG_FILTERING,
1007                                                 "message size is not greater than [ %d ]\n",
1008                                                 prop->value);
1009                         }
1010                 }
1011                 return ret;
1012         }
1013         case MATCHCRITERIA_SIZE_SMALLER:
1014         {
1015                 /* FIXME: info->size is a goffset */
1016                 gboolean ret = (info->size < (goffset) prop->value);
1017
1018                 /* debug output */
1019                 if (debug_filtering_session
1020                                 && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
1021                         if (ret) {
1022                                 log_print(LOG_DEBUG_FILTERING,
1023                                                 "message size is smaller than [ %d ]\n",
1024                                                 prop->value);
1025                         } else {
1026                                 log_print(LOG_DEBUG_FILTERING,
1027                                                 "message size is not smaller than [ %d ]\n",
1028                                                 prop->value);
1029                         }
1030                 }
1031                 return ret;
1032         }
1033         case MATCHCRITERIA_SIZE_EQUAL:
1034         {
1035                 /* FIXME: info->size is a goffset */
1036                 gboolean ret = (info->size == (goffset) prop->value);
1037
1038                 /* debug output */
1039                 if (debug_filtering_session
1040                                 && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
1041                         if (ret) {
1042                                 log_print(LOG_DEBUG_FILTERING,
1043                                                 "message size is equal to [ %d ]\n",
1044                                                 prop->value);
1045                         } else {
1046                                 log_print(LOG_DEBUG_FILTERING,
1047                                                 "message size is not equal to [ %d ]\n",
1048                                                 prop->value);
1049                         }
1050                 }
1051                 return ret;
1052         }
1053         case MATCHCRITERIA_PARTIAL:
1054         {
1055                 /* FIXME: info->size is a goffset */
1056                 gboolean ret = (info->total_size != 0 && info->size != (goffset)info->total_size);
1057
1058                 /* debug output */
1059                 if (debug_filtering_session
1060                                 && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
1061                         if (ret) {
1062                                 log_print(LOG_DEBUG_FILTERING,
1063                                                 "message is partially downloaded, size is less than total size [ %d ])\n",
1064                                                 info->total_size);
1065                         } else {
1066                                 log_print(LOG_DEBUG_FILTERING,
1067                                                 "message is not partially downloaded\n");
1068                         }
1069                 }
1070                 return ret;
1071         }
1072         case MATCHCRITERIA_NOT_PARTIAL:
1073         {
1074                 /* FIXME: info->size is a goffset */
1075                 gboolean ret = (info->total_size == 0 || info->size == (goffset)info->total_size);
1076
1077                 /* debug output */
1078                 if (debug_filtering_session
1079                                 && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
1080                         if (ret) {
1081                                 log_print(LOG_DEBUG_FILTERING,
1082                                                 "message is not partially downloaded\n");
1083                         } else {
1084                                 log_print(LOG_DEBUG_FILTERING,
1085                                                 "message is partially downloaded, size is less than total size [ %d ])\n",
1086                                                 info->total_size);
1087                         }
1088                 }
1089                 return ret;
1090         }
1091         case MATCHCRITERIA_NEWSGROUPS:
1092         case MATCHCRITERIA_NOT_NEWSGROUPS:
1093         {
1094                 gchar *context;
1095                 gboolean ret;
1096
1097                 context = g_strdup_printf(_("%s header"),
1098                                                 prefs_common_translated_header_name("Newsgroups:"));
1099                 ret = matcherprop_string_match(prop, info->newsgroups, context);
1100                 g_free(context);
1101                 return (prop->criteria == MATCHCRITERIA_NEWSGROUPS)? ret : !ret;
1102         }
1103         case MATCHCRITERIA_INREPLYTO:
1104         case MATCHCRITERIA_NOT_INREPLYTO:
1105         {
1106                 gchar *context;
1107                 gboolean ret;
1108
1109                 context = g_strdup_printf(_("%s header"),
1110                                                 prefs_common_translated_header_name("In-Reply-To:"));
1111                 ret = matcherprop_string_match(prop, info->inreplyto, context);
1112                 g_free(context);
1113                 return (prop->criteria == MATCHCRITERIA_INREPLYTO)? ret : !ret;
1114         }
1115         case MATCHCRITERIA_REFERENCES:
1116         case MATCHCRITERIA_NOT_REFERENCES:
1117         {
1118                 gchar *context;
1119                 gboolean ret;
1120
1121                 context = g_strdup_printf(_("%s header"),
1122                                                 prefs_common_translated_header_name("References:"));
1123                 ret = matcherprop_list_match(prop, info->references, context);
1124                 g_free(context);
1125                 return (prop->criteria == MATCHCRITERIA_REFERENCES)? ret : !ret;
1126         }
1127         case MATCHCRITERIA_TEST:
1128                 return matcherprop_match_test(prop, info);
1129         case MATCHCRITERIA_NOT_TEST:
1130                 return !matcherprop_match_test(prop, info);
1131         default:
1132                 return FALSE;
1133         }
1134 }
1135
1136 /* ********************* MatcherList *************************** */
1137
1138 /*!
1139  *\brief        Create a new list of matchers 
1140  *
1141  *\param        matchers List of matcher structures
1142  *\param        bool_and Operator
1143  *
1144  *\return       MatcherList * New list
1145  */
1146 MatcherList *matcherlist_new(GSList *matchers, gboolean bool_and)
1147 {
1148         MatcherList *cond;
1149
1150         cond = g_new0(MatcherList, 1);
1151
1152         cond->matchers = matchers;
1153         cond->bool_and = bool_and;
1154
1155         return cond;
1156 }
1157
1158 /*!
1159  *\brief        Frees a list of matchers
1160  *
1161  *\param        cond List of matchers
1162  */
1163 void matcherlist_free(MatcherList *cond)
1164 {
1165         GSList *l;
1166
1167         cm_return_if_fail(cond);
1168         for (l = cond->matchers ; l != NULL ; l = g_slist_next(l)) {
1169                 matcherprop_free((MatcherProp *) l->data);
1170         }
1171         g_slist_free(cond->matchers);
1172         g_free(cond);
1173 }
1174
1175 /*!
1176  *\brief        Skip all headers in a message file
1177  *
1178  *\param        fp Message file
1179  */
1180 static void matcherlist_skip_headers(FILE *fp)
1181 {
1182         gchar buf[BUFFSIZE];
1183
1184         while (procheader_get_one_field(buf, sizeof(buf), fp, NULL) != -1)
1185                 ;
1186 }
1187
1188 /*!
1189  *\brief        Check if a header matches a matcher condition
1190  *
1191  *\param        matcher Matcher structure to check header for
1192  *\param        buf Header name
1193  *
1194  *\return       boolean TRUE if matching header
1195  */
1196 static gboolean matcherprop_match_one_header(MatcherProp *matcher,
1197                                              gchar *buf)
1198 {
1199         gboolean result = FALSE;
1200         Header *header = NULL;
1201
1202         switch (matcher->criteria) {
1203         case MATCHCRITERIA_HEADER:
1204         case MATCHCRITERIA_NOT_HEADER:
1205                 header = procheader_parse_header(buf);
1206                 if (!header)
1207                         return FALSE;
1208                 if (procheader_headername_equal(header->name,
1209                                                 matcher->header)) {
1210                         if (matcher->criteria == MATCHCRITERIA_HEADER)
1211                                 result = matcherprop_string_match(matcher, header->body, _("header"));
1212                         else
1213                                 result = !matcherprop_string_match(matcher, header->body, _("header"));
1214                         procheader_header_free(header);
1215                         return result;
1216                 }
1217                 else {
1218                         procheader_header_free(header);
1219                 }
1220                 break;
1221         case MATCHCRITERIA_HEADERS_PART:
1222         case MATCHCRITERIA_MESSAGE:
1223                 header = procheader_parse_header(buf);
1224                 if (!header)
1225                         return FALSE;
1226                 result = matcherprop_header_line_match(matcher, 
1227                                header->name, header->body, _("header line"));
1228                 procheader_header_free(header);
1229                 return result;
1230         case MATCHCRITERIA_NOT_HEADERS_PART:
1231         case MATCHCRITERIA_NOT_MESSAGE:
1232                 header = procheader_parse_header(buf);
1233                 if (!header)
1234                         return FALSE;
1235                 result = !matcherprop_header_line_match(matcher, 
1236                                header->name, header->body, _("header line"));
1237                 procheader_header_free(header);
1238                 return result;
1239         case MATCHCRITERIA_FOUND_IN_ADDRESSBOOK:
1240         case MATCHCRITERIA_NOT_FOUND_IN_ADDRESSBOOK:
1241                 {
1242                         GSList *address_list = NULL;
1243                         gint match = MATCH_ONE;
1244                         gboolean found = FALSE;
1245
1246                         /* how many address headers are me trying to mach? */
1247                         if (strcasecmp(matcher->header, "Any") == 0)
1248                                 match = MATCH_ANY;
1249                         else if (strcasecmp(matcher->header, "All") == 0)
1250                                         match = MATCH_ALL;
1251
1252                         if (match == MATCH_ONE) {
1253                                 /* matching one address header exactly, is that the right one? */
1254                                 header = procheader_parse_header(buf);
1255                                 if (!header ||
1256                                                 !procheader_headername_equal(header->name, matcher->header))
1257                                         return FALSE;
1258                                 address_list = address_list_append(address_list, header->body);
1259                                 if (address_list == NULL)
1260                                         return FALSE;
1261
1262                         } else {
1263                                 header = procheader_parse_header(buf);
1264                                 if (!header)
1265                                         return FALSE;
1266                                 /* address header is one of the headers we have to match when checking
1267                                    for any address header or all address headers? */
1268                                 if (procheader_headername_equal(header->name, "From") ||
1269                                          procheader_headername_equal(header->name, "To") ||
1270                                          procheader_headername_equal(header->name, "Cc") ||
1271                                          procheader_headername_equal(header->name, "Reply-To") ||
1272                                          procheader_headername_equal(header->name, "Sender"))
1273                                         address_list = address_list_append(address_list, header->body);
1274                                 if (address_list == NULL)
1275                                         return FALSE;
1276                         }
1277
1278                         found = match_with_addresses_in_addressbook
1279                                                         (matcher, address_list, matcher->criteria,
1280                                                          matcher->expr, match);
1281                         g_slist_free(address_list);
1282
1283                         if (matcher->criteria == MATCHCRITERIA_NOT_FOUND_IN_ADDRESSBOOK)
1284                                 return !found;
1285                         else
1286                                 return found;
1287         }
1288         }
1289
1290         return FALSE;
1291 }
1292
1293 /*!
1294  *\brief        Check if the matcher structure wants headers to
1295  *              be matched
1296  *
1297  *\param        matcher Matcher structure
1298  *
1299  *\return       gboolean TRUE if the matcher structure describes
1300  *              a header match condition
1301  */
1302 static gboolean matcherprop_criteria_headers(const MatcherProp *matcher)
1303 {
1304         switch (matcher->criteria) {
1305         case MATCHCRITERIA_HEADER:
1306         case MATCHCRITERIA_NOT_HEADER:
1307         case MATCHCRITERIA_HEADERS_PART:
1308         case MATCHCRITERIA_NOT_HEADERS_PART:
1309         case MATCHCRITERIA_FOUND_IN_ADDRESSBOOK:
1310         case MATCHCRITERIA_NOT_FOUND_IN_ADDRESSBOOK:
1311                 return TRUE;
1312         default:
1313                 return FALSE;
1314         }
1315 }
1316
1317 /*!
1318  *\brief        Check if the matcher structure wants the message
1319  *              to be matched (just perform an action on any
1320  *              message)
1321  *
1322  *\param        matcher Matcher structure
1323  *
1324  *\return       gboolean TRUE if matcher condition should match
1325  *              a message
1326  */
1327 static gboolean matcherprop_criteria_message(MatcherProp *matcher)
1328 {
1329         switch (matcher->criteria) {
1330         case MATCHCRITERIA_MESSAGE:
1331         case MATCHCRITERIA_NOT_MESSAGE:
1332                 return TRUE;
1333         default:
1334                 return FALSE;
1335         }
1336 }
1337
1338 /*!
1339  *\brief        Check if a list of conditions matches one header in
1340  *              a message file.
1341  *
1342  *\param        matchers List of conditions
1343  *\param        fp Message file
1344  *
1345  *\return       gboolean TRUE if one of the headers is matched by
1346  *              the list of conditions. 
1347  */
1348 static gboolean matcherlist_match_headers(MatcherList *matchers, FILE *fp)
1349 {
1350         GSList *l;
1351         gchar buf[BUFFSIZE];
1352
1353         while (procheader_get_one_field(buf, sizeof(buf), fp, NULL) != -1) {
1354                 for (l = matchers->matchers ; l != NULL ; l = g_slist_next(l)) {
1355                         MatcherProp *matcher = (MatcherProp *) l->data;
1356                         gint match = MATCH_ANY;
1357
1358                         if (matcher->done)
1359                                 continue;
1360
1361                         /* determine the match range (all, any are our concern here) */
1362                         if (matcher->criteria == MATCHCRITERIA_NOT_HEADERS_PART ||
1363                             matcher->criteria == MATCHCRITERIA_NOT_MESSAGE) {
1364                                 match = MATCH_ALL;
1365
1366                         } else if (matcher->criteria == MATCHCRITERIA_FOUND_IN_ADDRESSBOOK ||
1367                                            matcher->criteria == MATCHCRITERIA_NOT_FOUND_IN_ADDRESSBOOK) {
1368                                 Header *header = NULL;
1369
1370                                 /* address header is one of the headers we have to match when checking
1371                                    for any address header or all address headers? */
1372                                 header = procheader_parse_header(buf);
1373                                 if (header &&
1374                                         (procheader_headername_equal(header->name, "From") ||
1375                                          procheader_headername_equal(header->name, "To") ||
1376                                          procheader_headername_equal(header->name, "Cc") ||
1377                                          procheader_headername_equal(header->name, "Reply-To") ||
1378                                          procheader_headername_equal(header->name, "Sender"))) {
1379
1380                                         if (strcasecmp(matcher->header, "Any") == 0)
1381                                                 match = MATCH_ANY;
1382                                         else if (strcasecmp(matcher->header, "All") == 0)
1383                                                 match = MATCH_ALL;
1384                                         else
1385                                                 match = MATCH_ONE;
1386                                 } else {
1387                                         /* further call to matcherprop_match_one_header() can't match
1388                                            and it irrelevant, so: don't alter the match result */
1389                                         continue;
1390                                 }
1391                         }
1392
1393                         /* ZERO line must NOT match for the rule to match.
1394                          */
1395                         if (match == MATCH_ALL) {
1396                                 if (matcherprop_match_one_header(matcher, buf)) {
1397                                         matcher->result = TRUE;
1398                                 } else {
1399                                         matcher->result = FALSE;
1400                                         matcher->done = TRUE;
1401                                 }
1402                         /* else, just one line matching is enough for the rule to match
1403                          */
1404                         } else if (matcherprop_criteria_headers(matcher) ||
1405                                    matcherprop_criteria_message(matcher)) {
1406                                 if (matcherprop_match_one_header(matcher, buf)) {
1407                                         matcher->result = TRUE;
1408                                         matcher->done = TRUE;
1409                                 }
1410                         }
1411                         
1412                         /* if the rule matched and the matchers are OR, no need to
1413                          * check the others */
1414                         if (matcher->result && matcher->done) {
1415                                 if (!matchers->bool_and)
1416                                         return TRUE;
1417                         }
1418                 }
1419         }
1420
1421         return FALSE;
1422 }
1423
1424 /*!
1425  *\brief        Check if a matcher wants to check the message body
1426  *
1427  *\param        matcher Matcher structure
1428  *
1429  *\return       gboolean TRUE if body must be matched.
1430  */
1431 static gboolean matcherprop_criteria_body(const MatcherProp *matcher)
1432 {
1433         switch (matcher->criteria) {
1434         case MATCHCRITERIA_BODY_PART:
1435         case MATCHCRITERIA_NOT_BODY_PART:
1436                 return TRUE;
1437         default:
1438                 return FALSE;
1439         }
1440 }
1441
1442 /*!
1443  *\brief        Check if a line in a message file's body matches
1444  *              the criteria
1445  *
1446  *\param        matchers List of conditions
1447  *\param        fp Message file
1448  *
1449  *\return       gboolean TRUE if succesful match
1450  */
1451 static gboolean matcherlist_match_body(MatcherList *matchers, gboolean body_only, MsgInfo *info)
1452 {
1453         GSList *l;
1454         MimeInfo *mimeinfo = NULL;
1455         MimeInfo *partinfo = NULL;
1456         gchar buf[BUFFSIZE];
1457         gboolean first_text_found = FALSE;
1458         FILE *outfp = NULL;
1459
1460         cm_return_val_if_fail(info != NULL, FALSE);
1461
1462         mimeinfo = procmime_scan_message(info);
1463
1464         /* Skip headers */
1465         partinfo = procmime_mimeinfo_next(mimeinfo);
1466
1467         for (; partinfo != NULL; partinfo = procmime_mimeinfo_next(partinfo)) {
1468
1469                 if (partinfo->type != MIMETYPE_TEXT && body_only)
1470                         continue;
1471
1472                 if (partinfo->type == MIMETYPE_TEXT) {
1473                         first_text_found = TRUE;
1474                         outfp = procmime_get_text_content(partinfo);
1475                 } else
1476                         outfp = procmime_get_binary_content(partinfo);
1477
1478                 if (!outfp) {
1479                         procmime_mimeinfo_free_all(mimeinfo);
1480                         return FALSE;
1481                 }
1482
1483                 while (fgets(buf, sizeof(buf), outfp) != NULL) {
1484                         strretchomp(buf);
1485
1486                         for (l = matchers->matchers ; l != NULL ; l = g_slist_next(l)) {
1487                                 MatcherProp *matcher = (MatcherProp *) l->data;
1488
1489                                 if (matcher->done) 
1490                                         continue;
1491
1492                                 /* Don't scan non-text parts when looking in body, only
1493                                  * when looking in whole message
1494                                  */
1495                                 if (partinfo && partinfo->type != MIMETYPE_TEXT &&
1496                                 (matcher->criteria == MATCHCRITERIA_NOT_BODY_PART ||
1497                                 matcher->criteria == MATCHCRITERIA_BODY_PART))
1498                                         continue;
1499
1500                                 /* if the criteria is ~body_part or ~message, ZERO lines
1501                                  * must match for the rule to match.
1502                                  */
1503                                 if (matcher->criteria == MATCHCRITERIA_NOT_BODY_PART ||
1504                                     matcher->criteria == MATCHCRITERIA_NOT_MESSAGE) {
1505                                         if (matcherprop_string_match(matcher, buf, 
1506                                                                 _("body line"))) {
1507                                                 matcher->result = FALSE;
1508                                                 matcher->done = TRUE;
1509                                         } else
1510                                                 matcher->result = TRUE;
1511                                 /* else, just one line has to match */
1512                                 } else if (matcherprop_criteria_body(matcher) ||
1513                                            matcherprop_criteria_message(matcher)) {
1514                                         if (matcherprop_string_match(matcher, buf,
1515                                                                 _("body line"))) {
1516                                                 matcher->result = TRUE;
1517                                                 matcher->done = TRUE;
1518                                         }
1519                                 }
1520
1521                                 /* if the matchers are OR'ed and the rule matched,
1522                                  * no need to check the others. */
1523                                 if (matcher->result && matcher->done) {
1524                                         if (!matchers->bool_and) {
1525                                                 procmime_mimeinfo_free_all(mimeinfo);
1526                                                 fclose(outfp);
1527                                                 return TRUE;
1528                                         }
1529                                 }
1530                         }
1531                 }
1532                 fclose(outfp);
1533
1534                 if (body_only && first_text_found)
1535                         break;
1536         }
1537         procmime_mimeinfo_free_all(mimeinfo);
1538
1539         return FALSE;
1540 }
1541
1542 /*!
1543  *\brief        Check if a message file matches criteria
1544  *
1545  *\param        matchers Criteria
1546  *\param        info Message info
1547  *\param        result Default result
1548  *
1549  *\return       gboolean TRUE if matched
1550  */
1551 static gboolean matcherlist_match_file(MatcherList *matchers, MsgInfo *info,
1552                                 gboolean result)
1553 {
1554         gboolean read_headers;
1555         gboolean read_body;
1556         gboolean body_only;
1557         GSList *l;
1558         FILE *fp;
1559         gchar *file;
1560
1561         /* file need to be read ? */
1562
1563         read_headers = FALSE;
1564         read_body = FALSE;
1565         body_only = TRUE;
1566         for (l = matchers->matchers ; l != NULL ; l = g_slist_next(l)) {
1567                 MatcherProp *matcher = (MatcherProp *) l->data;
1568
1569                 if (matcherprop_criteria_headers(matcher))
1570                         read_headers = TRUE;
1571                 if (matcherprop_criteria_body(matcher))
1572                         read_body = TRUE;
1573                 if (matcherprop_criteria_message(matcher)) {
1574                         read_headers = TRUE;
1575                         read_body = TRUE;
1576                         body_only = FALSE;
1577                 }
1578                 matcher->result = FALSE;
1579                 matcher->done = FALSE;
1580         }
1581
1582         if (!read_headers && !read_body)
1583                 return result;
1584
1585         file = procmsg_get_message_file_full(info, read_headers, read_body);
1586         if (file == NULL)
1587                 return FALSE;
1588
1589         if ((fp = g_fopen(file, "rb")) == NULL) {
1590                 FILE_OP_ERROR(file, "fopen");
1591                 g_free(file);
1592                 return result;
1593         }
1594
1595         /* read the headers */
1596
1597         if (read_headers) {
1598                 if (matcherlist_match_headers(matchers, fp))
1599                         read_body = FALSE;
1600         } else {
1601                 matcherlist_skip_headers(fp);
1602         }
1603
1604         /* read the body */
1605         if (read_body) {
1606                 matcherlist_match_body(matchers, body_only, info);
1607         }
1608         
1609         for (l = matchers->matchers; l != NULL; l = g_slist_next(l)) {
1610                 MatcherProp *matcher = (MatcherProp *) l->data;
1611
1612                 if (matcherprop_criteria_headers(matcher) ||
1613                     matcherprop_criteria_body(matcher)    ||
1614                     matcherprop_criteria_message(matcher)) {
1615                         if (matcher->result) {
1616                                 if (!matchers->bool_and) {
1617                                         result = TRUE;
1618                                         break;
1619                                 }
1620                         }
1621                         else {
1622                                 if (matchers->bool_and) {
1623                                         result = FALSE;
1624                                         break;
1625                                 }
1626                         }
1627                 }                       
1628         }
1629
1630         g_free(file);
1631
1632         fclose(fp);
1633         
1634         return result;
1635 }
1636
1637 /*!
1638  *\brief        Test list of conditions on a message.
1639  *
1640  *\param        matchers List of conditions
1641  *\param        info Message info
1642  *
1643  *\return       gboolean TRUE if matched
1644  */
1645 gboolean matcherlist_match(MatcherList *matchers, MsgInfo *info)
1646 {
1647         GSList *l;
1648         gboolean result;
1649
1650         if (!matchers)
1651                 return FALSE;
1652
1653         if (matchers->bool_and)
1654                 result = TRUE;
1655         else
1656                 result = FALSE;
1657
1658         /* test the cached elements */
1659
1660         for (l = matchers->matchers; l != NULL ;l = g_slist_next(l)) {
1661                 MatcherProp *matcher = (MatcherProp *) l->data;
1662
1663                 if (debug_filtering_session) {
1664                         gchar *buf = matcherprop_to_string(matcher);
1665                         log_print(LOG_DEBUG_FILTERING, _("checking if message matches [ %s ]\n"), buf);
1666                         g_free(buf);
1667                 }
1668
1669                 switch(matcher->criteria) {
1670                 case MATCHCRITERIA_ALL:
1671                 case MATCHCRITERIA_UNREAD:
1672                 case MATCHCRITERIA_NOT_UNREAD:
1673                 case MATCHCRITERIA_NEW:
1674                 case MATCHCRITERIA_NOT_NEW:
1675                 case MATCHCRITERIA_MARKED:
1676                 case MATCHCRITERIA_NOT_MARKED:
1677                 case MATCHCRITERIA_DELETED:
1678                 case MATCHCRITERIA_NOT_DELETED:
1679                 case MATCHCRITERIA_REPLIED:
1680                 case MATCHCRITERIA_NOT_REPLIED:
1681                 case MATCHCRITERIA_FORWARDED:
1682                 case MATCHCRITERIA_NOT_FORWARDED:
1683                 case MATCHCRITERIA_LOCKED:
1684                 case MATCHCRITERIA_NOT_LOCKED:
1685                 case MATCHCRITERIA_SPAM:
1686                 case MATCHCRITERIA_NOT_SPAM:
1687                 case MATCHCRITERIA_HAS_ATTACHMENT:
1688                 case MATCHCRITERIA_HAS_NO_ATTACHMENT:
1689                 case MATCHCRITERIA_SIGNED:
1690                 case MATCHCRITERIA_NOT_SIGNED:
1691                 case MATCHCRITERIA_COLORLABEL:
1692                 case MATCHCRITERIA_NOT_COLORLABEL:
1693                 case MATCHCRITERIA_IGNORE_THREAD:
1694                 case MATCHCRITERIA_NOT_IGNORE_THREAD:
1695                 case MATCHCRITERIA_WATCH_THREAD:
1696                 case MATCHCRITERIA_NOT_WATCH_THREAD:
1697                 case MATCHCRITERIA_SUBJECT:
1698                 case MATCHCRITERIA_NOT_SUBJECT:
1699                 case MATCHCRITERIA_FROM:
1700                 case MATCHCRITERIA_NOT_FROM:
1701                 case MATCHCRITERIA_TO:
1702                 case MATCHCRITERIA_NOT_TO:
1703                 case MATCHCRITERIA_CC:
1704                 case MATCHCRITERIA_NOT_CC:
1705                 case MATCHCRITERIA_TO_OR_CC:
1706                 case MATCHCRITERIA_NOT_TO_AND_NOT_CC:
1707                 case MATCHCRITERIA_TAG:
1708                 case MATCHCRITERIA_NOT_TAG:
1709                 case MATCHCRITERIA_TAGGED:
1710                 case MATCHCRITERIA_NOT_TAGGED:
1711                 case MATCHCRITERIA_AGE_GREATER:
1712                 case MATCHCRITERIA_AGE_LOWER:
1713                 case MATCHCRITERIA_NEWSGROUPS:
1714                 case MATCHCRITERIA_NOT_NEWSGROUPS:
1715                 case MATCHCRITERIA_INREPLYTO:
1716                 case MATCHCRITERIA_NOT_INREPLYTO:
1717                 case MATCHCRITERIA_REFERENCES:
1718                 case MATCHCRITERIA_NOT_REFERENCES:
1719                 case MATCHCRITERIA_SCORE_GREATER:
1720                 case MATCHCRITERIA_SCORE_LOWER:
1721                 case MATCHCRITERIA_SCORE_EQUAL:
1722                 case MATCHCRITERIA_SIZE_GREATER:
1723                 case MATCHCRITERIA_SIZE_SMALLER:
1724                 case MATCHCRITERIA_SIZE_EQUAL:
1725                 case MATCHCRITERIA_TEST:
1726                 case MATCHCRITERIA_NOT_TEST:
1727                 case MATCHCRITERIA_PARTIAL:
1728                 case MATCHCRITERIA_NOT_PARTIAL:
1729                         if (matcherprop_match(matcher, info)) {
1730                                 if (!matchers->bool_and) {
1731                                         if (debug_filtering_session)
1732                                                 log_status_ok(LOG_DEBUG_FILTERING, _("message matches\n"));
1733                                         return TRUE;
1734                                 }
1735                         }
1736                         else {
1737                                 if (matchers->bool_and) {
1738                                         if (debug_filtering_session)
1739                                                 log_status_nok(LOG_DEBUG_FILTERING, _("message does not match\n"));
1740                                         return FALSE;
1741                                 }
1742                         }
1743                 }
1744         }
1745
1746         /* test the condition on the file */
1747
1748         if (matcherlist_match_file(matchers, info, result)) {
1749                 if (!matchers->bool_and) {
1750                         if (debug_filtering_session)
1751                                 log_status_ok(LOG_DEBUG_FILTERING, _("message matches\n"));
1752                         return TRUE;
1753                 }
1754         } else {
1755                 if (matchers->bool_and) {
1756                         if (debug_filtering_session)
1757                                 log_status_nok(LOG_DEBUG_FILTERING, _("message does not match\n"));
1758                         return FALSE;
1759                 }
1760         }
1761
1762         if (debug_filtering_session) {
1763                 if (result)
1764                         log_status_ok(LOG_DEBUG_FILTERING, _("message matches\n"));
1765                 else
1766                         log_status_nok(LOG_DEBUG_FILTERING, _("message does not match\n"));
1767         }
1768         return result;
1769 }
1770
1771
1772 static gint quote_filter_str(gchar * result, guint size,
1773                              const gchar * path)
1774 {
1775         const gchar * p;
1776         gchar * result_p;
1777         guint remaining;
1778
1779         result_p = result;
1780         remaining = size;
1781
1782         for(p = path ; * p != '\0' ; p ++) {
1783
1784                 if ((* p != '\"') && (* p != '\\')) {
1785                         if (remaining > 0) {
1786                                 * result_p = * p;
1787                                 result_p ++; 
1788                                 remaining --;
1789                         }
1790                         else {
1791                                 result[size - 1] = '\0';
1792                                 return -1;
1793                         }
1794                 }
1795                 else { 
1796                         if (remaining >= 2) {
1797                                 * result_p = '\\';
1798                                 result_p ++; 
1799                                 * result_p = * p;
1800                                 result_p ++; 
1801                                 remaining -= 2;
1802                         }
1803                         else {
1804                                 result[size - 1] = '\0';
1805                                 return -1;
1806                         }
1807                 }
1808         }
1809         if (remaining > 0) {
1810                 * result_p = '\0';
1811         }
1812         else {
1813                 result[size - 1] = '\0';
1814                 return -1;
1815         }
1816   
1817         return 0;
1818 }
1819
1820
1821 gchar * matcher_quote_str(const gchar * src)
1822 {
1823         gchar * res;
1824         gint len;
1825         
1826         len = strlen(src) * 2 + 1;
1827         res = g_malloc(len);
1828         quote_filter_str(res, len, src);
1829         
1830         return res;
1831 }
1832
1833 /*!
1834  *\brief        Convert a matcher structure to a string
1835  *
1836  *\param        matcher Matcher structure
1837  *
1838  *\return       gchar * Newly allocated string
1839  */
1840 gchar *matcherprop_to_string(MatcherProp *matcher)
1841 {
1842         gchar *matcher_str = NULL;
1843         const gchar *criteria_str;
1844         const gchar *matchtype_str;
1845         int i;
1846         gchar * quoted_expr;
1847         gchar * quoted_header;
1848         
1849         criteria_str = NULL;
1850         for (i = 0; i < (int) (sizeof(matchparser_tab) / sizeof(MatchParser)); i++) {
1851                 if (matchparser_tab[i].id == matcher->criteria)
1852                         criteria_str = matchparser_tab[i].str;
1853         }
1854         if (criteria_str == NULL)
1855                 return NULL;
1856
1857         switch (matcher->criteria) {
1858         case MATCHCRITERIA_AGE_GREATER:
1859         case MATCHCRITERIA_AGE_LOWER:
1860         case MATCHCRITERIA_SCORE_GREATER:
1861         case MATCHCRITERIA_SCORE_LOWER:
1862         case MATCHCRITERIA_SCORE_EQUAL:
1863         case MATCHCRITERIA_SIZE_GREATER:
1864         case MATCHCRITERIA_SIZE_SMALLER:
1865         case MATCHCRITERIA_SIZE_EQUAL:
1866         case MATCHCRITERIA_COLORLABEL:
1867         case MATCHCRITERIA_NOT_COLORLABEL:
1868                 return g_strdup_printf("%s %i", criteria_str, matcher->value);
1869         case MATCHCRITERIA_ALL:
1870         case MATCHCRITERIA_UNREAD:
1871         case MATCHCRITERIA_NOT_UNREAD:
1872         case MATCHCRITERIA_NEW:
1873         case MATCHCRITERIA_NOT_NEW:
1874         case MATCHCRITERIA_MARKED:
1875         case MATCHCRITERIA_NOT_MARKED:
1876         case MATCHCRITERIA_DELETED:
1877         case MATCHCRITERIA_NOT_DELETED:
1878         case MATCHCRITERIA_REPLIED:
1879         case MATCHCRITERIA_NOT_REPLIED:
1880         case MATCHCRITERIA_FORWARDED:
1881         case MATCHCRITERIA_NOT_FORWARDED:
1882         case MATCHCRITERIA_LOCKED:
1883         case MATCHCRITERIA_NOT_LOCKED:
1884         case MATCHCRITERIA_SPAM:
1885         case MATCHCRITERIA_NOT_SPAM:
1886         case MATCHCRITERIA_HAS_ATTACHMENT:
1887         case MATCHCRITERIA_HAS_NO_ATTACHMENT:
1888         case MATCHCRITERIA_SIGNED:
1889         case MATCHCRITERIA_NOT_SIGNED:
1890         case MATCHCRITERIA_PARTIAL:
1891         case MATCHCRITERIA_NOT_PARTIAL:
1892         case MATCHCRITERIA_IGNORE_THREAD:
1893         case MATCHCRITERIA_NOT_IGNORE_THREAD:
1894         case MATCHCRITERIA_WATCH_THREAD:
1895         case MATCHCRITERIA_NOT_WATCH_THREAD:
1896         case MATCHCRITERIA_TAGGED:
1897         case MATCHCRITERIA_NOT_TAGGED:
1898                 return g_strdup(criteria_str);
1899         case MATCHCRITERIA_TEST:
1900         case MATCHCRITERIA_NOT_TEST:
1901                 quoted_expr = matcher_quote_str(matcher->expr);
1902                 matcher_str = g_strdup_printf("%s \"%s\"",
1903                                               criteria_str, quoted_expr);
1904                 g_free(quoted_expr);
1905                 return matcher_str;
1906         case MATCHCRITERIA_FOUND_IN_ADDRESSBOOK:
1907         case MATCHCRITERIA_NOT_FOUND_IN_ADDRESSBOOK:
1908                 quoted_header = matcher_quote_str(matcher->header);
1909                 quoted_expr = matcher_quote_str(matcher->expr);
1910                 matcher_str = g_strdup_printf("%s \"%s\" in \"%s\"",
1911                                               criteria_str, quoted_header, quoted_expr);
1912                 g_free(quoted_header);
1913                 g_free(quoted_expr);
1914                 return matcher_str;
1915         }
1916
1917         matchtype_str = NULL;
1918         for (i = 0; i < sizeof matchparser_tab / sizeof matchparser_tab[0]; i++) {
1919                 if (matchparser_tab[i].id == matcher->matchtype)
1920                         matchtype_str = matchparser_tab[i].str;
1921         }
1922
1923         if (matchtype_str == NULL)
1924                 return NULL;
1925
1926         switch (matcher->matchtype) {
1927         case MATCHTYPE_MATCH:
1928         case MATCHTYPE_MATCHCASE:
1929         case MATCHTYPE_REGEXP:
1930         case MATCHTYPE_REGEXPCASE:
1931                 quoted_expr = matcher_quote_str(matcher->expr);
1932                 if (matcher->header) {
1933                         quoted_header = matcher_quote_str(matcher->header);
1934                         matcher_str = g_strdup_printf
1935                                         ("%s \"%s\" %s \"%s\"",
1936                                          criteria_str, quoted_header,
1937                                          matchtype_str, quoted_expr);
1938                         g_free(quoted_header);
1939                 }
1940                 else
1941                         matcher_str = g_strdup_printf
1942                                         ("%s %s \"%s\"", criteria_str,
1943                                          matchtype_str, quoted_expr);
1944                 g_free(quoted_expr);
1945                 break;
1946         }
1947
1948         return matcher_str;
1949 }
1950
1951 /*!
1952  *\brief        Convert a list of conditions to a string
1953  *
1954  *\param        matchers List of conditions
1955  *
1956  *\return       gchar * Newly allocated string
1957  */
1958 gchar *matcherlist_to_string(const MatcherList *matchers)
1959 {
1960         gint count;
1961         gchar **vstr;
1962         GSList *l;
1963         gchar **cur_str;
1964         gchar *result = NULL;
1965
1966         count = g_slist_length(matchers->matchers);
1967         vstr = g_new(gchar *, count + 1);
1968
1969         for (l = matchers->matchers, cur_str = vstr; l != NULL;
1970              l = g_slist_next(l), cur_str ++) {
1971                 *cur_str = matcherprop_to_string((MatcherProp *) l->data);
1972                 if (*cur_str == NULL)
1973                         break;
1974         }
1975         *cur_str = NULL;
1976         
1977         if (matchers->bool_and)
1978                 result = g_strjoinv(" & ", vstr);
1979         else
1980                 result = g_strjoinv(" | ", vstr);
1981
1982         for (cur_str = vstr ; *cur_str != NULL ; cur_str ++)
1983                 g_free(*cur_str);
1984         g_free(vstr);
1985
1986         return result;
1987 }
1988
1989
1990 #define STRLEN_ZERO(s) ((s) ? strlen(s) : 0)
1991 #define STRLEN_DEFAULT(s,d) ((s) ? strlen(s) : STRLEN_ZERO(d))
1992
1993 static void add_str_default(gchar ** dest,
1994                             const gchar * s, const gchar * d)
1995 {
1996         gchar quoted_str[4096];
1997         const gchar * str;
1998         
1999         if (s != NULL)
2000                 str = s;
2001         else
2002                 str = d;
2003         
2004         quote_cmd_argument(quoted_str, sizeof(quoted_str), str);
2005         strcpy(* dest, quoted_str);
2006         
2007         (* dest) += strlen(* dest);
2008 }
2009
2010 /* matching_build_command() - preferably cmd should be unescaped */
2011 /*!
2012  *\brief        Build the command-line to execute
2013  *
2014  *\param        cmd String with command-line specifiers
2015  *\param        info Message info to use for command
2016  *
2017  *\return       gchar * Newly allocated string
2018  */
2019 gchar *matching_build_command(const gchar *cmd, MsgInfo *info)
2020 {
2021         const gchar *s = cmd;
2022         gchar *filename = NULL;
2023         gchar *processed_cmd;
2024         gchar *p;
2025         gint size;
2026
2027         const gchar *const no_subject    = _("(none)") ;
2028         const gchar *const no_from       = _("(none)") ;
2029         const gchar *const no_to         = _("(none)") ;
2030         const gchar *const no_cc         = _("(none)") ;
2031         const gchar *const no_date       = _("(none)") ;
2032         const gchar *const no_msgid      = _("(none)") ;
2033         const gchar *const no_newsgroups = _("(none)") ;
2034         const gchar *const no_references = _("(none)") ;
2035
2036         size = STRLEN_ZERO(cmd) + 1;
2037         while (*s != '\0') {
2038                 if (*s == '%') {
2039                         s++;
2040                         switch (*s) {
2041                         case '%':
2042                                 size -= 1;
2043                                 break;
2044                         case 's': /* subject */
2045                                 size += STRLEN_DEFAULT(info->subject, no_subject) - 2;
2046                                 break;
2047                         case 'f': /* from */
2048                                 size += STRLEN_DEFAULT(info->from, no_from) - 2;
2049                                 break;
2050                         case 't': /* to */
2051                                 size += STRLEN_DEFAULT(info->to, no_to) - 2;
2052                                 break;
2053                         case 'c': /* cc */
2054                                 size += STRLEN_DEFAULT(info->cc, no_cc) - 2;
2055                                 break;
2056                         case 'd': /* date */
2057                                 size += STRLEN_DEFAULT(info->date, no_date) - 2;
2058                                 break;
2059                         case 'i': /* message-id */
2060                                 size += STRLEN_DEFAULT(info->msgid, no_msgid) - 2;
2061                                 break;
2062                         case 'n': /* newsgroups */
2063                                 size += STRLEN_DEFAULT(info->newsgroups, no_newsgroups) - 2;
2064                                 break;
2065                         case 'r': /* references */
2066                                 /* FIXME: using the inreplyto header for reference */
2067                                 size += STRLEN_DEFAULT(info->inreplyto, no_references) - 2;
2068                                 break;
2069                         case 'F': /* file */
2070                                 if (filename == NULL)
2071                                         filename = folder_item_fetch_msg(info->folder, info->msgnum);
2072                                 
2073                                 if (filename == NULL) {
2074                                         g_warning("filename is not set");
2075                                         return NULL;
2076                                 }
2077                                 else {
2078                                         size += strlen(filename) - 2;
2079                                 }
2080                                 break;
2081                         }
2082                         s++;
2083                 }
2084                 else s++;
2085         }
2086         
2087         /* as the string can be quoted, we double the result */
2088         size *= 2;
2089
2090         processed_cmd = g_new0(gchar, size);
2091         s = cmd;
2092         p = processed_cmd;
2093
2094         while (*s != '\0') {
2095                 if (*s == '%') {
2096                         s++;
2097                         switch (*s) {
2098                         case '%':
2099                                 *p = '%';
2100                                 p++;
2101                                 break;
2102                         case 's': /* subject */
2103                                 add_str_default(&p, info->subject,
2104                                                 no_subject);
2105                                 break;
2106                         case 'f': /* from */
2107                                 add_str_default(&p, info->from,
2108                                                 no_from);
2109                                 break;
2110                         case 't': /* to */
2111                                 add_str_default(&p, info->to,
2112                                                 no_to);
2113                                 break;
2114                         case 'c': /* cc */
2115                                 add_str_default(&p, info->cc,
2116                                                 no_cc);
2117                                 break;
2118                         case 'd': /* date */
2119                                 add_str_default(&p, info->date,
2120                                                 no_date);
2121                                 break;
2122                         case 'i': /* message-id */
2123                                 add_str_default(&p, info->msgid,
2124                                                 no_msgid);
2125                                 break;
2126                         case 'n': /* newsgroups */
2127                                 add_str_default(&p, info->newsgroups,
2128                                                 no_newsgroups);
2129                                 break;
2130                         case 'r': /* references */
2131                                 /* FIXME: using the inreplyto header for references */
2132                                 add_str_default(&p, info->inreplyto, no_references);
2133                                 break;
2134                         case 'F': /* file */
2135                                 if (filename != NULL)
2136                                         add_str_default(&p, filename, NULL);
2137                                 break;
2138                         default:
2139                                 *p = '%';
2140                                 p++;
2141                                 *p = *s;
2142                                 p++;
2143                                 break;
2144                         }
2145                         s++;
2146                 }
2147                 else {
2148                         *p = *s;
2149                         p++;
2150                         s++;
2151                 }
2152         }
2153         g_free(filename);
2154         
2155         return processed_cmd;
2156 }
2157 #undef STRLEN_DEFAULT
2158 #undef STRLEN_ZERO
2159
2160 /* ************************************************************ */
2161
2162
2163 /*!
2164  *\brief        Write filtering list to file
2165  *
2166  *\param        fp File
2167  *\param        prefs_filtering List of filtering conditions
2168  */
2169 static int prefs_filtering_write(FILE *fp, GSList *prefs_filtering)
2170 {
2171         GSList *cur = NULL;
2172
2173         for (cur = prefs_filtering; cur != NULL; cur = cur->next) {
2174                 gchar *filtering_str = NULL;
2175                 gchar *tmp_name = NULL;
2176                 FilteringProp *prop = NULL;
2177
2178                 if (NULL == (prop = (FilteringProp *) cur->data))
2179                         continue;
2180                 
2181                 if (NULL == (filtering_str = filteringprop_to_string(prop)))
2182                         continue;
2183
2184                 if (prop->enabled) {
2185                         if (fputs("enabled ", fp) == EOF) {
2186                                 FILE_OP_ERROR("filtering config", "fputs");
2187                                 return -1;
2188                         }
2189                 } else {
2190                         if (fputs("disabled ", fp) == EOF) {
2191                                 FILE_OP_ERROR("filtering config", "fputs");
2192                                 return -1;
2193                         }
2194                 }
2195
2196                 if (fputs("rulename \"", fp) == EOF) {
2197                         FILE_OP_ERROR("filtering config", "fputs");
2198                         g_free(filtering_str);
2199                         return -1;
2200                 }
2201                 tmp_name = prop->name;
2202                 while (tmp_name && *tmp_name != '\0') {
2203                         if (*tmp_name != '"') {
2204                                 if (fputc(*tmp_name, fp) == EOF) {
2205                                         FILE_OP_ERROR("filtering config", "fputs || fputc");
2206                                         g_free(filtering_str);
2207                                         return -1;
2208                                 }
2209                         } else if (*tmp_name == '"') {
2210                                 if (fputc('\\', fp) == EOF ||
2211                                     fputc('"', fp) == EOF) {
2212                                         FILE_OP_ERROR("filtering config", "fputs || fputc");
2213                                         g_free(filtering_str);
2214                                         return -1;
2215                                 }
2216                         }
2217                         tmp_name ++;
2218                 }
2219                 if (fputs("\" ", fp) == EOF) {
2220                         FILE_OP_ERROR("filtering config", "fputs");
2221                         g_free(filtering_str);
2222                         return -1;
2223                 }
2224
2225                 if (prop->account_id != 0) {
2226                         gchar *tmp = NULL;
2227
2228                         tmp = g_strdup_printf("account %d ", prop->account_id);
2229                         if (fputs(tmp, fp) == EOF) {
2230                                 FILE_OP_ERROR("filtering config", "fputs");
2231                                 g_free(tmp);
2232                                 return -1;
2233                         }
2234                         g_free(tmp);
2235                 }
2236
2237                 if(fputs(filtering_str, fp) == EOF ||
2238                     fputc('\n', fp) == EOF) {
2239                         FILE_OP_ERROR("filtering config", "fputs || fputc");
2240                         g_free(filtering_str);
2241                         return -1;
2242                 }
2243                 g_free(filtering_str);
2244         }
2245         
2246         return 0;
2247 }
2248
2249 typedef struct _NodeLoopData {
2250         FILE *fp;
2251         gboolean error;
2252 } NodeLoopData;
2253
2254 /*!
2255  *\brief        Write matchers from a folder item
2256  *
2257  *\param        node Node with folder info
2258  *\param        data File pointer
2259  *
2260  *\return       gboolean FALSE
2261  */
2262 static gboolean prefs_matcher_write_func(GNode *node, gpointer d)
2263 {
2264         FolderItem *item;
2265         NodeLoopData *data = (NodeLoopData *)d;
2266         gchar *id;
2267         GSList *prefs_filtering;
2268
2269         item = node->data;
2270         /* prevent warning */
2271         if (item->path == NULL)
2272                 return FALSE;
2273         id = folder_item_get_identifier(item);
2274         if (id == NULL)
2275                 return FALSE;
2276         prefs_filtering = item->prefs->processing;
2277
2278         if (prefs_filtering != NULL) {
2279                 if (fprintf(data->fp, "[%s]\n", id) < 0) {
2280                         data->error = TRUE;
2281                         goto fail;
2282                 }
2283                 if (prefs_filtering_write(data->fp, prefs_filtering) < 0) {
2284                         data->error = TRUE;
2285                         goto fail;
2286                 }
2287                 if (fputc('\n', data->fp) == EOF) {
2288                         data->error = TRUE;
2289                         goto fail;
2290                 }
2291         }
2292 fail:
2293         g_free(id);
2294
2295         return FALSE;
2296 }
2297
2298 /*!
2299  *\brief        Save matchers from folder items
2300  *
2301  *\param        fp File
2302  */
2303 static int prefs_matcher_save(FILE *fp)
2304 {
2305         GList *cur;
2306         NodeLoopData data;
2307         
2308         data.fp = fp;
2309         data.error = FALSE;
2310
2311         for (cur = folder_get_list() ; cur != NULL ; cur = g_list_next(cur)) {
2312                 Folder *folder;
2313
2314                 folder = (Folder *) cur->data;
2315                 g_node_traverse(folder->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1,
2316                                 prefs_matcher_write_func, &data);
2317         }
2318         
2319         if (data.error == TRUE)
2320                 return -1;
2321
2322         /* pre global rules */
2323         if (fprintf(fp, "[preglobal]\n") < 0 ||
2324             prefs_filtering_write(fp, pre_global_processing) < 0 ||
2325             fputc('\n', fp) == EOF)
2326                 return -1;
2327
2328         /* post global rules */
2329         if (fprintf(fp, "[postglobal]\n") < 0 ||
2330             prefs_filtering_write(fp, post_global_processing) < 0 ||
2331             fputc('\n', fp) == EOF)
2332                 return -1;
2333         
2334         /* filtering rules */
2335         if (fprintf(fp, "[filtering]\n") < 0 ||
2336             prefs_filtering_write(fp, filtering_rules) < 0 ||
2337             fputc('\n', fp) == EOF)
2338                 return -1;
2339
2340         return 0;
2341 }
2342
2343 /*!
2344  *\brief        Write filtering / matcher configuration file
2345  */
2346 void prefs_matcher_write_config(void)
2347 {
2348         gchar *rcpath;
2349         PrefFile *pfile;
2350
2351         debug_print("Writing matcher configuration...\n");
2352
2353         rcpath = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
2354                              MATCHER_RC, NULL);
2355
2356         if ((pfile = prefs_write_open(rcpath)) == NULL) {
2357                 g_warning("failed to write configuration to file\n");
2358                 g_free(rcpath);
2359                 return;
2360         }
2361
2362         g_free(rcpath);
2363
2364         if (prefs_matcher_save(pfile->fp) < 0) {
2365                 g_warning("failed to write configuration to file\n");
2366                 prefs_file_close_revert(pfile);
2367         } else if (prefs_file_close(pfile) < 0) {
2368                 g_warning("failed to save configuration to file\n");
2369         }
2370 }
2371
2372 /* ******************************************************************* */
2373
2374 static void matcher_add_rulenames(const gchar *rcpath)
2375 {
2376         gchar *newpath = g_strconcat(rcpath, ".new", NULL);
2377         FILE *src = g_fopen(rcpath, "rb");
2378         FILE *dst = g_fopen(newpath, "wb");
2379         gchar buf[BUFFSIZE];
2380         int r;
2381         if (src == NULL) {
2382                 perror("fopen");
2383                 if (dst)
2384                         fclose(dst);
2385                 g_free(newpath);
2386                 return;
2387         }
2388         if (dst == NULL) {
2389                 perror("fopen");
2390                 if (src)
2391                         fclose(src);
2392                 g_free(newpath);
2393                 return;
2394         }
2395
2396         while (fgets (buf, sizeof(buf), src) != NULL) {
2397                 if (strlen(buf) > 2 && buf[0] != '['
2398                 && strncmp(buf, "rulename \"", 10)
2399                 && strncmp(buf, "enabled rulename \"", 18)
2400                 && strncmp(buf, "disabled rulename \"", 18)) {
2401                         r = fwrite("enabled rulename \"\" ",
2402                                 strlen("enabled rulename \"\" "), 1, dst);
2403                         if (r != 1) {
2404                                 g_message("cannot fwrite rulename\n");
2405                         }
2406                 }
2407                 r = fwrite(buf, strlen(buf), 1, dst);
2408                 if (r != 1) {
2409                         g_message("cannot fwrite rule\n");
2410                 }
2411         }
2412         fclose(dst);
2413         fclose(src);
2414         move_file(newpath, rcpath, TRUE);
2415         g_free(newpath);
2416 }
2417
2418 /*!
2419  *\brief        Read matcher configuration
2420  */
2421 void prefs_matcher_read_config(void)
2422 {
2423         gchar *rcpath;
2424         gchar *rc_old_format;
2425         FILE *f;
2426
2427         create_matchparser_hashtab();
2428         prefs_filtering_clear();
2429
2430         rcpath = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, MATCHER_RC, NULL);
2431         rc_old_format = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, MATCHER_RC, 
2432                                 ".pre_names", NULL);
2433         
2434         if (!is_file_exist(rc_old_format) && is_file_exist(rcpath)) {
2435                 /* backup file with no rules names, in case 
2436                  * anything goes wrong */
2437                 copy_file(rcpath, rc_old_format, FALSE);
2438                 /* now hack the file in order to have it to the new format */
2439                 matcher_add_rulenames(rcpath);
2440         }
2441         
2442         g_free(rc_old_format);
2443
2444         f = g_fopen(rcpath, "rb");
2445         g_free(rcpath);
2446
2447         if (f != NULL) {
2448                 matcher_parser_start_parsing(f);
2449                 fclose(matcher_parserin);
2450         }
2451         else {
2452                 /* previous version compatibility */
2453
2454                 /* g_print("reading filtering\n"); */
2455                 rcpath = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
2456                                      FILTERING_RC, NULL);
2457                 f = g_fopen(rcpath, "rb");
2458                 g_free(rcpath);
2459                 
2460                 if (f != NULL) {
2461                         matcher_parser_start_parsing(f);
2462                         fclose(matcher_parserin);
2463                 }
2464                 
2465                 /* g_print("reading scoring\n"); */
2466                 rcpath = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
2467                                      SCORING_RC, NULL);
2468                 f = g_fopen(rcpath, "rb");
2469                 g_free(rcpath);
2470                 
2471                 if (f != NULL) {
2472                         matcher_parser_start_parsing(f);
2473                         fclose(matcher_parserin);
2474                 }
2475         }
2476 }