diff --git a/lib/isc/include/isc/file.h b/lib/isc/include/isc/file.h index 7ccdcb6b76..d306cbbe80 100644 --- a/lib/isc/include/isc/file.h +++ b/lib/isc/include/isc/file.h @@ -15,7 +15,7 @@ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ -/* $Id: file.h,v 1.11 2000/09/08 21:46:58 gson Exp $ */ +/* $Id: file.h,v 1.12 2000/10/03 05:45:38 marka Exp $ */ #ifndef ISC_FILE_H #define ISC_FILE_H 1 @@ -171,6 +171,22 @@ isc_file_isabsolute(const char *filename); * Return ISC_TRUE iff the given file name is absolute. */ +isc_result_t +isc_file_template(const char *path, const char *templat, char *buf, + size_t buflen); +/* + * Create a OS specific template using 'path' to define the directory + * 'templat' to describe the filename and store the result in 'buf' + * such that path can be renamed to buf atomically. + */ + +isc_result_t +isc_file_renameunique(const char *file, char *templet); + +/* + * Rename 'file' using 'templet' as template for the new file name. + */ + /* * XXX We should also have a isc_file_writeeopen() function * for safely open a file in a publicly writable directory diff --git a/lib/isc/unix/file.c b/lib/isc/unix/file.c index bec600406e..cde307250d 100644 --- a/lib/isc/unix/file.c +++ b/lib/isc/unix/file.c @@ -15,7 +15,7 @@ * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ -/* $Id: file.c,v 1.22 2000/09/08 21:46:59 gson Exp $ */ +/* $Id: file.c,v 1.23 2000/10/03 05:45:39 marka Exp $ */ #include @@ -117,29 +117,59 @@ isc_file_settime(const char *file, isc_time_t *time) { isc_result_t isc_file_mktemplate(const char *path, char *buf, size_t buflen) { + return (isc_file_template(path, TEMPLATE, buf, buflen)); +} + +isc_result_t +isc_file_template(const char *path, const char *templat, char *buf, + size_t buflen) { char *s; REQUIRE(buf != NULL); + s = strrchr(templat, '/'); + if (s != NULL) + templat = s + 1; + s = strrchr(path, '/'); if (s != NULL) { - if ((s - path + 1 + sizeof(TEMPLATE)) > buflen) + if ((s - path + 1 + strlen(templat) + 1) > buflen) return (ISC_R_NOSPACE); strncpy(buf, path, s - path + 1); buf[s - path + 1] = '\0'; - strcat(buf, TEMPLATE); + strcat(buf, templat); } else { - if (sizeof(TEMPLATE) > buflen) + if ((strlen(templat) + 1) > buflen) return (ISC_R_NOSPACE); - strcpy(buf, TEMPLATE); + strcpy(buf, templat); } return (ISC_R_SUCCESS); } +isc_result_t +isc_file_renameunique(const char *file, char *templet) { + int fd = -1; + int res = 0; + isc_result_t result = ISC_R_SUCCESS; + + fd = mkstemp(templet); + if (fd == -1) { + result = isc__errno2result(errno); + } + if (result == ISC_R_SUCCESS) { + res = rename(file, templet); + if (res != 0) + result = isc__errno2result(errno); + } + if (fd != -1) + close(fd); + return (result); +} + isc_result_t isc_file_openunique(char *templet, FILE **fp) { int fd;