04f5108910ae4d1be7805046ebbe83630ad31408
[claws.git] / src / mbox.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2012 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, strerror(errno));
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\n", base);
401                         if (close(lockfd) < 0)
402                                 perror("close");
403                         return -1;
404                 }
405                 retval = lockfd;
406         } else {
407                 g_warning("invalid lock type\n");
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                 gboolean fcntled = FALSE;
433 #if HAVE_FCNTL_H && !defined(G_OS_WIN32)
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\n", 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\n");
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\n");
495         }
496
497         while ((n_read = read(srcfd, buf, sizeof(buf))) > 0) {
498                 if (n_read == -1 && errno != 0) {
499                         save_errno = errno;
500                         break;
501                 }
502                 if (fwrite(buf, 1, n_read, dest_fp) < n_read) {
503                         g_warning("writing to %s failed.\n", dest);
504                         fclose(dest_fp);
505                         claws_unlink(dest);
506                         return -1;
507                 }
508         }
509
510         if (save_errno != 0) {
511                 g_warning("error %d reading mbox: %s\n", save_errno,
512                                 strerror(save_errno));
513                 err = TRUE;
514         }
515
516         if (fclose(dest_fp) == EOF) {
517                 FILE_OP_ERROR(dest, "fclose");
518                 err = TRUE;
519         }
520
521         if (err) {
522                 claws_unlink(dest);
523                 return -1;
524         }
525
526         return 0;
527 }
528
529 void empty_mbox(const gchar *mbox)
530 {
531         FILE *fp;
532
533         if ((fp = g_fopen(mbox, "wb")) == NULL) {
534                 FILE_OP_ERROR(mbox, "fopen");
535                 g_warning("can't truncate mailbox to zero.\n");
536                 return;
537         }
538         fclose(fp);
539 }
540
541 gint export_list_to_mbox(GSList *mlist, const gchar *mbox)
542 /* return values: -2 skipped, -1 error, 0 OK */
543 {
544         GSList *cur;
545         MsgInfo *msginfo;
546         FILE *msg_fp;
547         FILE *mbox_fp;
548         gchar buf[BUFFSIZE];
549         int err = 0;
550
551         gint msgs = 1, total = g_slist_length(mlist);
552         if (g_file_test(mbox, G_FILE_TEST_EXISTS) == TRUE) {
553                 if (alertpanel_full(_("Overwrite mbox file"),
554                                         _("This file already exists. Do you want to overwrite it?"),
555                                         GTK_STOCK_CANCEL, _("Overwrite"), NULL, FALSE,
556                                         NULL, ALERT_WARNING, G_ALERTDEFAULT)
557                                 != G_ALERTALTERNATE) {
558                         return -2;
559                 }
560         }
561
562         if ((mbox_fp = g_fopen(mbox, "wb")) == NULL) {
563                 FILE_OP_ERROR(mbox, "fopen");
564                 alertpanel_error(_("Could not create mbox file:\n%s\n"), mbox);
565                 return -1;
566         }
567
568 #ifdef HAVE_FGETS_UNLOCKED
569         flockfile(mbox_fp);
570 #endif
571
572         statuswindow_print_all(_("Exporting to mbox..."));
573         for (cur = mlist; cur != NULL; cur = cur->next) {
574                 int len;
575                 gchar buft[BUFFSIZE];
576                 msginfo = (MsgInfo *)cur->data;
577
578                 msg_fp = procmsg_open_message(msginfo);
579                 if (!msg_fp) {
580                         continue;
581                 }
582
583 #ifdef HAVE_FGETS_UNLOCKED
584                 flockfile(msg_fp);
585 #endif
586                 strncpy2(buf,
587                          msginfo->from ? msginfo->from :
588                          cur_account && cur_account->address ?
589                          cur_account->address : "unknown",
590                          sizeof(buf));
591                 extract_address(buf);
592
593                 if (fprintf(mbox_fp, "From %s %s",
594                         buf, ctime_r(&msginfo->date_t, buft)) < 0) {
595                         err = -1;
596 #ifdef HAVE_FGETS_UNLOCKED
597                         funlockfile(msg_fp);
598 #endif
599                         fclose(msg_fp);
600                         goto out;
601                 }
602
603                 buf[0] = '\0';
604                 
605                 /* write email to mboxrc */
606                 while (SC_FGETS(buf, sizeof(buf), msg_fp) != NULL) {
607                         /* quote any From, >From, >>From, etc., according to mbox format specs */
608                         int offset;
609
610                         offset = 0;
611                         /* detect leading '>' char(s) */
612                         while ((buf[offset] == '>')) {
613                                 offset++;
614                         }
615                         if (!strncmp(buf+offset, "From ", 5)) {
616                                 if (SC_FPUTC('>', mbox_fp) == EOF) {
617                                         err = -1;
618 #ifdef HAVE_FGETS_UNLOCKED
619                                         funlockfile(msg_fp);
620 #endif
621                                         fclose(msg_fp);
622                                         goto out;
623                                 }
624                         }
625                         if (SC_FPUTS(buf, mbox_fp) == EOF) {
626                                 err = -1;
627 #ifdef HAVE_FGETS_UNLOCKED
628                                 funlockfile(msg_fp);
629 #endif
630                                 fclose(msg_fp);
631                                 goto out;
632                         }
633                 }
634
635                 /* force last line to end w/ a newline */
636                 len = strlen(buf);
637                 if (len > 0) {
638                         len--;
639                         if ((buf[len] != '\n') && (buf[len] != '\r')) {
640                                 if (SC_FPUTC('\n', mbox_fp) == EOF) {
641                                         err = -1;
642 #ifdef HAVE_FGETS_UNLOCKED
643                                         funlockfile(msg_fp);
644 #endif
645                                         fclose(msg_fp);
646                                         goto out;
647                                 }
648                         }
649                 }
650
651                 /* add a trailing empty line */
652                 if (SC_FPUTC('\n', mbox_fp) == EOF) {
653                         err = -1;
654 #ifdef HAVE_FGETS_UNLOCKED
655                         funlockfile(msg_fp);
656 #endif
657                         fclose(msg_fp);
658                         goto out;
659                 }
660
661 #ifdef HAVE_FGETS_UNLOCKED
662                 funlockfile(msg_fp);
663 #endif
664                 fclose(msg_fp);
665                 statusbar_progress_all(msgs++,total, 500);
666                 if (msgs%500 == 0)
667                         GTK_EVENTS_FLUSH();
668         }
669
670 out:
671         statusbar_progress_all(0,0,0);
672         statuswindow_pop_all();
673
674 #ifdef HAVE_FGETS_UNLOCKED
675         funlockfile(mbox_fp);
676 #endif
677         fclose(mbox_fp);
678
679         return err;
680 }
681
682 /* read all messages in SRC, and store them into one MBOX file. */
683 /* return values: -2 skipped, -1 error, 0 OK */
684 gint export_to_mbox(FolderItem *src, const gchar *mbox)
685 {
686         GSList *mlist;
687         gint ret;
688         
689         cm_return_val_if_fail(src != NULL, -1);
690         cm_return_val_if_fail(src->folder != NULL, -1);
691         cm_return_val_if_fail(mbox != NULL, -1);
692
693         debug_print("Exporting messages from %s into %s...\n",
694                     src->path, mbox);
695
696         mlist = folder_item_get_msg_list(src);
697
698         folder_item_update_freeze();
699         ret = export_list_to_mbox(mlist, mbox);
700         folder_item_update_thaw();
701
702         procmsg_msg_list_free(mlist);
703
704         return ret;
705 }