2006-08-29 [wwp] 2.4.0cvs110
[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                 gchar *msg = _("The SpamAssassin plugin couldn't filter "
275                                            "a message. The probable cause of the error "
276                                            "is an unreachable spamd daemon. Please make "
277                                            "sure spamd is running and accessible.");
278                 if (!prefs_common.no_recv_err_panel) {
279                         if (!warned_error) {
280                                 alertpanel_error(msg);
281                         }
282                         warned_error = TRUE;
283                 } else {
284                         gchar *tmp = g_strdup_printf("%s\n", msg);
285                         log_error(tmp);
286                         g_free(tmp);
287                 }
288         }
289         
290         return FALSE;
291 }
292
293 SpamAssassinConfig *spamassassin_get_config(void)
294 {
295         return &config;
296 }
297
298 gchar* spamassassin_create_tmp_spamc_wrapper(gboolean spam)
299 {
300         gchar *contents;
301         gchar *fname = get_tmp_file();
302
303         if (fname != NULL) {
304                 contents = g_strdup_printf(
305                                                 "spamc -d %s -p %u -u %s -t %u -s %u -L %s<\"$*\";exit $?",
306                                                 config.hostname, config.port, 
307                                                 config.username, config.timeout,
308                                                 config.max_size * 1024, spam?"spam":"ham");
309                 if (str_write_to_file(contents, fname) < 0) {
310                         g_free(fname);
311                         fname = NULL;
312                 }
313                 g_free(contents);
314         }
315         /* returned pointer must be free'ed by caller */
316         return fname;
317 }
318
319 int spamassassin_learn(MsgInfo *msginfo, GSList *msglist, gboolean spam)
320 {
321         gchar *cmd = NULL;
322         gchar *file = NULL;
323         const gchar *shell = g_getenv("SHELL");
324         gchar *spamc_wrapper = NULL;
325
326         if (msginfo == NULL && msglist == NULL) {
327                 return -1;
328         }
329
330         if (config.transport == SPAMASSASSIN_TRANSPORT_TCP
331         &&  prefs_common.work_offline
332         &&  !inc_offline_should_override(
333                 _("Sylpheed-Claws needs network access in order "
334                   "to feed this mail(s) to the remote learner."))) {
335                 return -1;
336         }
337
338         if (msginfo) {
339                 file = procmsg_get_message_file(msginfo);
340                 if (file == NULL) {
341                         return -1;
342                 }
343                 if (config.transport == SPAMASSASSIN_TRANSPORT_TCP) {
344                         spamc_wrapper = spamassassin_create_tmp_spamc_wrapper(spam);
345                         if (spamc_wrapper != NULL) {
346                                 cmd = g_strconcat(shell?shell:"sh", " ",
347                                                                 spamc_wrapper, " ", file, NULL);
348                         }
349                 } else {
350                         cmd = g_strdup_printf("sa-learn -u %s %s %s %s",
351                                                         config.username,
352                                                         prefs_common.work_offline?"-L":"",
353                                                         spam?"--spam":"--ham", file);
354                 }
355         }
356         if (msglist) {
357                 GSList *cur = msglist;
358                 MsgInfo *info;
359
360                 if (config.transport == SPAMASSASSIN_TRANSPORT_TCP) {
361                         /* execute n-times the spamc command */
362                         for (; cur; cur = cur->next) {
363                                 info = (MsgInfo *)cur->data;
364                                 gchar *tmpcmd = NULL;
365                                 gchar *tmpfile = get_tmp_file();
366
367                                 if (spamc_wrapper == NULL) {
368                                         spamc_wrapper = spamassassin_create_tmp_spamc_wrapper(spam);
369                                 }
370
371                                 if (spamc_wrapper && tmpfile &&
372                                 copy_file(procmsg_get_message_file(info), tmpfile, TRUE) == 0) {
373                                         tmpcmd = g_strconcat(shell?shell:"sh", " ", spamc_wrapper, " ",
374                                                                                 tmpfile, NULL);
375                                         debug_print("%s\n", tmpcmd);
376                                         execute_command_line(tmpcmd, FALSE);
377                                         g_free(tmpcmd);
378                                 }
379                                 g_free(tmpfile);
380                         }
381                         g_free(spamc_wrapper);
382                         return 0;
383                 } else {
384                         cmd = g_strdup_printf("sa-learn -u %s %s %s",
385                                         config.username,
386                                         prefs_common.work_offline?"-L":"",
387                                         spam?"--spam":"--ham");
388
389                         /* concatenate all message tmpfiles to the sa-learn command-line */
390                         for (; cur; cur = cur->next) {
391                                 info = (MsgInfo *)cur->data;
392                                 gchar *tmpcmd = NULL;
393                                 gchar *tmpfile = get_tmp_file();
394
395                                 if (tmpfile &&
396                                 copy_file(procmsg_get_message_file(info), tmpfile, TRUE) == 0) {                        
397                                         tmpcmd = g_strconcat(cmd, " ", tmpfile, NULL);
398                                         g_free(cmd);
399                                         cmd = tmpcmd;
400                                 }
401                                 g_free(tmpfile);
402                         }
403                 }
404         }
405         if (cmd == NULL) {
406                 return -1;
407         }
408         debug_print("%s\n", cmd);
409         /* only run sync calls to sa-learn/spamc to prevent system lockdown */
410         execute_command_line(cmd, FALSE);
411         g_free(cmd);
412         g_free(spamc_wrapper);
413
414         return 0;
415 }
416
417 void spamassassin_save_config(void)
418 {
419         PrefFile *pfile;
420         gchar *rcpath;
421
422         debug_print("Saving SpamAssassin Page\n");
423
424         rcpath = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, COMMON_RC, NULL);
425         pfile = prefs_write_open(rcpath);
426         g_free(rcpath);
427         if (!pfile || (prefs_set_block_label(pfile, "SpamAssassin") < 0))
428                 return;
429
430         if (prefs_write_param(param, pfile->fp) < 0) {
431                 g_warning("Failed to write SpamAssassin configuration to file\n");
432                 prefs_file_close_revert(pfile);
433                 return;
434         }
435         fprintf(pfile->fp, "\n");
436
437         prefs_file_close(pfile);
438 }
439
440 gboolean spamassassin_check_username(void)
441 {
442         if (config.username == NULL || config.username[0] == '\0') {
443                 config.username = (gchar*)g_get_user_name();
444                 if (config.username == NULL) {
445                         if (hook_id != -1) {
446                                 spamassassin_unregister_hook();
447                         }
448                         procmsg_unregister_spam_learner(spamassassin_learn);
449                         procmsg_spam_set_folder(NULL);
450                         return FALSE;
451                 }
452         }
453         return TRUE;
454 }
455
456 void spamassassin_set_message_callback(MessageCallback callback)
457 {
458         message_callback = callback;
459 }
460
461 gint plugin_init(gchar **error)
462 {
463         gchar *rcpath;
464
465         hook_id = -1;
466
467         if ((sylpheed_get_version() > VERSION_NUMERIC)) {
468                 *error = g_strdup("Your version of Sylpheed-Claws is newer than the version the SpamAssassin plugin was built with");
469                 return -1;
470         }
471
472         if ((sylpheed_get_version() < MAKE_NUMERIC_VERSION(0, 9, 3, 86))) {
473                 *error = g_strdup("Your version of Sylpheed-Claws is too old for the SpamAssassin plugin");
474                 return -1;
475         }
476
477         prefs_set_default(param);
478         rcpath = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, COMMON_RC, NULL);
479         prefs_read_config(param, "SpamAssassin", rcpath, NULL);
480         g_free(rcpath);
481         if (!spamassassin_check_username()) {
482                 *error = g_strdup("Failed to get username");
483                 return -1;
484         }
485         spamassassin_gtk_init();
486                 
487         debug_print("SpamAssassin plugin loaded\n");
488
489         if (config.process_emails) {
490                 spamassassin_register_hook();
491         }
492
493         if (!config.enable || config.transport == SPAMASSASSIN_DISABLED) {
494                 log_error(_("SpamAssassin plugin is loaded but disabled by its preferences.\n"));
495         }
496         else {
497                 if (config.transport == SPAMASSASSIN_TRANSPORT_TCP)
498                         debug_print("Enabling learner with a remote spamassassin server requires spamc/spamd 3.1.x\n");
499                 procmsg_register_spam_learner(spamassassin_learn);
500                 procmsg_spam_set_folder(config.save_folder);
501         }
502
503         return 0;
504         
505 }
506
507 void plugin_done(void)
508 {
509         if (hook_id != -1) {
510                 spamassassin_unregister_hook();
511         }
512         g_free(config.hostname);
513         g_free(config.save_folder);
514         spamassassin_gtk_done();
515         procmsg_unregister_spam_learner(spamassassin_learn);
516         procmsg_spam_set_folder(NULL);
517         debug_print("SpamAssassin plugin unloaded\n");
518 }
519
520 const gchar *plugin_name(void)
521 {
522         return _("SpamAssassin");
523 }
524
525 const gchar *plugin_desc(void)
526 {
527         return _("This plugin can check all messages that are received from an "
528                  "IMAP, LOCAL or POP account for spam using a SpamAssassin "
529                  "server. You will need a SpamAssassin Server (spamd) running "
530                  "somewhere.\n"
531                  "\n"
532                  "It can also be used for marking messages as Ham or Spam.\n"
533                  "\n"
534                  "When a message is identified as spam it can be deleted or "
535                  "saved in a specially designated folder.\n"
536                  "\n"
537                  "Options can be found in /Configuration/Preferences/Plugins/SpamAssassin");
538 }
539
540 const gchar *plugin_type(void)
541 {
542         return "GTK2";
543 }
544
545 const gchar *plugin_licence(void)
546 {
547         return "GPL";
548 }
549
550 const gchar *plugin_version(void)
551 {
552         return VERSION;
553 }
554
555 struct PluginFeature *plugin_provides(void)
556 {
557         static struct PluginFeature features[] = 
558                 { {PLUGIN_FILTERING, N_("Spam detection")},
559                   {PLUGIN_FILTERING, N_("Spam learning")},
560                   {PLUGIN_NOTHING, NULL}};
561         return features;
562 }
563
564 void spamassassin_register_hook(void)
565 {
566         hook_id = hooks_register_hook(MAIL_FILTERING_HOOKLIST, mail_filtering_hook, NULL);
567         if (hook_id == -1) {
568                 g_warning("Failed to register mail filtering hook");
569                 config.process_emails = FALSE;
570         }
571 }
572
573 void spamassassin_unregister_hook(void)
574 {
575         if (hook_id != -1) {
576                 hooks_unregister_hook(MAIL_FILTERING_HOOKLIST, hook_id);
577         }
578 }