2009-08-23 [colin] 3.7.2cvs26
[claws.git] / src / mbox.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2009 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                 claws_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         cm_return_val_if_fail(dest != NULL, -1);
96         cm_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                         claws_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                         claws_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                                 claws_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
270                 folder_item_set_batch(dropfolder, FALSE);
271                 procmsg_msglist_filter(to_filter, account, 
272                                 &filtered, &unfiltered, TRUE);
273                 folder_item_set_batch(dropfolder, TRUE);
274
275                 filtering_move_and_copy_msgs(to_filter);
276                 for (cur = filtered; cur; cur = g_slist_next(cur)) {
277                         MsgInfo *info = (MsgInfo *)cur->data;
278                         procmsg_msginfo_free(info);
279                 }
280
281                 unfiltered = g_slist_reverse(unfiltered);
282                 if (unfiltered) {
283                         folder_item_move_msgs(dest, unfiltered);
284                         for (cur = unfiltered; cur; cur = g_slist_next(cur)) {
285                                 MsgInfo *info = (MsgInfo *)cur->data;
286                                 procmsg_msginfo_free(info);
287                         }
288                 }
289
290                 g_slist_free(unfiltered);
291                 g_slist_free(filtered);
292                 g_slist_free(to_filter);
293         } else if (to_add) {
294                 folder_item_add_msgs(dropfolder, to_add, TRUE);
295                 procmsg_message_file_list_free(to_add);
296                 to_add = NULL;
297         }
298
299         folder_item_update_thaw();
300         
301         g_free(tmp_file);
302         fclose(mbox_fp);
303         debug_print("%d messages found.\n", msgs);
304
305         return msgs;
306 }
307
308 gint lock_mbox(const gchar *base, LockType type)
309 {
310 #ifdef G_OS_UNIX
311         gint retval = 0;
312
313         if (type == LOCK_FILE) {
314                 gchar *lockfile, *locklink;
315                 gint retry = 0;
316                 FILE *lockfp;
317
318                 lockfile = g_strdup_printf("%s.%d", base, getpid());
319                 if ((lockfp = g_fopen(lockfile, "wb")) == NULL) {
320                         FILE_OP_ERROR(lockfile, "fopen");
321                         g_warning("can't create lock file %s\n", lockfile);
322                         g_warning("use 'flock' instead of 'file' if possible.\n");
323                         g_free(lockfile);
324                         return -1;
325                 }
326
327                 if (fprintf(lockfp, "%d\n", getpid()) < 0) {
328                         FILE_OP_ERROR(lockfile, "fprintf");
329                         g_free(lockfile);
330                         fclose(lockfp);
331                         return -1;
332                 }
333
334                 if (fclose(lockfp) == EOF) {
335                         FILE_OP_ERROR(lockfile, "fclose");
336                         g_free(lockfile);
337                         return -1;
338                 }
339
340                 locklink = g_strconcat(base, ".lock", NULL);
341                 while (link(lockfile, locklink) < 0) {
342                         FILE_OP_ERROR(lockfile, "link");
343                         if (retry >= 5) {
344                                 g_warning("can't create %s\n", lockfile);
345                                 claws_unlink(lockfile);
346                                 g_free(lockfile);
347                                 return -1;
348                         }
349                         if (retry == 0)
350                                 g_warning("mailbox is owned by another"
351                                             " process, waiting...\n");
352                         retry++;
353                         sleep(5);
354                 }
355                 claws_unlink(lockfile);
356                 g_free(lockfile);
357         } else if (type == LOCK_FLOCK) {
358                 gint lockfd;
359                 gboolean fcntled = FALSE;
360 #if HAVE_FCNTL_H && !defined(G_OS_WIN32)
361                 struct flock fl;
362                 fl.l_type = F_WRLCK;
363                 fl.l_whence = SEEK_SET;
364                 fl.l_start = 0;
365                 fl.l_len = 0;
366 #endif
367
368 #if HAVE_FLOCK
369                 if ((lockfd = g_open(base, O_RDWR, 0)) < 0) {
370 #else
371                 if ((lockfd = g_open(base, O_RDWR, 0)) < 0) {
372 #endif
373                         FILE_OP_ERROR(base, "open");
374                         return -1;
375                 }
376                 
377 #if HAVE_FCNTL_H && !defined(G_OS_WIN32)
378                 if (fcntl(lockfd, F_SETLK, &fl) == -1) {
379                         g_warning("can't fnctl %s (%s)", base, strerror(errno));
380                         return -1;
381                 } else {
382                         fcntled = TRUE;
383                 }
384 #endif
385
386 #if HAVE_FLOCK
387                 if (flock(lockfd, LOCK_EX|LOCK_NB) < 0 && !fcntled) {
388                         perror("flock");
389 #else
390 #if HAVE_LOCKF
391                 if (lockf(lockfd, F_TLOCK, 0) < 0 && !fcntled) {
392                         perror("lockf");
393 #else
394                 {
395 #endif
396 #endif /* HAVE_FLOCK */
397                         g_warning("can't lock %s\n", base);
398                         if (close(lockfd) < 0)
399                                 perror("close");
400                         return -1;
401                 }
402                 retval = lockfd;
403         } else {
404                 g_warning("invalid lock type\n");
405                 return -1;
406         }
407
408         return retval;
409 #else
410         return -1;
411 #endif /* G_OS_UNIX */
412 }
413
414 gint unlock_mbox(const gchar *base, gint fd, LockType type)
415 {
416         if (type == LOCK_FILE) {
417                 gchar *lockfile;
418
419                 lockfile = g_strconcat(base, ".lock", NULL);
420                 if (claws_unlink(lockfile) < 0) {
421                         FILE_OP_ERROR(lockfile, "unlink");
422                         g_free(lockfile);
423                         return -1;
424                 }
425                 g_free(lockfile);
426
427                 return 0;
428         } else if (type == LOCK_FLOCK) {
429                 gboolean fcntled = FALSE;
430 #if HAVE_FCNTL_H && !defined(G_OS_WIN32)
431                 struct flock fl;
432                 fl.l_type = F_UNLCK;
433                 fl.l_whence = SEEK_SET;
434                 fl.l_start = 0;
435                 fl.l_len = 0;
436
437                 if (fcntl(fd, F_SETLK, &fl) == -1) {
438                         g_warning("can't fnctl %s", base);
439                 } else {
440                         fcntled = TRUE;
441                 }
442 #endif
443 #if HAVE_FLOCK
444                 if (flock(fd, LOCK_UN) < 0 && !fcntled) {
445                         perror("flock");
446 #else
447 #if HAVE_LOCKF
448                 if (lockf(fd, F_ULOCK, 0) < 0 && !fcntled) {
449                         perror("lockf");
450 #else
451                 {
452 #endif
453 #endif /* HAVE_FLOCK */
454                         g_warning("can't unlock %s\n", base);
455                         if (close(fd) < 0)
456                                 perror("close");
457                         return -1;
458                 }
459
460                 if (close(fd) < 0) {
461                         perror("close");
462                         return -1;
463                 }
464
465                 return 0;
466         }
467
468         g_warning("invalid lock type\n");
469         return -1;
470 }
471
472 gint copy_mbox(gint srcfd, const gchar *dest)
473 {
474         FILE *dest_fp;
475         ssize_t n_read;
476         gchar buf[BUFSIZ];
477         gboolean err = FALSE;
478         int save_errno = 0;
479
480         if (srcfd < 0) {
481                 return -1;
482         }
483
484         if ((dest_fp = g_fopen(dest, "wb")) == NULL) {
485                 FILE_OP_ERROR(dest, "fopen");
486                 return -1;
487         }
488
489         if (change_file_mode_rw(dest_fp, dest) < 0) {
490                 FILE_OP_ERROR(dest, "chmod");
491                 g_warning("can't change file mode\n");
492         }
493
494         while ((n_read = read(srcfd, buf, sizeof(buf))) > 0) {
495                 if (n_read == -1 && errno != 0) {
496                         save_errno = errno;
497                         break;
498                 }
499                 if (fwrite(buf, 1, n_read, dest_fp) < n_read) {
500                         g_warning("writing to %s failed.\n", 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\n", save_errno,
509                                 strerror(save_errno));
510                 err = TRUE;
511         }
512
513         if (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.\n");
533                 return;
534         }
535         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, FALSE,
553                                         NULL, ALERT_WARNING, G_ALERTDEFAULT)
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         statuswindow_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                 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         statuswindow_pop_all();
670
671 #ifdef HAVE_FGETS_UNLOCKED
672         funlockfile(mbox_fp);
673 #endif
674         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 }