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