Skip to content

Commit

Permalink
src/libudev/conf-files.c: fix bug of using basename
Browse files Browse the repository at this point in the history
BASENAME(3) Linux Programmer's Manual say:
> These functions may return pointers to statically allocated memory
> which may be overwritten by subsequent calls.

Using basename return value as key of hashmap is not safe, it may
cause that hashmap_put always return -EEXIST if hash collision happen.

Using basename return value as strcmp first and second parameters may
always return 0.

Signed-off-by: xiaofan <xiaofan@iscas.ac.cn>
  • Loading branch information
xfan1024 authored and xiaofan committed Oct 6, 2021
1 parent be70685 commit 56bc3eb
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 3 deletions.
4 changes: 2 additions & 2 deletions src/shared/conf-files.c
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ static int files_add(Hashmap *h, const char *root, const char *path, const char
if (!p)
return -ENOMEM;

r = hashmap_put(h, basename(p), p);
r = hashmap_put(h, eudev_basename(p), p);
if (r == -EEXIST) {
log_debug("Skipping overridden file: %s.", p);
free(p);
Expand All @@ -92,7 +92,7 @@ static int base_cmp(const void *a, const void *b) {

s1 = *(char * const *)a;
s2 = *(char * const *)b;
return strcmp(basename(s1), basename(s2));
return strcmp(eudev_basename(s1), eudev_basename(s2));
}

static int conf_files_list_strv_internal(char ***strv, const char *suffix, const char *root, char **dirs) {
Expand Down
10 changes: 9 additions & 1 deletion src/shared/util.c
Original file line number Diff line number Diff line change
Expand Up @@ -1725,7 +1725,7 @@ int tempfn_xxxxxx(const char *p, char **ret) {
* /foo/bar/.#waldoXXXXXX
*/

fn = basename((char*)p);
fn = eudev_basename(p);
if (!filename_is_valid(fn))
return -EINVAL;

Expand Down Expand Up @@ -1967,3 +1967,11 @@ void cmsg_close_all(struct msghdr *mh) {
if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS)
close_many((int*) CMSG_DATA(cmsg), (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int));
}

const char *eudev_basename(const char *filename) {
const char *p = strrchr(filename, '/');

if (p)
return p + 1;
return filename;
}
1 change: 1 addition & 0 deletions src/shared/util.h
Original file line number Diff line number Diff line change
Expand Up @@ -433,3 +433,4 @@ union inotify_event_buffer {
};

void cmsg_close_all(struct msghdr *mh);
const char *eudev_basename(const char *filename);

0 comments on commit 56bc3eb

Please sign in to comment.