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