2a9955fd6a2f40f1140173cfff87f75cf4a3dae3
[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 "folder.h"
65 #include "filtering.h"
66 #include "log.h"
67 #include "hooks.h"
68
69 static GList *inc_dialog_list = NULL;
70
71 static guint inc_lock_count = 0;
72
73 static GdkPixmap *currentxpm;
74 static GdkBitmap *currentxpmmask;
75 static GdkPixmap *errorxpm;
76 static GdkBitmap *errorxpmmask;
77 static GdkPixmap *okxpm;
78 static GdkBitmap *okxpmmask;
79
80 #define MSGBUFSIZE      8192
81
82 static void inc_finished                (MainWindow             *mainwin,
83                                          gboolean                new_messages);
84 static gint inc_account_mail            (PrefsAccount           *account,
85                                          MainWindow             *mainwin);
86
87 static IncProgressDialog *inc_progress_dialog_create    (void);
88 static void inc_progress_dialog_destroy (IncProgressDialog      *inc_dialog);
89
90 static IncSession *inc_session_new      (PrefsAccount           *account);
91 static void inc_session_destroy         (IncSession             *session);
92 static gint inc_start                   (IncProgressDialog      *inc_dialog);
93 static IncState inc_pop3_session_do     (IncSession             *session);
94
95 static gint inc_recv_data_progressive   (Session        *session,
96                                          guint           cur_len,
97                                          guint           total_len,
98                                          gpointer        data);
99 static gint inc_recv_data_finished      (Session        *session,
100                                          guint           len,
101                                          gpointer        data);
102 static gint inc_recv_message            (Session        *session,
103                                          const gchar    *msg,
104                                          gpointer        data);
105
106 static void inc_put_error               (IncState        istate);
107
108 static void inc_cancel_cb               (GtkWidget      *widget,
109                                          gpointer        data);
110 static gint inc_dialog_delete_cb        (GtkWidget      *widget,
111                                          GdkEventAny    *event,
112                                          gpointer        data);
113
114 static gint inc_spool                   (void);
115 static gint get_spool                   (FolderItem     *dest,
116                                          const gchar    *mbox);
117
118 static gint inc_spool_account(PrefsAccount *account);
119 static gint inc_all_spool(void);
120 static void inc_autocheck_timer_set_interval    (guint           interval);
121 static gint inc_autocheck_func                  (gpointer        data);
122
123 static void inc_notify_cmd              (gint new_msgs, 
124                                          gboolean notify);
125
126 #define FOLDER_SUMMARY_MISMATCH(f, s) \
127         (f) && (s) ? ((s)->newmsgs != (f)->new) || ((f)->unread != (s)->unread) || ((f)->total != (s)->messages) \
128         : FALSE
129         
130 /**
131  * inc_finished:
132  * @mainwin: Main window.
133  * @new_messages: TRUE if some messages have been received.
134  * 
135  * Update the folder view and the summary view after receiving
136  * messages.  If @new_messages is FALSE, this function avoids unneeded
137  * updating.
138  **/
139 static void inc_finished(MainWindow *mainwin, gboolean new_messages)
140 {
141         FolderItem *item;
142
143         if (prefs_common.scan_all_after_inc)
144                 folderview_check_new(NULL);
145
146         if (!new_messages && !prefs_common.scan_all_after_inc) return;
147
148         if (prefs_common.open_inbox_on_inc) {
149                 item = cur_account && cur_account->inbox
150                         ? folder_find_item_from_identifier(cur_account->inbox)
151                         : folder_get_default_inbox();
152                 if (FOLDER_SUMMARY_MISMATCH(item, mainwin->summaryview)) {      
153                         folderview_unselect(mainwin->folderview);
154                         folderview_select(mainwin->folderview, item);
155                 }       
156         }
157 }
158
159 void inc_mail(MainWindow *mainwin, gboolean notify)
160 {
161         gint new_msgs = 0;
162         gint account_new_msgs = 0;
163
164         if (inc_lock_count) return;
165
166         if (prefs_common.work_offline)
167                 if (alertpanel(_("Offline warning"), 
168                                _("You're working offline. Override?"),
169                                _("Yes"), _("No"), NULL) != G_ALERTDEFAULT)
170                 return;
171
172         inc_lock();
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                         account_new_msgs = inc_spool();
186                         if (account_new_msgs > 0)
187                                 new_msgs += account_new_msgs;
188                 }
189         } else {
190                 if (prefs_common.inc_local) {
191                         account_new_msgs = inc_spool();
192                         if (account_new_msgs > 0)
193                                 new_msgs += account_new_msgs;
194                 }
195                 cur_account->session = STYPE_NORMAL;
196                 account_new_msgs = inc_account_mail(cur_account, mainwin);
197                 if (account_new_msgs > 0)
198                         new_msgs += account_new_msgs;
199         }
200
201         inc_finished(mainwin, new_msgs > 0);
202         main_window_unlock(mainwin);
203         inc_notify_cmd(new_msgs, notify);
204         inc_autocheck_timer_set();
205         inc_unlock();
206 }
207
208 void inc_pop_before_smtp(PrefsAccount *acc)
209 {
210         acc->session = STYPE_POP_BEFORE_SMTP;
211         inc_account_mail(acc, NULL);
212 }
213
214 static gint inc_account_mail(PrefsAccount *account, MainWindow *mainwin)
215 {
216         IncProgressDialog *inc_dialog;
217         IncSession *session;
218         gchar *text[3];
219         FolderItem *item = NULL;
220         
221         if(mainwin && mainwin->summaryview)
222                 item = mainwin->summaryview->folder_item;
223
224         switch (account->protocol) {
225         case A_IMAP4:
226         case A_NNTP:
227                 /* Melvin: bug [14]
228                  * FIXME: it should return foldeview_check_new() value.
229                  * TODO: do it when bug [19] is fixed (IMAP folder sets 
230                  * an incorrect new message count)
231                  */
232                 folderview_check_new(FOLDER(account->folder));
233                 return 0;
234         case A_POP3:
235         case A_APOP:
236                 session = inc_session_new(account);
237                 if (!session) return 0;
238                 
239                 inc_dialog = inc_progress_dialog_create();
240                 inc_dialog->queue_list = g_list_append(inc_dialog->queue_list,
241                                                        session);
242                 inc_dialog->mainwin = mainwin;
243                 session->data = inc_dialog;
244         
245                 text[0] = NULL;
246                 text[1] = account->account_name;
247                 text[2] = _("Standby");
248                 gtk_clist_append(GTK_CLIST(inc_dialog->dialog->clist), text);
249                 
250                 if (mainwin) {
251                         toolbar_main_set_sensitive(mainwin);
252                         main_window_set_menu_sensitive(mainwin);
253                 }
254                         
255                 return inc_start(inc_dialog);
256
257         case A_LOCAL:
258                 return inc_spool_account(account);
259
260         default:
261                 break;
262         }
263         return 0;
264 }
265
266 void inc_all_account_mail(MainWindow *mainwin, gboolean notify)
267 {
268         GList *list, *queue_list = NULL;
269         IncProgressDialog *inc_dialog;
270         gint new_msgs = 0;
271         gint account_new_msgs = 0;
272         
273         if (prefs_common.work_offline)
274                 if (alertpanel(_("Offline warning"), 
275                                _("You're working offline. Override?"),
276                                _("Yes"), _("No"), NULL) != G_ALERTDEFAULT)
277                 return;
278
279         if (inc_lock_count) return;
280
281         inc_autocheck_timer_remove();
282         main_window_lock(mainwin);
283
284         if (prefs_common.inc_local) {
285                 account_new_msgs = inc_spool();
286                 if (account_new_msgs > 0)
287                         new_msgs += account_new_msgs;   
288         }
289
290         list = account_get_list();
291         if (!list) {
292                 inc_finished(mainwin, new_msgs > 0);
293                 main_window_unlock(mainwin);
294                 inc_notify_cmd(new_msgs, notify);
295                 inc_autocheck_timer_set();
296                 return;
297         }
298
299         /* check local folders */
300         account_new_msgs = inc_all_spool();
301         if (account_new_msgs > 0)
302                 new_msgs += account_new_msgs;
303
304         /* check IMAP4 folders */
305         for (; list != NULL; list = list->next) {
306                 PrefsAccount *account = list->data;
307                 if ((account->protocol == A_IMAP4 ||
308                      account->protocol == A_NNTP) && account->recv_at_getall) {
309                         new_msgs += folderview_check_new(FOLDER(account->folder));
310                 }
311         }
312
313         /* check POP3 accounts */
314         for (list = account_get_list(); list != NULL; list = list->next) {
315                 IncSession *session;
316                 PrefsAccount *account = list->data;
317                 account->session = STYPE_NORMAL;
318                 if (account->recv_at_getall) {
319                         session = inc_session_new(account);
320                         if (session)
321                                 queue_list = g_list_append(queue_list, session);
322                 }
323         }
324
325         if (!queue_list) {
326                 inc_finished(mainwin, new_msgs > 0);
327                 main_window_unlock(mainwin);
328                 inc_notify_cmd(new_msgs, notify);
329                 inc_autocheck_timer_set();
330                 return;
331         }
332
333         inc_dialog = inc_progress_dialog_create();
334         inc_dialog->queue_list = queue_list;
335         inc_dialog->mainwin = mainwin;
336         for (list = queue_list; list != NULL; list = list->next) {
337                 IncSession *session = list->data;
338                 Pop3Session *pop3_session = POP3_SESSION(session->session);
339                 gchar *text[3];
340
341                 session->data = inc_dialog;
342
343                 text[0] = NULL;
344                 text[1] = pop3_session->ac_prefs->account_name;
345                 text[2] = _("Standby");
346                 gtk_clist_append(GTK_CLIST(inc_dialog->dialog->clist), text);
347         }
348
349         toolbar_main_set_sensitive(mainwin);
350         main_window_set_menu_sensitive(mainwin);
351
352         new_msgs += inc_start(inc_dialog);
353         inc_finished(mainwin, new_msgs > 0);
354         main_window_unlock(mainwin);
355         inc_notify_cmd(new_msgs, notify);
356         inc_autocheck_timer_set();
357 }
358
359 static IncProgressDialog *inc_progress_dialog_create(void)
360 {
361         IncProgressDialog *dialog;
362         ProgressDialog *progress;
363
364         dialog = g_new0(IncProgressDialog, 1);
365
366         progress = progress_dialog_create();
367         gtk_window_set_title(GTK_WINDOW(progress->window),
368                              _("Retrieving new messages"));
369         gtk_signal_connect(GTK_OBJECT(progress->cancel_btn), "clicked",
370                            GTK_SIGNAL_FUNC(inc_cancel_cb), dialog);
371         gtk_signal_connect(GTK_OBJECT(progress->window), "delete_event",
372                            GTK_SIGNAL_FUNC(inc_dialog_delete_cb), dialog);
373         /* manage_window_set_transient(GTK_WINDOW(progress->window)); */
374
375         progress_dialog_set_value(progress, 0.0);
376
377         stock_pixmap_gdk(progress->clist, STOCK_PIXMAP_COMPLETE,
378                          &okxpm, &okxpmmask);
379         stock_pixmap_gdk(progress->clist, STOCK_PIXMAP_CONTINUE,
380                          &currentxpm, &currentxpmmask);
381         stock_pixmap_gdk(progress->clist, STOCK_PIXMAP_ERROR,
382                          &errorxpm, &errorxpmmask);
383
384         if (prefs_common.recv_dialog_mode == RECV_DIALOG_ALWAYS ||
385             (prefs_common.recv_dialog_mode == RECV_DIALOG_ACTIVE &&
386              manage_window_get_focus_window())) {
387                 dialog->show_dialog = TRUE;
388                 gtk_widget_show_now(progress->window);
389         }
390
391         dialog->dialog = progress;
392         dialog->queue_list = NULL;
393
394         inc_dialog_list = g_list_append(inc_dialog_list, dialog);
395
396         return dialog;
397 }
398
399 static void inc_progress_dialog_clear(IncProgressDialog *inc_dialog)
400 {
401         progress_dialog_set_value(inc_dialog->dialog, 0.0);
402         progress_dialog_set_label(inc_dialog->dialog, "");
403         if (inc_dialog->mainwin)
404                 gtk_progress_bar_update
405                         (GTK_PROGRESS_BAR(inc_dialog->mainwin->progressbar), 0.0);
406 }
407
408 static void inc_progress_dialog_destroy(IncProgressDialog *inc_dialog)
409 {
410         g_return_if_fail(inc_dialog != NULL);
411
412         inc_dialog_list = g_list_remove(inc_dialog_list, inc_dialog);
413         if (inc_dialog->mainwin)
414                 gtk_progress_bar_update
415                         (GTK_PROGRESS_BAR(inc_dialog->mainwin->progressbar), 0.0);
416         progress_dialog_destroy(inc_dialog->dialog);
417
418         g_free(inc_dialog);
419 }
420
421 static IncSession *inc_session_new(PrefsAccount *account)
422 {
423         IncSession *session;
424
425         g_return_val_if_fail(account != NULL, NULL);
426
427         if (account->protocol != A_POP3 && account->protocol != A_APOP)
428                 return NULL;
429         if (!account->recv_server || !account->userid)
430                 return NULL;
431
432         session = g_new0(IncSession, 1);
433         session->session = pop3_session_new(account);
434         session->session->data = session;
435
436         return session;
437 }
438
439 static void inc_session_destroy(IncSession *session)
440 {
441         g_return_if_fail(session != NULL);
442
443         session_destroy(session->session);
444         g_free(session);
445 }
446
447 static gint inc_start(IncProgressDialog *inc_dialog)
448 {
449         IncSession *session;
450         GtkCList *clist = GTK_CLIST(inc_dialog->dialog->clist);
451         Pop3Session *pop3_session;
452         IncState inc_state;
453         gint num = 0;
454         gint error_num = 0;
455         gint new_msgs = 0;
456         gchar *msg;
457         gchar *fin_msg;
458         FolderItem *processing, *inbox;
459         MsgInfo *msginfo;
460         GSList *msglist, *msglist_element;
461
462         while (inc_dialog->queue_list != NULL) {
463                 session = inc_dialog->queue_list->data;
464                 pop3_session = POP3_SESSION(session->session);
465
466                 inc_progress_dialog_clear(inc_dialog);
467
468                 gtk_clist_moveto(clist, num, -1, 1.0, 0.0);
469
470                 pop3_session->user = g_strdup(pop3_session->ac_prefs->userid);
471                 if (pop3_session->ac_prefs->passwd)
472                         pop3_session->pass =
473                                 g_strdup(pop3_session->ac_prefs->passwd);
474                 else if (pop3_session->ac_prefs->tmp_pass)
475                         pop3_session->pass =
476                                 g_strdup(pop3_session->ac_prefs->tmp_pass);
477                 else {
478                         gchar *pass;
479
480                         pass = input_dialog_query_password
481                                 (pop3_session->ac_prefs->recv_server,
482                                  pop3_session->user);
483
484                         if (inc_dialog->mainwin && inc_dialog->show_dialog)
485                                 manage_window_focus_in
486                                         (inc_dialog->mainwin->window,
487                                          NULL, NULL);
488                         if (pass) {
489                                 pop3_session->ac_prefs->tmp_pass =
490                                         g_strdup(pass);
491                                 pop3_session->pass = pass;
492                         } else {
493                                 inc_session_destroy(session);
494                                 inc_dialog->queue_list = g_list_remove
495                                         (inc_dialog->queue_list, session);
496                                 continue;
497                         }
498                 }
499
500                 gtk_clist_set_pixmap(clist, num, 0, currentxpm, currentxpmmask);
501                 gtk_clist_set_text(clist, num, 2, _("Retrieving"));
502
503                 session_set_recv_message_notify(session->session,
504                                                 inc_recv_message, session);
505                 session_set_recv_data_progressive_notify
506                         (session->session, inc_recv_data_progressive, session);
507                 session_set_recv_data_notify(session->session,
508                                              inc_recv_data_finished, session);
509
510                 /* begin POP3 session */
511                 inc_state = inc_pop3_session_do(session);
512
513                 switch (inc_state) {
514                 case INC_SUCCESS:
515                         if (pop3_session->cur_total_num > 0)
516                                 msg = g_strdup_printf
517                                         (_("Done (%d message(s) (%s) received)"),
518                                          pop3_session->cur_total_num,
519                                          to_human_readable(pop3_session->cur_total_recv_bytes));
520                         else
521                                 msg = g_strdup_printf(_("Done (no new messages)"));
522                         gtk_clist_set_pixmap(clist, num, 0, okxpm, okxpmmask);
523                         gtk_clist_set_text(clist, num, 2, msg);
524                         g_free(msg);
525                         break;
526                 case INC_CONNECT_ERROR:
527                         gtk_clist_set_pixmap(clist, num, 0, errorxpm, errorxpmmask);
528                         gtk_clist_set_text(clist, num, 2, _("Connection failed"));
529                         break;
530                 case INC_AUTH_FAILED:
531                         gtk_clist_set_pixmap(clist, num, 0, errorxpm, errorxpmmask);
532                         gtk_clist_set_text(clist, num, 2, _("Auth failed"));
533                         break;
534                 case INC_LOCKED:
535                         gtk_clist_set_pixmap(clist, num, 0, errorxpm, errorxpmmask);
536                         gtk_clist_set_text(clist, num, 2, _("Locked"));
537                         break;
538                 case INC_ERROR:
539                 case INC_NO_SPACE:
540                 case INC_IO_ERROR:
541                 case INC_SOCKET_ERROR:
542                         gtk_clist_set_pixmap(clist, num, 0, errorxpm, errorxpmmask);
543                         gtk_clist_set_text(clist, num, 2, _("Error"));
544                         break;
545                 case INC_CANCEL:
546                         gtk_clist_set_pixmap(clist, num, 0, okxpm, okxpmmask);
547                         gtk_clist_set_text(clist, num, 2, _("Cancelled"));
548                         break;
549                 default:
550                         break;
551                 }
552                 
553                 if (pop3_session->error_val == PS_AUTHFAIL) {
554                         if(!prefs_common.no_recv_err_panel) {
555                                 if((prefs_common.recv_dialog_mode == RECV_DIALOG_ALWAYS) ||
556                                     ((prefs_common.recv_dialog_mode == RECV_DIALOG_ACTIVE) && focus_window)) {
557                                         manage_window_focus_in(inc_dialog->dialog->window, NULL, NULL);
558                                 }
559                                 alertpanel_error
560                                         (_("Authorization for %s on %s failed"),
561                                          pop3_session->user,
562                                          pop3_session->ac_prefs->recv_server);
563                         }
564                 }
565
566                 /* CLAWS: perform filtering actions on dropped message */
567                 /* CLAWS: get default inbox (perhaps per account) */
568                 if (pop3_session->ac_prefs->inbox) {
569                         /* CLAWS: get destination folder / mailbox */
570                         inbox = folder_find_item_from_identifier(pop3_session->ac_prefs->inbox);
571                         if (!inbox)
572                                 inbox = folder_get_default_inbox();
573                 } else
574                         inbox = folder_get_default_inbox();
575
576                 /* get list of messages in processing */
577                 processing = folder_get_default_processing();
578                 folder_item_scan(processing);
579                 msglist = folder_item_get_msg_list(processing);
580
581                 folder_item_update_freeze();
582
583                 /* process messages */
584                 for(msglist_element = msglist; msglist_element != NULL; msglist_element = msglist_element->next) {
585                         MailFilteringData mail_filtering_data;
586                         msginfo = (MsgInfo *) msglist_element->data;
587                         
588                         mail_filtering_data.msginfo = msginfo;
589                         
590                         if (!hooks_invoke(MAIL_FILTERING_HOOKLIST, &mail_filtering_data)) {
591                                 /* filter if enabled in prefs or move to inbox if not */
592                                 if(global_processing && pop3_session->ac_prefs->filter_on_recv) {
593                                         filter_message_by_msginfo_with_inbox(global_processing, msginfo,
594                                                                              inbox);
595                                 } else {
596                                         folder_item_move_msg(inbox, msginfo);
597                                 }
598                         }
599                         procmsg_msginfo_free(msginfo);
600                 }
601                 g_slist_free(msglist);
602
603                 folder_item_update_thaw();
604
605
606                 new_msgs += pop3_session->cur_total_num;
607
608                 if (pop3_session->error_val == PS_AUTHFAIL &&
609                     pop3_session->ac_prefs->tmp_pass) {
610                         g_free(pop3_session->ac_prefs->tmp_pass);
611                         pop3_session->ac_prefs->tmp_pass = NULL;
612                 }
613
614                 pop3_write_uidl_list(pop3_session);
615
616                 if (inc_state != INC_SUCCESS && inc_state != INC_CANCEL) {
617                         error_num++;
618                         if (inc_state == INC_ERROR    ||
619                             inc_state == INC_IO_ERROR ||
620                             inc_state == INC_SOCKET_ERROR) {
621                                 inc_put_error(inc_state);
622                         } else if (inc_state == INC_NO_SPACE) {
623                                 inc_put_error(inc_state);
624                                 break;
625                         }
626                 }
627
628                 inc_session_destroy(session);
629                 inc_dialog->queue_list =
630                         g_list_remove(inc_dialog->queue_list, session);
631
632                 num++;
633         }
634
635         if (new_msgs > 0)
636                 fin_msg = g_strdup_printf(_("Finished (%d new message(s))"),
637                                           new_msgs);
638         else
639                 fin_msg = g_strdup_printf(_("Finished (no new messages)"));
640
641         progress_dialog_set_label(inc_dialog->dialog, fin_msg);
642
643         if (error_num && !prefs_common.no_recv_err_panel) {
644                 if (inc_dialog->show_dialog)
645                         manage_window_focus_in(inc_dialog->dialog->window,
646                                                NULL, NULL);
647                 alertpanel_error_log(_("Some errors occurred while getting mail."));
648                 if (inc_dialog->show_dialog)
649                         manage_window_focus_out(inc_dialog->dialog->window,
650                                                 NULL, NULL);
651         }
652
653         while (inc_dialog->queue_list != NULL) {
654                 session = inc_dialog->queue_list->data;
655                 inc_session_destroy(session);
656                 inc_dialog->queue_list =
657                         g_list_remove(inc_dialog->queue_list, session);
658         }
659
660         if (prefs_common.close_recv_dialog)
661                 inc_progress_dialog_destroy(inc_dialog);
662         else {
663                 gtk_window_set_title(GTK_WINDOW(inc_dialog->dialog->window),
664                                      fin_msg);
665                 gtk_label_set_text(GTK_LABEL(GTK_BIN(inc_dialog->dialog->cancel_btn)->child),
666                                    _("Close"));
667         }
668
669         g_free(fin_msg);
670
671         return new_msgs;
672 }
673
674 static IncState inc_pop3_session_do(IncSession *session)
675 {
676         Pop3Session *pop3_session = POP3_SESSION(session->session);
677         IncProgressDialog *inc_dialog = (IncProgressDialog *)session->data;
678         gchar *server;
679         gushort port;
680         gchar *buf;
681
682         debug_print("getting new messages of account %s...\n",
683                     pop3_session->ac_prefs->account_name);
684
685         buf = g_strdup_printf(_("%s: Retrieving new messages"),
686                               pop3_session->ac_prefs->recv_server);
687         gtk_window_set_title(GTK_WINDOW(inc_dialog->dialog->window), buf);
688         g_free(buf);
689
690         server = pop3_session->ac_prefs->recv_server;
691 #if USE_OPENSSL
692         port = pop3_session->ac_prefs->set_popport ?
693                 pop3_session->ac_prefs->popport :
694                 pop3_session->ac_prefs->ssl_pop == SSL_TUNNEL ? 995 : 110;
695         SESSION(pop3_session)->ssl_type = pop3_session->ac_prefs->ssl_pop;
696 #else
697         port = pop3_session->ac_prefs->set_popport ?
698                 pop3_session->ac_prefs->popport : 110;
699 #endif
700
701         statusbar_verbosity_set(TRUE);
702         buf = g_strdup_printf(_("Connecting to POP3 server: %s ..."), server);
703         log_message("%s\n", buf);
704
705         progress_dialog_set_label(inc_dialog->dialog, buf);
706         g_free(buf);
707         GTK_EVENTS_FLUSH();
708
709         statusbar_verbosity_set(FALSE);
710
711         if (session_connect(SESSION(pop3_session), server, port) < 0) {
712                 log_warning(_("Can't connect to POP3 server: %s:%d\n"),
713                             server, port);
714                 if(!prefs_common.no_recv_err_panel) {
715                         if((prefs_common.recv_dialog_mode == RECV_DIALOG_ALWAYS) ||
716                             ((prefs_common.recv_dialog_mode == RECV_DIALOG_ACTIVE) && focus_window)) {
717                                 manage_window_focus_in(inc_dialog->dialog->window, NULL, NULL);
718                         }
719                         alertpanel_error(_("Can't connect to POP3 server: %s:%d"),
720                                          server, port);
721                         manage_window_focus_out(inc_dialog->dialog->window, NULL, NULL);
722                 }
723                 session->inc_state = INC_CONNECT_ERROR;
724                 return INC_CONNECT_ERROR;
725         }
726
727         statusbar_verbosity_set(TRUE);
728
729         while (SESSION(pop3_session)->state != SESSION_DISCONNECTED &&
730                SESSION(pop3_session)->state != SESSION_ERROR)
731                 gtk_main_iteration();
732
733
734         statusbar_verbosity_set(FALSE);
735         if (session->inc_state == INC_SUCCESS) {
736                 switch (pop3_session->error_val) {
737                 case PS_SUCCESS:
738                         session->inc_state = INC_SUCCESS;
739                         break;
740                 case PS_AUTHFAIL:
741                         session->inc_state = INC_AUTH_FAILED;
742                         break;
743                 case PS_IOERR:
744                         session->inc_state = INC_IO_ERROR;
745                         break;
746                 case PS_SOCKET:
747                         session->inc_state = INC_SOCKET_ERROR;
748                         break;
749                 case PS_LOCKBUSY:
750                         session->inc_state = INC_LOCKED;
751                         break;
752                 default:
753                         session->inc_state = INC_ERROR;
754                         break;
755                 }
756         }
757
758         return session->inc_state;
759 }
760
761 static gint inc_recv_data_progressive(Session *session, guint cur_len,
762                                       guint total_len, gpointer data)
763 {
764         gchar buf[MSGBUFSIZE];
765         IncSession *inc_session = (IncSession *)data;
766         Pop3Session *pop3_session = POP3_SESSION(session);
767         IncProgressDialog *inc_dialog = (IncProgressDialog *)inc_session->data;
768         ProgressDialog *dialog = inc_dialog->dialog;
769         gint cur_total;
770         gchar *total_size;
771
772         cur_total = pop3_session->cur_total_bytes + cur_len;
773         if (cur_total > pop3_session->total_bytes)
774                 cur_total = pop3_session->total_bytes;
775
776         Xstrdup_a(total_size, to_human_readable(pop3_session->total_bytes),
777                   return FALSE);
778         g_snprintf(buf, sizeof(buf),
779                    _("Retrieving message (%d / %d) (%s / %s)"),
780                    pop3_session->cur_msg, pop3_session->count,
781                    to_human_readable(cur_total), total_size);
782         progress_dialog_set_label(dialog, buf);
783         progress_dialog_set_percentage
784                 (dialog, (gfloat)cur_total / (gfloat)pop3_session->total_bytes);
785         if (inc_dialog->mainwin)
786                 gtk_progress_bar_update
787                         (GTK_PROGRESS_BAR(inc_dialog->mainwin->progressbar),
788                          (gfloat)cur_total / (gfloat)pop3_session->total_bytes);
789         GTK_EVENTS_FLUSH();
790
791         return 0;
792 }
793
794 static gint inc_recv_data_finished(Session *session, guint len, gpointer data)
795 {
796         inc_recv_data_progressive(session, 0, len, data);
797         return 0;
798 }
799
800 static gint inc_recv_message(Session *session, const gchar *msg, gpointer data)
801 {
802         gchar buf[MSGBUFSIZE];
803         IncSession *inc_session = (IncSession *)data;
804         Pop3Session *pop3_session = POP3_SESSION(session);
805         IncProgressDialog *inc_dialog = (IncProgressDialog *)inc_session->data;
806         ProgressDialog *dialog = inc_dialog->dialog;
807
808         switch (pop3_session->state) {
809         case POP3_GREETING:
810                 break;
811         case POP3_GETAUTH_USER:
812         case POP3_GETAUTH_PASS:
813         case POP3_GETAUTH_APOP:
814                 progress_dialog_set_label(dialog, _("Authenticating..."));
815                 break;
816         case POP3_GETRANGE_STAT:
817                 progress_dialog_set_label
818                         (dialog, _("Getting the number of new messages (STAT)..."));
819                 break;
820         case POP3_GETRANGE_LAST:
821                 progress_dialog_set_label
822                         (dialog, _("Getting the number of new messages (LAST)..."));
823                 break;
824         case POP3_GETRANGE_UIDL:
825                 progress_dialog_set_label
826                         (dialog, _("Getting the number of new messages (UIDL)..."));
827                 break;
828         case POP3_GETSIZE_LIST:
829                 progress_dialog_set_label
830                         (dialog, _("Getting the size of messages (LIST)..."));
831                 break;
832         case POP3_TOP:
833                 g_snprintf(buf, sizeof(buf),
834                            _("Retrieving header (%d / %d)"),
835                            pop3_session->cur_msg, pop3_session->count);
836                 progress_dialog_set_label (dialog, buf);
837                 progress_dialog_set_percentage
838                         (dialog,
839                          (gfloat)(pop3_session->cur_msg) /
840                          (gfloat)(pop3_session->count));
841                 if (inc_dialog->mainwin)
842                         gtk_progress_bar_update 
843                                 (GTK_PROGRESS_BAR(inc_dialog->mainwin->progressbar),
844                                  (gfloat)(pop3_session->cur_msg) /
845                                  (gfloat)(pop3_session->count));
846                 break;
847         case POP3_RETR:
848                 inc_recv_data_progressive
849                         (session, 0,
850                          pop3_session->msg[pop3_session->cur_msg].size, data);
851                 break;
852         case POP3_DELETE:
853                 if (pop3_session->msg[pop3_session->cur_msg].recv_time <
854                         pop3_session->current_time) {
855                         g_snprintf(buf, sizeof(buf), _("Deleting message %d"),
856                                    pop3_session->cur_msg);
857                         progress_dialog_set_label(dialog, buf);
858                 }
859                 break;
860         case POP3_LOGOUT:
861                 progress_dialog_set_label(dialog, _("Quitting"));
862                 break;
863         default:
864                 break;
865         }
866
867         return 0;
868 }
869
870 gint inc_drop_message(const gchar *file, Pop3Session *session)
871 {
872         FolderItem *inbox;
873         FolderItem *dropfolder;
874         gint msgnum;
875         IncSession *inc_session = (IncSession *)(SESSION(session)->data);
876         gint val;
877
878         if (session->ac_prefs->inbox) {
879                 inbox = folder_find_item_from_identifier
880                         (session->ac_prefs->inbox);
881                 if (!inbox)
882                         inbox = folder_get_default_inbox();
883         } else
884                 inbox = folder_get_default_inbox();
885         if (!inbox) {
886                 unlink(file);
887                 return -1;
888         }
889
890         /* CLAWS: claws uses a global .processing folder for the filtering. */
891         dropfolder = folder_get_default_processing();
892
893         /* add msg file to drop folder */
894         if ((msgnum = folder_item_add_msg(dropfolder, file, TRUE)) < 0) {
895                 unlink(file);
896                 return -1;
897         }
898
899         return 0;
900 }
901
902 static void inc_put_error(IncState istate)
903 {
904         switch (istate) {
905         case INC_ERROR:
906                 if (!prefs_common.no_recv_err_panel)
907                         alertpanel_error
908                                 (_("Error occurred while processing mail."));
909                 break;
910         case INC_NO_SPACE:
911                 alertpanel_error(_("No disk space left."));
912                 break;
913         case INC_IO_ERROR:
914                 alertpanel_error(_("Can't write file."));
915                 break;
916         case INC_SOCKET_ERROR:
917                 alertpanel_error(_("Socket error."));
918                 break;
919         case INC_LOCKED:
920                 if (!prefs_common.no_recv_err_panel)
921                         alertpanel_error(_("Mailbox is locked."));
922                 break;
923         default:
924                 break;
925         }
926 }
927
928 static void inc_cancel(IncProgressDialog *dialog)
929 {
930         IncSession *session;
931
932         g_return_if_fail(dialog != NULL);
933
934         if (dialog->queue_list == NULL) {
935                 inc_progress_dialog_destroy(dialog);
936                 return;
937         }
938
939         session = dialog->queue_list->data;
940
941         session->session->state = SESSION_DISCONNECTED;
942         session->inc_state = INC_CANCEL;
943
944         log_message(_("Incorporation cancelled\n"));
945 }
946
947 gboolean inc_is_active(void)
948 {
949         return (inc_dialog_list != NULL);
950 }
951
952 void inc_cancel_all(void)
953 {
954         GList *cur;
955
956         for (cur = inc_dialog_list; cur != NULL; cur = cur->next)
957                 inc_cancel((IncProgressDialog *)cur->data);
958 }
959
960 static void inc_cancel_cb(GtkWidget *widget, gpointer data)
961 {
962         inc_cancel((IncProgressDialog *)data);
963 }
964
965 static gint inc_dialog_delete_cb(GtkWidget *widget, GdkEventAny *event,
966                                  gpointer data)
967 {
968         IncProgressDialog *dialog = (IncProgressDialog *)data;
969
970         if (dialog->queue_list == NULL)
971                 inc_progress_dialog_destroy(dialog);
972
973         return TRUE;
974 }
975
976 static gint inc_spool(void)
977 {
978         gchar *mbox, *logname;
979         gint msgs;
980
981         logname = g_get_user_name();
982         mbox = g_strconcat(prefs_common.spool_path
983                            ? prefs_common.spool_path : DEFAULT_SPOOL_PATH,
984                            G_DIR_SEPARATOR_S, logname, NULL);
985         msgs = get_spool(folder_get_default_inbox(), mbox);
986         g_free(mbox);
987
988         return msgs;
989 }
990
991 static gint inc_spool_account(PrefsAccount *account)
992 {
993         FolderItem *inbox;
994
995         if (account->inbox) {
996                 inbox = folder_find_item_from_path(account->inbox);
997                 if (!inbox)
998                         inbox = folder_get_default_inbox();
999         } else
1000                 inbox = folder_get_default_inbox();
1001
1002         return get_spool(inbox, account->local_mbox);
1003 }
1004
1005 static gint inc_all_spool(void)
1006 {
1007         GList *list = NULL;
1008         gint new_msgs = 0;
1009         gint account_new_msgs = 0;
1010
1011         list = account_get_list();
1012         if (!list) return 0;
1013
1014         for (; list != NULL; list = list->next) {
1015                 PrefsAccount *account = list->data;
1016
1017                 if ((account->protocol == A_LOCAL) &&
1018                     (account->recv_at_getall)) {
1019                         account_new_msgs = inc_spool_account(account);
1020                         if (account_new_msgs > 0)
1021                                 new_msgs += account_new_msgs;
1022                 }
1023         }
1024
1025         return new_msgs;
1026 }
1027
1028 static gint get_spool(FolderItem *dest, const gchar *mbox)
1029 {
1030         gint msgs, size;
1031         gint lockfd;
1032         gchar tmp_mbox[MAXPATHLEN + 1];
1033
1034         g_return_val_if_fail(dest != NULL, -1);
1035         g_return_val_if_fail(mbox != NULL, -1);
1036
1037         if (!is_file_exist(mbox) || (size = get_file_size(mbox)) == 0) {
1038                 debug_print("no messages in local mailbox.\n");
1039                 return 0;
1040         } else if (size < 0)
1041                 return -1;
1042
1043         if ((lockfd = lock_mbox(mbox, LOCK_FLOCK)) < 0)
1044                 return -1;
1045
1046         g_snprintf(tmp_mbox, sizeof(tmp_mbox), "%s%ctmpmbox.%08x",
1047                    get_tmp_dir(), G_DIR_SEPARATOR, (gint)mbox);
1048
1049         if (copy_mbox(mbox, tmp_mbox) < 0) {
1050                 unlock_mbox(mbox, lockfd, LOCK_FLOCK);
1051                 return -1;
1052         }
1053
1054         debug_print("Getting new messages from %s into %s...\n",
1055                     mbox, dest->path);
1056
1057         msgs = proc_mbox(dest, tmp_mbox);
1058
1059         unlink(tmp_mbox);
1060         if (msgs >= 0) empty_mbox(mbox);
1061         unlock_mbox(mbox, lockfd, LOCK_FLOCK);
1062
1063         return msgs;
1064 }
1065
1066 void inc_lock(void)
1067 {
1068         inc_lock_count++;
1069 }
1070
1071 void inc_unlock(void)
1072 {
1073         if (inc_lock_count > 0)
1074                 inc_lock_count--;
1075 }
1076
1077 static guint autocheck_timer = 0;
1078 static gpointer autocheck_data = NULL;
1079
1080 static void inc_notify_cmd(gint new_msgs, gboolean notify)
1081 {
1082
1083         gchar *buf;
1084
1085         if (!(new_msgs && notify && prefs_common.newmail_notify_cmd &&
1086             *prefs_common.newmail_notify_cmd))
1087                      return;
1088         if ((buf = strchr(prefs_common.newmail_notify_cmd, '%')) &&
1089                 buf[1] == 'd' && !strchr(&buf[1], '%'))
1090                 buf = g_strdup_printf(prefs_common.newmail_notify_cmd, 
1091                                       new_msgs);
1092         else
1093                 buf = g_strdup(prefs_common.newmail_notify_cmd);
1094
1095         execute_command_line(buf, TRUE);
1096
1097         g_free(buf);
1098 }
1099  
1100 void inc_autocheck_timer_init(MainWindow *mainwin)
1101 {
1102         autocheck_data = mainwin;
1103         inc_autocheck_timer_set();
1104 }
1105
1106 static void inc_autocheck_timer_set_interval(guint interval)
1107 {
1108         inc_autocheck_timer_remove();
1109         /* last test is to avoid re-enabling auto_check after modifying 
1110            the common preferences */
1111         if (prefs_common.autochk_newmail && autocheck_data
1112             && prefs_common.work_offline == FALSE) {
1113                 autocheck_timer = gtk_timeout_add
1114                         (interval, inc_autocheck_func, autocheck_data);
1115                 debug_print("added timer = %d\n", autocheck_timer);
1116         }
1117 }
1118
1119 void inc_autocheck_timer_set(void)
1120 {
1121         inc_autocheck_timer_set_interval(prefs_common.autochk_itv * 60000);
1122 }
1123
1124 void inc_autocheck_timer_remove(void)
1125 {
1126         if (autocheck_timer) {
1127                 debug_print("removed timer = %d\n", autocheck_timer);
1128                 gtk_timeout_remove(autocheck_timer);
1129                 autocheck_timer = 0;
1130         }
1131 }
1132
1133 static gint inc_autocheck_func(gpointer data)
1134 {
1135         MainWindow *mainwin = (MainWindow *)data;
1136
1137         if (inc_lock_count) {
1138                 debug_print("autocheck is locked.\n");
1139                 inc_autocheck_timer_set_interval(1000);
1140                 return FALSE;
1141         }
1142
1143         inc_all_account_mail(mainwin, prefs_common.newmail_notify_auto);
1144
1145         return FALSE;
1146 }