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