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