From 39fd2b127d8b64f39d8a61ced43b85de76ac8cf7 Mon Sep 17 00:00:00 2001 From: Olli Helenius Date: Thu, 12 Sep 2024 23:04:05 +0300 Subject: [PATCH] Add get_user_home Add an utility function for locating the current user's home directory using either $HOME or their passwd entry. --- src/common-utils/common-utils.c | 34 ++++++++++++++++++++++++--------- src/common-utils/common-utils.h | 1 + 2 files changed, 26 insertions(+), 9 deletions(-) diff --git a/src/common-utils/common-utils.c b/src/common-utils/common-utils.c index f24f1bf..c5bb35c 100644 --- a/src/common-utils/common-utils.c +++ b/src/common-utils/common-utils.c @@ -296,6 +296,29 @@ void nvfree(void *s) /* misc */ /****************************************************************************/ +/* + * get_user_home() - locate current user's home directory using either + * the enrivonment variable or their passwd entry. + * + * Returns NULL if the home directory cannot be located, otherwise + * returns a statically allocated string that is either the value + * of the environment variable or the passwd entry. + */ +const char *get_user_home() +{ + char *home = getenv("HOME"); + struct passwd *pw; + + if (home) return home; + + /* $HOME isn't set; get the home directory from /etc/passwd */ + + pw = getpwuid(getuid()); + if (pw) return pw->pw_dir; + + return NULL; +} + /* * tilde_expansion() - do tilde expansion on the given path name; * based loosely on code snippets found in the comp.unix.programmer @@ -310,7 +333,7 @@ void nvfree(void *s) char *tilde_expansion(const char *str) { - char *prefix = NULL; + const char *prefix = NULL; const char *replace; char *user, *ret; struct passwd *pw; @@ -324,14 +347,7 @@ char *tilde_expansion(const char *str) /* expand to the current user's home directory */ - prefix = getenv("HOME"); - if (!prefix) { - - /* $HOME isn't set; get the home directory from /etc/passwd */ - - pw = getpwuid(getuid()); - if (pw) prefix = pw->pw_dir; - } + prefix = get_user_home(); replace = str + 1; diff --git a/src/common-utils/common-utils.h b/src/common-utils/common-utils.h index 1705acf..2a60787 100644 --- a/src/common-utils/common-utils.h +++ b/src/common-utils/common-utils.h @@ -64,6 +64,7 @@ char *nvasprintf(const char *fmt, ...) NV_ATTRIBUTE_PRINTF(1, 2); void nv_append_sprintf(char **buf, const char *fmt, ...) NV_ATTRIBUTE_PRINTF(2, 3); void nvfree(void *s); +const char *get_user_home(); char *tilde_expansion(const char *str); char *nv_prepend_to_string_list(char *list, const char *item, const char *delim);