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