maildir-sync.c revision b63284468d717737ecd63d78b6928c5d7f0d3634
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/ 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 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. 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. 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 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 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/ 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 /* 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. */ /* This is mostly to avoid infinite looping when rename() destination already exists as the hard link of the file itself. */ /* most likely the files just don't exist anymore. don't really care about other errors much. */ /* Files are the same. this means either a race condition between stat() calls, or that the files were link()ed. */ /* The file has hard links and it hasn't had any changes (such as renames) for a while, so this rename()ing one file on top of the other would fix this safely, except POSIX decided that rename() doesn't work that way. So we'll have unlink() one and hope that another process didn't just decide to unlink() the other (uidlist lock prevents this from "unlink(%s) failed: %m",
path2);
/* preserve S= and W= sizes if they're available. (S=size is required for zlib plugin to work) */ "Couldn't fix a duplicate: rename(%s, %s) failed: %m",
"Couldn't fix a broken filename: rename(%s, %s) failed: %m",
"opendir(%s) failed: %m",
path);
"fstat(%s) failed: %m",
path);
/* don't even try to use file with empty base name */ /* we moved it - it's \Recent for us */ /* someone else moved it already */ /* not enough disk space / read-only maildir, "rename(%s, %s) failed: %m",
/* possibly duplicate - try fixing it */ /* OS X HFS+: readdir() fails sometimes when rename() "readdir(%s) failed: %m",
path);
"closedir(%s) failed: %m",
path);
/* save the exact new times. the new mtimes should be >= "start_time", but just in case something weird happens and mtime doesn't update, use "start_time". */ i_warning(
"Maildir: Scanning %s took %u seconds " "(%u readdir()s, %u rename()s to cur/, why=0x%x)",
/* header doesn't exist */ /* try to avoid stat()ing by first checking delayed changes */ /* refresh index and try again */ /* refresh index and try again */ /* make sure uidlist's next_uid is at least as large as index file's. typically this happens only if uidlist gets /* index is up to date. get the next-uid from it */ /* if there are files in new/, we'll need to move them. we'll check this by seeing if we have any recent messages */ /* if recent messages have been externally deleted from new/, we need to get them out of index. this requires that we make sure they weren't just moved to cur/. */ /* refresh index only after the first sync, i.e. avoid wasting time on refreshing it immediately after it was just opened */ 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, 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 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. /* locking failed. sync anyway without locking so that it's possible to expunge messages when out of quota. */ /* we're already forcing a sync, we're trying to find a message that was probably already expunged, don't loop for a long time trying to find it. */ "Internal mailbox synchronization failure, " "showing only old mails.",
/* 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). */ /* finish uidlist syncing, but keep it still locked */ /* make sure we sync the maildir later */ /* NOTE: index syncing here might cause a re-sync due to files getting lost, so this function might be called /* we didn't find it, possibly expunged? */ /* refresh uidlist and check again in case it was added after the last mailbox sync */ /* we've already refreshed it, don't bother again */ /* the uidlist doesn't exist. */ /* we're racing some file. retry the sync again to see if the file is really gone or not. if it is, this is a bit of unnecessary work, but if it's not, this is necessary for e.g. doveadm force-resync to work. */ /* maybe it's expunged. check again. */ /* make sure the map stays in private memory */ /* lost some files from new/, see if thery're in cur/ */