maildir-sync.c revision 4b43f50117630aa12b3cfd0cbd05ae22ba27fec1
/* Copyright (C) 2004 Timo Sirainen */
/*
Here's a description of how we handle Maildir synchronization and
it's problems:
We want to be as efficient as we can. The most efficient way to
check if changes have occurred is to stat() the new/ and cur/
directories and uidlist file - if their mtimes haven't changed,
there's no changes and we don't need to do anything.
Problem 1: Multiple changes can happen within a single second -
nothing guarantees that once we synced it, someone else didn't just
then make a modification. Such modifications wouldn't get noticed
until a new modification occurred later.
Problem 2: Syncing cur/ directory is much more costly than syncing
new/. Moving mails from new/ to cur/ will always change mtime of
cur/ causing us to sync it as well.
Problem 3: We may not be able to move mail from new/ to cur/
because we're out of quota, or simply because we're accessing a
read-only mailbox.
MAILDIR_SYNC_SECS
-----------------
Several checks below use MAILDIR_SYNC_SECS, which should be maximum
clock drift between all computers accessing the maildir (eg. via
NFS), rounded up to next second. Our default is 1 second, since
everyone should be using NTP.
Note that setting it to 0 works only if there's only one computer
accessing the maildir. It's practically impossible to make two
clocks _exactly_ synchronized.
It might be possible to only use file server's clock by looking at
the atime field, but I don't know how well that would actually work.
cur directory
-------------
We have dirty_cur_time variable which is set to cur/ directory's
mtime when it's >= time() - MAILDIR_SYNC_SECS and we _think_ we have
synchronized the directory.
When dirty_cur_time is non-zero, we don't synchronize the cur/
directory until
a) cur/'s mtime changes
b) opening a mail fails with ENOENT
c) time() > dirty_cur_time + MAILDIR_SYNC_SECS
This allows us to modify the maildir multiple times without having
to sync it at every change. The sync will eventually be done to
make sure we didn't miss any external changes.
The dirty_cur_time is set when:
- we change message flags
- we expunge messages
- we move mail from new/ to cur/
- we sync cur/ directory and it's mtime is >= time() - MAILDIR_SYNC_SECS
It's unset when we do the final syncing, ie. when mtime is
older than time() - MAILDIR_SYNC_SECS.
new directory
-------------
If new/'s mtime is >= time() - MAILDIR_SYNC_SECS, always synchronize
it. dirty_cur_time-like feature might save us a few syncs, but
that might break a client which saves a mail in one connection and
tries to fetch it in another one. new/ directory is almost always
empty, so syncing it should be very fast anyway. Actually this can
still happen if we sync only new/ dir while another client is also
moving mails from it to cur/ - it takes us a while to see them.
That's pretty unlikely to happen however, and only way to fix it
would be to always synchronize cur/ after new/.
Normally we move all mails from new/ to cur/ whenever we sync it. If
it's not possible for some reason, we mark the mail with "probably
exists in new/ directory" flag.
If rename() still fails because of ENOSPC or EDQUOT, we still save
the flag changes in index with dirty-flag on. When moving the mail
to cur/ directory, or when we notice it's already moved there, we
apply the flag changes to the filename, rename it and remove the
dirty flag. If there's dirty flags, this should be tried every time
after expunge or when closing the mailbox.
uidlist
-------
This file contains UID <-> filename mappings. It's updated only when
new mail arrives, so it may contain filenames that have already been
deleted. Updating is done by getting uidlist.lock file, writing the
whole uidlist into it and rename()ing it over the old uidlist. This
means there's no need to lock the file for reading.
Whenever uidlist is rewritten, it's mtime must be larger than the old
one's. Use utime() before rename() if needed. Note that inode checking
wouldn't have been sufficient as inode numbers can be reused.
This file is usually read the first time you need to know filename for
given UID. After that it's not re-read unless new mails come that we
don't know about.
broken clients
--------------
Originally the middle identifier in Maildir filename was specified
only as <process id>_<delivery counter>. That however created a
problem with randomized PIDs which made it possible that the same
PID was reused within one second.
So if within one second a mail was delivered, MUA moved it to cur/
and another mail was delivered by a new process using same PID as
the first one, we likely ended up overwriting the first mail when
the second mail was moved over it.
Nowadays everyone should be giving a bit more specific identifier,
for example include microseconds in it which Dovecot does.
There's a simple way to prevent this from happening in some cases:
Don't move the mail from new/ to cur/ if it's mtime is >= time() -
MAILDIR_SYNC_SECS. The second delivery's link() call then fails
because the file is already in new/, and it will then use a
different filename. There's a few problems with this however:
- it requires extra stat() call which is unneeded extra I/O
- another MUA might still move the mail to cur/
- if first file's flags are modified by either Dovecot or another
MUA, it's moved to cur/ (you _could_ just do the dirty-flagging
but that'd be ugly)
Because this is useful only for very few people and it requires
extra I/O, I decided not to implement this. It should be however
quite easy to do since we need to be able to deal with files in new/
in any case.
It's also possible to never accidentally overwrite a mail by using
link() + unlink() rather than rename(). This however isn't very
good idea as it introduces potential race conditions when multiple
clients are accessing the mailbox:
Trying to move the same mail from new/ to cur/ at the same time:
a) Client 1 uses slightly different filename than client 2,
for example one sets read-flag on but the other doesn't.
You have the same mail duplicated now.
b) Client 3 sees the mail between Client 1's and 2's link() calls
and changes it's flag. You have the same mail duplicated now.
And it gets worse when they're unlink()ing in cur/ directory:
c) Client 1 changes mails's flag and client 2 changes it back
between 1's link() and unlink(). The mail is now expunged.
d) If you try to deal with the duplicates by unlink()ing another
one of them, you might end up unlinking both of them.
So, what should we do then if we notice a duplicate? First of all,
it might not be a duplicate at all, readdir() might have just
returned it twice because it was just renamed. What we should do is
create a completely new base name for it and rename() it to that.
If the call fails with ENOENT, it only means that it wasn't a
duplicate after all.
*/
#include "lib.h"
#include "ioloop.h"
#include "array.h"
#include "buffer.h"
#include "hash.h"
#include "str.h"
#include "maildir-storage.h"
#include "maildir-uidlist.h"
#include "maildir-keywords.h"
#include <stdio.h>
#include <stddef.h>
#include <unistd.h>
#include <dirent.h>
#define MAILDIR_SYNC_SECS 1
#define MAILDIR_FILENAME_FLAG_FOUND 128
/* When rename()ing many files from new/ to cur/, it's possible that next
readdir() skips some files. we don't of course wish to lose them, so we
go and rescan the new/ directory again from beginning until no files are
left. This value is just an optimization to avoid checking the directory
twice unneededly. usually only NFS is the problem case. 1 is the safest
bet here, but I guess 5 will do just fine too. */
#define MAILDIR_RENAME_RESCAN_COUNT 5
struct maildir_sync_context {
struct maildir_mailbox *mbox;
bool partial;
struct maildir_uidlist_sync_ctx *uidlist_sync_ctx;
struct maildir_index_sync_context *index_sync_ctx;
};
struct maildir_index_sync_context {
struct maildir_mailbox *mbox;
struct mail_index_view *view;
struct mail_index_sync_ctx *sync_ctx;
struct mail_index_transaction *trans;
int dirty_state;
};
struct maildir_keywords_sync_ctx *
{
return ctx->keywords_sync_ctx;
}
{
ARRAY_SET_TYPE(keywords_r, unsigned int);
const char *info;
*flags_r = 0;
return 0;
switch (*info) {
case 'R': /* replied */
*flags_r |= MAIL_ANSWERED;
break;
case 'S': /* seen */
break;
case 'T': /* trashed */
*flags_r |= MAIL_DELETED;
break;
case 'D': /* draft */
*flags_r |= MAIL_DRAFT;
break;
case 'F': /* flagged */
*flags_r |= MAIL_FLAGGED;
break;
default:
if (*info >= MAILDIR_KEYWORD_FIRST &&
*info <= MAILDIR_KEYWORD_LAST) {
int idx;
if (idx < 0) {
/* unknown keyword. */
break;
}
(unsigned int *)&idx, 1);
break;
}
/* unknown flag - ignore */
break;
}
}
return 1;
}
static void
{
ARRAY_SET_TYPE(keywords, unsigned int);
const unsigned int *indexes;
unsigned int i, count;
char chr;
for (i = 0; i < count; i++) {
if (chr != '\0')
}
}
{
enum mail_flags flags_left;
int nextflag;
/* remove the old :info from file name, and get the old flags */
oldflags = "";
}
/* insert the new flags between old flags. flags must be sorted by
their ASCII code. unknown flags are kept. */
flags_left = flags;
for (;;) {
/* skip all known flags */
*oldflags == 'T' ||
(*oldflags >= MAILDIR_KEYWORD_FIRST &&
*oldflags <= MAILDIR_KEYWORD_LAST))
oldflags++;
256 : (unsigned char) *oldflags;
flags_left &= ~MAIL_DRAFT;
}
flags_left &= ~MAIL_FLAGGED;
}
flags_left &= ~MAIL_ANSWERED;
}
flags_left &= ~MAIL_SEEN;
}
flags_left &= ~MAIL_DELETED;
}
}
break;
oldflags++;
}
if (*oldflags == MAILDIR_FLAGS_SEP) {
/* another flagset, we don't know about these, just keep them */
while (*oldflags != '\0')
}
}
void *context __attr_unused__)
{
return 1;
}
return 0;
"unlink(%s) failed: %m", path);
return -1;
}
void *context)
{
const struct mail_index_sync_rec *recs;
const char *newpath;
enum mail_flags flags;
unsigned int i, count;
ctx->dirty_state = 0;
for (i = 0; i < count; i++) {
break;
break;
break;
i_unreached();
break;
}
}
if ((flags8 & MAIL_INDEX_MAIL_FLAG_DIRTY) != 0)
return 1;
}
return 0;
return 1;
}
return -1;
}
static int
{
struct mail_index_sync_rec *recs;
unsigned int i, count;
bool expunged, flag_changed;
for (i = 0; i < count; i++) {
break;
break;
flag_changed = TRUE;
break;
i_unreached();
break;
}
}
return -1;
if (expunged) {
maildir_expunge, ctx) < 0)
return -1;
} else if (flag_changed) {
maildir_sync_flags, ctx) < 0)
return -1;
}
for (i = count; i > 0; i--) {
&count);
if (count == 0) {
/* all sync_recs committed */
return 0;
}
}
}
}
return 0;
}
const struct mail_index_sync_rec *sync_rec)
{
struct mail_index_sync_rec sync_copy;
/* deinit */
(uint32_t)-1) < 0)
return -1;
}
return 0;
}
return 0; /* ignore */
/* convert to sequences to avoid looping through huge holes in
UID range */
return -1;
/* UIDs were expunged */
return 0;
}
const struct mail_index_sync_rec *rec =
break;
return -1;
}
return 0;
}
{
struct mail_index_sync_rec sync_rec;
int ret;
if (ret <= 0)
return ret;
struct mail_index_sync_rec, 32);
do {
return -1;
} while (ret > 0);
return -1;
return ret;
}
static struct maildir_sync_context *
{
struct maildir_sync_context *ctx;
return ctx;
}
{
}
{
const char *existing_fname, *existing_path;
int ret = 0;
t_push();
/* most likely the files just don't exist anymore.
don't really care about other errors much. */
t_pop();
return 0;
}
/* files are the same. this means either a race condition
between stat() calls, or someone has started link()ing the
files. either way there's no data loss if we just leave it
there. */
t_pop();
return 0;
}
i_warning("Fixed duplicate in %s: %s -> %s",
ret = -1;
}
t_pop();
return ret;
}
{
const char *dir;
unsigned int moves = 0;
int ret = 1;
bool move_new;
"opendir(%s) failed: %m", dir);
return -1;
}
t_push();
continue;
if (ret == 0) {
/* new file and we couldn't lock uidlist, check this
later in next sync. */
if (new_dir)
else
continue;
}
if (ret < 0)
break;
flags = 0;
if (move_new) {
str_truncate(src, 0);
str_truncate(dest, 0);
}
/* we moved it - it's \Recent for us */
moves++;
/* someone else moved it already */
moves++;
/* not enough disk space / read-only maildir,
leave here */
} else {
"rename(%s, %s) failed: %m",
}
} else if (new_dir) {
}
if (ret <= 0) {
if (ret < 0)
break;
/* possibly duplicate - try fixing it */
ret = -1;
break;
}
}
}
"closedir(%s) failed: %m", dir);
}
t_pop();
}
static void
{
/* FIXME: ugly, replace with extension header */
}
static int
bool *new_changed_r, bool *cur_changed_r)
{
"stat(%s) failed: %m", new_dir);
return -1;
}
"stat(%s) failed: %m", cur_dir);
return -1;
}
/* cur stamp is kept in index, we don't have to sync if
someone else has done it and updated the index.
FIXME: For now we're using sync_size field as the new/ dir's stamp.
Pretty ugly.. */
/* check if the index has been updated.. */
return -1;
}
}
/* If we're removing recent flags, always sync new/ directory if
it has mails. */
(!ibox->keep_recent &&
*new_changed_r = TRUE;
}
(mbox->dirty_cur_time != 0 &&
/* cur/ changed, or delayed cur/ check */
*cur_changed_r = TRUE;
cur_mtime : 0;
}
return 0;
}
struct maildir_index_sync_context **ctx_r)
{
struct maildir_index_sync_context *ctx;
struct mail_index_sync_ctx *sync_ctx;
struct mail_index_view *view;
return -1;
}
return 0;
}
bool failed)
{
if (ret < 0)
else {
ret = -1;
else if (seq != 0) {
}
}
}
if (ret < 0)
else {
ret = -1;
else {
}
}
if (ret < 0)
return ret;
}
bool partial)
{
struct maildir_uidlist_iter_ctx *iter;
struct mail_index_transaction *trans;
const struct mail_index_header *hdr;
const struct mail_index_record *rec;
const char *filename;
enum mail_flags flags;
int ret = 0;
bool full_rescan = FALSE;
/* uidvalidity changed and mailbox isn't being initialized,
reset mailbox so we can add all messages as new */
"Maildir %s sync: UIDVALIDITY changed (%u -> %u)",
return -1;
}
seq = 0;
unsigned int, MAILDIR_MAX_KEYWORDS);
unsigned int, MAILDIR_MAX_KEYWORDS);
/* the private flags are kept only in indexes. don't use them
at all even for newly seen mails */
if ((uflags & MAILDIR_UIDLIST_REC_FLAG_RECENT) != 0 &&
(uflags & MAILDIR_UIDLIST_REC_FLAG_NEW_DIR) != 0 &&
(uflags & MAILDIR_UIDLIST_REC_FLAG_MOVED) == 0) {
/* mail is recent for next session as well */
flags |= MAIL_RECENT;
}
seq++;
/* most likely a race condition: we read the
maildir, then someone else expunged messages
and committed changes to index. so, this
message shouldn't actually exist. mark it
racy and check in next sync.
the difference between this and the later
check is that this one happens when messages
are expunged from the end */
if ((uflags &
MAILDIR_UIDLIST_REC_FLAG_NONSYNCED) != 0) {
/* partial syncing */
continue;
}
if ((uflags &
MAILDIR_UIDLIST_REC_FLAG_RACING) != 0) {
"Maildir %s sync: "
"UID < next_uid "
"(%u < %u, file = %s)",
filename);
ret = -1;
break;
}
seq--;
continue;
}
flags);
if (array_count(&keywords) > 0) {
struct mail_keywords *kw;
MODIFY_REPLACE, kw);
}
continue;
}
ret = -1;
break;
}
/* expunged */
goto __again;
}
/* most likely a race condition: we read the
maildir, then someone else expunged messages and
committed changes to index. so, this message
shouldn't actually exist. mark it racy and check
in next sync. */
if ((uflags &
MAILDIR_UIDLIST_REC_FLAG_NONSYNCED) != 0) {
/* partial syncing */
seq--;
continue;
}
if ((uflags & MAILDIR_UIDLIST_REC_FLAG_RACING) != 0) {
"Maildir %s sync: "
"UID inserted in the middle of mailbox "
"(%u > %u, file = %s)",
ret = -1;
break;
}
seq--;
continue;
}
/* the private flags are stored only in indexes, keep them */
flags |= MAIL_RECENT;
} else {
}
}
if ((uflags & MAILDIR_UIDLIST_REC_FLAG_NONSYNCED) != 0) {
/* partial syncing */
if ((flags & MAIL_RECENT) != 0) {
/* we last saw this mail in new/, but it's
not there anymore. possibly expunged,
make sure. */
full_rescan = TRUE;
}
continue;
}
/* we haven't been able to update maildir with this
record's flag changes. don't sync them. */
continue;
}
/* FIXME: this is wrong if there's pending changes in
transaction log already. it gets fixed in next sync
however.. */
flags);
} else if ((flags & MAIL_RECENT) == 0 &&
/* just remove recent flag */
}
/* update keywords if they have changed */
ret = -1;
break;
}
struct mail_keywords *kw;
MODIFY_REPLACE, kw);
}
}
if (!partial) {
/* expunge the rest */
/* next_uid must be updated only in non-partial syncs since
partial syncs don't add the new mails to index. also we'll
have to do it here before syncing index records, since after
that the uidlist's next_uid value may have changed. */
}
}
if (!mbox->syncing_commit) {
/* now, sync the index. NOTE: may recurse back to here with
partial syncs */
if (maildir_sync_index_records(sync_ctx) < 0)
ret = -1;
}
if (mbox->dirty_cur_time == 0 &&
}
/* FIXME: use a header extension instead of sync_size.. */
} else {
}
}
if (hdr->uid_validity == 0) {
/* get the initial uidvalidity */
ret = -1;
if (uid_validity == 0) {
}
} else if (uid_validity == 0) {
hdr->uid_validity);
}
}
}
bool sync_last_commit)
{
int ret;
if (sync_last_commit) {
} else if (!forced) {
&new_changed, &cur_changed) < 0)
return -1;
if (!new_changed && !cur_changed)
return 1;
} else {
}
/*
Locking, locking, locking.. Wasn't maildir supposed to be lockless?
We can get here either as beginning a real maildir sync, or when
committing changes to maildir but a file was lost (maybe renamed).
So, we're going to need two locks. One for index and one for
uidlist. To avoid deadlocking do the uidlist lock always first.
uidlist is needed only for figuring out UIDs for newly seen files,
so theoretically we wouldn't need to lock it unless there are new
files. It has a few problems though, assuming the index lock didn't
already protect it (eg. in-memory indexes):
1. Just because you see a new file which doesn't exist in uidlist
file, doesn't mean that the file really exists anymore, or that
your readdir() lists all new files. Meaning that this is possible:
A: opendir(), readdir() -> new file ...
-- new files are written to the maildir --
B: opendir(), readdir() -> new file, lock uidlist,
readdir() -> another new file, rewrite uidlist, unlock
A: ... lock uidlist, readdir() -> nothing left, rewrite uidlist,
unlock
The second time running A didn't see the two new files. To handle
this correctly, it must not remove the new unseen files from
uidlist. This is possible to do, but adds extra complexity.
2. If another process is rename()ing files while we are
readdir()ing, it's possible that readdir() never lists some files,
causing Dovecot to assume they were expunged. In next sync they
would show up again, but client could have already been notified of
that and they would show up under new UIDs, so the damage is
already done.
Both of the problems can be avoided if we simply lock the uidlist
before syncing and keep it until sync is finished. Typically this
would happen in any case, as there is the index lock..
The second case is still a problem with external changes though,
because maildir doesn't require any kind of locking. Luckily this
problem rarely happens except under high amount of modifications.
*/
&ctx->uidlist_sync_ctx);
if (ret <= 0) {
/* failure / timeout. if forced is TRUE, we could still go
forward and check only for renamed files, but is it worth
the trouble? .. */
return ret;
}
&ctx->index_sync_ctx) < 0)
return -1;
}
if (new_changed || cur_changed) {
/* if we're going to check cur/ dir our current logic requires
that new/ dir is checked as well. it's a good idea anyway. */
/* rename()d at least some files, which might have
caused some other files to be missed. check again
(see MAILDIR_RENAME_RESCAN_COUNT). */
}
if (ret < 0)
return -1;
if (cur_changed) {
return -1;
}
/* finish uidlist syncing, but keep it still locked */
}
/* NOTE: index syncing here might cause a re-sync due to
files getting lost, so this function might be called
re-entrantly. FIXME: and that breaks in
maildir_uidlist_sync_deinit() */
ret < 0) < 0)
return -1;
if (ret < 0)
return -1;
if (ret == 0)
full_rescan = TRUE;
}
}
{
struct maildir_sync_context *ctx;
int ret;
return ret < 0 ? -1 : 0;
}
{
struct maildir_sync_context *ctx;
int ret;
return 0;
return ret < 0 ? -1 : 0;
}
struct mailbox_sync_context *
{
struct maildir_sync_context *ctx;
int ret = 0;
if ((flags & MAILBOX_SYNC_FLAG_FAST) == 0 ||
ioloop_time) {
if (ret == 0) {
/* lost some files from new/, see if thery're in cur/ */
}
}
}
{
bool new_changed, cur_changed;
int ret;
t_push();
&new_changed, &cur_changed);
t_pop();
}