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