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