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