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