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