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