116d19a4e9e1fe1f094870b88351f92369b680ac
[claws.git] / src / plugins / spamassassin / spamassassin.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2006 Hiroyuki Yamamoto and the Sylpheed-Claws 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
29 #include <glib.h>
30 #include <glib/gi18n.h>
31
32 #if HAVE_LOCALE_H
33 #  include <locale.h>
34 #endif
35
36 #include "common/sylpheed.h"
37 #include "common/version.h"
38 #include "plugin.h"
39 #include "common/utils.h"
40 #include "hooks.h"
41 #include "procmsg.h"
42 #include "folder.h"
43 #include "prefs.h"
44 #include "prefs_gtk.h"
45
46 #include "libspamc.h"
47 #include "spamassassin.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 enum {
76     CHILD_RUNNING = 1 << 0,
77     TIMEOUT_RUNNING = 1 << 1,
78 };
79
80 static guint hook_id = -1;
81 static int flags = SPAMC_RAW_MODE | SPAMC_SAFE_FALLBACK | SPAMC_CHECK_ONLY;
82 static MessageCallback message_callback;
83
84 static SpamAssassinConfig config;
85
86 static PrefParam param[] = {
87         {"enable", "FALSE", &config.enable, P_BOOL,
88         NULL, NULL, NULL},
89         {"transport", "0", &config.transport, P_INT,
90          NULL, NULL, NULL},
91         {"hostname", "localhost", &config.hostname, P_STRING,
92          NULL, NULL, NULL},
93         {"port", "783", &config.port, P_INT,
94          NULL, NULL, NULL},
95         {"socket", "", &config.socket, P_STRING,
96          NULL, NULL, NULL},
97         {"process_emails", "TRUE", &config.process_emails, P_BOOL,
98          NULL, NULL, NULL},
99         {"receive_spam", "TRUE", &config.receive_spam, P_BOOL,
100          NULL, NULL, NULL},
101         {"save_folder", NULL, &config.save_folder, P_STRING,
102          NULL, NULL, NULL},
103         {"max_size", "250", &config.max_size, P_INT,
104          NULL, NULL, NULL},
105         {"timeout", "30", &config.timeout, P_INT,
106          NULL, NULL, NULL},
107         {"username", "", &config.username, P_STRING,
108          NULL, NULL, NULL},
109
110         {NULL, NULL, NULL, P_OTHER, NULL, NULL, NULL}
111 };
112
113 gboolean timeout_func(gpointer data)
114 {
115         gint *running = (gint *) data;
116
117         if (*running & CHILD_RUNNING)
118                 return TRUE;
119
120         *running &= ~TIMEOUT_RUNNING;
121         return FALSE;
122 }
123
124 typedef enum {
125         MSG_IS_HAM = 0,
126         MSG_IS_SPAM = 1,
127         MSG_FILTERING_ERROR = 2
128 } MsgStatus;
129
130 static MsgStatus msg_is_spam(FILE *fp)
131 {
132         struct transport trans;
133         struct message m;
134         gboolean is_spam = FALSE;
135
136         if (!config.enable)
137                 return MSG_IS_HAM;
138
139         transport_init(&trans);
140         switch (config.transport) {
141         case SPAMASSASSIN_TRANSPORT_LOCALHOST:
142                 trans.type = TRANSPORT_LOCALHOST;
143                 trans.port = config.port;
144                 break;
145         case SPAMASSASSIN_TRANSPORT_TCP:
146                 trans.type = TRANSPORT_TCP;
147                 trans.hostname = config.hostname;
148                 trans.port = config.port;
149                 break;
150         case SPAMASSASSIN_TRANSPORT_UNIX:
151                 trans.type = TRANSPORT_UNIX;
152                 trans.socketpath = config.socket;
153                 break;
154         default:
155                 return MSG_IS_HAM;
156         }
157
158         if (transport_setup(&trans, flags) != EX_OK) {
159                 log_error(_("SpamAssassin plugin couldn't connect to spamd.\n"));
160                 debug_print("failed to setup transport\n");
161                 return MSG_FILTERING_ERROR;
162         }
163
164         m.type = MESSAGE_NONE;
165         m.max_len = config.max_size * 1024;
166         m.timeout = config.timeout;
167
168         if (message_read(fileno(fp), flags, &m) != EX_OK) {
169                 debug_print("failed to read message\n");
170                 message_cleanup(&m);
171                 return MSG_FILTERING_ERROR;
172         }
173
174         if (message_filter(&trans, config.username, flags, &m) != EX_OK) {
175                 log_error(_("SpamAssassin plugin filtering failed.\n"));
176                 debug_print("filtering the message failed\n");
177                 message_cleanup(&m);
178                 return MSG_FILTERING_ERROR;
179         }
180
181         if (m.is_spam == EX_ISSPAM)
182                 is_spam = TRUE;
183
184         message_cleanup(&m);
185
186         return is_spam ? MSG_IS_SPAM:MSG_IS_HAM;
187 }
188
189 static gboolean mail_filtering_hook(gpointer source, gpointer data)
190 {
191         MailFilteringData *mail_filtering_data = (MailFilteringData *) source;
192         MsgInfo *msginfo = mail_filtering_data->msginfo;
193         gboolean is_spam = FALSE, error = FALSE;
194         static gboolean warned_error = FALSE;
195         FILE *fp = NULL;
196         int pid = 0;
197         int status;
198
199         /* SPAMASSASSIN_DISABLED : keep test for compatibility purpose */
200         if (!config.enable || config.transport == SPAMASSASSIN_DISABLED) {
201                 log_error(_("SpamAssassin plugin is disabled by its preferences.\n"));
202                 return FALSE;
203         }
204         debug_print("Filtering message %d\n", msginfo->msgnum);
205         if (message_callback != NULL)
206                 message_callback(_("SpamAssassin: filtering message..."));
207
208         if ((fp = procmsg_open_message(msginfo)) == NULL) {
209                 debug_print("failed to open message file\n");
210                 return FALSE;
211         }
212
213         pid = fork();
214         if (pid == 0) {
215                 _exit(msg_is_spam(fp));
216         } else {
217                 gint running = 0;
218
219                 running |= CHILD_RUNNING;
220
221                 g_timeout_add(50, timeout_func, &running);
222                 running |= TIMEOUT_RUNNING;
223
224                 while(running & CHILD_RUNNING) {
225                         int ret;
226
227                         ret = waitpid(pid, &status, WNOHANG);
228                         if (ret == pid) {
229                                 if (WIFEXITED(status)) {
230                                         MsgStatus result = MSG_IS_HAM;
231                                         running &= ~CHILD_RUNNING;
232                                         result = WEXITSTATUS(status);
233                                         is_spam = (result == MSG_IS_SPAM) ? TRUE : FALSE;
234                                         error = (result == MSG_FILTERING_ERROR);
235                                 }
236                         } if (ret < 0) {
237                                 running &= ~CHILD_RUNNING;
238                         } /* ret == 0 continue */
239             
240                         g_main_iteration(TRUE);
241                 }
242
243                 while (running & TIMEOUT_RUNNING)
244                         g_main_iteration(TRUE);
245         }
246
247         fclose(fp);
248
249         if (is_spam) {
250                 debug_print("message is spam\n");
251                 procmsg_msginfo_set_flags(msginfo, MSG_SPAM, 0);
252                 if (config.receive_spam) {
253                         FolderItem *save_folder;
254
255                         if ((!config.save_folder) ||
256                             (config.save_folder[0] == '\0') ||
257                             ((save_folder = folder_find_item_from_identifier(config.save_folder)) == NULL))
258                                 save_folder = folder_get_default_trash();
259
260                         procmsg_msginfo_unset_flags(msginfo, ~0, 0);
261                         procmsg_msginfo_set_flags(msginfo, MSG_SPAM, 0);
262                         folder_item_move_msg(save_folder, msginfo);
263                 } else {
264                         folder_item_remove_msg(msginfo->folder, msginfo->msgnum);
265                 }
266
267                 return TRUE;
268         } else {
269                 debug_print("message is ham\n");
270                 procmsg_msginfo_unset_flags(msginfo, MSG_SPAM, 0);
271         }
272         
273         if (error) {
274                 if (!warned_error) {
275                         alertpanel_error(_("The SpamAssassin plugin couldn't filter "
276                                            "a message. The probable error cause is "
277                                            "an unreachable spamd daemon. Please make "
278                                            "sure spamd is running and accessible."));
279                 }
280                 warned_error = TRUE;
281         }
282         
283         return FALSE;
284 }
285
286 SpamAssassinConfig *spamassassin_get_config(void)
287 {
288         return &config;
289 }
290
291 gchar* spamassassin_create_tmp_spamc_wrapper(gboolean spam)
292 {
293         gchar *contents;
294         gchar *fname = get_tmp_file();
295
296         if (fname != NULL) {
297                 contents = g_strdup_printf(
298                                                 "spamc -d %s -p %u -u %s -t %u -s %u -L %s<\"$*\";exit $?",
299                                                 config.hostname, config.port, 
300                                                 config.username, config.timeout,
301                                                 config.max_size * 1024, spam?"spam":"ham");
302                 if (str_write_to_file(contents, fname) < 0) {
303                         g_free(fname);
304                         fname = NULL;
305                 }
306                 g_free(contents);
307         }
308         /* returned pointer must be free'ed by caller */
309         return fname;
310 }
311
312 int spamassassin_learn(MsgInfo *msginfo, GSList *msglist, gboolean spam)
313 {
314         gchar *cmd = NULL;
315         gchar *file = NULL;
316         const gchar *shell = g_getenv("SHELL");
317         gchar *spamc_wrapper = NULL;
318
319         if (msginfo == NULL && msglist == NULL) {
320                 return -1;
321         }
322
323         if (config.transport == SPAMASSASSIN_TRANSPORT_TCP
324         &&  prefs_common.work_offline
325         &&  !inc_offline_should_override(
326                 _("Sylpheed-Claws needs network access in order "
327                   "to feed this mail(s) to the remote learner."))) {
328                 return -1;
329         }
330
331         if (msginfo) {
332                 file = procmsg_get_message_file(msginfo);
333                 if (file == NULL) {
334                         return -1;
335                 }
336                 if (config.transport == SPAMASSASSIN_TRANSPORT_TCP) {
337                         spamc_wrapper = spamassassin_create_tmp_spamc_wrapper(spam);
338                         if (spamc_wrapper != NULL) {
339                                 cmd = g_strconcat(shell?shell:"sh", " ",
340                                                                 spamc_wrapper, " ", file, NULL);
341                         }
342                 } else {
343                         cmd = g_strdup_printf("sa-learn -u %s %s %s %s",
344                                                         config.username,
345                                                         prefs_common.work_offline?"-L":"",
346                                                         spam?"--spam":"--ham", file);
347                 }
348         }
349         if (msglist) {
350                 GSList *cur = msglist;
351                 MsgInfo *info;
352
353                 if (config.transport == SPAMASSASSIN_TRANSPORT_TCP) {
354                         /* execute n-times the spamc command */
355                         for (; cur; cur = cur->next) {
356                                 info = (MsgInfo *)cur->data;
357                                 gchar *tmpcmd = NULL;
358                                 gchar *tmpfile = get_tmp_file();
359
360                                 if (spamc_wrapper == NULL) {
361                                         spamc_wrapper = spamassassin_create_tmp_spamc_wrapper(spam);
362                                 }
363
364                                 if (spamc_wrapper && tmpfile &&
365                                 copy_file(procmsg_get_message_file(info), tmpfile, TRUE) == 0) {
366                                         tmpcmd = g_strconcat(shell?shell:"sh", " ", spamc_wrapper, " ",
367                                                                                 tmpfile, NULL);
368                                         debug_print("%s\n", tmpcmd);
369                                         execute_command_line(tmpcmd, FALSE);
370                                         g_free(tmpcmd);
371                                 }
372                                 g_free(tmpfile);
373                         }
374                         g_free(spamc_wrapper);
375                         return 0;
376                 } else {
377                         cmd = g_strdup_printf("sa-learn -u %s %s %s",
378                                         config.username,
379                                         prefs_common.work_offline?"-L":"",
380                                         spam?"--spam":"--ham");
381
382                         /* concatenate all message tmpfiles to the sa-learn command-line */
383                         for (; cur; cur = cur->next) {
384                                 info = (MsgInfo *)cur->data;
385                                 gchar *tmpcmd = NULL;
386                                 gchar *tmpfile = get_tmp_file();
387
388                                 if (tmpfile &&
389                                 copy_file(procmsg_get_message_file(info), tmpfile, TRUE) == 0) {                        
390                                         tmpcmd = g_strconcat(cmd, " ", tmpfile, NULL);
391                                         g_free(cmd);
392                                         cmd = tmpcmd;
393                                 }
394                                 g_free(tmpfile);
395                         }
396                 }
397         }
398         if (cmd == NULL) {
399                 return -1;
400         }
401         debug_print("%s\n", cmd);
402         /* only run sync calls to sa-learn/spamc to prevent system lockdown */
403         execute_command_line(cmd, FALSE);
404         g_free(cmd);
405         g_free(spamc_wrapper);
406
407         return 0;
408 }
409
410 void spamassassin_save_config(void)
411 {
412         PrefFile *pfile;
413         gchar *rcpath;
414
415         debug_print("Saving SpamAssassin Page\n");
416
417         rcpath = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, COMMON_RC, NULL);
418         pfile = prefs_write_open(rcpath);
419         g_free(rcpath);
420         if (!pfile || (prefs_set_block_label(pfile, "SpamAssassin") < 0))
421                 return;
422
423         if (prefs_write_param(param, pfile->fp) < 0) {
424                 g_warning("Failed to write SpamAssassin configuration to file\n");
425                 prefs_file_close_revert(pfile);
426                 return;
427         }
428         fprintf(pfile->fp, "\n");
429
430         prefs_file_close(pfile);
431 }
432
433 gboolean spamassassin_check_username(void)
434 {
435         if (config.username == NULL || config.username[0] == '\0') {
436                 config.username = (gchar*)g_get_user_name();
437                 if (config.username == NULL) {
438                         if (hook_id != -1) {
439                                 spamassassin_unregister_hook();
440                         }
441                         procmsg_unregister_spam_learner(spamassassin_learn);
442                         procmsg_spam_set_folder(NULL);
443                         return FALSE;
444                 }
445         }
446         return TRUE;
447 }
448
449 void spamassassin_set_message_callback(MessageCallback callback)
450 {
451         message_callback = callback;
452 }
453
454 gint plugin_init(gchar **error)
455 {
456         gchar *rcpath;
457
458         hook_id = -1;
459
460         if ((sylpheed_get_version() > VERSION_NUMERIC)) {
461                 *error = g_strdup("Your version of Sylpheed-Claws is newer than the version the SpamAssassin plugin was built with");
462                 return -1;
463         }
464
465         if ((sylpheed_get_version() < MAKE_NUMERIC_VERSION(0, 9, 3, 86))) {
466                 *error = g_strdup("Your version of Sylpheed-Claws is too old for the SpamAssassin plugin");
467                 return -1;
468         }
469
470         prefs_set_default(param);
471         rcpath = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, COMMON_RC, NULL);
472         prefs_read_config(param, "SpamAssassin", rcpath, NULL);
473         g_free(rcpath);
474         if (!spamassassin_check_username()) {
475                 *error = g_strdup("Failed to get username");
476                 return -1;
477         }
478         spamassassin_gtk_init();
479                 
480         debug_print("SpamAssassin plugin loaded\n");
481
482         if (config.process_emails) {
483                 spamassassin_register_hook();
484         }
485
486         if (!config.enable || config.transport == SPAMASSASSIN_DISABLED) {
487                 log_error(_("SpamAssassin plugin is loaded but disabled by its preferences.\n"));
488         }
489         else {
490                 if (config.transport == SPAMASSASSIN_TRANSPORT_TCP)
491                         debug_print("Enabling learner with a remote spamassassin server requires spamc/spamd 3.1.x\n");
492                 procmsg_register_spam_learner(spamassassin_learn);
493                 procmsg_spam_set_folder(config.save_folder);
494         }
495
496         return 0;
497         
498 }
499
500 void plugin_done(void)
501 {
502         if (hook_id != -1) {
503                 spamassassin_unregister_hook();
504         }
505         g_free(config.hostname);
506         g_free(config.save_folder);
507         spamassassin_gtk_done();
508         procmsg_unregister_spam_learner(spamassassin_learn);
509         procmsg_spam_set_folder(NULL);
510         debug_print("SpamAssassin plugin unloaded\n");
511 }
512
513 const gchar *plugin_name(void)
514 {
515         return _("SpamAssassin");
516 }
517
518 const gchar *plugin_desc(void)
519 {
520         return _("This plugin can check all messages that are received from an "
521                  "IMAP, LOCAL or POP account for spam using a SpamAssassin "
522                  "server. You will need a SpamAssassin Server (spamd) running "
523                  "somewhere.\n"
524                  "\n"
525                  "It can also be used for marking messages as Ham or Spam.\n"
526                  "\n"
527                  "When a message is identified as spam it can be deleted or "
528                  "saved in a specially designated folder.\n"
529                  "\n"
530                  "Options can be found in /Configuration/Preferences/Plugins/SpamAssassin");
531 }
532
533 const gchar *plugin_type(void)
534 {
535         return "GTK2";
536 }
537
538 const gchar *plugin_licence(void)
539 {
540         return "GPL";
541 }
542
543 const gchar *plugin_version(void)
544 {
545         return VERSION;
546 }
547
548 struct PluginFeature *plugin_provides(void)
549 {
550         static struct PluginFeature features[] = 
551                 { {PLUGIN_FILTERING, N_("Spam detection")},
552                   {PLUGIN_FILTERING, N_("Spam learning")},
553                   {PLUGIN_NOTHING, NULL}};
554         return features;
555 }
556
557 void spamassassin_register_hook(void)
558 {
559         hook_id = hooks_register_hook(MAIL_FILTERING_HOOKLIST, mail_filtering_hook, NULL);
560         if (hook_id == -1) {
561                 g_warning("Failed to register mail filtering hook");
562                 config.process_emails = FALSE;
563         }
564 }
565
566 void spamassassin_unregister_hook(void)
567 {
568         if (hook_id != -1) {
569                 hooks_unregister_hook(MAIL_FILTERING_HOOKLIST, hook_id);
570         }
571 }