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