]> git.ipfire.org Git - thirdparty/util-linux.git/blob - lib/idcache.c
lib/idcache: add void to function declaration [smatch scan]
[thirdparty/util-linux.git] / lib / idcache.c
1
2 #include <wchar.h>
3 #include <pwd.h>
4 #include <grp.h>
5 #include <sys/types.h>
6
7 #include "c.h"
8 #include "idcache.h"
9
10 #ifndef LOGIN_NAME_MAX
11 #define LOGIN_NAME_MAX 256
12 #endif
13
14 struct identry *get_id(struct idcache *ic, unsigned long int id)
15 {
16 struct identry *ent;
17
18 if (!ic)
19 return NULL;
20
21 for (ent = ic->ent; ent; ent = ent->next) {
22 if (ent->id == id)
23 return ent;
24 }
25
26 return NULL;
27 }
28
29 struct idcache *new_idcache(void)
30 {
31 return calloc(1, sizeof(struct idcache));
32 }
33
34 void free_idcache(struct idcache *ic)
35 {
36 struct identry *ent = ic->ent;
37
38 while (ent) {
39 struct identry *next = ent->next;
40 free(ent->name);
41 free(ent);
42 ent = next;
43 }
44
45 free(ic);
46 }
47
48 static void add_id(struct idcache *ic, char *name, unsigned long int id)
49 {
50 struct identry *ent, *x;
51 int w = 0;
52
53 ent = calloc(1, sizeof(struct identry));
54 if (!ent)
55 return;
56 ent->id = id;
57
58 if (name) {
59 #ifdef HAVE_WIDECHAR
60 wchar_t wc[LOGIN_NAME_MAX + 1];
61
62 if (mbstowcs(wc, name, LOGIN_NAME_MAX) > 0) {
63 wc[LOGIN_NAME_MAX] = '\0';
64 w = wcswidth(wc, LOGIN_NAME_MAX);
65 }
66 else
67 #endif
68 w = strlen(name);
69 }
70
71 /* note, we ignore names with non-printable widechars */
72 if (w > 0) {
73 ent->name = strdup(name);
74 if (!ent->name) {
75 free(ent);
76 return;
77 }
78 } else {
79 if (asprintf(&ent->name, "%lu", id) < 0) {
80 free(ent);
81 return;
82 }
83 }
84
85 for (x = ic->ent; x && x->next; x = x->next);
86
87 if (x)
88 x->next = ent;
89 else
90 ic->ent = ent;
91
92 if (w <= 0)
93 w = ent->name ? strlen(ent->name) : 0;
94 ic->width = ic->width < w ? w : ic->width;
95 return;
96 }
97
98 void add_uid(struct idcache *cache, unsigned long int id)
99 {
100 struct identry *ent= get_id(cache, id);
101
102 if (!ent) {
103 struct passwd *pw = getpwuid((uid_t) id);
104 add_id(cache, pw ? pw->pw_name : NULL, id);
105 }
106 }
107
108 void add_gid(struct idcache *cache, unsigned long int id)
109 {
110 struct identry *ent = get_id(cache, id);
111
112 if (!ent) {
113 struct group *gr = getgrgid((gid_t) id);
114 add_id(cache, gr ? gr->gr_name : NULL, id);
115 }
116 }
117