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