2007-01-26 [wwp] 2.7.2cvs2
[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                         return -1;
421                 } else {
422                         fcntled = TRUE;
423                 }
424 #endif
425 #if HAVE_FLOCK
426                 if (flock(fd, LOCK_UN) < 0 && !fcntled) {
427                         perror("flock");
428 #else
429 #if HAVE_LOCKF
430                 if (lockf(fd, F_ULOCK, 0) < 0 && !fcntled) {
431                         perror("lockf");
432 #else
433                 {
434 #endif
435 #endif /* HAVE_FLOCK */
436                         g_warning("can't unlock %s\n", base);
437                         if (close(fd) < 0)
438                                 perror("close");
439                         return -1;
440                 }
441
442                 if (close(fd) < 0) {
443                         perror("close");
444                         return -1;
445                 }
446
447                 return 0;
448         }
449
450         g_warning("invalid lock type\n");
451         return -1;
452 }
453
454 gint copy_mbox(const gchar *src, const gchar *dest)
455 {
456         return copy_file(src, dest, TRUE);
457 }
458
459 void empty_mbox(const gchar *mbox)
460 {
461         FILE *fp;
462
463         if ((fp = g_fopen(mbox, "wb")) == NULL) {
464                 FILE_OP_ERROR(mbox, "fopen");
465                 g_warning("can't truncate mailbox to zero.\n");
466                 return;
467         }
468         fclose(fp);
469 }
470
471 gint export_list_to_mbox(GSList *mlist, const gchar *mbox)
472 /* return values: -2 skipped, -1 error, 0 OK */
473 {
474         GSList *cur;
475         MsgInfo *msginfo;
476         FILE *msg_fp;
477         FILE *mbox_fp;
478         gchar buf[BUFFSIZE];
479         gint msgs = 1, total = g_slist_length(mlist);
480         if (g_file_test(mbox, G_FILE_TEST_EXISTS) == TRUE) {
481                 if (alertpanel_full(_("Overwrite mbox file"),
482                                         _("This file already exists. Do you want to overwrite it?"),
483                                         GTK_STOCK_CANCEL, _("Overwrite"), NULL, FALSE,
484                                         NULL, ALERT_WARNING, G_ALERTDEFAULT)
485                                 != G_ALERTALTERNATE) {
486                         return -2;
487                 }
488         }
489
490         if ((mbox_fp = g_fopen(mbox, "wb")) == NULL) {
491                 FILE_OP_ERROR(mbox, "fopen");
492                 alertpanel_error(_("Could not create mbox file:\n%s\n"), mbox);
493                 return -1;
494         }
495
496 #ifdef HAVE_FGETS_UNLOCKED
497         flockfile(mbox_fp);
498 #endif
499
500         statusbar_print_all(_("Exporting to mbox..."));
501         for (cur = mlist; cur != NULL; cur = cur->next) {
502                 int len;
503                 msginfo = (MsgInfo *)cur->data;
504
505                 msg_fp = procmsg_open_message(msginfo);
506                 if (!msg_fp) {
507                         continue;
508                 }
509
510 #ifdef HAVE_FGETS_UNLOCKED
511                 flockfile(msg_fp);
512 #endif
513                 strncpy2(buf,
514                          msginfo->from ? msginfo->from :
515                          cur_account && cur_account->address ?
516                          cur_account->address : "unknown",
517                          sizeof(buf));
518                 extract_address(buf);
519
520                 fprintf(mbox_fp, "From %s %s",
521                         buf, ctime(&msginfo->date_t));
522
523                 buf[0] = '\0';
524                 
525                 /* write email to mboxrc */
526                 while (SC_FGETS(buf, sizeof(buf), msg_fp) != NULL) {
527                         /* quote any From, >From, >>From, etc., according to mbox format specs */
528                         int offset;
529
530                         offset = 0;
531                         /* detect leading '>' char(s) */
532                         while ((buf[offset] == '>')) {
533                                 offset++;
534                         }
535                         if (!strncmp(buf+offset, "From ", 5))
536                                 SC_FPUTC('>', mbox_fp);
537                         SC_FPUTS(buf, mbox_fp);
538                 }
539
540                 /* force last line to end w/ a newline */
541                 len = strlen(buf);
542                 if (len > 0) {
543                         len--;
544                         if ((buf[len] != '\n') && (buf[len] != '\r'))
545                                 SC_FPUTC('\n', mbox_fp);
546                 }
547
548                 /* add a trailing empty line */
549                 SC_FPUTC('\n', mbox_fp);
550
551 #ifdef HAVE_FGETS_UNLOCKED
552                 funlockfile(msg_fp);
553 #endif
554                 fclose(msg_fp);
555                 statusbar_progress_all(msgs++,total, 500);
556                 if (msgs%500 == 0)
557                         GTK_EVENTS_FLUSH();
558         }
559         statusbar_progress_all(0,0,0);
560         statusbar_pop_all();
561
562 #ifdef HAVE_FGETS_UNLOCKED
563         funlockfile(mbox_fp);
564 #endif
565         fclose(mbox_fp);
566
567         return 0;
568 }
569
570 /* read all messages in SRC, and store them into one MBOX file. */
571 /* return values: -2 skipped, -1 error, 0 OK */
572 gint export_to_mbox(FolderItem *src, const gchar *mbox)
573 {
574         GSList *mlist;
575         gint ret;
576         
577         g_return_val_if_fail(src != NULL, -1);
578         g_return_val_if_fail(src->folder != NULL, -1);
579         g_return_val_if_fail(mbox != NULL, -1);
580
581         debug_print("Exporting messages from %s into %s...\n",
582                     src->path, mbox);
583
584         mlist = folder_item_get_msg_list(src);
585
586         folder_item_update_freeze();
587         ret = export_list_to_mbox(mlist, mbox);
588         folder_item_update_thaw();
589
590         procmsg_msg_list_free(mlist);
591
592         return ret;
593 }