File: uid_hash.c

package info (click to toggle)
acct 6.5.4-2.1
  • links: PTS
  • area: main
  • in suites: squeeze
  • size: 3,132 kB
  • ctags: 1,428
  • sloc: sh: 10,390; ansic: 9,695; cpp: 289; makefile: 185
file content (75 lines) | stat: -rw-r--r-- 1,515 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
/* uid_hash.c
 *
 * routines used by lastcomm and sa to hash data by uids
 *
 */

#include "config.h"

#include <stdio.h>
#include <pwd.h>

#ifdef HAVE_STRING_H
#include <string.h>
#endif

#include "common.h"
#include "files.h"
#include "hashtab.h"
#include "uid_hash.h"

/* globals */

struct hashtab *uid_table = NULL;

struct uid_data
{
  char *name;			/* name of the user */
};


/* code */

/* look up UID in the hash table of uids.  If it's not there, get it
 * from the password database and add it to the hash table.
 */

char *uid_name(int uid)
{
  struct hashtab_elem *he;

  if (uid_table == NULL)
    uid_table = hashtab_init(sizeof(int));

  he = hashtab_find(uid_table, (void *) &uid, sizeof(uid));

  if (he == NULL)
    {
      /* It wasn't there, so add it. */

      struct passwd *thispw = getpwuid (uid);
      struct uid_data ud;

      if (thispw != NULL)
        {
          ud.name = (char *) xmalloc(sizeof (char)* (strlen (thispw->pw_name) + 1));
          (void)strcpy(ud.name, thispw->pw_name);
        }
      else
        {
          int digits = 2, uid_copy = uid;

          /* Count the number of digits we'll need. */
          for (; uid_copy; digits++, uid_copy /= 10);

          ud.name = (char *) xmalloc (sizeof (char) * digits);
          (void)sprintf(ud.name, "%d", uid);
        }

      he = hashtab_create(uid_table, (void *) &uid, sizeof (uid));
      hashtab_set_value(he, &ud, sizeof (ud));
    }

  struct uid_data *ud = hashtab_get_value(he);
  return ud->name;
}