9b68a4d3911760e653140f70520cc42aa83aac2d
[claws.git] / src / inc.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2002 Hiroyuki Yamamoto
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #endif
23
24 #include "defs.h"
25
26 #include <glib.h>
27 #include <gtk/gtkmain.h>
28 #include <gtk/gtkwindow.h>
29 #include <gtk/gtksignal.h>
30 #include <gtk/gtkprogressbar.h>
31 #include <stdio.h>
32 #include <unistd.h>
33 #include <string.h>
34 #include <time.h>
35 #include <sys/types.h>
36 #include <sys/stat.h>
37 #include <sys/wait.h>
38 #include <signal.h>
39 #include <errno.h>
40
41 #include "intl.h"
42 #include "main.h"
43 #include "inc.h"
44 #include "mainwindow.h"
45 #include "folderview.h"
46 #include "summaryview.h"
47 #include "prefs_common.h"
48 #include "prefs_account.h"
49 #include "account.h"
50 #include "procmsg.h"
51 #include "socket.h"
52 #include "ssl.h"
53 #include "pop.h"
54 #include "recv.h"
55 #include "mbox.h"
56 #include "utils.h"
57 #include "gtkutils.h"
58 #include "statusbar.h"
59 #include "manage_window.h"
60 #include "stock_pixmap.h"
61 #include "progressdialog.h"
62 #include "inputdialog.h"
63 #include "alertpanel.h"
64 #include "filter.h"
65 #include "automaton.h"
66 #include "folder.h"
67 #include "filtering.h"
68 #include "selective_download.h"
69
70 static GList *inc_dialog_list = NULL;
71
72 static guint inc_lock_count = 0;
73
74 static GdkPixmap *currentxpm;
75 static GdkBitmap *currentxpmmask;
76 static GdkPixmap *errorxpm;
77 static GdkBitmap *errorxpmmask;
78 static GdkPixmap *okxpm;
79 static GdkBitmap *okxpmmask;
80
81 #define MSGBUFSIZE      8192
82
83 static void inc_finished                (MainWindow             *mainwin,
84                                          gboolean                new_messages);
85 static gint inc_account_mail            (PrefsAccount           *account,
86                                          MainWindow             *mainwin);
87
88 static IncProgressDialog *inc_progress_dialog_create    (void);
89 static void inc_progress_dialog_destroy (IncProgressDialog      *inc_dialog);
90
91 static IncSession *inc_session_new      (PrefsAccount           *account);
92 static void inc_session_destroy         (IncSession             *session);
93 static 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                         folderview_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_autocheck_timer_remove();
174         main_window_lock(mainwin);
175
176         if (prefs_common.use_extinc && prefs_common.extinc_cmd) {
177                 /* external incorporating program */
178                 if (execute_command_line(prefs_common.extinc_cmd, FALSE) < 0) {
179                         main_window_unlock(mainwin);
180                         inc_autocheck_timer_set();
181                         return;
182                 }
183
184                 if (prefs_common.inc_local)
185                         new_msgs = inc_spool();
186
187                 if (new_msgs <= 0)
188                         new_msgs = 1;
189         } else {
190                 if (prefs_common.inc_local) {
191                         new_msgs = inc_spool();
192                         if (new_msgs < 0)
193                                 new_msgs = 0;
194                 }
195                 cur_account->session = STYPE_NORMAL;
196                 new_msgs += inc_account_mail(cur_account, mainwin);
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 }
204
205 void inc_selective_download(MainWindow *mainwin, PrefsAccount *acc, gint session)
206 {
207         GSList *cur;
208         gint new_msgs = 0;
209
210         acc->session = session;
211         inc_account_mail(acc, mainwin);
212         acc->session = STYPE_NORMAL;
213         
214         for (cur = acc->msg_list; cur != NULL; cur = cur->next) {
215                 HeaderItems *items =(HeaderItems*)cur->data;
216
217                 if (items->state == SD_DOWNLOADED && 
218                     items->del_by_old_session == FALSE) {
219                         new_msgs++;                     
220                 }
221         }
222
223         if (new_msgs) {
224                 inc_finished(mainwin, TRUE);
225                 inc_notify_cmd(new_msgs, prefs_common.newmail_notify_manu);
226         }
227 }
228
229 void inc_pop_before_smtp(PrefsAccount *acc)
230 {
231         acc->session = STYPE_POP_BEFORE_SMTP;
232         inc_account_mail(acc, NULL);
233 }
234
235 static gint inc_account_mail(PrefsAccount *account, MainWindow *mainwin)
236 {
237         IncProgressDialog *inc_dialog;
238         IncSession *session;
239         gchar *text[3];
240         FolderItem *item = mainwin->summaryview->folder_item;
241
242         switch (account->protocol) {
243         case A_IMAP4:
244         case A_NNTP:
245                 folderview_check_new(FOLDER(account->folder));
246                 if (!prefs_common.scan_all_after_inc && item != NULL &&
247                     FOLDER(account->folder) == item->folder)
248                         folderview_update_item(item, TRUE);
249                 return 1;
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_set_sensitive(mainwin);
269                         main_window_set_menu_sensitive(mainwin);
270                 }
271                         
272                 return inc_start(inc_dialog);
273
274         case A_LOCAL:
275                 inc_spool_account(account);
276                 return 1;
277
278         default:
279                 break;
280         }
281         return 0;
282 }
283
284 void inc_all_account_mail(MainWindow *mainwin, gboolean notify)
285 {
286         GList *list, *queue_list = NULL;
287         IncProgressDialog *inc_dialog;
288         gint 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                 new_msgs = inc_spool();
303                 if (new_msgs < 0)
304                         new_msgs = 0;
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         inc_all_spool();
318
319         /* check IMAP4 folders */
320         for (; list != NULL; list = list->next) {
321                 PrefsAccount *account = list->data;
322                 if ((account->protocol == A_IMAP4 ||
323                      account->protocol == A_NNTP) && account->recv_at_getall) {
324                         FolderItem *item = mainwin->summaryview->folder_item;
325
326                         folderview_check_new(FOLDER(account->folder));
327                         if (!prefs_common.scan_all_after_inc && item != NULL &&
328                             FOLDER(account->folder) == item->folder)
329                                 folderview_update_item(item, TRUE);
330                 }
331         }
332
333         /* check POP3 accounts */
334         for (list = account_get_list(); list != NULL; list = list->next) {
335                 IncSession *session;
336                 PrefsAccount *account = list->data;
337                 account->session = STYPE_NORMAL;
338                 if (account->recv_at_getall) {
339                         session = inc_session_new(account);
340                         if (session)
341                                 queue_list = g_list_append(queue_list, session);
342                 }
343         }
344
345         if (!queue_list) {
346                 inc_finished(mainwin, new_msgs > 0);
347                 main_window_unlock(mainwin);
348                 inc_notify_cmd(new_msgs, notify);
349                 inc_autocheck_timer_set();
350                 return;
351         }
352
353         inc_dialog = inc_progress_dialog_create();
354         inc_dialog->queue_list = queue_list;
355         inc_dialog->mainwin = mainwin;
356         for (list = queue_list; list != NULL; list = list->next) {
357                 IncSession *session = list->data;
358                 gchar *text[3];
359
360                 session->data = inc_dialog;
361
362                 text[0] = NULL;
363                 text[1] = session->pop3_state->ac_prefs->account_name;
364                 text[2] = _("Standby");
365                 gtk_clist_append(GTK_CLIST(inc_dialog->dialog->clist), text);
366         }
367
368         toolbar_set_sensitive(mainwin);
369         main_window_set_menu_sensitive(mainwin);
370
371         new_msgs += inc_start(inc_dialog);
372
373         inc_finished(mainwin, new_msgs > 0);
374         main_window_unlock(mainwin);
375         inc_notify_cmd(new_msgs, notify);
376         inc_autocheck_timer_set();
377 }
378
379 static IncProgressDialog *inc_progress_dialog_create(void)
380 {
381         IncProgressDialog *dialog;
382         ProgressDialog *progress;
383
384         dialog = g_new0(IncProgressDialog, 1);
385
386         progress = progress_dialog_create();
387         gtk_window_set_title(GTK_WINDOW(progress->window),
388                              _("Retrieving new messages"));
389         gtk_signal_connect(GTK_OBJECT(progress->cancel_btn), "clicked",
390                            GTK_SIGNAL_FUNC(inc_cancel_cb), dialog);
391         gtk_signal_connect(GTK_OBJECT(progress->window), "delete_event",
392                            GTK_SIGNAL_FUNC(inc_dialog_delete_cb), dialog);
393         /* manage_window_set_transient(GTK_WINDOW(progress->window)); */
394
395         progress_dialog_set_value(progress, 0.0);
396
397         stock_pixmap_gdk(progress->clist, STOCK_PIXMAP_COMPLETE,
398                          &okxpm, &okxpmmask);
399         stock_pixmap_gdk(progress->clist, STOCK_PIXMAP_CONTINUE,
400                          &currentxpm, &currentxpmmask);
401         stock_pixmap_gdk(progress->clist, STOCK_PIXMAP_ERROR,
402                          &errorxpm, &errorxpmmask);
403
404         if (prefs_common.recv_dialog_mode == RECV_DIALOG_ALWAYS ||
405             (prefs_common.recv_dialog_mode == RECV_DIALOG_ACTIVE &&
406              manage_window_get_focus_window())) {
407                 dialog->show_dialog = TRUE;
408                 gtk_widget_show_now(progress->window);
409         }
410
411         dialog->dialog = progress;
412         dialog->queue_list = NULL;
413
414         inc_dialog_list = g_list_append(inc_dialog_list, dialog);
415
416         return dialog;
417 }
418
419 static void inc_progress_dialog_clear(IncProgressDialog *inc_dialog)
420 {
421         progress_dialog_set_value(inc_dialog->dialog, 0.0);
422         progress_dialog_set_label(inc_dialog->dialog, "");
423         if (inc_dialog->mainwin)
424                 gtk_progress_bar_update
425                         (GTK_PROGRESS_BAR(inc_dialog->mainwin->progressbar), 0.0);
426 }
427
428 static void inc_progress_dialog_destroy(IncProgressDialog *inc_dialog)
429 {
430         g_return_if_fail(inc_dialog != NULL);
431
432         inc_dialog_list = g_list_remove(inc_dialog_list, inc_dialog);
433         if (inc_dialog->mainwin)
434                 gtk_progress_bar_update
435                         (GTK_PROGRESS_BAR(inc_dialog->mainwin->progressbar), 0.0);
436         progress_dialog_destroy(inc_dialog->dialog);
437
438         g_free(inc_dialog);
439 }
440
441 static IncSession *inc_session_new(PrefsAccount *account)
442 {
443         IncSession *session;
444
445         g_return_val_if_fail(account != NULL, NULL);
446
447         if (account->protocol != A_POP3 && account->protocol != A_APOP)
448                 return NULL;
449         if (!account->recv_server || !account->userid)
450                 return NULL;
451
452         session = g_new0(IncSession, 1);
453         session->pop3_state = pop3_state_new(account);
454         session->pop3_state->data = session;
455         session->folder_table = g_hash_table_new(NULL, NULL);
456
457         return session;
458 }
459
460 static void inc_session_destroy(IncSession *session)
461 {
462         g_return_if_fail(session != NULL);
463
464         pop3_state_destroy(session->pop3_state);
465         g_hash_table_destroy(session->folder_table);
466         g_free(session);
467 }
468
469 static gint inc_start(IncProgressDialog *inc_dialog)
470 {
471         IncSession *session;
472         GtkCList *clist = GTK_CLIST(inc_dialog->dialog->clist);
473         Pop3State *pop3_state;
474         IncState inc_state;
475         gint num = 0;
476         gint error_num = 0;
477         gint new_msgs = 0;
478         gchar *msg;
479         gchar *fin_msg;
480
481         while (inc_dialog->queue_list != NULL) {
482                 session = inc_dialog->queue_list->data;
483                 pop3_state = session->pop3_state;
484
485                 inc_progress_dialog_clear(inc_dialog);
486
487                 gtk_clist_moveto(clist, num, -1, 1.0, 0.0);
488
489                 pop3_state->user = g_strdup(pop3_state->ac_prefs->userid);
490                 if (pop3_state->ac_prefs->passwd)
491                         pop3_state->pass =
492                                 g_strdup(pop3_state->ac_prefs->passwd);
493                 else if (pop3_state->ac_prefs->tmp_pass)
494                         pop3_state->pass =
495                                 g_strdup(pop3_state->ac_prefs->tmp_pass);
496                 else {
497                         gchar *pass;
498
499                         pass = input_dialog_query_password
500                                 (pop3_state->ac_prefs->recv_server,
501                                  pop3_state->user);
502
503                         if (inc_dialog->mainwin && inc_dialog->show_dialog)
504                                 manage_window_focus_in
505                                         (inc_dialog->mainwin->window,
506                                          NULL, NULL);
507                         if (pass) {
508                                 pop3_state->ac_prefs->tmp_pass = g_strdup(pass);
509                                 pop3_state->pass = pass;
510                         } else {
511                                 inc_session_destroy(session);
512                                 inc_dialog->queue_list = g_list_remove
513                                         (inc_dialog->queue_list, session);
514                                 continue;
515                         }
516                 }
517
518                 gtk_clist_set_pixmap(clist, num, 0, currentxpm, currentxpmmask);
519                 gtk_clist_set_text(clist, num, 2, _("Retrieving"));
520
521                 /* begin POP3 session */
522                 inc_state = inc_pop3_session_do(session);
523
524                 switch (inc_state) {
525                 case INC_SUCCESS:
526                         if (pop3_state->cur_total_num > 0)
527                                 msg = g_strdup_printf
528                                         (_("Done (%d message(s) (%s) received)"),
529                                          pop3_state->cur_total_num,
530                                          to_human_readable(pop3_state->cur_total_recv_bytes));
531                         else
532                                 msg = g_strdup_printf(_("Done (no new messages)"));
533                         gtk_clist_set_pixmap(clist, num, 0, okxpm, okxpmmask);
534                         gtk_clist_set_text(clist, num, 2, msg);
535                         g_free(msg);
536                         break;
537                 case INC_CONNECT_ERROR:
538                         gtk_clist_set_pixmap(clist, num, 0, errorxpm, errorxpmmask);
539                         gtk_clist_set_text(clist, num, 2, _("Connection failed"));
540                         break;
541                 case INC_AUTH_FAILED:
542                         gtk_clist_set_pixmap(clist, num, 0, errorxpm, errorxpmmask);
543                         gtk_clist_set_text(clist, num, 2, _("Auth failed"));
544                         break;
545                 case INC_LOCKED:
546                         gtk_clist_set_pixmap(clist, num, 0, errorxpm, errorxpmmask);
547                         gtk_clist_set_text(clist, num, 2, _("Locked"));
548                         break;
549                 case INC_ERROR:
550                 case INC_NOSPACE:
551                         gtk_clist_set_pixmap(clist, num, 0, errorxpm, errorxpmmask);
552                         gtk_clist_set_text(clist, num, 2, _("Error"));
553                         break;
554                 case INC_CANCEL:
555                         gtk_clist_set_pixmap(clist, num, 0, okxpm, okxpmmask);
556                         gtk_clist_set_text(clist, num, 2, _("Cancelled"));
557                         break;
558                 default:
559                         break;
560                 }
561                 
562                 if (pop3_state->error_val == PS_AUTHFAIL) {
563                         if(!prefs_common.no_recv_err_panel) {
564                                 if((prefs_common.recv_dialog_mode == RECV_DIALOG_ALWAYS) ||
565                                     ((prefs_common.recv_dialog_mode == RECV_DIALOG_ACTIVE) && focus_window)) {
566                                         manage_window_focus_in(inc_dialog->dialog->window, NULL, NULL);
567                                 }
568                                 alertpanel_error
569                                         (_("Authorization for %s on %s failed"),
570                                          pop3_state->user,
571                                          pop3_state->ac_prefs->recv_server);
572                         }
573                 }
574
575                 statusbar_pop_all();
576
577                 /* CLAWS: perform filtering actions on dropped message */
578                 if (global_processing != NULL) {
579                         FolderItem *processing, *inbox;
580                         MsgInfo *msginfo;
581                         GSList *msglist, *msglist_element;
582
583                         /* CLAWS: get default inbox (perhaps per account) */
584                         if (pop3_state->ac_prefs->inbox) {
585                                 /* CLAWS: get destination folder / mailbox */
586                                 inbox = folder_find_item_from_identifier(pop3_state->ac_prefs->inbox);
587                                 if (!inbox)
588                                         inbox = folder_get_default_inbox();
589                         } else
590                                 inbox = folder_get_default_inbox();
591
592                         /* get list of messages in processing */
593                         processing = folder_get_default_processing();
594                         folder_item_scan(processing);
595                         msglist = folder_item_get_msg_list(processing);
596
597                         /* process messages */
598                         for(msglist_element = msglist; msglist_element != NULL; msglist_element = msglist_element->next) {
599                                 msginfo = (MsgInfo *) msglist_element->data;
600                                 /* filter if enabled in prefs or move to inbox if not */
601                                 if(pop3_state->ac_prefs->filter_on_recv) {
602                                         filter_message_by_msginfo_with_inbox(global_processing, msginfo,
603                                                                              session->folder_table,
604                                                                              inbox);
605                                 } else {
606                                         folder_item_move_msg(inbox, msginfo);
607                                         g_hash_table_insert(session->folder_table, inbox,
608                                                             GINT_TO_POINTER(1));
609                                 }
610                                 procmsg_msginfo_free(msginfo);
611                         }
612                         g_slist_free(msglist);
613                 }
614
615
616                 new_msgs += pop3_state->cur_total_num;
617
618                 if (!prefs_common.scan_all_after_inc) {
619                         folder_item_scan_foreach(session->folder_table);
620                         folderview_update_item_foreach
621                                 (session->folder_table,
622                                  !prefs_common.open_inbox_on_inc);
623                 }
624
625                 if (pop3_state->error_val == PS_AUTHFAIL &&
626                     pop3_state->ac_prefs->tmp_pass) {
627                         g_free(pop3_state->ac_prefs->tmp_pass);
628                         pop3_state->ac_prefs->tmp_pass = NULL;
629                 }
630
631                 pop3_write_uidl_list(pop3_state);
632
633                 if (inc_state != INC_SUCCESS && inc_state != INC_CANCEL) {
634                         error_num++;
635                         if (inc_state == INC_NOSPACE) {
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 = GDK_INPUT_READ;
732         for (i = POP3_GREETING_RECV + 1; i < N_POP3_PHASE; ) {
733                 atm->state[i++].condition = GDK_INPUT_WRITE;
734                 atm->state[i++].condition = GDK_INPUT_READ;
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(NULL, 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_gdk_input_add(sockinfo,
803                                       atm->state[atm->num].condition,
804                                       automaton_input_cb, atm);
805
806         while (!atm->terminated)
807                 gtk_main_iteration();
808
809         log_verbosity_set(FALSE);
810         /* oha: see above */
811         recv_set_ui_func(NULL, NULL);
812
813         automaton_destroy(atm);
814
815         if (session->inc_state != INC_SUCCESS)
816                 return session->inc_state;
817
818         switch (pop3_state->error_val) {
819         case PS_SUCCESS:
820                 session->inc_state = INC_SUCCESS;
821                 break;
822         case PS_AUTHFAIL:
823                 session->inc_state = INC_AUTH_FAILED;
824                 break;
825         case PS_IOERR:
826                 session->inc_state = INC_NOSPACE;
827                 break;
828         case PS_LOCKBUSY:
829                 session->inc_state = INC_LOCKED;
830                 break;
831         default:
832                 session->inc_state = INC_ERROR;
833                 break;
834         }
835
836         return session->inc_state;
837 }
838
839 static gint pop3_automaton_terminate(SockInfo *source, Automaton *atm)
840 {
841         if (atm->terminated) return 0;
842
843         if (atm->tag > 0) {
844                 gdk_input_remove(atm->tag);
845                 atm->tag = 0;
846         }
847         if (atm->timeout_tag > 0) {
848                 gtk_timeout_remove(atm->timeout_tag);
849                 atm->timeout_tag = 0;
850         }
851         if (source)
852                 sock_close(source);
853
854         atm->terminated = TRUE;
855
856         return 0;
857 }
858
859 static gboolean inc_pop3_recv_func(SockInfo *sock, gint count, gint read_bytes,
860                                    gpointer data)
861 {
862         gchar buf[MSGBUFSIZE];
863         IncSession *session = (IncSession *)data;
864         Pop3State *state = session->pop3_state;
865         IncProgressDialog *inc_dialog = (IncProgressDialog *)session->data;
866         ProgressDialog *dialog = inc_dialog->dialog;
867         gint cur_total;
868         gchar *total_size;
869
870         cur_total = state->cur_total_bytes + read_bytes;
871         if (cur_total > state->total_bytes)
872                 cur_total = state->total_bytes;
873
874         Xstrdup_a(total_size, to_human_readable(state->total_bytes),
875                   return FALSE);
876         g_snprintf(buf, sizeof(buf),
877                    _("Retrieving message (%d / %d) (%s / %s)"),
878                    state->cur_msg, state->count,
879                    to_human_readable(cur_total), total_size);
880         progress_dialog_set_label(dialog, buf);
881
882         progress_dialog_set_percentage
883                 (dialog, (gfloat)cur_total / (gfloat)state->total_bytes);
884         if (inc_dialog->mainwin)
885                 gtk_progress_bar_update
886                         (GTK_PROGRESS_BAR(inc_dialog->mainwin->progressbar),
887                          (gfloat)cur_total / (gfloat)state->total_bytes);
888         GTK_EVENTS_FLUSH();
889
890         if (session->inc_state == INC_CANCEL)
891                 return FALSE;
892         else
893                 return TRUE;
894 }
895
896 void inc_progress_update(Pop3State *state, Pop3Phase phase)
897 {
898         gchar buf[MSGBUFSIZE];
899         IncSession *session = (IncSession *)state->data;
900         IncProgressDialog *inc_dialog = (IncProgressDialog *)session->data;
901         ProgressDialog *dialog = inc_dialog->dialog;
902         gchar *total_size;
903
904         switch (phase) {
905         case POP3_GREETING_RECV:
906                 break;
907         case POP3_GETAUTH_USER_SEND:
908         case POP3_GETAUTH_PASS_SEND:
909         case POP3_GETAUTH_APOP_SEND:
910                 progress_dialog_set_label(dialog, _("Authenticating..."));
911                 break;
912         case POP3_GETRANGE_STAT_SEND:
913                 progress_dialog_set_label
914                         (dialog, _("Getting the number of new messages (STAT)..."));
915                 break;
916         case POP3_GETRANGE_LAST_SEND:
917                 progress_dialog_set_label
918                         (dialog, _("Getting the number of new messages (LAST)..."));
919                 break;
920         case POP3_GETRANGE_UIDL_SEND:
921                 progress_dialog_set_label
922                         (dialog, _("Getting the number of new messages (UIDL)..."));
923                 break;
924         case POP3_GETSIZE_LIST_SEND:
925                 progress_dialog_set_label
926                         (dialog, _("Getting the size of messages (LIST)..."));
927                 break;
928         case POP3_TOP_SEND:
929                 g_snprintf(buf, sizeof(buf),
930                            _("Retrieving header (%d / %d)"),
931                            state->cur_msg, state->count);
932                 progress_dialog_set_label (dialog, buf);
933                 progress_dialog_set_percentage
934                         (dialog,
935                          (gfloat)(state->cur_msg) /
936                          (gfloat)(state->count));
937                 if (inc_dialog->mainwin)
938                         gtk_progress_bar_update 
939                                 (GTK_PROGRESS_BAR(inc_dialog->mainwin->progressbar),
940                                  (gfloat)(state->cur_msg) /
941                                  (gfloat)(state->count));
942                 break;
943         case POP3_RETR_SEND:
944                 Xstrdup_a(total_size, to_human_readable(state->total_bytes), return);
945                 g_snprintf(buf, sizeof(buf),
946                            _("Retrieving message (%d / %d) (%s / %s)"),
947                            state->cur_msg, state->count,
948                            to_human_readable(state->cur_total_bytes),
949                            total_size);
950                 progress_dialog_set_label(dialog, buf);
951                 progress_dialog_set_percentage
952                         (dialog,
953                          (gfloat)(state->cur_total_bytes) /
954                          (gfloat)(state->total_bytes));
955                 if (inc_dialog->mainwin)
956                         gtk_progress_bar_update
957                                 (GTK_PROGRESS_BAR(inc_dialog->mainwin->progressbar),
958                                  (gfloat)(state->cur_total_bytes) /
959                                  (gfloat)(state->total_bytes));
960                 break;
961         case POP3_DELETE_SEND:
962                 if (state->msg[state->cur_msg].recv_time < state->current_time) {
963                         g_snprintf(buf, sizeof(buf), _("Deleting message %d"),
964                                    state->cur_msg);
965                         progress_dialog_set_label(dialog, buf);
966                 }
967                 break;
968         case POP3_LOGOUT_SEND:
969                 progress_dialog_set_label(dialog, _("Quitting"));
970                 break;
971         default:
972                 break;
973         }
974 }
975
976 gint inc_drop_message(const gchar *file, Pop3State *state)
977 {
978         FolderItem *inbox;
979         FolderItem *dropfolder;
980         IncSession *session = (IncSession *)state->data;
981         gint val;
982         gint msgnum;
983
984         /* CLAWS: get default inbox (perhaps per account) */
985         if (state->ac_prefs->inbox) {
986                 /* CLAWS: get destination folder / mailbox */
987                 inbox = folder_find_item_from_identifier
988                         (state->ac_prefs->inbox);
989                 if (!inbox)
990                         inbox = folder_get_default_inbox();
991         } else
992                 inbox = folder_get_default_inbox();
993         if (!inbox) {
994                 unlink(file);
995                 return -1;
996         }
997
998         /* CLAWS: claws uses a global .processing folder for the filtering. */
999         if (global_processing == NULL) {
1000                 if (state->ac_prefs->filter_on_recv) {
1001                         dropfolder =
1002                                 filter_get_dest_folder(prefs_common.fltlist, file);
1003                         if (!dropfolder) dropfolder = inbox;
1004                         else if (!strcmp(dropfolder->path, FILTER_NOT_RECEIVE)) {
1005                                 debug_print("a message won't be received\n");
1006                                 unlink(file);
1007                                 return 1;
1008                         }
1009                 } else
1010                         dropfolder = inbox;
1011         } else {
1012                 dropfolder = folder_get_default_processing();
1013         }
1014
1015         val = GPOINTER_TO_INT(g_hash_table_lookup
1016                               (session->folder_table, dropfolder));
1017         if (val == 0) {
1018                 folder_item_scan(dropfolder);
1019                 /* force updating */
1020                 if (FOLDER_IS_LOCAL(dropfolder->folder))
1021                         dropfolder->mtime = 0;
1022                 g_hash_table_insert(session->folder_table, dropfolder,
1023                                     GINT_TO_POINTER(1));
1024         }
1025         
1026         /* add msg file to drop folder */
1027         if ((msgnum = folder_item_add_msg(dropfolder, file, TRUE)) < 0) {
1028                 unlink(file);
1029                 return -1;
1030         }
1031
1032         return 0;
1033 }
1034
1035 static void inc_put_error(IncState istate)
1036 {
1037         switch (istate) {
1038         case INC_ERROR:
1039                 if (!prefs_common.no_recv_err_panel)
1040                         alertpanel_error
1041                                 (_("Error occurred while processing mail."));
1042                 break;
1043         case INC_NOSPACE:
1044                 alertpanel_error(_("No disk space left."));
1045                 break;
1046         case INC_LOCKED:
1047                 if (!prefs_common.no_recv_err_panel)
1048                         alertpanel_error(_("Mailbox is locked."));
1049                 break;
1050         default:
1051                 break;
1052         }
1053 }
1054
1055 static void inc_cancel(IncProgressDialog *dialog)
1056 {
1057         IncSession *session;
1058         SockInfo *sockinfo;
1059
1060         g_return_if_fail(dialog != NULL);
1061
1062         if (dialog->queue_list == NULL) {
1063                 inc_progress_dialog_destroy(dialog);
1064                 return;
1065         }
1066
1067         session = dialog->queue_list->data;
1068         sockinfo = session->pop3_state->sockinfo;
1069
1070         if (!sockinfo || session->atm->terminated == TRUE) return;
1071
1072         session->pop3_state->cancelled = TRUE;
1073         session->inc_state = INC_CANCEL;
1074         session->atm->cancelled = TRUE;
1075
1076         log_message(_("Incorporation cancelled\n"));
1077 }
1078
1079 gboolean inc_is_active(void)
1080 {
1081         return (inc_dialog_list != NULL);
1082 }
1083
1084 void inc_cancel_all(void)
1085 {
1086         GList *cur;
1087
1088         for (cur = inc_dialog_list; cur != NULL; cur = cur->next)
1089                 inc_cancel((IncProgressDialog *)cur->data);
1090 }
1091
1092 static void inc_cancel_cb(GtkWidget *widget, gpointer data)
1093 {
1094         inc_cancel((IncProgressDialog *)data);
1095 }
1096
1097 static gint inc_dialog_delete_cb(GtkWidget *widget, GdkEventAny *event,
1098                                  gpointer data)
1099 {
1100         IncProgressDialog *dialog = (IncProgressDialog *)data;
1101
1102         if (dialog->queue_list == NULL)
1103                 inc_progress_dialog_destroy(dialog);
1104
1105         return TRUE;
1106 }
1107
1108 static gint inc_spool(void)
1109 {
1110         gchar *mbox, *logname;
1111         gint msgs;
1112
1113         logname = g_get_user_name();
1114         mbox = g_strconcat(prefs_common.spool_path
1115                            ? prefs_common.spool_path : DEFAULT_SPOOL_PATH,
1116                            G_DIR_SEPARATOR_S, logname, NULL);
1117         msgs = get_spool(folder_get_default_inbox(), mbox);
1118         g_free(mbox);
1119
1120         return msgs;
1121 }
1122
1123 static void inc_spool_account(PrefsAccount *account)
1124 {
1125         FolderItem *inbox;
1126
1127         if (account->inbox) {
1128                 inbox = folder_find_item_from_path(account->inbox);
1129                 if (!inbox)
1130                         inbox = folder_get_default_inbox();
1131         } else
1132                 inbox = folder_get_default_inbox();
1133
1134         get_spool(inbox, account->local_mbox);
1135 }
1136
1137 static void inc_all_spool(void)
1138 {
1139         GList *list = NULL;
1140
1141         list = account_get_list();
1142         if (!list) return;
1143
1144         for (; list != NULL; list = list->next) {
1145                 PrefsAccount *account = list->data;
1146
1147                 if ((account->protocol == A_LOCAL) &&
1148                     (account->recv_at_getall))
1149                         inc_spool_account(account);
1150         }
1151 }
1152
1153 static gint get_spool(FolderItem *dest, const gchar *mbox)
1154 {
1155         gint msgs, size;
1156         gint lockfd;
1157         gchar tmp_mbox[MAXPATHLEN + 1];
1158         GHashTable *folder_table = NULL;
1159
1160         g_return_val_if_fail(dest != NULL, -1);
1161         g_return_val_if_fail(mbox != NULL, -1);
1162
1163         if (!is_file_exist(mbox) || (size = get_file_size(mbox)) == 0) {
1164                 debug_print("no messages in local mailbox.\n");
1165                 return 0;
1166         } else if (size < 0)
1167                 return -1;
1168
1169         if ((lockfd = lock_mbox(mbox, LOCK_FLOCK)) < 0)
1170                 return -1;
1171
1172         g_snprintf(tmp_mbox, sizeof(tmp_mbox), "%s%ctmpmbox.%08x",
1173                    get_tmp_dir(), G_DIR_SEPARATOR, (gint)mbox);
1174
1175         if (copy_mbox(mbox, tmp_mbox) < 0) {
1176                 unlock_mbox(mbox, lockfd, LOCK_FLOCK);
1177                 return -1;
1178         }
1179
1180         debug_print("Getting new messages from %s into %s...\n",
1181                     mbox, dest->path);
1182
1183         if (prefs_common.filter_on_inc)
1184                 folder_table = g_hash_table_new(NULL, NULL);
1185         msgs = proc_mbox(dest, tmp_mbox, folder_table);
1186
1187         unlink(tmp_mbox);
1188         if (msgs >= 0) empty_mbox(mbox);
1189         unlock_mbox(mbox, lockfd, LOCK_FLOCK);
1190
1191         if (folder_table) {
1192                 if (!prefs_common.scan_all_after_inc) {
1193                 g_hash_table_insert(folder_table, dest,
1194                                     GINT_TO_POINTER(1));
1195                         folderview_update_item_foreach
1196                                 (folder_table, !prefs_common.open_inbox_on_inc);
1197                 }
1198                 g_hash_table_destroy(folder_table);
1199         } else if (!prefs_common.scan_all_after_inc) {
1200                 folderview_update_item(dest, TRUE);
1201         }
1202
1203         return msgs;
1204 }
1205
1206 void inc_lock(void)
1207 {
1208         inc_lock_count++;
1209 }
1210
1211 void inc_unlock(void)
1212 {
1213         if (inc_lock_count > 0)
1214                 inc_lock_count--;
1215 }
1216
1217 static guint autocheck_timer = 0;
1218 static gpointer autocheck_data = NULL;
1219
1220 static void inc_notify_cmd(gint new_msgs, gboolean notify)
1221 {
1222
1223         gchar *buf;
1224
1225         if (!(new_msgs && notify && prefs_common.newmail_notify_cmd &&
1226             *prefs_common.newmail_notify_cmd))
1227                      return;
1228         if ((buf = strchr(prefs_common.newmail_notify_cmd, '%')) &&
1229                 buf[1] == 'd' && !strchr(&buf[1], '%'))
1230                 buf = g_strdup_printf(prefs_common.newmail_notify_cmd, 
1231                                       new_msgs);
1232         else
1233                 buf = g_strdup(prefs_common.newmail_notify_cmd);
1234
1235         execute_command_line(buf, TRUE);
1236
1237         g_free(buf);
1238 }
1239  
1240 void inc_autocheck_timer_init(MainWindow *mainwin)
1241 {
1242         autocheck_data = mainwin;
1243         inc_autocheck_timer_set();
1244 }
1245
1246 static void inc_autocheck_timer_set_interval(guint interval)
1247 {
1248         inc_autocheck_timer_remove();
1249         /* last test is to avoid re-enabling auto_check after modifying 
1250            the common preferences */
1251         if (prefs_common.autochk_newmail && autocheck_data
1252             && prefs_common.work_offline == FALSE) {
1253                 autocheck_timer = gtk_timeout_add
1254                         (interval, inc_autocheck_func, autocheck_data);
1255                 debug_print("added timer = %d\n", autocheck_timer);
1256         }
1257 }
1258
1259 void inc_autocheck_timer_set(void)
1260 {
1261         inc_autocheck_timer_set_interval(prefs_common.autochk_itv * 60000);
1262 }
1263
1264 void inc_autocheck_timer_remove(void)
1265 {
1266         if (autocheck_timer) {
1267                 debug_print("removed timer = %d\n", autocheck_timer);
1268                 gtk_timeout_remove(autocheck_timer);
1269                 autocheck_timer = 0;
1270         }
1271 }
1272
1273 static gint inc_autocheck_func(gpointer data)
1274 {
1275         MainWindow *mainwin = (MainWindow *)data;
1276
1277         if (inc_lock_count) {
1278                 debug_print("autocheck is locked.\n");
1279                 inc_autocheck_timer_set_interval(1000);
1280                 return FALSE;
1281         }
1282
1283         inc_all_account_mail(mainwin, prefs_common.newmail_notify_auto);
1284
1285         return FALSE;
1286 }