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