fix bug 2989, 'Segfault at startup because of corrupted folderlist.xml'
[claws.git] / src / matcher.c
blob8c1fd115744afed7674635302738aef3d94286e9
1 /*
2 * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3 * Copyright (C) 2002-2012 by the Claws Mail Team and Hiroyuki Yamamoto
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.
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.
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/>.
20 #ifdef HAVE_CONFIG_H
21 # include "config.h"
22 #include "claws-features.h"
23 #endif
25 #include <glib.h>
26 #include <glib/gi18n.h>
27 #include <ctype.h>
28 #include <string.h>
29 #include <stdlib.h>
30 #include <errno.h>
32 #ifdef USE_PTHREAD
33 #include <pthread.h>
34 #endif
36 #include "defs.h"
37 #include "utils.h"
38 #include "procheader.h"
39 #include "matcher.h"
40 #include "matcher_parser.h"
41 #include "prefs_gtk.h"
42 #include "addr_compl.h"
43 #include "codeconv.h"
44 #include "quoted-printable.h"
45 #include "claws.h"
46 #include <ctype.h>
47 #include "prefs_common.h"
48 #include "log.h"
49 #include "tags.h"
50 #include "folder_item_prefs.h"
51 #include "procmsg.h"
53 /*!
54 *\brief Keyword lookup element
56 struct _MatchParser {
57 gint id; /*!< keyword id */
58 gchar *str; /*!< keyword */
60 typedef struct _MatchParser MatchParser;
62 /*!
63 *\brief Table with strings and ids used by the lexer and
64 * the parser. New keywords can be added here.
66 static const MatchParser matchparser_tab[] = {
67 /* msginfo flags */
68 {MATCHCRITERIA_ALL, "all"},
69 {MATCHCRITERIA_UNREAD, "unread"},
70 {MATCHCRITERIA_NOT_UNREAD, "~unread"},
71 {MATCHCRITERIA_NEW, "new"},
72 {MATCHCRITERIA_NOT_NEW, "~new"},
73 {MATCHCRITERIA_MARKED, "marked"},
74 {MATCHCRITERIA_NOT_MARKED, "~marked"},
75 {MATCHCRITERIA_DELETED, "deleted"},
76 {MATCHCRITERIA_NOT_DELETED, "~deleted"},
77 {MATCHCRITERIA_REPLIED, "replied"},
78 {MATCHCRITERIA_NOT_REPLIED, "~replied"},
79 {MATCHCRITERIA_FORWARDED, "forwarded"},
80 {MATCHCRITERIA_NOT_FORWARDED, "~forwarded"},
81 {MATCHCRITERIA_LOCKED, "locked"},
82 {MATCHCRITERIA_NOT_LOCKED, "~locked"},
83 {MATCHCRITERIA_COLORLABEL, "colorlabel"},
84 {MATCHCRITERIA_NOT_COLORLABEL, "~colorlabel"},
85 {MATCHCRITERIA_IGNORE_THREAD, "ignore_thread"},
86 {MATCHCRITERIA_NOT_IGNORE_THREAD, "~ignore_thread"},
87 {MATCHCRITERIA_WATCH_THREAD, "watch_thread"},
88 {MATCHCRITERIA_NOT_WATCH_THREAD, "~watch_thread"},
89 {MATCHCRITERIA_SPAM, "spam"},
90 {MATCHCRITERIA_NOT_SPAM, "~spam"},
91 {MATCHCRITERIA_HAS_ATTACHMENT, "has_attachment"},
92 {MATCHCRITERIA_HAS_NO_ATTACHMENT, "~has_attachment"},
93 {MATCHCRITERIA_SIGNED, "signed"},
94 {MATCHCRITERIA_NOT_SIGNED, "~signed"},
96 /* msginfo headers */
97 {MATCHCRITERIA_SUBJECT, "subject"},
98 {MATCHCRITERIA_NOT_SUBJECT, "~subject"},
99 {MATCHCRITERIA_FROM, "from"},
100 {MATCHCRITERIA_NOT_FROM, "~from"},
101 {MATCHCRITERIA_TO, "to"},
102 {MATCHCRITERIA_NOT_TO, "~to"},
103 {MATCHCRITERIA_CC, "cc"},
104 {MATCHCRITERIA_NOT_CC, "~cc"},
105 {MATCHCRITERIA_TO_OR_CC, "to_or_cc"},
106 {MATCHCRITERIA_NOT_TO_AND_NOT_CC, "~to_or_cc"},
107 {MATCHCRITERIA_TAG, "tag"},
108 {MATCHCRITERIA_NOT_TAG, "~tag"},
109 {MATCHCRITERIA_TAGGED, "tagged"},
110 {MATCHCRITERIA_NOT_TAGGED, "~tagged"},
111 {MATCHCRITERIA_AGE_GREATER, "age_greater"},
112 {MATCHCRITERIA_AGE_LOWER, "age_lower"},
113 {MATCHCRITERIA_AGE_GREATER_HOURS, "age_greater_hours"},
114 {MATCHCRITERIA_AGE_LOWER_HOURS, "age_lower_hours"},
115 {MATCHCRITERIA_NEWSGROUPS, "newsgroups"},
116 {MATCHCRITERIA_NOT_NEWSGROUPS, "~newsgroups"},
117 {MATCHCRITERIA_INREPLYTO, "inreplyto"},
118 {MATCHCRITERIA_NOT_INREPLYTO, "~inreplyto"},
119 {MATCHCRITERIA_REFERENCES, "references"},
120 {MATCHCRITERIA_NOT_REFERENCES, "~references"},
121 {MATCHCRITERIA_SCORE_GREATER, "score_greater"},
122 {MATCHCRITERIA_SCORE_LOWER, "score_lower"},
123 {MATCHCRITERIA_SCORE_EQUAL, "score_equal"},
124 {MATCHCRITERIA_PARTIAL, "partial"},
125 {MATCHCRITERIA_NOT_PARTIAL, "~partial"},
126 {MATCHCRITERIA_FOUND_IN_ADDRESSBOOK, "found_in_addressbook"},
127 {MATCHCRITERIA_NOT_FOUND_IN_ADDRESSBOOK, "~found_in_addressbook"},
129 {MATCHCRITERIA_SIZE_GREATER, "size_greater"},
130 {MATCHCRITERIA_SIZE_SMALLER, "size_smaller"},
131 {MATCHCRITERIA_SIZE_EQUAL, "size_equal"},
133 /* content have to be read */
134 {MATCHCRITERIA_HEADER, "header"},
135 {MATCHCRITERIA_NOT_HEADER, "~header"},
136 {MATCHCRITERIA_HEADERS_PART, "headers_part"},
137 {MATCHCRITERIA_NOT_HEADERS_PART, "~headers_part"},
138 {MATCHCRITERIA_MESSAGE, "message"},
139 {MATCHCRITERIA_NOT_MESSAGE, "~message"},
140 {MATCHCRITERIA_BODY_PART, "body_part"},
141 {MATCHCRITERIA_NOT_BODY_PART, "~body_part"},
142 {MATCHCRITERIA_TEST, "test"},
143 {MATCHCRITERIA_NOT_TEST, "~test"},
145 /* match type */
146 {MATCHTYPE_MATCHCASE, "matchcase"},
147 {MATCHTYPE_MATCH, "match"},
148 {MATCHTYPE_REGEXPCASE, "regexpcase"},
149 {MATCHTYPE_REGEXP, "regexp"},
151 /* actions */
152 {MATCHACTION_SCORE, "score"}, /* for backward compatibility */
153 {MATCHACTION_MOVE, "move"},
154 {MATCHACTION_COPY, "copy"},
155 {MATCHACTION_DELETE, "delete"},
156 {MATCHACTION_MARK, "mark"},
157 {MATCHACTION_UNMARK, "unmark"},
158 {MATCHACTION_LOCK, "lock"},
159 {MATCHACTION_UNLOCK, "unlock"},
160 {MATCHACTION_MARK_AS_READ, "mark_as_read"},
161 {MATCHACTION_MARK_AS_UNREAD, "mark_as_unread"},
162 {MATCHACTION_MARK_AS_SPAM, "mark_as_spam"},
163 {MATCHACTION_MARK_AS_HAM, "mark_as_ham"},
164 {MATCHACTION_FORWARD, "forward"},
165 {MATCHACTION_FORWARD_AS_ATTACHMENT, "forward_as_attachment"},
166 {MATCHACTION_EXECUTE, "execute"},
167 {MATCHACTION_COLOR, "color"},
168 {MATCHACTION_REDIRECT, "redirect"},
169 {MATCHACTION_CHANGE_SCORE, "change_score"},
170 {MATCHACTION_SET_SCORE, "set_score"},
171 {MATCHACTION_STOP, "stop"},
172 {MATCHACTION_HIDE, "hide"},
173 {MATCHACTION_IGNORE, "ignore"},
174 {MATCHACTION_WATCH, "watch"},
175 {MATCHACTION_ADD_TO_ADDRESSBOOK, "add_to_addressbook"},
176 {MATCHACTION_SET_TAG, "set_tag"},
177 {MATCHACTION_UNSET_TAG, "unset_tag"},
178 {MATCHACTION_CLEAR_TAGS, "clear_tags"},
181 enum {
182 MATCH_ANY = 0,
183 MATCH_ALL = 1,
184 MATCH_ONE = 2
187 enum {
188 CONTEXT_SUBJECT,
189 CONTEXT_FROM,
190 CONTEXT_TO,
191 CONTEXT_CC,
192 CONTEXT_NEWSGROUPS,
193 CONTEXT_IN_REPLY_TO,
194 CONTEXT_REFERENCES,
195 CONTEXT_HEADER,
196 CONTEXT_HEADER_LINE,
197 CONTEXT_BODY_LINE,
198 CONTEXT_TAG,
199 N_CONTEXT_STRS
202 static gchar *context_str[N_CONTEXT_STRS];
204 void matcher_init(void)
206 if (context_str[CONTEXT_SUBJECT] != NULL)
207 return;
209 context_str[CONTEXT_SUBJECT] = g_strdup_printf(_("%s header"), prefs_common_translated_header_name("Subject:"));
210 context_str[CONTEXT_FROM] = g_strdup_printf(_("%s header"), prefs_common_translated_header_name("From:"));
211 context_str[CONTEXT_TO] = g_strdup_printf(_("%s header"), prefs_common_translated_header_name("To:"));
212 context_str[CONTEXT_CC] = g_strdup_printf(_("%s header"), prefs_common_translated_header_name("Cc:"));
213 context_str[CONTEXT_NEWSGROUPS] = g_strdup_printf(_("%s header"), prefs_common_translated_header_name("Newsgroups:"));
214 context_str[CONTEXT_IN_REPLY_TO] = g_strdup_printf(_("%s header"), prefs_common_translated_header_name("In-Reply-To:"));
215 context_str[CONTEXT_REFERENCES] = g_strdup_printf(_("%s header"), prefs_common_translated_header_name("References:"));
216 context_str[CONTEXT_HEADER] = g_strdup(_("header"));
217 context_str[CONTEXT_HEADER_LINE] = g_strdup(_("header line"));
218 context_str[CONTEXT_BODY_LINE] = g_strdup(_("body line"));
219 context_str[CONTEXT_TAG] = g_strdup(_("tag"));
222 void matcher_done(void)
224 int i;
225 for (i = 0; i < N_CONTEXT_STRS; i++) {
226 g_free(context_str[i]);
227 context_str[i] = NULL;
231 extern gboolean debug_filtering_session;
234 *\brief Look up table with keywords defined in \sa matchparser_tab
236 static GHashTable *matchparser_hashtab;
239 *\brief Translate keyword id to keyword string
241 *\param id Id of keyword
243 *\return const gchar * Keyword
245 const gchar *get_matchparser_tab_str(gint id)
247 gint i;
249 for (i = 0; i < sizeof matchparser_tab / sizeof matchparser_tab[0]; i++) {
250 if (matchparser_tab[i].id == id)
251 return matchparser_tab[i].str;
253 return NULL;
257 *\brief Create keyword lookup table
259 static void create_matchparser_hashtab(void)
261 int i;
263 if (matchparser_hashtab) return;
264 matchparser_hashtab = g_hash_table_new(g_str_hash, g_str_equal);
265 for (i = 0; i < sizeof matchparser_tab / sizeof matchparser_tab[0]; i++)
266 g_hash_table_insert(matchparser_hashtab,
267 matchparser_tab[i].str,
268 (gpointer) &matchparser_tab[i]);
272 *\brief Return a keyword id from a keyword string
274 *\param str Keyword string
276 *\return gint Keyword id
278 gint get_matchparser_tab_id(const gchar *str)
280 MatchParser *res;
282 if (NULL != (res = g_hash_table_lookup(matchparser_hashtab, str))) {
283 return res->id;
284 } else
285 return -1;
288 /* **************** data structure allocation **************** */
291 *\brief Allocate a structure for a filtering / scoring
292 * "condition" (a matcher structure)
294 *\param criteria Criteria ID (MATCHCRITERIA_XXXX)
295 *\param header Header string (if criteria is MATCHCRITERIA_HEADER
296 or MATCHCRITERIA_FOUND_IN_ADDRESSBOOK)
297 *\param matchtype Type of action (MATCHTYPE_XXX)
298 *\param expr String value or expression to check
299 *\param value Integer value to check
301 *\return MatcherProp * Pointer to newly allocated structure
303 MatcherProp *matcherprop_new(gint criteria, const gchar *header,
304 gint matchtype, const gchar *expr,
305 int value)
307 MatcherProp *prop;
309 prop = g_new0(MatcherProp, 1);
310 prop->criteria = criteria;
311 prop->header = header != NULL ? g_strdup(header) : NULL;
313 prop->expr = expr != NULL ? g_strdup(expr) : NULL;
315 prop->matchtype = matchtype;
316 #ifndef G_OS_WIN32
317 prop->preg = NULL;
318 #endif
319 prop->value = value;
320 prop->error = 0;
322 return prop;
326 *\brief Free a matcher structure
328 *\param prop Pointer to matcher structure allocated with
329 * #matcherprop_new
331 void matcherprop_free(MatcherProp *prop)
333 g_free(prop->expr);
334 g_free(prop->header);
335 #ifndef G_OS_WIN32
336 if (prop->preg != NULL) {
337 regfree(prop->preg);
338 g_free(prop->preg);
340 #endif
341 g_free(prop);
345 *\brief Copy a matcher structure
347 *\param src Matcher structure to copy
349 *\return MatcherProp * Pointer to newly allocated matcher structure
351 MatcherProp *matcherprop_copy(const MatcherProp *src)
353 MatcherProp *prop = g_new0(MatcherProp, 1);
355 prop->criteria = src->criteria;
356 prop->header = src->header ? g_strdup(src->header) : NULL;
357 prop->expr = src->expr ? g_strdup(src->expr) : NULL;
358 prop->matchtype = src->matchtype;
360 #ifndef G_OS_WIN32
361 prop->preg = NULL; /* will be re-evaluated */
362 #endif
363 prop->value = src->value;
364 prop->error = src->error;
365 return prop;
368 /* ************** match ******************************/
370 static gboolean match_with_addresses_in_addressbook
371 (MatcherProp *prop, GSList *address_list, gint type,
372 gchar* folderpath, gint match)
374 GSList *walk = NULL;
375 gboolean found = FALSE;
376 gchar *path = NULL;
378 cm_return_val_if_fail(address_list != NULL, FALSE);
380 debug_print("match_with_addresses_in_addressbook(%d, %s)\n",
381 g_slist_length(address_list), folderpath?folderpath:"(null)");
383 if (folderpath == NULL ||
384 strcasecmp(folderpath, "Any") == 0 ||
385 *folderpath == '\0')
386 path = NULL;
387 else
388 path = folderpath;
390 start_address_completion(path);
392 for (walk = address_list; walk != NULL; walk = walk->next) {
393 /* exact matching of email address */
394 guint num_addr = complete_address(walk->data);
395 found = FALSE;
396 if (num_addr > 1) {
397 /* skip first item (this is the search string itself) */
398 int i = 1;
399 for (; i < num_addr && !found; i++) {
400 gchar *addr = get_complete_address(i);
401 extract_address(addr);
402 if (strcasecmp(addr, walk->data) == 0) {
403 found = TRUE;
405 /* debug output */
406 if (debug_filtering_session
407 && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
408 log_print(LOG_DEBUG_FILTERING,
409 "address [ %s ] matches\n",
410 (gchar *)walk->data);
413 g_free(addr);
416 /* debug output */
417 if (debug_filtering_session
418 && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH
419 && !found) {
420 log_print(LOG_DEBUG_FILTERING,
421 "address [ %s ] does NOT match\n",
422 (gchar *)walk->data);
424 g_free(walk->data);
426 if (match == MATCH_ALL) {
427 /* if matching all addresses, stop if one doesn't match */
428 if (!found) {
429 /* debug output */
430 if (debug_filtering_session
431 && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
432 log_print(LOG_DEBUG_FILTERING,
433 "not all address match (matching all)\n");
435 break;
437 } else if (match == MATCH_ANY) {
438 /* if matching any address, stop if one does match */
439 if (found) {
440 /* debug output */
441 if (debug_filtering_session
442 && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
443 log_print(LOG_DEBUG_FILTERING,
444 "at least one address matches (matching any)\n");
446 break;
449 /* MATCH_ONE: there should be only one loop iteration */
452 end_address_completion();
454 return found;
458 *\brief Find out if a string matches a condition
460 *\param prop Matcher structure
461 *\param str String to check
463 *\return gboolean TRUE if str matches the condition in the
464 * matcher structure
466 static gboolean matcherprop_string_match(MatcherProp *prop, const gchar *str,
467 const gchar *debug_context)
469 gchar *str1;
470 gchar *down_expr;
471 gboolean ret = FALSE;
472 gboolean should_free = FALSE;
473 if (str == NULL)
474 return FALSE;
476 if (prop->matchtype == MATCHTYPE_REGEXPCASE ||
477 prop->matchtype == MATCHTYPE_MATCHCASE) {
478 str1 = g_utf8_casefold(str, -1);
479 down_expr = g_utf8_casefold(prop->expr, -1);
480 should_free = TRUE;
481 } else {
482 str1 = (gchar *)str;
483 down_expr = (gchar *)prop->expr;
484 should_free = FALSE;
487 switch (prop->matchtype) {
488 case MATCHTYPE_REGEXPCASE:
489 case MATCHTYPE_REGEXP:
490 #ifndef G_OS_WIN32
491 if (!prop->preg && (prop->error == 0)) {
492 prop->preg = g_new0(regex_t, 1);
493 /* if regexp then don't use the escaped string */
494 if (regcomp(prop->preg, down_expr,
495 REG_NOSUB | REG_EXTENDED
496 | ((prop->matchtype == MATCHTYPE_REGEXPCASE)
497 ? REG_ICASE : 0)) != 0) {
498 prop->error = 1;
499 g_free(prop->preg);
500 prop->preg = NULL;
503 if (prop->preg == NULL) {
504 ret = FALSE;
505 goto free_strs;
508 if (regexec(prop->preg, str1, 0, NULL, 0) == 0)
509 ret = TRUE;
510 else
511 ret = FALSE;
513 /* debug output */
514 if (debug_filtering_session
515 && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
516 gchar *stripped = g_strdup(str);
518 strretchomp(stripped);
519 if (ret) {
520 log_print(LOG_DEBUG_FILTERING,
521 "%s value [ %s ] matches regular expression [ %s ] (%s)\n",
522 debug_context, stripped, prop->expr,
523 prop->matchtype == MATCHTYPE_REGEXP ? _("Case sensitive"):_("Case insensitive"));
524 } else {
525 log_print(LOG_DEBUG_FILTERING,
526 "%s value [ %s ] does NOT match regular expression [ %s ] (%s)\n",
527 debug_context, stripped, prop->expr,
528 prop->matchtype == MATCHTYPE_REGEXP ? _("Case sensitive"):_("Case insensitive"));
530 g_free(stripped);
532 break;
533 #endif
534 case MATCHTYPE_MATCHCASE:
535 case MATCHTYPE_MATCH:
536 ret = (strstr(str1, down_expr) != NULL);
538 /* debug output */
539 if (debug_filtering_session
540 && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
541 gchar *stripped = g_strdup(str);
543 strretchomp(stripped);
544 if (ret) {
545 log_print(LOG_DEBUG_FILTERING,
546 "%s value [ %s ] contains [ %s ] (%s)\n",
547 debug_context, stripped, prop->expr,
548 prop->matchtype == MATCHTYPE_MATCH ? _("Case sensitive"):_("Case insensitive"));
549 } else {
550 log_print(LOG_DEBUG_FILTERING,
551 "%s value [ %s ] does NOT contain [ %s ] (%s)\n",
552 debug_context, stripped, prop->expr,
553 prop->matchtype == MATCHTYPE_MATCH ? _("Case sensitive"):_("Case insensitive"));
555 g_free(stripped);
557 break;
559 default:
560 break;
563 free_strs:
564 if (should_free) {
565 g_free(str1);
566 g_free(down_expr);
568 return ret;
572 *\brief Find out if a tag matches a condition
574 *\param prop Matcher structure
575 *\param msginfo message to check
577 *\return gboolean TRUE if msginfo matches the condition in the
578 * matcher structure
580 static gboolean matcherprop_tag_match(MatcherProp *prop, MsgInfo *msginfo,
581 const gchar *debug_context)
583 gboolean ret = FALSE;
584 GSList *cur;
586 if (msginfo == NULL || msginfo->tags == NULL)
587 return FALSE;
589 for (cur = msginfo->tags; cur; cur = cur->next) {
590 const gchar *str = tags_get_tag(GPOINTER_TO_INT(cur->data));
591 if (!str)
592 continue;
593 if (matcherprop_string_match(prop, str, debug_context)) {
594 ret = TRUE;
595 break;
598 return ret;
602 *\brief Find out if the string-ed list matches a condition
604 *\param prop Matcher structure
605 *\param list GSList of strings to check
607 *\return gboolean TRUE if str matches the condition in the
608 * matcher structure
610 static gboolean matcherprop_list_match(MatcherProp *prop, const GSList *list,
611 const gchar *debug_context)
613 const GSList *cur;
615 for(cur = list; cur != NULL; cur = cur->next) {
616 if (matcherprop_string_match(prop, (gchar *)cur->data, debug_context))
617 return TRUE;
619 return FALSE;
622 static gboolean matcherprop_header_line_match(MatcherProp *prop, const gchar *hdr,
623 const gchar *str, const gchar *debug_context)
625 gchar *line = NULL;
626 gboolean res = FALSE;
628 if (hdr == NULL || str == NULL)
629 return FALSE;
631 line = g_strdup_printf("%s %s", hdr, str);
632 res = matcherprop_string_match(prop, line, debug_context);
633 g_free(line);
635 return res;
638 #ifdef USE_PTHREAD
639 typedef struct _thread_data {
640 const gchar *cmd;
641 gboolean done;
642 } thread_data;
643 #endif
645 #ifdef USE_PTHREAD
646 static void *matcher_test_thread(void *data)
648 thread_data *td = (thread_data *)data;
649 int result = -1;
651 pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
652 pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
654 result = system(td->cmd);
655 td->done = TRUE; /* let the caller thread join() */
656 return GINT_TO_POINTER(result);
658 #endif
661 *\brief Execute a command defined in the matcher structure
663 *\param prop Pointer to matcher structure
664 *\param info Pointer to message info structure
666 *\return gboolean TRUE if command was executed succesfully
668 static gboolean matcherprop_match_test(const MatcherProp *prop,
669 MsgInfo *info)
671 gchar *file;
672 gchar *cmd;
673 gint retval;
674 #ifdef USE_PTHREAD
675 pthread_t pt;
676 pthread_attr_t pta;
677 thread_data *td = g_new0(thread_data, 1);
678 void *res = NULL;
679 time_t start_time = time(NULL);
680 #endif
682 file = procmsg_get_message_file(info);
683 if (file == NULL) {
684 #ifdef USE_PTHREAD
685 g_free(td);
686 #endif
687 return FALSE;
689 g_free(file);
691 cmd = matching_build_command(prop->expr, info);
692 if (cmd == NULL) {
693 #ifdef USE_PTHREAD
694 g_free(td);
695 #endif
696 return FALSE;
699 #ifdef USE_PTHREAD
700 /* debug output */
701 if (debug_filtering_session
702 && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
703 log_print(LOG_DEBUG_FILTERING,
704 "starting threaded command [ %s ]\n",
705 cmd);
708 td->cmd = cmd;
709 td->done = FALSE;
710 if (pthread_attr_init(&pta) != 0 ||
711 pthread_attr_setdetachstate(&pta, PTHREAD_CREATE_JOINABLE) != 0 ||
712 pthread_create(&pt, &pta, matcher_test_thread, td) != 0)
713 retval = system(cmd);
714 else {
715 debug_print("waiting for test thread\n");
716 while(!td->done) {
717 /* don't let the interface freeze while waiting */
718 claws_do_idle();
719 if (time(NULL) - start_time > 30) {
720 pthread_cancel(pt);
721 td->done = TRUE;
722 retval = -1;
725 pthread_join(pt, &res);
726 retval = GPOINTER_TO_INT(res);
727 debug_print(" test thread returned %d\n", retval);
729 g_free(td);
730 #else
731 /* debug output */
732 if (debug_filtering_session
733 && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
734 log_print(LOG_DEBUG_FILTERING,
735 "starting synchronous command [ %s ]\n",
736 cmd);
739 retval = system(cmd);
740 #endif
741 debug_print("Command exit code: %d\n", retval);
743 /* debug output */
744 if (debug_filtering_session
745 && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
746 log_print(LOG_DEBUG_FILTERING,
747 "command returned [ %d ]\n",
748 retval);
751 g_free(cmd);
752 return (retval == 0);
756 *\brief Check if a message matches the condition in a matcher
757 * structure.
759 *\param prop Pointer to matcher structure
760 *\param info Pointer to message info
762 *\return gboolean TRUE if a match
764 static gboolean matcherprop_match(MatcherProp *prop,
765 MsgInfo *info)
767 time_t t;
768 gint age_mult_hours = 1;
770 switch(prop->criteria) {
771 case MATCHCRITERIA_ALL:
772 return TRUE;
773 case MATCHCRITERIA_UNREAD:
774 return MSG_IS_UNREAD(info->flags);
775 case MATCHCRITERIA_NOT_UNREAD:
776 return !MSG_IS_UNREAD(info->flags);
777 case MATCHCRITERIA_NEW:
778 return MSG_IS_NEW(info->flags);
779 case MATCHCRITERIA_NOT_NEW:
780 return !MSG_IS_NEW(info->flags);
781 case MATCHCRITERIA_MARKED:
782 return MSG_IS_MARKED(info->flags);
783 case MATCHCRITERIA_NOT_MARKED:
784 return !MSG_IS_MARKED(info->flags);
785 case MATCHCRITERIA_DELETED:
786 return MSG_IS_DELETED(info->flags);
787 case MATCHCRITERIA_NOT_DELETED:
788 return !MSG_IS_DELETED(info->flags);
789 case MATCHCRITERIA_REPLIED:
790 return MSG_IS_REPLIED(info->flags);
791 case MATCHCRITERIA_NOT_REPLIED:
792 return !MSG_IS_REPLIED(info->flags);
793 case MATCHCRITERIA_FORWARDED:
794 return MSG_IS_FORWARDED(info->flags);
795 case MATCHCRITERIA_NOT_FORWARDED:
796 return !MSG_IS_FORWARDED(info->flags);
797 case MATCHCRITERIA_LOCKED:
798 return MSG_IS_LOCKED(info->flags);
799 case MATCHCRITERIA_NOT_LOCKED:
800 return !MSG_IS_LOCKED(info->flags);
801 case MATCHCRITERIA_SPAM:
802 return MSG_IS_SPAM(info->flags);
803 case MATCHCRITERIA_NOT_SPAM:
804 return !MSG_IS_SPAM(info->flags);
805 case MATCHCRITERIA_HAS_ATTACHMENT:
806 return MSG_IS_WITH_ATTACHMENT(info->flags);
807 case MATCHCRITERIA_HAS_NO_ATTACHMENT:
808 return !MSG_IS_WITH_ATTACHMENT(info->flags);
809 case MATCHCRITERIA_SIGNED:
810 return MSG_IS_SIGNED(info->flags);
811 case MATCHCRITERIA_NOT_SIGNED:
812 return !MSG_IS_SIGNED(info->flags);
813 case MATCHCRITERIA_COLORLABEL:
815 gint color = MSG_GET_COLORLABEL_VALUE(info->flags);
816 gboolean ret = (color == prop->value);
818 /* debug output */
819 if (debug_filtering_session
820 && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
821 if (ret) {
822 log_print(LOG_DEBUG_FILTERING,
823 "message color value [ %d ] matches color value [ %d ]\n",
824 color, prop->value);
825 } else {
826 log_print(LOG_DEBUG_FILTERING,
827 "message color value [ %d ] does NOT match color value [ %d ]\n",
828 color, prop->value);
831 return ret;
833 case MATCHCRITERIA_NOT_COLORLABEL:
835 gint color = MSG_GET_COLORLABEL_VALUE(info->flags);
836 gboolean ret = (color != prop->value);
838 /* debug output */
839 if (debug_filtering_session
840 && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
841 if (ret) {
842 log_print(LOG_DEBUG_FILTERING,
843 "message color value [ %d ] matches color value [ %d ]\n",
844 color, prop->value);
845 } else {
846 log_print(LOG_DEBUG_FILTERING,
847 "message color value [ %d ] does NOT match color value [ %d ]\n",
848 color, prop->value);
851 return ret;
853 case MATCHCRITERIA_IGNORE_THREAD:
854 return MSG_IS_IGNORE_THREAD(info->flags);
855 case MATCHCRITERIA_NOT_IGNORE_THREAD:
856 return !MSG_IS_IGNORE_THREAD(info->flags);
857 case MATCHCRITERIA_WATCH_THREAD:
858 return MSG_IS_WATCH_THREAD(info->flags);
859 case MATCHCRITERIA_NOT_WATCH_THREAD:
860 return !MSG_IS_WATCH_THREAD(info->flags);
861 case MATCHCRITERIA_SUBJECT:
862 return matcherprop_string_match(prop, info->subject, context_str[CONTEXT_SUBJECT]);
863 case MATCHCRITERIA_NOT_SUBJECT:
864 return !matcherprop_string_match(prop, info->subject, context_str[CONTEXT_SUBJECT]);
865 case MATCHCRITERIA_FROM:
866 return matcherprop_string_match(prop, info->from, context_str[CONTEXT_FROM]);
867 case MATCHCRITERIA_NOT_FROM:
868 return !matcherprop_string_match(prop, info->from, context_str[CONTEXT_FROM]);
869 case MATCHCRITERIA_TO:
870 return matcherprop_string_match(prop, info->to, context_str[CONTEXT_TO]);
871 case MATCHCRITERIA_NOT_TO:
872 return !matcherprop_string_match(prop, info->to, context_str[CONTEXT_TO]);
873 case MATCHCRITERIA_CC:
874 return matcherprop_string_match(prop, info->cc, context_str[CONTEXT_CC]);
875 case MATCHCRITERIA_NOT_CC:
876 return !matcherprop_string_match(prop, info->cc, context_str[CONTEXT_CC]);
877 case MATCHCRITERIA_TO_OR_CC:
878 return matcherprop_string_match(prop, info->to, context_str[CONTEXT_TO])
879 || matcherprop_string_match(prop, info->cc, context_str[CONTEXT_CC]);
880 case MATCHCRITERIA_NOT_TO_AND_NOT_CC:
881 return !matcherprop_string_match(prop, info->to, context_str[CONTEXT_TO])
882 && !matcherprop_string_match(prop, info->cc, context_str[CONTEXT_CC]);
883 case MATCHCRITERIA_TAG:
884 return matcherprop_tag_match(prop, info, context_str[CONTEXT_TAG]);
885 case MATCHCRITERIA_NOT_TAG:
886 return !matcherprop_tag_match(prop, info, context_str[CONTEXT_TAG]);
887 case MATCHCRITERIA_TAGGED:
888 return info->tags != NULL;
889 case MATCHCRITERIA_NOT_TAGGED:
890 return info->tags == NULL;
891 case MATCHCRITERIA_AGE_GREATER:
892 age_mult_hours = 24;
893 /* Fallthrough intended */
894 case MATCHCRITERIA_AGE_GREATER_HOURS:
896 gboolean ret;
897 gint age;
899 t = time(NULL);
900 age = ((t - info->date_t) / (60 * 60 * age_mult_hours));
901 ret = (age >= prop->value);
903 /* debug output */
904 if (debug_filtering_session
905 && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
906 if (ret) {
907 log_print(LOG_DEBUG_FILTERING,
908 "message age [ %d ] is greater than [ %d ]\n",
909 age, prop->value);
910 } else {
911 log_print(LOG_DEBUG_FILTERING,
912 "message age [ %d ] is not greater than [ %d ]\n",
913 age, prop->value);
916 return ret;
918 case MATCHCRITERIA_AGE_LOWER:
919 age_mult_hours = 24;
920 /* Fallthrough intended */
921 case MATCHCRITERIA_AGE_LOWER_HOURS:
923 gboolean ret;
924 gint age;
926 t = time(NULL);
927 age = ((t - info->date_t) / (60 * 60 * age_mult_hours));
928 ret = (age < prop->value);
930 /* debug output */
931 if (debug_filtering_session
932 && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
933 if (ret) {
934 log_print(LOG_DEBUG_FILTERING,
935 "message age [ %d ] is lower than [ %d ]\n",
936 age, prop->value);
937 } else {
938 log_print(LOG_DEBUG_FILTERING,
939 "message age [ %d ] is not lower than [ %d ]\n",
940 age, prop->value);
943 return ret;
945 case MATCHCRITERIA_SCORE_GREATER:
947 gboolean ret = (info->score > prop->value);
949 /* debug output */
950 if (debug_filtering_session
951 && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
952 if (ret) {
953 log_print(LOG_DEBUG_FILTERING,
954 "message score [ %d ] is greater than [ %d ]\n",
955 info->score, prop->value);
956 } else {
957 log_print(LOG_DEBUG_FILTERING,
958 "message score [ %d ] is not greater than [ %d ]\n",
959 info->score, prop->value);
962 return ret;
964 case MATCHCRITERIA_SCORE_LOWER:
966 gboolean ret = (info->score < prop->value);
968 /* debug output */
969 if (debug_filtering_session
970 && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
971 if (ret) {
972 log_print(LOG_DEBUG_FILTERING,
973 "message score [ %d ] is lower than [ %d ]\n",
974 info->score, prop->value);
975 } else {
976 log_print(LOG_DEBUG_FILTERING,
977 "message score [ %d ] is not lower than [ %d ]\n",
978 info->score, prop->value);
981 return ret;
983 case MATCHCRITERIA_SCORE_EQUAL:
985 gboolean ret = (info->score == prop->value);
987 /* debug output */
988 if (debug_filtering_session
989 && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
990 if (ret) {
991 log_print(LOG_DEBUG_FILTERING,
992 "message score [ %d ] is equal to [ %d ]\n",
993 info->score, prop->value);
994 } else {
995 log_print(LOG_DEBUG_FILTERING,
996 "message score [ %d ] is not equal to [ %d ]\n",
997 info->score, prop->value);
1000 return ret;
1002 case MATCHCRITERIA_SIZE_GREATER:
1004 /* FIXME: info->size is a goffset */
1005 gboolean ret = (info->size > (goffset) prop->value);
1007 /* debug output */
1008 if (debug_filtering_session
1009 && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
1010 if (ret) {
1011 log_print(LOG_DEBUG_FILTERING,
1012 "message size is greater than [ %d ]\n",
1013 prop->value);
1014 } else {
1015 log_print(LOG_DEBUG_FILTERING,
1016 "message size is not greater than [ %d ]\n",
1017 prop->value);
1020 return ret;
1022 case MATCHCRITERIA_SIZE_SMALLER:
1024 /* FIXME: info->size is a goffset */
1025 gboolean ret = (info->size < (goffset) prop->value);
1027 /* debug output */
1028 if (debug_filtering_session
1029 && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
1030 if (ret) {
1031 log_print(LOG_DEBUG_FILTERING,
1032 "message size is smaller than [ %d ]\n",
1033 prop->value);
1034 } else {
1035 log_print(LOG_DEBUG_FILTERING,
1036 "message size is not smaller than [ %d ]\n",
1037 prop->value);
1040 return ret;
1042 case MATCHCRITERIA_SIZE_EQUAL:
1044 /* FIXME: info->size is a goffset */
1045 gboolean ret = (info->size == (goffset) prop->value);
1047 /* debug output */
1048 if (debug_filtering_session
1049 && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
1050 if (ret) {
1051 log_print(LOG_DEBUG_FILTERING,
1052 "message size is equal to [ %d ]\n",
1053 prop->value);
1054 } else {
1055 log_print(LOG_DEBUG_FILTERING,
1056 "message size is not equal to [ %d ]\n",
1057 prop->value);
1060 return ret;
1062 case MATCHCRITERIA_PARTIAL:
1064 /* FIXME: info->size is a goffset */
1065 gboolean ret = (info->total_size != 0 && info->size != (goffset)info->total_size);
1067 /* debug output */
1068 if (debug_filtering_session
1069 && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
1070 if (ret) {
1071 log_print(LOG_DEBUG_FILTERING,
1072 "message is partially downloaded, size is less than total size [ %d ])\n",
1073 info->total_size);
1074 } else {
1075 log_print(LOG_DEBUG_FILTERING,
1076 "message is not partially downloaded\n");
1079 return ret;
1081 case MATCHCRITERIA_NOT_PARTIAL:
1083 /* FIXME: info->size is a goffset */
1084 gboolean ret = (info->total_size == 0 || info->size == (goffset)info->total_size);
1086 /* debug output */
1087 if (debug_filtering_session
1088 && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
1089 if (ret) {
1090 log_print(LOG_DEBUG_FILTERING,
1091 "message is not partially downloaded\n");
1092 } else {
1093 log_print(LOG_DEBUG_FILTERING,
1094 "message is partially downloaded, size is less than total size [ %d ])\n",
1095 info->total_size);
1098 return ret;
1100 case MATCHCRITERIA_NEWSGROUPS:
1101 return matcherprop_string_match(prop, info->newsgroups, context_str[CONTEXT_NEWSGROUPS]);
1102 case MATCHCRITERIA_NOT_NEWSGROUPS:
1103 return !matcherprop_string_match(prop, info->newsgroups, context_str[CONTEXT_NEWSGROUPS]);
1104 case MATCHCRITERIA_INREPLYTO:
1105 return matcherprop_string_match(prop, info->inreplyto, context_str[CONTEXT_IN_REPLY_TO]);
1106 case MATCHCRITERIA_NOT_INREPLYTO:
1107 return !matcherprop_string_match(prop, info->inreplyto, context_str[CONTEXT_IN_REPLY_TO]);
1108 case MATCHCRITERIA_REFERENCES:
1109 return matcherprop_list_match(prop, info->references, context_str[CONTEXT_REFERENCES]);
1110 case MATCHCRITERIA_NOT_REFERENCES:
1111 return !matcherprop_list_match(prop, info->references, context_str[CONTEXT_REFERENCES]);
1112 case MATCHCRITERIA_TEST:
1113 return matcherprop_match_test(prop, info);
1114 case MATCHCRITERIA_NOT_TEST:
1115 return !matcherprop_match_test(prop, info);
1116 default:
1117 return FALSE;
1121 /* ********************* MatcherList *************************** */
1124 *\brief Create a new list of matchers
1126 *\param matchers List of matcher structures
1127 *\param bool_and Operator
1129 *\return MatcherList * New list
1131 MatcherList *matcherlist_new(GSList *matchers, gboolean bool_and)
1133 MatcherList *cond;
1135 cond = g_new0(MatcherList, 1);
1137 cond->matchers = matchers;
1138 cond->bool_and = bool_and;
1140 return cond;
1143 #ifdef G_OS_UNIX
1145 *\brief Builds a single regular expresion from an array of srings.
1147 *\param strings The lines containing the different sub-regexp.
1149 *\return The newly allocated regexp string.
1151 static gchar *build_complete_regexp(gchar **strings)
1153 int i = 0;
1154 gchar *expr = NULL;
1155 while (strings && strings[i] && *strings[i]) {
1156 int old_len = expr ? strlen(expr):0;
1157 int new_len = 0;
1158 gchar *tmpstr = NULL;
1160 if (g_utf8_validate(strings[i], -1, NULL))
1161 tmpstr = g_strdup(strings[i]);
1162 else
1163 tmpstr = conv_codeset_strdup(strings[i],
1164 conv_get_locale_charset_str_no_utf8(),
1165 CS_INTERNAL);
1167 if (strstr(tmpstr, "\n"))
1168 *(strstr(tmpstr, "\n")) = '\0';
1170 new_len = strlen(tmpstr);
1172 expr = g_realloc(expr,
1173 expr ? (old_len + strlen("|()") + new_len + 1)
1174 : (strlen("()") + new_len + 1));
1176 if (old_len) {
1177 strcpy(expr + old_len, "|(");
1178 strcpy(expr + old_len + 2, tmpstr);
1179 strcpy(expr + old_len + 2 + new_len, ")");
1180 } else {
1181 strcpy(expr+old_len, "(");
1182 strcpy(expr+old_len + 1, tmpstr);
1183 strcpy(expr+old_len + 1 + new_len, ")");
1185 g_free(tmpstr);
1186 i++;
1188 return expr;
1190 #endif
1193 *\brief Create a new list of matchers from a multi-line string
1195 *\param lines String with "\n"-separated expressions
1196 *\param bool_and Operator
1197 *\param case_sensitive If the matching is case sensitive or not
1199 *\return MatcherList * New matcher list
1201 MatcherList *matcherlist_new_from_lines(gchar *lines, gboolean bool_and,
1202 gboolean case_sensitive)
1204 MatcherProp *m = NULL;
1205 GSList *matchers = NULL;
1206 gchar **strings = g_strsplit(lines, "\n", -1);
1208 #ifdef G_OS_UNIX
1209 gchar *expr = NULL;
1210 expr = build_complete_regexp(strings);
1211 debug_print("building matcherprop for expr '%s'\n", expr?expr:"NULL");
1213 m = matcherprop_new(MATCHCRITERIA_SUBJECT, NULL,
1214 case_sensitive? MATCHTYPE_REGEXP: MATCHTYPE_REGEXPCASE,
1215 expr, 0);
1216 if (m == NULL) {
1217 /* print error message */
1218 debug_print("failed to allocate memory for matcherprop\n");
1219 } else {
1220 matchers = g_slist_append(matchers, m);
1223 g_free(expr);
1224 #else
1225 int i = 0;
1226 while (strings && strings[i] && *strings[i]) {
1227 m = matcherprop_new(MATCHCRITERIA_SUBJECT, NULL,
1228 case_sensitive? MATCHTYPE_MATCH: MATCHTYPE_MATCHCASE,
1229 strings[i], 0);
1230 if (m == NULL) {
1231 /* print error message */
1232 debug_print("failed to allocate memory for matcherprop\n");
1233 } else {
1234 matchers = g_slist_append(matchers, m);
1236 i++;
1238 #endif
1239 g_strfreev(strings);
1241 return matcherlist_new(matchers, bool_and);
1245 *\brief Frees a list of matchers
1247 *\param cond List of matchers
1249 void matcherlist_free(MatcherList *cond)
1251 GSList *l;
1253 cm_return_if_fail(cond);
1254 for (l = cond->matchers ; l != NULL ; l = g_slist_next(l)) {
1255 matcherprop_free((MatcherProp *) l->data);
1257 g_slist_free(cond->matchers);
1258 g_free(cond);
1262 *\brief Skip all headers in a message file
1264 *\param fp Message file
1266 static void matcherlist_skip_headers(FILE *fp)
1268 gchar buf[BUFFSIZE];
1270 while (procheader_get_one_field(buf, sizeof(buf), fp, NULL) != -1)
1275 *\brief Check if a header matches a matcher condition
1277 *\param matcher Matcher structure to check header for
1278 *\param buf Header name
1280 *\return boolean TRUE if matching header
1282 static gboolean matcherprop_match_one_header(MatcherProp *matcher,
1283 gchar *buf)
1285 gboolean result = FALSE;
1286 Header *header = NULL;
1288 switch (matcher->criteria) {
1289 case MATCHCRITERIA_HEADER:
1290 case MATCHCRITERIA_NOT_HEADER:
1291 header = procheader_parse_header(buf);
1292 if (!header)
1293 return FALSE;
1294 if (procheader_headername_equal(header->name,
1295 matcher->header)) {
1296 if (matcher->criteria == MATCHCRITERIA_HEADER)
1297 result = matcherprop_string_match(matcher, header->body, context_str[CONTEXT_HEADER]);
1298 else
1299 result = !matcherprop_string_match(matcher, header->body, context_str[CONTEXT_HEADER]);
1300 procheader_header_free(header);
1301 return result;
1303 else {
1304 procheader_header_free(header);
1306 break;
1307 case MATCHCRITERIA_HEADERS_PART:
1308 case MATCHCRITERIA_MESSAGE:
1309 header = procheader_parse_header(buf);
1310 if (!header)
1311 return FALSE;
1312 result = matcherprop_header_line_match(matcher,
1313 header->name, header->body, context_str[CONTEXT_HEADER_LINE]);
1314 procheader_header_free(header);
1315 return result;
1316 case MATCHCRITERIA_NOT_HEADERS_PART:
1317 case MATCHCRITERIA_NOT_MESSAGE:
1318 header = procheader_parse_header(buf);
1319 if (!header)
1320 return FALSE;
1321 result = !matcherprop_header_line_match(matcher,
1322 header->name, header->body, context_str[CONTEXT_HEADER_LINE]);
1323 procheader_header_free(header);
1324 return result;
1325 case MATCHCRITERIA_FOUND_IN_ADDRESSBOOK:
1326 case MATCHCRITERIA_NOT_FOUND_IN_ADDRESSBOOK:
1328 GSList *address_list = NULL;
1329 gint match = MATCH_ONE;
1330 gboolean found = FALSE;
1332 /* how many address headers are me trying to mach? */
1333 if (strcasecmp(matcher->header, "Any") == 0)
1334 match = MATCH_ANY;
1335 else if (strcasecmp(matcher->header, "All") == 0)
1336 match = MATCH_ALL;
1338 if (match == MATCH_ONE) {
1339 /* matching one address header exactly, is that the right one? */
1340 header = procheader_parse_header(buf);
1341 if (!header ||
1342 !procheader_headername_equal(header->name, matcher->header))
1343 return FALSE;
1344 address_list = address_list_append(address_list, header->body);
1345 if (address_list == NULL)
1346 return FALSE;
1348 } else {
1349 header = procheader_parse_header(buf);
1350 if (!header)
1351 return FALSE;
1352 /* address header is one of the headers we have to match when checking
1353 for any address header or all address headers? */
1354 if (procheader_headername_equal(header->name, "From") ||
1355 procheader_headername_equal(header->name, "To") ||
1356 procheader_headername_equal(header->name, "Cc") ||
1357 procheader_headername_equal(header->name, "Reply-To") ||
1358 procheader_headername_equal(header->name, "Sender"))
1359 address_list = address_list_append(address_list, header->body);
1360 if (address_list == NULL)
1361 return FALSE;
1364 found = match_with_addresses_in_addressbook
1365 (matcher, address_list, matcher->criteria,
1366 matcher->expr, match);
1367 g_slist_free(address_list);
1369 if (matcher->criteria == MATCHCRITERIA_NOT_FOUND_IN_ADDRESSBOOK)
1370 return !found;
1371 else
1372 return found;
1376 return FALSE;
1380 *\brief Check if the matcher structure wants headers to
1381 * be matched
1383 *\param matcher Matcher structure
1385 *\return gboolean TRUE if the matcher structure describes
1386 * a header match condition
1388 static gboolean matcherprop_criteria_headers(const MatcherProp *matcher)
1390 switch (matcher->criteria) {
1391 case MATCHCRITERIA_HEADER:
1392 case MATCHCRITERIA_NOT_HEADER:
1393 case MATCHCRITERIA_HEADERS_PART:
1394 case MATCHCRITERIA_NOT_HEADERS_PART:
1395 case MATCHCRITERIA_FOUND_IN_ADDRESSBOOK:
1396 case MATCHCRITERIA_NOT_FOUND_IN_ADDRESSBOOK:
1397 return TRUE;
1398 default:
1399 return FALSE;
1404 *\brief Check if the matcher structure wants the message
1405 * to be matched (just perform an action on any
1406 * message)
1408 *\param matcher Matcher structure
1410 *\return gboolean TRUE if matcher condition should match
1411 * a message
1413 static gboolean matcherprop_criteria_message(MatcherProp *matcher)
1415 switch (matcher->criteria) {
1416 case MATCHCRITERIA_MESSAGE:
1417 case MATCHCRITERIA_NOT_MESSAGE:
1418 return TRUE;
1419 default:
1420 return FALSE;
1425 *\brief Check if a list of conditions matches one header in
1426 * a message file.
1428 *\param matchers List of conditions
1429 *\param fp Message file
1431 *\return gboolean TRUE if one of the headers is matched by
1432 * the list of conditions.
1434 static gboolean matcherlist_match_headers(MatcherList *matchers, FILE *fp)
1436 GSList *l;
1437 gchar buf[BUFFSIZE];
1439 while (procheader_get_one_field(buf, sizeof(buf), fp, NULL) != -1) {
1440 for (l = matchers->matchers ; l != NULL ; l = g_slist_next(l)) {
1441 MatcherProp *matcher = (MatcherProp *) l->data;
1442 gint match = MATCH_ANY;
1444 if (matcher->done)
1445 continue;
1447 /* determine the match range (all, any are our concern here) */
1448 if (matcher->criteria == MATCHCRITERIA_NOT_HEADERS_PART ||
1449 matcher->criteria == MATCHCRITERIA_NOT_MESSAGE) {
1450 match = MATCH_ALL;
1452 } else if (matcher->criteria == MATCHCRITERIA_FOUND_IN_ADDRESSBOOK ||
1453 matcher->criteria == MATCHCRITERIA_NOT_FOUND_IN_ADDRESSBOOK) {
1454 Header *header = NULL;
1456 /* address header is one of the headers we have to match when checking
1457 for any address header or all address headers? */
1458 header = procheader_parse_header(buf);
1459 if (header &&
1460 (procheader_headername_equal(header->name, "From") ||
1461 procheader_headername_equal(header->name, "To") ||
1462 procheader_headername_equal(header->name, "Cc") ||
1463 procheader_headername_equal(header->name, "Reply-To") ||
1464 procheader_headername_equal(header->name, "Sender"))) {
1466 if (strcasecmp(matcher->header, "Any") == 0)
1467 match = MATCH_ANY;
1468 else if (strcasecmp(matcher->header, "All") == 0)
1469 match = MATCH_ALL;
1470 else
1471 match = MATCH_ONE;
1472 } else {
1473 /* further call to matcherprop_match_one_header() can't match
1474 and it irrelevant, so: don't alter the match result */
1475 continue;
1479 /* ZERO line must NOT match for the rule to match.
1481 if (match == MATCH_ALL) {
1482 if (matcherprop_match_one_header(matcher, buf)) {
1483 matcher->result = TRUE;
1484 } else {
1485 matcher->result = FALSE;
1486 matcher->done = TRUE;
1488 /* else, just one line matching is enough for the rule to match
1490 } else if (matcherprop_criteria_headers(matcher) ||
1491 matcherprop_criteria_message(matcher)) {
1492 if (matcherprop_match_one_header(matcher, buf)) {
1493 matcher->result = TRUE;
1494 matcher->done = TRUE;
1498 /* if the rule matched and the matchers are OR, no need to
1499 * check the others */
1500 if (matcher->result && matcher->done) {
1501 if (!matchers->bool_and)
1502 return TRUE;
1507 return FALSE;
1511 *\brief Check if a matcher wants to check the message body
1513 *\param matcher Matcher structure
1515 *\return gboolean TRUE if body must be matched.
1517 static gboolean matcherprop_criteria_body(const MatcherProp *matcher)
1519 switch (matcher->criteria) {
1520 case MATCHCRITERIA_BODY_PART:
1521 case MATCHCRITERIA_NOT_BODY_PART:
1522 return TRUE;
1523 default:
1524 return FALSE;
1528 static gboolean matcherlist_match_binary_content(MatcherList *matchers, MimeInfo *partinfo)
1530 FILE *outfp;
1531 gchar buf[BUFFSIZE];
1532 GSList *l;
1534 if (partinfo->type == MIMETYPE_TEXT)
1535 return FALSE;
1536 else
1537 outfp = procmime_get_binary_content(partinfo);
1539 if (!outfp)
1540 return FALSE;
1542 while (fgets(buf, sizeof(buf), outfp) != NULL) {
1543 strretchomp(buf);
1545 for (l = matchers->matchers ; l != NULL ; l = g_slist_next(l)) {
1546 MatcherProp *matcher = (MatcherProp *) l->data;
1548 if (matcher->done)
1549 continue;
1551 /* Don't scan non-text parts when looking in body, only
1552 * when looking in whole message
1554 if (partinfo && partinfo->type != MIMETYPE_TEXT &&
1555 (matcher->criteria == MATCHCRITERIA_NOT_BODY_PART ||
1556 matcher->criteria == MATCHCRITERIA_BODY_PART))
1557 continue;
1559 /* if the criteria is ~body_part or ~message, ZERO lines
1560 * must match for the rule to match.
1562 if (matcher->criteria == MATCHCRITERIA_NOT_BODY_PART ||
1563 matcher->criteria == MATCHCRITERIA_NOT_MESSAGE) {
1564 if (matcherprop_string_match(matcher, buf,
1565 context_str[CONTEXT_BODY_LINE])) {
1566 matcher->result = FALSE;
1567 matcher->done = TRUE;
1568 } else
1569 matcher->result = TRUE;
1570 /* else, just one line has to match */
1571 } else if (matcherprop_criteria_body(matcher) ||
1572 matcherprop_criteria_message(matcher)) {
1573 if (matcherprop_string_match(matcher, buf,
1574 context_str[CONTEXT_BODY_LINE])) {
1575 matcher->result = TRUE;
1576 matcher->done = TRUE;
1580 /* if the matchers are OR'ed and the rule matched,
1581 * no need to check the others. */
1582 if (matcher->result && matcher->done) {
1583 if (!matchers->bool_and) {
1584 fclose(outfp);
1585 return TRUE;
1591 fclose(outfp);
1592 return FALSE;
1595 static gboolean match_content_cb(const gchar *buf, gpointer data)
1597 MatcherList *matchers = (MatcherList *)data;
1598 gboolean all_done = TRUE;
1599 GSList *l;
1601 for (l = matchers->matchers ; l != NULL ; l = g_slist_next(l)) {
1602 MatcherProp *matcher = (MatcherProp *) l->data;
1604 if (matcher->done)
1605 continue;
1607 /* if the criteria is ~body_part or ~message, ZERO lines
1608 * must match for the rule to match.
1610 if (matcher->criteria == MATCHCRITERIA_NOT_BODY_PART ||
1611 matcher->criteria == MATCHCRITERIA_NOT_MESSAGE) {
1612 if (matcherprop_string_match(matcher, buf,
1613 context_str[CONTEXT_BODY_LINE])) {
1614 matcher->result = FALSE;
1615 matcher->done = TRUE;
1616 } else
1617 matcher->result = TRUE;
1618 /* else, just one line has to match */
1619 } else if (matcherprop_criteria_body(matcher) ||
1620 matcherprop_criteria_message(matcher)) {
1621 if (matcherprop_string_match(matcher, buf,
1622 context_str[CONTEXT_BODY_LINE])) {
1623 matcher->result = TRUE;
1624 matcher->done = TRUE;
1628 /* if the matchers are OR'ed and the rule matched,
1629 * no need to check the others. */
1630 if (matcher->result && matcher->done) {
1631 if (!matchers->bool_and) {
1632 return TRUE;
1636 if (!matcher->done)
1637 all_done = FALSE;
1639 return all_done;
1642 static gboolean matcherlist_match_text_content(MatcherList *matchers, MimeInfo *partinfo)
1644 if (partinfo->type != MIMETYPE_TEXT)
1645 return FALSE;
1647 return procmime_scan_text_content(partinfo, match_content_cb, matchers);
1651 *\brief Check if a line in a message file's body matches
1652 * the criteria
1654 *\param matchers List of conditions
1655 *\param fp Message file
1657 *\return gboolean TRUE if succesful match
1659 static gboolean matcherlist_match_body(MatcherList *matchers, gboolean body_only, MsgInfo *info)
1661 MimeInfo *mimeinfo = NULL;
1662 MimeInfo *partinfo = NULL;
1663 gboolean first_text_found = FALSE;
1665 cm_return_val_if_fail(info != NULL, FALSE);
1667 mimeinfo = procmime_scan_message(info);
1669 /* Skip headers */
1670 partinfo = procmime_mimeinfo_next(mimeinfo);
1672 for (; partinfo != NULL; partinfo = procmime_mimeinfo_next(partinfo)) {
1674 if (partinfo->type != MIMETYPE_TEXT && body_only)
1675 continue;
1677 if (partinfo->type == MIMETYPE_TEXT) {
1678 first_text_found = TRUE;
1679 if (matcherlist_match_text_content(matchers, partinfo)) {
1680 procmime_mimeinfo_free_all(mimeinfo);
1681 return TRUE;
1683 } else if (matcherlist_match_binary_content(matchers, partinfo)) {
1684 procmime_mimeinfo_free_all(mimeinfo);
1685 return TRUE;
1688 if (body_only && first_text_found)
1689 break;
1691 procmime_mimeinfo_free_all(mimeinfo);
1693 return FALSE;
1697 *\brief Check if a message file matches criteria
1699 *\param matchers Criteria
1700 *\param info Message info
1701 *\param result Default result
1703 *\return gboolean TRUE if matched
1705 static gboolean matcherlist_match_file(MatcherList *matchers, MsgInfo *info,
1706 gboolean result)
1708 gboolean read_headers;
1709 gboolean read_body;
1710 gboolean body_only;
1711 GSList *l;
1712 FILE *fp;
1713 gchar *file;
1715 /* file need to be read ? */
1717 read_headers = FALSE;
1718 read_body = FALSE;
1719 body_only = TRUE;
1720 for (l = matchers->matchers ; l != NULL ; l = g_slist_next(l)) {
1721 MatcherProp *matcher = (MatcherProp *) l->data;
1723 if (matcherprop_criteria_headers(matcher))
1724 read_headers = TRUE;
1725 if (matcherprop_criteria_body(matcher))
1726 read_body = TRUE;
1727 if (matcherprop_criteria_message(matcher)) {
1728 read_headers = TRUE;
1729 read_body = TRUE;
1730 body_only = FALSE;
1732 matcher->result = FALSE;
1733 matcher->done = FALSE;
1736 if (!read_headers && !read_body)
1737 return result;
1739 file = procmsg_get_message_file_full(info, read_headers, read_body);
1740 if (file == NULL)
1741 return FALSE;
1743 if ((fp = g_fopen(file, "rb")) == NULL) {
1744 FILE_OP_ERROR(file, "fopen");
1745 g_free(file);
1746 return result;
1749 /* read the headers */
1751 if (read_headers) {
1752 if (matcherlist_match_headers(matchers, fp))
1753 read_body = FALSE;
1754 } else {
1755 matcherlist_skip_headers(fp);
1758 /* read the body */
1759 if (read_body) {
1760 matcherlist_match_body(matchers, body_only, info);
1763 for (l = matchers->matchers; l != NULL; l = g_slist_next(l)) {
1764 MatcherProp *matcher = (MatcherProp *) l->data;
1766 if (matcherprop_criteria_headers(matcher) ||
1767 matcherprop_criteria_body(matcher) ||
1768 matcherprop_criteria_message(matcher)) {
1769 if (matcher->result) {
1770 if (!matchers->bool_and) {
1771 result = TRUE;
1772 break;
1775 else {
1776 if (matchers->bool_and) {
1777 result = FALSE;
1778 break;
1784 g_free(file);
1786 fclose(fp);
1788 return result;
1792 *\brief Test list of conditions on a message.
1794 *\param matchers List of conditions
1795 *\param info Message info
1797 *\return gboolean TRUE if matched
1799 gboolean matcherlist_match(MatcherList *matchers, MsgInfo *info)
1801 GSList *l;
1802 gboolean result;
1804 if (!matchers)
1805 return FALSE;
1807 if (matchers->bool_and)
1808 result = TRUE;
1809 else
1810 result = FALSE;
1812 /* test the cached elements */
1814 for (l = matchers->matchers; l != NULL ;l = g_slist_next(l)) {
1815 MatcherProp *matcher = (MatcherProp *) l->data;
1817 if (debug_filtering_session) {
1818 gchar *buf = matcherprop_to_string(matcher);
1819 log_print(LOG_DEBUG_FILTERING, _("checking if message matches [ %s ]\n"), buf);
1820 g_free(buf);
1823 switch(matcher->criteria) {
1824 case MATCHCRITERIA_ALL:
1825 case MATCHCRITERIA_UNREAD:
1826 case MATCHCRITERIA_NOT_UNREAD:
1827 case MATCHCRITERIA_NEW:
1828 case MATCHCRITERIA_NOT_NEW:
1829 case MATCHCRITERIA_MARKED:
1830 case MATCHCRITERIA_NOT_MARKED:
1831 case MATCHCRITERIA_DELETED:
1832 case MATCHCRITERIA_NOT_DELETED:
1833 case MATCHCRITERIA_REPLIED:
1834 case MATCHCRITERIA_NOT_REPLIED:
1835 case MATCHCRITERIA_FORWARDED:
1836 case MATCHCRITERIA_NOT_FORWARDED:
1837 case MATCHCRITERIA_LOCKED:
1838 case MATCHCRITERIA_NOT_LOCKED:
1839 case MATCHCRITERIA_SPAM:
1840 case MATCHCRITERIA_NOT_SPAM:
1841 case MATCHCRITERIA_HAS_ATTACHMENT:
1842 case MATCHCRITERIA_HAS_NO_ATTACHMENT:
1843 case MATCHCRITERIA_SIGNED:
1844 case MATCHCRITERIA_NOT_SIGNED:
1845 case MATCHCRITERIA_COLORLABEL:
1846 case MATCHCRITERIA_NOT_COLORLABEL:
1847 case MATCHCRITERIA_IGNORE_THREAD:
1848 case MATCHCRITERIA_NOT_IGNORE_THREAD:
1849 case MATCHCRITERIA_WATCH_THREAD:
1850 case MATCHCRITERIA_NOT_WATCH_THREAD:
1851 case MATCHCRITERIA_SUBJECT:
1852 case MATCHCRITERIA_NOT_SUBJECT:
1853 case MATCHCRITERIA_FROM:
1854 case MATCHCRITERIA_NOT_FROM:
1855 case MATCHCRITERIA_TO:
1856 case MATCHCRITERIA_NOT_TO:
1857 case MATCHCRITERIA_CC:
1858 case MATCHCRITERIA_NOT_CC:
1859 case MATCHCRITERIA_TO_OR_CC:
1860 case MATCHCRITERIA_NOT_TO_AND_NOT_CC:
1861 case MATCHCRITERIA_TAG:
1862 case MATCHCRITERIA_NOT_TAG:
1863 case MATCHCRITERIA_TAGGED:
1864 case MATCHCRITERIA_NOT_TAGGED:
1865 case MATCHCRITERIA_AGE_GREATER:
1866 case MATCHCRITERIA_AGE_LOWER:
1867 case MATCHCRITERIA_AGE_GREATER_HOURS:
1868 case MATCHCRITERIA_AGE_LOWER_HOURS:
1869 case MATCHCRITERIA_NEWSGROUPS:
1870 case MATCHCRITERIA_NOT_NEWSGROUPS:
1871 case MATCHCRITERIA_INREPLYTO:
1872 case MATCHCRITERIA_NOT_INREPLYTO:
1873 case MATCHCRITERIA_REFERENCES:
1874 case MATCHCRITERIA_NOT_REFERENCES:
1875 case MATCHCRITERIA_SCORE_GREATER:
1876 case MATCHCRITERIA_SCORE_LOWER:
1877 case MATCHCRITERIA_SCORE_EQUAL:
1878 case MATCHCRITERIA_SIZE_GREATER:
1879 case MATCHCRITERIA_SIZE_SMALLER:
1880 case MATCHCRITERIA_SIZE_EQUAL:
1881 case MATCHCRITERIA_TEST:
1882 case MATCHCRITERIA_NOT_TEST:
1883 case MATCHCRITERIA_PARTIAL:
1884 case MATCHCRITERIA_NOT_PARTIAL:
1885 if (matcherprop_match(matcher, info)) {
1886 if (!matchers->bool_and) {
1887 if (debug_filtering_session)
1888 log_status_ok(LOG_DEBUG_FILTERING, _("message matches\n"));
1889 return TRUE;
1892 else {
1893 if (matchers->bool_and) {
1894 if (debug_filtering_session)
1895 log_status_nok(LOG_DEBUG_FILTERING, _("message does not match\n"));
1896 return FALSE;
1902 /* test the condition on the file */
1904 if (matcherlist_match_file(matchers, info, result)) {
1905 if (!matchers->bool_and) {
1906 if (debug_filtering_session)
1907 log_status_ok(LOG_DEBUG_FILTERING, _("message matches\n"));
1908 return TRUE;
1910 } else {
1911 if (matchers->bool_and) {
1912 if (debug_filtering_session)
1913 log_status_nok(LOG_DEBUG_FILTERING, _("message does not match\n"));
1914 return FALSE;
1918 if (debug_filtering_session) {
1919 if (result)
1920 log_status_ok(LOG_DEBUG_FILTERING, _("message matches\n"));
1921 else
1922 log_status_nok(LOG_DEBUG_FILTERING, _("message does not match\n"));
1924 return result;
1928 static gint quote_filter_str(gchar * result, guint size,
1929 const gchar * path)
1931 const gchar * p;
1932 gchar * result_p;
1933 guint remaining;
1935 result_p = result;
1936 remaining = size;
1938 for(p = path ; * p != '\0' ; p ++) {
1940 if ((* p != '\"') && (* p != '\\')) {
1941 if (remaining > 0) {
1942 * result_p = * p;
1943 result_p ++;
1944 remaining --;
1946 else {
1947 result[size - 1] = '\0';
1948 return -1;
1951 else {
1952 if (remaining >= 2) {
1953 * result_p = '\\';
1954 result_p ++;
1955 * result_p = * p;
1956 result_p ++;
1957 remaining -= 2;
1959 else {
1960 result[size - 1] = '\0';
1961 return -1;
1965 if (remaining > 0) {
1966 * result_p = '\0';
1968 else {
1969 result[size - 1] = '\0';
1970 return -1;
1973 return 0;
1977 gchar * matcher_quote_str(const gchar * src)
1979 gchar * res;
1980 gint len;
1982 len = strlen(src) * 2 + 1;
1983 res = g_malloc(len);
1984 quote_filter_str(res, len, src);
1986 return res;
1990 *\brief Convert a matcher structure to a string
1992 *\param matcher Matcher structure
1994 *\return gchar * Newly allocated string
1996 gchar *matcherprop_to_string(MatcherProp *matcher)
1998 gchar *matcher_str = NULL;
1999 const gchar *criteria_str;
2000 const gchar *matchtype_str;
2001 int i;
2002 gchar * quoted_expr;
2003 gchar * quoted_header;
2005 criteria_str = NULL;
2006 for (i = 0; i < (int) (sizeof(matchparser_tab) / sizeof(MatchParser)); i++) {
2007 if (matchparser_tab[i].id == matcher->criteria)
2008 criteria_str = matchparser_tab[i].str;
2010 if (criteria_str == NULL)
2011 return NULL;
2013 switch (matcher->criteria) {
2014 case MATCHCRITERIA_AGE_GREATER:
2015 case MATCHCRITERIA_AGE_LOWER:
2016 case MATCHCRITERIA_AGE_GREATER_HOURS:
2017 case MATCHCRITERIA_AGE_LOWER_HOURS:
2018 case MATCHCRITERIA_SCORE_GREATER:
2019 case MATCHCRITERIA_SCORE_LOWER:
2020 case MATCHCRITERIA_SCORE_EQUAL:
2021 case MATCHCRITERIA_SIZE_GREATER:
2022 case MATCHCRITERIA_SIZE_SMALLER:
2023 case MATCHCRITERIA_SIZE_EQUAL:
2024 case MATCHCRITERIA_COLORLABEL:
2025 case MATCHCRITERIA_NOT_COLORLABEL:
2026 return g_strdup_printf("%s %i", criteria_str, matcher->value);
2027 case MATCHCRITERIA_ALL:
2028 case MATCHCRITERIA_UNREAD:
2029 case MATCHCRITERIA_NOT_UNREAD:
2030 case MATCHCRITERIA_NEW:
2031 case MATCHCRITERIA_NOT_NEW:
2032 case MATCHCRITERIA_MARKED:
2033 case MATCHCRITERIA_NOT_MARKED:
2034 case MATCHCRITERIA_DELETED:
2035 case MATCHCRITERIA_NOT_DELETED:
2036 case MATCHCRITERIA_REPLIED:
2037 case MATCHCRITERIA_NOT_REPLIED:
2038 case MATCHCRITERIA_FORWARDED:
2039 case MATCHCRITERIA_NOT_FORWARDED:
2040 case MATCHCRITERIA_LOCKED:
2041 case MATCHCRITERIA_NOT_LOCKED:
2042 case MATCHCRITERIA_SPAM:
2043 case MATCHCRITERIA_NOT_SPAM:
2044 case MATCHCRITERIA_HAS_ATTACHMENT:
2045 case MATCHCRITERIA_HAS_NO_ATTACHMENT:
2046 case MATCHCRITERIA_SIGNED:
2047 case MATCHCRITERIA_NOT_SIGNED:
2048 case MATCHCRITERIA_PARTIAL:
2049 case MATCHCRITERIA_NOT_PARTIAL:
2050 case MATCHCRITERIA_IGNORE_THREAD:
2051 case MATCHCRITERIA_NOT_IGNORE_THREAD:
2052 case MATCHCRITERIA_WATCH_THREAD:
2053 case MATCHCRITERIA_NOT_WATCH_THREAD:
2054 case MATCHCRITERIA_TAGGED:
2055 case MATCHCRITERIA_NOT_TAGGED:
2056 return g_strdup(criteria_str);
2057 case MATCHCRITERIA_TEST:
2058 case MATCHCRITERIA_NOT_TEST:
2059 quoted_expr = matcher_quote_str(matcher->expr);
2060 matcher_str = g_strdup_printf("%s \"%s\"",
2061 criteria_str, quoted_expr);
2062 g_free(quoted_expr);
2063 return matcher_str;
2064 case MATCHCRITERIA_FOUND_IN_ADDRESSBOOK:
2065 case MATCHCRITERIA_NOT_FOUND_IN_ADDRESSBOOK:
2066 quoted_header = matcher_quote_str(matcher->header);
2067 quoted_expr = matcher_quote_str(matcher->expr);
2068 matcher_str = g_strdup_printf("%s \"%s\" in \"%s\"",
2069 criteria_str, quoted_header, quoted_expr);
2070 g_free(quoted_header);
2071 g_free(quoted_expr);
2072 return matcher_str;
2075 matchtype_str = NULL;
2076 for (i = 0; i < sizeof matchparser_tab / sizeof matchparser_tab[0]; i++) {
2077 if (matchparser_tab[i].id == matcher->matchtype)
2078 matchtype_str = matchparser_tab[i].str;
2081 if (matchtype_str == NULL)
2082 return NULL;
2084 switch (matcher->matchtype) {
2085 case MATCHTYPE_MATCH:
2086 case MATCHTYPE_MATCHCASE:
2087 case MATCHTYPE_REGEXP:
2088 case MATCHTYPE_REGEXPCASE:
2089 quoted_expr = matcher_quote_str(matcher->expr);
2090 if (matcher->header) {
2091 quoted_header = matcher_quote_str(matcher->header);
2092 matcher_str = g_strdup_printf
2093 ("%s \"%s\" %s \"%s\"",
2094 criteria_str, quoted_header,
2095 matchtype_str, quoted_expr);
2096 g_free(quoted_header);
2098 else
2099 matcher_str = g_strdup_printf
2100 ("%s %s \"%s\"", criteria_str,
2101 matchtype_str, quoted_expr);
2102 g_free(quoted_expr);
2103 break;
2106 return matcher_str;
2110 *\brief Convert a list of conditions to a string
2112 *\param matchers List of conditions
2114 *\return gchar * Newly allocated string
2116 gchar *matcherlist_to_string(const MatcherList *matchers)
2118 gint count;
2119 gchar **vstr;
2120 GSList *l;
2121 gchar **cur_str;
2122 gchar *result = NULL;
2124 count = g_slist_length(matchers->matchers);
2125 vstr = g_new(gchar *, count + 1);
2127 for (l = matchers->matchers, cur_str = vstr; l != NULL;
2128 l = g_slist_next(l), cur_str ++) {
2129 *cur_str = matcherprop_to_string((MatcherProp *) l->data);
2130 if (*cur_str == NULL)
2131 break;
2133 *cur_str = NULL;
2135 if (matchers->bool_and)
2136 result = g_strjoinv(" & ", vstr);
2137 else
2138 result = g_strjoinv(" | ", vstr);
2140 for (cur_str = vstr ; *cur_str != NULL ; cur_str ++)
2141 g_free(*cur_str);
2142 g_free(vstr);
2144 return result;
2148 #define STRLEN_ZERO(s) ((s) ? strlen(s) : 0)
2149 #define STRLEN_DEFAULT(s,d) ((s) ? strlen(s) : STRLEN_ZERO(d))
2151 static void add_str_default(gchar ** dest,
2152 const gchar * s, const gchar * d)
2154 gchar quoted_str[4096];
2155 const gchar * str;
2157 if (s != NULL)
2158 str = s;
2159 else
2160 str = d;
2162 quote_cmd_argument(quoted_str, sizeof(quoted_str), str);
2163 strcpy(* dest, quoted_str);
2165 (* dest) += strlen(* dest);
2168 /* matching_build_command() - preferably cmd should be unescaped */
2170 *\brief Build the command-line to execute
2172 *\param cmd String with command-line specifiers
2173 *\param info Message info to use for command
2175 *\return gchar * Newly allocated string
2177 gchar *matching_build_command(const gchar *cmd, MsgInfo *info)
2179 const gchar *s = cmd;
2180 gchar *filename = NULL;
2181 gchar *processed_cmd;
2182 gchar *p;
2183 gint size;
2185 const gchar *const no_subject = _("(none)") ;
2186 const gchar *const no_from = _("(none)") ;
2187 const gchar *const no_to = _("(none)") ;
2188 const gchar *const no_cc = _("(none)") ;
2189 const gchar *const no_date = _("(none)") ;
2190 const gchar *const no_msgid = _("(none)") ;
2191 const gchar *const no_newsgroups = _("(none)") ;
2192 const gchar *const no_references = _("(none)") ;
2194 size = STRLEN_ZERO(cmd) + 1;
2195 while (*s != '\0') {
2196 if (*s == '%') {
2197 s++;
2198 switch (*s) {
2199 case '%':
2200 size -= 1;
2201 break;
2202 case 's': /* subject */
2203 size += STRLEN_DEFAULT(info->subject, no_subject) - 2;
2204 break;
2205 case 'f': /* from */
2206 size += STRLEN_DEFAULT(info->from, no_from) - 2;
2207 break;
2208 case 't': /* to */
2209 size += STRLEN_DEFAULT(info->to, no_to) - 2;
2210 break;
2211 case 'c': /* cc */
2212 size += STRLEN_DEFAULT(info->cc, no_cc) - 2;
2213 break;
2214 case 'd': /* date */
2215 size += STRLEN_DEFAULT(info->date, no_date) - 2;
2216 break;
2217 case 'i': /* message-id */
2218 size += STRLEN_DEFAULT(info->msgid, no_msgid) - 2;
2219 break;
2220 case 'n': /* newsgroups */
2221 size += STRLEN_DEFAULT(info->newsgroups, no_newsgroups) - 2;
2222 break;
2223 case 'r': /* references */
2224 /* FIXME: using the inreplyto header for reference */
2225 size += STRLEN_DEFAULT(info->inreplyto, no_references) - 2;
2226 break;
2227 case 'F': /* file */
2228 if (filename == NULL)
2229 filename = folder_item_fetch_msg(info->folder, info->msgnum);
2231 if (filename == NULL) {
2232 g_warning("filename is not set");
2233 return NULL;
2235 else {
2236 size += strlen(filename) - 2;
2238 break;
2240 s++;
2242 else s++;
2245 /* as the string can be quoted, we double the result */
2246 size *= 2;
2248 processed_cmd = g_new0(gchar, size);
2249 s = cmd;
2250 p = processed_cmd;
2252 while (*s != '\0') {
2253 if (*s == '%') {
2254 s++;
2255 switch (*s) {
2256 case '%':
2257 *p = '%';
2258 p++;
2259 break;
2260 case 's': /* subject */
2261 add_str_default(&p, info->subject,
2262 no_subject);
2263 break;
2264 case 'f': /* from */
2265 add_str_default(&p, info->from,
2266 no_from);
2267 break;
2268 case 't': /* to */
2269 add_str_default(&p, info->to,
2270 no_to);
2271 break;
2272 case 'c': /* cc */
2273 add_str_default(&p, info->cc,
2274 no_cc);
2275 break;
2276 case 'd': /* date */
2277 add_str_default(&p, info->date,
2278 no_date);
2279 break;
2280 case 'i': /* message-id */
2281 add_str_default(&p, info->msgid,
2282 no_msgid);
2283 break;
2284 case 'n': /* newsgroups */
2285 add_str_default(&p, info->newsgroups,
2286 no_newsgroups);
2287 break;
2288 case 'r': /* references */
2289 /* FIXME: using the inreplyto header for references */
2290 add_str_default(&p, info->inreplyto, no_references);
2291 break;
2292 case 'F': /* file */
2293 if (filename != NULL)
2294 add_str_default(&p, filename, NULL);
2295 break;
2296 default:
2297 *p = '%';
2298 p++;
2299 *p = *s;
2300 p++;
2301 break;
2303 s++;
2305 else {
2306 *p = *s;
2307 p++;
2308 s++;
2311 g_free(filename);
2313 return processed_cmd;
2315 #undef STRLEN_DEFAULT
2316 #undef STRLEN_ZERO
2318 /* ************************************************************ */
2322 *\brief Write filtering list to file
2324 *\param fp File
2325 *\param prefs_filtering List of filtering conditions
2327 static int prefs_filtering_write(FILE *fp, GSList *prefs_filtering)
2329 GSList *cur = NULL;
2331 for (cur = prefs_filtering; cur != NULL; cur = cur->next) {
2332 gchar *filtering_str = NULL;
2333 gchar *tmp_name = NULL;
2334 FilteringProp *prop = NULL;
2336 if (NULL == (prop = (FilteringProp *) cur->data))
2337 continue;
2339 if (NULL == (filtering_str = filteringprop_to_string(prop)))
2340 continue;
2342 if (prop->enabled) {
2343 if (fputs("enabled ", fp) == EOF) {
2344 FILE_OP_ERROR("filtering config", "fputs");
2345 return -1;
2347 } else {
2348 if (fputs("disabled ", fp) == EOF) {
2349 FILE_OP_ERROR("filtering config", "fputs");
2350 return -1;
2354 if (fputs("rulename \"", fp) == EOF) {
2355 FILE_OP_ERROR("filtering config", "fputs");
2356 g_free(filtering_str);
2357 return -1;
2359 tmp_name = prop->name;
2360 while (tmp_name && *tmp_name != '\0') {
2361 if (*tmp_name != '"') {
2362 if (fputc(*tmp_name, fp) == EOF) {
2363 FILE_OP_ERROR("filtering config", "fputs || fputc");
2364 g_free(filtering_str);
2365 return -1;
2367 } else if (*tmp_name == '"') {
2368 if (fputc('\\', fp) == EOF ||
2369 fputc('"', fp) == EOF) {
2370 FILE_OP_ERROR("filtering config", "fputs || fputc");
2371 g_free(filtering_str);
2372 return -1;
2375 tmp_name ++;
2377 if (fputs("\" ", fp) == EOF) {
2378 FILE_OP_ERROR("filtering config", "fputs");
2379 g_free(filtering_str);
2380 return -1;
2383 if (prop->account_id != 0) {
2384 gchar *tmp = NULL;
2386 tmp = g_strdup_printf("account %d ", prop->account_id);
2387 if (fputs(tmp, fp) == EOF) {
2388 FILE_OP_ERROR("filtering config", "fputs");
2389 g_free(tmp);
2390 return -1;
2392 g_free(tmp);
2395 if(fputs(filtering_str, fp) == EOF ||
2396 fputc('\n', fp) == EOF) {
2397 FILE_OP_ERROR("filtering config", "fputs || fputc");
2398 g_free(filtering_str);
2399 return -1;
2401 g_free(filtering_str);
2404 return 0;
2407 typedef struct _NodeLoopData {
2408 FILE *fp;
2409 gboolean error;
2410 } NodeLoopData;
2413 *\brief Write matchers from a folder item
2415 *\param node Node with folder info
2416 *\param data File pointer
2418 *\return gboolean FALSE
2420 static gboolean prefs_matcher_write_func(GNode *node, gpointer d)
2422 FolderItem *item;
2423 NodeLoopData *data = (NodeLoopData *)d;
2424 gchar *id;
2425 GSList *prefs_filtering;
2427 item = node->data;
2428 /* prevent warning */
2429 if (item->path == NULL)
2430 return FALSE;
2431 id = folder_item_get_identifier(item);
2432 if (id == NULL)
2433 return FALSE;
2434 prefs_filtering = item->prefs->processing;
2436 if (prefs_filtering != NULL) {
2437 if (fprintf(data->fp, "[%s]\n", id) < 0) {
2438 data->error = TRUE;
2439 goto fail;
2441 if (prefs_filtering_write(data->fp, prefs_filtering) < 0) {
2442 data->error = TRUE;
2443 goto fail;
2445 if (fputc('\n', data->fp) == EOF) {
2446 data->error = TRUE;
2447 goto fail;
2450 fail:
2451 g_free(id);
2453 return FALSE;
2457 *\brief Save matchers from folder items
2459 *\param fp File
2461 static int prefs_matcher_save(FILE *fp)
2463 GList *cur;
2464 NodeLoopData data;
2466 data.fp = fp;
2467 data.error = FALSE;
2469 for (cur = folder_get_list() ; cur != NULL ; cur = g_list_next(cur)) {
2470 Folder *folder;
2472 folder = (Folder *) cur->data;
2473 g_node_traverse(folder->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1,
2474 prefs_matcher_write_func, &data);
2477 if (data.error == TRUE)
2478 return -1;
2480 /* pre global rules */
2481 if (fprintf(fp, "[preglobal]\n") < 0 ||
2482 prefs_filtering_write(fp, pre_global_processing) < 0 ||
2483 fputc('\n', fp) == EOF)
2484 return -1;
2486 /* post global rules */
2487 if (fprintf(fp, "[postglobal]\n") < 0 ||
2488 prefs_filtering_write(fp, post_global_processing) < 0 ||
2489 fputc('\n', fp) == EOF)
2490 return -1;
2492 /* filtering rules */
2493 if (fprintf(fp, "[filtering]\n") < 0 ||
2494 prefs_filtering_write(fp, filtering_rules) < 0 ||
2495 fputc('\n', fp) == EOF)
2496 return -1;
2498 return 0;
2502 *\brief Write filtering / matcher configuration file
2504 void prefs_matcher_write_config(void)
2506 gchar *rcpath;
2507 PrefFile *pfile;
2509 debug_print("Writing matcher configuration...\n");
2511 rcpath = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
2512 MATCHER_RC, NULL);
2514 if ((pfile = prefs_write_open(rcpath)) == NULL) {
2515 g_warning("failed to write configuration to file\n");
2516 g_free(rcpath);
2517 return;
2520 g_free(rcpath);
2522 if (prefs_matcher_save(pfile->fp) < 0) {
2523 g_warning("failed to write configuration to file\n");
2524 prefs_file_close_revert(pfile);
2525 } else if (prefs_file_close(pfile) < 0) {
2526 g_warning("failed to save configuration to file\n");
2530 /* ******************************************************************* */
2532 static void matcher_add_rulenames(const gchar *rcpath)
2534 gchar *newpath = g_strconcat(rcpath, ".new", NULL);
2535 FILE *src = g_fopen(rcpath, "rb");
2536 FILE *dst = g_fopen(newpath, "wb");
2537 gchar buf[BUFFSIZE];
2538 int r;
2540 if (src == NULL) {
2541 perror("fopen");
2542 if (dst)
2543 fclose(dst);
2544 g_free(newpath);
2545 return;
2547 if (dst == NULL) {
2548 perror("fopen");
2549 if (src)
2550 fclose(src);
2551 g_free(newpath);
2552 return;
2555 while (fgets (buf, sizeof(buf), src) != NULL) {
2556 if (strlen(buf) > 2 && buf[0] != '['
2557 && strncmp(buf, "rulename \"", 10)
2558 && strncmp(buf, "enabled rulename \"", 18)
2559 && strncmp(buf, "disabled rulename \"", 18)) {
2560 r = fwrite("enabled rulename \"\" ",
2561 strlen("enabled rulename \"\" "), 1, dst);
2562 if (r != 1) {
2563 g_message("cannot fwrite rulename\n");
2566 r = fwrite(buf, strlen(buf), 1, dst);
2567 if (r != 1) {
2568 g_message("cannot fwrite rule\n");
2571 fclose(dst);
2572 fclose(src);
2573 move_file(newpath, rcpath, TRUE);
2574 g_free(newpath);
2578 *\brief Read matcher configuration
2580 void prefs_matcher_read_config(void)
2582 gchar *rcpath;
2583 gchar *rc_old_format;
2584 FILE *f;
2586 create_matchparser_hashtab();
2587 prefs_filtering_clear();
2589 rcpath = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, MATCHER_RC, NULL);
2590 rc_old_format = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, MATCHER_RC,
2591 ".pre_names", NULL);
2593 if (!is_file_exist(rc_old_format) && is_file_exist(rcpath)) {
2594 /* backup file with no rules names, in case
2595 * anything goes wrong */
2596 copy_file(rcpath, rc_old_format, FALSE);
2597 /* now hack the file in order to have it to the new format */
2598 matcher_add_rulenames(rcpath);
2601 g_free(rc_old_format);
2603 f = g_fopen(rcpath, "rb");
2604 g_free(rcpath);
2606 if (f != NULL) {
2607 matcher_parser_start_parsing(f);
2608 fclose(matcher_parserin);
2610 else {
2611 /* previous version compatibility */
2613 /* g_print("reading filtering\n"); */
2614 rcpath = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
2615 FILTERING_RC, NULL);
2616 f = g_fopen(rcpath, "rb");
2617 g_free(rcpath);
2619 if (f != NULL) {
2620 matcher_parser_start_parsing(f);
2621 fclose(matcher_parserin);
2624 /* g_print("reading scoring\n"); */
2625 rcpath = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
2626 SCORING_RC, NULL);
2627 f = g_fopen(rcpath, "rb");
2628 g_free(rcpath);
2630 if (f != NULL) {
2631 matcher_parser_start_parsing(f);
2632 fclose(matcher_parserin);