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