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