* src/filtering.[ch]
[claws.git] / src / inc.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2002 Hiroyuki Yamamoto
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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #endif
23
24 #include "defs.h"
25
26 #include <glib.h>
27 #include <gtk/gtkmain.h>
28 #include <gtk/gtkwindow.h>
29 #include <gtk/gtksignal.h>
30 #include <gtk/gtkprogressbar.h>
31 #include <stdio.h>
32 #include <unistd.h>
33 #include <string.h>
34 #include <sys/types.h>
35 #include <sys/stat.h>
36 #include <sys/wait.h>
37 #include <signal.h>
38 #include <errno.h>
39
40 #include "intl.h"
41 #include "main.h"
42 #include "inc.h"
43 #include "mainwindow.h"
44 #include "folderview.h"
45 #include "summaryview.h"
46 #include "prefs_common.h"
47 #include "prefs_account.h"
48 #include "account.h"
49 #include "procmsg.h"
50 #include "socket.h"
51 #include "ssl.h"
52 #include "pop.h"
53 #include "recv.h"
54 #include "mbox.h"
55 #include "utils.h"
56 #include "gtkutils.h"
57 #include "statusbar.h"
58 #include "manage_window.h"
59 #include "stock_pixmap.h"
60 #include "progressdialog.h"
61 #include "inputdialog.h"
62 #include "alertpanel.h"
63 #include "filter.h"
64 #include "automaton.h"
65 #include "folder.h"
66 #include "filtering.h"
67 #include "selective_download.h"
68
69 static guint inc_lock_count = 0;
70
71 static GdkPixmap *currentxpm;
72 static GdkBitmap *currentxpmmask;
73 static GdkPixmap *errorxpm;
74 static GdkBitmap *errorxpmmask;
75 static GdkPixmap *okxpm;
76 static GdkBitmap *okxpmmask;
77
78 #define MSGBUFSIZE      8192
79
80 static void inc_finished                (MainWindow             *mainwin,
81                                          gboolean                new_messages);
82 static gint inc_account_mail            (PrefsAccount           *account,
83                                          MainWindow             *mainwin);
84
85 static IncProgressDialog *inc_progress_dialog_create    (void);
86 static void inc_progress_dialog_destroy (IncProgressDialog      *inc_dialog);
87
88 static IncSession *inc_session_new      (PrefsAccount           *account);
89 static void inc_session_destroy         (IncSession             *session);
90 static Pop3State *inc_pop3_state_new    (PrefsAccount           *account);
91 static void inc_pop3_state_destroy      (Pop3State              *state);
92 static gint inc_start                   (IncProgressDialog      *inc_dialog);
93 static IncState inc_pop3_session_do     (IncSession             *session);
94 static gint pop3_automaton_terminate    (SockInfo               *source,
95                                          Automaton              *atm);
96
97 static GHashTable *inc_get_uidl_table   (PrefsAccount           *ac_prefs);
98 static void inc_write_uidl_list         (Pop3State              *state);
99
100 static gboolean inc_pop3_recv_func      (SockInfo       *sock,
101                                          gint            count,
102                                          gint            read_bytes,
103                                          gpointer        data);
104
105 static void inc_put_error               (IncState        istate);
106
107 static void inc_cancel                  (GtkWidget      *widget,
108                                          gpointer        data);
109
110 static gint inc_spool                   (void);
111 static gint get_spool                   (FolderItem     *dest,
112                                          const gchar    *mbox);
113
114 static void inc_all_spool(void);
115 static void inc_autocheck_timer_set_interval    (guint           interval);
116 static gint inc_autocheck_func                  (gpointer        data);
117
118 #define FOLDER_SUMMARY_MISMATCH(f, s) \
119         (f) && (s) ? ((s)->newmsgs != (f)->new) || ((f)->unread != (s)->unread) || ((f)->total != (s)->messages) \
120         : FALSE
121         
122 /**
123  * inc_finished:
124  * @mainwin: Main window.
125  * @new_messages: TRUE if some messages have been received.
126  * 
127  * Update the folder view and the summary view after receiving
128  * messages.  If @new_messages is FALSE, this function avoids unneeded
129  * updating.
130  **/
131 static void inc_finished(MainWindow *mainwin, gboolean new_messages)
132 {
133         FolderItem *item;
134
135         if (prefs_common.scan_all_after_inc)
136                 folderview_check_new(NULL);
137
138         if (!new_messages && !prefs_common.scan_all_after_inc) return;
139
140         if (prefs_common.open_inbox_on_inc) {
141                 item = cur_account && cur_account->inbox
142                         ? folder_find_item_from_path(cur_account->inbox)
143                         : folder_get_default_inbox();
144                 if (FOLDER_SUMMARY_MISMATCH(item, mainwin->summaryview)) {      
145                         folderview_unselect(mainwin->folderview);
146                         folderview_select(mainwin->folderview, item);
147                 }       
148         } else {
149                 item = mainwin->summaryview->folder_item;
150                 if (FOLDER_SUMMARY_MISMATCH(item, mainwin->summaryview)) {
151                         folderview_unselect(mainwin->folderview);
152                         folderview_select(mainwin->folderview, item);
153                 }       
154         }
155 }
156
157 void inc_mail(MainWindow *mainwin)
158 {
159         gint new_msgs = 0;
160
161         if (inc_lock_count) return;
162
163         inc_autocheck_timer_remove();
164         summary_write_cache(mainwin->summaryview);
165         main_window_lock(mainwin);
166
167         if (prefs_common.use_extinc && prefs_common.extinc_cmd) {
168                 /* external incorporating program */
169                 if (execute_command_line(prefs_common.extinc_cmd, FALSE) < 0) {
170                         main_window_unlock(mainwin);
171                         inc_autocheck_timer_set();
172                         return;
173                 }
174
175                 if (prefs_common.inc_local)
176                         new_msgs = inc_spool();
177         } else {
178                 if (prefs_common.inc_local)
179                         new_msgs = inc_spool();
180
181                 new_msgs += inc_account_mail(cur_account, mainwin);
182         }
183
184         inc_finished(mainwin, new_msgs > 0);
185         main_window_unlock(mainwin);
186         inc_autocheck_timer_set();
187 }
188
189 gint inc_selective_download(MainWindow *mainwin, gint session_type)
190 {
191         PrefsAccount *account = cur_account;
192         gint new_msgs = 0;      
193
194         account->session_type = session_type;
195         new_msgs = inc_account_mail(account, mainwin);
196         account->session_type = RETR_NORMAL;
197         
198         return new_msgs;
199 }
200
201 static gint inc_account_mail(PrefsAccount *account, MainWindow *mainwin)
202 {
203         IncProgressDialog *inc_dialog;
204         IncSession *session;
205         gchar *text[3];
206
207         if (account->protocol == A_IMAP4 || account->protocol == A_NNTP) {
208                 folderview_check_new(FOLDER(account->folder));
209                 return 1;
210         }
211
212         session = inc_session_new(account);
213         if (!session) return 0;
214
215         inc_dialog = inc_progress_dialog_create();
216         inc_dialog->queue_list = g_list_append(inc_dialog->queue_list, session);
217         inc_dialog->mainwin = mainwin;
218         session->data = inc_dialog;
219
220         text[0] = NULL;
221         text[1] = account->account_name;
222         text[2] = _("Standby");
223         gtk_clist_append(GTK_CLIST(inc_dialog->dialog->clist), text);
224
225         return inc_start(inc_dialog);
226 }
227
228 void inc_all_account_mail(MainWindow *mainwin)
229 {
230         GList *list, *queue_list = NULL;
231         IncProgressDialog *inc_dialog;
232         gint new_msgs = 0;
233
234         if (inc_lock_count) return;
235
236         inc_autocheck_timer_remove();
237         summary_write_cache(mainwin->summaryview);
238         main_window_lock(mainwin);
239
240         if (prefs_common.inc_local)
241                 new_msgs = inc_spool();
242
243         list = account_get_list();
244         if (!list) {
245                 inc_finished(mainwin, new_msgs > 0);
246                 main_window_unlock(mainwin);
247                 inc_autocheck_timer_set();
248                 return;
249         }
250
251         /* check IMAP4 folders */
252         for (; list != NULL; list = list->next) {
253                 PrefsAccount *account = list->data;
254                 if ((account->protocol == A_IMAP4 ||
255                      account->protocol == A_NNTP) && account->recv_at_getall)
256                         folderview_check_new(FOLDER(account->folder));
257         }
258
259         /* check POP3 accounts */
260         for (list = account_get_list(); list != NULL; list = list->next) {
261                 IncSession *session;
262                 PrefsAccount *account = list->data;
263                 account->session_type = RETR_NORMAL;
264                 if (account->recv_at_getall) {
265                         session = inc_session_new(account);
266                         if (session)
267                                 queue_list = g_list_append(queue_list, session);
268                 }
269         }
270
271         if (!queue_list) {
272                 inc_finished(mainwin, new_msgs > 0);
273                 main_window_unlock(mainwin);
274                 inc_autocheck_timer_set();
275                 return;
276         }
277
278         inc_dialog = inc_progress_dialog_create();
279         inc_dialog->queue_list = queue_list;
280         inc_dialog->mainwin = mainwin;
281         for (list = queue_list; list != NULL; list = list->next) {
282                 IncSession *session = list->data;
283                 gchar *text[3];
284
285                 session->data = inc_dialog;
286
287                 text[0] = NULL;
288                 text[1] = session->pop3_state->ac_prefs->account_name;
289                 text[2] = _("Standby");
290                 gtk_clist_append(GTK_CLIST(inc_dialog->dialog->clist), text);
291         }
292
293         new_msgs += inc_start(inc_dialog);
294
295         inc_finished(mainwin, new_msgs > 0);
296         main_window_unlock(mainwin);
297         inc_autocheck_timer_set();
298 }
299
300 static IncProgressDialog *inc_progress_dialog_create(void)
301 {
302         IncProgressDialog *dialog;
303         ProgressDialog *progress;
304
305         dialog = g_new0(IncProgressDialog, 1);
306
307         progress = progress_dialog_create();
308         gtk_window_set_title(GTK_WINDOW(progress->window),
309                              _("Retrieving new messages"));
310         gtk_signal_connect(GTK_OBJECT(progress->cancel_btn), "clicked",
311                            GTK_SIGNAL_FUNC(inc_cancel), dialog);
312         gtk_signal_connect(GTK_OBJECT(progress->window), "delete_event",
313                            GTK_SIGNAL_FUNC(gtk_true), NULL);
314         /* manage_window_set_transient(GTK_WINDOW(progress->window)); */
315
316         progress_dialog_set_value(progress, 0.0);
317
318         stock_pixmap_gdk(progress->clist, STOCK_PIXMAP_COMPLETE,
319                          &okxpm, &okxpmmask);
320         stock_pixmap_gdk(progress->clist, STOCK_PIXMAP_CONTINUE,
321                          &currentxpm, &currentxpmmask);
322         stock_pixmap_gdk(progress->clist, STOCK_PIXMAP_ERROR,
323                          &errorxpm, &errorxpmmask);
324
325         if (prefs_common.recv_dialog_mode == RECV_DIALOG_ALWAYS ||
326             (prefs_common.recv_dialog_mode == RECV_DIALOG_ACTIVE &&
327              manage_window_get_focus_window())) {
328                 dialog->show_dialog = TRUE;
329                 gtk_widget_show_now(progress->window);
330         }
331
332         dialog->dialog = progress;
333         dialog->queue_list = NULL;
334
335         return dialog;
336 }
337
338 static void inc_progress_dialog_clear(IncProgressDialog *inc_dialog)
339 {
340         progress_dialog_set_value(inc_dialog->dialog, 0.0);
341         progress_dialog_set_label(inc_dialog->dialog, "");
342         gtk_progress_bar_update
343                 (GTK_PROGRESS_BAR(inc_dialog->mainwin->progressbar), 0.0);
344 }
345
346 static void inc_progress_dialog_destroy(IncProgressDialog *inc_dialog)
347 {
348         g_return_if_fail(inc_dialog != NULL);
349
350         gtk_progress_bar_update
351                 (GTK_PROGRESS_BAR(inc_dialog->mainwin->progressbar), 0.0);
352         progress_dialog_destroy(inc_dialog->dialog);
353
354         g_free(inc_dialog);
355 }
356
357 static IncSession *inc_session_new(PrefsAccount *account)
358 {
359         IncSession *session;
360
361         g_return_val_if_fail(account != NULL, NULL);
362
363         if (account->protocol != A_POP3 && account->protocol != A_APOP)
364                 return NULL;
365         if (!account->recv_server || !account->userid)
366                 return NULL;
367
368         session = g_new0(IncSession, 1);
369         session->pop3_state = inc_pop3_state_new(account);
370         session->pop3_state->session = session;
371
372         return session;
373 }
374
375 static void inc_session_destroy(IncSession *session)
376 {
377         g_return_if_fail(session != NULL);
378
379         inc_pop3_state_destroy(session->pop3_state);
380         g_free(session);
381 }
382
383 static Pop3State *inc_pop3_state_new(PrefsAccount *account)
384 {
385         Pop3State *state;
386
387         state = g_new0(Pop3State, 1);
388
389         state->ac_prefs = account;
390         state->folder_table = g_hash_table_new(NULL, NULL);
391         state->id_table = inc_get_uidl_table(account);
392         state->id_list = NULL;
393         state->new_id_list = NULL;
394         state->inc_state = INC_SUCCESS;
395
396         return state;
397 }
398
399 static void inc_pop3_state_destroy(Pop3State *state)
400 {
401         g_hash_table_destroy(state->folder_table);
402         g_free(state->sizes);
403
404         if (state->id_table) {
405                 hash_free_strings(state->id_table);
406                 g_hash_table_destroy(state->id_table);
407         }
408         slist_free_strings(state->id_list);
409         slist_free_strings(state->new_id_list);
410         g_slist_free(state->id_list);
411         g_slist_free(state->new_id_list);
412
413         g_free(state->greeting);
414         g_free(state->user);
415         g_free(state->pass);
416         g_free(state->prev_folder);
417
418         g_free(state);
419 }
420
421 static gint inc_start(IncProgressDialog *inc_dialog)
422 {
423         IncSession *session;
424         GtkCList *clist = GTK_CLIST(inc_dialog->dialog->clist);
425         Pop3State *pop3_state;
426         IncState inc_state;
427         gint num = 0;
428         gint error_num = 0;
429         gint new_msgs = 0;
430
431         while (inc_dialog->queue_list != NULL) {
432                 session = inc_dialog->queue_list->data;
433                 pop3_state = session->pop3_state;
434
435                 inc_progress_dialog_clear(inc_dialog);
436
437                 gtk_clist_moveto(clist, num, -1, 1.0, 0.0);
438
439                 pop3_state->user = g_strdup(pop3_state->ac_prefs->userid);
440                 if (pop3_state->ac_prefs->passwd)
441                         pop3_state->pass =
442                                 g_strdup(pop3_state->ac_prefs->passwd);
443                 else if (pop3_state->ac_prefs->tmp_pass)
444                         pop3_state->pass =
445                                 g_strdup(pop3_state->ac_prefs->tmp_pass);
446                 else {
447                         gchar *pass;
448
449                         pass = input_dialog_query_password
450                                 (pop3_state->ac_prefs->recv_server,
451                                  pop3_state->user);
452
453                         if (inc_dialog->show_dialog)
454                                 manage_window_focus_in
455                                         (inc_dialog->mainwin->window,
456                                          NULL, NULL);
457                         if (pass) {
458                                 pop3_state->ac_prefs->tmp_pass = g_strdup(pass);
459                                 pop3_state->pass = pass;
460                         } else {
461                                 inc_session_destroy(session);
462                                 inc_dialog->queue_list = g_list_remove
463                                         (inc_dialog->queue_list, session);
464                                 continue;
465                         }
466                 }
467
468                 gtk_clist_set_pixmap(clist, num, 0, currentxpm, currentxpmmask);
469                 gtk_clist_set_text(clist, num, 2, _("Retrieving"));
470
471                 /* begin POP3 session */
472                 inc_state = inc_pop3_session_do(session);
473
474                 if (inc_state == INC_SUCCESS) {
475                         gtk_clist_set_pixmap(clist, num, 0, okxpm, okxpmmask);
476                         gtk_clist_set_text(clist, num, 2, _("Done"));
477                 } else if (inc_state == INC_CANCEL) {
478                         gtk_clist_set_pixmap(clist, num, 0, okxpm, okxpmmask);
479                         gtk_clist_set_text(clist, num, 2, _("Cancelled"));
480                 } else {
481                         gtk_clist_set_pixmap(clist, num, 0, errorxpm, errorxpmmask);
482                         if (inc_state == INC_CONNECT_ERROR)
483                                 gtk_clist_set_text(clist, num, 2,
484                                                    _("Connection failed"));
485                         else if (inc_state == INC_AUTH_FAILED)
486                                 gtk_clist_set_text(clist, num, 2,
487                                                    _("Auth failed"));
488                         else
489                                 gtk_clist_set_text(clist, num, 2, _("Error"));
490                 }
491
492                 if (pop3_state->error_val == PS_AUTHFAIL) {
493                         if(!prefs_common.noerrorpanel) {
494                                 if((prefs_common.recv_dialog_mode == RECV_DIALOG_ALWAYS) ||
495                                     ((prefs_common.recv_dialog_mode == RECV_DIALOG_ACTIVE) && focus_window)) {
496                                         manage_window_focus_in(inc_dialog->dialog->window, NULL, NULL);
497                                 }
498                                 alertpanel_error
499                                         (_("Authorization for %s on %s failed"),
500                                          pop3_state->user,
501                                          pop3_state->ac_prefs->recv_server);
502                         }
503                 }
504
505                 statusbar_pop_all();
506
507                 /* CLAWS: perform filtering actions on dropped message */
508                 if (global_processing != NULL) {
509                         FolderItem *processing, *inbox;
510                         Folder *folder;
511                         MsgInfo *msginfo;
512                         GSList *msglist, *msglist_element;
513
514                         /* CLAWS: get default inbox (perhaps per account) */
515                         if (pop3_state->ac_prefs->inbox) {
516                                 /* CLAWS: get destination folder / mailbox */
517                                 inbox = folder_find_item_from_identifier(pop3_state->ac_prefs->inbox);
518                                 if (!inbox)
519                                         inbox = folder_get_default_inbox();
520                         } else
521                                 inbox = folder_get_default_inbox();
522
523                         /* get list of messages in processing */
524                         processing = folder_get_default_processing();
525                         folder_item_scan(processing);
526                         folder = processing->folder;
527                         msglist = folder->get_msg_list(folder, processing, FALSE);
528
529                         /* process messages */
530                         for(msglist_element = msglist; msglist_element != NULL; msglist_element = msglist_element->next) {
531                                 msginfo = (MsgInfo *) msglist_element->data;
532                                 /* filter if enabled in prefs or move to inbox if not */
533                                 if(pop3_state->ac_prefs->filter_on_recv) {
534                                         filter_message_by_msginfo_with_inbox(global_processing, msginfo,
535                                                                              pop3_state->folder_table,
536                                                                              inbox);
537                                 } else {
538                                         folder_item_move_msg(inbox, msginfo);
539                                         g_hash_table_insert(pop3_state->folder_table, inbox,
540                                                             GINT_TO_POINTER(1));
541                                 }
542                                 procmsg_msginfo_free(msginfo);
543                         }
544                         g_slist_free(msglist);
545                 }
546
547
548                 new_msgs += pop3_state->cur_total_num;
549
550                 if (!prefs_common.scan_all_after_inc) {
551                         folder_item_scan_foreach(pop3_state->folder_table);
552                         folderview_update_item_foreach
553                                 (pop3_state->folder_table);
554                 }
555
556                 if (pop3_state->error_val == PS_AUTHFAIL &&
557                     pop3_state->ac_prefs->tmp_pass) {
558                         g_free(pop3_state->ac_prefs->tmp_pass);
559                         pop3_state->ac_prefs->tmp_pass = NULL;
560                 }
561
562                 inc_write_uidl_list(pop3_state);
563
564                 if (inc_state != INC_SUCCESS && inc_state != INC_CANCEL) {
565                         error_num++;
566                         if (inc_state == INC_NOSPACE) {
567                                 inc_put_error(inc_state);
568                                 break;
569                         }
570                 }
571
572                 inc_session_destroy(session);
573                 inc_dialog->queue_list =
574                         g_list_remove(inc_dialog->queue_list, session);
575
576                 num++;
577         }
578
579         if (error_num && !prefs_common.noerrorpanel) {
580                 if (inc_dialog->show_dialog)
581                         manage_window_focus_in(inc_dialog->dialog->window,
582                                                NULL, NULL);
583                 alertpanel_error(_("Some errors occured while getting mail."));
584                 if (inc_dialog->show_dialog)
585                         manage_window_focus_out(inc_dialog->dialog->window,
586                                                 NULL, NULL);
587         }
588
589         while (inc_dialog->queue_list != NULL) {
590                 session = inc_dialog->queue_list->data;
591                 inc_session_destroy(session);
592                 inc_dialog->queue_list =
593                         g_list_remove(inc_dialog->queue_list, session);
594         }
595
596         inc_progress_dialog_destroy(inc_dialog);
597
598         return new_msgs;
599 }
600
601 static IncState inc_pop3_session_do(IncSession *session)
602 {
603         Pop3State *pop3_state = session->pop3_state;
604         IncProgressDialog *inc_dialog = (IncProgressDialog *)session->data;
605         Automaton *atm;
606         SockInfo *sockinfo;
607         gint i;
608         gchar *server;
609         gushort port;
610         gchar *buf;
611         static AtmHandler handlers[] = {
612                 pop3_greeting_recv      ,
613                 pop3_getauth_user_send  , pop3_getauth_user_recv,
614                 pop3_getauth_pass_send  , pop3_getauth_pass_recv,
615                 pop3_getauth_apop_send  , pop3_getauth_apop_recv,
616                 pop3_getrange_stat_send , pop3_getrange_stat_recv,
617                 pop3_getrange_last_send , pop3_getrange_last_recv,
618                 pop3_getrange_uidl_send , pop3_getrange_uidl_recv,
619                 pop3_getsize_list_send  , pop3_getsize_list_recv,
620                 pop3_top_send           , pop3_top_recv,
621                 pop3_retr_send          , pop3_retr_recv,
622                 pop3_delete_send        , pop3_delete_recv,
623                 pop3_logout_send        , pop3_logout_recv
624         };
625
626         debug_print(_("getting new messages of account %s...\n"),
627                     pop3_state->ac_prefs->account_name);
628
629         atm = automaton_create(N_POP3_PHASE);
630
631         session->atm = atm;
632         atm->data = pop3_state;
633
634         buf = g_strdup_printf(_("%s: Retrieving new messages"),
635                               pop3_state->ac_prefs->recv_server);
636         gtk_window_set_title(GTK_WINDOW(inc_dialog->dialog->window), buf);
637         g_free(buf);
638
639         for (i = POP3_GREETING_RECV; i < N_POP3_PHASE; i++)
640                 atm->state[i].handler = handlers[i];
641         atm->state[POP3_GREETING_RECV].condition = GDK_INPUT_READ;
642         for (i = POP3_GETAUTH_USER_SEND; i < N_POP3_PHASE; ) {
643                 atm->state[i++].condition = GDK_INPUT_WRITE;
644                 atm->state[i++].condition = GDK_INPUT_READ;
645         }
646
647         atm->terminate = (AtmHandler)pop3_automaton_terminate;
648
649         atm->num = POP3_GREETING_RECV;
650
651         server = pop3_state->ac_prefs->recv_server;
652 #if USE_SSL
653         port = pop3_state->ac_prefs->set_popport ?
654                 pop3_state->ac_prefs->popport :
655                 pop3_state->ac_prefs->ssl_pop ? 995 : 110;
656 #else
657         port = pop3_state->ac_prefs->set_popport ?
658                 pop3_state->ac_prefs->popport : 110;
659 #endif
660
661         buf = g_strdup_printf(_("Connecting to POP3 server: %s ..."), server);
662         log_message("%s\n", buf);
663         progress_dialog_set_label(inc_dialog->dialog, buf);
664         g_free(buf);
665         GTK_EVENTS_FLUSH();
666         statusbar_pop_all();
667
668         if ((sockinfo = sock_connect(server, port)) == NULL) {
669                 log_warning(_("Can't connect to POP3 server: %s:%d\n"),
670                             server, port);
671                 if(!prefs_common.noerrorpanel) {
672                         if((prefs_common.recv_dialog_mode == RECV_DIALOG_ALWAYS) ||
673                             ((prefs_common.recv_dialog_mode == RECV_DIALOG_ACTIVE) && focus_window)) {
674                                 manage_window_focus_in(inc_dialog->dialog->window, NULL, NULL);
675                         }
676                         alertpanel_error(_("Can't connect to POP3 server: %s:%d"),
677                                          server, port);
678                         manage_window_focus_out(inc_dialog->dialog->window, NULL, NULL);
679                 }
680                 pop3_automaton_terminate(NULL, atm);
681                 automaton_destroy(atm);
682                 return INC_CONNECT_ERROR;
683         }
684
685 #if USE_SSL
686         if (pop3_state->ac_prefs->ssl_pop && !ssl_init_socket(sockinfo)) {
687                 pop3_automaton_terminate(NULL, atm);
688                 automaton_destroy(atm);
689                 return INC_CONNECT_ERROR;
690         }
691 #endif
692
693         /* :WK: Hmmm, with the later sock_gdk_input, we have 2 references
694          * to the sock structure - implement a reference counter?? */
695         pop3_state->sockinfo = sockinfo;
696         atm->help_sock = sockinfo;
697
698         log_verbosity_set(TRUE);
699         recv_set_ui_func(inc_pop3_recv_func, session);
700
701         atm->tag = sock_gdk_input_add(sockinfo,
702                                       atm->state[atm->num].condition,
703                                       automaton_input_cb, atm);
704
705         while (!atm->terminated)
706                 gtk_main_iteration();
707
708         log_verbosity_set(FALSE);
709         recv_set_ui_func(NULL, NULL);
710
711         automaton_destroy(atm);
712
713         return pop3_state->inc_state;
714 }
715
716 static gint pop3_automaton_terminate(SockInfo *source, Automaton *atm)
717 {
718         if (atm->terminated) return 0;
719
720         if (atm->tag > 0) {
721                 gdk_input_remove(atm->tag);
722                 atm->tag = 0;
723         }
724         if (atm->timeout_tag > 0) {
725                 gtk_timeout_remove(atm->timeout_tag);
726                 atm->timeout_tag = 0;
727         }
728         if (source)
729                 sock_close(source);
730
731         atm->terminated = TRUE;
732
733         return 0;
734 }
735
736 static GHashTable *inc_get_uidl_table(PrefsAccount *ac_prefs)
737 {
738         GHashTable *table;
739         gchar *path;
740         FILE *fp;
741         gchar buf[IDLEN + 3];
742
743         path = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
744                            "uidl-", ac_prefs->recv_server,
745                            "-", ac_prefs->userid, NULL);
746         if ((fp = fopen(path, "r")) == NULL) {
747                 if (ENOENT != errno) FILE_OP_ERROR(path, "fopen");
748                 g_free(path);
749                 return NULL;
750         }
751         g_free(path);
752
753         table = g_hash_table_new(g_str_hash, g_str_equal);
754
755         while (fgets(buf, sizeof(buf), fp) != NULL) {
756                 strretchomp(buf);
757                 g_hash_table_insert(table, g_strdup(buf), GINT_TO_POINTER(1));
758         }
759
760         fclose(fp);
761
762         return table;
763 }
764
765 static void inc_write_uidl_list(Pop3State *state)
766 {
767         gchar *path;
768         FILE *fp;
769         GSList *cur;
770
771         if (!state->id_list) return;
772
773         path = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
774                            "uidl-", state->ac_prefs->recv_server,
775                            "-", state->user, NULL);
776         if ((fp = fopen(path, "w")) == NULL) {
777                 FILE_OP_ERROR(path, "fopen");
778                 g_free(path);
779                 return;
780         }
781
782         for (cur = state->id_list; cur != NULL; cur = cur->next) {
783                 if (fputs((gchar *)cur->data, fp) == EOF) {
784                         FILE_OP_ERROR(path, "fputs");
785                         break;
786                 }
787                 if (fputc('\n', fp) == EOF) {
788                         FILE_OP_ERROR(path, "fputc");
789                         break;
790                 }
791         }
792
793         if (fclose(fp) == EOF) FILE_OP_ERROR(path, "fclose");
794         g_free(path);
795 }
796
797 static gboolean inc_pop3_recv_func(SockInfo *sock, gint count, gint read_bytes,
798                                    gpointer data)
799 {
800         gchar buf[MSGBUFSIZE];
801         IncSession *session = (IncSession *)data;
802         Pop3State *state = session->pop3_state;
803         IncProgressDialog *inc_dialog = session->data;
804         ProgressDialog *dialog = inc_dialog->dialog;
805         gint cur_total;
806         gchar *total_size;
807
808         cur_total = state->cur_total_bytes + read_bytes;
809         if (cur_total > state->total_bytes)
810                 cur_total = state->total_bytes;
811
812         Xstrdup_a(total_size, to_human_readable(state->total_bytes),
813                   return FALSE);
814         g_snprintf(buf, sizeof(buf),
815                    _("Retrieving message (%d / %d) (%s / %s)"),
816                    state->cur_msg, state->count,
817                    to_human_readable(cur_total), total_size);
818         progress_dialog_set_label(dialog, buf);
819
820         progress_dialog_set_percentage
821                 (dialog, (gfloat)cur_total / (gfloat)state->total_bytes);
822         gtk_progress_bar_update
823                 (GTK_PROGRESS_BAR(inc_dialog->mainwin->progressbar),
824                  (gfloat)cur_total / (gfloat)state->total_bytes);
825         GTK_EVENTS_FLUSH();
826
827         if (state->inc_state == INC_CANCEL)
828                 return FALSE;
829         else
830                 return TRUE;
831 }
832
833 void inc_progress_update(Pop3State *state, Pop3Phase phase)
834 {
835         gchar buf[MSGBUFSIZE];
836         IncProgressDialog *inc_dialog = state->session->data;
837         ProgressDialog *dialog = inc_dialog->dialog;
838         gchar *total_size;
839
840         switch (phase) {
841         case POP3_GREETING_RECV:
842                 break;
843         case POP3_GETAUTH_USER_SEND:
844         case POP3_GETAUTH_USER_RECV:
845         case POP3_GETAUTH_PASS_SEND:
846         case POP3_GETAUTH_PASS_RECV:
847         case POP3_GETAUTH_APOP_SEND:
848         case POP3_GETAUTH_APOP_RECV:
849                 progress_dialog_set_label(dialog, _("Authenticating..."));
850                 break;
851         case POP3_GETRANGE_STAT_SEND:
852         case POP3_GETRANGE_STAT_RECV:
853                 progress_dialog_set_label
854                         (dialog, _("Getting the number of new messages (STAT)..."));
855                 break;
856         case POP3_GETRANGE_LAST_SEND:
857         case POP3_GETRANGE_LAST_RECV:
858                 progress_dialog_set_label
859                         (dialog, _("Getting the number of new messages (LAST)..."));
860                 break;
861         case POP3_GETRANGE_UIDL_SEND:
862         case POP3_GETRANGE_UIDL_RECV:
863                 progress_dialog_set_label
864                         (dialog, _("Getting the number of new messages (UIDL)..."));
865                 break;
866         case POP3_GETSIZE_LIST_SEND:
867         case POP3_GETSIZE_LIST_RECV:
868                 progress_dialog_set_label
869                         (dialog, _("Getting the size of messages (LIST)..."));
870                 break;
871         case POP3_TOP_SEND:
872         case POP3_TOP_RECV:
873                 g_snprintf(buf, sizeof(buf),
874                            _("Retrieving header (%d / %d)"),
875                            state->cur_msg, state->count);
876                 progress_dialog_set_label (dialog, buf);
877                 progress_dialog_set_percentage
878                         (dialog,
879                          (gfloat)(state->cur_msg) /
880                          (gfloat)(state->count));
881                 gtk_progress_bar_update 
882                         (GTK_PROGRESS_BAR(inc_dialog->mainwin->progressbar),
883                          (gfloat)(state->cur_msg) /
884                          (gfloat)(state->count));
885                 break;
886         case POP3_RETR_SEND:
887         case POP3_RETR_RECV:
888                 Xstrdup_a(total_size, to_human_readable(state->total_bytes), return);
889                 g_snprintf(buf, sizeof(buf),
890                            _("Retrieving message (%d / %d) (%s / %s)"),
891                            state->cur_msg, state->count,
892                            to_human_readable(state->cur_total_bytes),
893                            total_size);
894                 progress_dialog_set_label(dialog, buf);
895                 progress_dialog_set_percentage
896                         (dialog,
897                          (gfloat)(state->cur_total_bytes) /
898                          (gfloat)(state->total_bytes));
899                 gtk_progress_bar_update
900                         (GTK_PROGRESS_BAR(inc_dialog->mainwin->progressbar),
901                          (gfloat)(state->cur_total_bytes) /
902                          (gfloat)(state->total_bytes));
903                 break;
904         case POP3_DELETE_SEND:
905         case POP3_DELETE_RECV:
906                 progress_dialog_set_label(dialog, _("Deleting message"));
907                 break;
908         case POP3_LOGOUT_SEND:
909         case POP3_LOGOUT_RECV:
910                 progress_dialog_set_label(dialog, _("Quitting"));
911                 break;
912         default:
913                 break;
914         }
915 }
916
917 gint inc_drop_message(const gchar *file, Pop3State *state)
918 {
919         FolderItem *inbox;
920         FolderItem *dropfolder;
921         gint val;
922         gint msgnum;
923
924         /* CLAWS: get default inbox (perhaps per account) */
925         if (state->ac_prefs->inbox) {
926                 /* CLAWS: get destination folder / mailbox */
927                 inbox = folder_find_item_from_identifier(state->ac_prefs->inbox);
928                 if (!inbox)
929                         inbox = folder_get_default_inbox();
930         } else
931                 inbox = folder_get_default_inbox();
932         if (!inbox) {
933                 unlink(file);
934                 return -1;
935         }
936
937         /* CLAWS: claws uses a global .processing folder for the filtering. */
938         if (global_processing == NULL) {
939                 if (state->ac_prefs->filter_on_recv) {
940                         dropfolder =
941                                 filter_get_dest_folder(prefs_common.fltlist, file);
942                         if (!dropfolder) dropfolder = inbox;
943                         else if (!strcmp(dropfolder->path, FILTER_NOT_RECEIVE)) {
944                                 g_warning(_("a message won't be received\n"));
945                                 return 1;
946                         }
947                 } else
948                         dropfolder = inbox;
949         } else {
950                 dropfolder = folder_get_default_processing();
951         }
952
953         val = GPOINTER_TO_INT(g_hash_table_lookup
954                               (state->folder_table, dropfolder));
955         if (val == 0) {
956                 folder_item_scan(dropfolder);
957                 g_hash_table_insert(state->folder_table, dropfolder,
958                                     GINT_TO_POINTER(1));
959         }
960         
961         /* add msg file to drop folder */
962         if ((msgnum = folder_item_add_msg(dropfolder, file, TRUE)) < 0) {
963                 unlink(file);
964                 return -1;
965         }
966
967         return 0;
968 }
969
970 static void inc_put_error(IncState istate)
971 {
972         switch (istate) {
973         case INC_ERROR:
974                 if(!prefs_common.noerrorpanel) {
975                         alertpanel_error(_("Error occurred while processing mail."));
976                 }
977                 break;
978         case INC_NOSPACE:
979                 alertpanel_error(_("No disk space left."));
980                 break;
981         default:
982                 break;
983         }
984 }
985
986 static void inc_cancel(GtkWidget *widget, gpointer data)
987 {
988         IncProgressDialog *dialog = data;
989         IncSession *session = dialog->queue_list->data;
990         SockInfo *sockinfo = session->pop3_state->sockinfo;
991
992         if (!sockinfo || session->atm->terminated == TRUE) return;
993
994         session->pop3_state->inc_state = INC_CANCEL;
995         pop3_automaton_terminate(sockinfo, session->atm);
996         session->pop3_state->sockinfo = NULL;
997 }
998
999 static gint inc_spool(void)
1000 {
1001         gchar *mbox, *logname;
1002         gint msgs;
1003
1004         logname = g_get_user_name();
1005         mbox = g_strconcat(prefs_common.spool_path
1006                            ? prefs_common.spool_path : DEFAULT_SPOOL_PATH,
1007                            G_DIR_SEPARATOR_S, logname, NULL);
1008         msgs = get_spool(folder_get_default_inbox(), mbox);
1009         g_free(mbox);
1010
1011         return msgs;
1012 }
1013
1014 static void inc_spool_account(PrefsAccount *account)
1015 {
1016         FolderItem *inbox;
1017         FolderItem *dropfolder;
1018         gint val;
1019
1020         if (account->inbox) {
1021                 inbox = folder_find_item_from_path(account->inbox);
1022                 if (!inbox)
1023                         inbox = folder_get_default_inbox();
1024         } else
1025                 inbox = folder_get_default_inbox();
1026
1027         get_spool(inbox, account->local_mbox);
1028 }
1029
1030 static void inc_all_spool(void)
1031 {
1032         GList *list = NULL;
1033
1034         list = account_get_list();
1035         if (!list) return;
1036
1037         for (; list != NULL; list = list->next) {
1038                 IncSession *session;
1039                 PrefsAccount *account = list->data;
1040
1041                 if (account->protocol == A_LOCAL)
1042                         inc_spool_account(account);
1043         }
1044 }
1045
1046 static gint get_spool(FolderItem *dest, const gchar *mbox)
1047 {
1048         gint msgs, size;
1049         gint lockfd;
1050         gchar tmp_mbox[MAXPATHLEN + 1];
1051         GHashTable *folder_table = NULL;
1052
1053         g_return_val_if_fail(dest != NULL, -1);
1054         g_return_val_if_fail(mbox != NULL, -1);
1055
1056         if (!is_file_exist(mbox) || (size = get_file_size(mbox)) == 0) {
1057                 debug_print(_("no messages in local mailbox.\n"));
1058                 return 0;
1059         } else if (size < 0)
1060                 return -1;
1061
1062         if ((lockfd = lock_mbox(mbox, LOCK_FLOCK)) < 0)
1063                 return -1;
1064
1065         g_snprintf(tmp_mbox, sizeof(tmp_mbox), "%s%ctmpmbox%d",
1066                    get_rc_dir(), G_DIR_SEPARATOR, (gint)mbox);
1067
1068         if (copy_mbox(mbox, tmp_mbox) < 0)
1069                 return -1;
1070
1071         debug_print(_("Getting new messages from %s into %s...\n"),
1072                     mbox, dest->path);
1073
1074         if (prefs_common.filter_on_inc)
1075                 folder_table = g_hash_table_new(NULL, NULL);
1076         msgs = proc_mbox(dest, tmp_mbox, folder_table);
1077
1078         unlink(tmp_mbox);
1079         if (msgs >= 0) empty_mbox(mbox);
1080         unlock_mbox(mbox, lockfd, LOCK_FLOCK);
1081
1082         if (folder_table) {
1083                 if (!prefs_common.scan_all_after_inc) {
1084                 g_hash_table_insert(folder_table, dest,
1085                                     GINT_TO_POINTER(1));
1086                         folder_item_scan_foreach(folder_table);
1087                         folderview_update_item_foreach(folder_table);
1088                 }
1089                 g_hash_table_destroy(folder_table);
1090         } else if (!prefs_common.scan_all_after_inc) {
1091                 folder_item_scan(dest);
1092                 folderview_update_item(dest, FALSE);
1093         }
1094
1095         return msgs;
1096 }
1097
1098 void inc_lock(void)
1099 {
1100         inc_lock_count++;
1101 }
1102
1103 void inc_unlock(void)
1104 {
1105         if (inc_lock_count > 0)
1106                 inc_lock_count--;
1107 }
1108
1109 static guint autocheck_timer = 0;
1110 static gpointer autocheck_data = NULL;
1111
1112 void inc_autocheck_timer_init(MainWindow *mainwin)
1113 {
1114         autocheck_data = mainwin;
1115         inc_autocheck_timer_set();
1116 }
1117
1118 static void inc_autocheck_timer_set_interval(guint interval)
1119 {
1120         inc_autocheck_timer_remove();
1121
1122         if (prefs_common.autochk_newmail && autocheck_data) {
1123                 autocheck_timer = gtk_timeout_add
1124                         (interval, inc_autocheck_func, autocheck_data);
1125                 debug_print("added timer = %d\n", autocheck_timer);
1126         }
1127 }
1128
1129 void inc_autocheck_timer_set(void)
1130 {
1131         inc_autocheck_timer_set_interval(prefs_common.autochk_itv * 60000);
1132 }
1133
1134 void inc_autocheck_timer_remove(void)
1135 {
1136         if (autocheck_timer) {
1137                 debug_print("removed timer = %d\n", autocheck_timer);
1138                 gtk_timeout_remove(autocheck_timer);
1139                 autocheck_timer = 0;
1140         }
1141 }
1142
1143 static gint inc_autocheck_func(gpointer data)
1144 {
1145         MainWindow *mainwin = (MainWindow *)data;
1146
1147         if (inc_lock_count) {
1148                 debug_print("autocheck is locked.\n");
1149                 inc_autocheck_timer_set_interval(1000);
1150                 return FALSE;
1151         }
1152
1153         inc_all_account_mail(mainwin);
1154
1155         return FALSE;
1156 }