summaryrefslogtreecommitdiff
path: root/src/minutils/s6ps_pwcache.c
blob: 2f4c329206efd2ec55a0041acc2315d76baf1dda (plain)
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
/* ISC license. */

#include <sys/types.h>
#include <pwd.h>
#include <errno.h>
#include <skalibs/types.h>
#include <skalibs/stralloc.h>
#include <skalibs/genalloc.h>
#include <skalibs/skamisc.h>
#include <skalibs/avltree.h>
#include "s6-ps.h"

static avltree pwcache_tree = AVLTREE_ZERO ;
static genalloc pwcache_index = GENALLOC_ZERO ;

int s6ps_pwcache_init (void)
{
  avltree_init(&pwcache_tree, 5, 3, 8, &left_dtok, &uint_cmp, &pwcache_index) ;
  return 1 ;
}

void s6ps_pwcache_finish (void)
{
  avltree_free(&pwcache_tree) ;
  genalloc_free(dius_t, &pwcache_index) ;
}

int s6ps_pwcache_lookup (stralloc *sa, uid_t uid)
{
  int wasnull = !satmp.s ;
  dius_t d = { .left = (unsigned int)uid, .right = satmp.len } ;
  unsigned int i ;
  if (!avltree_search(&pwcache_tree, &d.left, &i))
  {
    struct passwd *pw ;
    unsigned int n = genalloc_len(dius_t, &pwcache_index) ;
    errno = 0 ;
    pw = getpwuid(uid) ;
    if (!pw)
    {
      if (errno) return 0 ;
      if (!stralloc_readyplus(&satmp, UINT_FMT + 2)) return 0 ;
      stralloc_catb(&satmp, "(", 1) ;
      satmp.len += uint_fmt(satmp.s + satmp.len, uid) ;
      stralloc_catb(&satmp, ")", 2) ;
    }
    else if (!stralloc_cats(&satmp, pw->pw_name) || !stralloc_0(&satmp)) return 0 ;
    if (!genalloc_append(dius_t, &pwcache_index, &d)) goto err ;
    if (!avltree_insert(&pwcache_tree, n))
    {
      genalloc_setlen(dius_t, &pwcache_index, n) ;
      goto err ;
    }
    i = n ;
  }
  return stralloc_cats(sa, satmp.s + genalloc_s(dius_t, &pwcache_index)[i].right) ;
 err:
  {
    int e = errno ;
    if (wasnull) stralloc_free(&satmp) ;
    else satmp.len = d.right ;
    errno = e ;
  }
  return 0 ;
}