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