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