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