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