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