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