File: mailbox_maildir.c

package info (click to toggle)
balsa 2.4.12-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd, wheezy
  • size: 21,456 kB
  • ctags: 8,303
  • sloc: ansic: 93,724; xml: 13,662; sh: 11,146; makefile: 615; awk: 60
file content (985 lines) | stat: -rw-r--r-- 30,109 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
/* -*-mode:c; c-style:k&r; c-basic-offset:4; -*- */
/* Balsa E-Mail Client
 *
 * Copyright (C) 1997-2002 Stuart Parmenter and others,
 *                         See the file AUTHORS for a list.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2, or (at your option) 
 * any later version.
 *  
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the  
 * GNU General Public License for more details.
 *  
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  
 * 02111-1307, USA.
 */

#if defined(HAVE_CONFIG_H) && HAVE_CONFIG_H
# include "config.h"
#endif                          /* HAVE_CONFIG_H */


#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>

#include "libbalsa.h"
#include "libbalsa-conf.h"
#include "misc.h"
#include "libbalsa_private.h"
#include "mime-stream-shared.h"
#include <glib/gi18n.h>

struct message_info {
    LibBalsaMailboxLocalMessageInfo local_info;
    LibBalsaMessageFlag orig_flags;     /* Has only real flags */
    char *key;
    const char *subdir;
    char *filename;

    /* The message's order when parsing; needed for saving the message
     * tree in a form that will match the msgnos when the mailbox is
     * reopened. */
    guint fileno;
};
#define REAL_FLAGS(flags) ((flags) & LIBBALSA_MESSAGE_FLAGS_REAL)
#define FLAGS_REALLY_DIFFER(orig_flags, flags) \
    ((((orig_flags) ^ (flags)) & LIBBALSA_MESSAGE_FLAGS_REAL) != 0)
#define FLAGS_CHANGED(msg_info) \
    FLAGS_REALLY_DIFFER(msg_info->orig_flags, msg_info->local_info.flags)
  

static LibBalsaMailboxLocalClass *parent_class = NULL;

static void libbalsa_mailbox_maildir_class_init(LibBalsaMailboxMaildirClass *klass);
static void libbalsa_mailbox_maildir_init(LibBalsaMailboxMaildir * mailbox);

/* Object class method */
static void libbalsa_mailbox_maildir_finalize(GObject * object);

/* Mailbox class methods */
static void libbalsa_mailbox_maildir_load_config(LibBalsaMailbox * mailbox,
						 const gchar * prefix);

static GMimeStream *libbalsa_mailbox_maildir_get_message_stream(LibBalsaMailbox *
							   mailbox,
								guint msgno,
								gboolean peek);

static gboolean libbalsa_mailbox_maildir_open(LibBalsaMailbox * mailbox,
					      GError **err);
static void libbalsa_mailbox_maildir_close_mailbox(LibBalsaMailbox *
                                                   mailbox,
                                                   gboolean expunge);
static void libbalsa_mailbox_maildir_check(LibBalsaMailbox * mailbox);
static gboolean libbalsa_mailbox_maildir_sync(LibBalsaMailbox * mailbox,
                                              gboolean expunge);
static gboolean
libbalsa_mailbox_maildir_fetch_message_structure(LibBalsaMailbox * mailbox,
						 LibBalsaMessage * message,
						 LibBalsaFetchFlag flags);
static guint libbalsa_mailbox_maildir_add_messages(LibBalsaMailbox *
						   mailbox,
						   LibBalsaAddMessageIterator m,
						   void *m_arg, GError ** err);
static guint
libbalsa_mailbox_maildir_total_messages(LibBalsaMailbox * mailbox);

/* LibBalsaMailboxLocal class methods */
static gint lbm_maildir_check_files(const gchar * path, gboolean create);
static void lbm_maildir_set_path(LibBalsaMailboxLocal * local,
                                 const gchar * path);
static void lbm_maildir_remove_files(LibBalsaMailboxLocal * local);
static guint lbm_maildir_fileno(LibBalsaMailboxLocal * local, guint msgno);
static LibBalsaMailboxLocalMessageInfo
    *lbm_maildir_get_info(LibBalsaMailboxLocal * local, guint msgno);

/* util functions */
static struct message_info *message_info_from_msgno(LibBalsaMailboxMaildir
                                                    * mdir, guint msgno);
static LibBalsaMessageFlag parse_filename(const gchar *subdir,
					  const gchar *filename);
static void free_message_info(struct message_info *msg_info);
static int libbalsa_mailbox_maildir_open_temp (const gchar *dest_path,
					  char **name_used);

