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