1
0
mirror of https://github.com/gryf/wmaker.git synced 2025-12-23 14:42:29 +01:00

WUtil: Avoid memory leak and misbehaviour on internal function 'getuserhomedir'

If the function was called more than once with different usernames
it would always return the path for the user on the first call,
which is not what would be expected.

Furthermore, if the function succeeds it allocated memory to save
this path but it was never freed.

The good thing is that the use case for this function is so rare
that it is improbable it was ever called, which explains why it
was never seen.

The new code always behaves as expected, and does not allocate
memory anymore to avoid wasting time and memory for such small
things, which is acceptable because this function is local.

Signed-off-by: Christophe CURIS <christophe.curis@free.fr>
This commit is contained in:
Christophe CURIS
2013-06-09 16:28:48 +02:00
committed by Carlos R. Mafra
parent 7889c50c36
commit 3c2fc82b6e

View File

@@ -67,25 +67,31 @@ char *wgethomedir()
return home; return home;
} }
static char *getuserhomedir(const char *username) /*
* Return the home directory for the specified used
*
* If user not found, returns NULL, otherwise always returns a path that is
* statically stored.
*
* Please note you must use the path before any other call to 'getpw*' or it
* may be erased. This is a design choice to avoid duplication considering
* the use case for this function.
*/
static const char *getuserhomedir(const char *username)
{ {
static char *home = NULL; static const char default_home[] = "/";
struct passwd *user; struct passwd *user;
if (home)
return home;
user = getpwnam(username); user = getpwnam(username);
if (!user) { if (!user) {
werror(_("could not get password entry for user %s"), username); werror(_("could not get password entry for user %s"), username);
return NULL; return NULL;
} }
if (!user->pw_dir) if (!user->pw_dir)
home = "/"; return default_home;
else else
home = wstrdup(user->pw_dir); return user->pw_dir;
return home;
} }
char *wexpandpath(const char *path) char *wexpandpath(const char *path)
@@ -98,7 +104,7 @@ char *wexpandpath(const char *path)
memset(buffer, 0, PATH_MAX + 2); memset(buffer, 0, PATH_MAX + 2);
if (*path == '~') { if (*path == '~') {
char *home; const char *home;
path++; path++;
if (*path == '/' || *path == 0) { if (*path == '/' || *path == 0) {