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