GType
libbalsa_mailbox_maildir_get_type(void)
{
    static GType mailbox_type = 0;

    if (!mailbox_type) {
	static const GTypeInfo mailbox_info = {
	    sizeof(LibBalsaMailboxMaildirClass),
            NULL,               /* base_init */
            NULL,               /* base_finalize */
	    (GClassInitFunc) libbalsa_mailbox_maildir_class_init,
            NULL,               /* class_finalize */
            NULL,               /* class_data */
	    sizeof(LibBalsaMailboxMaildir),
            0,                  /* n_preallocs */
	    (GInstanceInitFunc) libbalsa_mailbox_maildir_init
	};

	mailbox_type =
	    g_type_register_static(LIBBALSA_TYPE_MAILBOX_LOCAL,
	                           "LibBalsaMailboxMaildir",
                                   &mailbox_info, 0);
    }

    return mailbox_type;
}

static void
libbalsa_mailbox_maildir_class_init(LibBalsaMailboxMaildirClass * klass)
{
    GObjectClass *object_class;
    LibBalsaMailboxClass *libbalsa_mailbox_class;
    LibBalsaMailboxLocalClass *libbalsa_mailbox_local_class;

    object_class = G_OBJECT_CLASS(klass);
    libbalsa_mailbox_class = LIBBALSA_MAILBOX_CLASS(klass);
    libbalsa_mailbox_local_class = LIBBALSA_MAILBOX_LOCAL_CLASS(klass);

    parent_class = g_type_class_peek_parent(klass);

    object_class->finalize = libbalsa_mailbox_maildir_finalize;

    libbalsa_mailbox_class->load_config =
	        libbalsa_mailbox_maildir_load_config;
    libbalsa_mailbox_class->get_message_stream =
	libbalsa_mailbox_maildir_get_message_stream;

    libbalsa_mailbox_class->open_mailbox = libbalsa_mailbox_maildir_open;
    libbalsa_mailbox_class->check = libbalsa_mailbox_maildir_check;

    libbalsa_mailbox_class->sync = libbalsa_mailbox_maildir_sync;
    libbalsa_mailbox_class->close_mailbox =
	libbalsa_mailbox_maildir_close_mailbox;
    libbalsa_mailbox_class->fetch_message_structure =
	libbalsa_mailbox_maildir_fetch_message_structure;
    libbalsa_mailbox_class->add_messages =
	libbalsa_mailbox_maildir_add_messages;
    libbalsa_mailbox_class->total_messages =
	libbalsa_mailbox_maildir_total_messages;

    libbalsa_mailbox_local_class->check_files  = lbm_maildir_check_files;
    libbalsa_mailbox_local_class->set_path     = lbm_maildir_set_path;
    libbalsa_mailbox_local_class->remove_files = lbm_maildir_remove_files;
    libbalsa_mailbox_local_class->fileno       = lbm_maildir_fileno;
    libbalsa_mailbox_local_class->get_info     = lbm_maildir_get_info;
}

static void
libbalsa_mailbox_maildir_init(LibBalsaMailboxMaildir * mdir)
{
}

static gint
lbm_maildir_check_files(const gchar * path, gboolean create)
{
    g_return_val_if_fail(path != NULL, -1);

    if (access(path, F_OK) == 0) {
        /* File exists. Check if it is a maildir... */
        if (libbalsa_mailbox_type_from_path(path) !=
            LIBBALSA_TYPE_MAILBOX_MAILDIR) {
            libbalsa_information(LIBBALSA_INFORMATION_WARNING,
                                 _("Mailbox %s does not appear to be a Maildir mailbox."),
                                 path);
            return -1;
        }
    } else if (create) {
        char tmp[_POSIX_PATH_MAX];

        if (mkdir(path, S_IRWXU)) {
            libbalsa_information(LIBBALSA_INFORMATION_WARNING,
                                 _("Could not create a MailDir directory at %s (%s)"),
                                 path, strerror(errno));
            return -1;
        }

        snprintf(tmp, sizeof(tmp), "%s/cur", path);
        if (mkdir(tmp, S_IRWXU)) {
            libbalsa_information(LIBBALSA_INFORMATION_WARNING,
                                 _("Could not create a MailDir at %s (%s)"),
                                 path, strerror(errno));
            rmdir(path);
            return -1;
        }

        snprintf(tmp, sizeof(tmp), "%s/new", path);
        if (mkdir(tmp, S_IRWXU)) {
            libbalsa_information(LIBBALSA_INFORMATION_WARNING,
                                 _("Could not create a MailDir at %s (%s)"),
                                 path, strerror(errno));
            snprintf(tmp, sizeof(tmp), "%s/cur", path);
            rmdir(tmp);
            rmdir(path);
            return -1;
        }

        snprintf(tmp, sizeof(tmp), "%s/tmp", path);
        if (mkdir(tmp, S_IRWXU)) {
            libbalsa_information(LIBBALSA_INFORMATION_WARNING,
                                 _("Could not create a MailDir at %s (%s)"),
                                 path, strerror(errno));
            snprintf(tmp, sizeof(tmp), "%s/cur", path);
            rmdir(tmp);
            snprintf(tmp, sizeof(tmp), "%s/new", path);
            rmdir(tmp);
            rmdir(path);
            return -1;
        }
    } else
        return -1;

    return 0;
}

