added missing line
[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
398         while (inc_dialog->queue_list != NULL) {
399                 session = inc_dialog->queue_list->data;
400                 pop3_state = session->pop3_state;
401
402                 inc_progress_dialog_clear(inc_dialog);
403
404                 gtk_clist_moveto(clist, num, 0, 1.0, 0.0);
405
406                 pop3_state->user = g_strdup(pop3_state->ac_prefs->userid);
407                 if (pop3_state->ac_prefs->passwd)
408                         pop3_state->pass =
409                                 g_strdup(pop3_state->ac_prefs->passwd);
410                 else if (pop3_state->ac_prefs->tmp_pass)
411                         pop3_state->pass =
412                                 g_strdup(pop3_state->ac_prefs->tmp_pass);
413                 else {
414                         gchar *pass;
415                         gchar *message;
416
417                         message = g_strdup_printf
418                                 (_("Input password for %s on %s:"),
419                                  pop3_state->user,
420                                  pop3_state->ac_prefs->recv_server);
421
422                         pass = input_dialog_with_invisible(_("Input password"),
423                                                            message, NULL);
424                         g_free(message);
425                         if((prefs_common.receive_dialog == RECVDIALOG_ALWAYS) ||
426                             ((prefs_common.receive_dialog == RECVDIALOG_WINDOW_ACTIVE) && focus_window)) {
427                                 manage_window_focus_in(inc_dialog->mainwin->window,
428                                                        NULL, NULL);
429                         }
430                         if (pass) {
431                                 pop3_state->ac_prefs->tmp_pass = g_strdup(pass);
432                                 pop3_state->pass = pass;
433                         } else {
434                                 inc_session_destroy(session);
435                                 inc_dialog->queue_list = g_list_remove
436                                         (inc_dialog->queue_list, session);
437                                 continue;
438                         }
439                 }
440
441                 gtk_clist_set_pixmap(clist, num, 0, currentxpm, currentxpmmask);
442                 gtk_clist_set_text(clist, num, 2, _("Retrieving"));
443
444                 /* begin POP3 session */
445                 inc_state = inc_pop3_session_do(session);
446
447                 if (inc_state == INC_SUCCESS || inc_state == INC_CANCEL) {
448                         gtk_clist_set_pixmap(clist, num, 0, okxpm, okxpmmask);
449                         gtk_clist_set_text(clist, num, 2, _("Done"));
450                 } else {
451                         gtk_clist_set_pixmap(clist, num, 0, errorxpm, errorxpmmask);
452                         gtk_clist_set_text(clist, num, 2, _("Error"));
453                 }
454
455                 if (pop3_state->error_val == PS_AUTHFAIL) {
456                         if(!prefs_common.noerrorpanel) {
457                                 if((prefs_common.receive_dialog == RECVDIALOG_ALWAYS) ||
458                                     ((prefs_common.receive_dialog == RECVDIALOG_WINDOW_ACTIVE) && focus_window)) {
459                                         manage_window_focus_in(inc_dialog->dialog->window, NULL, NULL);
460                                 }
461                                 alertpanel_error
462                                         (_("Authorization for %s on %s failed"),
463                                          pop3_state->user,
464                                          pop3_state->ac_prefs->recv_server);
465                         }
466                 }
467
468                 statusbar_pop_all();
469                 if((prefs_common.receive_dialog == RECVDIALOG_ALWAYS) ||
470                     ((prefs_common.receive_dialog == RECVDIALOG_WINDOW_ACTIVE) && focus_window)) {
471                         manage_window_focus_in(inc_dialog->mainwin->window, NULL, NULL);
472                 }
473                 
474                 folder_item_scan_foreach(pop3_state->folder_table);
475                 folderview_update_item_foreach(pop3_state->folder_table);
476
477                 if (pop3_state->error_val == PS_AUTHFAIL &&
478                     pop3_state->ac_prefs->tmp_pass) {
479                         g_free(pop3_state->ac_prefs->tmp_pass);
480                         pop3_state->ac_prefs->tmp_pass = NULL;
481                 }
482
483                 inc_write_uidl_list(pop3_state);
484
485                 if (inc_state != INC_SUCCESS) {
486                         inc_put_error(inc_state);
487                         break;
488                 }
489
490                 inc_session_destroy(session);
491                 inc_dialog->queue_list =
492                         g_list_remove(inc_dialog->queue_list, session);
493
494                 num++;
495         }
496
497         while (inc_dialog->queue_list != NULL) {
498                 session = inc_dialog->queue_list->data;
499                 inc_session_destroy(session);
500                 inc_dialog->queue_list =
501                         g_list_remove(inc_dialog->queue_list, session);
502         }
503
504         inc_progress_dialog_destroy(inc_dialog);
505 }
506
507
508 static IncState inc_pop3_session_do(IncSession *session)
509 {
510         Pop3State *pop3_state = session->pop3_state;
511         IncProgressDialog *inc_dialog = (IncProgressDialog *)session->data;
512         Automaton *atm;
513         SockInfo *sockinfo;
514         gint i;
515         gchar *server;
516         gushort port;
517         gchar *buf;
518         static AtmHandler handlers[] = {
519                 pop3_greeting_recv      ,
520                 pop3_getauth_user_send  , pop3_getauth_user_recv,
521                 pop3_getauth_pass_send  , pop3_getauth_pass_recv,
522                 pop3_getauth_apop_send  , pop3_getauth_apop_recv,
523                 pop3_getrange_stat_send , pop3_getrange_stat_recv,
524                 pop3_getrange_last_send , pop3_getrange_last_recv,
525                 pop3_getrange_uidl_send , pop3_getrange_uidl_recv,
526                 pop3_getsize_list_send  , pop3_getsize_list_recv,
527                 pop3_retr_send          , pop3_retr_recv,
528                 pop3_delete_send        , pop3_delete_recv,
529                 pop3_logout_send        , pop3_logout_recv
530         };
531
532         debug_print(_("getting new messages of account %s...\n"),
533                     pop3_state->ac_prefs->account_name);
534
535         atm = automaton_create(N_POP3_PHASE);
536
537         session->atm = atm;
538         atm->data = pop3_state;
539
540         buf = g_strdup_printf(_("%s: Retrieving new messages"),
541                               pop3_state->ac_prefs->recv_server);
542         gtk_window_set_title(GTK_WINDOW(inc_dialog->dialog->window), buf);
543         g_free(buf);
544
545         for (i = POP3_GREETING_RECV; i < N_POP3_PHASE; i++)
546                 atm->state[i].handler = handlers[i];
547         atm->state[POP3_GREETING_RECV].condition = GDK_INPUT_READ;
548         for (i = POP3_GETAUTH_USER_SEND; i < N_POP3_PHASE; ) {
549                 atm->state[i++].condition = GDK_INPUT_WRITE;
550                 atm->state[i++].condition = GDK_INPUT_READ;
551         }
552
553         atm->terminate = (AtmHandler)pop3_automaton_terminate;
554
555         atm->num = POP3_GREETING_RECV;
556
557         server = pop3_state->ac_prefs->recv_server;
558 #if USE_SSL
559         port = pop3_state->ac_prefs->set_popport ?
560                 pop3_state->ac_prefs->popport : (pop3_state->ac_prefs->pop_ssl ? 995 : 110);
561 #else
562         port = pop3_state->ac_prefs->set_popport ?
563                 pop3_state->ac_prefs->popport : 110;
564 #endif
565
566         buf = g_strdup_printf(_("Connecting to POP3 server: %s ..."), server);
567         log_message("%s\n", buf);
568         progress_dialog_set_label(inc_dialog->dialog, buf);
569         g_free(buf);
570         GTK_EVENTS_FLUSH();
571
572 #if USE_THREADS
573         if ((sockinfo = sock_connect_with_thread(server, port)) == NULL) {
574 #else
575         if ((sockinfo = sock_connect(server, port)) == NULL) {
576 #endif
577                 log_warning(_("Can't connect to POP3 server: %s:%d\n"),
578                             server, port);
579                 if(!prefs_common.noerrorpanel) {
580                         if((prefs_common.receive_dialog == RECVDIALOG_ALWAYS) ||
581                             ((prefs_common.receive_dialog == RECVDIALOG_WINDOW_ACTIVE) && focus_window)) {
582                                 manage_window_focus_in(inc_dialog->dialog->window, NULL, NULL);
583                         }
584                         alertpanel_error(_("Can't connect to POP3 server: %s:%d"),
585                                          server, port);
586                         manage_window_focus_out(inc_dialog->dialog->window, NULL, NULL);
587                 }
588                 pop3_automaton_terminate(NULL, atm);
589                 automaton_destroy(atm);
590
591                 return INC_ERROR;
592         }
593
594         /* :WK: Hmmm, with the later sock_gdk_input, we have 2 references
595          * to the sock structure - implement a reference counter?? */
596         pop3_state->sockinfo = sockinfo;
597         atm->help_sock = sockinfo;
598
599 #ifdef USE_SSL
600         if(pop3_state->ac_prefs->pop_ssl) {
601                 if(!ssl_init_socket(sockinfo)) {
602                         pop3_automaton_terminate(NULL, atm);
603                         automaton_destroy(atm);
604                         
605                         return INC_ERROR;
606                 }
607         } else {
608                 sockinfo->ssl = NULL;
609         }
610 #endif
611
612         recv_set_ui_func(inc_pop3_recv_func, session);
613
614 #if USE_THREADS
615         atm->timeout_tag = gtk_timeout_add
616                 (TIMEOUT_ITV, (GtkFunction)connection_check_cb, atm);
617 #else
618         atm->tag = sock_gdk_input_add(sockinfo,
619                                       atm->state[atm->num].condition,
620                                       automaton_input_cb, atm);
621 #endif
622
623         gtk_main();
624
625         recv_set_ui_func(NULL, NULL);
626
627 #if USE_THREADS
628 /*
629         pthread_join(sockinfo->connect_thr, NULL);
630 */      
631 #endif
632
633 #if USE_SSL
634         ssl_done_socket(sockinfo);
635 #endif
636         automaton_destroy(atm);
637
638         return pop3_state->inc_state;
639 }
640
641 static gint pop3_automaton_terminate(SockInfo *source, Automaton *atm)
642 {
643         if (atm->tag > 0) {
644                 gdk_input_remove(atm->tag);
645                 atm->tag = 0;
646         }
647         if (atm->timeout_tag > 0) {
648                 gtk_timeout_remove(atm->timeout_tag);
649                 atm->timeout_tag = 0;
650         }
651         if (source) {
652                 sock_close(source);
653                 gtk_main_quit();
654         }
655
656         atm->terminated = TRUE;
657
658         return 0;
659 }
660
661 static GHashTable *inc_get_uidl_table(PrefsAccount *ac_prefs)
662 {
663         GHashTable *table;
664         gchar *path;
665         FILE *fp;
666         gchar buf[IDLEN + 3];
667
668         path = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
669                            "uidl-", ac_prefs->recv_server,
670                            "-", ac_prefs->userid, NULL);
671         if ((fp = fopen(path, "r")) == NULL) {
672                 if (ENOENT != errno) FILE_OP_ERROR(path, "fopen");
673                 g_free(path);
674                 return NULL;
675         }
676         g_free(path);
677
678         table = g_hash_table_new(g_str_hash, g_str_equal);
679
680         while (fgets(buf, sizeof(buf), fp) != NULL) {
681                 strretchomp(buf);
682                 g_hash_table_insert(table, g_strdup(buf), GINT_TO_POINTER(1));
683         }
684
685         fclose(fp);
686
687         return table;
688 }
689
690 static void inc_write_uidl_list(Pop3State *state)
691 {
692         gchar *path;
693         FILE *fp;
694         GSList *cur;
695
696         if (!state->id_list) return;
697
698         path = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
699                            "uidl-", state->ac_prefs->recv_server,
700                            "-", state->user, NULL);
701         if ((fp = fopen(path, "w")) == NULL) {
702                 FILE_OP_ERROR(path, "fopen");
703                 g_free(path);
704                 return;
705         }
706
707         for (cur = state->id_list; cur != NULL; cur = cur->next) {
708                 if (fputs((gchar *)cur->data, fp) == EOF) {
709                         FILE_OP_ERROR(path, "fputs");
710                         break;
711                 }
712                 if (fputc('\n', fp) == EOF) {
713                         FILE_OP_ERROR(path, "fputc");
714                         break;
715                 }
716         }
717
718         if (fclose(fp) == EOF) FILE_OP_ERROR(path, "fclose");
719         g_free(path);
720 }
721
722 #if USE_THREADS
723 static gint connection_check_cb(Automaton *atm)
724 {
725         Pop3State *state = atm->data;
726         IncProgressDialog *inc_dialog = state->session->data;
727         SockInfo *sockinfo = state->sockinfo;
728
729         /* g_print("connection check\n"); */
730
731         if (sockinfo->state == CONN_LOOKUPFAILED ||
732             sockinfo->state == CONN_FAILED) {
733                 atm->timeout_tag = 0;
734                 log_warning(_("Can't connect to POP3 server: %s:%d\n"),
735                             sockinfo->hostname, sockinfo->port);
736                 if(!prefs_common.noerrorpanel) {
737                         if((prefs_common.receive_dialog == RECVDIALOG_ALWAYS) ||
738                             ((prefs_common.receive_dialog == RECVDIALOG_WINDOW_ACTIVE) && focus_window)) {
739                                 manage_window_focus_in(inc_dialog->dialog->window, NULL, NULL);
740                         }
741                         alertpanel_error(_("Can't connect to POP3 server: %s:%d"),
742                                          sockinfo->hostname, sockinfo->port);
743                         manage_window_focus_out(inc_dialog->dialog->window, NULL, NULL);
744                 }
745                 pop3_automaton_terminate(sockinfo, atm);
746                 return FALSE;
747         } else if (sockinfo->state == CONN_ESTABLISHED) {
748                 atm->timeout_tag = 0;
749                 atm->tag = sock_gdk_input_add(sockinfo,
750                                               atm->state[atm->num].condition,
751                                               automaton_input_cb, atm);
752                 return FALSE;
753         } else {
754                 return TRUE;
755         }
756 }
757 #endif
758
759 static void inc_pop3_recv_func(SockInfo *sock, gint count, gint read_bytes,
760                                gpointer data)
761 {
762         gchar buf[MSGBUFSIZE];
763         IncSession *session = (IncSession *)data;
764         Pop3State *state = session->pop3_state;
765         IncProgressDialog *inc_dialog = session->data;
766         ProgressDialog *dialog = inc_dialog->dialog;
767         gint cur_total;
768         gchar *total_size;
769
770         cur_total = state->cur_total_bytes + read_bytes;
771         if (cur_total > state->total_bytes)
772                 cur_total = state->total_bytes;
773
774         Xstrdup_a(total_size, to_human_readable(state->total_bytes), return);
775         g_snprintf(buf, sizeof(buf),
776                    _("Retrieving message (%d / %d) (%s / %s)"),
777                    state->cur_msg, state->count,
778                    to_human_readable(cur_total), total_size);
779         progress_dialog_set_label(dialog, buf);
780
781         progress_dialog_set_percentage
782                 (dialog, (gfloat)cur_total / (gfloat)state->total_bytes);
783         GTK_EVENTS_FLUSH();
784 }
785
786 void inc_progress_update(Pop3State *state, Pop3Phase phase)
787 {
788         gchar buf[MSGBUFSIZE];
789         IncProgressDialog *inc_dialog = state->session->data;
790         ProgressDialog *dialog = inc_dialog->dialog;
791         gchar *total_size;
792
793         switch (phase) {
794         case POP3_GREETING_RECV:
795                 break;
796         case POP3_GETAUTH_USER_SEND:
797         case POP3_GETAUTH_USER_RECV:
798         case POP3_GETAUTH_PASS_SEND:
799         case POP3_GETAUTH_PASS_RECV:
800         case POP3_GETAUTH_APOP_SEND:
801         case POP3_GETAUTH_APOP_RECV:
802                 progress_dialog_set_label(dialog, _("Authorizing..."));
803                 break;
804         case POP3_GETRANGE_STAT_SEND:
805         case POP3_GETRANGE_STAT_RECV:
806                 progress_dialog_set_label
807                         (dialog, _("Getting the number of new messages (STAT)..."));
808                 break;
809         case POP3_GETRANGE_LAST_SEND:
810         case POP3_GETRANGE_LAST_RECV:
811                 progress_dialog_set_label
812                         (dialog, _("Getting the number of new messages (LAST)..."));
813                 break;
814         case POP3_GETRANGE_UIDL_SEND:
815         case POP3_GETRANGE_UIDL_RECV:
816                 progress_dialog_set_label
817                         (dialog, _("Getting the number of new messages (UIDL)..."));
818                 break;
819         case POP3_GETSIZE_LIST_SEND:
820         case POP3_GETSIZE_LIST_RECV:
821                 progress_dialog_set_label
822                         (dialog, _("Getting the size of messages (LIST)..."));
823                 break;
824         case POP3_RETR_SEND:
825         case POP3_RETR_RECV:
826                 Xstrdup_a(total_size, to_human_readable(state->total_bytes), return);
827                 g_snprintf(buf, sizeof(buf),
828                            _("Retrieving message (%d / %d) (%s / %s)"),
829                            state->cur_msg, state->count,
830                            to_human_readable(state->cur_total_bytes),
831                            total_size);
832                 progress_dialog_set_label(dialog, buf);
833                 progress_dialog_set_percentage
834                         (dialog,
835                          (gfloat)(state->cur_total_bytes) /
836                          (gfloat)(state->total_bytes));
837                 break;
838         case POP3_DELETE_SEND:
839         case POP3_DELETE_RECV:
840                 progress_dialog_set_label(dialog, _("Deleting message"));
841                 break;
842         case POP3_LOGOUT_SEND:
843         case POP3_LOGOUT_RECV:
844                 progress_dialog_set_label(dialog, _("Quitting"));
845                 break;
846         default:
847                 break;
848         }
849 }
850
851 gint inc_drop_message(const gchar *file, Pop3State *state)
852 {
853         FolderItem *inbox;
854         FolderItem *dropfolder;
855         gint val;
856         gint msgnum;
857         
858         if (state->ac_prefs->inbox) {
859                 inbox = folder_find_item_from_path(state->ac_prefs->inbox);
860                 if (!inbox)
861                         inbox = folder_get_default_inbox();
862         } else
863                 inbox = folder_get_default_inbox();
864         if (!inbox) {
865                 unlink(file);
866                 return -1;
867         }
868
869         if (prefs_filtering == NULL) {
870                 /* old filtering */
871                 if (state->ac_prefs->filter_on_recv) {
872                         dropfolder =
873                                 filter_get_dest_folder(prefs_common.fltlist, file);
874                         if (!dropfolder) dropfolder = inbox;
875                         else if (!strcmp(dropfolder->path, FILTER_NOT_RECEIVE)) {
876                                 g_warning(_("a message won't be received\n"));
877                                 return 1;
878                         }
879                 } else
880                         dropfolder = inbox;
881         } else {
882                 /* new filtering */
883                 dropfolder = inbox;
884         }
885
886         val = GPOINTER_TO_INT(g_hash_table_lookup
887                               (state->folder_table, dropfolder));
888         if (val == 0) {
889                 folder_item_scan(dropfolder);
890                 g_hash_table_insert(state->folder_table, dropfolder,
891                                     GINT_TO_POINTER(1));
892         }
893
894         if (prefs_filtering == NULL || !state->ac_prefs->filter_on_recv) {
895                 if ((msgnum = folder_item_add_msg(dropfolder, file, TRUE)) < 0) {
896                         unlink(file);
897                         return -1;
898                 }
899         }
900         else {
901                 filter_incoming_message(dropfolder, file, state->folder_table);
902         }               
903
904         return 0;
905 }
906
907 static void inc_put_error(IncState istate)
908 {
909         switch (istate) {
910         case INC_ERROR:
911                 if(!prefs_common.noerrorpanel) {
912                         alertpanel_error(_("Error occurred while processing mail."));
913                 }
914                 break;
915         case INC_NOSPACE:
916                 alertpanel_error(_("No disk space left."));
917                 break;
918         default:
919                 break;
920         }
921 }
922
923 static void inc_cancel(GtkWidget *widget, gpointer data)
924 {
925         IncProgressDialog *dialog = data;
926         IncSession *session = dialog->queue_list->data;
927         SockInfo *sockinfo = session->pop3_state->sockinfo;
928
929 #if USE_THREADS
930         if (sockinfo->state == CONN_READY ||
931             sockinfo->state == CONN_LOOKUPSUCCESS) {
932                 pthread_cancel(sockinfo->connect_thr);
933                 /* pthread_kill(sockinfo->connect_thr, SIGINT); */
934                 g_print("connection was cancelled.\n");
935         }
936 #endif
937
938         session->pop3_state->inc_state = INC_CANCEL;
939         pop3_automaton_terminate(sockinfo, session->atm);
940 }
941
942 static gint inc_spool(void)
943 {
944         gchar *mbox, *logname;
945         gint msgs;
946
947         logname = g_get_user_name();
948         mbox = g_strconcat(prefs_common.spool_path
949                            ? prefs_common.spool_path : DEFAULT_SPOOL_PATH,
950                            G_DIR_SEPARATOR_S, logname, NULL);
951         msgs = get_spool(folder_get_default_inbox(), mbox);
952         g_free(mbox);
953
954         return msgs;
955 }
956
957 static void inc_spool_account(PrefsAccount *account)
958 {
959         FolderItem *inbox;
960         FolderItem *dropfolder;
961         gint val;
962
963         if (account->inbox) {
964                 inbox = folder_find_item_from_path(account->inbox);
965                 if (!inbox)
966                         inbox = folder_get_default_inbox();
967         } else
968                 inbox = folder_get_default_inbox();
969
970         get_spool(inbox, account->local_mbox);
971 }
972
973 static void inc_all_spool(void)
974 {
975         GList *list = NULL;
976
977         list = account_get_list();
978         if (!list) return;
979
980         for (; list != NULL; list = list->next) {
981                 IncSession *session;
982                 PrefsAccount *account = list->data;
983
984                 if (account->protocol == A_LOCAL)
985                         inc_spool_account(account);
986         }
987 }
988
989 static gint get_spool(FolderItem *dest, const gchar *mbox)
990 {
991         gint msgs, size;
992         gint lockfd;
993         gchar tmp_mbox[MAXPATHLEN + 1];
994         GHashTable *folder_table = NULL;
995
996         g_return_val_if_fail(dest != NULL, -1);
997         g_return_val_if_fail(mbox != NULL, -1);
998
999         if (!is_file_exist(mbox) || (size = get_file_size(mbox)) == 0) {
1000                 debug_print(_("no messages in local mailbox.\n"));
1001                 return 0;
1002         } else if (size < 0)
1003                 return -1;
1004
1005         if ((lockfd = lock_mbox(mbox, LOCK_FLOCK)) < 0)
1006                 return -1;
1007
1008         g_snprintf(tmp_mbox, sizeof(tmp_mbox), "%s%ctmpmbox%d",
1009                    get_rc_dir(), G_DIR_SEPARATOR, (gint)mbox);
1010
1011         if (copy_mbox(mbox, tmp_mbox) < 0)
1012                 return -1;
1013
1014         debug_print(_("Getting new messages from %s into %s...\n"),
1015                     mbox, dest->path);
1016
1017         if (prefs_common.filter_on_inc)
1018                 folder_table = g_hash_table_new(NULL, NULL);
1019         msgs = proc_mbox(dest, tmp_mbox, folder_table);
1020
1021         unlink(tmp_mbox);
1022         if (msgs >= 0) empty_mbox(mbox);
1023         unlock_mbox(mbox, lockfd, LOCK_FLOCK);
1024
1025         if (folder_table) {
1026                 g_hash_table_insert(folder_table, dest,
1027                                     GINT_TO_POINTER(1));
1028                 folder_item_scan_foreach(folder_table);
1029                 folderview_update_item_foreach(folder_table);
1030                 g_hash_table_destroy(folder_table);
1031         } else {
1032                 folder_item_scan(dest);
1033                 folderview_update_item(dest, FALSE);
1034         }
1035
1036         return msgs;
1037 }
1038
1039 static guint autocheck_timer = 0;
1040 static gpointer autocheck_data = NULL;
1041
1042 void inc_autocheck_timer_init(MainWindow *mainwin)
1043 {
1044         autocheck_data = mainwin;
1045         inc_autocheck_timer_set();
1046 }
1047
1048 void inc_autocheck_timer_set(void)
1049 {
1050         inc_autocheck_timer_remove();
1051
1052         if (prefs_common.autochk_newmail && autocheck_data) {
1053                 autocheck_timer = gtk_timeout_add
1054                         (prefs_common.autochk_itv * 60000,
1055                          inc_autocheck_func,
1056                          autocheck_data);
1057         }
1058 }
1059
1060 void inc_autocheck_timer_remove(void)
1061 {
1062         if (autocheck_timer) {
1063                 gtk_timeout_remove(autocheck_timer);
1064                 autocheck_timer = 0;
1065         }
1066 }
1067
1068 static gint inc_autocheck_func(gpointer data)
1069 {
1070         MainWindow *mainwin = (MainWindow *)data;
1071
1072         inc_all_account_mail(mainwin);
1073
1074         return FALSE;
1075 }