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