Permalink
Browse files

add get_home_dir utility

  • Loading branch information...
1 parent 27641c7 commit 517d2ce6d5a03a0efdb66244d0e5122f37951abe @vodik committed Dec 18, 2013
Showing with 26 additions and 12 deletions.
  1. +2 −6 envoy.c
  2. +1 −6 gpg-protocol.rl
  3. +22 −0 util.c
  4. +1 −0 util.h
View
@@ -116,19 +116,15 @@ static char *get_key_path(const char *home, const char *fragment)
static _noreturn_ void add_keys(char **keys, int count)
{
/* command + end-of-opts + NULL + keys */
+ const char *home_dir = get_home_dir();
char *args[count + 3];
- struct passwd *pwd;
int i;
- pwd = getpwuid(getuid());
- if (pwd == NULL || pwd->pw_dir == NULL)
- err(EXIT_FAILURE, "failed to lookup passwd entry");
-
args[0] = "/usr/bin/ssh-add";
args[1] = "--";
for (i = 0; i < count; i++)
- args[2 + i] = get_key_path(pwd->pw_dir, keys[i]);
+ args[2 + i] = get_key_path(home_dir, keys[i]);
args[2 + count] = NULL;
View
@@ -23,7 +23,6 @@
#include <string.h>
#include <err.h>
#include <errno.h>
-#include <pwd.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/un.h>
@@ -168,11 +167,7 @@ int gpg_update_tty(struct gpg_t *gpg)
if (xauthority) {
gpg_send_message(gpg, "OPTION xauthority=%s\n", xauthority);
} else {
- struct passwd *pwd = getpwuid(getuid());
- if (pwd == NULL || pwd->pw_dir == NULL)
- err(EXIT_FAILURE, "failed to lookup passwd entry");
-
- gpg_send_message(gpg, "OPTION xauthority=%s/.Xauthority\n", pwd->pw_dir);
+ gpg_send_message(gpg, "OPTION xauthority=%s/.Xauthority\n", get_home_dir());
}
}
View
22 util.c
@@ -3,7 +3,11 @@
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
+#include <unistd.h>
#include <err.h>
+#include <pwd.h>
+
+static char *home_dir_cache = NULL;
static char *joinpath_ap(const char *root, va_list ap)
{
@@ -60,3 +64,21 @@ void safe_asprintf(char **strp, const char *fmt, ...)
err(EXIT_FAILURE, "failed to allocate memory");
va_end(ap);
}
+
+const char *get_home_dir(void)
+{
+ if (!home_dir_cache) {
+ home_dir_cache = getenv("HOME");
+
+ if (home_dir_cache && home_dir_cache[0])
+ home_dir_cache = strdup(home_dir_cache);
+ else {
+ struct passwd *pwd = getpwuid(getuid());
+ if (!pwd)
+ err(EXIT_FAILURE, "failed to get pwd entry for user");
+ home_dir_cache = strdup(pwd->pw_dir);
+ }
+ }
+
+ return home_dir_cache;
+}
View
1 util.h
@@ -35,5 +35,6 @@ static inline bool strneq(const char *s1, const char *s2, size_t n) { return str
char *joinpath(const char *root, ...);
void safe_asprintf(char **strp, const char *fmt, ...) _printf_(2, 3);
+const char *get_home_dir(void);
// vim: et:sts=4:sw=4:cino=(0

0 comments on commit 517d2ce

Please sign in to comment.