I have a password-protected web folder, and am looking for a safe way for an external admin script to update the contents of the password file.

In the past, I've just used flat password files. When changing an entry, the admin script would read the original file in and write a modified version to a temporary file, then rename the temporary file to the original filename once it was finished, so that Apache would never see a partially-written file.

I'd prefer to use some sort of DBM-style password database, where I don't have to recopy the entire password file just to update one entry. However, this would require some sort of file locking -- and since file locks in Linux are advisory, Apache would kinda need to cooperate.

I don't know much about DBM files, but I found the following information which seems to suggest that you should use something like "flock" when multiple processes might try to access a DB file concurrently:

DB_File - Perl5 access to Berkeley DB version 1.x

I did an experiment to see if Apache would automatically use "flock" when reading the database file, but no dice. Here's my httpd.conf entry:

<Files echo.pl>
AuthType Basic
AuthName "Test 1"
AuthBasicProvider dbm
AuthDBMType DB
AuthDBMUserFile /etc/mypasswdfile.db
Require valid-user

I then opened an exclusive lock from the shell as follows:

exec 5</etc/mypasswdfile.db ; flock 5

If Apache were using locks then this would cause it to hang when attempting to read the password database, but it had no effect. (It asks for a username and password and matches it against the contents of the DB file properly, but it doesn't attempt to obtain a shared lock.)

Does anyone know of a simple way to make Apache use some sort of file locking mechanism to prevent race conditions when reading a DBM-style password database?