static void
lbm_maildir_set_subdirs(LibBalsaMailboxMaildir * mdir, const gchar * path)
{
    g_free(mdir->curdir);
    mdir->curdir = g_build_filename(path, "cur", NULL);
    g_free(mdir->newdir);
    mdir->newdir = g_build_filename(path, "new", NULL);
    g_free(mdir->tmpdir);
    mdir->tmpdir = g_build_filename(path, "tmp", NULL);
}

static void
lbm_maildir_set_path(LibBalsaMailboxLocal * local, const gchar * path)
{
    lbm_maildir_set_subdirs(LIBBALSA_MAILBOX_MAILDIR(local), path);
}

GObject *
libbalsa_mailbox_maildir_new(const gchar * path, gboolean create)
{
    LibBalsaMailbox *mailbox;

    mailbox = g_object_new(LIBBALSA_TYPE_MAILBOX_MAILDIR, NULL);

    mailbox->is_directory = TRUE;

    if (libbalsa_mailbox_local_set_path(LIBBALSA_MAILBOX_LOCAL(mailbox),
                                        path, create) != 0) {
        g_object_unref(mailbox);
        return NULL;
    }

    return G_OBJECT(mailbox);
}

static void
libbalsa_mailbox_maildir_finalize(GObject * object)
{
    LibBalsaMailboxMaildir *mdir = LIBBALSA_MAILBOX_MAILDIR(object);
    g_free(mdir->curdir);
    mdir->curdir = NULL;
    g_free(mdir->newdir);
    mdir->newdir = NULL;
    g_free(mdir->tmpdir);
    mdir->tmpdir = NULL;

    if (G_OBJECT_CLASS(parent_class)->finalize)
	G_OBJECT_CLASS(parent_class)->finalize(object);
}

static void
libbalsa_mailbox_maildir_load_config(LibBalsaMailbox * mailbox,
				     const gchar * prefix)
{
    LibBalsaMailboxMaildir *mdir = LIBBALSA_MAILBOX_MAILDIR(mailbox);
    gchar *path;

    path = libbalsa_conf_get_string("Path");
    lbm_maildir_set_subdirs(mdir, path);
    g_free(path);

    LIBBALSA_MAILBOX_CLASS(parent_class)->load_config(mailbox, prefix);
}

static GMimeStream *
libbalsa_mailbox_maildir_get_message_stream(LibBalsaMailbox * mailbox,
					    guint msgno, gboolean peek)
{
    struct message_info *msg_info;

    g_return_val_if_fail(MAILBOX_OPEN(mailbox), NULL);

    msg_info =
        message_info_from_msgno((LibBalsaMailboxMaildir *) mailbox, msgno);
    if (!msg_info)
	return NULL;

    return libbalsa_mailbox_local_get_message_stream(mailbox,
						     msg_info->subdir,
						     msg_info->filename);
}

static void
lbm_maildir_remove_files(LibBalsaMailboxLocal *mailbox)
{
    const gchar* path;
    g_return_if_fail(LIBBALSA_IS_MAILBOX_MAILDIR(mailbox));
    path = libbalsa_mailbox_local_get_path(mailbox);
    g_print("DELETE MAILDIR\n");

    if (!libbalsa_delete_directory_contents(path)) {
	libbalsa_information(LIBBALSA_INFORMATION_ERROR,
			     _("Could not remove contents of %s:\n%s"),
			     path, strerror(errno));
	return;
    }
    if ( rmdir(path) == -1 ) {
	libbalsa_information(LIBBALSA_INFORMATION_ERROR,
			     _("Could not remove %s:\n%s"),
			     path, strerror(errno));
    }
    LIBBALSA_MAILBOX_LOCAL_CLASS(parent_class)->remove_files(mailbox);
}

