52a19d3ef1b45aa5a45a1f68318e428dd9fccced
[claws.git] / src / inc.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2002 Hiroyuki Yamamoto
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #endif
23
24 #include "defs.h"
25
26 #include <glib.h>
27 #include <gtk/gtkmain.h>
28 #include <gtk/gtkwindow.h>
29 #include <gtk/gtksignal.h>
30 #include <gtk/gtkprogressbar.h>
31 #include <stdio.h>
32 #include <unistd.h>
33 #include <string.h>
34 #include <time.h>
35 #include <sys/types.h>
36 #include <sys/stat.h>
37 #include <sys/wait.h>
38 #include <signal.h>
39 #include <errno.h>
40
41 #include "intl.h"
42 #include "main.h"
43 #include "inc.h"
44 #include "mainwindow.h"
45 #include "folderview.h"
46 #include "summaryview.h"
47 #include "prefs_common.h"
48 #include "prefs_account.h"
49 #include "account.h"
50 #include "procmsg.h"
51 #include "socket.h"
52 #include "ssl.h"
53 #include "pop.h"
54 #include "recv.h"
55 #include "mbox.h"
56 #include "utils.h"
57 #include "gtkutils.h"
58 #include "statusbar.h"
59 #include "manage_window.h"
60 #include "stock_pixmap.h"
61 #include "progressdialog.h"
62 #include "inputdialog.h"
63 #include "alertpanel.h"
64 #include "automaton.h"
65 #include "folder.h"
66 #include "filtering.h"
67 #include "selective_download.h"
68 #include "log.h"
69 #include "hooks.h"
70
71 static GList *inc_dialog_list = NULL;
72
73 static guint inc_lock_count = 0;
74
75 static GdkPixmap *currentxpm;
76 static GdkBitmap *currentxpmmask;
77 static GdkPixmap *errorxpm;
78 static GdkBitmap *errorxpmmask;
79 static GdkPixmap *okxpm;
80 static GdkBitmap *okxpmmask;
81
82 #define MSGBUFSIZE      8192
83
84 static void inc_finished                (MainWindow             *mainwin,
85                                          gboolean                new_messages);
86 static gint inc_account_mail            (PrefsAccount           *account,
87                                          MainWindow             *mainwin);
88
89 static IncProgressDialog *inc_progress_dialog_create    (void);
90 static void inc_progress_dialog_destroy (IncProgressDialog      *inc_dialog);
91
92 static IncSession *inc_session_new      (PrefsAccount           *account);
93 static void inc_session_destroy         (IncSession             *session);
94 static gint inc_start                   (IncProgressDialog      *inc_dialog);
95 static IncState inc_pop3_session_do     (IncSession             *session);
96 static gint pop3_automaton_terminate    (SockInfo               *source,
97                                          Automaton              *atm);
98
99 static gboolean inc_pop3_recv_func      (SockInfo       *sock,
100                                          gint            count,
101                                          gint            read_bytes,
102                                          gpointer        data);
103
104 static void inc_put_error               (IncState        istate);
105
106 static void inc_cancel_cb               (GtkWidget      *widget,
107                                          gpointer        data);
108 static gint inc_dialog_delete_cb        (GtkWidget      *widget,
109                                          GdkEventAny    *event,
110                                          gpointer        data);
111
112 static gint inc_spool                   (void);
113 static gint get_spool                   (FolderItem     *dest,
114                                          const gchar    *mbox);
115
116 static void inc_spool_account(PrefsAccount *account);
117 static void inc_all_spool(void);
118 static void inc_autocheck_timer_set_interval    (guint           interval);
119 static gint inc_autocheck_func                  (gpointer        data);
120
121 static void inc_notify_cmd              (gint new_msgs, 
122                                          gboolean notify);
123
124 #define FOLDER_SUMMARY_MISMATCH(f, s) \
125         (f) && (s) ? ((s)->newmsgs != (f)->new) || ((f)->unread != (s)->unread) || ((f)->total != (s)->messages) \
126         : FALSE
127         
128 /**
129  * inc_finished:
130  * @mainwin: Main window.
131  * @new_messages: TRUE if some messages have been received.
132  * 
133  * Update the folder view and the summary view after receiving
134  * messages.  If @new_messages is FALSE, this function avoids unneeded
135  * updating.
136  **/
137 static void inc_finished(MainWindow *mainwin, gboolean new_messages)
138 {
139         FolderItem *item;
140
141         if (prefs_common.scan_all_after_inc)
142                 folderview_check_new(NULL);
143
144         if (!new_messages && !prefs_common.scan_all_after_inc) return;
145
146         if (prefs_common.open_inbox_on_inc) {
147                 item = cur_account && cur_account->inbox
148                         ? folder_find_item_from_identifier(cur_account->inbox)
149                         : folder_get_default_inbox();
150                 if (FOLDER_SUMMARY_MISMATCH(item, mainwin->summaryview)) {      
151                         folderview_unselect(mainwin->folderview);
152                         folderview_select(mainwin->folderview, item);
153                 }       
154         } else if (prefs_common.scan_all_after_inc) {
155                 item = mainwin->summaryview->folder_item;
156                 if (FOLDER_SUMMARY_MISMATCH(item, mainwin->summaryview)) {
157                         folder_update_item(item, TRUE);
158                 }       
159         }
160 }
161
162 void inc_mail(MainWindow *mainwin, gboolean notify)
163 {
164         gint new_msgs = 0;
165
166         if (inc_lock_count) return;
167
168         if (prefs_common.work_offline)
169                 if (alertpanel(_("Offline warning"), 
170                                _("You're working offline. Override?"),
171                                _("Yes"), _("No"), NULL) != G_ALERTDEFAULT)
172                 return;
173
174         inc_lock();
175         inc_autocheck_timer_remove();
176         main_window_lock(mainwin);
177
178         if (prefs_common.use_extinc && prefs_common.extinc_cmd) {
179                 /* external incorporating program */
180                 if (execute_command_line(prefs_common.extinc_cmd, FALSE) < 0) {
181                         main_window_unlock(mainwin);
182                         inc_autocheck_timer_set();
183                         return;
184                 }
185
186                 if (prefs_common.inc_local)
187                         new_msgs = inc_spool();
188
189                 if (new_msgs <= 0)
190                         new_msgs = 1;
191         } else {
192                 if (prefs_common.inc_local) {
193                         new_msgs = inc_spool();
194                         if (new_msgs < 0)
195                                 new_msgs = 0;
196                 }
197                 cur_account->session = STYPE_NORMAL;
198                 new_msgs += inc_account_mail(cur_account, mainwin);
199         }
200
201         inc_finished(mainwin, new_msgs > 0);
202         main_window_unlock(mainwin);
203         inc_notify_cmd(new_msgs, notify);
204         inc_autocheck_timer_set();
205         inc_unlock();
206 }
207
208 void inc_selective_download(MainWindow *mainwin, PrefsAccount *acc, gint session)
209 {
210         GSList *cur;
211         gint new_msgs = 0;
212
213         acc->session = session;
214         inc_account_mail(acc, mainwin);
215         acc->session = STYPE_NORMAL;
216         
217         for (cur = acc->msg_list; cur != NULL; cur = cur->next) {
218                 HeaderItems *items =(HeaderItems*)cur->data;
219
220                 if (items->state == SD_DOWNLOADED && 
221                     items->del_by_old_session == FALSE) {
222                         new_msgs++;                     
223                 }
224         }
225
226         if (new_msgs) {
227                 inc_finished(mainwin, TRUE);
228                 inc_notify_cmd(new_msgs, prefs_common.newmail_notify_manu);
229         }
230 }
231
232 void inc_pop_before_smtp(PrefsAccount *acc)
233 {
234         acc->session = STYPE_POP_BEFORE_SMTP;
235         inc_account_mail(acc, NULL);
236 }
237
238 static gint inc_account_mail(PrefsAccount *account, MainWindow *mainwin)
239 {
240         IncProgressDialog *inc_dialog;
241         IncSession *session;
242         gchar *text[3];
243         FolderItem *item = NULL;
244         
245         if(mainwin && mainwin->summaryview)
246                 item = mainwin->summaryview->folder_item;
247
248         switch (account->protocol) {
249         case A_IMAP4:
250         case A_NNTP:
251                 folderview_check_new(FOLDER(account->folder));
252                 if (!prefs_common.scan_all_after_inc && item != NULL &&
253                     FOLDER(account->folder) == item->folder)
254                         folder_update_item(item, TRUE);
255                 return 1;
256
257         case A_POP3:
258         case A_APOP:
259                 session = inc_session_new(account);
260                 if (!session) return 0;
261                 
262                 inc_dialog = inc_progress_dialog_create();
263                 inc_dialog->queue_list = g_list_append(inc_dialog->queue_list,
264                                                        session);
265                 inc_dialog->mainwin = mainwin;
266                 session->data = inc_dialog;
267         
268                 text[0] = NULL;
269                 text[1] = account->account_name;
270                 text[2] = _("Standby");
271                 gtk_clist_append(GTK_CLIST(inc_dialog->dialog->clist), text);
272                 
273                 if (mainwin) {
274                         toolbar_main_set_sensitive(mainwin);
275                         main_window_set_menu_sensitive(mainwin);
276                 }
277                         
278                 return inc_start(inc_dialog);
279
280         case A_LOCAL:
281                 inc_spool_account(account);
282                 return 1;
283
284         default:
285                 break;
286         }
287         return 0;
288 }
289
290 void inc_all_account_mail(MainWindow *mainwin, gboolean notify)
291 {
292         GList *list, *queue_list = NULL;
293         IncProgressDialog *inc_dialog;
294         gint new_msgs = 0;
295         
296         if (prefs_common.work_offline)
297                 if (alertpanel(_("Offline warning"), 
298                                _("You're working offline. Override?"),
299                                _("Yes"), _("No"), NULL) != G_ALERTDEFAULT)
300                 return;
301
302         if (inc_lock_count) return;
303
304         inc_autocheck_timer_remove();
305         main_window_lock(mainwin);
306
307         if (prefs_common.inc_local) {
308                 new_msgs = inc_spool();
309                 if (new_msgs < 0)
310                         new_msgs = 0;
311         }
312
313         list = account_get_list();
314         if (!list) {
315                 inc_finished(mainwin, new_msgs > 0);
316                 main_window_unlock(mainwin);
317                 inc_notify_cmd(new_msgs, notify);
318                 inc_autocheck_timer_set();
319                 return;
320         }
321
322         /* check local folders */
323         inc_all_spool();
324
325         /* check IMAP4 folders */
326         for (; list != NULL; list = list->next) {
327                 PrefsAccount *account = list->data;
328                 if ((account->protocol == A_IMAP4 ||
329                      account->protocol == A_NNTP) && account->recv_at_getall) {
330                         FolderItem *item = mainwin->summaryview->folder_item;
331
332                         folderview_check_new(FOLDER(account->folder));
333                         if (!prefs_common.scan_all_after_inc && item != NULL &&
334                             FOLDER(account->folder) == item->folder)
335                                 folder_update_item(item, TRUE);
336                 }
337         }
338
339         /* check POP3 accounts */
340         for (list = account_get_list(); list != NULL; list = list->next) {
341                 IncSession *session;
342                 PrefsAccount *account = list->data;
343                 account->session = STYPE_NORMAL;
344                 if (account->recv_at_getall) {
345                         session = inc_session_new(account);
346                         if (session)
347                                 queue_list = g_list_append(queue_list, session);
348                 }
349         }
350
351         if (!queue_list) {
352                 inc_finished(mainwin, new_msgs > 0);
353                 main_window_unlock(mainwin);
354                 inc_notify_cmd(new_msgs, notify);
355                 inc_autocheck_timer_set();
356                 return;
357         }
358
359         inc_dialog = inc_progress_dialog_create();
360         inc_dialog->queue_list = queue_list;
361         inc_dialog->mainwin = mainwin;
362         for (list = queue_list; list != NULL; list = list->next) {
363                 IncSession *session = list->data;
364                 gchar *text[3];
365
366                 session->data = inc_dialog;
367
368                 text[0] = NULL;
369                 text[1] = session->pop3_state->ac_prefs->account_name;
370                 text[2] = _("Standby");
371                 gtk_clist_append(GTK_CLIST(inc_dialog->dialog->clist), text);
372         }
373
374         toolbar_main_set_sensitive(mainwin);
375         main_window_set_menu_sensitive(mainwin);
376
377         new_msgs += inc_start(inc_dialog);
378
379         inc_finished(mainwin, new_msgs > 0);
380         main_window_unlock(mainwin);
381         inc_notify_cmd(new_msgs, notify);
382         inc_autocheck_timer_set();
383 }
384
385 static IncProgressDialog *inc_progress_dialog_create(void)
386 {
387         IncProgressDialog *dialog;
388         ProgressDialog *progress;
389
390         dialog = g_new0(IncProgressDialog, 1);
391
392         progress = progress_dialog_create();
393         gtk_window_set_title(GTK_WINDOW(progress->window),
394                              _("Retrieving new messages"));
395         gtk_signal_connect(GTK_OBJECT(progress->cancel_btn), "clicked",
396                            GTK_SIGNAL_FUNC(inc_cancel_cb), dialog);
397         gtk_signal_connect(GTK_OBJECT(progress->window), "delete_event",
398                            GTK_SIGNAL_FUNC(inc_dialog_delete_cb), dialog);
399         /* manage_window_set_transient(GTK_WINDOW(progress->window)); */
400
401         progress_dialog_set_value(progress, 0.0);
402
403         stock_pixmap_gdk(progress->clist, STOCK_PIXMAP_COMPLETE,
404                          &okxpm, &okxpmmask);
405         stock_pixmap_gdk(progress->clist, STOCK_PIXMAP_CONTINUE,
406                          &currentxpm, &currentxpmmask);
407         stock_pixmap_gdk(progress->clist, STOCK_PIXMAP_ERROR,
408                          &errorxpm, &errorxpmmask);
409
410         if (prefs_common.recv_dialog_mode == RECV_DIALOG_ALWAYS ||
411             (prefs_common.recv_dialog_mode == RECV_DIALOG_ACTIVE &&
412              manage_window_get_focus_window())) {
413                 dialog->show_dialog = TRUE;
414                 gtk_widget_show_now(progress->window);
415         }
416
417         dialog->dialog = progress;
418         dialog->queue_list = NULL;
419
420         inc_dialog_list = g_list_append(inc_dialog_list, dialog);
421
422         return dialog;
423 }
424
425 static void inc_progress_dialog_clear(IncProgressDialog *inc_dialog)
426 {
427         progress_dialog_set_value(inc_dialog->dialog, 0.0);
428         progress_dialog_set_label(inc_dialog->dialog, "");
429         if (inc_dialog->mainwin)
430                 gtk_progress_bar_update
431                         (GTK_PROGRESS_BAR(inc_dialog->mainwin->progressbar), 0.0);
432 }
433
434 static void inc_progress_dialog_destroy(IncProgressDialog *inc_dialog)
435 {
436         g_return_if_fail(inc_dialog != NULL);
437
438         inc_dialog_list = g_list_remove(inc_dialog_list, inc_dialog);
439         if (inc_dialog->mainwin)
440                 gtk_progress_bar_update
441                         (GTK_PROGRESS_BAR(inc_dialog->mainwin->progressbar), 0.0);
442         progress_dialog_destroy(inc_dialog->dialog);
443
444         g_free(inc_dialog);
445 }
446
447 static IncSession *inc_session_new(PrefsAccount *account)
448 {
449         IncSession *session;
450
451         g_return_val_if_fail(account != NULL, NULL);
452
453         if (account->protocol != A_POP3 && account->protocol != A_APOP)
454                 return NULL;
455         if (!account->recv_server || !account->userid)
456                 return NULL;
457
458         session = g_new0(IncSession, 1);
459         session->pop3_state = pop3_state_new(account);
460         session->pop3_state->data = session;
461
462         return session;
463 }
464
465 static void inc_session_destroy(IncSession *session)
466 {
467         g_return_if_fail(session != NULL);
468
469         pop3_state_destroy(session->pop3_state);
470         g_free(session);
471 }
472
473 static gint inc_start(IncProgressDialog *inc_dialog)
474 {
475         IncSession *session;
476         GtkCList *clist = GTK_CLIST(inc_dialog->dialog->clist);
477         Pop3State *pop3_state;
478         IncState inc_state;
479         gint num = 0;
480         gint error_num = 0;
481         gint new_msgs = 0;
482         gchar *msg;
483         gchar *fin_msg;
484         FolderItem *processing, *inbox;
485         MsgInfo *msginfo;
486         GSList *msglist, *msglist_element;
487
488         while (inc_dialog->queue_list != NULL) {
489                 session = inc_dialog->queue_list->data;
490                 pop3_state = session->pop3_state;
491
492                 inc_progress_dialog_clear(inc_dialog);
493
494                 gtk_clist_moveto(clist, num, -1, 1.0, 0.0);
495
496                 pop3_state->user = g_strdup(pop3_state->ac_prefs->userid);
497                 if (pop3_state->ac_prefs->passwd)
498                         pop3_state->pass =
499                                 g_strdup(pop3_state->ac_prefs->passwd);
500                 else if (pop3_state->ac_prefs->tmp_pass)
501                         pop3_state->pass =
502                                 g_strdup(pop3_state->ac_prefs->tmp_pass);
503                 else {
504                         gchar *pass;
505
506                         pass = input_dialog_query_password
507                                 (pop3_state->ac_prefs->recv_server,
508                                  pop3_state->user);
509
510                         if (inc_dialog->mainwin && inc_dialog->show_dialog)
511                                 manage_window_focus_in
512                                         (inc_dialog->mainwin->window,
513                                          NULL, NULL);
514                         if (pass) {
515                                 pop3_state->ac_prefs->tmp_pass = g_strdup(pass);
516                                 pop3_state->pass = pass;
517                         } else {
518                                 inc_session_destroy(session);
519                                 inc_dialog->queue_list = g_list_remove
520                                         (inc_dialog->queue_list, session);
521                                 continue;
522                         }
523                 }
524
525                 gtk_clist_set_pixmap(clist, num, 0, currentxpm, currentxpmmask);
526                 gtk_clist_set_text(clist, num, 2, _("Retrieving"));
527
528                 /* begin POP3 session */
529                 inc_state = inc_pop3_session_do(session);
530
531                 switch (inc_state) {
532                 case INC_SUCCESS:
533                         if (pop3_state->cur_total_num > 0)
534                                 msg = g_strdup_printf
535                                         (_("Done (%d message(s) (%s) received)"),
536                                          pop3_state->cur_total_num,
537                                          to_human_readable(pop3_state->cur_total_recv_bytes));
538                         else
539                                 msg = g_strdup_printf(_("Done (no new messages)"));
540                         gtk_clist_set_pixmap(clist, num, 0, okxpm, okxpmmask);
541                         gtk_clist_set_text(clist, num, 2, msg);
542                         g_free(msg);
543                         break;
544                 case INC_CONNECT_ERROR:
545                         gtk_clist_set_pixmap(clist, num, 0, errorxpm, errorxpmmask);
546                         gtk_clist_set_text(clist, num, 2, _("Connection failed"));
547                         break;
548                 case INC_AUTH_FAILED:
549                         gtk_clist_set_pixmap(clist, num, 0, errorxpm, errorxpmmask);
550                         gtk_clist_set_text(clist, num, 2, _("Auth failed"));
551                         break;
552                 case INC_LOCKED:
553                         gtk_clist_set_pixmap(clist, num, 0, errorxpm, errorxpmmask);
554                         gtk_clist_set_text(clist, num, 2, _("Locked"));
555                         break;
556                 case INC_ERROR:
557                 case INC_NO_SPACE:
558                 case INC_IO_ERROR:
559                 case INC_SOCKET_ERROR:
560                         gtk_clist_set_pixmap(clist, num, 0, errorxpm, errorxpmmask);
561                         gtk_clist_set_text(clist, num, 2, _("Error"));
562                         break;
563                 case INC_CANCEL:
564                         gtk_clist_set_pixmap(clist, num, 0, okxpm, okxpmmask);
565                         gtk_clist_set_text(clist, num, 2, _("Cancelled"));
566                         break;
567                 default:
568                         break;
569                 }
570                 
571                 if (pop3_state->error_val == PS_AUTHFAIL) {
572                         if(!prefs_common.no_recv_err_panel) {
573                                 if((prefs_common.recv_dialog_mode == RECV_DIALOG_ALWAYS) ||
574                                     ((prefs_common.recv_dialog_mode == RECV_DIALOG_ACTIVE) && focus_window)) {
575                                         manage_window_focus_in(inc_dialog->dialog->window, NULL, NULL);
576                                 }
577                                 alertpanel_error
578                                         (_("Authorization for %s on %s failed"),
579                                          pop3_state->user,
580                                          pop3_state->ac_prefs->recv_server);
581                         }
582                 }
583
584                 /* CLAWS: perform filtering actions on dropped message */
585                 /* CLAWS: get default inbox (perhaps per account) */
586                 if (pop3_state->ac_prefs->inbox) {
587                         /* CLAWS: get destination folder / mailbox */
588                         inbox = folder_find_item_from_identifier(pop3_state->ac_prefs->inbox);
589                         if (!inbox)
590                                 inbox = folder_get_default_inbox();
591                 } else
592                         inbox = folder_get_default_inbox();
593
594                 /* get list of messages in processing */
595                 processing = folder_get_default_processing();
596                 folder_item_scan(processing);
597                 msglist = folder_item_get_msg_list(processing);
598
599                 /* process messages */
600                 for(msglist_element = msglist; msglist_element != NULL; msglist_element = msglist_element->next) {
601                         MailFilteringData mail_filtering_data;
602                         msginfo = (MsgInfo *) msglist_element->data;
603                         
604                         mail_filtering_data.msginfo = msginfo;
605                         
606                         if (!hooks_invoke(MAIL_FILTERING_HOOKLIST, &mail_filtering_data)) {
607                                 /* filter if enabled in prefs or move to inbox if not */
608                                 if(global_processing && pop3_state->ac_prefs->filter_on_recv) {
609                                         filter_message_by_msginfo_with_inbox(global_processing, msginfo,
610                                                                              inbox);
611                                 } else {
612                                         folder_item_move_msg(inbox, msginfo);
613                                 }
614                         }
615                         procmsg_msginfo_free(msginfo);
616                 }
617                 g_slist_free(msglist);
618
619
620                 new_msgs += pop3_state->cur_total_num;
621
622                 if (!prefs_common.scan_all_after_inc) {
623                         folder_update_items_when_required
624                                  (!prefs_common.open_inbox_on_inc);
625                 }
626
627                 if (pop3_state->error_val == PS_AUTHFAIL &&
628                     pop3_state->ac_prefs->tmp_pass) {
629                         g_free(pop3_state->ac_prefs->tmp_pass);
630                         pop3_state->ac_prefs->tmp_pass = NULL;
631                 }
632
633                 pop3_write_uidl_list(pop3_state);
634
635                 if (inc_state != INC_SUCCESS && inc_state != INC_CANCEL) {
636                         error_num++;
637                         if (inc_state == INC_ERROR    ||
638                             inc_state == INC_NO_SPACE ||
639                             inc_state == INC_IO_ERROR ||
640                             inc_state == INC_SOCKET_ERROR) {
641                                 inc_put_error(inc_state);
642                                 break;
643                         }
644                 }
645
646                 inc_session_destroy(session);
647                 inc_dialog->queue_list =
648                         g_list_remove(inc_dialog->queue_list, session);
649
650                 num++;
651         }
652
653         if (new_msgs > 0)
654                 fin_msg = g_strdup_printf(_("Finished (%d new message(s))"),
655                                           new_msgs);
656         else
657                 fin_msg = g_strdup_printf(_("Finished (no new messages)"));
658
659         progress_dialog_set_label(inc_dialog->dialog, fin_msg);
660
661         if (error_num && !prefs_common.no_recv_err_panel) {
662                 if (inc_dialog->show_dialog)
663                         manage_window_focus_in(inc_dialog->dialog->window,
664                                                NULL, NULL);
665                 alertpanel_error(_("Some errors occurred while getting mail."));
666                 if (inc_dialog->show_dialog)
667                         manage_window_focus_out(inc_dialog->dialog->window,
668                                                 NULL, NULL);
669         }
670
671         while (inc_dialog->queue_list != NULL) {
672                 session = inc_dialog->queue_list->data;
673                 inc_session_destroy(session);
674                 inc_dialog->queue_list =
675                         g_list_remove(inc_dialog->queue_list, session);
676         }
677
678         if (prefs_common.close_recv_dialog)
679                 inc_progress_dialog_destroy(inc_dialog);
680         else {
681                 gtk_window_set_title(GTK_WINDOW(inc_dialog->dialog->window),
682                                      fin_msg);
683                 gtk_label_set_text(GTK_LABEL(GTK_BIN(inc_dialog->dialog->cancel_btn)->child),
684                                    _("Close"));
685         }
686
687         g_free(fin_msg);
688
689         return new_msgs;
690 }
691
692 static IncState inc_pop3_session_do(IncSession *session)
693 {
694         Pop3State *pop3_state = session->pop3_state;
695         IncProgressDialog *inc_dialog = (IncProgressDialog *)session->data;
696         Automaton *atm;
697         SockInfo *sockinfo;
698         gint i;
699         gchar *server;
700         gushort port;
701         gchar *buf;
702         static AtmHandler handlers[] = {
703                 pop3_greeting_recv      ,
704 #if USE_OPENSSL
705                 pop3_stls_send          , pop3_stls_recv,
706 #endif
707                 pop3_getauth_user_send  , pop3_getauth_user_recv,
708                 pop3_getauth_pass_send  , pop3_getauth_pass_recv,
709                 pop3_getauth_apop_send  , pop3_getauth_apop_recv,
710                 pop3_getrange_stat_send , pop3_getrange_stat_recv,
711                 pop3_getrange_last_send , pop3_getrange_last_recv,
712                 pop3_getrange_uidl_send , pop3_getrange_uidl_recv,
713                 pop3_getsize_list_send  , pop3_getsize_list_recv,
714                 pop3_top_send           , pop3_top_recv,
715                 pop3_retr_send          , pop3_retr_recv,
716                 pop3_delete_send        , pop3_delete_recv,
717                 pop3_logout_send        , pop3_logout_recv
718         };
719
720         debug_print("getting new messages of account %s...\n",
721                     pop3_state->ac_prefs->account_name);
722
723         pop3_state->ac_prefs->last_pop_login_time = time(NULL);
724         atm = automaton_create(N_POP3_PHASE);
725
726         session->atm = atm;
727         atm->data = pop3_state;
728
729         buf = g_strdup_printf(_("%s: Retrieving new messages"),
730                               pop3_state->ac_prefs->recv_server);
731         gtk_window_set_title(GTK_WINDOW(inc_dialog->dialog->window), buf);
732         g_free(buf);
733
734         for (i = POP3_GREETING_RECV; i < N_POP3_PHASE; i++)
735                 atm->state[i].handler = handlers[i];
736         atm->state[POP3_GREETING_RECV].condition = (G_IO_IN | G_IO_HUP | G_IO_ERR);
737         for (i = POP3_GREETING_RECV + 1; i < N_POP3_PHASE; ) {
738                 atm->state[i++].condition = (G_IO_OUT | G_IO_ERR);
739                 atm->state[i++].condition = (G_IO_IN | G_IO_HUP | G_IO_ERR);
740         }
741
742         atm->terminate = (AtmHandler)pop3_automaton_terminate;
743         atm->ui_func = (AtmUIFunc)inc_progress_update;
744
745         atm->num = POP3_GREETING_RECV;
746
747         server = pop3_state->ac_prefs->recv_server;
748 #if USE_OPENSSL
749         port = pop3_state->ac_prefs->set_popport ?
750                 pop3_state->ac_prefs->popport :
751                 pop3_state->ac_prefs->ssl_pop == SSL_TUNNEL ? 995 : 110;
752 #else
753         port = pop3_state->ac_prefs->set_popport ?
754                 pop3_state->ac_prefs->popport : 110;
755 #endif
756
757         buf = g_strdup_printf(_("Connecting to POP3 server: %s ..."), server);
758         log_message("%s\n", buf);
759         progress_dialog_set_label(inc_dialog->dialog, buf);
760         g_free(buf);
761         GTK_EVENTS_FLUSH();
762
763         if ((sockinfo = sock_connect(server, port)) == NULL) {
764                 log_warning(_("Can't connect to POP3 server: %s:%d\n"),
765                             server, port);
766                 if(!prefs_common.no_recv_err_panel) {
767                         if((prefs_common.recv_dialog_mode == RECV_DIALOG_ALWAYS) ||
768                             ((prefs_common.recv_dialog_mode == RECV_DIALOG_ACTIVE) && focus_window)) {
769                                 manage_window_focus_in(inc_dialog->dialog->window, NULL, NULL);
770                         }
771                         alertpanel_error(_("Can't connect to POP3 server: %s:%d"),
772                                          server, port);
773                         manage_window_focus_out(inc_dialog->dialog->window, NULL, NULL);
774                 }
775                 pop3_automaton_terminate(NULL, atm);
776                 automaton_destroy(atm);
777                 session->inc_state = INC_CONNECT_ERROR;
778                 return INC_CONNECT_ERROR;
779         }
780
781 #if USE_OPENSSL
782         if (pop3_state->ac_prefs->ssl_pop == SSL_TUNNEL &&
783             !ssl_init_socket(sockinfo)) {
784                 pop3_automaton_terminate(sockinfo, atm);
785                 automaton_destroy(atm);
786                 session->inc_state = INC_CONNECT_ERROR;
787                 return INC_CONNECT_ERROR;
788         }
789 #endif
790
791         /* :WK: Hmmm, with the later sock_gdk_input, we have 2 references
792          * to the sock structure - implement a reference counter?? */
793         pop3_state->sockinfo = sockinfo;
794         atm->help_sock = sockinfo;
795
796         statusbar_verbosity_set(TRUE);
797         /* oha: this messes up inc_progress update:
798            disabling this would avoid the label "Retrieve Header"
799            being overwritten by "Retrieve Message"
800            Setting inc_pop3_recv_func is not necessary
801            since atm already handles the progress dialog ui
802            just fine.
803         */
804         recv_set_ui_func(inc_pop3_recv_func, session);
805
806         atm->tag = sock_input_add(sockinfo,
807                                   atm->state[atm->num].condition,
808                                   automaton_input_cb, atm);
809
810         while (!atm->terminated && !atm->cancelled)
811                 gtk_main_iteration();
812
813         if (!atm->terminated)
814                 pop3_automaton_terminate(sockinfo, atm);
815
816         statusbar_verbosity_set(FALSE);
817         /* oha: see above */
818         recv_set_ui_func(NULL, NULL);
819
820         automaton_destroy(atm);
821
822         if (session->inc_state != INC_SUCCESS)
823                 return session->inc_state;
824
825         switch (pop3_state->error_val) {
826         case PS_SUCCESS:
827                 session->inc_state = INC_SUCCESS;
828                 break;
829         case PS_AUTHFAIL:
830                 session->inc_state = INC_AUTH_FAILED;
831                 break;
832         case PS_IOERR:
833                 session->inc_state = INC_IO_ERROR;
834                 break;
835         case PS_SOCKET:
836                 session->inc_state = INC_SOCKET_ERROR;
837                 break;
838         case PS_LOCKBUSY:
839                 session->inc_state = INC_LOCKED;
840                 break;
841         default:
842                 session->inc_state = INC_ERROR;
843                 break;
844         }
845
846         return session->inc_state;
847 }
848
849 static gint pop3_automaton_terminate(SockInfo *source, Automaton *atm)
850 {
851         if (atm->terminated) return 0;
852
853         if (atm->tag > 0) {
854                 gdk_input_remove(atm->tag);
855                 atm->tag = 0;
856         }
857         if (atm->timeout_tag > 0) {
858                 gtk_timeout_remove(atm->timeout_tag);
859                 atm->timeout_tag = 0;
860         }
861         if (source)
862                 sock_close(source);
863
864         atm->terminated = TRUE;
865
866         return 0;
867 }
868
869 static gboolean inc_pop3_recv_func(SockInfo *sock, gint count, gint read_bytes,
870                                    gpointer data)
871 {
872         gchar buf[MSGBUFSIZE];
873         IncSession *session = (IncSession *)data;
874         Pop3State *state = session->pop3_state;
875         IncProgressDialog *inc_dialog = (IncProgressDialog *)session->data;
876         ProgressDialog *dialog = inc_dialog->dialog;
877         gint cur_total;
878         gchar *total_size;
879
880         cur_total = state->cur_total_bytes + read_bytes;
881         if (cur_total > state->total_bytes)
882                 cur_total = state->total_bytes;
883
884         Xstrdup_a(total_size, to_human_readable(state->total_bytes),
885                   return FALSE);
886         g_snprintf(buf, sizeof(buf),
887                    _("Retrieving message (%d / %d) (%s / %s)"),
888                    state->cur_msg, state->count,
889                    to_human_readable(cur_total), total_size);
890         progress_dialog_set_label(dialog, buf);
891
892         progress_dialog_set_percentage
893                 (dialog, (gfloat)cur_total / (gfloat)state->total_bytes);
894         if (inc_dialog->mainwin)
895                 gtk_progress_bar_update
896                         (GTK_PROGRESS_BAR(inc_dialog->mainwin->progressbar),
897                          (gfloat)cur_total / (gfloat)state->total_bytes);
898         GTK_EVENTS_FLUSH();
899
900         if (session->inc_state == INC_CANCEL)
901                 return FALSE;
902         else
903                 return TRUE;
904 }
905
906 void inc_progress_update(Pop3State *state, Pop3Phase phase)
907 {
908         gchar buf[MSGBUFSIZE];
909         IncSession *session = (IncSession *)state->data;
910         IncProgressDialog *inc_dialog = (IncProgressDialog *)session->data;
911         ProgressDialog *dialog = inc_dialog->dialog;
912         gchar *total_size;
913
914         switch (phase) {
915         case POP3_GREETING_RECV:
916                 break;
917         case POP3_GETAUTH_USER_SEND:
918         case POP3_GETAUTH_PASS_SEND:
919         case POP3_GETAUTH_APOP_SEND:
920                 progress_dialog_set_label(dialog, _("Authenticating..."));
921                 break;
922         case POP3_GETRANGE_STAT_SEND:
923                 progress_dialog_set_label
924                         (dialog, _("Getting the number of new messages (STAT)..."));
925                 break;
926         case POP3_GETRANGE_LAST_SEND:
927                 progress_dialog_set_label
928                         (dialog, _("Getting the number of new messages (LAST)..."));
929                 break;
930         case POP3_GETRANGE_UIDL_SEND:
931                 progress_dialog_set_label
932                         (dialog, _("Getting the number of new messages (UIDL)..."));
933                 break;
934         case POP3_GETSIZE_LIST_SEND:
935                 progress_dialog_set_label
936                         (dialog, _("Getting the size of messages (LIST)..."));
937                 break;
938         case POP3_TOP_SEND:
939                 g_snprintf(buf, sizeof(buf),
940                            _("Retrieving header (%d / %d)"),
941                            state->cur_msg, state->count);
942                 progress_dialog_set_label (dialog, buf);
943                 progress_dialog_set_percentage
944                         (dialog,
945                          (gfloat)(state->cur_msg) /
946                          (gfloat)(state->count));
947                 if (inc_dialog->mainwin)
948                         gtk_progress_bar_update 
949                                 (GTK_PROGRESS_BAR(inc_dialog->mainwin->progressbar),
950                                  (gfloat)(state->cur_msg) /
951                                  (gfloat)(state->count));
952                 break;
953         case POP3_RETR_SEND:
954                 Xstrdup_a(total_size, to_human_readable(state->total_bytes), return);
955                 g_snprintf(buf, sizeof(buf),
956                            _("Retrieving message (%d / %d) (%s / %s)"),
957                            state->cur_msg, state->count,
958                            to_human_readable(state->cur_total_bytes),
959                            total_size);
960                 progress_dialog_set_label(dialog, buf);
961                 progress_dialog_set_percentage
962                         (dialog,
963                          (gfloat)(state->cur_total_bytes) /
964                          (gfloat)(state->total_bytes));
965                 if (inc_dialog->mainwin)
966                         gtk_progress_bar_update
967                                 (GTK_PROGRESS_BAR(inc_dialog->mainwin->progressbar),
968                                  (gfloat)(state->cur_total_bytes) /
969                                  (gfloat)(state->total_bytes));
970                 break;
971         case POP3_DELETE_SEND:
972                 if (state->msg[state->cur_msg].recv_time < state->current_time) {
973                         g_snprintf(buf, sizeof(buf), _("Deleting message %d"),
974                                    state->cur_msg);
975                         progress_dialog_set_label(dialog, buf);
976                 }
977                 break;
978         case POP3_LOGOUT_SEND:
979                 progress_dialog_set_label(dialog, _("Quitting"));
980                 break;
981         default:
982                 break;
983         }
984 }
985
986 gint inc_drop_message(const gchar *file, Pop3State *state)
987 {
988         FolderItem *inbox;
989         FolderItem *dropfolder;
990         gint msgnum;
991
992         /* CLAWS: get default inbox (perhaps per account) */
993         if (state->ac_prefs->inbox) {
994                 /* CLAWS: get destination folder / mailbox */
995                 inbox = folder_find_item_from_identifier
996                         (state->ac_prefs->inbox);
997                 if (!inbox)
998                         inbox = folder_get_default_inbox();
999         } else
1000                 inbox = folder_get_default_inbox();
1001         if (!inbox) {
1002                 unlink(file);
1003                 return -1;
1004         }
1005
1006         /* CLAWS: claws uses a global .processing folder for the filtering. */
1007         dropfolder = folder_get_default_processing();
1008
1009         /* add msg file to drop folder */
1010         if ((msgnum = folder_item_add_msg(dropfolder, file, TRUE)) < 0) {
1011                 unlink(file);
1012                 return -1;
1013         }
1014
1015         return 0;
1016 }
1017
1018 static void inc_put_error(IncState istate)
1019 {
1020         switch (istate) {
1021         case INC_ERROR:
1022                 if (!prefs_common.no_recv_err_panel)
1023                         alertpanel_error
1024                                 (_("Error occurred while processing mail."));
1025                 break;
1026         case INC_NO_SPACE:
1027                 alertpanel_error(_("No disk space left."));
1028                 break;
1029         case INC_IO_ERROR:
1030                 alertpanel_error(_("Can't write file."));
1031                 break;
1032         case INC_SOCKET_ERROR:
1033                 alertpanel_error(_("Socket error."));
1034                 break;
1035         case INC_LOCKED:
1036                 if (!prefs_common.no_recv_err_panel)
1037                         alertpanel_error(_("Mailbox is locked."));
1038                 break;
1039         default:
1040                 break;
1041         }
1042 }
1043
1044 static void inc_cancel(IncProgressDialog *dialog)
1045 {
1046         IncSession *session;
1047         SockInfo *sockinfo;
1048
1049         g_return_if_fail(dialog != NULL);
1050
1051         if (dialog->queue_list == NULL) {
1052                 inc_progress_dialog_destroy(dialog);
1053                 return;
1054         }
1055
1056         session = dialog->queue_list->data;
1057         sockinfo = session->pop3_state->sockinfo;
1058
1059         if (!sockinfo || session->atm->terminated == TRUE) return;
1060
1061         session->pop3_state->cancelled = TRUE;
1062         session->inc_state = INC_CANCEL;
1063         session->atm->cancelled = TRUE;
1064
1065         log_message(_("Incorporation cancelled\n"));
1066 }
1067
1068 gboolean inc_is_active(void)
1069 {
1070         return (inc_dialog_list != NULL);
1071 }
1072
1073 void inc_cancel_all(void)
1074 {
1075         GList *cur;
1076
1077         for (cur = inc_dialog_list; cur != NULL; cur = cur->next)
1078                 inc_cancel((IncProgressDialog *)cur->data);
1079 }
1080
1081 static void inc_cancel_cb(GtkWidget *widget, gpointer data)
1082 {
1083         inc_cancel((IncProgressDialog *)data);
1084 }
1085
1086 static gint inc_dialog_delete_cb(GtkWidget *widget, GdkEventAny *event,
1087                                  gpointer data)
1088 {
1089         IncProgressDialog *dialog = (IncProgressDialog *)data;
1090
1091         if (dialog->queue_list == NULL)
1092                 inc_progress_dialog_destroy(dialog);
1093
1094         return TRUE;
1095 }
1096
1097 static gint inc_spool(void)
1098 {
1099         gchar *mbox, *logname;
1100         gint msgs;
1101
1102         logname = g_get_user_name();
1103         mbox = g_strconcat(prefs_common.spool_path
1104                            ? prefs_common.spool_path : DEFAULT_SPOOL_PATH,
1105                            G_DIR_SEPARATOR_S, logname, NULL);
1106         msgs = get_spool(folder_get_default_inbox(), mbox);
1107         g_free(mbox);
1108
1109         return msgs;
1110 }
1111
1112 static void inc_spool_account(PrefsAccount *account)
1113 {
1114         FolderItem *inbox;
1115
1116         if (account->inbox) {
1117                 inbox = folder_find_item_from_path(account->inbox);
1118                 if (!inbox)
1119                         inbox = folder_get_default_inbox();
1120         } else
1121                 inbox = folder_get_default_inbox();
1122
1123         get_spool(inbox, account->local_mbox);
1124 }
1125
1126 static void inc_all_spool(void)
1127 {
1128         GList *list = NULL;
1129
1130         list = account_get_list();
1131         if (!list) return;
1132
1133         for (; list != NULL; list = list->next) {
1134                 PrefsAccount *account = list->data;
1135
1136                 if ((account->protocol == A_LOCAL) &&
1137                     (account->recv_at_getall))
1138                         inc_spool_account(account);
1139         }
1140 }
1141
1142 static gint get_spool(FolderItem *dest, const gchar *mbox)
1143 {
1144         gint msgs, size;
1145         gint lockfd;
1146         gchar tmp_mbox[MAXPATHLEN + 1];
1147
1148         g_return_val_if_fail(dest != NULL, -1);
1149         g_return_val_if_fail(mbox != NULL, -1);
1150
1151         if (!is_file_exist(mbox) || (size = get_file_size(mbox)) == 0) {
1152                 debug_print("no messages in local mailbox.\n");
1153                 return 0;
1154         } else if (size < 0)
1155                 return -1;
1156
1157         if ((lockfd = lock_mbox(mbox, LOCK_FLOCK)) < 0)
1158                 return -1;
1159
1160         g_snprintf(tmp_mbox, sizeof(tmp_mbox), "%s%ctmpmbox.%08x",
1161                    get_tmp_dir(), G_DIR_SEPARATOR, (gint)mbox);
1162
1163         if (copy_mbox(mbox, tmp_mbox) < 0) {
1164                 unlock_mbox(mbox, lockfd, LOCK_FLOCK);
1165                 return -1;
1166         }
1167
1168         debug_print("Getting new messages from %s into %s...\n",
1169                     mbox, dest->path);
1170
1171         msgs = proc_mbox(dest, tmp_mbox);
1172
1173         unlink(tmp_mbox);
1174         if (msgs >= 0) empty_mbox(mbox);
1175         unlock_mbox(mbox, lockfd, LOCK_FLOCK);
1176
1177         if (!prefs_common.scan_all_after_inc) {
1178                 folder_update_items_when_required
1179                         (!prefs_common.open_inbox_on_inc);
1180         } else if (!prefs_common.scan_all_after_inc) {
1181                 folder_update_item(dest, TRUE);
1182         }
1183
1184         return msgs;
1185 }
1186
1187 void inc_lock(void)
1188 {
1189         inc_lock_count++;
1190 }
1191
1192 void inc_unlock(void)
1193 {
1194         if (inc_lock_count > 0)
1195                 inc_lock_count--;
1196 }
1197
1198 static guint autocheck_timer = 0;
1199 static gpointer autocheck_data = NULL;
1200
1201 static void inc_notify_cmd(gint new_msgs, gboolean notify)
1202 {
1203
1204         gchar *buf;
1205
1206         if (!(new_msgs && notify && prefs_common.newmail_notify_cmd &&
1207             *prefs_common.newmail_notify_cmd))
1208                      return;
1209         if ((buf = strchr(prefs_common.newmail_notify_cmd, '%')) &&
1210                 buf[1] == 'd' && !strchr(&buf[1], '%'))
1211                 buf = g_strdup_printf(prefs_common.newmail_notify_cmd, 
1212                                       new_msgs);
1213         else
1214                 buf = g_strdup(prefs_common.newmail_notify_cmd);
1215
1216         execute_command_line(buf, TRUE);
1217
1218         g_free(buf);
1219 }
1220  
1221 void inc_autocheck_timer_init(MainWindow *mainwin)
1222 {
1223         autocheck_data = mainwin;
1224         inc_autocheck_timer_set();
1225 }
1226
1227 static void inc_autocheck_timer_set_interval(guint interval)
1228 {
1229         inc_autocheck_timer_remove();
1230         /* last test is to avoid re-enabling auto_check after modifying 
1231            the common preferences */
1232         if (prefs_common.autochk_newmail && autocheck_data
1233             && prefs_common.work_offline == FALSE) {
1234                 autocheck_timer = gtk_timeout_add
1235                         (interval, inc_autocheck_func, autocheck_data);
1236                 debug_print("added timer = %d\n", autocheck_timer);
1237         }
1238 }
1239
1240 void inc_autocheck_timer_set(void)
1241 {
1242         inc_autocheck_timer_set_interval(prefs_common.autochk_itv * 60000);
1243 }
1244
1245 void inc_autocheck_timer_remove(void)
1246 {
1247         if (autocheck_timer) {
1248                 debug_print("removed timer = %d\n", autocheck_timer);
1249                 gtk_timeout_remove(autocheck_timer);
1250                 autocheck_timer = 0;
1251         }
1252 }
1253
1254 static gint inc_autocheck_func(gpointer data)
1255 {
1256         MainWindow *mainwin = (MainWindow *)data;
1257
1258         if (inc_lock_count) {
1259                 debug_print("autocheck is locked.\n");
1260                 inc_autocheck_timer_set_interval(1000);
1261                 return FALSE;
1262         }
1263
1264         inc_all_account_mail(mainwin, prefs_common.newmail_notify_auto);
1265
1266         return FALSE;
1267 }