1 /* guestfish - the filesystem interactive shell
2 * Copyright (C) 2009 Red Hat Inc.
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
27 #include <sys/types.h>
31 static char *expand_home (char *orig, const char *append);
32 static const char *find_home_for_username (const char *, size_t);
33 static const char *find_home_for_current_user (void);
35 /* This is called from the script loop if we find a candidate for
36 * ~username (tilde-expansion).
39 try_tilde_expansion (char *str)
41 assert (str[0] == '~');
43 /* Expand "~" to current user's home directory. */
44 if (str[1] == '\0') /* ~ */
45 return expand_home (str, NULL);
46 else if (str[1] == '/') /* ~/... */
47 return expand_home (str, &str[1]);
49 /* Try expanding the part up to the following '\0' or '/' as a
50 * username from the password file.
53 const char *home, *rest;
54 size_t len = strcspn (&str[1], "/");
57 home = find_home_for_username (&str[1], len);
60 len = strlen (home) + strlen (rest) + 1;
72 /* No match, return the orignal string. */
76 /* Return $HOME + append string. */
78 expand_home (char *orig, const char *append)
84 home = getenv ("HOME");
86 /* $HOME not set, bash can look up the current user in the
87 * password file and find their home that way. (RHBZ#617440).
89 home = find_home_for_current_user ();
94 len = strlen (home) + (append ? strlen (append) : 0) + 1;
103 strcat (str, append);
108 /* Lookup username (of length ulen), return home directory if found,
109 * or NULL if not found.
112 find_home_for_username (const char *username, size_t ulen)
117 while ((pw = getpwent ()) != NULL) {
118 if (strlen (pw->pw_name) == ulen &&
119 STREQLEN (username, pw->pw_name, ulen))
127 find_home_for_current_user (void)
130 uid_t euid = geteuid ();
133 while ((pw = getpwent ()) != NULL) {
134 if (pw->pw_uid == euid)