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