Switch core from strerror to g_strerror
[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\n"); \
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.\n");
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\n", 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\n");
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\n", 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\n");
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\n", lockfile);
325                         g_warning("use 'flock' instead of 'file' if possible.\n");
326                         g_free(lockfile);
327                         return -1;
328                 }
329
330                 if (fprintf(lockfp, "%d\n", getpid()) < 0) {
331                         FILE_OP_ERROR(lockfile, "fprintf");
332                         g_free(lockfile);
333                         fclose(lockfp);
334                         return -1;
335                 }
336
337                 if (fclose(lockfp) == EOF) {
338                         FILE_OP_ERROR(lockfile, "fclose");
339                         g_free(lockfile);
340                         return -1;
341                 }
342
343                 locklink = g_strconcat(base, ".lock", NULL);
344                 while (link(lockfile, locklink) < 0) {
345                         FILE_OP_ERROR(lockfile, "link");
346                         if (retry >= 5) {
347                                 g_warning("can't create %s\n", lockfile);
348                                 claws_unlink(lockfile);
349                                 g_free(lockfile);
350                                 return -1;
351                         }
352                         if (retry == 0)
353                                 g_warning("mailbox is owned by another"
354                                             " process, waiting...\n");
355                         retry++;
356                         sleep(5);
357                 }
358                 claws_unlink(lockfile);
359                 g_free(lockfile);
360         } else if (type == LOCK_FLOCK) {
361                 gint lockfd;
362                 gboolean fcntled = FALSE;
363 #if HAVE_FCNTL_H && !defined(G_OS_WIN32)
364                 struct flock fl;
365                 fl.l_type = F_WRLCK;
366                 fl.l_whence = SEEK_SET;
367                 fl.l_start = 0;
368                 fl.l_len = 0;
369 #endif
370
371 #if HAVE_FLOCK
372                 if ((lockfd = g_open(base, O_RDWR, 0)) < 0) {
373 #else
374                 if ((lockfd = g_open(base, O_RDWR, 0)) < 0) {
375 #endif
376                         FILE_OP_ERROR(base, "open");
377                         return -1;
378                 }
379                 
380 #if HAVE_FCNTL_H && !defined(G_OS_WIN32)
381                 if (fcntl(lockfd, F_SETLK, &fl) == -1) {
382                         g_warning("can't fnctl %s (%s)", base, g_strerror(errno));
383                         close(lockfd);
384                         return -1;
385                 } else {
386                         fcntled = TRUE;
387                 }
388 #endif
389
390 #if HAVE_FLOCK
391                 if (flock(lockfd, LOCK_EX|LOCK_NB) < 0 && !fcntled) {
392                         perror("flock");
393 #else
394 #if HAVE_LOCKF
395                 if (lockf(lockfd, F_TLOCK, 0) < 0 && !fcntled) {
396                         perror("lockf");
397 #else
398                 {
399 #endif
400 #endif /* HAVE_FLOCK */
401                         g_warning("can't lock %s\n", base);
402                         if (close(lockfd) < 0)
403                                 perror("close");
404                         return -1;
405                 }
406                 retval = lockfd;
407         } else {
408                 g_warning("invalid lock type\n");
409                 return -1;
410         }
411
412         return retval;
413 #else
414         return -1;
415 #endif /* G_OS_UNIX */
416 }
417
418 gint unlock_mbox(const gchar *base, gint fd, LockType type)
419 {
420         if (type == LOCK_FILE) {
421                 gchar *lockfile;
422
423                 lockfile = g_strconcat(base, ".lock", NULL);
424                 if (claws_unlink(lockfile) < 0) {
425                         FILE_OP_ERROR(lockfile, "unlink");
426                         g_free(lockfile);
427                         return -1;
428                 }
429                 g_free(lockfile);
430
431                 return 0;
432         } else if (type == LOCK_FLOCK) {
433                 gboolean fcntled = FALSE;
434 #if HAVE_FCNTL_H && !defined(G_OS_WIN32)
435                 struct flock fl;
436                 fl.l_type = F_UNLCK;
437                 fl.l_whence = SEEK_SET;
438                 fl.l_start = 0;
439                 fl.l_len = 0;
440
441                 if (fcntl(fd, F_SETLK, &fl) == -1) {
442                         g_warning("can't fnctl %s", base);
443                 } else {
444                         fcntled = TRUE;
445                 }
446 #endif
447 #if HAVE_FLOCK
448                 if (flock(fd, LOCK_UN) < 0 && !fcntled) {
449                         perror("flock");
450 #else
451 #if HAVE_LOCKF
452                 if (lockf(fd, F_ULOCK, 0) < 0 && !fcntled) {
453                         perror("lockf");
454 #else
455                 {
456 #endif
457 #endif /* HAVE_FLOCK */
458                         g_warning("can't unlock %s\n", base);
459                         if (close(fd) < 0)
460                                 perror("close");
461                         return -1;
462                 }
463
464                 if (close(fd) < 0) {
465                         perror("close");
466                         return -1;
467                 }
468
469                 return 0;
470         }
471
472         g_warning("invalid lock type\n");
473         return -1;
474 }
475
476 gint copy_mbox(gint srcfd, const gchar *dest)
477 {
478         FILE *dest_fp;
479         ssize_t n_read;
480         gchar buf[BUFSIZ];
481         gboolean err = FALSE;
482         int save_errno = 0;
483
484         if (srcfd < 0) {
485                 return -1;
486         }
487
488         if ((dest_fp = g_fopen(dest, "wb")) == NULL) {
489                 FILE_OP_ERROR(dest, "fopen");
490                 return -1;
491         }
492
493         if (change_file_mode_rw(dest_fp, dest) < 0) {
494                 FILE_OP_ERROR(dest, "chmod");
495                 g_warning("can't change file mode\n");
496         }
497
498         while ((n_read = read(srcfd, buf, sizeof(buf))) > 0) {
499                 if (n_read == -1 && errno != 0) {
500                         save_errno = errno;
501                         break;
502                 }
503                 if (fwrite(buf, 1, n_read, dest_fp) < n_read) {
504                         g_warning("writing to %s failed.\n", dest);
505                         fclose(dest_fp);
506                         claws_unlink(dest);
507                         return -1;
508                 }
509         }
510
511         if (save_errno != 0) {
512                 g_warning("error %d reading mbox: %s\n", save_errno,
513                                 g_strerror(save_errno));
514                 err = TRUE;
515         }
516
517         if (fclose(dest_fp) == EOF) {
518                 FILE_OP_ERROR(dest, "fclose");
519                 err = TRUE;
520         }
521
522         if (err) {
523                 claws_unlink(dest);
524                 return -1;
525         }
526
527         return 0;
528 }
529
530 void empty_mbox(const gchar *mbox)
531 {
532         FILE *fp;
533
534         if ((fp = g_fopen(mbox, "wb")) == NULL) {
535                 FILE_OP_ERROR(mbox, "fopen");
536                 g_warning("can't truncate mailbox to zero.\n");
537                 return;
538         }
539         fclose(fp);
540 }
541
542 gint export_list_to_mbox(GSList *mlist, const gchar *mbox)
543 /* return values: -2 skipped, -1 error, 0 OK */
544 {
545         GSList *cur;
546         MsgInfo *msginfo;
547         FILE *msg_fp;
548         FILE *mbox_fp;
549         gchar buf[BUFFSIZE];
550         int err = 0;
551
552         gint msgs = 1, total = g_slist_length(mlist);
553         if (g_file_test(mbox, G_FILE_TEST_EXISTS) == TRUE) {
554                 if (alertpanel_full(_("Overwrite mbox file"),
555                                         _("This file already exists. Do you want to overwrite it?"),
556                                         GTK_STOCK_CANCEL, _("Overwrite"), NULL, FALSE,
557                                         NULL, ALERT_WARNING, G_ALERTDEFAULT)
558                                 != G_ALERTALTERNATE) {
559                         return -2;
560                 }
561         }
562
563         if ((mbox_fp = g_fopen(mbox, "wb")) == NULL) {
564                 FILE_OP_ERROR(mbox, "fopen");
565                 alertpanel_error(_("Could not create mbox file:\n%s\n"), mbox);
566                 return -1;
567         }
568
569 #ifdef HAVE_FGETS_UNLOCKED
570         flockfile(mbox_fp);
571 #endif
572
573         statuswindow_print_all(_("Exporting to mbox..."));
574         for (cur = mlist; cur != NULL; cur = cur->next) {
575                 int len;
576                 gchar buft[BUFFSIZE];
577                 msginfo = (MsgInfo *)cur->data;
578
579                 msg_fp = procmsg_open_message(msginfo);
580                 if (!msg_fp) {
581                         continue;
582                 }
583
584 #ifdef HAVE_FGETS_UNLOCKED
585                 flockfile(msg_fp);
586 #endif
587                 strncpy2(buf,
588                          msginfo->from ? msginfo->from :
589                          cur_account && cur_account->address ?
590                          cur_account->address : "unknown",
591                          sizeof(buf));
592                 extract_address(buf);
593
594                 if (fprintf(mbox_fp, "From %s %s",
595                         buf, ctime_r(&msginfo->date_t, buft)) < 0) {
596                         err = -1;
597 #ifdef HAVE_FGETS_UNLOCKED
598                         funlockfile(msg_fp);
599 #endif
600                         fclose(msg_fp);
601                         goto out;
602                 }
603
604                 buf[0] = '\0';
605                 
606                 /* write email to mboxrc */
607                 while (SC_FGETS(buf, sizeof(buf), msg_fp) != NULL) {
608                         /* quote any From, >From, >>From, etc., according to mbox format specs */
609                         int offset;
610
611                         offset = 0;
612                         /* detect leading '>' char(s) */
613                         while ((buf[offset] == '>')) {
614                                 offset++;
615                         }
616                         if (!strncmp(buf+offset, "From ", 5)) {
617                                 if (SC_FPUTC('>', mbox_fp) == EOF) {
618                                         err = -1;
619 #ifdef HAVE_FGETS_UNLOCKED
620                                         funlockfile(msg_fp);
621 #endif
622                                         fclose(msg_fp);
623                                         goto out;
624                                 }
625                         }
626                         if (SC_FPUTS(buf, mbox_fp) == EOF) {
627                                 err = -1;
628 #ifdef HAVE_FGETS_UNLOCKED
629                                 funlockfile(msg_fp);
630 #endif
631                                 fclose(msg_fp);
632                                 goto out;
633                         }
634                 }
635
636                 /* force last line to end w/ a newline */
637                 len = strlen(buf);
638                 if (len > 0) {
639                         len--;
640                         if ((buf[len] != '\n') && (buf[len] != '\r')) {
641                                 if (SC_FPUTC('\n', mbox_fp) == EOF) {
642                                         err = -1;
643 #ifdef HAVE_FGETS_UNLOCKED
644                                         funlockfile(msg_fp);
645 #endif
646                                         fclose(msg_fp);
647                                         goto out;
648                                 }
649                         }
650                 }
651
652                 /* add a trailing empty line */
653                 if (SC_FPUTC('\n', mbox_fp) == EOF) {
654                         err = -1;
655 #ifdef HAVE_FGETS_UNLOCKED
656                         funlockfile(msg_fp);
657 #endif
658                         fclose(msg_fp);
659                         goto out;
660                 }
661
662 #ifdef HAVE_FGETS_UNLOCKED
663                 funlockfile(msg_fp);
664 #endif
665                 fclose(msg_fp);
666                 statusbar_progress_all(msgs++,total, 500);
667                 if (msgs%500 == 0)
668                         GTK_EVENTS_FLUSH();
669         }
670
671 out:
672         statusbar_progress_all(0,0,0);
673         statuswindow_pop_all();
674
675 #ifdef HAVE_FGETS_UNLOCKED
676         funlockfile(mbox_fp);
677 #endif
678         fclose(mbox_fp);
679
680         return err;
681 }
682
683 /* read all messages in SRC, and store them into one MBOX file. */
684 /* return values: -2 skipped, -1 error, 0 OK */
685 gint export_to_mbox(FolderItem *src, const gchar *mbox)
686 {
687         GSList *mlist;
688         gint ret;
689         
690         cm_return_val_if_fail(src != NULL, -1);
691         cm_return_val_if_fail(src->folder != NULL, -1);
692         cm_return_val_if_fail(mbox != NULL, -1);
693
694         debug_print("Exporting messages from %s into %s...\n",
695                     src->path, mbox);
696
697         mlist = folder_item_get_msg_list(src);
698
699         folder_item_update_freeze();
700         ret = export_list_to_mbox(mlist, mbox);
701         folder_item_update_thaw();
702
703         procmsg_msg_list_free(mlist);
704
705         return ret;
706 }