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