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 (const char *);
32 static const char *find_home_for_username (const char *, size_t);
34 /* This is called from the script loop if we find a candidate for
35 * ~username (tilde-expansion).
38 try_tilde_expansion (char *str)
40 assert (str[0] == '~');
42 /* Expand current user's home directory. By simple experimentation
43 * I found out that bash always uses $HOME.
45 if (str[1] == '\0') /* ~ */
46 return expand_home (NULL);
47 else if (str[1] == '/') /* ~/... */
48 return expand_home (&str[1]);
50 /* Try expanding the part up to the following '\0' or '/' as a
51 * username from the password file.
54 const char *home, *rest;
55 size_t len = strcspn (&str[1], "/");
58 home = find_home_for_username (&str[1], len);
61 len = strlen (home) + strlen (rest);
73 /* No match, return the orignal string. */
77 /* Return $HOME + append string. */
79 expand_home (const char *append)
85 home = getenv ("HOME");
86 if (!home) home = "~";
88 len = strlen (home) + (append ? strlen (append) : 0) + 1;
102 /* Lookup username (of length ulen), return home directory if found,
103 * or NULL if not found.
106 find_home_for_username (const char *username, size_t ulen)
111 while ((pw = getpwent ()) != NULL) {
112 if (strlen (pw->pw_name) == ulen &&
113 STREQLEN (username, pw->pw_name, ulen))