2 * Copyright (c) 2000-2013 Apple Inc. All Rights Reserved.
4 * The contents of this file constitute Original Code as defined in and are
5 * subject to the Apple Public Source License Version 1.2 (the 'License').
6 * You may not use this file except in compliance with the License. Please obtain
7 * a copy of the License at http://www.apple.com/publicsource and read it before
10 * This Original Code and all software distributed under the License are
11 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS
12 * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT
13 * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
14 * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the
15 * specific language governing rights and limitations under the License.
19 #include <security_filedb/AtomicFile.h>
21 #include <security_utilities/devrandom.h>
22 #include <CommonCrypto/CommonDigest.h>
23 #include <security_cdsa_utilities/cssmerrors.h>
24 #include <Security/cssm.h>
29 #include <sys/param.h>
30 #include <sys/types.h>
31 #include <sys/mount.h>
41 #define kAtomicFileMaxBlockSize INT_MAX
47 AtomicFile::AtomicFile(const std::string
&inPath
) :
50 pathSplit(inPath
, mDir
, mFile
);
52 if (mDir
.length() == 0)
54 const char* buffer
= getwd(NULL
);
61 // determine if the path is on a local or a networked volume
63 int result
= statfs(mDir
.c_str(), &info
);
64 if (result
== -1) // error on opening?
66 mIsLocalFileSystem
= false; // revert to the old ways if we can't tell what kind of system we have
70 mIsLocalFileSystem
= (info
.f_flags
& MNT_LOCAL
) != 0;
71 if (mIsLocalFileSystem
)
73 // compute the name of the lock file for this file
76 CC_SHA1_Update(&ctx
, (const void*) mFile
.c_str(), (CC_LONG
)mFile
.length());
77 u_int8_t digest
[CC_SHA1_DIGEST_LENGTH
];
78 CC_SHA1_Final(digest
, &ctx
);
80 u_int32_t hash
= (digest
[0] << 24) | (digest
[1] << 16) | (digest
[2] << 8) | digest
[3];
83 sprintf(buffer
, "%08X", hash
);
84 mLockFilePath
= mDir
+ ".fl" + buffer
;
89 AtomicFile::~AtomicFile()
93 // Acquire the write lock and remove the file.
95 AtomicFile::performDelete()
97 AtomicLockedFile
lock(*this);
98 if (::unlink(mPath
.c_str()) != 0)
101 secnotice("atomicfile", "unlink %s: %s", mPath
.c_str(), strerror(error
));
103 CssmError::throwMe(CSSMERR_DL_DATASTORE_DOESNOT_EXIST
);
105 UnixError::throwMe(error
);
108 // unlink our lock file
109 ::unlink(mLockFilePath
.c_str());
112 // Acquire the write lock and rename the file (and bump the version and stuff).
114 AtomicFile::rename(const std::string
&inNewPath
)
116 const char *path
= mPath
.c_str();
117 const char *newPath
= inNewPath
.c_str();
119 // @@@ lock the destination file too.
120 AtomicLockedFile
lock(*this);
121 if (::rename(path
, newPath
) != 0)
124 secnotice("atomicfile", "rename(%s, %s): %s", path
, newPath
, strerror(error
));
125 UnixError::throwMe(error
);
129 // Lock the file for writing and return a newly created AtomicTempFile.
130 RefPointer
<AtomicTempFile
>
131 AtomicFile::create(mode_t mode
)
133 const char *path
= mPath
.c_str();
135 // First make sure the directory to this file exists and is writable
138 RefPointer
<AtomicLockedFile
> lock(new AtomicLockedFile(*this));
139 int fileRef
= ropen(path
, O_WRONLY
|O_CREAT
|O_EXCL
, mode
);
143 secnotice("atomicfile", "open %s: %s", path
, strerror(error
));
145 // Do the obvious error code translations here.
146 // @@@ Consider moving these up a level.
148 CssmError::throwMe(CSSM_ERRCODE_OS_ACCESS_DENIED
);
149 else if (error
== EEXIST
)
150 CssmError::throwMe(CSSMERR_DL_DATASTORE_ALREADY_EXISTS
);
152 UnixError::throwMe(error
);
158 // Now that we have created the lock and the new db file create a tempfile
160 RefPointer
<AtomicTempFile
> temp(new AtomicTempFile(*this, lock
, mode
));
161 secinfo("atomicfile", "%p created %s", this, path
);
166 // Creating the temp file failed so remove the db file we just created too.
167 if (::unlink(path
) == -1)
169 secnotice("atomicfile", "unlink %s: %s", path
, strerror(errno
));
175 // Lock the database file for writing and return a newly created AtomicTempFile.
176 // If the parent directory allows the write we're going to allow this. Previous
177 // versions checked for writability of the db file and that caused problems when
178 // setuid programs had made entries. As long as the db (keychain) file is readable
179 // this function can make the newer keychain file with the correct owner just by virtue
180 // of the copy that takes place.
182 RefPointer
<AtomicTempFile
>
186 RefPointer
<AtomicLockedFile
> lock(new AtomicLockedFile(*this));
187 return new AtomicTempFile(*this, lock
);
190 // Return a bufferedFile containing current version of the file for reading.
191 RefPointer
<AtomicBufferedFile
>
194 return new AtomicBufferedFile(mPath
, mIsLocalFileSystem
);
198 AtomicFile::mode() const
200 const char *path
= mPath
.c_str();
202 if (::stat(path
, &st
) == -1)
205 secinfo("atomicfile", "stat %s: %s", path
, strerror(error
));
206 UnixError::throwMe(error
);
211 // Split full into a dir and file component.
213 AtomicFile::pathSplit(const std::string
&inFull
, std::string
&outDir
, std::string
&outFile
)
215 std::string::size_type slash
, len
= inFull
.size();
216 slash
= inFull
.rfind('/');
217 if (slash
== std::string::npos
)
222 else if (slash
+ 1 == len
)
229 outDir
= inFull
.substr(0, slash
+ 1);
230 outFile
= inFull
.substr(slash
+ 1, len
);
235 // Make sure the directory up to inDir exists inDir *must* end in a slash.
238 AtomicFile::mkpath(const std::string
&inDir
, mode_t mode
)
240 // see if the file already exists and is a directory
242 int result
= stat(inDir
.c_str(), &st
);
244 if (result
== 0) // file exists
246 if ((st
.st_mode
& S_IFDIR
) == 0)
248 // whatever was there, it wasn't a directory. That's really bad, so complain
249 syslog(LOG_ALERT
, "Needed a directory at %s, but the file that was there was not one.\n", inDir
.c_str());
250 UnixError::throwMe(ENOTDIR
);
255 // the file did not exist, try to create it
256 result
= mkpath_np(inDir
.c_str(), 0777); // make the directory with umask
259 // mkpath_np does not set errno, you have to look at the result.
260 UnixError::throwMe(result
);
264 // Double check and see if we got what we hoped for
265 result
= stat(inDir
.c_str(), &st
);
268 UnixError::throwMe(errno
);
271 if ((st
.st_mode
& S_IFDIR
) == 0)
273 // we didn't create a dictionary? That's curious...
274 syslog(LOG_ALERT
, "Failed to create a directory when we asked for one to be created at %s\n", inDir
.c_str());
275 UnixError::throwMe(ENOTDIR
);
280 AtomicFile::ropen(const char *const name
, int flags
, mode_t mode
)
282 bool isCreate
= (flags
& O_CREAT
) != 0;
285 The purpose of checkForRead and checkForWrite is to mitigate
286 spamming of the log when a user has installed certain third
287 party software packages which create additional keychains.
288 Certain applications use a custom sandbox profile which do not
289 permit this and so the user gets a ton of spam in the log.
290 This turns into a serious performance problem.
292 We handle this situation by checking two factors:
294 1: If the user is trying to create a file, we send the
295 request directly to open. This is the right thing
296 to do, as we don't want most applications creating
297 keychains unless they have been expressly authorized
300 The layers above this one only set O_CREAT when a file
301 doesn't exist, so the case where O_CREAT can be called
302 on an existing file is irrelevant.
304 2: If the user is trying to open the file for reading or
305 writing, we check with the sandbox mechanism to see if
306 the operation will be permitted (and tell it not to
307 log if it the operation will fail).
309 If the operation is not permitted, we return -1 which
310 emulates the behavior of open. sandbox_check sets
311 errno properly, so the layers which call this function
312 will be able to act as though open had been called.
315 bool checkForRead
= false;
316 bool checkForWrite
= false;
318 int fd
, tries_left
= 4 /* kNoResRetry */;
322 switch (flags
& O_ACCMODE
)
328 checkForWrite
= true;
332 checkForWrite
= true;
338 int result
= sandbox_check(getpid(), "file-read-data", (sandbox_filter_type
) (SANDBOX_FILTER_PATH
| SANDBOX_CHECK_NO_REPORT
), name
);
347 int result
= sandbox_check(getpid(), "file-write-data", (sandbox_filter_type
) (SANDBOX_FILTER_PATH
| SANDBOX_CHECK_NO_REPORT
), name
);
357 fd
= ::open(name
, flags
, mode
);
358 } while (fd
< 0 && (errno
== EINTR
|| (errno
== ENFILE
&& --tries_left
>= 0)));
364 AtomicFile::rclose(int fd
)
369 result
= ::close(fd
);
370 } while(result
&& errno
== EINTR
);
376 // AtomicBufferedFile - This represents an instance of a file opened for reading.
377 // The file is read into memory and closed after this is done.
378 // The memory is released when this object is destroyed.
380 AtomicBufferedFile::AtomicBufferedFile(const std::string
&inPath
, bool isLocal
) :
388 AtomicBufferedFile::~AtomicBufferedFile()
392 // In release mode, the assert() is compiled out so rv may be unused.
393 __unused
int rv
= AtomicFile::rclose(mFileRef
);
395 secinfo("atomicfile", "%p closed %s", this, mPath
.c_str());
400 secinfo("atomicfile", "%p free %s buffer %p", this, mPath
.c_str(), mBuffer
);
406 // Open the file and return the length in bytes.
409 AtomicBufferedFile::open()
411 const char *path
= mPath
.c_str();
414 secnotice("atomicfile", "open %s: already open, closing and reopening", path
);
418 mFileRef
= AtomicFile::ropen(path
, O_RDONLY
, 0);
422 secinfo("atomicfile", "open %s: %s", path
, strerror(error
));
424 // Do the obvious error code translations here.
425 // @@@ Consider moving these up a level.
427 CssmError::throwMe(CSSMERR_DL_DATASTORE_DOESNOT_EXIST
);
428 else if (error
== EACCES
)
429 CssmError::throwMe(CSSM_ERRCODE_OS_ACCESS_DENIED
);
431 UnixError::throwMe(error
);
435 int result
= fstat(mFileRef
, &st
);
438 mLength
= st
.st_size
;
443 secinfo("atomicfile", "lseek(%s, END): %s", path
, strerror(error
));
444 AtomicFile::rclose(mFileRef
);
446 UnixError::throwMe(error
);
449 secnotice("atomicfile", "%p opened %s: %qd bytes", this, path
, mLength
);
455 // Unload the contents of the file.
458 AtomicBufferedFile::unloadBuffer()
467 // Load the contents of the file into memory.
469 AtomicBufferedFile::loadBuffer()
471 // make a buffer big enough to hold the entire file
472 mBuffer
= new uint8
[(size_t) mLength
];
473 if(lseek(mFileRef
, 0, SEEK_SET
) < 0) {
475 secinfo("atomicfile", "lseek(%s, BEGINNING): %s", mPath
.c_str(), strerror(error
));
476 UnixError::throwMe(error
);
480 ssize_t bytesToRead
= (ssize_t
)mLength
;
481 while (bytesToRead
> 0)
483 ssize_t bytesRead
= ::read(mFileRef
, mBuffer
+ pos
, bytesToRead
);
489 secinfo("atomicfile", "read(%s, %zd): %s", mPath
.c_str(), bytesToRead
, strerror(error
));
490 AtomicFile::rclose(mFileRef
);
492 UnixError::throwMe(error
);
497 bytesToRead
-= bytesRead
;
506 // Read the file starting at inOffset for inLength bytes into the buffer and return
507 // a pointer to it. On return outLength contain the actual number of bytes read, it
508 // will only ever be less than inLength if EOF was reached, and it will never be more
512 AtomicBufferedFile::read(off_t inOffset
, off_t inLength
, off_t
&outLength
)
516 secinfo("atomicfile", "read %s: file yet not opened, opening", mPath
.c_str());
520 off_t bytesLeft
= inLength
;
523 secinfo("atomicfile", "%p free %s buffer %p", this, mPath
.c_str(), mBuffer
);
529 secinfo("atomicfile", "%p allocated %s buffer %p size %qd", this, mPath
.c_str(), mBuffer
, bytesLeft
);
531 off_t maxEnd
= inOffset
+ inLength
;
532 if (maxEnd
> mLength
)
537 outLength
= maxEnd
- inOffset
;
539 return mBuffer
+ inOffset
;
543 AtomicBufferedFile::close()
547 secnotice("atomicfile", "close %s: already closed", mPath
.c_str());
551 int result
= AtomicFile::rclose(mFileRef
);
556 secnotice("atomicfile", "close %s: %s", mPath
.c_str(), strerror(errno
));
557 UnixError::throwMe(error
);
560 secinfo("atomicfile", "%p closed %s", this, mPath
.c_str());
566 // AtomicTempFile - A temporary file to write changes to.
568 AtomicTempFile::AtomicTempFile(AtomicFile
&inFile
, const RefPointer
<AtomicLockedFile
> &inLockedFile
, mode_t mode
) :
570 mLockedFile(inLockedFile
),
576 AtomicTempFile::AtomicTempFile(AtomicFile
&inFile
, const RefPointer
<AtomicLockedFile
> &inLockedFile
) :
578 mLockedFile(inLockedFile
),
581 create(mFile
.mode());
584 AtomicTempFile::~AtomicTempFile()
586 // rollback if we didn't commit yet.
592 // Open the file and return the length in bytes.
595 AtomicTempFile::create(mode_t mode
)
597 // we now generate our temporary file name through sandbox API's.
599 // put the dir into a canonical form
600 string dir
= mFile
.dir();
601 int i
= (int)dir
.length() - 1;
603 // walk backwards until we get to a non / character
604 while (i
>= 0 && dir
[i
] == '/')
609 // point one beyond the string
612 const char* temp
= _amkrtemp((dir
.substr(0, i
) + "/" + mFile
.file()).c_str());
615 UnixError::throwMe(errno
);
621 const char *path
= mPath
.c_str();
623 mFileRef
= AtomicFile::ropen(path
, O_WRONLY
|O_CREAT
|O_TRUNC
, mode
);
627 secnotice("atomicfile", "create %s: %s", path
, strerror(error
));
629 // Do the obvious error code translations here.
630 // @@@ Consider moving these up a level.
632 CssmError::throwMe(CSSM_ERRCODE_OS_ACCESS_DENIED
);
634 UnixError::throwMe(error
);
637 // If we aren't creating the inital file, make sure we preserve
638 // the mode of the old file regardless of the current umask.
639 // If we are creating the inital file we respect the users
643 if (::fchmod(mFileRef
, mode
))
646 secnotice("atomicfile", "fchmod %s: %s", path
, strerror(error
));
647 UnixError::throwMe(error
);
651 secnotice("atomicfile", "%p created %s", this, path
);
655 AtomicTempFile::write(AtomicFile::OffsetType inOffsetType
, off_t inOffset
, const uint32 inData
)
657 uint32 aData
= htonl(inData
);
658 write(inOffsetType
, inOffset
, reinterpret_cast<uint8
*>(&aData
), sizeof(aData
));
662 AtomicTempFile::write(AtomicFile::OffsetType inOffsetType
, off_t inOffset
,
663 const uint32
*inData
, uint32 inCount
)
665 #ifdef HOST_LONG_IS_NETWORK_LONG
666 // Optimize this for the case where hl == nl
667 const uint32
*aBuffer
= inData
;
669 auto_array
<uint32
> aBuffer(inCount
);
670 for (uint32 i
= 0; i
< inCount
; i
++)
671 aBuffer
.get()[i
] = htonl(inData
[i
]);
674 write(inOffsetType
, inOffset
, reinterpret_cast<const uint8
*>(aBuffer
.get()),
675 inCount
* sizeof(*inData
));
679 AtomicTempFile::write(AtomicFile::OffsetType inOffsetType
, off_t inOffset
, const uint8
*inData
, size_t inLength
)
682 if (inOffsetType
== AtomicFile::FromEnd
)
684 pos
= ::lseek(mFileRef
, 0, SEEK_END
);
688 secnotice("atomicfile", "lseek(%s, %qd): %s", mPath
.c_str(), inOffset
, strerror(error
));
689 UnixError::throwMe(error
);
692 else if (inOffsetType
== AtomicFile::FromStart
)
695 CssmError::throwMe(CSSM_ERRCODE_INTERNAL_ERROR
);
697 off_t bytesLeft
= inLength
;
698 const uint8
*ptr
= inData
;
701 size_t toWrite
= bytesLeft
> kAtomicFileMaxBlockSize
? kAtomicFileMaxBlockSize
: size_t(bytesLeft
);
702 ssize_t bytesWritten
= ::pwrite(mFileRef
, ptr
, toWrite
, pos
);
703 if (bytesWritten
== -1)
708 // We got interrupted by a signal, so try again.
709 secnotice("atomicfile", "write %s: interrupted, retrying", mPath
.c_str());
713 secnotice("atomicfile", "write %s: %s", mPath
.c_str(), strerror(error
));
714 UnixError::throwMe(error
);
717 // Write returning 0 is bad mmkay.
718 if (bytesWritten
== 0)
720 secnotice("atomicfile", "write %s: 0 bytes written", mPath
.c_str());
721 CssmError::throwMe(CSSMERR_DL_INTERNAL_ERROR
);
724 secdebug("atomicfile", "%p wrote %s %ld bytes from %p", this, mPath
.c_str(), bytesWritten
, ptr
);
726 bytesLeft
-= bytesWritten
;
733 AtomicTempFile::fsync()
737 secnotice("atomicfile", "fsync %s: already closed", mPath
.c_str());
744 result
= ::fsync(mFileRef
);
745 } while (result
&& errno
== EINTR
);
750 secnotice("atomicfile", "fsync %s: %s", mPath
.c_str(), strerror(errno
));
751 UnixError::throwMe(error
);
754 secinfo("atomicfile", "%p fsynced %s", this, mPath
.c_str());
759 AtomicTempFile::close()
763 secnotice("atomicfile", "close %s: already closed", mPath
.c_str());
767 int result
= AtomicFile::rclose(mFileRef
);
772 secnotice("atomicfile", "close %s: %s", mPath
.c_str(), strerror(errno
));
773 UnixError::throwMe(error
);
776 secinfo("atomicfile", "%p closed %s", this, mPath
.c_str());
780 // Commit the current create or write and close the write file. Note that a throw during the commit does an automatic rollback.
782 AtomicTempFile::commit()
788 const char *oldPath
= mPath
.c_str();
789 const char *newPath
= mFile
.path().c_str();
791 // <rdar://problem/6991037>
792 // Copy the security parameters of one file to another
793 // Adding this to guard against setuid utilities that are re-writing a user's keychain. We don't want to leave them root-owned.
794 // In order to not break backward compatability we'll make a best effort, but continue if these efforts fail.
796 // To clear something up - newPath is the name the keychain will become - which is the name of the file being replaced
797 // oldPath is the "temp filename".
800 s
= copyfile_state_alloc();
802 if(copyfile(newPath
, oldPath
, s
, COPYFILE_SECURITY
| COPYFILE_NOFOLLOW
) == -1) // Not fatal
803 secnotice("atomicfile", "copyfile (%s, %s): %s", oldPath
, newPath
, strerror(errno
));
805 copyfile_state_free(s
);
806 // END <rdar://problem/6991037>
808 ::utimes(oldPath
, NULL
);
810 if (::rename(oldPath
, newPath
) == -1)
813 secnotice("atomicfile", "rename (%s, %s): %s", oldPath
, newPath
, strerror(errno
));
814 UnixError::throwMe(error
);
817 secnotice("atomicfile", "%p commited %s to %s", this, oldPath
, newPath
);
819 // Unlock the lockfile
829 // Rollback the current create or write (happens automatically if commit() isn't called before the destructor is.
831 AtomicTempFile::rollback() throw()
835 AtomicFile::rclose(mFileRef
);
839 // @@@ Log errors if this fails.
840 const char *path
= mPath
.c_str();
841 if (::unlink(path
) == -1)
843 secnotice("atomicfile", "unlink %s: %s", path
, strerror(errno
));
844 // rollback can't throw
847 // @@@ Think about this. Depending on how we do locking we might not need this.
850 const char *path
= mFile
.path().c_str();
851 if (::unlink(path
) == -1)
853 secnotice("atomicfile", "unlink %s: %s", path
, strerror(errno
));
854 // rollback can't throw
861 // An advisory write lock for inFile.
863 FileLocker::~FileLocker()
869 LocalFileLocker::LocalFileLocker(AtomicFile
&inFile
) :
870 mPath(inFile
.lockFileName())
875 LocalFileLocker::~LocalFileLocker()
882 static double GetTime()
885 gettimeofday(&t
, NULL
);
886 return ((double) t
.tv_sec
) + ((double) t
.tv_usec
) / 1000000.0;
893 LocalFileLocker::lock(mode_t mode
)
899 // if the lock file doesn't exist, create it
900 mLockFile
= open(mPath
.c_str(), O_RDONLY
| O_CREAT
, mode
);
902 // if we can't open or create the file, something is wrong
905 UnixError::throwMe(errno
);
908 // try to get exclusive access to the file
909 IFDEBUG(double startTime
= GetTime());
910 int result
= flock(mLockFile
, LOCK_EX
);
911 IFDEBUG(double endTime
= GetTime());
913 IFDEBUG(secnotice("atomictime", "Waited %.4f milliseconds for file lock", (endTime
- startTime
) * 1000.0));
915 // errors at this point are bad
918 UnixError::throwMe(errno
);
921 // check and see if the file we have access to still exists. If not, another file shared our file lock
922 // due to a hash collision and has thrown our lock away -- that, or a user blew the lock file away himself.
924 result
= fstat(mLockFile
, &st
);
926 // errors at this point are bad
929 UnixError::throwMe(errno
);
932 if (st
.st_nlink
== 0) // we've been unlinked!
936 } while (st
.st_nlink
== 0);
941 LocalFileLocker::unlock()
943 flock(mLockFile
, LOCK_UN
);
949 NetworkFileLocker::NetworkFileLocker(AtomicFile
&inFile
) :
951 mPath(inFile
.dir() + "lck~" + inFile
.file())
955 NetworkFileLocker::~NetworkFileLocker()
960 NetworkFileLocker::unique(mode_t mode
)
962 static const int randomPart
= 16;
963 DevRandomGenerator randomGen
;
964 std::string::size_type dirSize
= mDir
.size();
965 std::string
fullname(dirSize
+ randomPart
+ 2, '\0');
966 fullname
.replace(0, dirSize
, mDir
);
967 fullname
[dirSize
] = '~'; /* UNIQ_PREFIX */
968 char buf
[randomPart
];
972 for (int retries
= 0; retries
< 10; ++retries
)
974 /* Make a random filename. */
975 randomGen
.random(buf
, randomPart
);
976 for (int ix
= 0; ix
< randomPart
; ++ix
)
978 char ch
= buf
[ix
] & 0x3f;
979 fullname
[ix
+ dirSize
+ 1] = ch
+
981 : ch
< 26 + 26 ? 'a' - 26
982 : ch
< 26 + 26 + 10 ? '0' - 26 - 26
983 : ch
== 26 + 26 + 10 ? '-' - 26 - 26 - 10
984 : '_' - 26 - 26 - 11);
987 result
= lstat(fullname
.c_str(), &filebuf
);
988 if (result
&& errno
== ENAMETOOLONG
)
991 fullname
.erase(fullname
.end() - 1);
992 while((result
= lstat(fullname
.c_str(), &filebuf
)) && errno
== ENAMETOOLONG
&& fullname
.size() > dirSize
+ 8);
993 } /* either it stopped being a problem or we ran out of filename */
995 if (result
&& errno
== ENOENT
)
997 fd
= AtomicFile::ropen(fullname
.c_str(), O_WRONLY
|O_CREAT
|O_EXCL
, mode
);
998 if (fd
>= 0 || errno
!= EEXIST
)
1006 ::syslog(LOG_ERR
, "Couldn't create temp file %s: %s", fullname
.c_str(), strerror(error
));
1007 secnotice("atomicfile", "Couldn't create temp file %s: %s", fullname
.c_str(), strerror(error
));
1008 UnixError::throwMe(error
);
1011 /* @@@ Check for EINTR. */
1012 write(fd
, "0", 1); /* pid 0, `works' across networks */
1014 AtomicFile::rclose(fd
);
1019 /* Return 0 on success and 1 on failure if st is set to the result of stat(old) and -1 on failure if the stat(old) failed. */
1021 NetworkFileLocker::rlink(const char *const old
, const char *const newn
, struct stat
&sto
)
1023 int result
= ::link(old
,newn
);
1027 if (::lstat(old
, &sto
) == 0)
1030 if (::lstat(newn
, &stn
) == 0
1031 && sto
.st_dev
== stn
.st_dev
1032 && sto
.st_ino
== stn
.st_ino
1033 && sto
.st_uid
== stn
.st_uid
1034 && sto
.st_gid
== stn
.st_gid
1035 && !S_ISLNK(sto
.st_mode
))
1037 /* Link failed but files are the same so the link really went ok. */
1043 errno
= serrno
; /* Restore errno from link() */
1049 /* NFS-resistant rename()
1050 * rename with fallback for systems that don't support it
1051 * Note that this does not preserve the contents of the file. */
1053 NetworkFileLocker::myrename(const char *const old
, const char *const newn
)
1059 /* Try a real hardlink */
1060 ret
= rlink(old
, newn
, stbuf
);
1063 if (stbuf
.st_nlink
< 2 && (errno
== EXDEV
|| errno
== ENOTSUP
))
1065 /* Hard link failed so just create a new file with O_EXCL instead. */
1066 fd
= AtomicFile::ropen(newn
, O_WRONLY
|O_CREAT
|O_EXCL
, stbuf
.st_mode
);
1072 /* We want the errno from the link or the ropen, not that of the unlink. */
1075 /* Unlink the temp file. */
1078 AtomicFile::rclose(fd
);
1085 NetworkFileLocker::xcreat(const char *const name
, mode_t mode
, time_t &tim
)
1087 std::string uniqueName
= unique(mode
);
1088 const char *uniquePath
= uniqueName
.c_str();
1089 struct stat stbuf
; /* return the filesystem time to the caller */
1090 stat(uniquePath
, &stbuf
);
1091 tim
= stbuf
.st_mtime
;
1092 return myrename(uniquePath
, name
);
1096 NetworkFileLocker::lock(mode_t mode
)
1098 const char *path
= mPath
.c_str();
1099 bool triedforce
= false;
1101 time_t t
, locktimeout
= 1024; /* DEFlocktimeout, 17 minutes. */
1102 bool doSyslog
= false;
1103 bool failed
= false;
1108 /* Don't syslog first time through. */
1110 ::syslog(LOG_NOTICE
, "Locking %s", path
);
1114 secinfo("atomicfile", "Locking %s", path
); /* in order to cater for clock skew: get */
1115 if (!xcreat(path
, mode
, t
)) /* time t from the filesystem */
1117 /* lock acquired, hurray! */
1122 case EEXIST
: /* check if it's time for a lock override */
1123 if (!lstat(path
, &stbuf
) && stbuf
.st_size
<= 16 /* MAX_locksize */ && locktimeout
1124 && !lstat(path
, &stbuf
) && locktimeout
< t
- stbuf
.st_mtime
)
1125 /* stat() till unlink() should be atomic, but can't guarantee that. */
1129 /* Already tried, force lock override, not trying again */
1133 else if (S_ISDIR(stbuf
.st_mode
) || ::unlink(path
))
1136 ::syslog(LOG_ERR
, "Forced unlock denied on %s", path
);
1137 secnotice("atomicfile", "Forced unlock denied on %s", path
);
1141 ::syslog(LOG_ERR
, "Forcing lock on %s", path
);
1142 secnotice("atomicfile", "Forcing lock on %s", path
);
1143 sleep(16 /* DEFsuspend */);
1148 triedforce
= false; /* legitimate iteration, clear flag */
1150 /* Reset retry counter. */
1155 case ENOSPC
: /* no space left, treat it as a transient */
1156 #ifdef EDQUOT /* NFS failure */
1157 case EDQUOT
: /* maybe it was a short term shortage? */
1163 if(++retries
< (256 + 1)) /* nfsTRY number of times+1 to ignore spurious NFS errors */
1170 case ENAMETOOLONG
: /* Filename is too long, shorten and retry */
1171 if (mPath
.size() > mDir
.size() + 8)
1173 secnotice("atomicfile", "Truncating %s and retrying lock", path
);
1174 mPath
.erase(mPath
.end() - 1);
1175 path
= mPath
.c_str();
1176 /* Reset retry counter. */
1191 ::syslog(LOG_ERR
, "Lock failure on %s: %s", path
, strerror(error
));
1192 secnotice("atomicfile", "Lock failure on %s: %s", path
, strerror(error
));
1193 UnixError::throwMe(error
);
1198 NetworkFileLocker::unlock()
1200 const char *path
= mPath
.c_str();
1201 if (::unlink(path
) == -1)
1203 secnotice("atomicfile", "unlink %s: %s", path
, strerror(errno
));
1204 // unlock can't throw
1210 AtomicLockedFile::AtomicLockedFile(AtomicFile
&inFile
)
1212 if (inFile
.isOnLocalFileSystem())
1214 mFileLocker
= new LocalFileLocker(inFile
);
1218 mFileLocker
= new NetworkFileLocker(inFile
);
1226 AtomicLockedFile::~AtomicLockedFile()
1235 AtomicLockedFile::lock(mode_t mode
)
1237 mFileLocker
->lock(mode
);
1242 void AtomicLockedFile::unlock() throw()
1244 mFileLocker
->unlock();
1249 #undef kAtomicFileMaxBlockSize