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