Some more source code documentation.
[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 /** Prime number used for calculating the slot for an uid. */
341 #define PRIME1 0xb11924e1
342 /** Prime number used for probe all slots. */
343 #define PRIME2 0x01000193
344
345 /**
346  * Create a hash table large enough of given size.
347  *
348  * \param bits Sets the maximal number of hash table entries to ^bits.
349  */
350 void create_hash_table(unsigned bits)
351 {
352         int i;
353
354         uid_hash_table_size = 1 << bits;
355         uid_hash_table = adu_calloc(uid_hash_table_size *
356                 sizeof(struct user_info));
357         uid_hash_table_sort_idx = adu_malloc(uid_hash_table_size * sizeof(int));
358         for (i = 0; i < uid_hash_table_size; i++)
359                 uid_hash_table_sort_idx[i] = i;
360 }
361
362 /**
363  * Close all open user tables and destroy the uid hash table.
364  *
365  * For each used slot in the uid hash table, close the osl user table if it is
366  * open.  Finally, free the uid hash table.
367  */
368 void close_user_tables(void)
369 {
370         struct user_info *ui;
371
372         FOR_EACH_USER(ui) {
373                 int ret;
374
375                 if (!ui_used(ui))
376                         continue;
377                 if (!ui->table)
378                         continue;
379                 INFO_LOG("closing user table for uid %u\n", (unsigned)ui->uid);
380                 ret = osl(osl_close_table(ui->table, OSL_MARK_CLEAN));
381                 if (ret < 0)
382                         ERROR_LOG("failed to close user table %u: %s\n",
383                                 (unsigned)ui->uid, adu_strerror(-ret));
384                 free((char *)ui->desc->name);
385                 ui->desc->name = NULL;
386                 free((char *)ui->desc->dir);
387                 ui->desc->dir = NULL;
388                 free(ui->pw_name);
389                 ui->pw_name = NULL;
390                 free(ui->desc);
391                 ui->desc = NULL;
392                 ui->table = NULL;
393                 ui->flags = 0;
394         }
395         free(uid_hash_table);
396         uid_hash_table = NULL;
397         free(uid_hash_table_sort_idx);
398         uid_hash_table_sort_idx = NULL;
399 }
400
401 /*
402  * We use a hash table of size s=2^uid_hash_bits to map the uids into the
403  * interval [0..s-1]. Hash collisions are treated by open addressing, i.e.
404  * unused slots in the table are used to store different uids that hash to the
405  * same slot.
406  *
407  * If a hash collision occurs, different slots are successively probed in order
408  * to find an unused slot for the new uid. Probing is implemented via a second
409  * hash function that maps the uid to h=(uid * PRIME2) | 1, which is always an
410  * odd number.
411  *
412  * An odd number is sufficient to make sure each entry of the hash table gets
413  * probed for probe_num between 0 and s-1 because s is a power of two, hence
414  * the second hash value has never a common divisor with the hash table size.
415  * IOW: h is invertible in the ring [0..s-1].
416  */
417 static uint32_t double_hash(uint32_t uid, uint32_t probe_num)
418 {
419         return (uid * PRIME1 + ((uid * PRIME2) | 1) * probe_num)
420                 % uid_hash_table_size;
421 }
422
423 static struct user_info *lookup_uid(uint32_t uid)
424 {
425         uint32_t p;
426
427         for (p = 0; p < uid_hash_table_size; p++) {
428                 struct user_info *ui = uid_hash_table + double_hash(uid, p);
429                 if (!ui_used(ui))
430                         return ui;
431                 if (ui->uid == uid)
432                         return ui;
433         }
434         return NULL;
435 }
436
437 /**
438  * Create and open a osl table for the given uid.
439  *
440  * \param uid The user ID.
441  * \param ui_ptr Result pointer
442  *
443  * Find out whether \a uid already exists in the uid hash table.  If yes, just
444  * return the user info struct via \a ui_ptr. Otherwise, insert \a uid into the
445  * uid hash table, create and open the osl user table and also return the user
446  * info struct via \a ui_ptr.
447  *
448  * \return Standard.
449  */
450 int create_user_table(uint32_t uid, struct user_info **ui_ptr)
451 {
452         struct user_info *ui = lookup_uid(uid);
453
454         if (!ui)
455                 return -E_HASH_TABLE_OVERFLOW;
456         *ui_ptr = ui;
457         if (ui_used(ui))
458                 return 1;
459         ui->uid = uid;
460         ui->flags |= UI_FL_SLOT_USED;
461         return open_user_table(ui, 1);
462 }
463
464 static char *get_uid_list_name(void)
465 {
466         return make_message("%s/uid_list", conf.database_dir_arg);
467 }
468
469 static int (*hash_table_comparator)(struct user_info *a, struct user_info *b);
470
471 static int comp_wrapper(const void *a, const void *b)
472 {
473         struct user_info *x = uid_hash_table + *(unsigned *)a;
474         struct user_info *y = uid_hash_table + *(unsigned *)b;
475         return hash_table_comparator(x, y);
476 }
477
478 /**
479  * Sort the hash table according to a given comparator.
480  *
481  * \param comp The comparator.
482  *
483  * The comparator is a user-defined function which must return 1, 0, or -1.
484  *
485  * \sa qsort(3).
486  */
487 void sort_hash_table(int (*comp)(struct user_info *, struct user_info *))
488 {
489         hash_table_comparator = comp;
490         qsort(uid_hash_table_sort_idx, uid_hash_table_size,
491                 sizeof(*uid_hash_table_sort_idx), comp_wrapper);
492 }
493
494 /**
495  * Open the osl tables for all admissible uids.
496  *
497  * \param admissible_uids Determines which uids are considered admissible.
498  *
499  * Each slot in the hash table contains, among other information, a bit which
500  * specifies whether the uid of the slot is admissible in the current context.
501  *
502  * This function iterates over all entries in the hash table and checks for
503  * each used slot whether the corresponding uid is admissible with respect to
504  * \a admissible_uids. If so, it sets the admissible bit for this slot and
505  * opens the osl table of the uid.
506  *
507  * \return Stamdard.
508  */
509 int open_admissible_user_tables(struct uid_range *admissible_uids)
510 {
511         struct user_info *ui;
512
513         assert(uid_hash_table);
514         DEBUG_LOG("size: %d\n", uid_hash_table_size);
515         FOR_EACH_USER(ui) {
516                 int ret;
517
518                 if (!ui_used(ui))
519                         continue;
520                 if (!uid_is_admissible(ui->uid, admissible_uids)) {
521                         DEBUG_LOG("uid %u is not admissible\n", ui->uid);
522                         ui->flags &= ~UI_FL_ADMISSIBLE;
523                         continue;
524                 }
525                 ui->flags |= UI_FL_ADMISSIBLE;
526                 if (ui->table)
527                         continue;
528                 ret = open_user_table(ui, 0);
529                 if (ret < 0)
530                         return ret;
531         }
532         return 1;
533 }
534
535 /**
536  * Read the file of all possible uids.
537  *
538  * This is called from select/interactive mode. First a large hash table, large
539  * enough to store all uids contained in the uid file is created. Next, the
540  * uids are read from the uid file which was created during the creation of the
541  * database and each uid is inserted into the hash table.
542  *
543  * \sa write_uid_file().
544  *
545  * \return Standard.
546  */
547 int read_uid_file(void)
548 {
549         size_t size;
550         uint32_t n;
551         char *filename = get_uid_list_name(), *map;
552         int ret = mmap_full_file(filename, O_RDONLY, (void **)&map, &size, NULL);
553         unsigned bits;
554
555         if (ret < 0) {
556                 ERROR_LOG("failed to map %s\n", filename);
557                 free(filename);
558                 return ret;
559         }
560         num_uids = size / 4;
561         INFO_LOG("found %u uids in %s\n", (unsigned)num_uids, filename);
562         free(filename);
563         /*
564          * Compute number of hash table bits. The hash table size must be a
565          * power of two and larger than the number of uids.
566          */
567         bits = 2;
568         while (1 << bits < num_uids)
569                 bits++;
570         create_hash_table(bits);
571         for (n = 0; n < num_uids; n++) {
572                 uint32_t uid = read_u32(map + n * sizeof(uid));
573                 struct user_info *ui = lookup_uid(uid);
574                 assert(ui);
575                 if (ui_used(ui)) { /* impossible */
576                         ERROR_LOG("duplicate user id!?\n");
577                         ret = -EFAULT;
578                         goto out;
579                 }
580                 ui->uid = uid;
581                 ui->flags |= UI_FL_SLOT_USED;
582         }
583         ret = 1;
584 out:
585         adu_munmap(map, size);
586         return ret;
587 }
588
589 /**
590  * Write the list of uids to permanent storage.
591  *
592  * This is called from create mode after the dir table and all uer tables have
593  * been created. The file simply contains the list of all uids that own at
594  * least one regular file in the base directory and hence an osl table for this
595  * uid exists.
596  *
597  * \sa read_uid_file().
598  *
599  * \return Standard.
600  */
601 int write_uid_file(void)
602 {
603         char *buf, *p, *filename;
604         size_t size = num_uids * sizeof(uint32_t);
605         int ret;
606         struct user_info *ui;
607
608         if (!num_uids)
609                 return 0;
610         buf = p = adu_malloc(size);
611         FOR_EACH_USER(ui) {
612                 if (!ui_used(ui))
613                         continue;
614                 write_u32(p, ui->uid);
615                 p += sizeof(uint32_t);
616         }
617         filename = get_uid_list_name();
618         ret = adu_write_file(filename, buf, size);
619         free(filename);
620         free(buf);
621         return ret;
622 }