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