From: Timo Sirainen Date: Tue, 8 Sep 2015 15:49:00 +0000 (+0300) Subject: lib: Added i_unlink() and i_unlink_if_exists() X-Git-Tag: 2.2.19.rc1~59 X-Git-Url: http://git.ipfire.org/?a=commitdiff_plain;h=8dc04cf60ea2f2d176ce4e5ca36c050e4c0a858b;p=thirdparty%2Fdovecot%2Fcore.git lib: Added i_unlink() and i_unlink_if_exists() These log the error message on a failed unlink(). They also include the source code file and line number to make it easier to find which unlink() actually failed if the path itself doesn't already clearly identify it. This can be especially useful if the path is (null), "" or contains some corrupted garbage. --- diff --git a/src/lib/lib.c b/src/lib/lib.c index 43478ddef1..e06cb61eb4 100644 --- a/src/lib/lib.c +++ b/src/lib/lib.c @@ -30,6 +30,33 @@ int close_keep_errno(int *fd) return ret; } +#undef i_unlink +int i_unlink(const char *path, const char *source_fname, + unsigned int source_linenum) +{ + if (unlink(path) < 0) { + i_error("unlink(%s) failed: %m (in %s:%u)", + path, source_fname, source_linenum); + return -1; + } + return 0; +} + +#undef i_unlink_if_exists +int i_unlink_if_exists(const char *path, const char *source_fname, + unsigned int source_linenum) +{ + if (unlink(path) == 0) + return 1; + else if (errno == ENOENT) + return 0; + else { + i_error("unlink(%s) failed: %m (in %s:%u)", + path, source_fname, source_linenum); + return -1; + } +} + void lib_atexit(lib_atexit_callback_t *callback) { lib_atexit_priority(callback, 0); diff --git a/src/lib/lib.h b/src/lib/lib.h index 2102d195f2..bec259d5c2 100644 --- a/src/lib/lib.h +++ b/src/lib/lib.h @@ -49,6 +49,16 @@ typedef void lib_atexit_callback_t(void); #define LIB_ATEXIT_PRIORITY_LOW 10 int close_keep_errno(int *fd); +/* Call unlink(). If it fails, log an error including the source filename + and line number. */ +int i_unlink(const char *path, const char *source_fname, + unsigned int source_linenum); +#define i_unlink(path) i_unlink(path, __FILE__, __LINE__) +/* Same as i_unlink(), but don't log an error if errno=ENOENT. Returns 1 on + unlink() success, 0 if errno=ENOENT, -1 on other errors. */ +int i_unlink_if_exists(const char *path, const char *source_fname, + unsigned int source_linenum); +#define i_unlink_if_exists(path) i_unlink_if_exists(path, __FILE__, __LINE__) /* Call the given callback at the beginning of lib_deinit(). The main difference to atexit() is that liblib's memory allocation and logging