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