static LibBalsaMessageFlag parse_filename(const gchar *subdir,
					  const gchar *filename)
{
    const gchar *p;
    LibBalsaMessageFlag flags;

    flags = LIBBALSA_MESSAGE_FLAG_NEW;
    if (strcmp(subdir, "cur") != 0)
	flags |= LIBBALSA_MESSAGE_FLAG_RECENT;

    if ((p = strrchr (filename, ':')) != NULL && strncmp (p + 1, "2,", 2) == 0)
    {
	p += 3;
	while (*p)
	{
	    switch (*p)
	    {
		case 'F':
		    flags |= LIBBALSA_MESSAGE_FLAG_FLAGGED;
		    break;
	
		case 'S': /* seen */
		    flags &= ~LIBBALSA_MESSAGE_FLAG_NEW;
		    break;

		case 'R': /* replied */
		    flags |= LIBBALSA_MESSAGE_FLAG_REPLIED;
		    break;

		case 'T': /* trashed */
		    flags |= LIBBALSA_MESSAGE_FLAG_DELETED;
		    break;
	    }
	    p++;
	}
    }
    return flags;
}

static void lbm_maildir_parse(LibBalsaMailboxMaildir * mdir,
                              const gchar *subdir, guint * fileno)
{
    gchar *path;
    GDir *dir;
    GHashTable *messages_info;
    GPtrArray *msgno_2_msg_info;
    const gchar *filename;
    gchar *key;
    gchar *p;
    LibBalsaMessageFlag flags;
    LibBalsaMailbox *mailbox = (LibBalsaMailbox *) mdir;

    path = g_build_filename(libbalsa_mailbox_local_get_path(mailbox),
			    subdir, NULL);
    dir = g_dir_open(path, 0, NULL);
    g_free(path);
    if (dir == NULL)
	return;

    messages_info = mdir->messages_info;
    msgno_2_msg_info = mdir->msgno_2_msg_info;
    while ((filename = g_dir_read_name(dir)) != NULL)
    {
	struct message_info *msg_info;
	if (filename[0] == '.')
	    continue;

	key = g_strdup(filename);
	/* strip flags of filename */
	if ((p = strrchr(key, ':')) && !strncmp(p, ":2,", 3))
	    *p = '\0';

	flags = parse_filename(subdir, filename);
	msg_info = g_hash_table_lookup(messages_info, key);
	if (msg_info) {
	    g_free(key);
	    g_free(msg_info->filename);
	    msg_info->filename = g_strdup(filename);
	    if (FLAGS_REALLY_DIFFER(msg_info->orig_flags, flags)) {
#undef DEBUG /* #define DEBUG TRUE */
#ifdef DEBUG
		g_message("Message flags for \"%s\" changed\n",
                          msg_info->key);
#endif
		msg_info->orig_flags = flags;
	    }
	} else {
	    msg_info = g_new0(struct message_info, 1);
	    g_hash_table_insert(messages_info, key, msg_info);
	    g_ptr_array_add(msgno_2_msg_info, msg_info);
	    msg_info->key=key;
	    msg_info->filename=g_strdup(filename);
	    msg_info->local_info.flags = msg_info->orig_flags = flags;
	    msg_info->fileno = 0;
	}
	msg_info->subdir = subdir;
        if (!msg_info->fileno)
            /* First time we saw this key. */
	    msg_info->fileno = ++*fileno;
    }
    g_dir_close(dir);
}

static void
lbm_maildir_parse_subdirs(LibBalsaMailboxMaildir * mdir)
{
    guint msgno, fileno = 0;

    for (msgno = mdir->msgno_2_msg_info->len; msgno > 0; --msgno) {
        struct message_info *msg_info =
            message_info_from_msgno(mdir, msgno);
        msg_info->fileno = 0;
    }

    lbm_maildir_parse(mdir, "cur", &fileno);
    /* We parse "new" after "cur", so that any recent messages will have
     * higher msgnos than any current messages. That ensures that the
     * message tree saved by LibBalsaMailboxLocal is still valid, and
     * that the new messages will be inserted correctly into the tree by
     * libbalsa_mailbox_local_add_messages. */
    lbm_maildir_parse(mdir, "new", &fileno);
}

