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