Fix build
[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 #include "claws_io.h"
60
61 #define MESSAGEBUFSIZE  8192
62
63 #ifdef HAVE_FGETS_UNLOCKED
64 #define SC_FGETS fgets_unlocked
65 #define SC_FPUTS fputs_unlocked
66 #define SC_FPUTC fputc_unlocked
67 #else
68 #define SC_FGETS fgets
69 #define SC_FPUTS fputs
70 #define SC_FPUTC fputc
71 #endif
72
73 #define FPUTS_TO_TMP_ABORT_IF_FAIL(s) \
74 { \
75         lines++; \
76         if (fputs(s, tmp_fp) == EOF) { \
77                 g_warning("can't write to temporary file"); \
78                 fclose(tmp_fp); \
79                 fclose(mbox_fp); \
80                 claws_unlink(tmp_file); \
81                 g_free(tmp_file); \
82                 return -1; \
83         } \
84 }
85
86 gint proc_mbox(FolderItem *dest, const gchar *mbox, gboolean apply_filter,
87                PrefsAccount *account)
88 /* return values: -1 error, >=0 number of msgs added */
89 {
90         FILE *mbox_fp;
91         gchar buf[MESSAGEBUFSIZE];
92         gchar *tmp_file;
93         gint msgs = 0;
94         gint lines;
95         MsgInfo *msginfo;
96         gboolean more;
97         GSList *to_filter = NULL, *filtered = NULL, *unfiltered = NULL, *cur, *to_add = NULL;
98         gboolean printed = FALSE;
99         FolderItem *dropfolder;
100
101         cm_return_val_if_fail(dest != NULL, -1);
102         cm_return_val_if_fail(mbox != NULL, -1);
103
104         debug_print("Getting messages from %s into %s...\n", mbox, dest->path);
105
106         if ((mbox_fp = g_fopen(mbox, "rb")) == NULL) {
107                 FILE_OP_ERROR(mbox, "fopen");
108                 alertpanel_error(_("Could not open mbox file:\n%s\n"), mbox);
109                 return -1;
110         }
111
112         /* ignore empty lines on the head */
113         do {
114                 if (fgets(buf, sizeof(buf), mbox_fp) == NULL) {
115                         g_warning("can't read mbox file.");
116                         fclose(mbox_fp);
117                         return -1;
118                 }
119         } while (buf[0] == '\n' || buf[0] == '\r');
120
121         if (strncmp(buf, "From ", 5) != 0) {
122                 g_warning("invalid mbox format: %s", mbox);
123                 fclose(mbox_fp);
124                 return -1;
125         }
126
127         tmp_file = get_tmp_file();
128
129         folder_item_update_freeze();
130
131         if (apply_filter)
132                 dropfolder = folder_get_default_processing(account->account_id);
133         else
134                 dropfolder = dest;
135         
136         do {
137                 FILE *tmp_fp;
138                 gint empty_lines;
139                 gint msgnum;
140                 
141                 if (msgs > 0 && msgs%500 == 0) {
142                         if (printed)
143                                 statusbar_pop_all();
144                         statusbar_print_all(
145                                         ngettext("Importing from mbox... (%d mail imported)",
146                                                 "Importing from mbox... (%d mails imported)", msgs), msgs);
147                         printed=TRUE;
148                         GTK_EVENTS_FLUSH();
149                 }
150         
151                 if ((tmp_fp = g_fopen(tmp_file, "wb")) == NULL) {
152                         FILE_OP_ERROR(tmp_file, "fopen");
153                         g_warning("can't open temporary file");
154                         fclose(mbox_fp);
155                         g_free(tmp_file);
156                         return -1;
157                 }
158                 if (change_file_mode_rw(tmp_fp, tmp_file) < 0) {
159                         FILE_OP_ERROR(tmp_file, "chmod");
160                 }
161
162                 empty_lines = 0;
163                 lines = 0;
164
165                 /* process all lines from mboxrc file */
166                 while (fgets(buf, sizeof(buf), mbox_fp) != NULL) {
167                         int offset;
168
169                         /* eat empty lines */
170                         if (buf[0] == '\n' || buf[0] == '\r') {
171                                 empty_lines++;
172                                 continue;
173                         }
174
175                         /* From separator or quoted From */
176                         offset = 0;
177                         /* detect leading '>' char(s) */
178                         while (buf[offset] == '>') {
179                                 offset++;
180                         }
181                         if (!strncmp(buf+offset, "From ", 5)) {
182                                 /* From separator: */
183                                 if (offset == 0) {
184                                         /* expect next mbox item */
185                                         break;
186                                 }
187
188                                 /* quoted From: */
189                                 /* flush any eaten empty line */
190                                 if (empty_lines > 0) {
191                                         while (empty_lines-- > 0) {
192                                                 FPUTS_TO_TMP_ABORT_IF_FAIL("\n");
193                                 }
194                                         empty_lines = 0;
195                                 }
196                                 /* store the unquoted line */
197                                 FPUTS_TO_TMP_ABORT_IF_FAIL(buf + 1);
198                                 continue;
199                         }
200
201                         /* other line */
202                         /* flush any eaten empty line */
203                         if (empty_lines > 0) {                  
204                                 while (empty_lines-- > 0) {
205                                         FPUTS_TO_TMP_ABORT_IF_FAIL("\n");
206                         }
207                                 empty_lines = 0;
208                         }
209                         /* store the line itself */
210                                         FPUTS_TO_TMP_ABORT_IF_FAIL(buf);
211                 }
212                 /* end of mbox item or end of mbox */
213
214                 /* flush any eaten empty line (but the last one) */
215                 if (empty_lines > 0) {
216                         while (--empty_lines > 0) {
217                                 FPUTS_TO_TMP_ABORT_IF_FAIL("\n");
218                         }
219                 }
220
221                 /* more emails to expect? */
222                 more = !feof(mbox_fp);
223
224                 /* warn if email part is empty (it's the minimum check 
225                    we can do */
226                 if (lines == 0) {
227                         g_warning("malformed mbox: %s: message %d is empty", mbox, msgs);
228                         fclose(tmp_fp);
229                         fclose(mbox_fp);
230                         claws_unlink(tmp_file);
231                         return -1;
232                 }
233
234                 if (safe_fclose(tmp_fp) == EOF) {
235                         FILE_OP_ERROR(tmp_file, "fclose");
236                         g_warning("can't write to temporary file");
237                         fclose(mbox_fp);
238                         claws_unlink(tmp_file);
239                         g_free(tmp_file);
240                         return -1;
241                 }
242
243                 if (apply_filter) {
244                         if ((msgnum = folder_item_add_msg(dropfolder, tmp_file, NULL, TRUE)) < 0) {
245                                 fclose(mbox_fp);
246                                 claws_unlink(tmp_file);
247                                 g_free(tmp_file);
248                                 return -1;
249                         }
250                         msginfo = folder_item_get_msginfo(dropfolder, msgnum);
251                         to_filter = g_slist_prepend(to_filter, msginfo);
252                 } else {
253                         MsgFileInfo *finfo = g_new0(MsgFileInfo, 1);
254                         finfo->file = tmp_file;
255                         
256                         to_add = g_slist_prepend(to_add, finfo);
257                         tmp_file = get_tmp_file();
258                         
259                         /* flush every 500 */
260                         if (msgs > 0 && msgs % 500 == 0) {
261                                 folder_item_add_msgs(dropfolder, to_add, TRUE);
262                                 procmsg_message_file_list_free(to_add);
263                                 to_add = NULL;
264                         }
265                 }
266                 msgs++;
267         } while (more);
268
269         if (printed)
270                 statusbar_pop_all();
271
272         if (apply_filter) {
273
274                 folder_item_set_batch(dropfolder, FALSE);
275                 procmsg_msglist_filter(to_filter, account, 
276                                 &filtered, &unfiltered, TRUE);
277                 folder_item_set_batch(dropfolder, TRUE);
278
279                 filtering_move_and_copy_msgs(to_filter);
280                 for (cur = filtered; cur; cur = g_slist_next(cur)) {
281                         MsgInfo *info = (MsgInfo *)cur->data;
282                         procmsg_msginfo_free(&info);
283                 }
284
285                 unfiltered = g_slist_reverse(unfiltered);
286                 if (unfiltered) {
287                         folder_item_move_msgs(dest, unfiltered);
288                         for (cur = unfiltered; cur; cur = g_slist_next(cur)) {
289                                 MsgInfo *info = (MsgInfo *)cur->data;
290                                 procmsg_msginfo_free(&info);
291                         }
292                 }
293
294                 g_slist_free(unfiltered);
295                 g_slist_free(filtered);
296                 g_slist_free(to_filter);
297         } else if (to_add) {
298                 folder_item_add_msgs(dropfolder, to_add, TRUE);
299                 procmsg_message_file_list_free(to_add);
300                 to_add = NULL;
301         }
302
303         folder_item_update_thaw();
304         
305         g_free(tmp_file);
306         fclose(mbox_fp);
307         debug_print("%d messages found.\n", msgs);
308
309         return msgs;
310 }
311
312 gint lock_mbox(const gchar *base, LockType type)
313 {
314 #ifdef G_OS_UNIX
315         gint retval = 0;
316
317         if (type == LOCK_FILE) {
318                 gchar *lockfile, *locklink;
319                 gint retry = 0;
320                 FILE *lockfp;
321
322                 lockfile = g_strdup_printf("%s.%d", base, getpid());
323                 if ((lockfp = g_fopen(lockfile, "wb")) == NULL) {
324                         FILE_OP_ERROR(lockfile, "fopen");
325                         g_warning("can't create lock file '%s', use 'flock' instead of 'file' if possible.", lockfile);
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 (safe_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'", 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...");
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", base);
402                         if (close(lockfd) < 0)
403                                 perror("close");
404                         return -1;
405                 }
406                 retval = lockfd;
407         } else {
408                 g_warning("invalid lock type");
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 #if HAVE_FCNTL_H && !defined(G_OS_WIN32)
434                 gboolean fcntled = FALSE;
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", 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");
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");
496         }
497
498         while ((n_read = read(srcfd, buf, sizeof(buf))) > 0) {
499                 if (fwrite(buf, 1, n_read, dest_fp) < n_read) {
500                         g_warning("writing to %s failed.", dest);
501                         fclose(dest_fp);
502                         claws_unlink(dest);
503                         return -1;
504                 }
505         }
506
507         if (save_errno != 0) {
508                 g_warning("error %d reading mbox: %s", save_errno,
509                                 g_strerror(save_errno));
510                 err = TRUE;
511         }
512
513         if (safe_fclose(dest_fp) == EOF) {
514                 FILE_OP_ERROR(dest, "fclose");
515                 err = TRUE;
516         }
517
518         if (err) {
519                 claws_unlink(dest);
520                 return -1;
521         }
522
523         return 0;
524 }
525
526 void empty_mbox(const gchar *mbox)
527 {
528         FILE *fp;
529
530         if ((fp = g_fopen(mbox, "wb")) == NULL) {
531                 FILE_OP_ERROR(mbox, "fopen");
532                 g_warning("can't truncate mailbox to zero.");
533                 return;
534         }
535         safe_fclose(fp);
536 }
537
538 gint export_list_to_mbox(GSList *mlist, const gchar *mbox)
539 /* return values: -2 skipped, -1 error, 0 OK */
540 {
541         GSList *cur;
542         MsgInfo *msginfo;
543         FILE *msg_fp;
544         FILE *mbox_fp;
545         gchar buf[BUFFSIZE];
546         int err = 0;
547
548         gint msgs = 1, total = g_slist_length(mlist);
549         if (g_file_test(mbox, G_FILE_TEST_EXISTS) == TRUE) {
550                 if (alertpanel_full(_("Overwrite mbox file"),
551                                         _("This file already exists. Do you want to overwrite it?"),
552                                         GTK_STOCK_CANCEL, _("Overwrite"), NULL,
553                                         ALERTFOCUS_FIRST, FALSE, NULL, ALERT_WARNING)
554                                 != G_ALERTALTERNATE) {
555                         return -2;
556                 }
557         }
558
559         if ((mbox_fp = g_fopen(mbox, "wb")) == NULL) {
560                 FILE_OP_ERROR(mbox, "fopen");
561                 alertpanel_error(_("Could not create mbox file:\n%s\n"), mbox);
562                 return -1;
563         }
564
565 #ifdef HAVE_FGETS_UNLOCKED
566         flockfile(mbox_fp);
567 #endif
568
569         statusbar_print_all(_("Exporting to mbox..."));
570         for (cur = mlist; cur != NULL; cur = cur->next) {
571                 int len;
572                 gchar buft[BUFFSIZE];
573                 msginfo = (MsgInfo *)cur->data;
574
575                 msg_fp = procmsg_open_message(msginfo);
576                 if (!msg_fp) {
577                         continue;
578                 }
579
580 #ifdef HAVE_FGETS_UNLOCKED
581                 flockfile(msg_fp);
582 #endif
583                 strncpy2(buf,
584                          msginfo->from ? msginfo->from :
585                          cur_account && cur_account->address ?
586                          cur_account->address : "unknown",
587                          sizeof(buf));
588                 extract_address(buf);
589
590                 if (fprintf(mbox_fp, "From %s %s",
591                         buf, ctime_r(&msginfo->date_t, buft)) < 0) {
592                         err = -1;
593 #ifdef HAVE_FGETS_UNLOCKED
594                         funlockfile(msg_fp);
595 #endif
596                         fclose(msg_fp);
597                         goto out;
598                 }
599
600                 buf[0] = '\0';
601                 
602                 /* write email to mboxrc */
603                 while (SC_FGETS(buf, sizeof(buf), msg_fp) != NULL) {
604                         /* quote any From, >From, >>From, etc., according to mbox format specs */
605                         int offset;
606
607                         offset = 0;
608                         /* detect leading '>' char(s) */
609                         while (buf[offset] == '>') {
610                                 offset++;
611                         }
612                         if (!strncmp(buf+offset, "From ", 5)) {
613                                 if (SC_FPUTC('>', mbox_fp) == EOF) {
614                                         err = -1;
615 #ifdef HAVE_FGETS_UNLOCKED
616                                         funlockfile(msg_fp);
617 #endif
618                                         fclose(msg_fp);
619                                         goto out;
620                                 }
621                         }
622                         if (SC_FPUTS(buf, mbox_fp) == EOF) {
623                                 err = -1;
624 #ifdef HAVE_FGETS_UNLOCKED
625                                 funlockfile(msg_fp);
626 #endif
627                                 fclose(msg_fp);
628                                 goto out;
629                         }
630                 }
631
632                 /* force last line to end w/ a newline */
633                 len = strlen(buf);
634                 if (len > 0) {
635                         len--;
636                         if ((buf[len] != '\n') && (buf[len] != '\r')) {
637                                 if (SC_FPUTC('\n', mbox_fp) == EOF) {
638                                         err = -1;
639 #ifdef HAVE_FGETS_UNLOCKED
640                                         funlockfile(msg_fp);
641 #endif
642                                         fclose(msg_fp);
643                                         goto out;
644                                 }
645                         }
646                 }
647
648                 /* add a trailing empty line */
649                 if (SC_FPUTC('\n', mbox_fp) == EOF) {
650                         err = -1;
651 #ifdef HAVE_FGETS_UNLOCKED
652                         funlockfile(msg_fp);
653 #endif
654                         fclose(msg_fp);
655                         goto out;
656                 }
657
658 #ifdef HAVE_FGETS_UNLOCKED
659                 funlockfile(msg_fp);
660 #endif
661                 safe_fclose(msg_fp);
662                 statusbar_progress_all(msgs++,total, 500);
663                 if (msgs%500 == 0)
664                         GTK_EVENTS_FLUSH();
665         }
666
667 out:
668         statusbar_progress_all(0,0,0);
669         statusbar_pop_all();
670
671 #ifdef HAVE_FGETS_UNLOCKED
672         funlockfile(mbox_fp);
673 #endif
674         safe_fclose(mbox_fp);
675
676         return err;
677 }
678
679 /* read all messages in SRC, and store them into one MBOX file. */
680 /* return values: -2 skipped, -1 error, 0 OK */
681 gint export_to_mbox(FolderItem *src, const gchar *mbox)
682 {
683         GSList *mlist;
684         gint ret;
685         
686         cm_return_val_if_fail(src != NULL, -1);
687         cm_return_val_if_fail(src->folder != NULL, -1);
688         cm_return_val_if_fail(mbox != NULL, -1);
689
690         debug_print("Exporting messages from %s into %s...\n",
691                     src->path, mbox);
692
693         mlist = folder_item_get_msg_list(src);
694
695         folder_item_update_freeze();
696         ret = export_list_to_mbox(mlist, mbox);
697         folder_item_update_thaw();
698
699         procmsg_msg_list_free(mlist);
700
701         return ret;
702 }