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