a3a29383108e24c4ceafd12c09807b3050807b08
[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 <time.h>
35 #include <sys/types.h>
36 #include <sys/stat.h>
37 #include <sys/wait.h>
38 #include <signal.h>
39 #include <errno.h>
40
41 #include "intl.h"
42 #include "main.h"
43 #include "inc.h"
44 #include "mainwindow.h"
45 #include "folderview.h"
46 #include "summaryview.h"
47 #include "prefs_common.h"
48 #include "prefs_account.h"
49 #include "account.h"
50 #include "procmsg.h"
51 #include "socket.h"
52 #include "ssl.h"
53 #include "pop.h"
54 #include "recv.h"
55 #include "mbox.h"
56 #include "utils.h"
57 #include "gtkutils.h"
58 #include "statusbar.h"
59 #include "manage_window.h"
60 #include "stock_pixmap.h"
61 #include "progressdialog.h"
62 #include "inputdialog.h"
63 #include "alertpanel.h"
64 #include "filter.h"
65 #include "automaton.h"
66 #include "folder.h"
67 #include "filtering.h"
68 #include "selective_download.h"
69
70 static GList *inc_dialog_list = NULL;
71
72 static guint inc_lock_count = 0;
73
74 static GdkPixmap *currentxpm;
75 static GdkBitmap *currentxpmmask;
76 static GdkPixmap *errorxpm;
77 static GdkBitmap *errorxpmmask;
78 static GdkPixmap *okxpm;
79 static GdkBitmap *okxpmmask;
80
81 #define MSGBUFSIZE      8192
82
83 static void inc_finished                (MainWindow             *mainwin,
84                                          gboolean                new_messages);
85 static gint inc_account_mail            (PrefsAccount           *account,
86                                          MainWindow             *mainwin);
87
88 static IncProgressDialog *inc_progress_dialog_create    (void);
89 static void inc_progress_dialog_destroy (IncProgressDialog      *inc_dialog);
90
91 static IncSession *inc_session_new      (PrefsAccount           *account);
92 static void inc_session_destroy         (IncSession             *session);
93 static Pop3State *inc_pop3_state_new    (PrefsAccount           *account);
94 static void inc_pop3_state_destroy      (Pop3State              *state);
95 static gint inc_start                   (IncProgressDialog      *inc_dialog);
96 static IncState inc_pop3_session_do     (IncSession             *session);
97 static gint pop3_automaton_terminate    (SockInfo               *source,
98                                          Automaton              *atm);
99
100 static GHashTable *inc_get_uidl_table   (PrefsAccount           *ac_prefs);
101 static void inc_write_uidl_list         (Pop3State              *state);
102
103 static gboolean inc_pop3_recv_func      (SockInfo       *sock,
104                                          gint            count,
105                                          gint            read_bytes,
106                                          gpointer        data);
107
108 static void inc_put_error               (IncState        istate);
109
110 static void inc_cancel_cb               (GtkWidget      *widget,
111                                          gpointer        data);
112 static gint inc_dialog_delete_cb        (GtkWidget      *widget,
113                                          GdkEventAny    *event,
114                                          gpointer        data);
115
116 static gint inc_spool                   (void);
117 static gint get_spool                   (FolderItem     *dest,
118                                          const gchar    *mbox);
119
120 static void inc_spool_account(PrefsAccount *account);
121 static void inc_all_spool(void);
122 static void inc_autocheck_timer_set_interval    (guint           interval);
123 static gint inc_autocheck_func                  (gpointer        data);
124
125 static void inc_notify_cmd              (gint new_msgs, 
126                                          gboolean notify);
127
128 #define FOLDER_SUMMARY_MISMATCH(f, s) \
129         (f) && (s) ? ((s)->newmsgs != (f)->new) || ((f)->unread != (s)->unread) || ((f)->total != (s)->messages) \
130         : FALSE
131         
132 /**
133  * inc_finished:
134  * @mainwin: Main window.
135  * @new_messages: TRUE if some messages have been received.
136  * 
137  * Update the folder view and the summary view after receiving
138  * messages.  If @new_messages is FALSE, this function avoids unneeded
139  * updating.
140  **/
141 static void inc_finished(MainWindow *mainwin, gboolean new_messages)
142 {
143         FolderItem *item;
144
145         if (prefs_common.scan_all_after_inc)
146                 folderview_check_new(NULL);
147
148         if (!new_messages && !prefs_common.scan_all_after_inc) return;
149
150         if (prefs_common.open_inbox_on_inc) {
151                 item = cur_account && cur_account->inbox
152                         ? folder_find_item_from_identifier(cur_account->inbox)
153                         : folder_get_default_inbox();
154                 if (FOLDER_SUMMARY_MISMATCH(item, mainwin->summaryview)) {      
155                         folderview_unselect(mainwin->folderview);
156                         folderview_select(mainwin->folderview, item);
157                 }       
158         } else if (prefs_common.scan_all_after_inc) {
159                 item = mainwin->summaryview->folder_item;
160                 if (FOLDER_SUMMARY_MISMATCH(item, mainwin->summaryview)) {
161                         folderview_update_item(item, TRUE);
162                 }       
163         }
164 }
165
166 void inc_mail(MainWindow *mainwin, gboolean notify)
167 {
168         gint new_msgs = 0;
169
170         if (inc_lock_count) return;
171
172         if (prefs_common.work_offline)
173                 if (alertpanel(_("Offline warning"), 
174                                _("You're working offline. Override?"),
175                                _("Yes"), _("No"), NULL) != G_ALERTDEFAULT)
176                 return;
177
178         inc_autocheck_timer_remove();
179         main_window_lock(mainwin);
180
181         if (prefs_common.use_extinc && prefs_common.extinc_cmd) {
182                 /* external incorporating program */
183                 if (execute_command_line(prefs_common.extinc_cmd, FALSE) < 0) {
184                         main_window_unlock(mainwin);
185                         inc_autocheck_timer_set();
186                         return;
187                 }
188
189                 if (prefs_common.inc_local)
190                         new_msgs = inc_spool();
191
192                 if (new_msgs <= 0)
193                         new_msgs = 1;
194         } else {
195                 if (prefs_common.inc_local)
196                         new_msgs = inc_spool();
197
198                 new_msgs += inc_account_mail(cur_account, mainwin);
199         }
200
201         inc_finished(mainwin, new_msgs > 0);
202         main_window_unlock(mainwin);
203         inc_notify_cmd(new_msgs, notify);
204         inc_autocheck_timer_set();
205 }
206
207 void inc_selective_download(MainWindow *mainwin, PrefsAccount *acc, gint session)
208 {
209         GSList *cur;
210         gint new_msgs = 0;
211
212         acc->session = session;
213         inc_account_mail(acc, mainwin);
214         acc->session = STYPE_NORMAL;
215         
216         for (cur = acc->msg_list; cur != NULL; cur = cur->next) {
217                 HeaderItems *items =(HeaderItems*)cur->data;
218
219                 if (items->state == SD_DOWNLOADED && 
220                     items->del_by_old_session == FALSE) {
221                         new_msgs++;                     
222                 }
223         }
224
225         if (new_msgs) {
226                 inc_finished(mainwin, TRUE);
227                 inc_notify_cmd(new_msgs, prefs_common.newmail_notify_manu);
228         }
229 }
230
231 static gint inc_account_mail(PrefsAccount *account, MainWindow *mainwin)
232 {
233         IncProgressDialog *inc_dialog;
234         IncSession *session;
235         gchar *text[3];
236
237         switch (account->protocol) {
238         case A_IMAP4:
239         case A_NNTP:
240                 folderview_check_new(FOLDER(account->folder));
241                 return 1;
242
243         case A_POP3:
244         case A_APOP:
245                 session = inc_session_new(account);
246                 if (!session) return 0;
247                 
248                 inc_dialog = inc_progress_dialog_create();
249                 inc_dialog->queue_list = g_list_append(inc_dialog->queue_list,
250                                                        session);
251                 inc_dialog->mainwin = mainwin;
252                 session->data = inc_dialog;
253         
254                 text[0] = NULL;
255                 text[1] = account->account_name;
256                 text[2] = _("Standby");
257                 gtk_clist_append(GTK_CLIST(inc_dialog->dialog->clist), text);
258                 
259                 toolbar_set_sensitive(mainwin);
260                 main_window_set_menu_sensitive(mainwin);
261                 
262                 return inc_start(inc_dialog);
263
264         case A_LOCAL:
265                 inc_spool_account(account);
266                 return 1;
267         }
268         return 0;
269 }
270
271 void inc_all_account_mail(MainWindow *mainwin, gboolean notify)
272 {
273         GList *list, *queue_list = NULL;
274         IncProgressDialog *inc_dialog;
275         gint new_msgs = 0;
276         
277         if (prefs_common.work_offline)
278                 if (alertpanel(_("Offline warning"), 
279                                _("You're working offline. Override?"),
280                                _("Yes"), _("No"), NULL) != G_ALERTDEFAULT)
281                 return;
282
283         if (inc_lock_count) return;
284
285         inc_autocheck_timer_remove();
286         main_window_lock(mainwin);
287
288         if (prefs_common.inc_local) {
289                 new_msgs = inc_spool();
290                 if (new_msgs < 0)
291                         new_msgs = 0;
292         }
293
294         list = account_get_list();
295         if (!list) {
296                 inc_finished(mainwin, new_msgs > 0);
297                 main_window_unlock(mainwin);
298                 inc_notify_cmd(new_msgs, notify);
299                 inc_autocheck_timer_set();
300                 return;
301         }
302
303         /* check local folders */
304         inc_all_spool();
305
306         /* check IMAP4 folders */
307         for (; list != NULL; list = list->next) {
308                 PrefsAccount *account = list->data;
309                 if ((account->protocol == A_IMAP4 ||
310                      account->protocol == A_NNTP) && account->recv_at_getall)
311                         folderview_check_new(FOLDER(account->folder));
312         }
313
314         /* check POP3 accounts */
315         for (list = account_get_list(); list != NULL; list = list->next) {
316                 IncSession *session;
317                 PrefsAccount *account = list->data;
318                 account->session = STYPE_NORMAL;
319                 if (account->recv_at_getall) {
320                         session = inc_session_new(account);
321                         if (session)
322                                 queue_list = g_list_append(queue_list, session);
323                 }
324         }
325
326         if (!queue_list) {
327                 inc_finished(mainwin, new_msgs > 0);
328                 main_window_unlock(mainwin);
329                 inc_notify_cmd(new_msgs, notify);
330                 inc_autocheck_timer_set();
331                 return;
332         }
333
334         inc_dialog = inc_progress_dialog_create();
335         inc_dialog->queue_list = queue_list;
336         inc_dialog->mainwin = mainwin;
337         for (list = queue_list; list != NULL; list = list->next) {
338                 IncSession *session = list->data;
339                 gchar *text[3];
340
341                 session->data = inc_dialog;
342
343                 text[0] = NULL;
344                 text[1] = session->pop3_state->ac_prefs->account_name;
345                 text[2] = _("Standby");
346                 gtk_clist_append(GTK_CLIST(inc_dialog->dialog->clist), text);
347         }
348
349         toolbar_set_sensitive(mainwin);
350         main_window_set_menu_sensitive(mainwin);
351
352         new_msgs += inc_start(inc_dialog);
353
354         inc_finished(mainwin, new_msgs > 0);
355         main_window_unlock(mainwin);
356         inc_notify_cmd(new_msgs, notify);
357         inc_autocheck_timer_set();
358 }
359
360 static IncProgressDialog *inc_progress_dialog_create(void)
361 {
362         IncProgressDialog *dialog;
363         ProgressDialog *progress;
364
365         dialog = g_new0(IncProgressDialog, 1);
366
367         progress = progress_dialog_create();
368         gtk_window_set_title(GTK_WINDOW(progress->window),
369                              _("Retrieving new messages"));
370         gtk_signal_connect(GTK_OBJECT(progress->cancel_btn), "clicked",
371                            GTK_SIGNAL_FUNC(inc_cancel_cb), dialog);
372         gtk_signal_connect(GTK_OBJECT(progress->window), "delete_event",
373                            GTK_SIGNAL_FUNC(inc_dialog_delete_cb), dialog);
374         /* manage_window_set_transient(GTK_WINDOW(progress->window)); */
375
376         progress_dialog_set_value(progress, 0.0);
377
378         stock_pixmap_gdk(progress->clist, STOCK_PIXMAP_COMPLETE,
379                          &okxpm, &okxpmmask);
380         stock_pixmap_gdk(progress->clist, STOCK_PIXMAP_CONTINUE,
381                          &currentxpm, &currentxpmmask);
382         stock_pixmap_gdk(progress->clist, STOCK_PIXMAP_ERROR,
383                          &errorxpm, &errorxpmmask);
384
385         if (prefs_common.recv_dialog_mode == RECV_DIALOG_ALWAYS ||
386             (prefs_common.recv_dialog_mode == RECV_DIALOG_ACTIVE &&
387              manage_window_get_focus_window())) {
388                 dialog->show_dialog = TRUE;
389                 gtk_widget_show_now(progress->window);
390         }
391
392         dialog->dialog = progress;
393         dialog->queue_list = NULL;
394
395         inc_dialog_list = g_list_append(inc_dialog_list, dialog);
396
397         return dialog;
398 }
399
400 static void inc_progress_dialog_clear(IncProgressDialog *inc_dialog)
401 {
402         progress_dialog_set_value(inc_dialog->dialog, 0.0);
403         progress_dialog_set_label(inc_dialog->dialog, "");
404         gtk_progress_bar_update
405                 (GTK_PROGRESS_BAR(inc_dialog->mainwin->progressbar), 0.0);
406 }
407
408 static void inc_progress_dialog_destroy(IncProgressDialog *inc_dialog)
409 {
410         g_return_if_fail(inc_dialog != NULL);
411
412         inc_dialog_list = g_list_remove(inc_dialog_list, inc_dialog);
413
414         gtk_progress_bar_update
415                 (GTK_PROGRESS_BAR(inc_dialog->mainwin->progressbar), 0.0);
416         progress_dialog_destroy(inc_dialog->dialog);
417
418         g_free(inc_dialog);
419 }
420
421 static IncSession *inc_session_new(PrefsAccount *account)
422 {
423         IncSession *session;
424
425         g_return_val_if_fail(account != NULL, NULL);
426
427         if (account->protocol != A_POP3 && account->protocol != A_APOP)
428                 return NULL;
429         if (!account->recv_server || !account->userid)
430                 return NULL;
431
432         session = g_new0(IncSession, 1);
433         session->pop3_state = inc_pop3_state_new(account);
434         session->pop3_state->session = session;
435
436         return session;
437 }
438
439 static void inc_session_destroy(IncSession *session)
440 {
441         g_return_if_fail(session != NULL);
442
443         inc_pop3_state_destroy(session->pop3_state);
444         g_free(session);
445 }
446
447 static Pop3State *inc_pop3_state_new(PrefsAccount *account)
448 {
449         Pop3State *state;
450
451         state = g_new0(Pop3State, 1);
452
453         state->ac_prefs = account;
454         state->folder_table = g_hash_table_new(NULL, NULL);
455         state->uidl_todelete_list = NULL;
456         state->uidl_table = inc_get_uidl_table(account);
457         state->inc_state = INC_SUCCESS;
458         state->current_time = time(NULL);
459
460         return state;
461 }
462
463 static void inc_pop3_state_destroy(Pop3State *state)
464 {
465         gint n;
466
467         g_hash_table_destroy(state->folder_table);
468
469         for (n = 1; n <= state->count; n++)
470                 g_free(state->msg[n].uidl);
471         g_free(state->msg);
472
473         if (state->uidl_table) {
474                 hash_free_strings(state->uidl_table);
475                 g_hash_table_destroy(state->uidl_table);
476         }
477         g_slist_free(state->uidl_todelete_list);
478         g_free(state->greeting);
479         g_free(state->user);
480         g_free(state->pass);
481         g_free(state->prev_folder);
482
483         g_free(state);
484 }
485
486 static gint inc_start(IncProgressDialog *inc_dialog)
487 {
488         IncSession *session;
489         GtkCList *clist = GTK_CLIST(inc_dialog->dialog->clist);
490         Pop3State *pop3_state;
491         IncState inc_state;
492         gint num = 0;
493         gint error_num = 0;
494         gint new_msgs = 0;
495         gchar *fin_msg;
496
497         while (inc_dialog->queue_list != NULL) {
498                 session = inc_dialog->queue_list->data;
499                 pop3_state = session->pop3_state;
500
501                 inc_progress_dialog_clear(inc_dialog);
502
503                 gtk_clist_moveto(clist, num, -1, 1.0, 0.0);
504
505                 pop3_state->user = g_strdup(pop3_state->ac_prefs->userid);
506                 if (pop3_state->ac_prefs->passwd)
507                         pop3_state->pass =
508                                 g_strdup(pop3_state->ac_prefs->passwd);
509                 else if (pop3_state->ac_prefs->tmp_pass)
510                         pop3_state->pass =
511                                 g_strdup(pop3_state->ac_prefs->tmp_pass);
512                 else {
513                         gchar *pass;
514
515                         pass = input_dialog_query_password
516                                 (pop3_state->ac_prefs->recv_server,
517                                  pop3_state->user);
518
519                         if (inc_dialog->show_dialog)
520                                 manage_window_focus_in
521                                         (inc_dialog->mainwin->window,
522                                          NULL, NULL);
523                         if (pass) {
524                                 pop3_state->ac_prefs->tmp_pass = g_strdup(pass);
525                                 pop3_state->pass = pass;
526                         } else {
527                                 inc_session_destroy(session);
528                                 inc_dialog->queue_list = g_list_remove
529                                         (inc_dialog->queue_list, session);
530                                 continue;
531                         }
532                 }
533
534                 gtk_clist_set_pixmap(clist, num, 0, currentxpm, currentxpmmask);
535                 gtk_clist_set_text(clist, num, 2, _("Retrieving"));
536
537                 /* begin POP3 session */
538                 inc_state = inc_pop3_session_do(session);
539
540                 if (inc_state == INC_SUCCESS) {
541                         gchar *msg;
542
543                         if (pop3_state->cur_total_num > 0)
544                                 msg = g_strdup_printf
545                                         (_("Done (%d message(s) (%s) received)"),
546                                          pop3_state->cur_total_num,
547                                          to_human_readable(pop3_state->cur_total_recv_bytes));
548                         else
549                                 msg = g_strdup_printf(_("Done (no new messages)"));
550                         gtk_clist_set_pixmap(clist, num, 0, okxpm, okxpmmask);
551                         gtk_clist_set_text(clist, num, 2, msg);
552                         g_free(msg);
553                 } else if (inc_state == INC_CANCEL) {
554                         gtk_clist_set_pixmap(clist, num, 0, okxpm, okxpmmask);
555                         gtk_clist_set_text(clist, num, 2, _("Cancelled"));
556                 } else {
557                         gtk_clist_set_pixmap(clist, num, 0, errorxpm, errorxpmmask);
558                         if (inc_state == INC_CONNECT_ERROR)
559                                 gtk_clist_set_text(clist, num, 2,
560                                                    _("Connection failed"));
561                         else if (inc_state == INC_AUTH_FAILED)
562                                 gtk_clist_set_text(clist, num, 2,
563                                                    _("Auth failed"));
564                         else
565                                 gtk_clist_set_text(clist, num, 2, _("Error"));
566                 }
567
568                 if (pop3_state->error_val == PS_AUTHFAIL) {
569                         if(!prefs_common.no_recv_err_panel) {
570                                 if((prefs_common.recv_dialog_mode == RECV_DIALOG_ALWAYS) ||
571                                     ((prefs_common.recv_dialog_mode == RECV_DIALOG_ACTIVE) && focus_window)) {
572                                         manage_window_focus_in(inc_dialog->dialog->window, NULL, NULL);
573                                 }
574                                 alertpanel_error
575                                         (_("Authorization for %s on %s failed"),
576                                          pop3_state->user,
577                                          pop3_state->ac_prefs->recv_server);
578                         }
579                 }
580
581                 statusbar_pop_all();
582
583                 /* CLAWS: perform filtering actions on dropped message */
584                 if (global_processing != NULL) {
585                         FolderItem *processing, *inbox;
586                         MsgInfo *msginfo;
587                         GSList *msglist, *msglist_element;
588
589                         /* CLAWS: get default inbox (perhaps per account) */
590                         if (pop3_state->ac_prefs->inbox) {
591                                 /* CLAWS: get destination folder / mailbox */
592                                 inbox = folder_find_item_from_identifier(pop3_state->ac_prefs->inbox);
593                                 if (!inbox)
594                                         inbox = folder_get_default_inbox();
595                         } else
596                                 inbox = folder_get_default_inbox();
597
598                         /* get list of messages in processing */
599                         processing = folder_get_default_processing();
600                         folder_item_scan(processing);
601                         msglist = folder_item_get_msg_list(processing);
602
603                         /* process messages */
604                         for(msglist_element = msglist; msglist_element != NULL; msglist_element = msglist_element->next) {
605                                 msginfo = (MsgInfo *) msglist_element->data;
606                                 /* filter if enabled in prefs or move to inbox if not */
607                                 if(pop3_state->ac_prefs->filter_on_recv) {
608                                         filter_message_by_msginfo_with_inbox(global_processing, msginfo,
609                                                                              pop3_state->folder_table,
610                                                                              inbox);
611                                 } else {
612                                         folder_item_move_msg(inbox, msginfo);
613                                         g_hash_table_insert(pop3_state->folder_table, inbox,
614                                                             GINT_TO_POINTER(1));
615                                 }
616                                 procmsg_msginfo_free(msginfo);
617                         }
618                         g_slist_free(msglist);
619                 }
620
621
622                 new_msgs += pop3_state->cur_total_num;
623
624                 folderview_update_item_foreach
625                         (pop3_state->folder_table, TRUE);
626
627                 if (pop3_state->error_val == PS_AUTHFAIL &&
628                     pop3_state->ac_prefs->tmp_pass) {
629                         g_free(pop3_state->ac_prefs->tmp_pass);
630                         pop3_state->ac_prefs->tmp_pass = NULL;
631                 }
632
633                 inc_write_uidl_list(pop3_state);
634
635                 if (inc_state != INC_SUCCESS && inc_state != INC_CANCEL) {
636                         error_num++;
637                         if (inc_state == INC_NOSPACE) {
638                                 inc_put_error(inc_state);
639                                 break;
640                         }
641                 }
642
643                 inc_session_destroy(session);
644                 inc_dialog->queue_list =
645                         g_list_remove(inc_dialog->queue_list, session);
646
647                 num++;
648         }
649
650         if (new_msgs > 0)
651                 fin_msg = g_strdup_printf(_("Finished (%d new message(s))"),
652                                           new_msgs);
653         else
654                 fin_msg = g_strdup_printf(_("Finished (no new messages)"));
655
656         progress_dialog_set_label(inc_dialog->dialog, fin_msg);
657
658         if (error_num && !prefs_common.no_recv_err_panel) {
659                 if (inc_dialog->show_dialog)
660                         manage_window_focus_in(inc_dialog->dialog->window,
661                                                NULL, NULL);
662                 alertpanel_error(_("Some errors occurred while getting mail."));
663                 if (inc_dialog->show_dialog)
664                         manage_window_focus_out(inc_dialog->dialog->window,
665                                                 NULL, NULL);
666         }
667
668         while (inc_dialog->queue_list != NULL) {
669                 session = inc_dialog->queue_list->data;
670                 inc_session_destroy(session);
671                 inc_dialog->queue_list =
672                         g_list_remove(inc_dialog->queue_list, session);
673         }
674
675         if (prefs_common.close_recv_dialog)
676                 inc_progress_dialog_destroy(inc_dialog);
677         else {
678                 gtk_window_set_title(GTK_WINDOW(inc_dialog->dialog->window),
679                                      fin_msg);
680                 gtk_label_set_text(GTK_LABEL(GTK_BIN(inc_dialog->dialog->cancel_btn)->child),
681                                    _("Close"));
682         }
683
684         g_free(fin_msg);
685
686         return new_msgs;
687 }
688
689 static IncState inc_pop3_session_do(IncSession *session)
690 {
691         Pop3State *pop3_state = session->pop3_state;
692         IncProgressDialog *inc_dialog = (IncProgressDialog *)session->data;
693         Automaton *atm;
694         SockInfo *sockinfo;
695         gint i;
696         gchar *server;
697         gushort port;
698         gchar *buf;
699         static AtmHandler handlers[] = {
700                 pop3_greeting_recv      ,
701 #if USE_SSL
702                 pop3_stls_send          , pop3_stls_recv,
703 #endif
704                 pop3_getauth_user_send  , pop3_getauth_user_recv,
705                 pop3_getauth_pass_send  , pop3_getauth_pass_recv,
706                 pop3_getauth_apop_send  , pop3_getauth_apop_recv,
707                 pop3_getrange_stat_send , pop3_getrange_stat_recv,
708                 pop3_getrange_last_send , pop3_getrange_last_recv,
709                 pop3_getrange_uidl_send , pop3_getrange_uidl_recv,
710                 pop3_getsize_list_send  , pop3_getsize_list_recv,
711                 pop3_top_send           , pop3_top_recv,
712                 pop3_retr_send          , pop3_retr_recv,
713                 pop3_delete_send        , pop3_delete_recv,
714                 pop3_logout_send        , pop3_logout_recv
715         };
716
717         debug_print("getting new messages of account %s...\n",
718                     pop3_state->ac_prefs->account_name);
719
720         atm = automaton_create(N_POP3_PHASE);
721
722         session->atm = atm;
723         atm->data = pop3_state;
724
725         buf = g_strdup_printf(_("%s: Retrieving new messages"),
726                               pop3_state->ac_prefs->recv_server);
727         gtk_window_set_title(GTK_WINDOW(inc_dialog->dialog->window), buf);
728         g_free(buf);
729
730         for (i = POP3_GREETING_RECV; i < N_POP3_PHASE; i++)
731                 atm->state[i].handler = handlers[i];
732         atm->state[POP3_GREETING_RECV].condition = GDK_INPUT_READ;
733         for (i = POP3_GREETING_RECV + 1; i < N_POP3_PHASE; ) {
734                 atm->state[i++].condition = GDK_INPUT_WRITE;
735                 atm->state[i++].condition = GDK_INPUT_READ;
736         }
737
738         atm->terminate = (AtmHandler)pop3_automaton_terminate;
739         atm->ui_func = (AtmUIFunc)inc_progress_update;
740
741         atm->num = POP3_GREETING_RECV;
742
743         server = pop3_state->ac_prefs->recv_server;
744 #if USE_SSL
745         port = pop3_state->ac_prefs->set_popport ?
746                 pop3_state->ac_prefs->popport :
747                 pop3_state->ac_prefs->ssl_pop == SSL_TUNNEL ? 995 : 110;
748 #else
749         port = pop3_state->ac_prefs->set_popport ?
750                 pop3_state->ac_prefs->popport : 110;
751 #endif
752
753         buf = g_strdup_printf(_("Connecting to POP3 server: %s ..."), server);
754         log_message("%s\n", buf);
755         progress_dialog_set_label(inc_dialog->dialog, buf);
756         g_free(buf);
757         GTK_EVENTS_FLUSH();
758         statusbar_pop_all();
759
760         if ((sockinfo = sock_connect(server, port)) == NULL) {
761                 log_warning(_("Can't connect to POP3 server: %s:%d\n"),
762                             server, port);
763                 if(!prefs_common.no_recv_err_panel) {
764                         if((prefs_common.recv_dialog_mode == RECV_DIALOG_ALWAYS) ||
765                             ((prefs_common.recv_dialog_mode == RECV_DIALOG_ACTIVE) && focus_window)) {
766                                 manage_window_focus_in(inc_dialog->dialog->window, NULL, NULL);
767                         }
768                         alertpanel_error(_("Can't connect to POP3 server: %s:%d"),
769                                          server, port);
770                         manage_window_focus_out(inc_dialog->dialog->window, NULL, NULL);
771                 }
772                 pop3_automaton_terminate(NULL, atm);
773                 automaton_destroy(atm);
774                 return INC_CONNECT_ERROR;
775         }
776
777 #if USE_SSL
778         if (pop3_state->ac_prefs->ssl_pop == SSL_TUNNEL &&
779             !ssl_init_socket(sockinfo)) {
780                 pop3_automaton_terminate(NULL, atm);
781                 automaton_destroy(atm);
782                 return INC_CONNECT_ERROR;
783         }
784 #endif
785
786         /* :WK: Hmmm, with the later sock_gdk_input, we have 2 references
787          * to the sock structure - implement a reference counter?? */
788         pop3_state->sockinfo = sockinfo;
789         atm->help_sock = sockinfo;
790
791         log_verbosity_set(TRUE);
792         /* oha: this messes up inc_progress update:
793            disabling this would avoid the label "Retrieve Header"
794            being overwritten by "Retrieve Message"
795            Setting inc_pop3_recv_func is not necessary
796            since atm already handles the progress dialog ui
797            just fine.
798         */
799         recv_set_ui_func(inc_pop3_recv_func, session);
800
801         atm->tag = sock_gdk_input_add(sockinfo,
802                                       atm->state[atm->num].condition,
803                                       automaton_input_cb, atm);
804
805         while (!atm->terminated)
806                 gtk_main_iteration();
807
808         log_verbosity_set(FALSE);
809         /* oha: see above */
810         recv_set_ui_func(NULL, NULL);
811
812         automaton_destroy(atm);
813
814         return pop3_state->inc_state;
815 }
816
817 static gint pop3_automaton_terminate(SockInfo *source, Automaton *atm)
818 {
819         if (atm->terminated) return 0;
820
821         if (atm->tag > 0) {
822                 gdk_input_remove(atm->tag);
823                 atm->tag = 0;
824         }
825         if (atm->timeout_tag > 0) {
826                 gtk_timeout_remove(atm->timeout_tag);
827                 atm->timeout_tag = 0;
828         }
829         if (source)
830                 sock_close(source);
831
832         atm->terminated = TRUE;
833
834         return 0;
835 }
836
837 static GHashTable *inc_get_uidl_table(PrefsAccount *ac_prefs)
838 {
839         GHashTable *table;
840         gchar *path;
841         FILE *fp;
842         gchar buf[IDLEN + 3];
843         gchar uidl[IDLEN + 3];
844         time_t recv_time;
845         time_t now;
846
847         path = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
848                            "uidl", G_DIR_SEPARATOR_S, ac_prefs->recv_server,
849                            "-", ac_prefs->userid, NULL);
850         if ((fp = fopen(path, "rb")) == NULL) {
851                 if (ENOENT != errno) FILE_OP_ERROR(path, "fopen");
852                 g_free(path);
853                 path = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
854                                    "uidl-", ac_prefs->recv_server,
855                                    "-", ac_prefs->userid, NULL);
856                 if ((fp = fopen(path, "rb")) == NULL) {
857                         if (ENOENT != errno) FILE_OP_ERROR(path, "fopen");
858                         g_free(path);
859                         return NULL;
860                 }
861         }
862         g_free(path);
863
864         table = g_hash_table_new(g_str_hash, g_str_equal);
865
866         now = time(NULL);
867
868         while (fgets(buf, sizeof(buf), fp) != NULL) {
869                 strretchomp(buf);
870                 recv_time = 0;
871                 if (sscanf(buf, "%s\t%ld", uidl, &recv_time) != 2) {
872                         if (sscanf(buf, "%s", uidl) != 1)
873                                 continue;
874                         else
875                                 recv_time = now;
876                 }
877                 if (recv_time == 0)
878                         recv_time = 1;
879                 g_hash_table_insert(table, g_strdup(uidl),
880                                     GINT_TO_POINTER(recv_time));
881         }
882
883         fclose(fp);
884         return table;
885 }
886
887 static void inc_write_uidl_list(Pop3State *state)
888 {
889         gchar *path;
890         FILE *fp;
891         Pop3MsgInfo *msg;
892         gint n;
893
894         if (!state->uidl_is_valid) return;
895
896         path = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
897                            "uidl", G_DIR_SEPARATOR_S,
898                            state->ac_prefs->recv_server,
899                            "-", state->ac_prefs->userid, NULL);
900         if ((fp = fopen(path, "wb")) == NULL) {
901                 FILE_OP_ERROR(path, "fopen");
902                 g_free(path);
903                 return;
904         }
905
906         for (n = 1; n <= state->count; n++) {
907                 msg = &state->msg[n];
908                 if (msg->uidl && msg->received && !msg->deleted)
909                         fprintf(fp, "%s\t%ld\n", msg->uidl, msg->recv_time);
910         }
911
912         if (fclose(fp) == EOF) FILE_OP_ERROR(path, "fclose");
913         g_free(path);
914 }
915
916 static gboolean inc_pop3_recv_func(SockInfo *sock, gint count, gint read_bytes,
917                                    gpointer data)
918 {
919         gchar buf[MSGBUFSIZE];
920         IncSession *session = (IncSession *)data;
921         Pop3State *state = session->pop3_state;
922         IncProgressDialog *inc_dialog = session->data;
923         ProgressDialog *dialog = inc_dialog->dialog;
924         gint cur_total;
925         gchar *total_size;
926
927         cur_total = state->cur_total_bytes + read_bytes;
928         if (cur_total > state->total_bytes)
929                 cur_total = state->total_bytes;
930
931         Xstrdup_a(total_size, to_human_readable(state->total_bytes),
932                   return FALSE);
933         g_snprintf(buf, sizeof(buf),
934                    _("Retrieving message (%d / %d) (%s / %s)"),
935                    state->cur_msg, state->count,
936                    to_human_readable(cur_total), total_size);
937         progress_dialog_set_label(dialog, buf);
938
939         progress_dialog_set_percentage
940                 (dialog, (gfloat)cur_total / (gfloat)state->total_bytes);
941         gtk_progress_bar_update
942                 (GTK_PROGRESS_BAR(inc_dialog->mainwin->progressbar),
943                  (gfloat)cur_total / (gfloat)state->total_bytes);
944         GTK_EVENTS_FLUSH();
945
946         if (state->inc_state == INC_CANCEL)
947                 return FALSE;
948         else
949                 return TRUE;
950 }
951
952 void inc_progress_update(Pop3State *state, Pop3Phase phase)
953 {
954         gchar buf[MSGBUFSIZE];
955         IncProgressDialog *inc_dialog = state->session->data;
956         ProgressDialog *dialog = inc_dialog->dialog;
957         gchar *total_size;
958
959         switch (phase) {
960         case POP3_GREETING_RECV:
961                 break;
962         case POP3_GETAUTH_USER_SEND:
963         case POP3_GETAUTH_PASS_SEND:
964         case POP3_GETAUTH_APOP_SEND:
965                 progress_dialog_set_label(dialog, _("Authenticating..."));
966                 break;
967         case POP3_GETRANGE_STAT_SEND:
968                 progress_dialog_set_label
969                         (dialog, _("Getting the number of new messages (STAT)..."));
970                 break;
971         case POP3_GETRANGE_LAST_SEND:
972                 progress_dialog_set_label
973                         (dialog, _("Getting the number of new messages (LAST)..."));
974                 break;
975         case POP3_GETRANGE_UIDL_SEND:
976                 progress_dialog_set_label
977                         (dialog, _("Getting the number of new messages (UIDL)..."));
978                 break;
979         case POP3_GETSIZE_LIST_SEND:
980                 progress_dialog_set_label
981                         (dialog, _("Getting the size of messages (LIST)..."));
982                 break;
983         case POP3_TOP_SEND:
984                 g_snprintf(buf, sizeof(buf),
985                            _("Retrieving header (%d / %d)"),
986                            state->cur_msg, state->count);
987                 progress_dialog_set_label (dialog, buf);
988                 progress_dialog_set_percentage
989                         (dialog,
990                          (gfloat)(state->cur_msg) /
991                          (gfloat)(state->count));
992                 gtk_progress_bar_update 
993                         (GTK_PROGRESS_BAR(inc_dialog->mainwin->progressbar),
994                          (gfloat)(state->cur_msg) /
995                          (gfloat)(state->count));
996                 break;
997         case POP3_RETR_SEND:
998                 Xstrdup_a(total_size, to_human_readable(state->total_bytes), return);
999                 g_snprintf(buf, sizeof(buf),
1000                            _("Retrieving message (%d / %d) (%s / %s)"),
1001                            state->cur_msg, state->count,
1002                            to_human_readable(state->cur_total_bytes),
1003                            total_size);
1004                 progress_dialog_set_label(dialog, buf);
1005                 progress_dialog_set_percentage
1006                         (dialog,
1007                          (gfloat)(state->cur_total_bytes) /
1008                          (gfloat)(state->total_bytes));
1009                 gtk_progress_bar_update
1010                         (GTK_PROGRESS_BAR(inc_dialog->mainwin->progressbar),
1011                          (gfloat)(state->cur_total_bytes) /
1012                          (gfloat)(state->total_bytes));
1013                 break;
1014         case POP3_DELETE_SEND:
1015                 if (state->msg[state->cur_msg].recv_time < state->current_time) {
1016                         g_snprintf(buf, sizeof(buf), _("Deleting message %d"),
1017                                    state->cur_msg);
1018                         progress_dialog_set_label(dialog, buf);
1019                 }
1020                 break;
1021         case POP3_LOGOUT_SEND:
1022                 progress_dialog_set_label(dialog, _("Quitting"));
1023                 break;
1024         default:
1025                 break;
1026         }
1027 }
1028
1029 gint inc_drop_message(const gchar *file, Pop3State *state)
1030 {
1031         FolderItem *inbox;
1032         FolderItem *dropfolder;
1033         gint val;
1034         gint msgnum;
1035
1036         /* CLAWS: get default inbox (perhaps per account) */
1037         if (state->ac_prefs->inbox) {
1038                 /* CLAWS: get destination folder / mailbox */
1039                 inbox = folder_find_item_from_identifier
1040                         (state->ac_prefs->inbox);
1041                 if (!inbox)
1042                         inbox = folder_get_default_inbox();
1043         } else
1044                 inbox = folder_get_default_inbox();
1045         if (!inbox) {
1046                 unlink(file);
1047                 return -1;
1048         }
1049
1050         /* CLAWS: claws uses a global .processing folder for the filtering. */
1051         if (global_processing == NULL) {
1052                 if (state->ac_prefs->filter_on_recv) {
1053                         dropfolder =
1054                                 filter_get_dest_folder(prefs_common.fltlist, file);
1055                         if (!dropfolder) dropfolder = inbox;
1056                         else if (!strcmp(dropfolder->path, FILTER_NOT_RECEIVE)) {
1057                                 g_warning(_("a message won't be received\n"));
1058                                 return 1;
1059                         }
1060                 } else
1061                         dropfolder = inbox;
1062         } else {
1063                 dropfolder = folder_get_default_processing();
1064         }
1065
1066         val = GPOINTER_TO_INT(g_hash_table_lookup
1067                               (state->folder_table, dropfolder));
1068         if (val == 0) {
1069                 folder_item_scan(dropfolder);
1070                 /* force updating */
1071                 if (FOLDER_IS_LOCAL(dropfolder->folder))
1072                         dropfolder->mtime = 0;
1073                 g_hash_table_insert(state->folder_table, dropfolder,
1074                                     GINT_TO_POINTER(1));
1075         }
1076         
1077         /* add msg file to drop folder */
1078         if ((msgnum = folder_item_add_msg(dropfolder, file, TRUE)) < 0) {
1079                 unlink(file);
1080                 return -1;
1081         }
1082
1083         return 0;
1084 }
1085
1086 static void inc_put_error(IncState istate)
1087 {
1088         switch (istate) {
1089         case INC_ERROR:
1090                 if (!prefs_common.no_recv_err_panel)
1091                         alertpanel_error
1092                                 (_("Error occurred while processing mail."));
1093                 break;
1094         case INC_NOSPACE:
1095                 alertpanel_error(_("No disk space left."));
1096                 break;
1097         default:
1098                 break;
1099         }
1100 }
1101
1102 static void inc_cancel(IncProgressDialog *dialog)
1103 {
1104         IncSession *session;
1105         SockInfo *sockinfo;
1106
1107         g_return_if_fail(dialog != NULL);
1108
1109         if (dialog->queue_list == NULL) {
1110                 inc_progress_dialog_destroy(dialog);
1111                 return;
1112         }
1113
1114         session = dialog->queue_list->data;
1115         sockinfo = session->pop3_state->sockinfo;
1116
1117         if (!sockinfo || session->atm->terminated == TRUE) return;
1118
1119         session->pop3_state->inc_state = INC_CANCEL;
1120         pop3_automaton_terminate(sockinfo, session->atm);
1121         session->pop3_state->sockinfo = NULL;
1122 }
1123
1124 gboolean inc_is_active(void)
1125 {
1126         return (inc_dialog_list != NULL);
1127 }
1128
1129 void inc_cancel_all(void)
1130 {
1131         GList *cur;
1132
1133         for (cur = inc_dialog_list; cur != NULL; cur = cur->next)
1134                 inc_cancel((IncProgressDialog *)cur->data);
1135 }
1136
1137 static void inc_cancel_cb(GtkWidget *widget, gpointer data)
1138 {
1139         inc_cancel((IncProgressDialog *)data);
1140 }
1141
1142 static gint inc_dialog_delete_cb(GtkWidget *widget, GdkEventAny *event,
1143                                  gpointer data)
1144 {
1145         IncProgressDialog *dialog = (IncProgressDialog *)data;
1146
1147         if (dialog->queue_list == NULL)
1148                 inc_progress_dialog_destroy(dialog);
1149
1150         return TRUE;
1151 }
1152
1153 static gint inc_spool(void)
1154 {
1155         gchar *mbox, *logname;
1156         gint msgs;
1157
1158         logname = g_get_user_name();
1159         mbox = g_strconcat(prefs_common.spool_path
1160                            ? prefs_common.spool_path : DEFAULT_SPOOL_PATH,
1161                            G_DIR_SEPARATOR_S, logname, NULL);
1162         msgs = get_spool(folder_get_default_inbox(), mbox);
1163         g_free(mbox);
1164
1165         return msgs;
1166 }
1167
1168 static void inc_spool_account(PrefsAccount *account)
1169 {
1170         FolderItem *inbox;
1171
1172         if (account->inbox) {
1173                 inbox = folder_find_item_from_path(account->inbox);
1174                 if (!inbox)
1175                         inbox = folder_get_default_inbox();
1176         } else
1177                 inbox = folder_get_default_inbox();
1178
1179         get_spool(inbox, account->local_mbox);
1180 }
1181
1182 static void inc_all_spool(void)
1183 {
1184         GList *list = NULL;
1185
1186         list = account_get_list();
1187         if (!list) return;
1188
1189         for (; list != NULL; list = list->next) {
1190                 PrefsAccount *account = list->data;
1191
1192                 if ((account->protocol == A_LOCAL) &&
1193                     (account->recv_at_getall))
1194                         inc_spool_account(account);
1195         }
1196 }
1197
1198 static gint get_spool(FolderItem *dest, const gchar *mbox)
1199 {
1200         gint msgs, size;
1201         gint lockfd;
1202         gchar tmp_mbox[MAXPATHLEN + 1];
1203         GHashTable *folder_table = NULL;
1204
1205         g_return_val_if_fail(dest != NULL, -1);
1206         g_return_val_if_fail(mbox != NULL, -1);
1207
1208         if (!is_file_exist(mbox) || (size = get_file_size(mbox)) == 0) {
1209                 debug_print("no messages in local mailbox.\n");
1210                 return 0;
1211         } else if (size < 0)
1212                 return -1;
1213
1214         if ((lockfd = lock_mbox(mbox, LOCK_FLOCK)) < 0)
1215                 return -1;
1216
1217         g_snprintf(tmp_mbox, sizeof(tmp_mbox), "%s%ctmpmbox.%08x",
1218                    get_tmp_dir(), G_DIR_SEPARATOR, (gint)mbox);
1219
1220         if (copy_mbox(mbox, tmp_mbox) < 0) {
1221                 unlock_mbox(mbox, lockfd, LOCK_FLOCK);
1222                 return -1;
1223         }
1224
1225         debug_print("Getting new messages from %s into %s...\n",
1226                     mbox, dest->path);
1227
1228         if (prefs_common.filter_on_inc)
1229                 folder_table = g_hash_table_new(NULL, NULL);
1230         msgs = proc_mbox(dest, tmp_mbox, folder_table);
1231
1232         unlink(tmp_mbox);
1233         if (msgs >= 0) empty_mbox(mbox);
1234         unlock_mbox(mbox, lockfd, LOCK_FLOCK);
1235
1236         if (folder_table) {
1237                 if (!prefs_common.scan_all_after_inc) {
1238                 g_hash_table_insert(folder_table, dest,
1239                                     GINT_TO_POINTER(1));
1240                         folderview_update_item_foreach(folder_table, TRUE);
1241                 }
1242                 g_hash_table_destroy(folder_table);
1243         } else if (!prefs_common.scan_all_after_inc) {
1244                 folderview_update_item(dest, TRUE);
1245         }
1246
1247         return msgs;
1248 }
1249
1250 void inc_lock(void)
1251 {
1252         inc_lock_count++;
1253 }
1254
1255 void inc_unlock(void)
1256 {
1257         if (inc_lock_count > 0)
1258                 inc_lock_count--;
1259 }
1260
1261 static guint autocheck_timer = 0;
1262 static gpointer autocheck_data = NULL;
1263
1264 static void inc_notify_cmd(gint new_msgs, gboolean notify)
1265 {
1266
1267         gchar *buf;
1268
1269         if (!(new_msgs && notify && prefs_common.newmail_notify_cmd &&
1270             *prefs_common.newmail_notify_cmd))
1271                      return;
1272         if ((buf = strchr(prefs_common.newmail_notify_cmd, '%')) &&
1273                 buf[1] == 'd' && !strchr(&buf[1], '%'))
1274                 buf = g_strdup_printf(prefs_common.newmail_notify_cmd, 
1275                                       new_msgs);
1276         else
1277                 buf = g_strdup(prefs_common.newmail_notify_cmd);
1278
1279         execute_command_line(buf, TRUE);
1280
1281         g_free(buf);
1282 }
1283  
1284 void inc_autocheck_timer_init(MainWindow *mainwin)
1285 {
1286         autocheck_data = mainwin;
1287         inc_autocheck_timer_set();
1288 }
1289
1290 static void inc_autocheck_timer_set_interval(guint interval)
1291 {
1292         inc_autocheck_timer_remove();
1293         /* last test is to avoid re-enabling auto_check after modifying 
1294            the common preferences */
1295         if (prefs_common.autochk_newmail && autocheck_data
1296             && prefs_common.work_offline == FALSE) {
1297                 autocheck_timer = gtk_timeout_add
1298                         (interval, inc_autocheck_func, autocheck_data);
1299                 debug_print("added timer = %d\n", autocheck_timer);
1300         }
1301 }
1302
1303 void inc_autocheck_timer_set(void)
1304 {
1305         inc_autocheck_timer_set_interval(prefs_common.autochk_itv * 60000);
1306 }
1307
1308 void inc_autocheck_timer_remove(void)
1309 {
1310         if (autocheck_timer) {
1311                 debug_print("removed timer = %d\n", autocheck_timer);
1312                 gtk_timeout_remove(autocheck_timer);
1313                 autocheck_timer = 0;
1314         }
1315 }
1316
1317 static gint inc_autocheck_func(gpointer data)
1318 {
1319         MainWindow *mainwin = (MainWindow *)data;
1320
1321         if (inc_lock_count) {
1322                 debug_print("autocheck is locked.\n");
1323                 inc_autocheck_timer_set_interval(1000);
1324                 return FALSE;
1325         }
1326
1327         inc_all_account_mail(mainwin, prefs_common.newmail_notify_auto);
1328
1329         return FALSE;
1330 }