File: tildexpand.c

package info (click to toggle)
casio 2.2-9
  • links: PTS
  • area: main
  • in suites: woody
  • size: 704 kB
  • ctags: 417
  • sloc: ansic: 3,452; makefile: 90
file content (87 lines) | stat: -rw-r--r-- 1,958 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/*

tildexpand.c

Author: Tatu Ylonen <ylo@cs.hut.fi>

Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
                   All rights reserved

Created: Wed Jul 12 01:07:36 1995 ylo

*/

/*
 * $Id: tildexpand.c,v 1.2 1995/07/13 01:41:03 ylo Exp $
 * $Log: tildexpand.c,v $
 * Revision 1.2  1995/07/13  01:41:03  ylo
 * 	Removed "Last modified" header.
 * 	Added cvs log.
 *
 * $Endlog$
 */
#include <sys/types.h>
#include <string.h>
#include <pwd.h>
#include <assert.h>
#include <stdio.h>

void fatal(char *msg)
{
  fprintf(stderr, "%s\n", msg);
  exit(-1);
}

char *tilde_expand_filename(const char *filename, uid_t my_uid)
{
  const char *cp;
  unsigned int userlen;
  char *expanded;
  struct passwd *pw;
  char user[100];
  const char *homedir;

  /* Return immediately if no tilde. */
  if (filename[0] != '~')
    return strdup(filename); /* x */


  /* Skiop the tilde. */
  filename++;

  /* Find where the username ends. */
  cp = strchr(filename, '/');
  if (cp)
    userlen = cp - filename;  /* Have something after username. */
  else
    userlen = strlen(filename); /* Nothign after username. */
  if (userlen == 0)
    pw = getpwuid(my_uid);  /* Own home directory. */
  else
    {
      /* Tilde refers to someone elses home directory. */
      if (userlen > sizeof(user) - 1)
	fatal("User name after tilde too long.");
      memcpy(user, filename, userlen);
      user[userlen] = 0;
      pw = getpwnam(user);
    }
  
  /* Check that we found the user. */
  if (!pw)
    fatal(strcat("Unknown user %100s.", user));
  
  homedir = pw->pw_dir;

  /* If referring to someones home directory, return it now. */
  if (!cp)
    { /* Only home directory specified */
      return strdup(homedir); /* x */
    }
  
  /* Build a path combining the specified directory and path. */
  expanded = (char *)malloc(strlen(homedir) + strlen(cp + 1) + 2);
  assert(expanded);
  sprintf(expanded, "%s/%s", homedir, cp + 1);
  return expanded;
}