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