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