static gboolean
libbalsa_mailbox_maildir_open(LibBalsaMailbox * mailbox, GError **err)
{
    struct stat st;
    LibBalsaMailboxMaildir *mdir;
    const gchar* path;

    g_return_val_if_fail(LIBBALSA_IS_MAILBOX_MAILDIR(mailbox), FALSE);

    mdir = LIBBALSA_MAILBOX_MAILDIR(mailbox);
    path = libbalsa_mailbox_local_get_path(mailbox);

    if (stat(path, &st) == -1) {
	g_set_error(err, LIBBALSA_MAILBOX_ERROR, LIBBALSA_MAILBOX_OPEN_ERROR,
		    _("Mailbox does not exist."));
	return FALSE;
    }

    mdir->messages_info = g_hash_table_new_full(g_str_hash, g_str_equal,
				  NULL, (GDestroyNotify)free_message_info);
    mdir->msgno_2_msg_info = g_ptr_array_new();

    if (stat(mdir->tmpdir, &st) != -1)
	libbalsa_mailbox_set_mtime(mailbox, st.st_mtime);

    mailbox->readonly = 
	!(access(mdir->curdir, W_OK) == 0 &&
          access(mdir->newdir, W_OK) == 0 &&
          access(mdir->tmpdir, W_OK) == 0);

    mailbox->unread_messages = 0;
    lbm_maildir_parse_subdirs(mdir);
    LIBBALSA_MAILBOX_LOCAL(mailbox)->sync_time = 0;
    LIBBALSA_MAILBOX_LOCAL(mailbox)->sync_cnt  = 1;
#ifdef DEBUG
    g_print(_("%s: Opening %s Refcount: %d\n"),
	    "LibBalsaMailboxMaildir", mailbox->name, mailbox->open_ref);
#endif
    return TRUE;
}

/* Check for a new message in subdir. */
static gboolean
lbm_maildir_check(const gchar * subdir)
{
    GDir *dir;
    const gchar *filename;
    const gchar *p;
    gboolean retval = FALSE;

    if ((dir = g_dir_open(subdir, 0, NULL))) {
	while ((filename = g_dir_read_name(dir))) {
	    if (*filename != '.' && (!(p = strstr(filename, ":2,"))
				     || !(strchr(p + 3, 'S')
					  || strchr(p + 3, 'T')))) {
		/* One new message is enough. */
		retval = TRUE;
		break;
	    }
	}
	g_dir_close(dir);
    }

    return retval;
}

/* Called with mailbox locked. */
static void
libbalsa_mailbox_maildir_check(LibBalsaMailbox * mailbox)
{
    struct stat st;
    LibBalsaMailboxMaildir *mdir;
    guint renumber, msgno;
    struct message_info *msg_info;
    const gchar *path;
    time_t mtime;

    g_assert(LIBBALSA_IS_MAILBOX_MAILDIR(mailbox));

    mdir = LIBBALSA_MAILBOX_MAILDIR(mailbox);

    if (stat(mdir->tmpdir, &st) == -1)
	return;

    if ((mtime = libbalsa_mailbox_get_mtime(mailbox)) == 0) {
	/* First check--just cache the mtime. */
	libbalsa_mailbox_set_mtime(mailbox, st.st_mtime);
        return;
    }
    if (st.st_mtime == mtime)
	return;

    libbalsa_mailbox_set_mtime(mailbox, st.st_mtime);

    if (!MAILBOX_OPEN(mailbox)) {
	libbalsa_mailbox_set_unread_messages_flag(mailbox,
						  lbm_maildir_check(mdir->
								    newdir)
						  ||
						  lbm_maildir_check(mdir->
								    curdir));
	return;
    }

    /* Was any message removed? */
    path = libbalsa_mailbox_local_get_path(mailbox);
    renumber = mdir->msgno_2_msg_info->len + 1;
    for (msgno = 1; msgno <= mdir->msgno_2_msg_info->len; ) {
	gchar *filename;

        msg_info = message_info_from_msgno(mdir, msgno);
	filename = g_build_filename(path, msg_info->subdir,
				    msg_info->filename, NULL);
	if (access(filename, F_OK) == 0)
	    msgno++;
	else {
	    g_ptr_array_remove(mdir->msgno_2_msg_info, msg_info);
	    g_hash_table_remove(mdir->messages_info, msg_info->key);
	    libbalsa_mailbox_local_msgno_removed(mailbox, msgno);
	    if (renumber > msgno)
		/* First message that needs renumbering. */
		renumber = msgno;
	}
	g_free(filename);
    }
    for (msgno = renumber; msgno <= mdir->msgno_2_msg_info->len; msgno++) {
	msg_info = message_info_from_msgno(mdir, msgno);
	if (msg_info->local_info.message)
	    msg_info->local_info.message->msgno = msgno;
    }

    msgno = mdir->msgno_2_msg_info->len;
    lbm_maildir_parse_subdirs(mdir);
    libbalsa_mailbox_local_load_messages(mailbox, msgno);
}

