Add \brief command to file header to make doxygen happy.
[adu.git] / user.c
1 /*
2 * Copyright (C) 2008 Andre Noll <maan@systemlinux.org>
3 *
4 * Licensed under the GPL v2. For licencing details see COPYING.
5 */
6
7 /** \file user.c \brief User and user ID handling. */
8
9 #include "adu.h"
10 #include <dirent.h> /* readdir() */
11 #include <sys/types.h>
12 #include <pwd.h>
13 #include "cmdline.h" /* TODO: This file should be independent of command line options */
14 #include "user.h"
15 #include "fd.h"
16 #include "string.h"
17 #include "error.h"
18
19 /**
20 * Describes one range of admissible user IDs.
21 *
22 * adu converts the admissible user ids given at the command line
23 * into an array of such structs.
24 */
25 struct uid_range {
26 /** Lowest admissible user ID. */
27 uint32_t low;
28 /** Greatest admissible user ID. */
29 uint32_t high;
30 };
31
32 /** Iterate over all uid ranges. */
33 #define FOR_EACH_UID_RANGE(ur, urs) for (ur = urs; ur->low <= ur->high; ur++)
34
35 /** Flags for the user hash table. */
36 enum uid_info_flags {
37 /** Whether this slot of the hash table is used. */
38 UI_FL_SLOT_USED = 1,
39 /** Whether this uid should be taken into account. */
40 UI_FL_ADMISSIBLE = 2,
41 };
42
43 /*
44 * Contains info for each user that owns at least one regular file.
45 *
46 * Even users that are not taken into account because of the --uid
47 * option occupy a slot in this hash table. This allows to find out
48 * quicky whether a uid is admissible. And yes, this has to be fast.
49 */
50 static struct user_info *uid_hash_table;
51
52 /** This is always a power of two. It is set in create_hash_table(). */
53 static uint32_t uid_hash_table_size;
54
55 /* Array of indices to the entries of \a uid_hash_table. */
56 static int *uid_hash_table_sort_idx;
57
58 /** The number of used slots in the hash table. */
59 static uint32_t num_uids;
60
61 /*
62 * The columns of the per-user tables.
63 *
64 * Adu tracks disk usage on a per-user basis. For each user, a user table is
65 * being created. The rows of the user table have three columns: The directory
66 * number that may be resolved to the path using the directory table, the
67 * number of bytes and the number of files in that directory owned by the given
68 * user.
69 */
70 static struct osl_column_description user_table_cols[] = {
71 [UT_DIR_NUM] = {
72 .storage_type = OSL_MAPPED_STORAGE,
73 .storage_flags = OSL_RBTREE | OSL_FIXED_SIZE | OSL_UNIQUE,
74 .name = "dir_num",
75 .compare_function = uint64_compare,
76 .data_size = sizeof(uint64_t)
77 },
78 [UT_BYTES] = {
79 .storage_type = OSL_MAPPED_STORAGE,
80 .storage_flags = OSL_RBTREE | OSL_FIXED_SIZE,
81 .compare_function = size_compare,
82 .name = "num_bytes",
83 .data_size = sizeof(uint64_t)
84 },
85 [UT_FILES] = {
86 .storage_type = OSL_MAPPED_STORAGE,
87 .storage_flags = OSL_RBTREE | OSL_FIXED_SIZE,
88 .compare_function = size_compare,
89 .name = "num_files",
90 .data_size = sizeof(uint64_t)
91 },
92 };
93
94 static int check_uid_arg(const char *arg, uint32_t *uid)
95 {
96 const uint32_t max = ~0U;
97 /*
98 * we need an 64-bit int for string -> uid conversion because strtoll()
99 * returns a signed value.
100 */
101 int64_t val;
102 int ret = atoi64(arg, &val);
103
104 if (ret < 0)
105 return ret;
106 if (val < 0 || val > max)
107 return -ERRNO_TO_ERROR(EINVAL);
108 *uid = val;
109 return 1;
110 }
111
112 static int parse_uid_range(const char *orig_arg, struct uid_range *ur)
113 {
114 int ret;
115 char *arg = adu_strdup(orig_arg), *p = strchr(arg, '-');
116
117 if (!p || p == arg) { /* -42 or 42 */
118 ret = check_uid_arg(p? p + 1 : arg, &ur->high);
119 if (ret < 0)
120 goto out;
121 ur->low = p? 0 : ur->high;
122 ret = 1;
123 goto out;
124 }
125 /* 42- or 42-4711 */
126 *p = '\0';
127 p++;
128 ret = check_uid_arg(arg, &ur->low);
129 if (ret < 0)
130 goto out;
131 ur->high = ~0U;
132 if (*p) { /* 42-4711 */
133 ret = check_uid_arg(p, &ur->high);
134 if (ret < 0)
135 goto out;
136 }
137 if (ur->low > ur->high)
138 ret = -ERRNO_TO_ERROR(EINVAL);
139 out:
140 if (ret < 0)
141 ERROR_LOG("bad uid option: %s\n", orig_arg);
142 else
143 INFO_LOG("admissible uid range: %u - %u\n", ur->low,
144 ur->high);
145 free(arg);
146 return ret;
147 }
148
149 /**
150 * Convert the --uid argument to an array of uid ranges.
151 *
152 * \param orig_arg The argument to the --uid option.
153 * \param ur Result pointer.
154 *
155 * Returns Negative on errors. On success, the number of uid ranges
156 * is returned.
157 */
158 int parse_uid_arg(const char *orig_arg, struct uid_range **ur)
159 {
160 char *arg, **argv;
161 unsigned n;
162 int i, ret = 1;
163
164 if (!orig_arg)
165 return 0;
166 arg = adu_strdup(orig_arg);
167 n = split_args(arg, &argv, ",");
168 if (!n)
169 return -E_SYNTAX;
170 *ur = adu_malloc((n + 1) * sizeof(struct uid_range));
171 for (i = 0; i < n; i++) {
172 ret = parse_uid_range(argv[i], *ur + i);
173 if (ret < 0)
174 break;
175 }
176 free(argv);
177 free(arg);
178 if (ret < 0) {
179 free(*ur);
180 *ur = NULL;
181 return ret;
182 }
183 /* an empty range indicates the end of the list */
184 (*ur)[n].low = 1;
185 (*ur)[n].high = 0;
186 return n;
187 }
188
189 static int uid_is_admissible(uint32_t uid, struct uid_range *urs)
190 {
191 struct uid_range *ur;
192 int ret = 1;
193
194 if (!urs) /* empty array means all uids are allowed */
195 return 1;
196 FOR_EACH_UID_RANGE(ur, urs)
197 if (ur->low <= uid && ur->high >= uid)
198 goto out;
199 ret = 0;
200 out:
201 DEBUG_LOG("uid %u is %sadmissible\n", (unsigned)uid,
202 ret? "" : "not ");
203 return ret;
204 }
205
206 /**
207 * Add each given user to the array of admissible users.
208 *
209 * \param users Array of user names to add.
210 * \param num_users Length of \a users.
211 * \param admissible_uids The users which are already admissible.
212 * \param num_uid_ranges The number of intervals of \a admissible_uids.
213 *
214 * For each given user, the function checks whether that user is already
215 * admissible, i.e. its uid is contained in one of the ranges given by \a
216 * admissible_uids. If it is, the function ignores that user. Otherwise, a new
217 * length-one range consisting of that uid only is appended to \a
218 * admissible_uids.
219 *
220 * \return Negative on errors, the new number of uid ranges on success.
221 */
222 int append_users(char **users, int num_users,
223 struct uid_range **admissible_uids, int num_uid_ranges)
224 {
225 int i;
226 struct uid_range *au = *admissible_uids;
227
228 for (i = 0; i < num_users; i++) {
229 char *u = users[i];
230 struct uid_range *ur;
231 struct passwd *pw = getpwnam(u);
232
233 if (!pw) {
234 ERROR_LOG("user %s not found\n", u);
235 return -ERRNO_TO_ERROR(EINVAL);
236 }
237 if (au && uid_is_admissible(pw->pw_uid, au))
238 continue; /* nothing to do */
239 /* add a range consisting of this uid only */
240 num_uid_ranges++;
241 au = adu_realloc(au, (num_uid_ranges + 1) *
242 sizeof(struct uid_range));
243 *admissible_uids = au;
244 ur = au + num_uid_ranges - 1; /* the new uid range */
245 ur->low = ur->high = pw->pw_uid;
246 /* terminate the list */
247 ur++;
248 ur->low = 1;
249 ur->high = 0;
250 }
251 return num_uid_ranges;
252 }
253
254 static inline int ui_used(struct user_info *ui)
255 {
256 return ui->flags & UI_FL_SLOT_USED;
257 }
258
259 static inline int ui_admissible(struct user_info *ui)
260 {
261 return ui->flags & UI_FL_ADMISSIBLE;
262 }
263
264 static int open_user_table(struct user_info *ui, int create)
265 {
266 int ret;
267 struct passwd *pw;
268
269 ui->desc = adu_malloc(sizeof(*ui->desc));
270 ui->desc->num_columns = NUM_UT_COLUMNS;
271 ui->desc->flags = 0;
272 ui->desc->column_descriptions = user_table_cols;
273 ui->desc->dir = adu_strdup(conf.database_dir_arg);
274 ui->desc->name = make_message("%u", (unsigned)ui->uid);
275 pw = getpwuid(ui->uid);
276 if (pw && pw->pw_name)
277 ui->pw_name = adu_strdup(pw->pw_name);
278
279 INFO_LOG("opening table for uid %u\n", (unsigned)ui->uid);
280 if (create) {
281 ret = osl(osl_create_table(ui->desc));
282 if (ret < 0)
283 goto err;
284 num_uids++;
285 }
286 ret = osl(osl_open_table(ui->desc, &ui->table));
287 if (ret < 0)
288 goto err;
289 return 1;
290 err:
291 free((char *)ui->desc->name);
292 free((char *)ui->desc->dir);
293 free(ui->pw_name);
294 free(ui->desc);
295 ui->desc->name = NULL;
296 ui->desc->dir = NULL;
297 ui->desc = NULL;
298 ui->table = NULL;
299 ui->flags = 0;
300 return ret;
301 }
302
303 /** Iterate over each user in the uid hash table. */
304 #define FOR_EACH_USER(ui) for (ui = uid_hash_table; ui < \
305 uid_hash_table + uid_hash_table_size; ui++)
306
307
308 /**
309 * Execute the given function for each admissible user.
310 *
311 * \param func The function to execute.
312 * \param data Arbitrary pointer.
313 *
314 * This function calls \a func for each admissible user in the uid hash table.
315 * The \a data pointer is passed as the second argument to \a func.
316 *
317 * \return As soon as \a func returns a negative value, the loop is terminated
318 * and that negative value is returned. Otherwise, the function returns 1.
319 */
320 int for_each_admissible_user(int (*func)(struct user_info *, void *),
321 void *data)
322 {
323 int i;
324
325 assert(uid_hash_table);
326 for (i = 0; i < uid_hash_table_size; i++) {
327 int ret;
328 struct user_info *ui = uid_hash_table +
329 uid_hash_table_sort_idx[i];
330
331 if (!ui_used(ui) || !ui_admissible(ui))
332 continue;
333 ret = func(ui, data);
334 if (ret < 0)
335 return ret;
336 }
337 return 1;
338 }
339
340 #define PRIME1 0xb11924e1
341 #define PRIME2 0x01000193
342
343 void create_hash_table(unsigned bits)
344 {
345 int i;
346
347 uid_hash_table_size = 1 << bits;
348 uid_hash_table = adu_calloc(uid_hash_table_size *
349 sizeof(struct user_info));
350 uid_hash_table_sort_idx = adu_malloc(uid_hash_table_size * sizeof(int));
351 for (i = 0; i < uid_hash_table_size; i++)
352 uid_hash_table_sort_idx[i] = i;
353 }
354
355 void close_user_tables(void)
356 {
357 struct user_info *ui;
358
359 FOR_EACH_USER(ui) {
360 int ret;
361
362 if (!ui_used(ui))
363 continue;
364 if (!ui->table)
365 continue;
366 INFO_LOG("closing user table for uid %u\n", (unsigned)ui->uid);
367 ret = osl(osl_close_table(ui->table, OSL_MARK_CLEAN));
368 if (ret < 0)
369 ERROR_LOG("failed to close user table %u: %s\n",
370 (unsigned)ui->uid, adu_strerror(-ret));
371 free((char *)ui->desc->name);
372 ui->desc->name = NULL;
373 free((char *)ui->desc->dir);
374 ui->desc->dir = NULL;
375 free(ui->pw_name);
376 ui->pw_name = NULL;
377 free(ui->desc);
378 ui->desc = NULL;
379 ui->table = NULL;
380 ui->flags = 0;
381 }
382 free(uid_hash_table);
383 uid_hash_table = NULL;
384 free(uid_hash_table_sort_idx);
385 uid_hash_table_sort_idx = NULL;
386 }
387
388 /*
389 * We use a hash table of size s=2^uid_hash_bits to map the uids into the
390 * interval [0..s-1]. Hash collisions are treated by open addressing, i.e.
391 * unused slots in the table are used to store different uids that hash to the
392 * same slot.
393 *
394 * If a hash collision occurs, different slots are successively probed in order
395 * to find an unused slot for the new uid. Probing is implemented via a second
396 * hash function that maps the uid to h=(uid * PRIME2) | 1, which is always an
397 * odd number.
398 *
399 * An odd number is sufficient to make sure each entry of the hash table gets
400 * probed for probe_num between 0 and s-1 because s is a power of two, hence
401 * the second hash value has never a common divisor with the hash table size.
402 * IOW: h is invertible in the ring [0..s-1].
403 */
404 static uint32_t double_hash(uint32_t uid, uint32_t probe_num)
405 {
406 return (uid * PRIME1 + ((uid * PRIME2) | 1) * probe_num)
407 % uid_hash_table_size;
408 }
409
410 static struct user_info *lookup_uid(uint32_t uid)
411 {
412 uint32_t p;
413
414 for (p = 0; p < uid_hash_table_size; p++) {
415 struct user_info *ui = uid_hash_table + double_hash(uid, p);
416 if (!ui_used(ui))
417 return ui;
418 if (ui->uid == uid)
419 return ui;
420 }
421 return NULL;
422 }
423
424 int create_user_table(uint32_t uid, struct user_info **ui_ptr)
425 {
426 struct user_info *ui = lookup_uid(uid);
427
428 if (!ui)
429 return -E_HASH_TABLE_OVERFLOW;
430 *ui_ptr = ui;
431 if (ui_used(ui))
432 return 1;
433 ui->uid = uid;
434 ui->flags |= UI_FL_SLOT_USED;
435 return open_user_table(ui, 1);
436 }
437
438 static char *get_uid_list_name(void)
439 {
440 return make_message("%s/uid_list", conf.database_dir_arg);
441 }
442
443 static int (*hash_table_comparator)(struct user_info *a, struct user_info *b);
444
445 static int comp_wrapper(const void *a, const void *b)
446 {
447 struct user_info *x = uid_hash_table + *(unsigned *)a;
448 struct user_info *y = uid_hash_table + *(unsigned *)b;
449 return hash_table_comparator(x, y);
450 }
451
452 void sort_hash_table(int (*comp)(struct user_info *, struct user_info *))
453 {
454 hash_table_comparator = comp;
455 qsort(uid_hash_table_sort_idx, uid_hash_table_size,
456 sizeof(*uid_hash_table_sort_idx), comp_wrapper);
457 }
458
459 int open_admissible_user_tables(struct uid_range *admissible_uids)
460 {
461 struct user_info *ui;
462
463 assert(uid_hash_table);
464 DEBUG_LOG("size: %d\n", uid_hash_table_size);
465 FOR_EACH_USER(ui) {
466 int ret;
467
468 if (!ui_used(ui))
469 continue;
470 if (!uid_is_admissible(ui->uid, admissible_uids)) {
471 DEBUG_LOG("uid %u is not admissible\n", ui->uid);
472 ui->flags &= ~UI_FL_ADMISSIBLE;
473 continue;
474 }
475 ui->flags |= UI_FL_ADMISSIBLE;
476 if (ui->table)
477 continue;
478 ret = open_user_table(ui, 0);
479 if (ret < 0)
480 return ret;
481 }
482 return 1;
483 }
484
485 int read_uid_file(void)
486 {
487 size_t size;
488 uint32_t n;
489 char *filename = get_uid_list_name(), *map;
490 int ret = mmap_full_file(filename, O_RDONLY, (void **)&map, &size, NULL);
491 unsigned bits;
492
493 if (ret < 0) {
494 ERROR_LOG("failed to map %s\n", filename);
495 free(filename);
496 return ret;
497 }
498 num_uids = size / 4;
499 INFO_LOG("found %u uids in %s\n", (unsigned)num_uids, filename);
500 free(filename);
501 /*
502 * Compute number of hash table bits. The hash table size must be a
503 * power of two and larger than the number of uids.
504 */
505 bits = 2;
506 while (1 << bits < num_uids)
507 bits++;
508 create_hash_table(bits);
509 for (n = 0; n < num_uids; n++) {
510 uint32_t uid = read_u32(map + n * sizeof(uid));
511 struct user_info *ui = lookup_uid(uid);
512 assert(ui);
513 if (ui_used(ui)) { /* impossible */
514 ERROR_LOG("duplicate user id!?\n");
515 ret = -EFAULT;
516 goto out;
517 }
518 ui->uid = uid;
519 ui->flags |= UI_FL_SLOT_USED;
520 }
521 ret = 1;
522 out:
523 adu_munmap(map, size);
524 return ret;
525 }
526
527 int write_uid_file(void)
528 {
529 char *buf, *p, *filename;
530 size_t size = num_uids * sizeof(uint32_t);
531 int ret;
532 struct user_info *ui;
533
534 if (!num_uids)
535 return 0;
536 buf = p = adu_malloc(size);
537 FOR_EACH_USER(ui) {
538 if (!ui_used(ui))
539 continue;
540 write_u32(p, ui->uid);
541 p += sizeof(uint32_t);
542 }
543 filename = get_uid_list_name();
544 ret = adu_write_file(filename, buf, size);
545 free(filename);
546 free(buf);
547 return ret;
548 }