38cffbfb320eaa923f79a8a30a7b70ce2dff5aea
[claws.git] / src / inc.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2004 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/time.h>
36 #include <sys/types.h>
37 #include <sys/stat.h>
38 #include <sys/wait.h>
39 #include <signal.h>
40 #include <errno.h>
41
42 #include "intl.h"
43 #include "main.h"
44 #include "inc.h"
45 #include "mainwindow.h"
46 #include "folderview.h"
47 #include "summaryview.h"
48 #include "prefs_common.h"
49 #include "prefs_account.h"
50 #include "account.h"
51 #include "procmsg.h"
52 #include "socket.h"
53 #include "ssl.h"
54 #include "pop.h"
55 #include "recv.h"
56 #include "mbox.h"
57 #include "utils.h"
58 #include "gtkutils.h"
59 #include "statusbar.h"
60 #include "manage_window.h"
61 #include "stock_pixmap.h"
62 #include "progressdialog.h"
63 #include "inputdialog.h"
64 #include "alertpanel.h"
65 #include "folder.h"
66 #include "filtering.h"
67 #include "log.h"
68 #include "hooks.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_real       (MainWindow             *mainwin,
86                                          PrefsAccount           *account);
87
88 static IncProgressDialog *inc_progress_dialog_create
89                                         (gboolean                autocheck);
90 static void inc_progress_dialog_set_list(IncProgressDialog      *inc_dialog);
91 static void inc_progress_dialog_destroy (IncProgressDialog      *inc_dialog);
92
93 static IncSession *inc_session_new      (PrefsAccount           *account);
94 static void inc_session_destroy         (IncSession             *session);
95 static gint inc_start                   (IncProgressDialog      *inc_dialog);
96 static IncState inc_pop3_session_do     (IncSession             *session);
97
98 static void inc_progress_dialog_update  (IncProgressDialog      *inc_dialog,
99                                          IncSession             *inc_session);
100
101 static void inc_progress_dialog_set_label
102                                         (IncProgressDialog      *inc_dialog,
103                                          IncSession             *inc_session);
104 static void inc_progress_dialog_set_progress
105                                         (IncProgressDialog      *inc_dialog,
106                                          IncSession             *inc_session);
107
108 static void inc_progress_dialog_update_periodic
109                                         (IncProgressDialog      *inc_dialog,
110                                          IncSession             *inc_session);
111
112 static gint inc_recv_data_progressive   (Session        *session,
113                                          guint           cur_len,
114                                          guint           total_len,
115                                          gpointer        data);
116 static gint inc_recv_data_finished      (Session        *session,
117                                          guint           len,
118                                          gpointer        data);
119 static gint inc_recv_message            (Session        *session,
120                                          const gchar    *msg,
121                                          gpointer        data);
122 static gint inc_drop_message            (Pop3Session    *session,
123                                          const gchar    *file);
124
125 static void inc_put_error               (IncState        istate,
126                                          const gchar    *msg);
127
128 static void inc_cancel_cb               (GtkWidget      *widget,
129                                          gpointer        data);
130 static gint inc_dialog_delete_cb        (GtkWidget      *widget,
131                                          GdkEventAny    *event,
132                                          gpointer        data);
133
134 static gint get_spool                   (FolderItem     *dest,
135                                          const gchar    *mbox);
136
137 static gint inc_spool_account(PrefsAccount *account);
138 static gint inc_all_spool(void);
139 static void inc_autocheck_timer_set_interval    (guint           interval);
140 static gint inc_autocheck_func                  (gpointer        data);
141
142 static void inc_notify_cmd              (gint new_msgs, 
143                                          gboolean notify);
144         
145 /**
146  * inc_finished:
147  * @mainwin: Main window.
148  * @new_messages: TRUE if some messages have been received.
149  * 
150  * Update the folder view and the summary view after receiving
151  * messages.  If @new_messages is FALSE, this function avoids unneeded
152  * updating.
153  **/
154 static void inc_finished(MainWindow *mainwin, gboolean new_messages)
155 {
156         FolderItem *item;
157
158         if (prefs_common.scan_all_after_inc)
159                 folderview_check_new(NULL);
160
161         if (!new_messages && !prefs_common.scan_all_after_inc) return;
162
163         if (prefs_common.open_inbox_on_inc) {
164                 item = cur_account && cur_account->inbox
165                         ? folder_find_item_from_identifier(cur_account->inbox)
166                         : folder_get_default_inbox();
167                 folderview_unselect(mainwin->folderview);
168                 folderview_select(mainwin->folderview, item);
169         }
170 }
171
172 void inc_mail(MainWindow *mainwin, gboolean notify)
173 {
174         gint new_msgs = 0;
175         gint account_new_msgs = 0;
176
177         if (inc_lock_count) return;
178
179         if (prefs_common.work_offline)
180                 if (alertpanel(_("Offline warning"), 
181                                _("You're working offline. Override?"),
182                                _("Yes"), _("No"), NULL) != G_ALERTDEFAULT)
183                 return;
184
185         inc_lock();
186         inc_autocheck_timer_remove();
187         main_window_lock(mainwin);
188
189         if (prefs_common.use_extinc && prefs_common.extinc_cmd) {
190                 /* external incorporating program */
191                 if (execute_command_line(prefs_common.extinc_cmd, FALSE) < 0) {
192                         main_window_unlock(mainwin);
193                         inc_autocheck_timer_set();
194                         return;
195                 }
196         } else {
197                 account_new_msgs = inc_account_mail_real(mainwin, cur_account);
198                 if (account_new_msgs > 0)
199                         new_msgs += account_new_msgs;
200         }
201
202         inc_finished(mainwin, new_msgs > 0);
203         main_window_unlock(mainwin);
204         inc_notify_cmd(new_msgs, notify);
205         inc_autocheck_timer_set();
206         inc_unlock();
207 }
208
209 void inc_pop_before_smtp(PrefsAccount *acc)
210 {
211         /* FIXME: assumes to attach to first main window */
212         inc_account_mail(mainwindow_get_mainwindow(), acc);
213 }
214
215 static gint inc_account_mail_real(MainWindow *mainwin, PrefsAccount *account)
216 {
217         IncProgressDialog *inc_dialog;
218         IncSession *session;
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(FALSE);
240                 inc_dialog->queue_list = g_list_append(inc_dialog->queue_list,
241                                                        session);
242                 inc_dialog->mainwin = mainwin;
243                 inc_progress_dialog_set_list(inc_dialog);
244
245                 if (mainwin) {
246                         toolbar_main_set_sensitive(mainwin);
247                         main_window_set_menu_sensitive(mainwin);
248                 }
249                         
250                 return inc_start(inc_dialog);
251
252         case A_LOCAL:
253                 return inc_spool_account(account);
254
255         default:
256                 break;
257         }
258         return 0;
259 }
260
261 gint inc_account_mail(MainWindow *mainwin, PrefsAccount *account)
262 {
263         gint new_msgs;
264
265         if (inc_lock_count) return 0;
266
267         if (prefs_common.work_offline)
268                 if (alertpanel(_("Offline warning"), 
269                                _("You're working offline. Override?"),
270                                _("Yes"), _("No"), NULL) != G_ALERTDEFAULT)
271                         return 0;
272
273         inc_autocheck_timer_remove();
274         main_window_lock(mainwin);
275
276         new_msgs = inc_account_mail_real(mainwin, account);
277
278         inc_finished(mainwin, new_msgs > 0);
279         main_window_unlock(mainwin);
280         inc_autocheck_timer_set();
281
282         return new_msgs;
283 }
284
285 void inc_all_account_mail(MainWindow *mainwin, gboolean autocheck,
286                           gboolean notify)
287 {
288         GList *list, *queue_list = NULL;
289         IncProgressDialog *inc_dialog;
290         gint new_msgs = 0;
291         gint account_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         list = account_get_list();
305         if (!list) {
306                 inc_finished(mainwin, new_msgs > 0);
307                 main_window_unlock(mainwin);
308                 inc_notify_cmd(new_msgs, notify);
309                 inc_autocheck_timer_set();
310                 return;
311         }
312
313         /* check local folders */
314         account_new_msgs = inc_all_spool();
315         if (account_new_msgs > 0)
316                 new_msgs += account_new_msgs;
317
318         /* check IMAP4 folders */
319         for (; list != NULL; list = list->next) {
320                 PrefsAccount *account = list->data;
321                 if ((account->protocol == A_IMAP4 ||
322                      account->protocol == A_NNTP) && account->recv_at_getall) {
323                         new_msgs += folderview_check_new(FOLDER(account->folder));
324                 }
325         }
326
327         /* check POP3 accounts */
328         for (list = account_get_list(); list != NULL; list = list->next) {
329                 IncSession *session;
330                 PrefsAccount *account = list->data;
331
332                 if (account->recv_at_getall) {
333                         session = inc_session_new(account);
334                         if (session)
335                                 queue_list = g_list_append(queue_list, session);
336                 }
337         }
338
339         if (!queue_list) {
340                 inc_finished(mainwin, new_msgs > 0);
341                 main_window_unlock(mainwin);
342                 inc_notify_cmd(new_msgs, notify);
343                 inc_autocheck_timer_set();
344                 return;
345         }
346
347         inc_dialog = inc_progress_dialog_create(autocheck);
348         inc_dialog->queue_list = queue_list;
349         inc_dialog->mainwin = mainwin;
350         inc_progress_dialog_set_list(inc_dialog);
351
352         toolbar_main_set_sensitive(mainwin);
353         main_window_set_menu_sensitive(mainwin);
354
355         new_msgs += inc_start(inc_dialog);
356         inc_finished(mainwin, new_msgs > 0);
357         main_window_unlock(mainwin);
358         inc_notify_cmd(new_msgs, notify);
359         inc_autocheck_timer_set();
360 }
361
362 static IncProgressDialog *inc_progress_dialog_create(gboolean autocheck)
363 {
364         IncProgressDialog *dialog;
365         ProgressDialog *progress;
366
367         dialog = g_new0(IncProgressDialog, 1);
368
369         progress = progress_dialog_create();
370         gtk_window_set_title(GTK_WINDOW(progress->window),
371                              _("Retrieving new messages"));
372         gtk_signal_connect(GTK_OBJECT(progress->cancel_btn), "clicked",
373                            GTK_SIGNAL_FUNC(inc_cancel_cb), dialog);
374         gtk_signal_connect(GTK_OBJECT(progress->window), "delete_event",
375                            GTK_SIGNAL_FUNC(inc_dialog_delete_cb), dialog);
376         /* manage_window_set_transient(GTK_WINDOW(progress->window)); */
377
378         progress_dialog_set_value(progress, 0.0);
379
380         stock_pixmap_gdk(progress->clist, STOCK_PIXMAP_COMPLETE,
381                          &okxpm, &okxpmmask);
382         stock_pixmap_gdk(progress->clist, STOCK_PIXMAP_CONTINUE,
383                          &currentxpm, &currentxpmmask);
384         stock_pixmap_gdk(progress->clist, STOCK_PIXMAP_ERROR,
385                          &errorxpm, &errorxpmmask);
386
387         if (prefs_common.recv_dialog_mode == RECV_DIALOG_ALWAYS ||
388             (prefs_common.recv_dialog_mode == RECV_DIALOG_MANUAL &&
389              !autocheck)) {
390                 dialog->show_dialog = TRUE;
391                 gtk_widget_show_now(progress->window);
392         }
393
394         dialog->dialog = progress;
395         gettimeofday(&dialog->progress_tv, NULL);
396         gettimeofday(&dialog->folder_tv, NULL);
397         dialog->queue_list = NULL;
398         dialog->cur_row = 0;
399
400         inc_dialog_list = g_list_append(inc_dialog_list, dialog);
401
402         return dialog;
403 }
404
405 static void inc_progress_dialog_set_list(IncProgressDialog *inc_dialog)
406 {
407         GList *list;
408
409         for (list = inc_dialog->queue_list; list != NULL; list = list->next) {
410                 IncSession *session = list->data;
411                 Pop3Session *pop3_session = POP3_SESSION(session->session);
412                 gchar *text[3];
413
414                 session->data = inc_dialog;
415
416                 text[0] = NULL;
417                 text[1] = pop3_session->ac_prefs->account_name;
418                 text[2] = _("Standby");
419                 gtk_clist_append(GTK_CLIST(inc_dialog->dialog->clist), text);
420         }
421 }
422
423 static void inc_progress_dialog_clear(IncProgressDialog *inc_dialog)
424 {
425         progress_dialog_set_value(inc_dialog->dialog, 0.0);
426         progress_dialog_set_label(inc_dialog->dialog, "");
427         if (inc_dialog->mainwin)
428                 main_window_progress_off(inc_dialog->mainwin);
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
437         if (inc_dialog->mainwin)
438                 main_window_progress_off(inc_dialog->mainwin);
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
457         session->session = pop3_session_new(account);
458         session->session->data = session;
459         POP3_SESSION(session->session)->drop_message = inc_drop_message;
460         session_set_recv_message_notify(session->session,
461                                         inc_recv_message, session);
462         session_set_recv_data_progressive_notify(session->session,
463                                                  inc_recv_data_progressive,
464                                                  session);
465         session_set_recv_data_notify(session->session,
466                                      inc_recv_data_finished, session);
467
468         return session;
469 }
470
471 static void inc_session_destroy(IncSession *session)
472 {
473         g_return_if_fail(session != NULL);
474
475         session_destroy(session->session);
476         g_free(session);
477 }
478
479 static gint inc_start(IncProgressDialog *inc_dialog)
480 {
481         IncSession *session;
482         GtkCList *clist = GTK_CLIST(inc_dialog->dialog->clist);
483         GList *qlist;
484         Pop3Session *pop3_session;
485         IncState inc_state;
486         gint error_num = 0;
487         gint new_msgs = 0;
488         gchar *msg;
489         gchar *fin_msg;
490         FolderItem *processing, *inbox;
491         MsgInfo *msginfo;
492         GSList *msglist, *msglist_element;
493
494         qlist = inc_dialog->queue_list;
495         while (qlist != NULL) {
496                 GList *next = qlist->next;
497
498                 session = qlist->data;
499                 pop3_session = POP3_SESSION(session->session); 
500                 pop3_session->user = g_strdup(pop3_session->ac_prefs->userid);
501                 if (pop3_session->ac_prefs->passwd)
502                         pop3_session->pass =
503                                 g_strdup(pop3_session->ac_prefs->passwd);
504                 else if (pop3_session->ac_prefs->tmp_pass)
505                         pop3_session->pass =
506                                 g_strdup(pop3_session->ac_prefs->tmp_pass);
507                 else {
508                         gchar *pass;
509
510                         if (inc_dialog->show_dialog)
511                                 manage_window_focus_in
512                                         (inc_dialog->dialog->window,
513                                          NULL, NULL);
514
515                         pass = input_dialog_query_password
516                                 (pop3_session->ac_prefs->recv_server,
517                                  pop3_session->user);
518
519                         if (inc_dialog->show_dialog)
520                                 manage_window_focus_out
521                                         (inc_dialog->dialog->window,
522                                          NULL, NULL);
523
524                         if (pass) {
525                                 pop3_session->ac_prefs->tmp_pass =
526                                         g_strdup(pass);
527                                 pop3_session->pass = pass;
528                         }
529                 }
530
531                 qlist = next;
532         }
533
534 #define SET_PIXMAP_AND_TEXT(xpm, xpmmask, str)                             \
535 {                                                                          \
536         gtk_clist_set_pixmap(clist, inc_dialog->cur_row, 0, xpm, xpmmask); \
537         gtk_clist_set_text(clist, inc_dialog->cur_row, 2, str);            \
538 }
539
540         for (; inc_dialog->queue_list != NULL; inc_dialog->cur_row++) {
541                 session = inc_dialog->queue_list->data;
542                 pop3_session = POP3_SESSION(session->session);
543
544                 if (pop3_session->pass == NULL) {
545                         SET_PIXMAP_AND_TEXT(okxpm, okxpmmask, _("Cancelled"));
546                         inc_session_destroy(session);
547                         inc_dialog->queue_list =
548                                 g_list_remove(inc_dialog->queue_list, session);
549                         continue;
550                 }
551
552                 inc_progress_dialog_clear(inc_dialog);
553                 gtk_clist_moveto(clist, inc_dialog->cur_row, -1, 1.0, 0.0);
554
555                 SET_PIXMAP_AND_TEXT(currentxpm, currentxpmmask,
556                                     _("Retrieving"));
557
558                 /* begin POP3 session */
559                 inc_state = inc_pop3_session_do(session);
560
561                 switch (inc_state) {
562                 case INC_SUCCESS:
563                         if (pop3_session->cur_total_num > 0)
564                                 msg = g_strdup_printf
565                                         (_("Done (%d message(s) (%s) received)"),
566                                          pop3_session->cur_total_num,
567                                          to_human_readable(pop3_session->cur_total_recv_bytes));
568                         else
569                                 msg = g_strdup_printf(_("Done (no new messages)"));
570                         SET_PIXMAP_AND_TEXT(okxpm, okxpmmask, msg);
571                         g_free(msg);
572                         break;
573                 case INC_CONNECT_ERROR:
574                         SET_PIXMAP_AND_TEXT(errorxpm, errorxpmmask,
575                                             _("Connection failed"));
576                         break;
577                 case INC_AUTH_FAILED:
578                         SET_PIXMAP_AND_TEXT(errorxpm, errorxpmmask,
579                                             _("Auth failed"));
580                         break;
581                 case INC_LOCKED:
582                         SET_PIXMAP_AND_TEXT(errorxpm, errorxpmmask,
583                                             _("Locked"));
584                         break;
585                 case INC_ERROR:
586                 case INC_NO_SPACE:
587                 case INC_IO_ERROR:
588                 case INC_SOCKET_ERROR:
589                 case INC_EOF:
590                         SET_PIXMAP_AND_TEXT(errorxpm, errorxpmmask, _("Error"));
591                         break;
592                 case INC_CANCEL:
593                         SET_PIXMAP_AND_TEXT(okxpm, okxpmmask, _("Cancelled"));
594                         break;
595                 default:
596                         break;
597                 }
598                 
599                 if (pop3_session->error_val == PS_AUTHFAIL) {
600                         if(!prefs_common.no_recv_err_panel) {
601                                 if((prefs_common.recv_dialog_mode == RECV_DIALOG_ALWAYS) ||
602                                     ((prefs_common.recv_dialog_mode == RECV_DIALOG_MANUAL) && focus_window))
603                                         manage_window_focus_in(inc_dialog->dialog->window, NULL, NULL);
604                         }
605                 }
606
607                 /* CLAWS: perform filtering actions on dropped message */
608                 /* CLAWS: get default inbox (perhaps per account) */
609                 if (pop3_session->ac_prefs->inbox) {
610                         /* CLAWS: get destination folder / mailbox */
611                         inbox = folder_find_item_from_identifier(pop3_session->ac_prefs->inbox);
612                         if (!inbox)
613                                 inbox = folder_get_default_inbox();
614                 } else
615                         inbox = folder_get_default_inbox();
616
617                 /* get list of messages in processing */
618                 processing = folder_get_default_processing();
619                 folder_item_scan(processing);
620                 msglist = folder_item_get_msg_list(processing);
621
622                 /* process messages */
623                 for(msglist_element = msglist; msglist_element != NULL; msglist_element = msglist_element->next) {
624                         msginfo = (MsgInfo *) msglist_element->data;
625                         if (!pop3_session->ac_prefs->filter_on_recv || !procmsg_msginfo_filter(msginfo))
626                                 folder_item_move_msg(inbox, msginfo);
627                         procmsg_msginfo_free(msginfo);
628                 }
629                 g_slist_free(msglist);
630
631                 statusbar_pop_all();
632
633                 new_msgs += pop3_session->cur_total_num;
634
635                 if (pop3_session->error_val == PS_AUTHFAIL &&
636                     pop3_session->ac_prefs->tmp_pass) {
637                         g_free(pop3_session->ac_prefs->tmp_pass);
638                         pop3_session->ac_prefs->tmp_pass = NULL;
639                 }
640
641                 pop3_write_uidl_list(pop3_session);
642
643                 if (inc_state != INC_SUCCESS && inc_state != INC_CANCEL) {
644                         error_num++;
645                         if (inc_dialog->show_dialog)
646                                 manage_window_focus_in
647                                         (inc_dialog->dialog->window,
648                                          NULL, NULL);
649                         inc_put_error(inc_state, pop3_session->error_msg);
650                         if (inc_dialog->show_dialog)
651                                 manage_window_focus_out
652                                         (inc_dialog->dialog->window,
653                                          NULL, NULL);
654                         if (inc_state == INC_NO_SPACE ||
655                             inc_state == INC_IO_ERROR)
656                                 break;
657                 }
658
659                 inc_session_destroy(session);
660                 inc_dialog->queue_list =
661                         g_list_remove(inc_dialog->queue_list, session);
662         }
663
664 #undef SET_PIXMAP_AND_TEXT
665
666         if (new_msgs > 0)
667                 fin_msg = g_strdup_printf(_("Finished (%d new message(s))"),
668                                           new_msgs);
669         else
670                 fin_msg = g_strdup_printf(_("Finished (no new messages)"));
671
672         progress_dialog_set_label(inc_dialog->dialog, fin_msg);
673
674 #if 0
675         if (error_num && !prefs_common.no_recv_err_panel) {
676                 if (inc_dialog->show_dialog)
677                         manage_window_focus_in(inc_dialog->dialog->window,
678                                                NULL, NULL);
679                 alertpanel_error_log(_("Some errors occurred while getting mail."));
680                 if (inc_dialog->show_dialog)
681                         manage_window_focus_out(inc_dialog->dialog->window,
682                                                 NULL, NULL);
683         }
684 #endif
685
686         while (inc_dialog->queue_list != NULL) {
687                 session = inc_dialog->queue_list->data;
688                 inc_session_destroy(session);
689                 inc_dialog->queue_list =
690                         g_list_remove(inc_dialog->queue_list, session);
691         }
692
693         if (prefs_common.close_recv_dialog || !inc_dialog->show_dialog)
694                 inc_progress_dialog_destroy(inc_dialog);
695         else {
696                 gtk_window_set_title(GTK_WINDOW(inc_dialog->dialog->window),
697                                      fin_msg);
698                 gtk_label_set_text(GTK_LABEL(GTK_BIN(inc_dialog->dialog->cancel_btn)->child),
699                                    _("Close"));
700         }
701
702         g_free(fin_msg);
703
704         return new_msgs;
705 }
706
707 static IncState inc_pop3_session_do(IncSession *session)
708 {
709         Pop3Session *pop3_session = POP3_SESSION(session->session);
710         IncProgressDialog *inc_dialog = (IncProgressDialog *)session->data;
711         gchar *server;
712         gushort port;
713         gchar *buf;
714
715         debug_print("getting new messages of account %s...\n",
716                     pop3_session->ac_prefs->account_name);
717                     
718         pop3_session->ac_prefs->last_pop_login_time = time(NULL);
719
720         buf = g_strdup_printf(_("%s: Retrieving new messages"),
721                               pop3_session->ac_prefs->recv_server);
722         gtk_window_set_title(GTK_WINDOW(inc_dialog->dialog->window), buf);
723         g_free(buf);
724
725         server = pop3_session->ac_prefs->recv_server;
726 #if USE_OPENSSL
727         port = pop3_session->ac_prefs->set_popport ?
728                 pop3_session->ac_prefs->popport :
729                 pop3_session->ac_prefs->ssl_pop == SSL_TUNNEL ? 995 : 110;
730         SESSION(pop3_session)->ssl_type = pop3_session->ac_prefs->ssl_pop;
731         if (pop3_session->ac_prefs->ssl_pop != SSL_NONE)
732                 SESSION(pop3_session)->nonblocking =
733                         pop3_session->ac_prefs->use_nonblocking_ssl;
734 #else
735         port = pop3_session->ac_prefs->set_popport ?
736                 pop3_session->ac_prefs->popport : 110;
737 #endif
738
739         buf = g_strdup_printf(_("Connecting to POP3 server: %s..."), server);
740         log_message("%s\n", buf);
741
742         progress_dialog_set_label(inc_dialog->dialog, buf);
743         g_free(buf);
744
745         if (session_connect(SESSION(pop3_session), server, port) < 0) {
746                 log_warning(_("Can't connect to POP3 server: %s:%d\n"),
747                             server, port);
748                 if(!prefs_common.no_recv_err_panel) {
749                         if((prefs_common.recv_dialog_mode == RECV_DIALOG_ALWAYS) ||
750                             ((prefs_common.recv_dialog_mode == RECV_DIALOG_MANUAL) && focus_window)) {
751                                 manage_window_focus_in(inc_dialog->dialog->window, NULL, NULL);
752                         }
753                         alertpanel_error(_("Can't connect to POP3 server: %s:%d"),
754                                          server, port);
755                         manage_window_focus_out(inc_dialog->dialog->window, NULL, NULL);
756                 }
757                 session->inc_state = INC_CONNECT_ERROR;
758                 statusbar_pop_all();
759                 return INC_CONNECT_ERROR;
760         }
761
762         while (session_is_connected(SESSION(pop3_session)) &&
763                session->inc_state != INC_CANCEL)
764                 gtk_main_iteration();
765
766         statusbar_pop_all();
767
768         if (session->inc_state == INC_SUCCESS) {
769                 switch (pop3_session->error_val) {
770                 case PS_SUCCESS:
771                         if (SESSION(pop3_session)->state == SESSION_ERROR) {
772                                 if (pop3_session->state == POP3_READY)
773                                         session->inc_state = INC_CONNECT_ERROR;
774                                 else
775                                         session->inc_state = INC_ERROR;
776                         } else if (SESSION(pop3_session)->state == SESSION_EOF)
777                                 session->inc_state = INC_EOF;
778                         else
779                                 session->inc_state = INC_SUCCESS;
780                         break;
781                 case PS_AUTHFAIL:
782                         session->inc_state = INC_AUTH_FAILED;
783                         break;
784                 case PS_IOERR:
785                         session->inc_state = INC_IO_ERROR;
786                         break;
787                 case PS_SOCKET:
788                         session->inc_state = INC_SOCKET_ERROR;
789                         break;
790                 case PS_LOCKBUSY:
791                         session->inc_state = INC_LOCKED;
792                         break;
793                 default:
794                         session->inc_state = INC_ERROR;
795                         break;
796                 }
797         }
798
799         return session->inc_state;
800 }
801
802 static void inc_progress_dialog_update(IncProgressDialog *inc_dialog,
803                                        IncSession *inc_session)
804 {
805         inc_progress_dialog_set_label(inc_dialog, inc_session);
806         inc_progress_dialog_set_progress(inc_dialog, inc_session);
807 }
808
809 static void inc_progress_dialog_set_label(IncProgressDialog *inc_dialog,
810                                           IncSession *inc_session)
811 {
812         ProgressDialog *dialog = inc_dialog->dialog;
813         Pop3Session *session;
814
815         g_return_if_fail(inc_session != NULL);
816
817         session = POP3_SESSION(inc_session->session);
818
819         switch (session->state) {
820         case POP3_GREETING:
821                 break;
822         case POP3_GETAUTH_USER:
823         case POP3_GETAUTH_PASS:
824         case POP3_GETAUTH_APOP:
825                 progress_dialog_set_label(dialog, _("Authenticating..."));
826                 statusbar_print_all(_("Retrieving messages from %s (%s) ..."),
827                                     SESSION(session)->server,
828                                     session->ac_prefs->account_name);
829                 break;
830         case POP3_GETRANGE_STAT:
831                 progress_dialog_set_label
832                         (dialog, _("Getting the number of new messages (STAT)..."));
833                 break;
834         case POP3_GETRANGE_LAST:
835                 progress_dialog_set_label
836                         (dialog, _("Getting the number of new messages (LAST)..."));
837                 break;
838         case POP3_GETRANGE_UIDL:
839                 progress_dialog_set_label
840                         (dialog, _("Getting the number of new messages (UIDL)..."));
841                 break;
842         case POP3_GETSIZE_LIST:
843                 progress_dialog_set_label
844                         (dialog, _("Getting the size of messages (LIST)..."));
845                 break;
846         case POP3_RETR:
847         case POP3_RETR_RECV:
848                 break;
849         case POP3_DELETE:
850 #if 0
851                 if (session->msg[session->cur_msg].recv_time <
852                         session->current_time) {
853                         gchar buf[MSGBUFSIZE];
854                         g_snprintf(buf, sizeof(buf), _("Deleting message %d"),
855                                    session->cur_msg);
856                         progress_dialog_set_label(dialog, buf);
857                 }
858 #endif
859                 break;
860         case POP3_LOGOUT:
861                 progress_dialog_set_label(dialog, _("Quitting"));
862                 break;
863         default:
864                 break;
865         }
866 }
867
868 static void inc_progress_dialog_set_progress(IncProgressDialog *inc_dialog,
869                                              IncSession *inc_session)
870 {
871         gchar buf[MSGBUFSIZE];
872         Pop3Session *pop3_session = POP3_SESSION(inc_session->session);
873         gchar *total_size_str;
874         gint cur_total;
875         gint total;
876
877         if (!pop3_session->new_msg_exist) return;
878
879         cur_total = inc_session->cur_total_bytes;
880         total = pop3_session->total_bytes;
881         if (pop3_session->state == POP3_RETR ||
882             pop3_session->state == POP3_RETR_RECV ||
883             pop3_session->state == POP3_DELETE) {
884                 Xstrdup_a(total_size_str, to_human_readable(total), return);
885                 g_snprintf(buf, sizeof(buf),
886                            _("Retrieving message (%d / %d) (%s / %s)"),
887                            pop3_session->cur_msg, pop3_session->count,
888                            to_human_readable(cur_total), total_size_str);
889                 progress_dialog_set_label(inc_dialog->dialog, buf);
890         }
891
892         progress_dialog_set_percentage
893                 (inc_dialog->dialog,(gfloat)cur_total / (gfloat)total);
894
895         gtk_progress_set_show_text
896                 (GTK_PROGRESS(inc_dialog->mainwin->progressbar), TRUE);
897         g_snprintf(buf, sizeof(buf), "%d / %d",
898                    pop3_session->cur_msg, pop3_session->count);
899         gtk_progress_set_format_string
900                 (GTK_PROGRESS(inc_dialog->mainwin->progressbar), buf);
901         gtk_progress_bar_update
902                 (GTK_PROGRESS_BAR(inc_dialog->mainwin->progressbar),
903                  (gfloat)cur_total / (gfloat)total);
904
905         if (pop3_session->cur_total_num > 0) {
906                 g_snprintf(buf, sizeof(buf),
907                            _("Retrieving (%d message(s) (%s) received)"),
908                            pop3_session->cur_total_num,
909                            to_human_readable
910                            (pop3_session->cur_total_recv_bytes));
911                 gtk_clist_set_text(GTK_CLIST(inc_dialog->dialog->clist),
912                                    inc_dialog->cur_row, 2, buf);
913         }
914 }
915
916 static void inc_progress_dialog_update_periodic(IncProgressDialog *inc_dialog,
917                                                 IncSession *inc_session)
918 {
919         struct timeval tv_cur;
920         struct timeval tv_result;
921         gint msec;
922
923         gettimeofday(&tv_cur, NULL);
924
925         tv_result.tv_sec = tv_cur.tv_sec - inc_dialog->progress_tv.tv_sec;
926         tv_result.tv_usec = tv_cur.tv_usec - inc_dialog->progress_tv.tv_usec;
927         if (tv_result.tv_usec < 0) {
928                 tv_result.tv_sec--;
929                 tv_result.tv_usec += 1000000;
930         }
931
932         msec = tv_result.tv_sec * 1000 + tv_result.tv_usec / 1000;
933         if (msec > PROGRESS_UPDATE_INTERVAL) {
934                 inc_progress_dialog_update(inc_dialog, inc_session);
935                 inc_dialog->progress_tv.tv_sec = tv_cur.tv_sec;
936                 inc_dialog->progress_tv.tv_usec = tv_cur.tv_usec;
937         }
938 }
939
940 static gint inc_recv_data_progressive(Session *session, guint cur_len,
941                                       guint total_len, gpointer data)
942 {
943         IncSession *inc_session = (IncSession *)data;
944         Pop3Session *pop3_session = POP3_SESSION(session);
945         IncProgressDialog *inc_dialog;
946         gint cur_total;
947
948         g_return_val_if_fail(inc_session != NULL, -1);
949
950         if (pop3_session->state != POP3_RETR &&
951             pop3_session->state != POP3_RETR_RECV &&
952             pop3_session->state != POP3_DELETE &&
953             pop3_session->state != POP3_LOGOUT) return 0;
954
955         if (!pop3_session->new_msg_exist) return 0;
956
957         cur_total = pop3_session->cur_total_bytes + cur_len;
958         if (cur_total > pop3_session->total_bytes)
959                 cur_total = pop3_session->total_bytes;
960         inc_session->cur_total_bytes = cur_total;
961
962         inc_dialog = (IncProgressDialog *)inc_session->data;
963         inc_progress_dialog_update_periodic(inc_dialog, inc_session);
964
965         return 0;
966 }
967
968 static gint inc_recv_data_finished(Session *session, guint len, gpointer data)
969 {
970         IncSession *inc_session = (IncSession *)data;
971         IncProgressDialog *inc_dialog;
972
973         g_return_val_if_fail(inc_session != NULL, -1);
974
975         inc_dialog = (IncProgressDialog *)inc_session->data;
976
977         inc_recv_data_progressive(session, 0, 0, inc_session);
978
979         if (POP3_SESSION(session)->state == POP3_LOGOUT) {
980                 inc_progress_dialog_update(inc_dialog, inc_session);
981         }
982
983         return 0;
984 }
985
986 static gint inc_recv_message(Session *session, const gchar *msg, gpointer data)
987 {
988         IncSession *inc_session = (IncSession *)data;
989         IncProgressDialog *inc_dialog;
990
991         g_return_val_if_fail(inc_session != NULL, -1);
992
993         inc_dialog = (IncProgressDialog *)inc_session->data;
994
995         switch (POP3_SESSION(session)->state) {
996         case POP3_GETAUTH_USER:
997         case POP3_GETAUTH_PASS:
998         case POP3_GETAUTH_APOP:
999         case POP3_GETRANGE_STAT:
1000         case POP3_GETRANGE_LAST:
1001         case POP3_GETRANGE_UIDL:
1002         case POP3_GETSIZE_LIST:
1003                 inc_progress_dialog_update(inc_dialog, inc_session);
1004                 break;
1005         case POP3_RETR:
1006                 inc_recv_data_progressive(session, 0, 0, inc_session);
1007                 break;
1008         case POP3_LOGOUT:
1009                 inc_progress_dialog_update(inc_dialog, inc_session);
1010                 break;
1011         default:
1012                 break;
1013         }
1014
1015         return 0;
1016 }
1017
1018 static gint inc_drop_message(Pop3Session *session, const gchar *file)
1019 {
1020         FolderItem *inbox;
1021         FolderItem *dropfolder;
1022         IncSession *inc_session = (IncSession *)(SESSION(session)->data);
1023         gint msgnum;
1024
1025         g_return_val_if_fail(inc_session != NULL, -1);
1026
1027         if (session->ac_prefs->inbox) {
1028                 inbox = folder_find_item_from_identifier
1029                         (session->ac_prefs->inbox);
1030                 if (!inbox)
1031                         inbox = folder_get_default_inbox();
1032         } else
1033                 inbox = folder_get_default_inbox();
1034         if (!inbox) {
1035                 unlink(file);
1036                 return -1;
1037         }
1038
1039         /* CLAWS: claws uses a global .processing folder for the filtering. */
1040         dropfolder = folder_get_default_processing();
1041
1042         /* add msg file to drop folder */
1043         if ((msgnum = folder_item_add_msg(dropfolder, file, NULL, TRUE)) < 0) {
1044                 unlink(file);
1045                 return -1;
1046         }
1047
1048         return 0;
1049 }
1050
1051 static void inc_put_error(IncState istate, const gchar *msg)
1052 {
1053         gchar *log_msg = NULL;
1054         gchar *err_msg = NULL;
1055         gboolean fatal_error = FALSE;
1056
1057         switch (istate) {
1058         case INC_CONNECT_ERROR:
1059                 log_msg = _("Connection failed.");
1060                 if (prefs_common.no_recv_err_panel)
1061                         break;
1062                 err_msg = g_strdup(log_msg);
1063                 break;
1064         case INC_ERROR:
1065                 log_msg = _("Error occurred while processing mail.");
1066                 if (prefs_common.no_recv_err_panel)
1067                         break;
1068                 if (msg)
1069                         err_msg = g_strdup_printf
1070                                 (_("Error occurred while processing mail:\n%s"),
1071                                  msg);
1072                 else
1073                         err_msg = g_strdup(log_msg);
1074                 break;
1075         case INC_NO_SPACE:
1076                 log_msg = _("No disk space left.");
1077                 err_msg = g_strdup(log_msg);
1078                 fatal_error = TRUE;
1079                 break;
1080         case INC_IO_ERROR:
1081                 log_msg = _("Can't write file.");
1082                 err_msg = g_strdup(log_msg);
1083                 fatal_error = TRUE;
1084                 break;
1085         case INC_SOCKET_ERROR:
1086                 log_msg = _("Socket error.");
1087                 if (prefs_common.no_recv_err_panel)
1088                         break;
1089                 err_msg = g_strdup(log_msg);
1090                 break;
1091         case INC_EOF:
1092                 log_msg = _("Connection closed by the remote host.");
1093                 if (prefs_common.no_recv_err_panel)
1094                         break;
1095                 err_msg = g_strdup(log_msg);
1096                 break;
1097         case INC_LOCKED:
1098                 log_msg = _("Mailbox is locked.");
1099                 if (prefs_common.no_recv_err_panel)
1100                         break;
1101                 if (msg)
1102                         err_msg = g_strdup_printf(_("Mailbox is locked:\n%s"),
1103                                                   msg);
1104                 else
1105                         err_msg = g_strdup(log_msg);
1106                 break;
1107         case INC_AUTH_FAILED:
1108                 log_msg = _("Authentication failed.");
1109                 if (prefs_common.no_recv_err_panel)
1110                         break;
1111                 if (msg)
1112                         err_msg = g_strdup_printf
1113                                 (_("Authentication failed:\n%s"), msg);
1114                 else
1115                         err_msg = g_strdup(log_msg);
1116                 break;
1117         default:
1118                 break;
1119         }
1120
1121         if (log_msg) {
1122                 if (fatal_error)
1123                         log_error("%s\n", log_msg);
1124                 else
1125                         log_warning("%s\n", log_msg);
1126         }
1127         if (err_msg) {
1128                 alertpanel_error_log(err_msg);
1129                 g_free(err_msg);
1130         }
1131 }
1132
1133 static void inc_cancel(IncProgressDialog *dialog)
1134 {
1135         IncSession *session;
1136
1137         g_return_if_fail(dialog != NULL);
1138
1139         if (dialog->queue_list == NULL) {
1140                 inc_progress_dialog_destroy(dialog);
1141                 return;
1142         }
1143
1144         session = dialog->queue_list->data;
1145
1146         session->inc_state = INC_CANCEL;
1147
1148         log_message(_("Incorporation cancelled\n"));
1149 }
1150
1151 gboolean inc_is_active(void)
1152 {
1153         return (inc_dialog_list != NULL);
1154 }
1155
1156 void inc_cancel_all(void)
1157 {
1158         GList *cur;
1159
1160         for (cur = inc_dialog_list; cur != NULL; cur = cur->next)
1161                 inc_cancel((IncProgressDialog *)cur->data);
1162 }
1163
1164 static void inc_cancel_cb(GtkWidget *widget, gpointer data)
1165 {
1166         inc_cancel((IncProgressDialog *)data);
1167 }
1168
1169 static gint inc_dialog_delete_cb(GtkWidget *widget, GdkEventAny *event,
1170                                  gpointer data)
1171 {
1172         IncProgressDialog *dialog = (IncProgressDialog *)data;
1173
1174         if (dialog->queue_list == NULL)
1175                 inc_progress_dialog_destroy(dialog);
1176
1177         return TRUE;
1178 }
1179
1180 static gint inc_spool_account(PrefsAccount *account)
1181 {
1182         FolderItem *inbox;
1183         gchar *mbox, *logname;
1184         gint result;
1185
1186         logname = g_get_user_name();
1187
1188         if (account->inbox) {
1189                 inbox = folder_find_item_from_path(account->inbox);
1190                 if (!inbox)
1191                         inbox = folder_get_default_inbox();
1192         } else
1193                 inbox = folder_get_default_inbox();
1194
1195         if (is_file_exist(account->local_mbox))
1196                 mbox = g_strdup(account->local_mbox);
1197         else 
1198                 mbox = g_strconcat(account->local_mbox,
1199                                    G_DIR_SEPARATOR_S, logname, NULL);
1200         
1201         result = get_spool(inbox, mbox);
1202         g_free(mbox);
1203         
1204         statusbar_pop_all();
1205         
1206         return result;
1207 }
1208
1209 static gint inc_all_spool(void)
1210 {
1211         GList *list = NULL;
1212         gint new_msgs = 0;
1213         gint account_new_msgs = 0;
1214
1215         list = account_get_list();
1216         if (!list) return 0;
1217
1218         for (; list != NULL; list = list->next) {
1219                 PrefsAccount *account = list->data;
1220
1221                 if ((account->protocol == A_LOCAL) &&
1222                     (account->recv_at_getall)) {
1223                         account_new_msgs = inc_spool_account(account);
1224                         if (account_new_msgs > 0)
1225                                 new_msgs += account_new_msgs;
1226                 }
1227         }
1228
1229         return new_msgs;
1230 }
1231
1232 static gint get_spool(FolderItem *dest, const gchar *mbox)
1233 {
1234         gint msgs, size;
1235         gint lockfd;
1236         gchar tmp_mbox[MAXPATHLEN + 1];
1237
1238         g_return_val_if_fail(dest != NULL, -1);
1239         g_return_val_if_fail(mbox != NULL, -1);
1240
1241         if (!is_file_exist(mbox) || (size = get_file_size(mbox)) == 0) {
1242                 debug_print("no messages in local mailbox.\n");
1243                 return 0;
1244         } else if (size < 0)
1245                 return -1;
1246
1247         if ((lockfd = lock_mbox(mbox, LOCK_FLOCK)) < 0)
1248                 return -1;
1249
1250         g_snprintf(tmp_mbox, sizeof(tmp_mbox), "%s%ctmpmbox.%08x",
1251                    get_tmp_dir(), G_DIR_SEPARATOR, (gint)mbox);
1252
1253         if (copy_mbox(mbox, tmp_mbox) < 0) {
1254                 unlock_mbox(mbox, lockfd, LOCK_FLOCK);
1255                 return -1;
1256         }
1257
1258         debug_print("Getting new messages from %s into %s...\n",
1259                     mbox, dest->path);
1260
1261         msgs = proc_mbox(dest, tmp_mbox, TRUE);
1262
1263         unlink(tmp_mbox);
1264         if (msgs >= 0) empty_mbox(mbox);
1265         unlock_mbox(mbox, lockfd, LOCK_FLOCK);
1266
1267         return msgs;
1268 }
1269
1270 void inc_lock(void)
1271 {
1272         inc_lock_count++;
1273 }
1274
1275 void inc_unlock(void)
1276 {
1277         if (inc_lock_count > 0)
1278                 inc_lock_count--;
1279 }
1280
1281 static guint autocheck_timer = 0;
1282 static gpointer autocheck_data = NULL;
1283
1284 static void inc_notify_cmd(gint new_msgs, gboolean notify)
1285 {
1286
1287         gchar *buf;
1288
1289         if (!(new_msgs && notify && prefs_common.newmail_notify_cmd &&
1290             *prefs_common.newmail_notify_cmd))
1291                      return;
1292         if ((buf = strchr(prefs_common.newmail_notify_cmd, '%')) &&
1293                 buf[1] == 'd' && !strchr(&buf[1], '%'))
1294                 buf = g_strdup_printf(prefs_common.newmail_notify_cmd, 
1295                                       new_msgs);
1296         else
1297                 buf = g_strdup(prefs_common.newmail_notify_cmd);
1298
1299         execute_command_line(buf, TRUE);
1300
1301         g_free(buf);
1302 }
1303  
1304 void inc_autocheck_timer_init(MainWindow *mainwin)
1305 {
1306         autocheck_data = mainwin;
1307         inc_autocheck_timer_set();
1308 }
1309
1310 static void inc_autocheck_timer_set_interval(guint interval)
1311 {
1312         inc_autocheck_timer_remove();
1313         /* last test is to avoid re-enabling auto_check after modifying 
1314            the common preferences */
1315         if (prefs_common.autochk_newmail && autocheck_data
1316             && prefs_common.work_offline == FALSE) {
1317                 autocheck_timer = gtk_timeout_add
1318                         (interval, inc_autocheck_func, autocheck_data);
1319                 debug_print("added timer = %d\n", autocheck_timer);
1320         }
1321 }
1322
1323 void inc_autocheck_timer_set(void)
1324 {
1325         inc_autocheck_timer_set_interval(prefs_common.autochk_itv * 60000);
1326 }
1327
1328 void inc_autocheck_timer_remove(void)
1329 {
1330         if (autocheck_timer) {
1331                 debug_print("removed timer = %d\n", autocheck_timer);
1332                 gtk_timeout_remove(autocheck_timer);
1333                 autocheck_timer = 0;
1334         }
1335 }
1336
1337 static gint inc_autocheck_func(gpointer data)
1338 {
1339         MainWindow *mainwin = (MainWindow *)data;
1340
1341         if (inc_lock_count) {
1342                 debug_print("autocheck is locked.\n");
1343                 inc_autocheck_timer_set_interval(1000);
1344                 return FALSE;
1345         }
1346
1347         inc_all_account_mail(mainwin, TRUE, prefs_common.newmail_notify_auto);
1348
1349         return FALSE;
1350 }