static void
free_message_info(struct message_info *msg_info)
{
    if (!msg_info)
	return;
    g_free(msg_info->key);
    g_free(msg_info->filename);
    if (msg_info->local_info.message) {
	msg_info->local_info.message->mailbox = NULL;
	msg_info->local_info.message->msgno   = 0;
	g_object_remove_weak_pointer(G_OBJECT(msg_info->local_info.message),
				     (gpointer) & msg_info->local_info.message);
    }
    g_free(msg_info);
}

static void
libbalsa_mailbox_maildir_close_mailbox(LibBalsaMailbox * mailbox,
                                       gboolean expunge)
{
    LibBalsaMailboxMaildir *mdir = LIBBALSA_MAILBOX_MAILDIR(mailbox);
    guint len;

    len = mdir->msgno_2_msg_info->len;
    libbalsa_mailbox_maildir_sync(mailbox, expunge);
    if (mdir->msgno_2_msg_info->len != len)
        libbalsa_mailbox_changed(mailbox);

    if (LIBBALSA_MAILBOX_CLASS(parent_class)->close_mailbox)
        LIBBALSA_MAILBOX_CLASS(parent_class)->close_mailbox(mailbox,
                                                            expunge);

    /* Now it's safe to free the message info. */
    g_hash_table_destroy(mdir->messages_info);
    mdir->messages_info = NULL;

    g_ptr_array_free(mdir->msgno_2_msg_info, TRUE);
    mdir->msgno_2_msg_info = NULL;
}

static gchar *
lbm_mdir_get_key(void)
{
    static int counter;

    return g_strdup_printf("%s-%d-%d", g_get_user_name(), getpid(),
                           counter++);
}

static int
libbalsa_mailbox_maildir_open_temp(const gchar *dest_path,
                                   char **name_used)
{
    int fd;
    gchar *filename;

    do {
	gchar *key = lbm_mdir_get_key();
	filename = g_build_filename(dest_path, "tmp", key, NULL);
	g_free(key);
	fd = open (filename, O_WRONLY | O_EXCL | O_CREAT, 0600);
	if (fd == -1)
	{
	    g_free(filename);
	    if (errno != EEXIST)
		return -1;
	}
    } while (fd == -1);
    *name_used = filename;
    return fd;
}

/* Sync: flush flags and expunge. */
static gboolean
maildir_sync_add(struct message_info *msg_info, const gchar * path)
{
    gchar new_flags[10];
    int len;
    const gchar *subdir;
    gchar *filename;
    gchar *new;
    gchar *orig;
    gboolean retval = TRUE;

    len = 0;

    if ((msg_info->local_info.flags & LIBBALSA_MESSAGE_FLAG_FLAGGED) != 0)
	new_flags[len++] = 'F';
    if ((msg_info->local_info.flags & LIBBALSA_MESSAGE_FLAG_NEW) == 0)
	new_flags[len++] = 'S';
    if ((msg_info->local_info.flags & LIBBALSA_MESSAGE_FLAG_REPLIED) != 0)
	new_flags[len++] = 'R';
    if ((msg_info->local_info.flags & LIBBALSA_MESSAGE_FLAG_DELETED) != 0)
	new_flags[len++] = 'T';

    new_flags[len] = '\0';

    subdir = msg_info->local_info.flags & LIBBALSA_MESSAGE_FLAG_RECENT ? "new" : "cur";
    filename =
        g_strconcat(msg_info->key, (len ? ":2," : ""), new_flags, NULL);
    new = g_build_filename(path, subdir, filename, NULL);
    orig =
        g_build_filename(path, msg_info->subdir, msg_info->filename, NULL);
    if (strcmp(orig, new)) {
        while (g_file_test(new, G_FILE_TEST_EXISTS)) {
#ifdef DEBUG
	    g_message("File \"%s\" exists, requesting new key.\n", new);
#endif
            g_free(msg_info->key);
            msg_info->key = lbm_mdir_get_key();
            g_free(filename);
            filename =
                g_strconcat(msg_info->key, (len ? ":2," : ""), new_flags,
                            NULL);
            g_free(new);
            new = g_build_filename(path, subdir, filename, NULL);
        }
	if (rename(orig, new) >= 0) /* FIXME: change to safe_rename??? */
	    msg_info->subdir = subdir;
	else {
#ifdef DEBUG
            g_message("Rename \"%s\" \"%s\": %s\n", orig, new,
                      g_strerror(errno));
#endif
	    retval = FALSE;
	}
    }
    g_free(orig);
    g_free(new);
    g_free(msg_info->filename);
    msg_info->filename = filename;
    msg_info->orig_flags = REAL_FLAGS(msg_info->local_info.flags);

    return retval;
}

