726fca4521eddd17c7a09c99684d8f6647422f6c
[claws.git] / src / plugins / bogofilter / bogofilter.c
1 /*
2  * Claws Mail -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2012 Colin Leroy <colin@colino.net> and 
4  * the Claws Mail team
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program. If not, see <http://www.gnu.org/licenses/>.
18  * 
19  */
20
21 #ifdef HAVE_CONFIG_H
22 #  include "config.h"
23 #include "claws-features.h"
24 #endif
25
26 #include "defs.h"
27
28 #include <sys/types.h>
29 #include <sys/wait.h>
30 #include <errno.h>
31
32 #include <glib.h>
33 #include <glib/gi18n.h>
34
35 #if HAVE_LOCALE_H
36 #  include <locale.h>
37 #endif
38
39 #include "common/claws.h"
40 #include "common/version.h"
41 #include "plugin.h"
42 #include "common/utils.h"
43 #include "hooks.h"
44 #include "procmsg.h"
45 #include "folder.h"
46 #include "prefs.h"
47 #include "prefs_gtk.h"
48
49 #include "bogofilter.h"
50 #include "inc.h"
51 #include "log.h"
52 #include "prefs_common.h"
53 #include "alertpanel.h"
54 #include "addr_compl.h"
55
56 #ifdef HAVE_SYSEXITS_H
57 #include <sysexits.h>
58 #endif
59 #ifdef HAVE_ERRNO_H
60 #include <errno.h>
61 #endif
62 #ifdef HAVE_SYS_ERRNO_H
63 #include <sys/errno.h>
64 #endif
65 #ifdef HAVE_TIME_H
66 #include <time.h>
67 #endif
68 #ifdef HAVE_SYS_TIME_H
69 #include <sys/time.h>
70 #endif
71 #ifdef HAVE_SIGNAL_H
72 #include <signal.h>
73 #endif
74 #ifdef HAVE_PWD_H
75 #include <pwd.h>
76 #endif
77 #ifdef USE_PTHREAD
78 #include <pthread.h>
79 #endif
80
81 #define PLUGIN_NAME (_("Bogofilter"))
82
83 static guint hook_id = -1;
84 static MessageCallback message_callback;
85
86 static BogofilterConfig config;
87
88 static PrefParam param[] = {
89         {"process_emails", "TRUE", &config.process_emails, P_BOOL,
90          NULL, NULL, NULL},
91         {"receive_spam", "TRUE", &config.receive_spam, P_BOOL,
92          NULL, NULL, NULL},
93         {"save_folder", NULL, &config.save_folder, P_STRING,
94          NULL, NULL, NULL},
95         {"save_unsure", "FALSE", &config.save_unsure, P_BOOL,
96          NULL, NULL, NULL},
97         {"save_unsure_folder", NULL, &config.save_unsure_folder, P_STRING,
98          NULL, NULL, NULL},
99         {"max_size", "250", &config.max_size, P_INT,
100          NULL, NULL, NULL},
101         {"bogopath", "bogofilter", &config.bogopath, P_STRING,
102          NULL, NULL, NULL},
103         {"insert_header", "FALSE", &config.insert_header, P_BOOL,
104          NULL, NULL, NULL},
105         {"whitelist_ab", "FALSE", &config.whitelist_ab, P_BOOL,
106          NULL, NULL, NULL},
107         {"whitelist_ab_folder", N_("Any"), &config.whitelist_ab_folder, P_STRING,
108          NULL, NULL, NULL},
109         {"learn_from_whitelist", "FALSE", &config.learn_from_whitelist, P_BOOL,
110          NULL, NULL, NULL},
111         {"mark_as_read", "TRUE", &config.mark_as_read, P_BOOL,
112          NULL, NULL, NULL},
113
114         {NULL, NULL, NULL, P_OTHER, NULL, NULL, NULL}
115 };
116
117 /*
118  * Helper function for spawn_with_input() - write an entire
119  * string to a fd.
120  */
121 static gboolean
122 write_all (int         fd,
123            const char *buf,
124            gsize       to_write)
125 {
126   while (to_write > 0)
127     {
128       gssize count = write (fd, buf, to_write);
129       if (count < 0)
130         {
131           if (errno != EINTR)
132             return FALSE;
133         }
134       else
135         {
136           to_write -= count;
137           buf += count;
138         }
139     }
140
141   return TRUE;
142 }
143
144 typedef struct _BogoFilterData {
145         MailFilteringData *mail_filtering_data;
146         gchar **bogo_args;
147         GSList *msglist;
148         GSList *new_hams;
149         GSList *new_unsure;
150         GSList *new_spams;
151         GSList *whitelisted_new_spams;
152         gboolean done;
153         int status;
154         gboolean in_thread;
155 } BogoFilterData;
156
157 static BogoFilterData *to_filter_data = NULL;
158 #ifdef USE_PTHREAD
159 static gboolean filter_th_done = FALSE;
160 static pthread_mutex_t list_mutex = PTHREAD_MUTEX_INITIALIZER;
161 static pthread_mutex_t wait_mutex = PTHREAD_MUTEX_INITIALIZER; 
162 static pthread_cond_t wait_cond = PTHREAD_COND_INITIALIZER; 
163 #endif
164
165 static gboolean found_in_addressbook(const gchar *address)
166 {
167         gchar *addr = NULL;
168         gboolean found = FALSE;
169         gint num_addr = 0;
170         
171         if (!address)
172                 return FALSE;
173         
174         addr = g_strdup(address);
175         extract_address(addr);
176         num_addr = complete_address(addr);
177         if (num_addr > 1) {
178                 /* skip first item (this is the search string itself) */
179                 int i = 1;
180                 for (; i < num_addr && !found; i++) {
181                         gchar *caddr = get_complete_address(i);
182                         extract_address(caddr);
183                         if (strcasecmp(caddr, addr) == 0)
184                                 found = TRUE;
185                         g_free(caddr);
186                 }
187         }
188         g_free(addr);
189         return found;
190 }
191
192 static void bogofilter_do_filter(BogoFilterData *data)
193 {
194         GPid bogo_pid;
195         gint bogo_stdin, bogo_stdout;
196         GError *error = NULL;
197         gboolean bogo_forked;
198         int status = 0;
199         MsgInfo *msginfo;
200         GSList *cur = NULL;
201         int total = 0, curnum = 1;
202         gchar *file = NULL;
203         gchar buf[BUFSIZ];
204
205         total = g_slist_length(data->msglist);
206
207         bogo_forked = g_spawn_async_with_pipes(
208                         NULL, data->bogo_args,NULL, G_SPAWN_SEARCH_PATH|G_SPAWN_DO_NOT_REAP_CHILD,
209                         NULL, NULL, &bogo_pid, &bogo_stdin,
210                         &bogo_stdout, NULL, &error);
211                 
212         if (bogo_forked == FALSE) {
213                 g_warning("%s\n", error ? error->message:"ERROR???");
214                 g_error_free(error);
215                 error = NULL;
216                 status = -1;
217         } else {
218         
219                 if (config.whitelist_ab) {
220                         gchar *ab_folderpath;
221
222                         if (*config.whitelist_ab_folder == '\0' ||
223                                 strcasecmp(config.whitelist_ab_folder, "Any") == 0) {
224                                 /* match the whole addressbook */
225                                 ab_folderpath = NULL;
226                         } else {
227                                 /* match the specific book/folder of the addressbook */
228                                 ab_folderpath = config.whitelist_ab_folder;
229                         }
230
231                         start_address_completion(ab_folderpath);
232                 }
233
234                 for (cur = data->msglist; cur; cur = cur->next) {
235                         gboolean whitelisted = FALSE;
236                         msginfo = (MsgInfo *)cur->data;
237                         debug_print("Filtering message %d (%d/%d)\n", msginfo->msgnum, curnum, total);
238
239                         if (message_callback != NULL)
240                                 message_callback(NULL, total, curnum++, data->in_thread);
241
242                         if (config.whitelist_ab && msginfo->from && 
243                             found_in_addressbook(msginfo->from))
244                                 whitelisted = TRUE;
245
246                         /* can set flags (SCANNED, ATTACHMENT) but that's ok 
247                          * as GUI updates are hooked not direct */
248
249                         file = procmsg_get_message_file(msginfo);
250
251                         if (file) {
252                                 gchar *tmp = g_strdup_printf("%s\n",file);
253                                 /* send filename to bogofilter */
254                                 write_all(bogo_stdin, tmp, strlen(tmp));
255                                 g_free(tmp);
256                                 memset(buf, 0, sizeof(buf));
257                                 /* get the result */
258                                 if (read(bogo_stdout, buf, sizeof(buf)-1) < 0) {
259                                         g_warning("bogofilter short read\n");
260                                         debug_print("message %d is ham\n", msginfo->msgnum);
261                                         data->mail_filtering_data->unfiltered = g_slist_prepend(
262                                                 data->mail_filtering_data->unfiltered, msginfo);
263                                         data->new_hams = g_slist_prepend(data->new_hams, msginfo);
264                                 } else {
265                                         gchar **parts = NULL;
266                                         if (strchr(buf, '/')) {
267                                                 tmp = strrchr(buf, '/')+1;
268                                         } else {
269                                                 tmp = buf;
270                                         }
271                                         parts = g_strsplit(tmp, " ", 0);
272                                         debug_print("read %s\n", buf);
273                                         
274                                         /* note the result if the header if needed */
275                                         if (parts && parts[0] && parts[1] && parts[2] && 
276                                             FOLDER_TYPE(msginfo->folder->folder) == F_MH &&
277                                             config.insert_header) {
278                                                 gchar *tmpfile = get_tmp_file();
279                                                 FILE *input = g_fopen(file, "r");
280                                                 FILE *output = g_fopen(tmpfile, "w");
281                                                 if (strstr(parts[2], "\n"))
282                                                         *(strstr(parts[2], "\n")) = '\0';
283                                                 if (input && !output) 
284                                                         fclose (input);
285                                                 else if (!input && output)
286                                                         fclose (output);
287                                                 else {
288                                                         gchar tmpbuf[BUFFSIZE];
289                                                         gboolean err = FALSE;
290                                                         const gchar *bogosity = *parts[1] == 'S' ? "Spam":
291                                                                                  (*parts[1] == 'H' ? "Ham":"Unsure");
292                                                         gchar *tmpstr = g_strdup_printf(
293                                                                         "X-Bogosity: %s, spamicity=%s%s\n",
294                                                                         bogosity, parts[2],
295                                                                         whitelisted?" [whitelisted]":"");
296                                                         if (fwrite(tmpstr, 1, strlen(tmpstr), output) < strlen(tmpstr)) {
297                                                                 err = TRUE;
298                                                         } else {
299                                                                 while (fgets(tmpbuf, sizeof(buf), input)) {
300                                                                         if (fputs(tmpbuf, output) == EOF) {
301                                                                                 err = TRUE;
302                                                                                 break;
303                                                                         }
304                                                                 }
305                                                         }
306                                                         fclose(input);
307                                                         if (fclose(output) == EOF)
308                                                                 err = TRUE;
309                                                         if (!err)
310                                                                 move_file(tmpfile, file, TRUE);
311                                                         g_free(tmpstr);
312                                                 }
313                                                 g_free(tmpfile);
314                                         }
315
316                                         /* file the mail */
317                                         if (!whitelisted && parts && parts[0] && parts[1] && *parts[1] == 'S') {
318
319                                                 debug_print("message %d is spam\n", msginfo->msgnum);
320                                                 /* Spam will be filtered away */
321                                                 data->mail_filtering_data->filtered = g_slist_prepend(
322                                                         data->mail_filtering_data->filtered, msginfo);
323                                                 data->new_spams = g_slist_prepend(data->new_spams, msginfo);
324
325                                         } else if (whitelisted && parts && parts[0] && parts[1] && 
326                                                         (*parts[1] == 'S' || *parts[1] == 'U')) {
327
328                                                 debug_print("message %d is whitelisted %s\n", msginfo->msgnum,
329                                                         *parts[1] == 'S' ? "spam":"unsure");
330                                                 /* Whitelisted spam will *not* be filtered away, but continue
331                                                  * their trip through filtering as if it was ham. */
332                                                 data->mail_filtering_data->unfiltered = g_slist_prepend(
333                                                         data->mail_filtering_data->unfiltered, msginfo);
334                                                 /* But it gets put in a different list, so that we 
335                                                  * can still flag it and inform the user that it is
336                                                  * considered a spam (so that he can teach bogo that 
337                                                  * it was not). */
338                                                 data->whitelisted_new_spams = g_slist_prepend(data->whitelisted_new_spams, msginfo);
339
340                                         } else if (config.save_unsure && parts && parts[0] && parts[1] && *parts[1] == 'U') {
341                                                 
342                                                 debug_print("message %d is unsure\n", msginfo->msgnum);
343                                                 /* Spam will be filtered away */
344                                                 data->mail_filtering_data->filtered = g_slist_prepend(
345                                                         data->mail_filtering_data->filtered, msginfo);
346                                                 data->new_unsure = g_slist_prepend(data->new_unsure, msginfo);
347
348                                         } else {
349                                                 
350                                                 debug_print("message %d is ham\n", msginfo->msgnum);
351                                                 data->mail_filtering_data->unfiltered = g_slist_prepend(
352                                                         data->mail_filtering_data->unfiltered, msginfo);
353                                                 data->new_hams = g_slist_prepend(data->new_hams, msginfo);
354
355                                         }
356                                         g_strfreev(parts);
357                                 }
358                                 g_free(file);
359                         } else {
360                                 data->mail_filtering_data->unfiltered = g_slist_prepend(
361                                         data->mail_filtering_data->unfiltered, msginfo);
362                                 data->new_hams = g_slist_prepend(data->new_hams, msginfo);
363                         }
364                 }
365                 if (config.whitelist_ab)
366                         end_address_completion();
367         }
368         if (status != -1) {
369                 close(bogo_stdout);
370                 close(bogo_stdin);
371                 waitpid(bogo_pid, &status, 0);
372                 if (!WIFEXITED(status))
373                         status = -1;
374                 else
375                         status = WEXITSTATUS(status);
376         }
377
378         to_filter_data->status = status; 
379 }
380
381 #ifdef USE_PTHREAD
382 static void *bogofilter_filtering_thread(void *data) 
383 {
384         while (!filter_th_done) {
385                 pthread_mutex_lock(&list_mutex);
386                 if (to_filter_data == NULL || to_filter_data->done == TRUE) {
387                         pthread_mutex_unlock(&list_mutex);
388                         debug_print("thread is waiting for something to filter\n");
389                         pthread_mutex_lock(&wait_mutex);
390                         pthread_cond_wait(&wait_cond, &wait_mutex);
391                         pthread_mutex_unlock(&wait_mutex);
392                 } else {
393                         debug_print("thread awaken with something to filter\n");
394                         to_filter_data->done = FALSE;
395                         bogofilter_do_filter(to_filter_data);
396                         pthread_mutex_unlock(&list_mutex);
397                         to_filter_data->done = TRUE;
398                         usleep(100);
399                 }
400         }
401         return NULL;
402 }
403
404 static pthread_t filter_th = 0;
405
406 static void bogofilter_start_thread(void)
407 {
408         filter_th_done = FALSE;
409         if (filter_th != 0 || 1)
410                 return;
411         if (pthread_create(&filter_th, 0, 
412                         bogofilter_filtering_thread, 
413                         NULL) != 0) {
414                 filter_th = 0;
415                 return;
416         }
417         debug_print("thread created\n");
418 }
419
420 static void bogofilter_stop_thread(void)
421 {
422         void *res;
423         while (pthread_mutex_trylock(&list_mutex) != 0) {
424                 GTK_EVENTS_FLUSH();
425                 usleep(100);
426         }
427         if (filter_th != 0) {
428                 filter_th_done = TRUE;
429                 debug_print("waking thread up\n");
430                 pthread_mutex_lock(&wait_mutex);
431                 pthread_cond_broadcast(&wait_cond);
432                 pthread_mutex_unlock(&wait_mutex);
433                 pthread_join(filter_th, &res);
434                 filter_th = 0;
435         }
436         pthread_mutex_unlock(&list_mutex);
437         debug_print("thread done\n");
438 }
439 #endif
440
441 static gboolean mail_filtering_hook(gpointer source, gpointer data)
442 {
443         MailFilteringData *mail_filtering_data = (MailFilteringData *) source;
444         MsgInfo *msginfo = mail_filtering_data->msginfo;
445         GSList *msglist = mail_filtering_data->msglist;
446         GSList *cur = NULL;
447         static gboolean warned_error = FALSE;
448         int status = 0;
449         int total = 0, curnum = 0;
450         GSList *new_hams = NULL, *new_spams = NULL;
451         GSList *new_unsure, *whitelisted_new_spams = NULL;
452         gchar *bogo_exec = (config.bogopath && *config.bogopath) ? config.bogopath:"bogofilter";
453         gchar *bogo_args[4];
454         gboolean ok_to_thread = TRUE;
455
456         bogo_args[0] = bogo_exec;
457         bogo_args[1] = "-T";
458         bogo_args[2] = "-b";
459         bogo_args[3] = NULL;
460         
461         if (!config.process_emails) {
462                 return FALSE;
463         }
464         
465         if (msglist == NULL && msginfo != NULL) {
466                 g_warning("wrong call to bogofilter mail_filtering_hook");
467                 return FALSE;
468         }
469         
470         total = g_slist_length(msglist);
471         
472         /* we have to make sure the mails are cached - or it'll break on IMAP */
473         if (message_callback != NULL)
474                 message_callback(_("Bogofilter: fetching bodies..."), total, 0, FALSE);
475         for (cur = msglist; cur; cur = cur->next) {
476                 gchar *file = procmsg_get_message_file((MsgInfo *)cur->data);
477                 if (file == NULL)
478                         ok_to_thread = FALSE;
479                 if (message_callback != NULL)
480                         message_callback(NULL, total, curnum++, FALSE);
481                 g_free(file);
482         }
483         if (message_callback != NULL)
484                 message_callback(NULL, 0, 0, FALSE);
485
486         if (message_callback != NULL)
487                 message_callback(_("Bogofilter: filtering messages..."), total, 0, FALSE);
488
489 #ifdef USE_PTHREAD
490         while (pthread_mutex_trylock(&list_mutex) != 0) {
491                 GTK_EVENTS_FLUSH();
492                 usleep(100);
493         }
494 #endif
495         to_filter_data = g_new0(BogoFilterData, 1);
496         to_filter_data->msglist = msglist;
497         to_filter_data->mail_filtering_data = mail_filtering_data;
498         to_filter_data->new_hams = NULL;
499         to_filter_data->new_unsure = NULL;
500         to_filter_data->new_spams = NULL;
501         to_filter_data->whitelisted_new_spams = NULL;
502         to_filter_data->done = FALSE;
503         to_filter_data->status = -1;
504         to_filter_data->bogo_args = bogo_args;
505 #ifdef USE_PTHREAD
506         to_filter_data->in_thread = (filter_th != 0 && ok_to_thread);
507 #else
508         to_filter_data->in_thread = FALSE;
509 #endif
510
511 #ifdef USE_PTHREAD
512         pthread_mutex_unlock(&list_mutex);
513         
514         if (filter_th != 0 && ok_to_thread) {
515                 debug_print("waking thread to let it filter things\n");
516                 pthread_mutex_lock(&wait_mutex);
517                 pthread_cond_broadcast(&wait_cond);
518                 pthread_mutex_unlock(&wait_mutex);
519
520                 while (!to_filter_data->done) {
521                         GTK_EVENTS_FLUSH();
522                         usleep(100);
523                 }
524         }
525
526         while (pthread_mutex_trylock(&list_mutex) != 0) {
527                 GTK_EVENTS_FLUSH();
528                 usleep(100);
529
530         }
531         if (filter_th == 0 || !ok_to_thread)
532                 bogofilter_do_filter(to_filter_data);
533 #else
534         bogofilter_do_filter(to_filter_data);   
535 #endif
536
537         new_hams = to_filter_data->new_hams;
538         new_unsure = to_filter_data->new_unsure;
539         new_spams = to_filter_data->new_spams;
540         whitelisted_new_spams = to_filter_data->whitelisted_new_spams;
541         status = to_filter_data->status;
542         g_free(to_filter_data);
543         to_filter_data = NULL;
544 #ifdef USE_PTHREAD
545         pthread_mutex_unlock(&list_mutex);
546 #endif
547
548
549         /* unflag hams */
550         for (cur = new_hams; cur; cur = cur->next) {
551                 MsgInfo *msginfo = (MsgInfo *)cur->data;
552                 procmsg_msginfo_unset_flags(msginfo, MSG_SPAM, 0);
553                 debug_print("unflagging ham: %d\n", msginfo->msgnum);
554         }
555         /* unflag unsure */
556         for (cur = new_unsure; cur; cur = cur->next) {
557                 MsgInfo *msginfo = (MsgInfo *)cur->data;
558                 procmsg_msginfo_unset_flags(msginfo, MSG_SPAM, 0);
559                 debug_print("unflagging unsure: %d\n", msginfo->msgnum);
560         }
561         if (config.learn_from_whitelist && whitelisted_new_spams) {
562                 /* flag whitelisted spams */
563                 for (cur = whitelisted_new_spams; cur; cur = cur->next) {
564                         MsgInfo *msginfo = (MsgInfo *)cur->data;
565                         procmsg_msginfo_set_flags(msginfo, MSG_SPAM, 0);
566                         debug_print("flagging whitelisted non-ham: %d\n", msginfo->msgnum);
567                 }
568                 /* correct bogo */
569                 bogofilter_learn(NULL, whitelisted_new_spams, FALSE);
570
571                 /* unflag them */
572                 for (cur = whitelisted_new_spams; cur; cur = cur->next) {
573                         MsgInfo *msginfo = (MsgInfo *)cur->data;
574                         procmsg_msginfo_unset_flags(msginfo, MSG_SPAM, 0);
575                         debug_print("unflagging whitelisted non-ham: %d\n", msginfo->msgnum);
576                 }
577         } else {
578                 for (cur = whitelisted_new_spams; cur; cur = cur->next) {
579                         MsgInfo *msginfo = (MsgInfo *)cur->data;
580                         procmsg_msginfo_unset_flags(msginfo, MSG_SPAM, 0);
581                         debug_print("not flagging whitelisted non-ham: %d\n", msginfo->msgnum);
582                 }
583         }
584
585         /* flag spams and delete them if !config.receive_spam 
586          * (if config.receive_spam is set, we'll move them later) */
587         for (cur = new_spams; cur; cur = cur->next) {
588                 MsgInfo *msginfo = (MsgInfo *)cur->data;
589                 if (config.receive_spam) {
590                         if (config.mark_as_read)
591                                 procmsg_msginfo_unset_flags(msginfo, ~0, 0);
592                         procmsg_msginfo_set_flags(msginfo, MSG_SPAM, 0);
593                 } else {
594                         folder_item_remove_msg(msginfo->folder, msginfo->msgnum);
595                 }
596         }
597         
598         if (status < 0 || status > 2) { /* I/O or other errors */
599                 gchar *msg = NULL;
600                 
601                 if (status == 3)
602                         msg =  g_strdup_printf(_("The Bogofilter plugin couldn't filter "
603                                            "a message. The probable cause of the "
604                                            "error is that it didn't learn from any mail.\n"
605                                            "Use \"/Mark/Mark as spam\" and \"/Mark/Mark as "
606                                            "ham\" to train Bogofilter with a few hundred "
607                                            "spam and ham messages."));
608                 else
609                         msg =  g_strdup_printf(_("The Bogofilter plugin couldn't filter "
610                                            "a message. The command `%s %s %s` couldn't be run."), 
611                                            bogo_args[0], bogo_args[1], bogo_args[2]);
612                 if (!prefs_common.no_recv_err_panel) {
613                         if (!warned_error) {
614                                 alertpanel_error("%s", msg);
615                         }
616                         warned_error = TRUE;
617                 } else {
618                         log_error(LOG_PROTOCOL, "%s\n", msg);
619                 }
620                 g_free(msg);
621         }
622         if (status < 0 || status > 2) {
623                 g_slist_free(mail_filtering_data->filtered);
624                 g_slist_free(mail_filtering_data->unfiltered);
625                 mail_filtering_data->filtered = NULL;
626                 mail_filtering_data->unfiltered = NULL;
627         } else {
628                 if (config.receive_spam && new_spams) {
629                         FolderItem *save_folder = NULL;
630
631                         if ((!config.save_folder) ||
632                             (config.save_folder[0] == '\0') ||
633                             ((save_folder = folder_find_item_from_identifier(config.save_folder)) == NULL)) {
634                                 if (mail_filtering_data->account && mail_filtering_data->account->set_trash_folder) {
635                                         save_folder = folder_find_item_from_identifier(
636                                                 mail_filtering_data->account->trash_folder);
637                                         if (save_folder)
638                                                 debug_print("found trash folder from account's advanced settings\n");
639                                 }
640                                 if (save_folder == NULL && mail_filtering_data->account &&
641                                     mail_filtering_data->account->folder) {
642                                         save_folder = mail_filtering_data->account->folder->trash;
643                                         if (save_folder)
644                                                 debug_print("found trash folder from account's trash\n");
645                                 }
646                                 if (save_folder == NULL && mail_filtering_data->account &&
647                                     !mail_filtering_data->account->folder)  {
648                                         if (mail_filtering_data->account->inbox) {
649                                                 FolderItem *item = folder_find_item_from_identifier(
650                                                         mail_filtering_data->account->inbox);
651                                                 if (item && item->folder->trash) {
652                                                         save_folder = item->folder->trash;
653                                                         debug_print("found trash folder from account's inbox\n");
654                                                 }
655                                         } 
656                                         if (!save_folder && mail_filtering_data->account->local_inbox) {
657                                                 FolderItem *item = folder_find_item_from_identifier(
658                                                         mail_filtering_data->account->local_inbox);
659                                                 if (item && item->folder->trash) {
660                                                         save_folder = item->folder->trash;
661                                                         debug_print("found trash folder from account's local_inbox\n");
662                                                 }
663                                         }
664                                 }
665                                 if (save_folder == NULL) {
666                                         debug_print("using default trash folder\n");
667                                         save_folder = folder_get_default_trash();
668                                 }
669                         }
670                         if (save_folder) {
671                                 for (cur = new_spams; cur; cur = cur->next) {
672                                         msginfo = (MsgInfo *)cur->data;
673                                         msginfo->filter_op = IS_MOVE;
674                                         msginfo->to_filter_folder = save_folder;
675                                 }
676                         }
677                 }
678                 if (config.save_unsure && new_unsure) {
679                         FolderItem *save_unsure_folder = NULL;
680
681                         if ((!config.save_unsure_folder) ||
682                             (config.save_unsure_folder[0] == '\0') ||
683                             ((save_unsure_folder = folder_find_item_from_identifier(config.save_unsure_folder)) == NULL)) {
684                                 if (mail_filtering_data->account)
685                                         save_unsure_folder = folder_find_item_from_identifier(
686                                                 mail_filtering_data->account->inbox);
687                                 if (save_unsure_folder == NULL && mail_filtering_data->account &&
688                                     mail_filtering_data->account->folder)
689                                         save_unsure_folder = mail_filtering_data->account->folder->inbox;
690                                 if (save_unsure_folder == NULL && mail_filtering_data->account &&
691                                     !mail_filtering_data->account->folder)  {
692                                         if (mail_filtering_data->account->inbox) {
693                                                 FolderItem *item = folder_find_item_from_identifier(
694                                                         mail_filtering_data->account->inbox);
695                                                 if (item) {
696                                                         save_unsure_folder = item;
697                                                 }
698                                         } 
699                                         if (!save_unsure_folder && mail_filtering_data->account->local_inbox) {
700                                                 FolderItem *item = folder_find_item_from_identifier(
701                                                         mail_filtering_data->account->local_inbox);
702                                                 if (item) {
703                                                         save_unsure_folder = item;
704                                                 }
705                                         }
706                                 }
707                                 if (save_unsure_folder == NULL)
708                                         save_unsure_folder = folder_get_default_inbox();
709                         }
710                         if (save_unsure_folder) {
711                                 for (cur = new_unsure; cur; cur = cur->next) {
712                                         msginfo = (MsgInfo *)cur->data;
713                                         msginfo->filter_op = IS_MOVE;
714                                         msginfo->to_filter_folder = save_unsure_folder;
715                                 }
716                         }
717                 }
718         } 
719         g_slist_free(new_hams);
720         g_slist_free(new_unsure);
721         g_slist_free(new_spams);
722         g_slist_free(whitelisted_new_spams);
723
724         if (message_callback != NULL)
725                 message_callback(NULL, 0, 0, FALSE);
726         mail_filtering_data->filtered   = g_slist_reverse(
727                 mail_filtering_data->filtered);
728         mail_filtering_data->unfiltered = g_slist_reverse(
729                 mail_filtering_data->unfiltered);
730         
731         return FALSE;
732 }
733
734 BogofilterConfig *bogofilter_get_config(void)
735 {
736         return &config;
737 }
738
739 int bogofilter_learn(MsgInfo *msginfo, GSList *msglist, gboolean spam)
740 {
741         gchar *cmd = NULL;
742         gchar *file = NULL;
743         const gchar *bogo_exec = (config.bogopath && *config.bogopath) ? config.bogopath:"bogofilter";
744         gint status = 0;
745         if (msginfo == NULL && msglist == NULL) {
746                 return -1;
747         }
748
749         if (msginfo) {
750                 file = procmsg_get_message_file(msginfo);
751                 if (file == NULL) {
752                         return -1;
753                 } else {
754                         if (message_callback != NULL)
755                                 message_callback(_("Bogofilter: learning from message..."), 0, 0, FALSE);
756                         if (spam)
757                                 /* learn as spam */
758                                 cmd = g_strdup_printf("%s -s -I '%s'", bogo_exec, file);
759                         else if (MSG_IS_SPAM(msginfo->flags))
760                                 /* correct bogofilter, this wasn't spam */
761                                 cmd = g_strdup_printf("%s -Sn -I '%s'", bogo_exec, file);
762                         else 
763                                 /* learn as ham */
764                                 cmd = g_strdup_printf("%s -n -I '%s'", bogo_exec, file);
765                                 
766                         debug_print("%s\n", cmd);
767                         if ((status = execute_command_line(cmd, FALSE)) != 0)
768                                 log_error(LOG_PROTOCOL, _("Learning failed; `%s` returned with status %d."),
769                                                 cmd, status);
770                         g_free(cmd);
771                         g_free(file);
772                         if (message_callback != NULL)
773                                 message_callback(NULL, 0, 0, FALSE);
774                         return 0;
775                 }
776         }
777         if (msglist) {
778                 GSList *cur = msglist;
779                 MsgInfo *info;
780                 int total = g_slist_length(msglist);
781                 int done = 0;
782                 gboolean some_correction = FALSE, some_no_correction = FALSE;
783         
784                 if (message_callback != NULL)
785                         message_callback(_("Bogofilter: learning from messages..."), total, 0, FALSE);
786                 
787                 for (cur = msglist; cur && status == 0; cur = cur->next) {
788                         info = (MsgInfo *)cur->data;
789                         if (spam)
790                                 some_no_correction = TRUE;
791                         else if (MSG_IS_SPAM(info->flags))
792                                 /* correct bogofilter, this wasn't spam */
793                                 some_correction = TRUE;
794                         else 
795                                 some_no_correction = TRUE;
796                         
797                 }
798                 
799                 if (some_correction && some_no_correction) {
800                         /* we potentially have to do different stuff for every mail */
801                         for (cur = msglist; cur && status == 0; cur = cur->next) {
802                                 info = (MsgInfo *)cur->data;
803                                 file = procmsg_get_message_file(info);
804
805                                 if (spam)
806                                         /* learn as spam */
807                                         cmd = g_strdup_printf("%s -s -I '%s'", bogo_exec, file);
808                                 else if (MSG_IS_SPAM(info->flags))
809                                         /* correct bogofilter, this wasn't spam */
810                                         cmd = g_strdup_printf("%s -Sn -I '%s'", bogo_exec, file);
811                                 else 
812                                         /* learn as ham */
813                                         cmd = g_strdup_printf("%s -n -I '%s'", bogo_exec, file);
814                                 
815                                 debug_print("%s\n", cmd);
816                                 if ((status = execute_command_line(cmd, FALSE)) != 0)
817                                         log_error(LOG_PROTOCOL, _("Learning failed; `%s` returned with status %d."),
818                                                         cmd, status);
819
820                                 g_free(cmd);
821                                 g_free(file);
822                                 done++;
823                                 if (message_callback != NULL)
824                                         message_callback(NULL, total, done, FALSE);
825                         }
826                 } else if (some_correction || some_no_correction) {
827                         cur = msglist;
828                         
829                         gchar *bogo_args[4];
830                         GPid bogo_pid;
831                         gint bogo_stdin;
832                         GError *error = NULL;
833                         gboolean bogo_forked;
834
835                         bogo_args[0] = (gchar *)bogo_exec;
836                         if (some_correction && !some_no_correction)
837                                 bogo_args[1] = "-Sn";
838                         else if (some_no_correction && !some_correction)
839                                 bogo_args[1] = spam ? "-s":"-n";
840                         bogo_args[2] = "-b";
841                         bogo_args[3] = NULL;
842                         debug_print("|%s %s %s ...\n", bogo_args[0], bogo_args[1], bogo_args[2]);
843                         bogo_forked = g_spawn_async_with_pipes(
844                                         NULL, bogo_args,NULL, G_SPAWN_SEARCH_PATH|G_SPAWN_DO_NOT_REAP_CHILD,
845                                         NULL, NULL, &bogo_pid, &bogo_stdin,
846                                         NULL, NULL, &error);
847
848                         while (bogo_forked && cur) {
849                                 gchar *tmp = NULL;
850                                 info = (MsgInfo *)cur->data;
851                                 file = procmsg_get_message_file(info);
852                                 if (file) {
853                                         tmp = g_strdup_printf("%s\n", 
854                                                 file);
855                                         write_all(bogo_stdin, tmp, strlen(tmp));
856                                         g_free(tmp);
857                                 }
858                                 g_free(file);
859                                 done++;
860                                 if (message_callback != NULL)
861                                         message_callback(NULL, total, done, FALSE);
862                                 cur = cur->next;
863                         }
864                         if (bogo_forked) {
865                                 close(bogo_stdin);
866                                 waitpid(bogo_pid, &status, 0);
867                                 if (!WIFEXITED(status))
868                                         status = -1;
869                                 else
870                                         status = WEXITSTATUS(status);
871                         }
872                         if (!bogo_forked || status != 0) {
873                                 log_error(LOG_PROTOCOL, _("Learning failed; `%s %s %s` returned with error:\n%s"),
874                                                 bogo_args[0], bogo_args[1], bogo_args[2], 
875                                                 error ? error->message:_("Unknown error"));
876                                 if (error)
877                                         g_error_free(error);
878                         }
879
880                 }
881
882                 if (message_callback != NULL)
883                         message_callback(NULL, 0, 0, FALSE);
884                 return 0;
885         }
886         return -1;
887 }
888
889 void bogofilter_save_config(void)
890 {
891         PrefFile *pfile;
892         gchar *rcpath;
893
894         debug_print("Saving Bogofilter Page\n");
895
896         rcpath = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, COMMON_RC, NULL);
897         pfile = prefs_write_open(rcpath);
898         g_free(rcpath);
899         if (!pfile || (prefs_set_block_label(pfile, "Bogofilter") < 0))
900                 return;
901
902         if (prefs_write_param(param, pfile->fp) < 0) {
903                 g_warning("Failed to write Bogofilter configuration to file\n");
904                 prefs_file_close_revert(pfile);
905                 return;
906         }
907         if (fprintf(pfile->fp, "\n") < 0) {
908                 FILE_OP_ERROR(rcpath, "fprintf");
909                 prefs_file_close_revert(pfile);
910         } else
911                 prefs_file_close(pfile);
912 }
913
914 void bogofilter_set_message_callback(MessageCallback callback)
915 {
916         message_callback = callback;
917 }
918
919 gint plugin_init(gchar **error)
920 {
921         gchar *rcpath;
922
923         hook_id = -1;
924
925         if (!check_plugin_version(MAKE_NUMERIC_VERSION(2,9,2,72),
926                                 VERSION_NUMERIC, PLUGIN_NAME, error))
927                 return -1;
928
929         prefs_set_default(param);
930         rcpath = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, COMMON_RC, NULL);
931         prefs_read_config(param, "Bogofilter", rcpath, NULL);
932         g_free(rcpath);
933
934         bogofilter_gtk_init();
935                 
936         debug_print("Bogofilter plugin loaded\n");
937
938 #ifdef USE_PTHREAD
939         bogofilter_start_thread();
940 #endif
941
942         if (config.process_emails) {
943                 bogofilter_register_hook();
944         }
945
946         procmsg_register_spam_learner(bogofilter_learn);
947         procmsg_spam_set_folder(config.save_folder, bogofilter_get_spam_folder);
948
949         return 0;
950         
951 }
952
953 FolderItem *bogofilter_get_spam_folder(MsgInfo *msginfo)
954 {
955         FolderItem *item = folder_find_item_from_identifier(config.save_folder);
956
957         if (item || msginfo == NULL || msginfo->folder == NULL)
958                 return item;
959
960         if (msginfo->folder->folder &&
961             msginfo->folder->folder->account && 
962             msginfo->folder->folder->account->set_trash_folder) {
963                 item = folder_find_item_from_identifier(
964                         msginfo->folder->folder->account->trash_folder);
965         }
966
967         if (item == NULL && 
968             msginfo->folder->folder &&
969             msginfo->folder->folder->trash)
970                 item = msginfo->folder->folder->trash;
971                 
972         if (item == NULL)
973                 item = folder_get_default_trash();
974                 
975         debug_print("bogo spam dir: %s\n", folder_item_get_path(item));
976         return item;
977 }
978
979 gboolean plugin_done(void)
980 {
981         if (hook_id != -1) {
982                 bogofilter_unregister_hook();
983         }
984 #ifdef USE_PTHREAD
985         bogofilter_stop_thread();
986 #endif
987         g_free(config.save_folder);
988         bogofilter_gtk_done();
989         procmsg_unregister_spam_learner(bogofilter_learn);
990         procmsg_spam_set_folder(NULL, NULL);
991         debug_print("Bogofilter plugin unloaded\n");
992         return TRUE;
993 }
994
995 const gchar *plugin_name(void)
996 {
997         return PLUGIN_NAME;
998 }
999
1000 const gchar *plugin_desc(void)
1001 {
1002         return _("This plugin can check all messages that are received from an "
1003                  "IMAP, LOCAL or POP account for spam using Bogofilter. "
1004                  "You will need Bogofilter installed locally.\n"
1005                  "\n"
1006                  "Before Bogofilter can recognize spam messages, you have to "
1007                  "train it by marking a few hundred spam and ham messages "
1008                  "with the use of \"/Mark/Mark as spam\" and \"/Mark/Mark as "
1009                  "ham\".\n"
1010                  "\n"
1011                  "When a message is identified as spam it can be deleted or "
1012                  "saved in a specially designated folder.\n"
1013                  "\n"
1014                  "Options can be found in /Configuration/Preferences/Plugins/Bogofilter");
1015 }
1016
1017 const gchar *plugin_type(void)
1018 {
1019         return "GTK2";
1020 }
1021
1022 const gchar *plugin_licence(void)
1023 {
1024         return "GPL3+";
1025 }
1026
1027 const gchar *plugin_version(void)
1028 {
1029         return VERSION;
1030 }
1031
1032 struct PluginFeature *plugin_provides(void)
1033 {
1034         static struct PluginFeature features[] = 
1035                 { {PLUGIN_FILTERING, N_("Spam detection")},
1036                   {PLUGIN_FILTERING, N_("Spam learning")},
1037                   {PLUGIN_NOTHING, NULL}};
1038         return features;
1039 }
1040
1041 void bogofilter_register_hook(void)
1042 {
1043         if (hook_id == -1)
1044                 hook_id = hooks_register_hook(MAIL_LISTFILTERING_HOOKLIST, mail_filtering_hook, NULL);
1045         if (hook_id == -1) {
1046                 g_warning("Failed to register mail filtering hook");
1047                 config.process_emails = FALSE;
1048         }
1049 }
1050
1051 void bogofilter_unregister_hook(void)
1052 {
1053         if (hook_id != -1) {
1054                 hooks_unregister_hook(MAIL_LISTFILTERING_HOOKLIST, hook_id);
1055         }
1056         hook_id = -1;
1057 }