ACL: less error prone error handling in ACLSaveToFile().

This commit is contained in:
antirez 2019-02-22 12:41:57 +01:00
parent 2d3cad684c
commit 2bea3929d0

View File

@ -1268,7 +1268,9 @@ sds ACLLoadFromFile(const char *filename) {
* When C_ERR is returned a log is produced with hints about the issue. */ * When C_ERR is returned a log is produced with hints about the issue. */
int ACLSaveToFile(const char *filename) { int ACLSaveToFile(const char *filename) {
sds acl = sdsempty(); sds acl = sdsempty();
int fd; int fd = -1;
sds tmpfilename = NULL;
int retval = C_ERR;
/* Let's generate an SDS string containing the new version of the /* Let's generate an SDS string containing the new version of the
* ACL file. */ * ACL file. */
@ -1291,40 +1293,37 @@ int ACLSaveToFile(const char *filename) {
raxStop(&ri); raxStop(&ri);
/* Create a temp file with the new content. */ /* Create a temp file with the new content. */
sds tmpfilename = sdsnew(filename); tmpfilename = sdsnew(filename);
tmpfilename = sdscatfmt(tmpfilename,".tmp-%i-%I", tmpfilename = sdscatfmt(tmpfilename,".tmp-%i-%I",
(int)getpid(),(int)mstime()); (int)getpid(),(int)mstime());
if ((fd = open(tmpfilename,O_WRONLY|O_CREAT,0644)) == -1) { if ((fd = open(tmpfilename,O_WRONLY|O_CREAT,0644)) == -1) {
serverLog(LL_WARNING,"Opening temp ACL file for ACL SAVE: %s", serverLog(LL_WARNING,"Opening temp ACL file for ACL SAVE: %s",
strerror(errno)); strerror(errno));
sdsfree(tmpfilename); goto cleanup;
sdsfree(acl);
return C_ERR;
} }
/* Write it. */ /* Write it. */
if (write(fd,acl,sdslen(acl)) != (ssize_t)sdslen(acl)) { if (write(fd,acl,sdslen(acl)) != (ssize_t)sdslen(acl)) {
serverLog(LL_WARNING,"Writing ACL file for ACL SAVE: %s", serverLog(LL_WARNING,"Writing ACL file for ACL SAVE: %s",
strerror(errno)); strerror(errno));
close(fd); goto cleanup;
unlink(tmpfilename);
sdsfree(tmpfilename);
sdsfree(acl);
return C_ERR;
} }
close(fd); close(fd); fd = -1;
sdsfree(acl);
/* Let's replace the new file with the old one. */ /* Let's replace the new file with the old one. */
if (rename(tmpfilename,filename) == -1) { if (rename(tmpfilename,filename) == -1) {
serverLog(LL_WARNING,"Renaming ACL file for ACL SAVE: %s", serverLog(LL_WARNING,"Renaming ACL file for ACL SAVE: %s",
strerror(errno)); strerror(errno));
unlink(tmpfilename); goto cleanup;
sdsfree(tmpfilename);
return C_ERR;
} }
sdsfree(tmpfilename); tmpfilename = NULL;
retval = C_OK; /* If we reached this point, everything is fine. */
cleanup:
if (fd != -1) close(fd);
if (tmpfilename) unlink(tmpfilename);
sdsfree(tmpfilename); sdsfree(tmpfilename);
sdsfree(acl);
return C_OK; return C_OK;
} }