static gboolean
libbalsa_mailbox_maildir_sync(LibBalsaMailbox * mailbox, gboolean expunge)
{
    /*
     * foreach message_info
     *  mark_move if subdir == "new"
     *  mark_move if flags changed
     *  move/rename and record change if mark_move
     * record mtime of dirs
     */
    LibBalsaMailboxMaildir *mdir = LIBBALSA_MAILBOX_MAILDIR(mailbox);
    const gchar *path = libbalsa_mailbox_local_get_path(mailbox);
    GSList *removed_list = NULL;
    gboolean ok = TRUE;
    GSList *l;
    guint renumber, msgno;
    struct message_info *msg_info;
    guint changes = 0;

    for (msgno = 1; msgno <= mdir->msgno_2_msg_info->len; msgno++) {
	msg_info = message_info_from_msgno(mdir, msgno);

	if (expunge && (msg_info->local_info.flags & LIBBALSA_MESSAGE_FLAG_DELETED)) {
	    /* skip this block if the message should only be renamed */
	    gchar *orig = g_build_filename(path, msg_info->subdir,
                                           msg_info->filename, NULL);
	    unlink (orig);
	    g_free(orig);
	    removed_list =
		g_slist_prepend(removed_list, GUINT_TO_POINTER(msgno));
	    ++changes;
	    continue;
	}

	if (mailbox->state == LB_MAILBOX_STATE_CLOSING)
	    msg_info->local_info.flags &= ~LIBBALSA_MESSAGE_FLAG_RECENT;
	if (((msg_info->local_info.flags & LIBBALSA_MESSAGE_FLAG_RECENT)
             && strcmp(msg_info->subdir, "new") != 0)
            || (!(msg_info->local_info.flags & LIBBALSA_MESSAGE_FLAG_RECENT)
                && strcmp(msg_info->subdir, "cur") != 0)
            || FLAGS_CHANGED(msg_info)) {
	    if (!maildir_sync_add(msg_info, path))
		ok = FALSE;
	    ++changes;
	}
    }

    if (!ok) {
	g_slist_free(removed_list);
	return FALSE;
    }

    renumber = mdir->msgno_2_msg_info->len + 1;
    for (l = removed_list; l; l = l->next) {
	msgno = GPOINTER_TO_UINT(l->data);
	if (renumber > msgno)
	    renumber = msgno;
	msg_info = message_info_from_msgno(mdir, msgno);

	g_ptr_array_remove(mdir->msgno_2_msg_info, msg_info);
	libbalsa_mailbox_local_msgno_removed(mailbox, msgno);
	/* This will free removed: */
	g_hash_table_remove(mdir->messages_info, msg_info->key);
    }
    g_slist_free(removed_list);
    for (msgno = renumber; msgno <= mdir->msgno_2_msg_info->len; msgno++) {
	msg_info = message_info_from_msgno(mdir, msgno);
	if (msg_info->local_info.message)
	    msg_info->local_info.message->msgno = msgno;
    }

    if (changes) {              /* Record mtime of dir. */
        struct stat st;

        /* Reparse, to get the fileno entries right. */
        lbm_maildir_parse_subdirs(mdir);
        mailbox->msg_tree_changed = TRUE;

        if (stat(mdir->tmpdir, &st) == 0)
            libbalsa_mailbox_set_mtime(mailbox, st.st_mtime);
    }

    return TRUE;
}

static struct message_info *
message_info_from_msgno(LibBalsaMailboxMaildir * mdir, guint msgno)
{
    g_assert(msgno > 0 && msgno <= mdir->msgno_2_msg_info->len);

    return (struct message_info *) g_ptr_array_index(mdir->
                                                     msgno_2_msg_info,
                                                     msgno - 1);
}


