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