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