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