0b7bdb9f86834767d1b0b65a9fc598092ee3bf98
[claws.git] / src / plugins / bogofilter / bogofilter.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2006 Hiroyuki Yamamoto and the Claws Mail Team
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #endif
23
24 #include "defs.h"
25
26 #include <sys/types.h>
27 #include <sys/wait.h>
28 #include <errno.h>
29
30 #include <glib.h>
31 #include <glib/gi18n.h>
32
33 #if HAVE_LOCALE_H
34 #  include <locale.h>
35 #endif
36
37 #include "common/sylpheed.h"
38 #include "common/version.h"
39 #include "plugin.h"
40 #include "common/utils.h"
41 #include "hooks.h"
42 #include "procmsg.h"
43 #include "folder.h"
44 #include "prefs.h"
45 #include "prefs_gtk.h"
46
47 #include "bogofilter.h"
48 #include "inc.h"
49 #include "log.h"
50 #include "prefs_common.h"
51 #include "alertpanel.h"
52
53 #ifdef HAVE_SYSEXITS_H
54 #include <sysexits.h>
55 #endif
56 #ifdef HAVE_ERRNO_H
57 #include <errno.h>
58 #endif
59 #ifdef HAVE_SYS_ERRNO_H
60 #include <sys/errno.h>
61 #endif
62 #ifdef HAVE_TIME_H
63 #include <time.h>
64 #endif
65 #ifdef HAVE_SYS_TIME_H
66 #include <sys/time.h>
67 #endif
68 #ifdef HAVE_SIGNAL_H
69 #include <signal.h>
70 #endif
71 #ifdef HAVE_PWD_H
72 #include <pwd.h>
73 #endif
74
75 #define MAILS_PER_BATCH 20
76
77 static guint hook_id = -1;
78 static MessageCallback message_callback;
79
80 static BogofilterConfig config;
81
82 static PrefParam param[] = {
83         {"process_emails", "TRUE", &config.process_emails, P_BOOL,
84          NULL, NULL, NULL},
85         {"receive_spam", "TRUE", &config.receive_spam, P_BOOL,
86          NULL, NULL, NULL},
87         {"save_folder", NULL, &config.save_folder, P_STRING,
88          NULL, NULL, NULL},
89         {"max_size", "250", &config.max_size, P_INT,
90          NULL, NULL, NULL},
91         {"bogopath", "bogofilter", &config.bogopath, P_STRING,
92          NULL, NULL, NULL},
93
94         {NULL, NULL, NULL, P_OTHER, NULL, NULL, NULL}
95 };
96
97 /*
98  * Helper function for spawn_with_input() - write an entire
99  * string to a fd.
100  */
101 static gboolean
102 write_all (int         fd,
103            const char *buf,
104            gsize       to_write)
105 {
106   while (to_write > 0)
107     {
108       gssize count = write (fd, buf, to_write);
109       if (count < 0)
110         {
111           if (errno != EINTR)
112             return FALSE;
113         }
114       else
115         {
116           to_write -= count;
117           buf += count;
118         }
119     }
120
121   return TRUE;
122 }
123
124 static gboolean mail_filtering_hook(gpointer source, gpointer data)
125 {
126         MailFilteringData *mail_filtering_data = (MailFilteringData *) source;
127         MsgInfo *msginfo = mail_filtering_data->msginfo;
128         GSList *msglist = mail_filtering_data->msglist;
129         GSList *cur = NULL;
130         static gboolean warned_error = FALSE;
131         gchar *file = NULL;
132         int status = 0;
133         gchar *bogo_exec = (config.bogopath && *config.bogopath) ? config.bogopath:"bogofilter";
134         int total = 0, curnum = 0;
135         GSList *spams = NULL;
136         gchar buf[BUFSIZ];
137
138         gchar *bogo_args[4];
139         GPid bogo_pid;
140         gint bogo_stdin, bogo_stdout;
141         GError *error = NULL;
142         gboolean bogo_forked;
143
144         if (!config.process_emails) {
145                 return FALSE;
146         }
147         
148         if (msglist == NULL && msginfo != NULL) {
149                 g_warning("wrong call to bogofilter mail_filtering_hook");
150                 return FALSE;
151         }
152         
153         total = g_slist_length(msglist);
154         if (message_callback != NULL)
155                 message_callback(_("Bogofilter: filtering messages..."), total, 0);
156
157         bogo_args[0] = bogo_exec;
158         bogo_args[1] = "-T";
159         bogo_args[2] = "-b";
160         bogo_args[3] = NULL;
161
162         bogo_forked = g_spawn_async_with_pipes(
163                         NULL, bogo_args,NULL, G_SPAWN_SEARCH_PATH|G_SPAWN_DO_NOT_REAP_CHILD,
164                         NULL, NULL, &bogo_pid, &bogo_stdin,
165                         &bogo_stdout, NULL, &error);
166                 
167         if (bogo_forked == FALSE) {
168                 g_warning("%s\n", error ? error->message:"ERROR???");
169                 g_error_free(error);
170                 error = NULL;
171                 status = -1;
172         } else {
173                 for (cur = msglist; cur; cur = cur->next) {
174                         msginfo = (MsgInfo *)cur->data;
175                         debug_print("Filtering message %d (%d/%d)\n", msginfo->msgnum, curnum, total);
176
177                         if (message_callback != NULL)
178                                 message_callback(NULL, total, curnum++);
179
180                         file = procmsg_get_message_file(msginfo);
181
182                         if (file) {
183                                 gchar *tmp = g_strdup_printf("%s\n",file);
184                                 write_all(bogo_stdin, tmp, strlen(tmp));
185                                 g_free(tmp);
186                                 memset(buf, 0, sizeof(buf));
187                                 if (read(bogo_stdout, buf, sizeof(buf)-1) < 0) {
188                                         g_warning("bogofilter short read\n");
189                                         debug_print("message %d is ham\n", msginfo->msgnum);
190                                         procmsg_msginfo_unset_flags(msginfo, MSG_SPAM, 0);
191                                         mail_filtering_data->unfiltered = g_slist_prepend(
192                                                 mail_filtering_data->unfiltered, msginfo);
193                                 } else {
194                                         gchar **parts = NULL;
195                                         if (strchr(buf, '/')) {
196                                                 tmp = strrchr(buf, '/')+1;
197                                         } else {
198                                                 tmp = buf;
199                                         }
200                                         parts = g_strsplit(tmp, " ", 0);
201                                         debug_print("read %s\n", buf);
202                                         if (parts && parts[0] && parts[1] && *parts[1] == 'S') {
203                                                 debug_print("message %d is spam\n", msginfo->msgnum);
204                                                 procmsg_msginfo_set_flags(msginfo, MSG_SPAM, 0);
205                                                 
206                                                 if (config.receive_spam) {
207                                                         procmsg_msginfo_unset_flags(msginfo, ~0, 0);
208                                                         procmsg_msginfo_set_flags(msginfo, MSG_SPAM, 0);
209                                                         spams = g_slist_prepend(spams, msginfo);
210                                                 } else {
211                                                         folder_item_remove_msg(msginfo->folder, msginfo->msgnum);
212                                                 }
213
214                                                 mail_filtering_data->filtered = g_slist_prepend(
215                                                         mail_filtering_data->filtered, msginfo);
216                                         } else {
217                                                 debug_print("message %d is ham\n", msginfo->msgnum);
218                                                 procmsg_msginfo_unset_flags(msginfo, MSG_SPAM, 0);
219                                                 mail_filtering_data->unfiltered = g_slist_prepend(
220                                                         mail_filtering_data->unfiltered, msginfo);
221                                         }
222                                         g_strfreev(parts);
223                                 }
224                                 g_free(file);
225                         } else {
226                                 procmsg_msginfo_unset_flags(msginfo, MSG_SPAM, 0);
227                                 mail_filtering_data->unfiltered = g_slist_prepend(
228                                         mail_filtering_data->unfiltered, msginfo);
229                         }
230                 }
231         }
232         
233         if (status != -1) {
234                 close(bogo_stdout);
235                 close(bogo_stdin);
236                 waitpid(bogo_pid, &status, 0);
237                 if (!WIFEXITED(status))
238                         status = -1;
239                 else
240                         status = WEXITSTATUS(status);
241         } 
242
243         if (status < 0 || status > 2) { /* I/O or other errors */
244                 gchar *msg = NULL;
245                 
246                 if (status == 3)
247                         msg =  g_strdup_printf(_("The Bogofilter plugin couldn't filter "
248                                            "a message. The probable cause of the "
249                                            "error is that it didn't learn from any mail.\n"
250                                            "Use \"/Mark/Mark as spam\" and \"/Mark/Mark as "
251                                            "ham\" to train Bogofilter with a few hundred "
252                                            "spam and ham messages."));
253                 else
254                         msg =  g_strdup_printf(_("The Bogofilter plugin couldn't filter "
255                                            "a message. the command `%s %s %s` couldn't be run."), 
256                                            bogo_args[0], bogo_args[1], bogo_args[2]);
257                 if (!prefs_common.no_recv_err_panel) {
258                         if (!warned_error) {
259                                 alertpanel_error(msg);
260                         }
261                         warned_error = TRUE;
262                 } else {
263                         gchar *tmp = g_strdup_printf("%s\n", msg);
264                         log_error(tmp);
265                         g_free(tmp);
266                 }
267                 g_free(msg);
268         }
269         if (status < 0 || status > 2) {
270                 g_slist_free(mail_filtering_data->filtered);
271                 g_slist_free(mail_filtering_data->unfiltered);
272                 g_slist_free(spams);
273                 mail_filtering_data->filtered = NULL;
274                 mail_filtering_data->unfiltered = NULL;
275         } else if (config.receive_spam && spams) {
276                 FolderItem *save_folder;
277
278                 if ((!config.save_folder) ||
279                     (config.save_folder[0] == '\0') ||
280                     ((save_folder = folder_find_item_from_identifier(config.save_folder)) == NULL))
281                         save_folder = folder_get_default_trash();
282                 if (save_folder) {
283                         for (cur = spams; cur; cur = cur->next) {
284                                 msginfo = (MsgInfo *)cur->data;
285                                 msginfo->is_move = TRUE;
286                                 msginfo->to_filter_folder = save_folder;
287                         }
288                 }
289         } 
290
291         if (message_callback != NULL)
292                 message_callback(NULL, 0, 0);
293         mail_filtering_data->filtered = g_slist_reverse(
294                 mail_filtering_data->filtered);
295         mail_filtering_data->unfiltered = g_slist_reverse(
296                 mail_filtering_data->unfiltered);
297         
298         return FALSE;
299 }
300
301 BogofilterConfig *bogofilter_get_config(void)
302 {
303         return &config;
304 }
305
306 int bogofilter_learn(MsgInfo *msginfo, GSList *msglist, gboolean spam)
307 {
308         gchar *cmd = NULL;
309         gchar *file = NULL;
310         const gchar *bogo_exec = (config.bogopath && *config.bogopath) ? config.bogopath:"bogofilter";
311         gint status = 0;
312         if (msginfo == NULL && msglist == NULL) {
313                 return -1;
314         }
315
316         if (msginfo) {
317                 file = procmsg_get_message_file(msginfo);
318                 if (file == NULL) {
319                         return -1;
320                 } else {
321                         if (message_callback != NULL)
322                                 message_callback(_("Bogofilter: learning from message..."), 0, 0);
323                         if (spam)
324                                 /* learn as spam */
325                                 cmd = g_strdup_printf("%s -s -I '%s'", bogo_exec, file);
326                         else if (MSG_IS_SPAM(msginfo->flags))
327                                 /* correct bogofilter, this wasn't spam */
328                                 cmd = g_strdup_printf("%s -Sn -I '%s'", bogo_exec, file);
329                         else 
330                                 /* learn as ham */
331                                 cmd = g_strdup_printf("%s -n -I '%s'", bogo_exec, file);
332                         if ((status = execute_command_line(cmd, FALSE)) != 0)
333                                 log_error(_("Learning failed; `%s` returned with status %d."),
334                                                 cmd, status);
335                         g_free(cmd);
336                         g_free(file);
337                         if (message_callback != NULL)
338                                 message_callback(NULL, 0, 0);
339                         return 0;
340                 }
341         }
342         if (msglist) {
343                 GSList *cur = msglist;
344                 MsgInfo *info;
345                 int total = g_slist_length(msglist);
346                 int done = 0;
347                 gboolean some_correction = FALSE, some_no_correction = FALSE;
348         
349                 if (message_callback != NULL)
350                         message_callback(_("Bogofilter: learning from messages..."), total, 0);
351                 
352                 for (cur = msglist; cur && status == 0; cur = cur->next) {
353                         info = (MsgInfo *)cur->data;
354                         if (spam)
355                                 some_no_correction = TRUE;
356                         else if (MSG_IS_SPAM(info->flags))
357                                 /* correct bogofilter, this wasn't spam */
358                                 some_correction = TRUE;
359                         else 
360                                 some_no_correction = TRUE;
361                         
362                 }
363                 
364                 if (some_correction && some_no_correction) {
365                         /* we potentially have to do different stuff for every mail */
366                         for (cur = msglist; cur && status == 0; cur = cur->next) {
367                                 info = (MsgInfo *)cur->data;
368                                 file = procmsg_get_message_file(info);
369
370                                 if (spam)
371                                         /* learn as spam */
372                                         cmd = g_strdup_printf("%s -s -I '%s'", bogo_exec, file);
373                                 else if (MSG_IS_SPAM(info->flags))
374                                         /* correct bogofilter, this wasn't spam */
375                                         cmd = g_strdup_printf("%s -Sn -I '%s'", bogo_exec, file);
376                                 else 
377                                         /* learn as ham */
378                                         cmd = g_strdup_printf("%s -n -I '%s'", bogo_exec, file);
379
380                                 if ((status = execute_command_line(cmd, FALSE)) != 0)
381                                         log_error(_("Learning failed; `%s` returned with status %d."),
382                                                         cmd, status);
383
384                                 g_free(cmd);
385                                 g_free(file);
386                                 done++;
387                                 if (message_callback != NULL)
388                                         message_callback(NULL, total, done);
389                         }
390                 } else if (some_correction || some_no_correction) {
391                         cur = msglist;
392                         
393                         gchar *bogo_args[4];
394                         GPid bogo_pid;
395                         gint bogo_stdin;
396                         GError *error = NULL;
397                         gboolean bogo_forked;
398
399                         bogo_args[0] = (gchar *)bogo_exec;
400                         if (some_correction && !some_no_correction)
401                                 bogo_args[1] = "-Sn";
402                         else if (some_no_correction && !some_correction)
403                                 bogo_args[1] = spam ? "-s":"-n";
404                         bogo_args[2] = "-b";
405                         bogo_args[3] = NULL;
406
407                         bogo_forked = g_spawn_async_with_pipes(
408                                         NULL, bogo_args,NULL, G_SPAWN_SEARCH_PATH|G_SPAWN_DO_NOT_REAP_CHILD,
409                                         NULL, NULL, &bogo_pid, &bogo_stdin,
410                                         NULL, NULL, &error);
411
412                         while (bogo_forked && cur) {
413                                 gchar *tmp = NULL;
414                                 info = (MsgInfo *)cur->data;
415                                 file = procmsg_get_message_file(info);
416                                 if (file) {
417                                         tmp = g_strdup_printf("%s\n", 
418                                                 file);
419                                         write_all(bogo_stdin, tmp, strlen(tmp));
420                                         g_free(tmp);
421                                 }
422                                 g_free(file);
423                                 done++;
424                                 if (message_callback != NULL)
425                                         message_callback(NULL, total, done);
426                                 cur = cur->next;
427                         }
428                         if (bogo_forked) {
429                                 close(bogo_stdin);
430                                 waitpid(bogo_pid, &status, 0);
431                                 if (!WIFEXITED(status))
432                                         status = -1;
433                                 else
434                                         status = WEXITSTATUS(status);
435                         }
436                         if (!bogo_forked || status != 0) {
437                                 log_error(_("Learning failed; `%s %s %s` returned with error:\n%s"),
438                                                 bogo_args[0], bogo_args[1], bogo_args[2], 
439                                                 error ? error->message:_("Unknown error"));
440                                 if (error)
441                                         g_error_free(error);
442                         }
443
444                 }
445
446                 if (message_callback != NULL)
447                         message_callback(NULL, 0, 0);
448                 return 0;
449         }
450         return -1;
451 }
452
453 void bogofilter_save_config(void)
454 {
455         PrefFile *pfile;
456         gchar *rcpath;
457
458         debug_print("Saving Bogofilter Page\n");
459
460         rcpath = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, COMMON_RC, NULL);
461         pfile = prefs_write_open(rcpath);
462         g_free(rcpath);
463         if (!pfile || (prefs_set_block_label(pfile, "Bogofilter") < 0))
464                 return;
465
466         if (prefs_write_param(param, pfile->fp) < 0) {
467                 g_warning("Failed to write Bogofilter configuration to file\n");
468                 prefs_file_close_revert(pfile);
469                 return;
470         }
471         fprintf(pfile->fp, "\n");
472
473         prefs_file_close(pfile);
474 }
475
476 void bogofilter_set_message_callback(MessageCallback callback)
477 {
478         message_callback = callback;
479 }
480
481 gint plugin_init(gchar **error)
482 {
483         gchar *rcpath;
484
485         hook_id = -1;
486
487         if ((sylpheed_get_version() > VERSION_NUMERIC)) {
488                 *error = g_strdup(_("Your version of Claws Mail is newer than the version the Bogofilter plugin was built with"));
489                 return -1;
490         }
491
492         if ((sylpheed_get_version() < MAKE_NUMERIC_VERSION(0, 9, 3, 86))) {
493                 *error = g_strdup(_("Your version of Claws Mail is too old for the Bogofilter plugin"));
494                 return -1;
495         }
496
497         prefs_set_default(param);
498         rcpath = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, COMMON_RC, NULL);
499         prefs_read_config(param, "Bogofilter", rcpath, NULL);
500         g_free(rcpath);
501
502         bogofilter_gtk_init();
503                 
504         debug_print("Bogofilter plugin loaded\n");
505
506         if (config.process_emails) {
507                 bogofilter_register_hook();
508         }
509
510         procmsg_register_spam_learner(bogofilter_learn);
511         procmsg_spam_set_folder(config.save_folder);
512
513         return 0;
514         
515 }
516
517 void plugin_done(void)
518 {
519         if (hook_id != -1) {
520                 bogofilter_unregister_hook();
521         }
522         g_free(config.save_folder);
523         bogofilter_gtk_done();
524         procmsg_unregister_spam_learner(bogofilter_learn);
525         procmsg_spam_set_folder(NULL);
526         debug_print("Bogofilter plugin unloaded\n");
527 }
528
529 const gchar *plugin_name(void)
530 {
531         return _("Bogofilter");
532 }
533
534 const gchar *plugin_desc(void)
535 {
536         return _("This plugin can check all messages that are received from an "
537                  "IMAP, LOCAL or POP account for spam using Bogofilter. "
538                  "You will need Bogofilter installed locally.\n "
539                  "\n"
540                  "Before Bogofilter can recognize spam messages, you have to "
541                  "train it by marking a few hundred spam and ham messages. "
542                  "Use \"/Mark/Mark as Spam\" and \"/Mark/Mark as ham\" to "
543                  "train Bogofilter.\n"
544                  "\n"
545                  "When a message is identified as spam it can be deleted or "
546                  "saved in a specially designated folder.\n"
547                  "\n"
548                  "Options can be found in /Configuration/Preferences/Plugins/Bogofilter");
549 }
550
551 const gchar *plugin_type(void)
552 {
553         return "GTK2";
554 }
555
556 const gchar *plugin_licence(void)
557 {
558         return "GPL";
559 }
560
561 const gchar *plugin_version(void)
562 {
563         return VERSION;
564 }
565
566 struct PluginFeature *plugin_provides(void)
567 {
568         static struct PluginFeature features[] = 
569                 { {PLUGIN_FILTERING, N_("Spam detection")},
570                   {PLUGIN_FILTERING, N_("Spam learning")},
571                   {PLUGIN_NOTHING, NULL}};
572         return features;
573 }
574
575 void bogofilter_register_hook(void)
576 {
577         if (hook_id == -1)
578                 hook_id = hooks_register_hook(MAIL_LISTFILTERING_HOOKLIST, mail_filtering_hook, NULL);
579         if (hook_id == -1) {
580                 g_warning("Failed to register mail filtering hook");
581                 config.process_emails = FALSE;
582         }
583 }
584
585 void bogofilter_unregister_hook(void)
586 {
587         if (hook_id != -1) {
588                 hooks_unregister_hook(MAIL_LISTFILTERING_HOOKLIST, hook_id);
589         }
590         hook_id = -1;
591 }