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