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.
28 #include <sys/types.h>
32 static char *expand_home (const char *);
33 static const char *find_home_for_username (const char *, size_t);
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 current user's home directory. By simple experimentation
44 * I found out that bash always uses $HOME.
46 if (str[1] == '\0') /* ~ */
47 return expand_home (NULL);
48 else if (str[1] == '/') /* ~/... */
49 return expand_home (&str[1]);
51 /* Try expanding the part up to the following '\0' or '/' as a
52 * username from the password file.
55 const char *home, *rest;
56 size_t len = strcspn (&str[1], "/");
59 home = find_home_for_username (&str[1], len);
62 len = strlen (home) + strlen (rest);
74 /* No match, return the orignal string. */
78 /* Return $HOME + append string. */
80 expand_home (const char *append)
86 home = getenv ("HOME");
87 if (!home) home = "~";
89 len = strlen (home) + (append ? strlen (append) : 0);
103 /* Lookup username (of length ulen), return home directory if found,
104 * or NULL if not found.
107 find_home_for_username (const char *username, size_t ulen)
112 while ((pw = getpwent ()) != NULL) {
113 if (strlen (pw->pw_name) == ulen &&
114 strncmp (username, pw->pw_name, ulen) == 0)