fix 'pop before smtp' timeout
[claws.git] / src / inc.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2003 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                                          const gchar    *msg);
108
109 static void inc_cancel_cb               (GtkWidget      *widget,
110                                          gpointer        data);
111 static gint inc_dialog_delete_cb        (GtkWidget      *widget,
112                                          GdkEventAny    *event,
113                                          gpointer        data);
114
115 static gint inc_spool                   (void);
116 static gint get_spool                   (FolderItem     *dest,
117                                          const gchar    *mbox);
118
119 static gint inc_spool_account(PrefsAccount *account);
120 static gint inc_all_spool(void);
121 static void inc_autocheck_timer_set_interval    (guint           interval);
122 static gint inc_autocheck_func                  (gpointer        data);
123
124 static void inc_notify_cmd              (gint new_msgs, 
125                                          gboolean notify);
126
127 #define FOLDER_SUMMARY_MISMATCH(f, s) \
128         (f) && (s) ? ((s)->newmsgs != (f)->new_msgs) || ((f)->unread_msgs != (s)->unread) || ((f)->total_msgs != (s)->messages) \
129         : FALSE
130         
131 /**
132  * inc_finished:
133  * @mainwin: Main window.
134  * @new_messages: TRUE if some messages have been received.
135  * 
136  * Update the folder view and the summary view after receiving
137  * messages.  If @new_messages is FALSE, this function avoids unneeded
138  * updating.
139  **/
140 static void inc_finished(MainWindow *mainwin, gboolean new_messages)
141 {
142         FolderItem *item;
143
144         if (prefs_common.scan_all_after_inc)
145                 folderview_check_new(NULL);
146
147         if (!new_messages && !prefs_common.scan_all_after_inc) return;
148
149         if (prefs_common.open_inbox_on_inc) {
150                 item = cur_account && cur_account->inbox
151                         ? folder_find_item_from_identifier(cur_account->inbox)
152                         : folder_get_default_inbox();
153                 if (FOLDER_SUMMARY_MISMATCH(item, mainwin->summaryview)) {      
154                         folderview_unselect(mainwin->folderview);
155                         folderview_select(mainwin->folderview, item);
156                 }       
157         }
158 }
159
160 void inc_mail(MainWindow *mainwin, gboolean notify)
161 {
162         gint new_msgs = 0;
163         gint account_new_msgs = 0;
164
165         if (inc_lock_count) return;
166
167         if (prefs_common.work_offline)
168                 if (alertpanel(_("Offline warning"), 
169                                _("You're working offline. Override?"),
170                                _("Yes"), _("No"), NULL) != G_ALERTDEFAULT)
171                 return;
172
173         inc_lock();
174         inc_autocheck_timer_remove();
175         main_window_lock(mainwin);
176
177         if (prefs_common.use_extinc && prefs_common.extinc_cmd) {
178                 /* external incorporating program */
179                 if (execute_command_line(prefs_common.extinc_cmd, FALSE) < 0) {
180                         main_window_unlock(mainwin);
181                         inc_autocheck_timer_set();
182                         return;
183                 }
184
185                 if (prefs_common.inc_local) {
186                         account_new_msgs = inc_spool();
187                         if (account_new_msgs > 0)
188                                 new_msgs += account_new_msgs;
189                 }
190         } else {
191                 if (prefs_common.inc_local) {
192                         account_new_msgs = inc_spool();
193                         if (account_new_msgs > 0)
194                                 new_msgs += account_new_msgs;
195                 }
196
197                 account_new_msgs = inc_account_mail(cur_account, mainwin);
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         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
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                         msginfo = (MsgInfo *) msglist_element->data;
586                         if (!pop3_session->ac_prefs->filter_on_recv || !procmsg_msginfo_filter(msginfo))
587                                 folder_item_move_msg(inbox, msginfo);
588                         procmsg_msginfo_free(msginfo);
589                 }
590                 g_slist_free(msglist);
591
592                 folder_item_update_thaw();
593
594
595                 new_msgs += pop3_session->cur_total_num;
596
597                 if (pop3_session->error_val == PS_AUTHFAIL &&
598                     pop3_session->ac_prefs->tmp_pass) {
599                         g_free(pop3_session->ac_prefs->tmp_pass);
600                         pop3_session->ac_prefs->tmp_pass = NULL;
601                 }
602
603                 pop3_write_uidl_list(pop3_session);
604
605                 if (inc_state != INC_SUCCESS && inc_state != INC_CANCEL) {
606                         error_num++;
607                         if (inc_dialog->show_dialog)
608                                 manage_window_focus_in
609                                         (inc_dialog->dialog->window,
610                                          NULL, NULL);
611                         inc_put_error(inc_state, pop3_session->error_msg);
612                         if (inc_dialog->show_dialog)
613                                 manage_window_focus_out
614                                         (inc_dialog->dialog->window,
615                                          NULL, NULL);
616                         if (inc_state == INC_NO_SPACE ||
617                             inc_state == INC_IO_ERROR)
618                                 break;
619                 }
620
621                 inc_session_destroy(session);
622                 inc_dialog->queue_list =
623                         g_list_remove(inc_dialog->queue_list, session);
624
625                 num++;
626         }
627
628         if (new_msgs > 0)
629                 fin_msg = g_strdup_printf(_("Finished (%d new message(s))"),
630                                           new_msgs);
631         else
632                 fin_msg = g_strdup_printf(_("Finished (no new messages)"));
633
634         progress_dialog_set_label(inc_dialog->dialog, fin_msg);
635
636         if (error_num && !prefs_common.no_recv_err_panel) {
637                 if (inc_dialog->show_dialog)
638                         manage_window_focus_in(inc_dialog->dialog->window,
639                                                NULL, NULL);
640                 alertpanel_error_log(_("Some errors occurred while getting mail."));
641                 if (inc_dialog->show_dialog)
642                         manage_window_focus_out(inc_dialog->dialog->window,
643                                                 NULL, NULL);
644         }
645
646         while (inc_dialog->queue_list != NULL) {
647                 session = inc_dialog->queue_list->data;
648                 inc_session_destroy(session);
649                 inc_dialog->queue_list =
650                         g_list_remove(inc_dialog->queue_list, session);
651         }
652
653         if (prefs_common.close_recv_dialog)
654                 inc_progress_dialog_destroy(inc_dialog);
655         else {
656                 gtk_window_set_title(GTK_WINDOW(inc_dialog->dialog->window),
657                                      fin_msg);
658                 gtk_label_set_text(GTK_LABEL(GTK_BIN(inc_dialog->dialog->cancel_btn)->child),
659                                    _("Close"));
660         }
661
662         g_free(fin_msg);
663
664         return new_msgs;
665 }
666
667 static IncState inc_pop3_session_do(IncSession *session)
668 {
669         Pop3Session *pop3_session = POP3_SESSION(session->session);
670         IncProgressDialog *inc_dialog = (IncProgressDialog *)session->data;
671         gchar *server;
672         gushort port;
673         gchar *buf;
674
675         debug_print("getting new messages of account %s...\n",
676                     pop3_session->ac_prefs->account_name);
677                     
678         pop3_session->ac_prefs->last_pop_login_time = time(NULL);
679
680         buf = g_strdup_printf(_("%s: Retrieving new messages"),
681                               pop3_session->ac_prefs->recv_server);
682         gtk_window_set_title(GTK_WINDOW(inc_dialog->dialog->window), buf);
683         g_free(buf);
684
685         server = pop3_session->ac_prefs->recv_server;
686 #if USE_OPENSSL
687         port = pop3_session->ac_prefs->set_popport ?
688                 pop3_session->ac_prefs->popport :
689                 pop3_session->ac_prefs->ssl_pop == SSL_TUNNEL ? 995 : 110;
690         SESSION(pop3_session)->ssl_type = pop3_session->ac_prefs->ssl_pop;
691 #else
692         port = pop3_session->ac_prefs->set_popport ?
693                 pop3_session->ac_prefs->popport : 110;
694 #endif
695
696         statusbar_verbosity_set(TRUE);
697         buf = g_strdup_printf(_("Connecting to POP3 server: %s ..."), server);
698         log_message("%s\n", buf);
699
700         progress_dialog_set_label(inc_dialog->dialog, buf);
701         g_free(buf);
702         GTK_EVENTS_FLUSH();
703
704         statusbar_verbosity_set(FALSE);
705
706         if (session_connect(SESSION(pop3_session), server, port) < 0) {
707                 log_warning(_("Can't connect to POP3 server: %s:%d\n"),
708                             server, port);
709                 if(!prefs_common.no_recv_err_panel) {
710                         if((prefs_common.recv_dialog_mode == RECV_DIALOG_ALWAYS) ||
711                             ((prefs_common.recv_dialog_mode == RECV_DIALOG_ACTIVE) && focus_window)) {
712                                 manage_window_focus_in(inc_dialog->dialog->window, NULL, NULL);
713                         }
714                         alertpanel_error(_("Can't connect to POP3 server: %s:%d"),
715                                          server, port);
716                         manage_window_focus_out(inc_dialog->dialog->window, NULL, NULL);
717                 }
718                 session->inc_state = INC_CONNECT_ERROR;
719                 return INC_CONNECT_ERROR;
720         }
721
722         statusbar_verbosity_set(TRUE);
723
724         while (SESSION(pop3_session)->state != SESSION_DISCONNECTED &&
725                SESSION(pop3_session)->state != SESSION_ERROR &&
726                session->inc_state != INC_CANCEL)
727                 gtk_main_iteration();
728
729
730         statusbar_verbosity_set(FALSE);
731         if (session->inc_state == INC_SUCCESS) {
732                 switch (pop3_session->error_val) {
733                 case PS_SUCCESS:
734                         if (SESSION(pop3_session)->state == SESSION_ERROR) {
735                                 if (pop3_session->state == POP3_READY)
736                                         session->inc_state = INC_CONNECT_ERROR;
737                                 else
738                                         session->inc_state = INC_ERROR;
739                         } else
740                                 session->inc_state = INC_SUCCESS;
741                         break;
742                 case PS_AUTHFAIL:
743                         session->inc_state = INC_AUTH_FAILED;
744                         break;
745                 case PS_IOERR:
746                         session->inc_state = INC_IO_ERROR;
747                         break;
748                 case PS_SOCKET:
749                         session->inc_state = INC_SOCKET_ERROR;
750                         break;
751                 case PS_LOCKBUSY:
752                         session->inc_state = INC_LOCKED;
753                         break;
754                 default:
755                         session->inc_state = INC_ERROR;
756                         break;
757                 }
758         }
759
760         return session->inc_state;
761 }
762
763 static gint inc_recv_data_progressive(Session *session, guint cur_len,
764                                       guint total_len, gpointer data)
765 {
766         gchar buf[MSGBUFSIZE];
767         IncSession *inc_session = (IncSession *)data;
768         Pop3Session *pop3_session = POP3_SESSION(session);
769         IncProgressDialog *inc_dialog;
770         ProgressDialog *dialog;
771         gint cur_total;
772         gchar *total_size;
773
774         g_return_val_if_fail(inc_session != NULL, -1);
775
776         inc_dialog = (IncProgressDialog *)inc_session->data;
777         dialog = inc_dialog->dialog;
778
779         cur_total = pop3_session->cur_total_bytes + cur_len;
780         if (cur_total > pop3_session->total_bytes)
781                 cur_total = pop3_session->total_bytes;
782
783         Xstrdup_a(total_size, to_human_readable(pop3_session->total_bytes),
784                   return FALSE);
785         g_snprintf(buf, sizeof(buf),
786                    _("Retrieving message (%d / %d) (%s / %s)"),
787                    pop3_session->cur_msg, pop3_session->count,
788                    to_human_readable(cur_total), total_size);
789         progress_dialog_set_label(dialog, buf);
790         progress_dialog_set_percentage
791                 (dialog, (gfloat)cur_total / (gfloat)pop3_session->total_bytes);
792         if (inc_dialog->mainwin)
793                 gtk_progress_bar_update
794                         (GTK_PROGRESS_BAR(inc_dialog->mainwin->progressbar),
795                          (gfloat)cur_total / (gfloat)pop3_session->total_bytes);
796         GTK_EVENTS_FLUSH();
797
798         return 0;
799 }
800
801 static gint inc_recv_data_finished(Session *session, guint len, gpointer data)
802 {
803         IncSession *inc_session = (IncSession *)data;
804
805         g_return_val_if_fail(inc_session != NULL, -1);
806
807         inc_recv_data_progressive(session, 0, len, inc_session);
808         return 0;
809 }
810
811 static gint inc_recv_message(Session *session, const gchar *msg, gpointer data)
812 {
813         gchar buf[MSGBUFSIZE];
814         IncSession *inc_session = (IncSession *)data;
815         Pop3Session *pop3_session = POP3_SESSION(session);
816         IncProgressDialog *inc_dialog;
817         ProgressDialog *dialog;
818
819         g_return_val_if_fail(inc_session != NULL, -1);
820
821         inc_dialog = (IncProgressDialog *)inc_session->data;
822         dialog = inc_dialog->dialog;
823
824         switch (pop3_session->state) {
825         case POP3_GREETING:
826                 break;
827         case POP3_GETAUTH_USER:
828         case POP3_GETAUTH_PASS:
829         case POP3_GETAUTH_APOP:
830                 progress_dialog_set_label(dialog, _("Authenticating..."));
831                 break;
832         case POP3_GETRANGE_STAT:
833                 progress_dialog_set_label
834                         (dialog, _("Getting the number of new messages (STAT)..."));
835                 break;
836         case POP3_GETRANGE_LAST:
837                 progress_dialog_set_label
838                         (dialog, _("Getting the number of new messages (LAST)..."));
839                 break;
840         case POP3_GETRANGE_UIDL:
841                 progress_dialog_set_label
842                         (dialog, _("Getting the number of new messages (UIDL)..."));
843                 break;
844         case POP3_GETSIZE_LIST:
845                 progress_dialog_set_label
846                         (dialog, _("Getting the size of messages (LIST)..."));
847                 break;
848         case POP3_RETR:
849                 inc_recv_data_progressive
850                         (session, 0,
851                          pop3_session->msg[pop3_session->cur_msg].size, data);
852                 break;
853         case POP3_DELETE:
854                 if (pop3_session->msg[pop3_session->cur_msg].recv_time <
855                         pop3_session->current_time) {
856                         g_snprintf(buf, sizeof(buf), _("Deleting message %d"),
857                                    pop3_session->cur_msg);
858                         progress_dialog_set_label(dialog, buf);
859                 }
860                 break;
861         case POP3_LOGOUT:
862                 progress_dialog_set_label(dialog, _("Quitting"));
863                 break;
864         default:
865                 break;
866         }
867
868         return 0;
869 }
870
871 gint inc_drop_message(const gchar *file, Pop3Session *session)
872 {
873         FolderItem *inbox;
874         FolderItem *dropfolder;
875         gint msgnum;
876         IncSession *inc_session = (IncSession *)(SESSION(session)->data);
877         gint val;
878
879         if (session->ac_prefs->inbox) {
880                 inbox = folder_find_item_from_identifier
881                         (session->ac_prefs->inbox);
882                 if (!inbox)
883                         inbox = folder_get_default_inbox();
884         } else
885                 inbox = folder_get_default_inbox();
886         if (!inbox) {
887                 unlink(file);
888                 return -1;
889         }
890
891         /* CLAWS: claws uses a global .processing folder for the filtering. */
892         dropfolder = folder_get_default_processing();
893
894         /* add msg file to drop folder */
895         if ((msgnum = folder_item_add_msg(dropfolder, file, TRUE)) < 0) {
896                 unlink(file);
897                 return -1;
898         }
899
900         return 0;
901 }
902
903 static void inc_put_error(IncState istate, const gchar *msg)
904 {
905         switch (istate) {
906         case INC_ERROR:
907                 if (prefs_common.no_recv_err_panel)
908                         break;
909                 if (msg)
910                         alertpanel_error(_("Error occurred while processing mail:\n%s"), msg);
911                 else
912                         alertpanel_error(_("Error occurred while processing mail."));
913                 break;
914         case INC_NO_SPACE:
915                 alertpanel_error(_("No disk space left."));
916                 break;
917         case INC_IO_ERROR:
918                 alertpanel_error(_("Can't write file."));
919                 break;
920         case INC_SOCKET_ERROR:
921                 if (prefs_common.no_recv_err_panel)
922                         break;
923                 alertpanel_error(_("Socket error."));
924                 break;
925         case INC_LOCKED:
926                 if (prefs_common.no_recv_err_panel)
927                         break;
928                 if (msg)
929                         alertpanel_error(_("Mailbox is locked:\n%s"), msg);
930                 else
931                         alertpanel_error(_("Mailbox is locked."));
932                 break;
933         case INC_AUTH_FAILED:
934                 if (prefs_common.no_recv_err_panel)
935                         break;
936                 if (msg)
937                         alertpanel_error(_("Authentication failed:\n%s"),
938                                          msg);
939                 else
940                         alertpanel_error(_("Authentication failed."));
941                 break;
942         default:
943                 break;
944         }
945 }
946
947 static void inc_cancel(IncProgressDialog *dialog)
948 {
949         IncSession *session;
950
951         g_return_if_fail(dialog != NULL);
952
953         if (dialog->queue_list == NULL) {
954                 inc_progress_dialog_destroy(dialog);
955                 return;
956         }
957
958         session = dialog->queue_list->data;
959
960         session->inc_state = INC_CANCEL;
961
962         log_message(_("Incorporation cancelled\n"));
963 }
964
965 gboolean inc_is_active(void)
966 {
967         return (inc_dialog_list != NULL);
968 }
969
970 void inc_cancel_all(void)
971 {
972         GList *cur;
973
974         for (cur = inc_dialog_list; cur != NULL; cur = cur->next)
975                 inc_cancel((IncProgressDialog *)cur->data);
976 }
977
978 static void inc_cancel_cb(GtkWidget *widget, gpointer data)
979 {
980         inc_cancel((IncProgressDialog *)data);
981 }
982
983 static gint inc_dialog_delete_cb(GtkWidget *widget, GdkEventAny *event,
984                                  gpointer data)
985 {
986         IncProgressDialog *dialog = (IncProgressDialog *)data;
987
988         if (dialog->queue_list == NULL)
989                 inc_progress_dialog_destroy(dialog);
990
991         return TRUE;
992 }
993
994 static gint inc_spool(void)
995 {
996         gchar *mbox, *logname;
997         gint msgs;
998
999         logname = g_get_user_name();
1000         mbox = g_strconcat(prefs_common.spool_path
1001                            ? prefs_common.spool_path : DEFAULT_SPOOL_PATH,
1002                            G_DIR_SEPARATOR_S, logname, NULL);
1003         msgs = get_spool(folder_get_default_inbox(), mbox);
1004         g_free(mbox);
1005
1006         return msgs;
1007 }
1008
1009 static gint inc_spool_account(PrefsAccount *account)
1010 {
1011         FolderItem *inbox;
1012
1013         if (account->inbox) {
1014                 inbox = folder_find_item_from_path(account->inbox);
1015                 if (!inbox)
1016                         inbox = folder_get_default_inbox();
1017         } else
1018                 inbox = folder_get_default_inbox();
1019
1020         return get_spool(inbox, account->local_mbox);
1021 }
1022
1023 static gint inc_all_spool(void)
1024 {
1025         GList *list = NULL;
1026         gint new_msgs = 0;
1027         gint account_new_msgs = 0;
1028
1029         list = account_get_list();
1030         if (!list) return 0;
1031
1032         for (; list != NULL; list = list->next) {
1033                 PrefsAccount *account = list->data;
1034
1035                 if ((account->protocol == A_LOCAL) &&
1036                     (account->recv_at_getall)) {
1037                         account_new_msgs = inc_spool_account(account);
1038                         if (account_new_msgs > 0)
1039                                 new_msgs += account_new_msgs;
1040                 }
1041         }
1042
1043         return new_msgs;
1044 }
1045
1046 static gint get_spool(FolderItem *dest, const gchar *mbox)
1047 {
1048         gint msgs, size;
1049         gint lockfd;
1050         gchar tmp_mbox[MAXPATHLEN + 1];
1051
1052         g_return_val_if_fail(dest != NULL, -1);
1053         g_return_val_if_fail(mbox != NULL, -1);
1054
1055         if (!is_file_exist(mbox) || (size = get_file_size(mbox)) == 0) {
1056                 debug_print("no messages in local mailbox.\n");
1057                 return 0;
1058         } else if (size < 0)
1059                 return -1;
1060
1061         if ((lockfd = lock_mbox(mbox, LOCK_FLOCK)) < 0)
1062                 return -1;
1063
1064         g_snprintf(tmp_mbox, sizeof(tmp_mbox), "%s%ctmpmbox.%08x",
1065                    get_tmp_dir(), G_DIR_SEPARATOR, (gint)mbox);
1066
1067         if (copy_mbox(mbox, tmp_mbox) < 0) {
1068                 unlock_mbox(mbox, lockfd, LOCK_FLOCK);
1069                 return -1;
1070         }
1071
1072         debug_print("Getting new messages from %s into %s...\n",
1073                     mbox, dest->path);
1074
1075         msgs = proc_mbox(dest, tmp_mbox);
1076
1077         unlink(tmp_mbox);
1078         if (msgs >= 0) empty_mbox(mbox);
1079         unlock_mbox(mbox, lockfd, LOCK_FLOCK);
1080
1081         return msgs;
1082 }
1083
1084 void inc_lock(void)
1085 {
1086         inc_lock_count++;
1087 }
1088
1089 void inc_unlock(void)
1090 {
1091         if (inc_lock_count > 0)
1092                 inc_lock_count--;
1093 }
1094
1095 static guint autocheck_timer = 0;
1096 static gpointer autocheck_data = NULL;
1097
1098 static void inc_notify_cmd(gint new_msgs, gboolean notify)
1099 {
1100
1101         gchar *buf;
1102
1103         if (!(new_msgs && notify && prefs_common.newmail_notify_cmd &&
1104             *prefs_common.newmail_notify_cmd))
1105                      return;
1106         if ((buf = strchr(prefs_common.newmail_notify_cmd, '%')) &&
1107                 buf[1] == 'd' && !strchr(&buf[1], '%'))
1108                 buf = g_strdup_printf(prefs_common.newmail_notify_cmd, 
1109                                       new_msgs);
1110         else
1111                 buf = g_strdup(prefs_common.newmail_notify_cmd);
1112
1113         execute_command_line(buf, TRUE);
1114
1115         g_free(buf);
1116 }
1117  
1118 void inc_autocheck_timer_init(MainWindow *mainwin)
1119 {
1120         autocheck_data = mainwin;
1121         inc_autocheck_timer_set();
1122 }
1123
1124 static void inc_autocheck_timer_set_interval(guint interval)
1125 {
1126         inc_autocheck_timer_remove();
1127         /* last test is to avoid re-enabling auto_check after modifying 
1128            the common preferences */
1129         if (prefs_common.autochk_newmail && autocheck_data
1130             && prefs_common.work_offline == FALSE) {
1131                 autocheck_timer = gtk_timeout_add
1132                         (interval, inc_autocheck_func, autocheck_data);
1133                 debug_print("added timer = %d\n", autocheck_timer);
1134         }
1135 }
1136
1137 void inc_autocheck_timer_set(void)
1138 {
1139         inc_autocheck_timer_set_interval(prefs_common.autochk_itv * 60000);
1140 }
1141
1142 void inc_autocheck_timer_remove(void)
1143 {
1144         if (autocheck_timer) {
1145                 debug_print("removed timer = %d\n", autocheck_timer);
1146                 gtk_timeout_remove(autocheck_timer);
1147                 autocheck_timer = 0;
1148         }
1149 }
1150
1151 static gint inc_autocheck_func(gpointer data)
1152 {
1153         MainWindow *mainwin = (MainWindow *)data;
1154
1155         if (inc_lock_count) {
1156                 debug_print("autocheck is locked.\n");
1157                 inc_autocheck_timer_set_interval(1000);
1158                 return FALSE;
1159         }
1160
1161         inc_all_account_mail(mainwin, prefs_common.newmail_notify_auto);
1162
1163         return FALSE;
1164 }