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