fix bug 3973, ''select all' in summaryview does not automatically focus the summaryview'
[claws.git] / src / mbox.c
1 /*
2  * Claws Mail -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2015 Hiroyuki Yamamoto and the Claws Mail team
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 3 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, see <http://www.gnu.org/licenses/>.
17  *
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #include "claws-features.h"
23 #endif
24
25
26 #define _GNU_SOURCE
27 #include <stdio.h>
28
29 #ifdef USE_PTHREAD
30 #include <pthread.h>
31 #endif
32
33 #include "defs.h"
34 #include <glib.h>
35 #include <glib/gi18n.h>
36 #include <stdlib.h>
37 #include <unistd.h>
38 #include <string.h>
39 #include <fcntl.h>
40 #include <sys/file.h>
41 #include <ctype.h>
42 #include <time.h>
43 #include <errno.h>
44
45 #ifdef G_OS_WIN32
46 #  include <w32lib.h>
47 #endif
48
49 #include "mbox.h"
50 #include "procmsg.h"
51 #include "folder.h"
52 #include "prefs_common.h"
53 #include "prefs_account.h"
54 #include "account.h"
55 #include "utils.h"
56 #include "filtering.h"
57 #include "alertpanel.h"
58 #include "statusbar.h"
59
60 #define MESSAGEBUFSIZE  8192
61
62 #ifdef HAVE_FGETS_UNLOCKED
63 #define SC_FGETS fgets_unlocked
64 #define SC_FPUTS fputs_unlocked
65 #define SC_FPUTC fputc_unlocked
66 #else
67 #define SC_FGETS fgets
68 #define SC_FPUTS fputs
69 #define SC_FPUTC fputc
70 #endif
71
72 #define FPUTS_TO_TMP_ABORT_IF_FAIL(s) \
73 { \
74         lines++; \
75         if (fputs(s, tmp_fp) == EOF) { \
76                 g_warning("can't write to temporary file"); \
77                 fclose(tmp_fp); \
78                 fclose(mbox_fp); \
79                 claws_unlink(tmp_file); \
80                 g_free(tmp_file); \
81                 return -1; \
82         } \
83 }
84
85 gint proc_mbox(FolderItem *dest, const gchar *mbox, gboolean apply_filter,
86                PrefsAccount *account)
87 /* return values: -1 error, >=0 number of msgs added */
88 {
89         FILE *mbox_fp;
90         gchar buf[MESSAGEBUFSIZE];
91         gchar *tmp_file;
92         gint msgs = 0;
93         gint lines;
94         MsgInfo *msginfo;
95         gboolean more;
96         GSList *to_filter = NULL, *filtered = NULL, *unfiltered = NULL, *cur, *to_add = NULL;
97         gboolean printed = FALSE;
98         FolderItem *dropfolder;
99
100         cm_return_val_if_fail(dest != NULL, -1);
101         cm_return_val_if_fail(mbox != NULL, -1);
102
103         debug_print("Getting messages from %s into %s...\n", mbox, dest->path);
104
105         if ((mbox_fp = g_fopen(mbox, "rb")) == NULL) {
106                 FILE_OP_ERROR(mbox, "fopen");
107                 alertpanel_error(_("Could not open mbox file:\n%s\n"), mbox);
108                 return -1;
109         }
110
111         /* ignore empty lines on the head */
112         do {
113                 if (fgets(buf, sizeof(buf), mbox_fp) == NULL) {
114                         g_warning("can't read mbox file.");
115                         fclose(mbox_fp);
116                         return -1;
117                 }
118         } while (buf[0] == '\n' || buf[0] == '\r');
119
120         if (strncmp(buf, "From ", 5) != 0) {
121                 g_warning("invalid mbox format: %s", mbox);
122                 fclose(mbox_fp);
123                 return -1;
124         }
125
126         tmp_file = get_tmp_file();
127
128         folder_item_update_freeze();
129
130         if (apply_filter)
131                 dropfolder = folder_get_default_processing(account->account_id);
132         else
133                 dropfolder = dest;
134         
135         do {
136                 FILE *tmp_fp;
137                 gint empty_lines;
138                 gint msgnum;
139                 
140                 if (msgs > 0 && msgs%500 == 0) {
141                         if (printed)
142                                 statusbar_pop_all();
143                         statusbar_print_all(
144                                         ngettext("Importing from mbox... (%d mail imported)",
145                                                 "Importing from mbox... (%d mails imported)", msgs), msgs);
146                         printed=TRUE;
147                         GTK_EVENTS_FLUSH();
148                 }
149         
150                 if ((tmp_fp = g_fopen(tmp_file, "wb")) == NULL) {
151                         FILE_OP_ERROR(tmp_file, "fopen");
152                         g_warning("can't open temporary file");
153                         fclose(mbox_fp);
154                         g_free(tmp_file);
155                         return -1;
156                 }
157                 if (change_file_mode_rw(tmp_fp, tmp_file) < 0) {
158                         FILE_OP_ERROR(tmp_file, "chmod");
159                 }
160
161                 empty_lines = 0;
162                 lines = 0;
163
164                 /* process all lines from mboxrc file */
165                 while (fgets(buf, sizeof(buf), mbox_fp) != NULL) {
166                         int offset;
167
168                         /* eat empty lines */
169                         if (buf[0] == '\n' || buf[0] == '\r') {
170                                 empty_lines++;
171                                 continue;
172                         }
173
174                         /* From separator or quoted From */
175                         offset = 0;
176                         /* detect leading '>' char(s) */
177                         while ((buf[offset] == '>')) {
178                                 offset++;
179                         }
180                         if (!strncmp(buf+offset, "From ", 5)) {
181                                 /* From separator: */
182                                 if (offset == 0) {
183                                         /* expect next mbox item */
184                                         break;
185                                 }
186
187                                 /* quoted From: */
188                                 /* flush any eaten empty line */
189                                 if (empty_lines > 0) {
190                                         while (empty_lines-- > 0) {
191                                                 FPUTS_TO_TMP_ABORT_IF_FAIL("\n");
192                                 }
193                                         empty_lines = 0;
194                                 }
195                                 /* store the unquoted line */
196                                 FPUTS_TO_TMP_ABORT_IF_FAIL(buf + 1);
197                                 continue;
198                         }
199
200                         /* other line */
201                         /* flush any eaten empty line */
202                         if (empty_lines > 0) {                  
203                                 while (empty_lines-- > 0) {
204                                         FPUTS_TO_TMP_ABORT_IF_FAIL("\n");
205                         }
206                                 empty_lines = 0;
207                         }
208                         /* store the line itself */
209                                         FPUTS_TO_TMP_ABORT_IF_FAIL(buf);
210                 }
211                 /* end of mbox item or end of mbox */
212
213                 /* flush any eaten empty line (but the last one) */
214                 if (empty_lines > 0) {
215                         while (--empty_lines > 0) {
216                                 FPUTS_TO_TMP_ABORT_IF_FAIL("\n");
217                         }
218                 }
219
220                 /* more emails to expect? */
221                 more = !feof(mbox_fp);
222
223                 /* warn if email part is empty (it's the minimum check 
224                    we can do */
225                 if (lines == 0) {
226                         g_warning("malformed mbox: %s: message %d is empty", mbox, msgs);
227                         fclose(tmp_fp);
228                         fclose(mbox_fp);
229                         claws_unlink(tmp_file);
230                         return -1;
231                 }
232
233                 if (fclose(tmp_fp) == EOF) {
234                         FILE_OP_ERROR(tmp_file, "fclose");
235                         g_warning("can't write to temporary file");
236                         fclose(mbox_fp);
237                         claws_unlink(tmp_file);
238                         g_free(tmp_file);
239                         return -1;
240                 }
241
242                 if (apply_filter) {
243                         if ((msgnum = folder_item_add_msg(dropfolder, tmp_file, NULL, TRUE)) < 0) {
244                                 fclose(mbox_fp);
245                                 claws_unlink(tmp_file);
246                                 g_free(tmp_file);
247                                 return -1;
248                         }
249                         msginfo = folder_item_get_msginfo(dropfolder, msgnum);
250                         to_filter = g_slist_prepend(to_filter, msginfo);
251                 } else {
252                         MsgFileInfo *finfo = g_new0(MsgFileInfo, 1);
253                         finfo->file = tmp_file;
254                         
255                         to_add = g_slist_prepend(to_add, finfo);
256                         tmp_file = get_tmp_file();
257                         
258                         /* flush every 500 */
259                         if (msgs > 0 && msgs % 500 == 0) {
260                                 folder_item_add_msgs(dropfolder, to_add, TRUE);
261                                 procmsg_message_file_list_free(to_add);
262                                 to_add = NULL;
263                         }
264                 }
265                 msgs++;
266         } while (more);
267
268         if (printed)
269                 statusbar_pop_all();
270
271         if (apply_filter) {
272
273                 folder_item_set_batch(dropfolder, FALSE);
274                 procmsg_msglist_filter(to_filter, account, 
275                                 &filtered, &unfiltered, TRUE);
276                 folder_item_set_batch(dropfolder, TRUE);
277
278                 filtering_move_and_copy_msgs(to_filter);
279                 for (cur = filtered; cur; cur = g_slist_next(cur)) {
280                         MsgInfo *info = (MsgInfo *)cur->data;
281                         procmsg_msginfo_free(&info);
282                 }
283
284                 unfiltered = g_slist_reverse(unfiltered);
285                 if (unfiltered) {
286                         folder_item_move_msgs(dest, unfiltered);
287                         for (cur = unfiltered; cur; cur = g_slist_next(cur)) {
288                                 MsgInfo *info = (MsgInfo *)cur->data;
289                                 procmsg_msginfo_free(&info);
290                         }
291                 }
292
293                 g_slist_free(unfiltered);
294                 g_slist_free(filtered);
295                 g_slist_free(to_filter);
296         } else if (to_add) {
297                 folder_item_add_msgs(dropfolder, to_add, TRUE);
298                 procmsg_message_file_list_free(to_add);
299                 to_add = NULL;
300         }
301
302         folder_item_update_thaw();
303         
304         g_free(tmp_file);
305         fclose(mbox_fp);
306         debug_print("%d messages found.\n", msgs);
307
308         return msgs;
309 }
310
311 gint lock_mbox(const gchar *base, LockType type)
312 {
313 #ifdef G_OS_UNIX
314         gint retval = 0;
315
316         if (type == LOCK_FILE) {
317                 gchar *lockfile, *locklink;
318                 gint retry = 0;
319                 FILE *lockfp;
320
321                 lockfile = g_strdup_printf("%s.%d", base, getpid());
322                 if ((lockfp = g_fopen(lockfile, "wb")) == NULL) {
323                         FILE_OP_ERROR(lockfile, "fopen");
324                         g_warning("can't create lock file '%s', use 'flock' instead of 'file' if possible.", lockfile);
325                         g_free(lockfile);
326                         return -1;
327                 }
328
329                 if (fprintf(lockfp, "%d\n", getpid()) < 0) {
330                         FILE_OP_ERROR(lockfile, "fprintf");
331                         g_free(lockfile);
332                         fclose(lockfp);
333                         return -1;
334                 }
335
336                 if (fclose(lockfp) == EOF) {
337                         FILE_OP_ERROR(lockfile, "fclose");
338                         g_free(lockfile);
339                         return -1;
340                 }
341
342                 locklink = g_strconcat(base, ".lock", NULL);
343                 while (link(lockfile, locklink) < 0) {
344                         FILE_OP_ERROR(lockfile, "link");
345                         if (retry >= 5) {
346                                 g_warning("can't create '%s'", lockfile);
347                                 claws_unlink(lockfile);
348                                 g_free(lockfile);
349                                 return -1;
350                         }
351                         if (retry == 0)
352                                 g_warning("mailbox is owned by another"
353                                           " process, waiting...");
354                         retry++;
355                         sleep(5);
356                 }
357                 claws_unlink(lockfile);
358                 g_free(lockfile);
359         } else if (type == LOCK_FLOCK) {
360                 gint lockfd;
361                 gboolean fcntled = FALSE;
362 #if HAVE_FCNTL_H && !defined(G_OS_WIN32)
363                 struct flock fl;
364                 fl.l_type = F_WRLCK;
365                 fl.l_whence = SEEK_SET;
366                 fl.l_start = 0;
367                 fl.l_len = 0;
368 #endif
369
370 #if HAVE_FLOCK
371                 if ((lockfd = g_open(base, O_RDWR, 0)) < 0) {
372 #else
373                 if ((lockfd = g_open(base, O_RDWR, 0)) < 0) {
374 #endif
375                         FILE_OP_ERROR(base, "open");
376                         return -1;
377                 }
378                 
379 #if HAVE_FCNTL_H && !defined(G_OS_WIN32)
380                 if (fcntl(lockfd, F_SETLK, &fl) == -1) {
381                         g_warning("can't fnctl %s (%s)", base, g_strerror(errno));
382                         close(lockfd);
383                         return -1;
384                 } else {
385                         fcntled = TRUE;
386                 }
387 #endif
388
389 #if HAVE_FLOCK
390                 if (flock(lockfd, LOCK_EX|LOCK_NB) < 0 && !fcntled) {
391                         perror("flock");
392 #else
393 #if HAVE_LOCKF
394                 if (lockf(lockfd, F_TLOCK, 0) < 0 && !fcntled) {
395                         perror("lockf");
396 #else
397                 {
398 #endif
399 #endif /* HAVE_FLOCK */
400                         g_warning("can't lock %s", base);
401                         if (close(lockfd) < 0)
402                                 perror("close");
403                         return -1;
404                 }
405                 retval = lockfd;
406         } else {
407                 g_warning("invalid lock type");
408                 return -1;
409         }
410
411         return retval;
412 #else
413         return -1;
414 #endif /* G_OS_UNIX */
415 }
416
417 gint unlock_mbox(const gchar *base, gint fd, LockType type)
418 {
419         if (type == LOCK_FILE) {
420                 gchar *lockfile;
421
422                 lockfile = g_strconcat(base, ".lock", NULL);
423                 if (claws_unlink(lockfile) < 0) {
424                         FILE_OP_ERROR(lockfile, "unlink");
425                         g_free(lockfile);
426                         return -1;
427                 }
428                 g_free(lockfile);
429
430                 return 0;
431         } else if (type == LOCK_FLOCK) {
432 #if HAVE_FCNTL_H && !defined(G_OS_WIN32)
433                 gboolean fcntled = FALSE;
434                 struct flock fl;
435                 fl.l_type = F_UNLCK;
436                 fl.l_whence = SEEK_SET;
437                 fl.l_start = 0;
438                 fl.l_len = 0;
439
440                 if (fcntl(fd, F_SETLK, &fl) == -1) {
441                         g_warning("can't fnctl %s", base);
442                 } else {
443                         fcntled = TRUE;
444                 }
445 #endif
446 #if HAVE_FLOCK
447                 if (flock(fd, LOCK_UN) < 0 && !fcntled) {
448                         perror("flock");
449 #else
450 #if HAVE_LOCKF
451                 if (lockf(fd, F_ULOCK, 0) < 0 && !fcntled) {
452                         perror("lockf");
453 #else
454                 {
455 #endif
456 #endif /* HAVE_FLOCK */
457                         g_warning("can't unlock %s", base);
458                         if (close(fd) < 0)
459                                 perror("close");
460                         return -1;
461                 }
462
463                 if (close(fd) < 0) {
464                         perror("close");
465                         return -1;
466                 }
467
468                 return 0;
469         }
470
471         g_warning("invalid lock type");
472         return -1;
473 }
474
475 gint copy_mbox(gint srcfd, const gchar *dest)
476 {
477         FILE *dest_fp;
478         ssize_t n_read;
479         gchar buf[BUFSIZ];
480         gboolean err = FALSE;
481         int save_errno = 0;
482
483         if (srcfd < 0) {
484                 return -1;
485         }
486
487         if ((dest_fp = g_fopen(dest, "wb")) == NULL) {
488                 FILE_OP_ERROR(dest, "fopen");
489                 return -1;
490         }
491
492         if (change_file_mode_rw(dest_fp, dest) < 0) {
493                 FILE_OP_ERROR(dest, "chmod");
494                 g_warning("can't change file mode");
495         }
496
497         while ((n_read = read(srcfd, buf, sizeof(buf))) > 0) {
498                 if (fwrite(buf, 1, n_read, dest_fp) < n_read) {
499                         g_warning("writing to %s failed.", dest);
500                         fclose(dest_fp);
501                         claws_unlink(dest);
502                         return -1;
503                 }
504         }
505
506         if (save_errno != 0) {
507                 g_warning("error %d reading mbox: %s", save_errno,
508                                 g_strerror(save_errno));
509                 err = TRUE;
510         }
511
512         if (fclose(dest_fp) == EOF) {
513                 FILE_OP_ERROR(dest, "fclose");
514                 err = TRUE;
515         }
516
517         if (err) {
518                 claws_unlink(dest);
519                 return -1;
520         }
521
522         return 0;
523 }
524
525 void empty_mbox(const gchar *mbox)
526 {
527         FILE *fp;
528
529         if ((fp = g_fopen(mbox, "wb")) == NULL) {
530                 FILE_OP_ERROR(mbox, "fopen");
531                 g_warning("can't truncate mailbox to zero.");
532                 return;
533         }
534         fclose(fp);
535 }
536
537 gint export_list_to_mbox(GSList *mlist, const gchar *mbox)
538 /* return values: -2 skipped, -1 error, 0 OK */
539 {
540         GSList *cur;
541         MsgInfo *msginfo;
542         FILE *msg_fp;
543         FILE *mbox_fp;
544         gchar buf[BUFFSIZE];
545         int err = 0;
546
547         gint msgs = 1, total = g_slist_length(mlist);
548         if (g_file_test(mbox, G_FILE_TEST_EXISTS) == TRUE) {
549                 if (alertpanel_full(_("Overwrite mbox file"),
550                                         _("This file already exists. Do you want to overwrite it?"),
551                                         GTK_STOCK_CANCEL, _("Overwrite"), NULL,
552                                         ALERTFOCUS_FIRST, FALSE, NULL, ALERT_WARNING)
553                                 != G_ALERTALTERNATE) {
554                         return -2;
555                 }
556         }
557
558         if ((mbox_fp = g_fopen(mbox, "wb")) == NULL) {
559                 FILE_OP_ERROR(mbox, "fopen");
560                 alertpanel_error(_("Could not create mbox file:\n%s\n"), mbox);
561                 return -1;
562         }
563
564 #ifdef HAVE_FGETS_UNLOCKED
565         flockfile(mbox_fp);
566 #endif
567
568         statusbar_print_all(_("Exporting to mbox..."));
569         for (cur = mlist; cur != NULL; cur = cur->next) {
570                 int len;
571                 gchar buft[BUFFSIZE];
572                 msginfo = (MsgInfo *)cur->data;
573
574                 msg_fp = procmsg_open_message(msginfo);
575                 if (!msg_fp) {
576                         continue;
577                 }
578
579 #ifdef HAVE_FGETS_UNLOCKED
580                 flockfile(msg_fp);
581 #endif
582                 strncpy2(buf,
583                          msginfo->from ? msginfo->from :
584                          cur_account && cur_account->address ?
585                          cur_account->address : "unknown",
586                          sizeof(buf));
587                 extract_address(buf);
588
589                 if (fprintf(mbox_fp, "From %s %s",
590                         buf, ctime_r(&msginfo->date_t, buft)) < 0) {
591                         err = -1;
592 #ifdef HAVE_FGETS_UNLOCKED
593                         funlockfile(msg_fp);
594 #endif
595                         fclose(msg_fp);
596                         goto out;
597                 }
598
599                 buf[0] = '\0';
600                 
601                 /* write email to mboxrc */
602                 while (SC_FGETS(buf, sizeof(buf), msg_fp) != NULL) {
603                         /* quote any From, >From, >>From, etc., according to mbox format specs */
604                         int offset;
605
606                         offset = 0;
607                         /* detect leading '>' char(s) */
608                         while ((buf[offset] == '>')) {
609                                 offset++;
610                         }
611                         if (!strncmp(buf+offset, "From ", 5)) {
612                                 if (SC_FPUTC('>', mbox_fp) == EOF) {
613                                         err = -1;
614 #ifdef HAVE_FGETS_UNLOCKED
615                                         funlockfile(msg_fp);
616 #endif
617                                         fclose(msg_fp);
618                                         goto out;
619                                 }
620                         }
621                         if (SC_FPUTS(buf, mbox_fp) == EOF) {
622                                 err = -1;
623 #ifdef HAVE_FGETS_UNLOCKED
624                                 funlockfile(msg_fp);
625 #endif
626                                 fclose(msg_fp);
627                                 goto out;
628                         }
629                 }
630
631                 /* force last line to end w/ a newline */
632                 len = strlen(buf);
633                 if (len > 0) {
634                         len--;
635                         if ((buf[len] != '\n') && (buf[len] != '\r')) {
636                                 if (SC_FPUTC('\n', mbox_fp) == EOF) {
637                                         err = -1;
638 #ifdef HAVE_FGETS_UNLOCKED
639                                         funlockfile(msg_fp);
640 #endif
641                                         fclose(msg_fp);
642                                         goto out;
643                                 }
644                         }
645                 }
646
647                 /* add a trailing empty line */
648                 if (SC_FPUTC('\n', mbox_fp) == EOF) {
649                         err = -1;
650 #ifdef HAVE_FGETS_UNLOCKED
651                         funlockfile(msg_fp);
652 #endif
653                         fclose(msg_fp);
654                         goto out;
655                 }
656
657 #ifdef HAVE_FGETS_UNLOCKED
658                 funlockfile(msg_fp);
659 #endif
660                 fclose(msg_fp);
661                 statusbar_progress_all(msgs++,total, 500);
662                 if (msgs%500 == 0)
663                         GTK_EVENTS_FLUSH();
664         }
665
666 out:
667         statusbar_progress_all(0,0,0);
668         statusbar_pop_all();
669
670 #ifdef HAVE_FGETS_UNLOCKED
671         funlockfile(mbox_fp);
672 #endif
673         fclose(mbox_fp);
674
675         return err;
676 }
677
678 /* read all messages in SRC, and store them into one MBOX file. */
679 /* return values: -2 skipped, -1 error, 0 OK */
680 gint export_to_mbox(FolderItem *src, const gchar *mbox)
681 {
682         GSList *mlist;
683         gint ret;
684         
685         cm_return_val_if_fail(src != NULL, -1);
686         cm_return_val_if_fail(src->folder != NULL, -1);
687         cm_return_val_if_fail(mbox != NULL, -1);
688
689         debug_print("Exporting messages from %s into %s...\n",
690                     src->path, mbox);
691
692         mlist = folder_item_get_msg_list(src);
693
694         folder_item_update_freeze();
695         ret = export_list_to_mbox(mlist, mbox);
696         folder_item_update_thaw();
697
698         procmsg_msg_list_free(mlist);
699
700         return ret;
701 }