Damien Miller | d4a8b7e | 1999-10-27 13:42:43 +1000 | [diff] [blame] | 1 | /* |
| 2 | |
| 3 | tildexpand.c |
| 4 | |
| 5 | Author: Tatu Ylonen <ylo@cs.hut.fi> |
| 6 | |
| 7 | Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland |
| 8 | All rights reserved |
| 9 | |
| 10 | Created: Wed Jul 12 01:07:36 1995 ylo |
| 11 | |
| 12 | */ |
| 13 | |
| 14 | #include "includes.h" |
| 15 | RCSID("$Id: tildexpand.c,v 1.1 1999/10/27 03:42:46 damien Exp $"); |
| 16 | |
| 17 | #include "xmalloc.h" |
| 18 | #include "ssh.h" |
| 19 | |
| 20 | /* Expands tildes in the file name. Returns data allocated by xmalloc. |
| 21 | Warning: this calls getpw*. */ |
| 22 | |
| 23 | char *tilde_expand_filename(const char *filename, uid_t my_uid) |
| 24 | { |
| 25 | const char *cp; |
| 26 | unsigned int userlen; |
| 27 | char *expanded; |
| 28 | struct passwd *pw; |
| 29 | char user[100]; |
| 30 | |
| 31 | /* Return immediately if no tilde. */ |
| 32 | if (filename[0] != '~') |
| 33 | return xstrdup(filename); |
| 34 | |
| 35 | /* Skip the tilde. */ |
| 36 | filename++; |
| 37 | |
| 38 | /* Find where the username ends. */ |
| 39 | cp = strchr(filename, '/'); |
| 40 | if (cp) |
| 41 | userlen = cp - filename; /* Have something after username. */ |
| 42 | else |
| 43 | userlen = strlen(filename); /* Nothign after username. */ |
| 44 | if (userlen == 0) |
| 45 | pw = getpwuid(my_uid); /* Own home directory. */ |
| 46 | else |
| 47 | { |
| 48 | /* Tilde refers to someone elses home directory. */ |
| 49 | if (userlen > sizeof(user) - 1) |
| 50 | fatal("User name after tilde too long."); |
| 51 | memcpy(user, filename, userlen); |
| 52 | user[userlen] = 0; |
| 53 | pw = getpwnam(user); |
| 54 | } |
| 55 | |
| 56 | /* Check that we found the user. */ |
| 57 | if (!pw) |
| 58 | fatal("Unknown user %100s.", user); |
| 59 | |
| 60 | /* If referring to someones home directory, return it now. */ |
| 61 | if (!cp) |
| 62 | { /* Only home directory specified */ |
| 63 | return xstrdup(pw->pw_dir); |
| 64 | } |
| 65 | |
| 66 | /* Build a path combining the specified directory and path. */ |
| 67 | expanded = xmalloc(strlen(pw->pw_dir) + strlen(cp + 1) + 2); |
| 68 | sprintf(expanded, "%s/%s", pw->pw_dir, cp + 1); |
| 69 | return expanded; |
| 70 | } |