static gboolean
libbalsa_mailbox_maildir_fetch_message_structure(LibBalsaMailbox * mailbox,
						 LibBalsaMessage * message,
						 LibBalsaFetchFlag flags)
{
    if (!message->mime_msg) {
	struct message_info *msg_info =
            message_info_from_msgno((LibBalsaMailboxMaildir *) mailbox,
                                    message->msgno);
	message->mime_msg =
	    libbalsa_mailbox_local_get_mime_message(mailbox,
						    msg_info->subdir,
						    msg_info->filename);
    }

    return LIBBALSA_MAILBOX_CLASS(parent_class)->
        fetch_message_structure(mailbox, message, flags);
}

static guint
lbm_maildir_fileno(LibBalsaMailboxLocal * local, guint msgno)
{
    struct message_info *msg_info;

    if (!msgno)
        return 0;

    msg_info =
        message_info_from_msgno((LibBalsaMailboxMaildir *) local, msgno);

    return msg_info->fileno;
}

static LibBalsaMailboxLocalMessageInfo *
lbm_maildir_get_info(LibBalsaMailboxLocal * local, guint msgno)
{
    struct message_info *msg_info;

    msg_info =
        message_info_from_msgno((LibBalsaMailboxMaildir *) local, msgno);

    return &msg_info->local_info;
}

/* Called with mailbox locked. */
static gboolean
libbalsa_mailbox_maildir_add_message(LibBalsaMailbox * mailbox,
                                     GMimeStream * stream,
                                     LibBalsaMessageFlag flags,
                                     GError **err)
{
    const char *path;
    char *tmp;
    int fd;
    GMimeStream *out_stream;
    GMimeStream *in_stream;
    GMimeFilter *crlffilter;
    char *new_filename;
    struct message_info *msg_info;
    gint retval;
    time_t mtime;

    /* open tempfile */
    path = libbalsa_mailbox_local_get_path(mailbox);
    fd = libbalsa_mailbox_maildir_open_temp(path, &tmp);
    if (fd == -1)
	return FALSE;
    out_stream = g_mime_stream_fs_new(fd);

    in_stream = g_mime_stream_filter_new(stream);
    crlffilter =
        g_mime_filter_crlf_new(FALSE,
                               FALSE);
    g_mime_stream_filter_add(GMIME_STREAM_FILTER(in_stream), crlffilter);
    g_object_unref(crlffilter);
 
    libbalsa_mime_stream_shared_lock(stream);
    retval = g_mime_stream_write_to_stream(in_stream, out_stream);
    libbalsa_mime_stream_shared_unlock(stream);
    g_object_unref(in_stream);
    g_object_unref(out_stream);

    if (retval < 0) {
	unlink (tmp);
	g_free(tmp);
        g_set_error(err, LIBBALSA_MAILBOX_ERROR,
                    LIBBALSA_MAILBOX_COPY_ERROR,
                    _("Data copy error"));
	return FALSE;
    }

    new_filename = strrchr(tmp, '/');
    if (new_filename)
	new_filename++;
    else
	new_filename = tmp;
    msg_info = g_new0(struct message_info, 1);
    msg_info->subdir = "tmp";
    msg_info->key = g_strdup(new_filename);
    msg_info->filename = g_strdup(new_filename);
    msg_info->local_info.flags = flags | LIBBALSA_MESSAGE_FLAG_RECENT;
    retval = maildir_sync_add(msg_info, path);
    free_message_info(msg_info);
    g_free(tmp);

    if ((mtime = libbalsa_mailbox_get_mtime(mailbox)) != 0)
	/* If we checked or synced the mailbox less than 1 second ago,
	 * the cached modification time could be the same as the new
	 * modification time, so we'll invalidate the cached time. */
	libbalsa_mailbox_set_mtime(mailbox, --mtime);

    return retval;
}

static guint
libbalsa_mailbox_maildir_add_messages(LibBalsaMailbox * mailbox,
				      LibBalsaAddMessageIterator msg_iterator,
				      void *arg,
				      GError **err)
{
    LibBalsaMessageFlag flag;
    GMimeStream *stream;

    guint cnt = 0;
    while( msg_iterator(&flag, &stream, arg) ) {
	gboolean success =
	    libbalsa_mailbox_maildir_add_message(mailbox, stream, flag, err);
	g_object_unref(stream);
	if(!success)
	    break;
	cnt++;
    }
    return cnt;
}

static guint
libbalsa_mailbox_maildir_total_messages(LibBalsaMailbox * mailbox)
{
    LibBalsaMailboxMaildir *mdir = (LibBalsaMailboxMaildir *) mailbox;

    return mdir->msgno_2_msg_info ? mdir->msgno_2_msg_info->len : 0;
}