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