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