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