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