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