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