summaryrefslogtreecommitdiffstats
path: root/lib/idcache.c
blob: 2facf13e025188d029c0eb0a5f79c0a033e0150f (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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#include <wchar.h>
#include <pwd.h>
#include <grp.h>
#include <sys/types.h>

#include "c.h"
#include "idcache.h"

struct identry *get_id(struct idcache *ic, unsigned long int id)
{
	struct identry *ent;

	if (!ic)
		return NULL;

	for (ent = ic->ent; ent; ent = ent->next) {
		if (ent->id == id)
			return ent;
	}

	return NULL;
}

struct idcache *new_idcache(void)
{
	return calloc(1, sizeof(struct idcache));
}

void free_idcache(struct idcache *ic)
{
	struct identry *ent = ic->ent;

	while (ent) {
		struct identry *next = ent->next;
		free(ent->name);
		free(ent);
		ent = next;
	}

	free(ic);
}

static void add_id(struct idcache *ic, char *name, unsigned long int id)
{
	struct identry *ent, *x;
	int w = 0;

	ent = calloc(1, sizeof(struct identry));
	if (!ent)
		return;
	ent->id = id;

	if (name) {
#ifdef HAVE_WIDECHAR
		wchar_t wc[LOGIN_NAME_MAX + 1];

		if (mbstowcs(wc, name, LOGIN_NAME_MAX) > 0) {
			wc[LOGIN_NAME_MAX] = '\0';
			w = wcswidth(wc, LOGIN_NAME_MAX);
		}
		else
#endif
			w = strlen(name);
	}

	/* note, we ignore names with non-printable widechars */
	if (w > 0) {
		ent->name = strdup(name);
		if (!ent->name) {
			free(ent);
			return;
		}
	} else {
		if (asprintf(&ent->name, "%lu", id) < 0) {
			free(ent);
			return;
		}
	}

	for (x = ic->ent; x && x->next; x = x->next);

	if (x)
		x->next = ent;
	else
		ic->ent = ent;

	if (w <= 0)
		w = ent->name ? strlen(ent->name) : 0;
	ic->width = ic->width < w ? w : ic->width;
	return;
}

void add_uid(struct idcache *cache, unsigned long int id)
{
	struct identry *ent= get_id(cache, id);

	if (!ent) {
		struct passwd *pw = getpwuid((uid_t) id);
		add_id(cache, pw ? pw->pw_name : NULL, id);
	}
}

void add_gid(struct idcache *cache, unsigned long int id)
{
	struct identry *ent = get_id(cache, id);

	if (!ent) {
		struct group *gr = getgrgid((gid_t) id);
		add_id(cache, gr ? gr->gr_name : NULL, id);
	}
}