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