Skip to content

Commit

Permalink
mosquitto_ctrl dynsec init uses open( , O_EXCL | O_CREAT)
Browse files Browse the repository at this point in the history
This allows us to refuse to open an existing file, without a race
condition.
  • Loading branch information
ralight committed Aug 16, 2023
1 parent 00b24e0 commit 3ab0a9a
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 7 deletions.
2 changes: 2 additions & 0 deletions ChangeLog.txt
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ Clients:

Apps:
- mosquitto_passwd uses mkstemp() for backup files.
- `mosquitto_ctrl dynsec init` will refuse to overwrite an existing file,
without a race-condition.


2.0.15 - 2022-08-16
Expand Down
19 changes: 12 additions & 7 deletions apps/mosquitto_ctrl/dynsec.c
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
#include <string.h>

#ifndef WIN32
# include <errno.h>
# include <fcntl.h>
# include <strings.h>
#endif

Expand Down Expand Up @@ -739,13 +741,6 @@ static int dynsec_init(int argc, char *argv[])
admin_password = password;
}

fptr = mosquitto__fopen(filename, "rb", true);
if(fptr){
fclose(fptr);
fprintf(stderr, "dynsec init: '%s' already exists. Remove the file or use a different location..\n", filename);
return -1;
}

tree = init_create(admin_user, admin_password, "admin");
if(tree == NULL){
fprintf(stderr, "dynsec init: Out of memory.\n");
Expand All @@ -754,7 +749,17 @@ static int dynsec_init(int argc, char *argv[])
json_str = cJSON_Print(tree);
cJSON_Delete(tree);

#ifdef WIN32
fptr = mosquitto__fopen(filename, "wb", true);
#else
int fd = open(filename, O_CREAT | O_EXCL | O_WRONLY, 0640);
if(fd < 0){
free(json_str);
fprintf(stderr, "dynsec init: Unable to open '%s' for writing (%s).\n", filename, strerror(errno));
return -1;
}
fptr = fdopen(fd, "wb");
#endif
if(fptr){
fprintf(fptr, "%s", json_str);
free(json_str);
Expand Down

0 comments on commit 3ab0a9a

Please sign in to comment.