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