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