3eec0b4d67c20509c4de586b5d4bf16d17fb362c
[adu.git] / adu.c
1 #include "adu.h"
2 #include <dirent.h> /* readdir() */
3 #include <pwd.h>
4
5 #include "gcc-compat.h"
6 #include "cmdline.h"
7 #include "fd.h"
8 #include "string.h"
9 #include "error.h"
10 #include "portable_io.h"
11
12 DEFINE_ERRLIST;
13 int osl_errno;
14
15 /** In case a signal is received, its number is stored here. */
16 static int signum;
17
18 /** Command line and config file options. */
19 struct gengetopt_args_info conf;
20
21 /** The number of different uids found so far. */
22 uint32_t num_uids = 0;
23
24 /** This is always a power of two. It is set in create_hash_table(). */
25 static uint32_t uid_hash_table_size;
26
27 /**
28  * Contains info for each user that owns at least one regular file.
29  *
30  * Even users that are not taken into account because of the --uid
31  * option occupy a slot in this hash table. This allows to find out
32  * quicky whether a uid is admissible. And yes, this has to be fast.
33  */
34 static struct user_info *uid_hash_table;
35
36 static inline int ui_used(struct user_info *ui)
37 {
38         return ui->flags & UI_FL_SLOT_USED;
39 }
40
41 static inline int ui_admissible(struct user_info *ui)
42 {
43         return ui->flags & UI_FL_ADMISSIBLE;
44 }
45
46 /**
47  * The table containing the directory names and statistics.
48  */
49 struct osl_table *dir_table = NULL;
50
51 /**
52  * The array of all uid ranges that were given at the command line.
53  */
54 struct uid_range *admissible_uids;
55
56 /** Evaluates to 1 if x < y, to -1 if x > y and to 0 if x == y. */
57 #define NUM_COMPARE(x, y) ((int)((x) < (y)) - (int)((x) > (y)))
58
59 /**
60  * Compare the size of two directories
61  *
62  * \param obj1 Pointer to the first object.
63  * \param obj2 Pointer to the second object.
64  *
65  * This function first compares the size values as usual integers. If they compare as
66  * equal, the address of \a obj1 and \a obj2 are compared. So this compare function
67  * returns zero if and only if \a obj1 and \a obj2 point to the same memory area.
68  */
69 static int size_compare(const struct osl_object *obj1, const struct osl_object *obj2)
70 {
71         uint64_t d1 = *(uint64_t *)obj1->data;
72         uint64_t d2 = *(uint64_t *)obj2->data;
73         int ret = NUM_COMPARE(d2, d1);
74
75         if (ret)
76                 return ret;
77         //INFO_LOG("addresses: %p, %p\n", obj1->data, obj2->data);
78         return NUM_COMPARE(obj2->data, obj1->data);
79 }
80
81 /**
82  * Compare two osl objects pointing to unsigned integers of 64 bit size.
83  *
84  * \param obj1 Pointer to the first integer.
85  * \param obj2 Pointer to the second integer.
86  *
87  * \return The values required for an osl compare function.
88  *
89  * \sa osl_compare_func, osl_hash_compare().
90  */
91 static int uint64_compare(const struct osl_object *obj1,
92                 const struct osl_object *obj2)
93 {
94         uint64_t d1 = read_u64((const char *)obj1->data);
95         uint64_t d2 = read_u64((const char *)obj2->data);
96
97         if (d1 < d2)
98                 return 1;
99         if (d1 > d2)
100                 return -1;
101         return 0;
102 }
103
104 static struct osl_column_description dir_table_cols[] = {
105         [DT_NAME] = {
106                 .storage_type = OSL_MAPPED_STORAGE,
107                 .storage_flags = 0,
108                 .name = "dir",
109         },
110         [DT_NUM] = {
111                 .storage_type = OSL_MAPPED_STORAGE,
112                 .storage_flags = OSL_RBTREE | OSL_FIXED_SIZE | OSL_UNIQUE,
113                 .name = "num",
114                 .compare_function = uint64_compare,
115                 .data_size = sizeof(uint64_t)
116         },
117         [DT_PARENT_NUM] = {
118                 .storage_type = OSL_MAPPED_STORAGE,
119                 .storage_flags = OSL_RBTREE | OSL_FIXED_SIZE | OSL_UNIQUE,
120                 .name = "parent_num",
121                 .compare_function = size_compare,
122                 .data_size = sizeof(uint64_t)
123         },
124         [DT_BYTES] = {
125                 .storage_type = OSL_MAPPED_STORAGE,
126                 .storage_flags =  OSL_RBTREE | OSL_FIXED_SIZE,
127                 .compare_function = size_compare,
128                 .name = "num_bytes",
129                 .data_size = sizeof(uint64_t)
130         },
131         [DT_FILES] = {
132                 .storage_type = OSL_MAPPED_STORAGE,
133                 .storage_flags =  OSL_RBTREE | OSL_FIXED_SIZE,
134                 .compare_function = size_compare,
135                 .name = "num_files",
136                 .data_size = sizeof(uint64_t)
137         }
138 };
139
140 static struct osl_table_description dir_table_desc = {
141         .name = "dir_table",
142         .num_columns = NUM_DT_COLUMNS,
143         .flags = 0,
144         .column_descriptions = dir_table_cols,
145 };
146
147 static struct osl_column_description user_table_cols[] = {
148         [UT_DIR_NUM] = {
149                 .storage_type = OSL_MAPPED_STORAGE,
150                 .storage_flags = OSL_RBTREE | OSL_FIXED_SIZE | OSL_UNIQUE,
151                 .name = "dir_num",
152                 .compare_function = uint64_compare,
153                 .data_size = sizeof(uint64_t)
154         },
155         [UT_BYTES] = {
156                 .storage_type = OSL_MAPPED_STORAGE,
157                 .storage_flags = OSL_RBTREE | OSL_FIXED_SIZE,
158                 .compare_function = size_compare,
159                 .name = "num_bytes",
160                 .data_size = sizeof(uint64_t)
161         },
162         [UT_FILES] = {
163                 .storage_type = OSL_MAPPED_STORAGE,
164                 .storage_flags = OSL_RBTREE | OSL_FIXED_SIZE,
165                 .compare_function = size_compare,
166                 .name = "num_files",
167                 .data_size = sizeof(uint64_t)
168         },
169 };
170
171 static int check_uid_arg(const char *arg, uint32_t *uid)
172 {
173         const uint32_t max = ~0U;
174         /*
175          * we need an 64-bit int for string -> uid conversion because strtoll()
176          * returns a signed value.
177          */
178         int64_t val;
179         int ret = atoi64(arg, &val);
180
181         if (ret < 0)
182                 return ret;
183         if (val < 0 || val > max)
184                 return -ERRNO_TO_ERROR(EINVAL);
185         *uid = val;
186         return 1;
187 }
188
189 static int parse_uid_range(const char *orig_arg, struct uid_range *ur)
190 {
191         int ret;
192         char *arg = adu_strdup(orig_arg), *p = strchr(arg, '-');
193
194         if (!p || p == arg) { /* -42 or 42 */
195                 ret = check_uid_arg(p? p + 1 : arg, &ur->high);
196                 if (ret < 0)
197                         goto out;
198                 ur->low = p? 0 : ur->high;
199                 ret = 1;
200                 goto out;
201         }
202         /* 42- or 42-4711 */
203         *p = '\0';
204         p++;
205         ret = check_uid_arg(arg, &ur->low);
206         if (ret < 0)
207                 goto out;
208         ur->high = ~0U;
209         if (*p) { /* 42-4711 */
210                 ret = check_uid_arg(p, &ur->high);
211                 if (ret < 0)
212                         goto out;
213         }
214         if (ur->low > ur->high)
215                 ret = -ERRNO_TO_ERROR(EINVAL);
216 out:
217         if (ret < 0)
218                 ERROR_LOG("bad uid option: %s\n", orig_arg);
219         else
220                 INFO_LOG("admissible uid range: %u - %u\n", ur->low,
221                         ur->high);
222         free(arg);
223         return ret;
224 }
225
226 /**
227  * The log function.
228  *
229  * \param ll Loglevel.
230  * \param fml Usual format string.
231  *
232  * All XXX_LOG() macros use this function.
233  */
234 __printf_2_3 void __log(int ll, const char* fmt,...)
235 {
236         va_list argp;
237         FILE *outfd;
238         struct tm *tm;
239         time_t t1;
240         char str[255] = "";
241
242         if (ll < conf.loglevel_arg)
243                 return;
244         outfd = stderr;
245         time(&t1);
246         tm = localtime(&t1);
247         strftime(str, sizeof(str), "%b %d %H:%M:%S", tm);
248         fprintf(outfd, "%s ", str);
249         va_start(argp, fmt);
250         vfprintf(outfd, fmt, argp);
251         va_end(argp);
252 }
253
254 static int open_user_table(struct user_info *ui, int create)
255 {
256         int ret;
257         struct passwd *pw;
258
259         ui->desc = adu_malloc(sizeof(*ui->desc));
260         ui->desc->num_columns = NUM_UT_COLUMNS;
261         ui->desc->flags = 0;
262         ui->desc->column_descriptions = user_table_cols;
263         ui->desc->dir = adu_strdup(conf.database_dir_arg);
264         ui->desc->name = make_message("%u", (unsigned)ui->uid);
265         pw = getpwuid(ui->uid);
266         if (pw && pw->pw_name)
267                 ui->pw_name = adu_strdup(pw->pw_name);
268
269         INFO_LOG(".............................uid #%u: %u\n",
270                 (unsigned)num_uids, (unsigned)ui->uid);
271         if (create) {
272                 ret = osl(osl_create_table(ui->desc));
273                 if (ret < 0)
274                         goto err;
275                 num_uids++;
276         }
277         ret = osl(osl_open_table(ui->desc, &ui->table));
278         if (ret < 0)
279                 goto err;
280         return 1;
281 err:
282         free((char *)ui->desc->name);
283         free((char *)ui->desc->dir);
284         free(ui->pw_name);
285         free(ui->desc);
286         ui->desc->name = NULL;
287         ui->desc->dir = NULL;
288         ui->desc = NULL;
289         ui->table = NULL;
290         ui->flags = 0;
291         return ret;
292 }
293
294 int for_each_admissible_user(int (*func)(struct user_info *, void *),
295                 void *data)
296 {
297         struct user_info *ui = uid_hash_table;
298
299         if (!ui)
300                 return -ERRNO_TO_ERROR(EFAULT);
301
302         for (; ui < uid_hash_table + uid_hash_table_size; ui++) {
303                 int ret;
304
305                 if (!ui_used(ui) || !ui_admissible(ui))
306                         continue;
307                 ret = func(ui, data);
308                 if (ret < 0)
309                         return ret;
310         }
311         return 1;
312 }
313
314 #define PRIME1 0x811c9dc5
315 #define PRIME2 0x01000193
316
317 void create_hash_table(unsigned bits)
318 {
319         uid_hash_table_size = 1 << bits;
320         uid_hash_table = adu_calloc(uid_hash_table_size *
321                 sizeof(struct user_info));
322 }
323
324 static void free_hash_table(void)
325 {
326         free(uid_hash_table);
327         uid_hash_table = NULL;
328 }
329
330 static void close_dir_table(void)
331 {
332         int ret;
333
334         if (!dir_table)
335                 return;
336         ret = osl(osl_close_table(dir_table, OSL_MARK_CLEAN));
337         if (ret < 0)
338                 ERROR_LOG("failed to close dir table: %s\n", adu_strerror(-ret));
339         free((char *)dir_table_desc.dir);
340         dir_table = NULL;
341 }
342
343 static int close_user_table(struct user_info *ui, __a_unused void *data)
344 {
345         int ret;
346
347         ret = osl(osl_close_table(ui->table, OSL_MARK_CLEAN));
348         if (ret < 0)
349                 ERROR_LOG("failed to close user table %u: %s\n",
350                         (unsigned) ui->uid, adu_strerror(-ret));
351         free((char *)ui->desc->name);
352         ui->desc->name = NULL;
353         free((char *)ui->desc->dir);
354         ui->desc->dir = NULL;
355         free(ui->pw_name);
356         ui->pw_name = NULL;
357         free(ui->desc);
358         ui->desc = NULL;
359         ui->table = NULL;
360         ui->flags = 0;
361         return 1;
362 }
363
364 static void close_user_tables(void)
365 {
366         for_each_admissible_user(close_user_table, NULL);
367 }
368
369 void close_all_tables(void)
370 {
371         close_dir_table();
372         close_user_tables();
373         free_hash_table();
374 }
375
376 static void signal_handler(int s)
377 {
378         signum = s;
379 }
380
381 void check_signals(void)
382 {
383         if (likely(!signum))
384                 return;
385         EMERG_LOG("caught signal %d\n", signum);
386         close_all_tables();
387         exit(EXIT_FAILURE);
388 }
389
390 static int init_signals(void)
391 {
392         if (signal(SIGINT, &signal_handler) == SIG_ERR)
393                 return -E_SIGNAL_SIG_ERR;
394         if (signal(SIGTERM, &signal_handler) == SIG_ERR)
395                 return -E_SIGNAL_SIG_ERR;
396         if (signal(SIGPIPE, &signal_handler) == SIG_ERR)
397                 return -E_SIGNAL_SIG_ERR;
398         return 1;
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]. 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].
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 int uid_is_admissible(uint32_t uid)
424 {
425         int i;
426
427         for (i = 0; i < conf.uid_given; i++) {
428                 struct uid_range *ur = admissible_uids + i;
429
430                 if (ur->low <= uid && ur->high >= uid)
431                         break;
432         }
433         i = !conf.uid_given || i < conf.uid_given;
434         DEBUG_LOG("uid %u is %sadmissible\n", (unsigned)uid,
435                 i? "" : "not ");
436         return i;
437 }
438
439 int search_uid(uint32_t uid, enum search_uid_flags flags,
440                 struct user_info **ui_ptr)
441 {
442         uint32_t p;
443
444         for (p = 0; p < uid_hash_table_size; p++) {
445                 struct user_info *ui = uid_hash_table + double_hash(uid, p);
446
447                 if (!ui_used(ui)) {
448                         int ret;
449                         if (!flags)
450                                 return -E_BAD_UID;
451                         ui->uid = uid;
452                         ui->flags |= UI_FL_SLOT_USED;
453                         if (!uid_is_admissible(uid))
454                                 return 0;
455                         ui->flags |= UI_FL_ADMISSIBLE;
456                         ret = open_user_table(ui, flags & CREATE_USER_TABLE);
457                         if (ret < 0)
458                                 return ret;
459
460                         if (ui_ptr)
461                                 *ui_ptr = ui;
462                         return 1;
463                 }
464                 if (ui->uid != uid)
465                         continue;
466                 if (ui_ptr)
467                         *ui_ptr = ui;
468                 return 0;
469         }
470         return flags? -E_HASH_TABLE_OVERFLOW : -E_BAD_UID;
471 }
472
473 char *get_uid_list_name(void)
474 {
475         return make_message("%s/uid_list", conf.database_dir_arg);
476 }
477
478 int open_dir_table(int create)
479 {
480         dir_table_desc.dir = adu_strdup(conf.database_dir_arg);
481
482         if (create) {
483                 int ret = osl(osl_create_table(&dir_table_desc));
484                 if (ret < 0) {
485                         free((char *)dir_table_desc.dir);
486                         return ret;
487                 }
488         }
489         return osl(osl_open_table(&dir_table_desc, &dir_table));
490 }
491
492 static int check_args(void)
493 {
494         int i, ret;
495
496
497         if (conf.create_given && !conf.base_dir_given)
498                 return -E_SYNTAX;
499
500         /* remove trailing slashes from base-dir arg */
501         if (conf.base_dir_given) {
502                 size_t len = strlen(conf.base_dir_arg);
503                 for (;;) {
504                         if (!len) /* empty string */
505                                 return -ERRNO_TO_ERROR(EINVAL);
506                         if (!--len) /* length 1 is always OK */
507                                 break;
508                         if (conf.base_dir_arg[len] != '/')
509                                 break; /* no trailing slash, also OK */
510                         conf.base_dir_arg[len] = '\0';
511                 }
512         }
513         if (!conf.uid_given)
514                 return 0;
515         admissible_uids = adu_malloc(conf.uid_given * sizeof(*admissible_uids));
516         for (i = 0; i < conf.uid_given; i++) {
517                 ret = parse_uid_range(conf.uid_arg[i], admissible_uids + i);
518                 if (ret < 0)
519                         goto err;
520         }
521         return 1;
522 err:
523         free(admissible_uids);
524         admissible_uids = NULL;
525         return ret;
526 }
527
528 int main(int argc, char **argv)
529 {
530         int ret;
531         struct cmdline_parser_params params = {
532                 .override = 0,
533                 .initialize = 1,
534                 .check_required = 1,
535                 .check_ambiguity = 1,
536                 .print_errors = 1
537         };
538
539         cmdline_parser_ext(argc, argv, &conf, &params); /* aborts on errors */
540         ret = check_args();
541         if (ret < 0)
542                 goto out;
543         ret = init_signals();
544         if (ret < 0)
545                 goto out;
546         ret = -E_SYNTAX;
547         if (conf.select_given)
548                 ret = com_select();
549         else
550                 ret = com_create();
551         if (ret < 0)
552                 goto out;
553 out:
554         free(admissible_uids);
555         if (ret < 0) {
556                 ERROR_LOG("%s\n", adu_strerror(-ret));
557                 return -EXIT_FAILURE;
558         }
559         return EXIT_SUCCESS;
560 }