]> git.tuebingen.mpg.de Git - adu.git/blob - adu.c
Fix the uid parser.
[adu.git] / adu.c
1 #include "adu.h"
2 #include <dirent.h> /* readdir() */
3
4 #include "gcc-compat.h"
5 #include "cmdline.h"
6 #include "fd.h"
7 #include "string.h"
8 #include "error.h"
9 #include "portable_io.h"
10
11 DEFINE_ERRLIST;
12 int osl_errno;
13
14 /** Command line and config file options. */
15 static struct gengetopt_args_info conf;
16
17 enum uid_info_flags {
18         /** whether this slot of the hash table is used. */
19         UI_FL_SLOT_USED = 1,
20         /** whether this uid should be taken into account. */
21         UI_FL_ADMISSIBLE = 2,
22 };
23
24 struct user_info {
25         uint32_t uid;
26         uint32_t flags;
27         struct osl_table *table;
28         uint64_t files;
29         uint64_t bytes;
30         uint64_t dirs;
31         struct osl_table_description *desc;
32 };
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 struct uid_range {
54         uint32_t low;
55         uint32_t high;
56 };
57
58 static struct uid_range *admissible_uids;
59
60 static inline int check_uid_arg(const char *arg, uint32_t *uid)
61 {
62         const uint32_t max = ~0U;
63         /*
64          * we need an 64-bit int for string -> uid conversion because strtoll()
65          * returns a signed value.
66          */
67         int64_t val;
68         int ret = para_atoi64(arg, &val);
69
70         if (ret < 0)
71                 return ret;
72         if (val < 0 || val > max)
73                 return -ERRNO_TO_ERROR(EINVAL);
74         *uid = val;
75         return 1;
76 }
77
78 static int parse_uid_range(const char *orig_arg, struct uid_range *ur)
79 {
80         int ret;
81         char *arg = para_strdup(orig_arg), *p = strchr(arg, '-');
82
83         if (!p || p == arg) { /* -42 or 42 */
84                 ret = check_uid_arg(p? p + 1 : arg, &ur->high);
85                 if (ret < 0)
86                         goto out;
87                 ur->low = p? 0 : ur->high;
88                 ret = 1;
89                 goto out;
90         }
91         /* 42- or 42-4711 */
92         *p = '\0';
93         p++;
94         ret = check_uid_arg(arg, &ur->low);
95         if (ret < 0)
96                 goto out;
97         ur->high = ~0U;
98         if (*p) { /* 42-4711 */
99                 ret = check_uid_arg(p, &ur->high);
100                 if (ret < 0)
101                         goto out;
102         }
103         if (ur->low > ur->high)
104                 ret = -ERRNO_TO_ERROR(EINVAL);
105 out:
106         if (ret < 0)
107                 ERROR_LOG("bad uid option: %s\n", orig_arg);
108         else
109                 INFO_LOG("admissible uid range: %u - %u\n", ur->low,
110                         ur->high);
111         free(arg);
112         return ret;
113 }
114
115
116 /** evaluates to 1 if x < y, to -1 if x > y and to 0 if x == y */
117 #define NUM_COMPARE(x, y) ((int)((x) < (y)) - (int)((x) > (y)))
118
119 /**
120  * The log function.
121  *
122  * \param ll Loglevel.
123  * \param fml Usual format string.
124  *
125  * All XXX_LOG() macros use this function.
126  */
127 __printf_2_3 void __log(int ll, const char* fmt,...)
128 {
129         va_list argp;
130         FILE *outfd;
131         struct tm *tm;
132         time_t t1;
133         char str[255] = "";
134
135         if (ll < conf.loglevel_arg)
136                 return;
137         outfd = stderr;
138         time(&t1);
139         tm = localtime(&t1);
140         strftime(str, sizeof(str), "%b %d %H:%M:%S", tm);
141         fprintf(outfd, "%s ", str);
142         va_start(argp, fmt);
143         vfprintf(outfd, fmt, argp);
144         va_end(argp);
145 }
146
147 /**
148  * Compare the size of two directories
149  *
150  * \param obj1 Pointer to the first object.
151  * \param obj2 Pointer to the second object.
152  *
153  * This function first compares the size values as usual integers. If they compare as
154  * equal, the address of \a obj1 and \a obj2 are compared. So this compare function
155  * returns zero if and only if \a obj1 and \a obj2 point to the same memory area.
156  */
157 static int size_compare(const struct osl_object *obj1, const struct osl_object *obj2)
158 {
159         uint64_t d1 = *(uint64_t *)obj1->data;
160         uint64_t d2 = *(uint64_t *)obj2->data;
161         int ret = NUM_COMPARE(d2, d1);
162
163         if (ret)
164                 return ret;
165         //INFO_LOG("addresses: %p, %p\n", obj1->data, obj2->data);
166         return NUM_COMPARE(obj2->data, obj1->data);
167 }
168
169 /**
170  * Compare two osl objects pointing to unsigned integers of 64 bit size.
171  *
172  * \param obj1 Pointer to the first integer.
173  * \param obj2 Pointer to the second integer.
174  *
175  * \return The values required for an osl compare function.
176  *
177  * \sa osl_compare_func, osl_hash_compare().
178  */
179 static int uint64_compare(const struct osl_object *obj1,
180                 const struct osl_object *obj2)
181 {
182         uint64_t d1 = read_u64((const char *)obj1->data);
183         uint64_t d2 = read_u64((const char *)obj2->data);
184
185         if (d1 < d2)
186                 return 1;
187         if (d1 > d2)
188                 return -1;
189         return 0;
190 }
191
192 /** The columns of the directory table. */
193 enum dir_table_columns {
194         /** The name of the directory. */
195         DT_NAME,
196         /** The dir count number. */
197         DT_NUM,
198         /** The number of the parent directory. */
199         DT_PARENT_NUM,
200         /** The number of bytes of all regular files. */
201         DT_BYTES,
202         /** The number of all regular files. */
203         DT_FILES,
204         /** Number of columns in this table. */
205         NUM_DT_COLUMNS
206 };
207
208 static struct osl_column_description dir_table_cols[] = {
209         [DT_NAME] = {
210                 .storage_type = OSL_MAPPED_STORAGE,
211                 .storage_flags = 0,
212                 .name = "dir",
213         },
214         [DT_NUM] = {
215                 .storage_type = OSL_MAPPED_STORAGE,
216                 .storage_flags = OSL_RBTREE | OSL_FIXED_SIZE | OSL_UNIQUE,
217                 .name = "num",
218                 .compare_function = uint64_compare,
219                 .data_size = sizeof(uint64_t)
220         },
221         [DT_PARENT_NUM] = {
222                 .storage_type = OSL_MAPPED_STORAGE,
223                 .storage_flags = OSL_RBTREE | OSL_FIXED_SIZE | OSL_UNIQUE,
224                 .name = "parent_num",
225                 .compare_function = size_compare,
226                 .data_size = sizeof(uint64_t)
227         },
228         [DT_BYTES] = {
229                 .storage_type = OSL_MAPPED_STORAGE,
230                 .storage_flags =  OSL_RBTREE | OSL_FIXED_SIZE,
231                 .compare_function = size_compare,
232                 .name = "num_bytes",
233                 .data_size = sizeof(uint64_t)
234         },
235         [DT_FILES] = {
236                 .storage_type = OSL_MAPPED_STORAGE,
237                 .storage_flags =  OSL_RBTREE | OSL_FIXED_SIZE,
238                 .compare_function = size_compare,
239                 .name = "num_files",
240                 .data_size = sizeof(uint64_t)
241         }
242 };
243
244 static struct osl_table_description dir_table_desc = {
245         .name = "dir_table",
246         .num_columns = NUM_DT_COLUMNS,
247         .flags = 0,
248         .column_descriptions = dir_table_cols,
249 };
250
251 /** The columns of the id table. */
252 enum user_table_columns {
253         /** The numer of the directory. */
254         UT_DIR_NUM,
255         /** The number of bytes of all regular files in this dir owned by this id. */
256         UT_BYTES,
257         /** The number of files in this dir owned by this id. */
258         UT_FILES,
259         /** Number of columns in this table. */
260         NUM_UT_COLUMNS
261 };
262
263 static struct osl_column_description user_table_cols[] = {
264         [UT_DIR_NUM] = {
265                 .storage_type = OSL_MAPPED_STORAGE,
266                 .storage_flags = OSL_RBTREE | OSL_FIXED_SIZE | OSL_UNIQUE,
267                 .name = "dir_num",
268                 .compare_function = uint64_compare,
269                 .data_size = sizeof(uint64_t)
270         },
271         [UT_BYTES] = {
272                 .storage_type = OSL_MAPPED_STORAGE,
273                 .storage_flags = OSL_RBTREE | OSL_FIXED_SIZE,
274                 .compare_function = size_compare,
275                 .name = "num_bytes",
276                 .data_size = sizeof(uint64_t)
277         },
278         [UT_FILES] = {
279                 .storage_type = OSL_MAPPED_STORAGE,
280                 .storage_flags = OSL_RBTREE | OSL_FIXED_SIZE,
281                 .compare_function = size_compare,
282                 .name = "num_files",
283                 .data_size = sizeof(uint64_t)
284         },
285 };
286
287 static struct osl_table *dir_table;
288
289 static int add_directory(char *dirname, uint64_t *dir_num, uint64_t *parent_dir_num,
290                 uint64_t *dir_size, uint64_t *dir_files)
291 {
292         struct osl_object dir_objects[NUM_DT_COLUMNS];
293
294         INFO_LOG("adding #%llu: %s\n", (long long unsigned)*dir_num, dirname);
295         dir_objects[DT_NAME].data = dirname;
296         dir_objects[DT_NAME].size = strlen(dirname) + 1;
297         dir_objects[DT_NUM].data = dir_num;
298         dir_objects[DT_NUM].size = sizeof(*dir_num);
299         dir_objects[DT_PARENT_NUM].data = parent_dir_num;
300         dir_objects[DT_PARENT_NUM].size = sizeof(*parent_dir_num);
301         dir_objects[DT_BYTES].data = dir_size;
302         dir_objects[DT_BYTES].size = sizeof(*dir_size);
303         dir_objects[DT_FILES].data = dir_files;
304         dir_objects[DT_FILES].size = sizeof(*dir_files);
305         return osl(osl_add_row(dir_table, dir_objects));
306 }
307
308 static uint32_t num_uids;
309
310 static int open_user_table(struct user_info *ui, int create)
311 {
312         int ret;
313
314         ui->desc = para_malloc(sizeof(*ui->desc));
315         ui->desc->num_columns = NUM_UT_COLUMNS;
316         ui->desc->flags = 0;
317         ui->desc->column_descriptions = user_table_cols;
318         ui->desc->dir = para_strdup(conf.database_dir_arg);
319         ui->desc->name = make_message("%u", (unsigned)ui->uid);
320         INFO_LOG(".............................uid #%u: %u\n",
321                 (unsigned)num_uids, (unsigned)ui->uid);
322         if (create) {
323                 ret = osl(osl_create_table(ui->desc));
324                 if (ret < 0)
325                         goto err;
326                 num_uids++;
327         }
328         ret = osl(osl_open_table(ui->desc, &ui->table));
329         if (ret < 0)
330                 goto err;
331         return 1;
332 err:
333         free((char *)ui->desc->name);
334         free((char *)ui->desc->dir);
335         free(ui->desc);
336         ui->desc->name = NULL;
337         ui->desc->dir = NULL;
338         ui->desc = NULL;
339         ui->table = NULL;
340         ui->flags = 0;
341         return ret;
342 }
343
344 #define uid_hash_bits 8
345 static uint32_t uid_hash_table_size = 1 << uid_hash_bits;
346 #define PRIME1 0x811c9dc5
347 #define PRIME2 0x01000193
348
349 static void create_hash_table(void)
350 {
351         uid_hash_table = para_calloc(uid_hash_table_size
352                 * sizeof(struct user_info));
353 }
354
355 static void free_hash_table(void)
356 {
357         free(uid_hash_table);
358         uid_hash_table = NULL;
359 }
360
361 static int create_tables(void)
362 {
363         int ret;
364
365         dir_table_desc.dir = para_strdup(conf.database_dir_arg);
366         ret = osl(osl_create_table(&dir_table_desc));
367         if (ret < 0)
368                 return ret;
369         create_hash_table();
370         return 1;
371 }
372
373 /*
374  * We use a hash table of size s=2^uid_hash_bits to map the uids into the
375  * interval [0..s]. Hash collisions are treated by open addressing, i.e.
376  * unused slots in the table are used to store different uids that hash to the
377  * same slot.
378  *
379  * If a hash collision occurs, different slots are successively probed in order
380  * to find an unused slot for the new uid. Probing is implemented via a second
381  * hash function that maps the uid to h=(uid * PRIME2) | 1, which is always an
382  * odd number.
383  *
384  * An odd number is sufficient to make sure each entry of the hash table gets
385  * probed for probe_num between 0 and s-1 because s is a power of two, hence
386  * the second hash value has never a common divisor with the hash table size.
387  * IOW: h is invertible in the ring [0..s].
388  */
389 static uint32_t double_hash(uint32_t uid, uint32_t probe_num)
390 {
391         return (uid * PRIME1 + ((uid * PRIME2) | 1) * probe_num)
392                 % uid_hash_table_size;
393 }
394
395 #define FOR_EACH_USER(ui) for (ui = uid_hash_table; ui && ui < uid_hash_table \
396                 + uid_hash_table_size; ui++)
397
398 enum search_uid_flags {
399         OPEN_USER_TABLE = 1,
400         CREATE_USER_TABLE = 2,
401 };
402
403 static int uid_is_admissible(uint32_t uid)
404 {
405         int i;
406
407         for (i = 0; i < conf.uid_given; i++) {
408                 struct uid_range *ur = admissible_uids + i;
409
410                 if (ur->low <= uid && ur->high >= uid)
411                         break;
412         }
413         i = !conf.uid_given || i < conf.uid_given;
414         DEBUG_LOG("uid %u is %sadmissible\n", (unsigned)uid,
415                 i? "" : "not ");
416         return i;
417 }
418
419 static int search_uid(uint32_t uid, enum search_uid_flags flags,
420                 struct user_info **ui_ptr)
421 {
422         uint32_t p;
423
424         for (p = 0; p < uid_hash_table_size; p++) {
425                 struct user_info *ui = uid_hash_table + double_hash(uid, p);
426
427                 if (!ui_used(ui)) {
428                         int ret;
429                         if (!flags)
430                                 return -E_BAD_UID;
431                         ui->uid = uid;
432                         ui->flags |= UI_FL_SLOT_USED;
433                         if (!uid_is_admissible(uid))
434                                 return 0;
435                         ui->flags |= UI_FL_ADMISSIBLE;
436                         ret = open_user_table(ui, flags & CREATE_USER_TABLE);
437                         if (ret < 0)
438                                 return ret;
439
440                         if (ui_ptr)
441                                 *ui_ptr = ui;
442                         return 1;
443                 }
444                 if (ui->uid != uid)
445                         continue;
446                 if (ui_ptr)
447                         *ui_ptr = ui;
448                 return 0;
449         }
450         return flags? -E_HASH_TABLE_OVERFLOW : -E_BAD_UID;
451 }
452
453 static int update_user_row(struct osl_table *t, uint64_t dir_num,
454                 uint64_t *add)
455 {
456         struct osl_row *row;
457         struct osl_object obj = {.data = &dir_num, .size = sizeof(dir_num)};
458
459         int ret = osl(osl_get_row(t, UT_DIR_NUM, &obj, &row));
460
461         if (ret == -E_OSL && osl_errno != E_OSL_RB_KEY_NOT_FOUND)
462                 return ret;
463         if (ret < 0) { /* this is the first file we add */
464                 struct osl_object objects[NUM_UT_COLUMNS];
465                 uint64_t num_files = 1;
466
467                 objects[UT_DIR_NUM].data = &dir_num;
468                 objects[UT_DIR_NUM].size = sizeof(dir_num);
469                 objects[UT_BYTES].data = add;
470                 objects[UT_BYTES].size = sizeof(*add);
471                 objects[UT_FILES].data = &num_files;
472                 objects[UT_FILES].size = sizeof(num_files);
473                 INFO_LOG("######################### ret: %d\n", ret);
474                 ret = osl(osl_add_row(t, objects));
475                 INFO_LOG("######################### ret: %d\n", ret);
476                 return ret;
477         } else { /* add size and increment file count */
478                 uint64_t num;
479                 struct osl_object obj1, obj2 = {.data = &num, .size = sizeof(num)};
480
481                 ret = osl(osl_get_object(t, row, UT_BYTES, &obj1));
482                 if (ret < 0)
483                         return ret;
484                 num = *(uint64_t *)obj1.data + *add;
485                 ret = osl(osl_update_object(t, row, UT_BYTES, &obj2));
486                 if (ret < 0)
487                         return ret;
488                 ret = osl(osl_get_object(t, row, UT_FILES, &obj1));
489                 if (ret < 0)
490                         return ret;
491                 num = *(uint64_t *)obj1.data + 1;
492                 return osl(osl_update_object(t, row, UT_FILES, &obj2));
493         }
494 }
495
496 static uint64_t num_dirs;
497 static uint64_t num_files;
498 static uint64_t num_bytes;
499
500 int scan_dir(char *dirname, uint64_t *parent_dir_num)
501 {
502         DIR *dir;
503         struct dirent *entry;
504         int ret, cwd_fd, ret2;
505         uint64_t dir_size = 0, dir_files = 0;
506         uint64_t this_dir_num = ++num_dirs;
507
508         DEBUG_LOG("----------------- %llu: %s\n", (long long unsigned)num_dirs, dirname);
509         ret = para_opendir(dirname, &dir, &cwd_fd);
510         if (ret < 0) {
511                 if (ret != -ERRNO_TO_ERROR(EACCES))
512                         return ret;
513                 WARNING_LOG("permission denied for %s\n", dirname);
514                 return 1;
515         }
516         while ((entry = readdir(dir))) {
517                 mode_t m;
518                 struct stat s;
519                 uint32_t uid;
520                 uint64_t size;
521                 struct user_info *ui;
522
523                 if (!strcmp(entry->d_name, "."))
524                         continue;
525                 if (!strcmp(entry->d_name, ".."))
526                         continue;
527                 if (lstat(entry->d_name, &s) == -1) {
528                         WARNING_LOG("lstat error for %s/%s\n", dirname,
529                                 entry->d_name);
530                         continue;
531                 }
532                 m = s.st_mode;
533                 if (!S_ISREG(m) && !S_ISDIR(m))
534                         continue;
535                 if (S_ISDIR(m)) {
536                         ret = scan_dir(entry->d_name, &this_dir_num);
537                         if (ret < 0)
538                                 goto out;
539                         continue;
540                 }
541                 /* regular file */
542                 size = s.st_size;
543                 dir_size += size;
544                 num_bytes += size;
545                 dir_files++;
546                 num_files++;
547                 uid = s.st_uid;
548                 ret = search_uid(uid, CREATE_USER_TABLE | OPEN_USER_TABLE, &ui);
549                 if (ret < 0)
550                         goto out;
551                 ui->bytes += size;
552                 ui->files++;
553                 ret = update_user_row(ui->table, this_dir_num, &size);
554                 if (ret < 0)
555                         goto out;
556         }
557         ret = add_directory(dirname, &this_dir_num, parent_dir_num,
558                         &dir_size, &dir_files);
559 out:
560         closedir(dir);
561         ret2 = para_fchdir(cwd_fd);
562         if (ret2 < 0 && ret >= 0)
563                 ret = ret2;
564         close(cwd_fd);
565         return ret;
566 }
567
568 static int get_dir_name_by_number(uint64_t *dirnum, char **name)
569 {
570         char *result = NULL, *tmp;
571         struct osl_row *row;
572         uint64_t val = *dirnum;
573         struct osl_object obj = {.data = &val, .size = sizeof(val)};
574         int ret;
575
576 again:
577         ret = osl(osl_get_row(dir_table, DT_NUM, &obj, &row));
578         if (ret < 0)
579                 goto out;
580         ret = osl(osl_get_object(dir_table, row, DT_NAME, &obj));
581         if (ret < 0)
582                 goto out;
583         if (result) {
584                 tmp = make_message("%s/%s", (char *)obj.data, result);
585                 free(result);
586                 result = tmp;
587         } else
588                 result = para_strdup((char *)obj.data);
589         ret = osl(osl_get_object(dir_table, row, DT_PARENT_NUM, &obj));
590         if (ret < 0)
591                 goto out;
592         val = *(uint64_t *)obj.data;
593         if (val)
594                 goto again;
595 out:
596         if (ret < 0) {
597                 free(result);
598                 *name = NULL;
599         } else
600                 *name = result;
601         return ret;
602 }
603
604 static int get_dir_name_of_row(struct osl_row *dir_table_row, char **name)
605 {
606         struct osl_object obj;
607         int ret;
608         char *this_dir, *prefix = NULL;
609
610         *name = NULL;
611         ret = osl(osl_get_object(dir_table, dir_table_row, DT_NAME, &obj));
612         if (ret < 0)
613                 return ret;
614         this_dir = para_strdup((char *)obj.data);
615         ret = osl(osl_get_object(dir_table, dir_table_row, DT_PARENT_NUM, &obj));
616         if (ret < 0)
617                 goto out;
618         if (!*(uint64_t *)obj.data) {
619                 *name = this_dir;
620                 return 1;
621         }
622         ret = get_dir_name_by_number((uint64_t *)obj.data, &prefix);
623         if (ret < 0)
624                 goto out;
625         *name = make_message("%s/%s", prefix, this_dir);
626         free(prefix);
627         ret = 1;
628 out:
629         free(this_dir);
630         return ret;
631 }
632
633 const uint64_t size_unit_divisors[] = {
634         [size_unit_arg_b] = 1ULL,
635         [size_unit_arg_k] = 1024ULL,
636         [size_unit_arg_m] = 1024ULL * 1024ULL,
637         [size_unit_arg_g] = 1024ULL * 1024ULL * 1024ULL,
638         [size_unit_arg_t] = 1024ULL * 1024ULL * 1024ULL * 1024ULL,
639 };
640
641 const uint64_t count_unit_divisors[] = {
642
643         [count_unit_arg_n] = 1ULL,
644         [count_unit_arg_k] = 1000ULL,
645         [count_unit_arg_m] = 1000ULL * 1000ULL,
646         [count_unit_arg_g] = 1000ULL * 1000ULL * 1000ULL,
647         [count_unit_arg_t] = 1000ULL * 1000ULL * 1000ULL * 1000ULL,
648 };
649
650 const char size_unit_abbrevs[] = " BKMGT";
651 const char count_unit_abbrevs[] = "  KMGT";
652
653 static void format_size_value(enum enum_size_unit unit, uint64_t value, char *result)
654 {
655         if (unit == size_unit_arg_h) /* human readable */
656                 for (unit = size_unit_arg_b; unit < size_unit_arg_t && value > size_unit_divisors[unit + 1]; unit++)
657                                 ; /* nothing */
658         sprintf(result, "%llu%c", (long long unsigned)value / size_unit_divisors[unit], size_unit_abbrevs[unit]);
659 }
660
661 static void format_count_value(enum enum_count_unit unit, uint64_t value, char *result)
662 {
663         if (unit == count_unit_arg_h) /* human readable */
664                 for (unit = count_unit_arg_n; unit < count_unit_arg_t && value > count_unit_divisors[unit + 1]; unit++)
665                                 ; /* nothing */
666         sprintf(result, "%llu%c", (long long unsigned)value / count_unit_divisors[unit], count_unit_abbrevs[unit]);
667 }
668
669 enum global_stats_flags {
670         GSF_PRINT_DIRNAME = 1,
671         GSF_PRINT_BYTES = 2,
672         GSF_PRINT_FILES = 4,
673         GSF_COMPUTE_SUMMARY = 8,
674 };
675
676 struct global_stats_info {
677         uint32_t count;
678         int ret;
679         int osl_errno;
680         enum global_stats_flags flags;
681 };
682
683 static int global_stats_loop_function(struct osl_row *row, void *data)
684 {
685         struct global_stats_info *gsi = data;
686         struct osl_object obj;
687         char *dirname, formated_value[25];
688         int ret, summary = gsi->flags & GSF_COMPUTE_SUMMARY;
689
690         if (!gsi->count && !summary) {
691                 ret = -E_LOOP_COMPLETE;
692                 goto err;
693         }
694         if (gsi->count && (gsi->flags & GSF_PRINT_DIRNAME)) {
695                 ret = get_dir_name_of_row(row, &dirname);
696                 if (ret < 0)
697                         goto err;
698                 printf("%s%s", dirname,
699                         (gsi->flags & (GSF_PRINT_FILES | GSF_PRINT_BYTES))?
700                                 "\t" : "\n"
701                 );
702         }
703         if (summary || (gsi->count && (gsi->flags & GSF_PRINT_FILES))) {
704                 uint64_t files;
705                 ret = osl(osl_get_object(dir_table, row, DT_FILES, &obj));
706                 if (ret < 0)
707                         goto err;
708                 files = *(uint64_t *)obj.data;
709                 if (gsi->count && (gsi->flags & GSF_PRINT_FILES)) {
710                         format_size_value(conf.size_unit_arg, files,
711                                 formated_value);
712                         printf("%s%s", formated_value,
713                                 (gsi->flags & GSF_PRINT_BYTES)? "\t" : "\n");
714                 }
715                 if (summary)
716                         num_files += files;
717         }
718         if (summary || (gsi->count && (gsi->flags & GSF_PRINT_BYTES))) {
719                 uint64_t bytes;
720                 ret = osl(osl_get_object(dir_table, row, DT_BYTES, &obj));
721                 if (ret < 0)
722                         goto err;
723                 bytes = *(uint64_t *)obj.data;
724                 if (gsi->count && (gsi->flags & GSF_PRINT_BYTES)) {
725                         format_size_value(conf.size_unit_arg, bytes,
726                                 formated_value);
727                         printf("%s\n", formated_value);
728                 }
729                 if (summary) {
730                         num_bytes += bytes;
731                         num_dirs++;
732                 }
733         }
734         if (gsi->count > 0)
735                 gsi->count--;
736         return 1;
737 err:
738         gsi->ret = ret;
739         gsi->osl_errno = (ret == -E_OSL)? osl_errno : 0;
740         return -1;
741 }
742
743 static void print_id_stats(void)
744 {
745         struct user_info *ui;
746
747         printf("--------------------- user summary (uid/dirs/files/bytes):\n");
748         FOR_EACH_USER(ui) {
749                 char formated_dir_count[25], formated_file_count[25],
750                         formated_bytes[25];
751                 if (!ui_used(ui))
752                         continue;
753                 format_count_value(conf.count_unit_arg, ui->dirs,
754                         formated_dir_count);
755                 format_count_value(conf.count_unit_arg, ui->files,
756                         formated_file_count);
757                 format_size_value(conf.size_unit_arg, ui->bytes,
758                         formated_bytes);
759                 printf("%u\t%s\t%s\t%s\n", (unsigned)ui->uid,
760                         formated_dir_count,
761                         formated_file_count,
762                         formated_bytes
763                 );
764         }
765 }
766
767 enum user_stats_flags {
768         USF_PRINT_DIRNAME = 1,
769         USF_PRINT_BYTES = 2,
770         USF_PRINT_FILES = 4,
771         USF_COMPUTE_SUMMARY = 8,
772 };
773
774 struct user_stats_info {
775         uint32_t count;
776         enum user_stats_flags flags;
777         int ret;
778         int osl_errno;
779         struct user_info *ui;
780 };
781
782 static int user_stats_loop_function(struct osl_row *row, void *data)
783 {
784         struct user_stats_info *usi = data;
785         struct osl_object obj;
786         int ret, summary = usi->flags & GSF_COMPUTE_SUMMARY;
787         char formated_value[25];
788
789         if (!usi->count && !summary) {
790                 ret = -E_LOOP_COMPLETE;
791                 goto err;
792         }
793         if (usi->count && (usi->flags & USF_PRINT_DIRNAME)) {
794                 char *dirname;
795                 ret = osl(osl_get_object(usi->ui->table, row, UT_DIR_NUM, &obj));
796                 if (ret < 0)
797                         goto err;
798                 ret = get_dir_name_by_number((uint64_t *)obj.data, &dirname);
799                 if (ret < 0)
800                         goto err;
801                 printf("%s%s",
802                         dirname,
803                         (usi->flags & (USF_PRINT_FILES | USF_PRINT_BYTES))?
804                                 "\t" : "\n"
805                 );
806         }
807         if (summary || (usi->count && (usi->flags & USF_PRINT_FILES))) {
808                 uint64_t files;
809                 ret = osl(osl_get_object(usi->ui->table, row, UT_FILES, &obj));
810                 if (ret < 0)
811                         goto err;
812                 files = *(uint64_t *)obj.data;
813                 if (usi->count && (usi->flags & USF_PRINT_FILES)) {
814                         format_size_value(conf.size_unit_arg, files,
815                                 formated_value);
816                         printf("%s%s", formated_value,
817                                 (usi->flags & USF_PRINT_BYTES)? "\t" : "\n"
818                         );
819                 }
820                 if (summary)
821                         usi->ui->files += files;
822         }
823         if (summary || (usi->count && (usi->flags & USF_PRINT_BYTES))) {
824                 uint64_t bytes;
825                 ret = osl(osl_get_object(usi->ui->table, row, UT_BYTES, &obj));
826                 if (ret < 0)
827                         goto err;
828                 bytes = *(uint64_t *)obj.data;
829                 if (usi->count && (usi->flags & USF_PRINT_BYTES)) {
830                         format_size_value(conf.size_unit_arg, bytes,
831                                 formated_value);
832                         printf("%s\n", formated_value);
833                 }
834                 if (summary) {
835                         usi->ui->bytes += bytes;
836                         usi->ui->dirs++;
837                 }
838
839         }
840         if (usi->count > 0)
841                 usi->count--;
842         return 1;
843 err:
844         usi->ret = ret;
845         usi->osl_errno = (ret == -E_OSL)? osl_errno : 0;
846         return -1;
847 }
848
849 static int check_loop_return(int ret, int loop_ret, int loop_osl_errno)
850 {
851         if (ret >= 0)
852                 return ret;
853         assert(ret == -E_OSL);
854         if (osl_errno != E_OSL_LOOP)
855                 /* error not caused by loop function returning negative. */
856                 return ret;
857         assert(loop_ret < 0);
858         if (loop_ret == -E_LOOP_COMPLETE) /* no error */
859                 return 1;
860         if (loop_ret == -E_OSL) { /* osl error in loop function */
861                 assert(loop_osl_errno);
862                 osl_errno = loop_osl_errno;
863         }
864         return loop_ret;
865 }
866
867 static int adu_loop_reverse(struct osl_table *t, unsigned col_num, void *private_data,
868                 osl_rbtree_loop_func *func, int *loop_ret, int *loop_osl_errno)
869 {
870         int ret = osl(osl_rbtree_loop_reverse(t, col_num, private_data, func));
871         return check_loop_return(ret, *loop_ret, *loop_osl_errno);
872 }
873
874 static int print_user_stats(void)
875 {
876         struct user_info *ui;
877         int ret;
878
879         FOR_EACH_USER(ui) {
880                 struct user_stats_info usi = {
881                         .count = conf.limit_arg,
882                         .ui = ui
883                 };
884                 if (!ui_used(ui) || !ui_admissible(ui))
885                         continue;
886                 usi.flags = USF_PRINT_DIRNAME | USF_PRINT_BYTES | USF_COMPUTE_SUMMARY;
887                 printf("************************************************ uid %u\n",
888                         (unsigned) ui->uid);
889                 printf("----------------- Largest dirs -------------------\n");
890                 ret = adu_loop_reverse(ui->table, UT_BYTES, &usi, user_stats_loop_function,
891                         &usi.ret, &usi.osl_errno);
892                 if (ret < 0)
893                         return ret;
894                 printf("---------- dirs containing most files ------------\n");
895                 usi.count = conf.limit_arg,
896                 usi.flags = USF_PRINT_DIRNAME | USF_PRINT_FILES;
897                 ret = adu_loop_reverse(ui->table, UT_FILES, &usi, user_stats_loop_function,
898                         &usi.ret, &usi.osl_errno);
899                 if (ret < 0)
900                         return ret;
901         }
902         return 1;
903 }
904
905 static int print_statistics(void)
906 {
907         int ret;
908         struct global_stats_info gsi = {
909                 .count = conf.limit_arg,
910                 .flags = GSF_PRINT_DIRNAME | GSF_PRINT_BYTES | GSF_COMPUTE_SUMMARY
911         };
912
913         printf("----------------- Largest dirs -------------------\n");
914         ret = adu_loop_reverse(dir_table, DT_BYTES, &gsi,
915                 global_stats_loop_function, &gsi.ret, &gsi.osl_errno);
916         if (ret < 0)
917                 return ret;
918         gsi.count = conf.limit_arg;
919
920         gsi.flags = GSF_PRINT_DIRNAME | GSF_PRINT_FILES;
921         printf("---------- dirs containing most files ------------\n");
922         ret = adu_loop_reverse(dir_table, DT_FILES, &gsi,
923                 global_stats_loop_function, &gsi.ret, &gsi.osl_errno);
924         if (ret < 0)
925                 return ret;
926         printf("------------------ Global summary (dirs/files/bytes)\n"
927                 "%llu\t%llu\t%llu\n",
928                 (long long unsigned)num_dirs, (long long unsigned)num_files,
929                 (long long unsigned)num_bytes);
930         print_user_stats();
931         print_id_stats();
932         return 1;
933 }
934
935 static char *get_uid_list_name(void)
936 {
937         return make_message("%s/uid_list", conf.database_dir_arg);
938 }
939
940 static int write_uid_list(void)
941 {
942         char *buf, *filename;
943         uint32_t count = 0;
944         struct user_info *ui;
945         size_t size = num_uids * sizeof(uint32_t);
946         int ret;
947
948         if (!num_uids)
949                 return 0;
950         buf = para_malloc(size);
951         FOR_EACH_USER(ui) {
952                 if (!ui_used(ui) || !ui_admissible(ui))
953                         continue;
954                 DEBUG_LOG("saving uid %u\n", (unsigned) ui->uid);
955                 write_u32(buf + count++ * sizeof(uint32_t), ui->uid);
956         }
957         filename = get_uid_list_name();
958         ret = para_write_file(filename, buf, size);
959         free(filename);
960         free(buf);
961         return ret;
962 }
963
964 static int open_dir_table(void)
965 {
966         if (!dir_table_desc.dir) /* we did not create the table */
967                 dir_table_desc.dir = para_strdup(conf.database_dir_arg);
968         return osl(osl_open_table(&dir_table_desc, &dir_table));
969 }
970
971 static void close_dir_table(void)
972 {
973         int ret;
974
975         if (!dir_table)
976                 return;
977         ret = osl(osl_close_table(dir_table, OSL_MARK_CLEAN));
978         if (ret < 0)
979                 ERROR_LOG("failed to close dir table: %s\n", adu_strerror(-ret));
980         free((char *)dir_table_desc.dir);
981         dir_table = NULL;
982 }
983
984 static void close_user_table(struct user_info *ui)
985 {
986         int ret;
987
988         if (!ui || !ui_used(ui) || !ui_admissible(ui))
989                 return;
990         ret = osl(osl_close_table(ui->table, OSL_MARK_CLEAN));
991         if (ret < 0)
992                 ERROR_LOG("failed to close user table %u: %s\n",
993                         (unsigned) ui->uid, adu_strerror(-ret));
994         free((char *)ui->desc->name);
995         ui->desc->name = NULL;
996         free((char *)ui->desc->dir);
997         ui->desc->dir = NULL;
998         free(ui->desc);
999         ui->desc = NULL;
1000         ui->table = NULL;
1001         ui->flags = 0;
1002 }
1003
1004 static void close_user_tables(void)
1005 {
1006         struct user_info *ui;
1007
1008         FOR_EACH_USER(ui)
1009                 close_user_table(ui);
1010 }
1011
1012 static void close_all_tables(void)
1013 {
1014         close_dir_table();
1015         close_user_tables();
1016         free_hash_table();
1017 }
1018
1019 static int com_create()
1020 {
1021         uint64_t zero = 0ULL;
1022         int ret = create_tables();
1023
1024         if (ret < 0)
1025                 return ret;
1026         ret = open_dir_table();
1027         if (ret < 0)
1028                 return ret;
1029         ret = scan_dir(conf.base_dir_arg, &zero);
1030         if (ret < 0)
1031                 goto out;
1032         ret = write_uid_list();
1033 out:
1034         close_all_tables();
1035         return ret;
1036 }
1037
1038 static int read_uid_file(void)
1039 {
1040         size_t size;
1041         uint32_t n;
1042         char *filename = get_uid_list_name(), *map;
1043         int ret = mmap_full_file(filename, O_RDONLY, (void **)&map, &size, NULL);
1044
1045         if (ret < 0) {
1046                 INFO_LOG("failed to map %s\n", filename);
1047                 free(filename);
1048                 return ret;
1049         }
1050         num_uids = size / 4;
1051         INFO_LOG("found %u uids in %s\n", (unsigned)num_uids, filename);
1052         free(filename);
1053         /* hash table size should be a power of two and larger than the number of uids */
1054         uid_hash_table_size = 4;
1055         while (uid_hash_table_size < num_uids)
1056                 uid_hash_table_size *= 2;
1057         create_hash_table();
1058         for (n = 0; n < num_uids; n++) {
1059                 uint32_t uid = read_u32(map + n * sizeof(uid));
1060                 ret = search_uid(uid, OPEN_USER_TABLE, NULL);
1061                 if (ret < 0)
1062                         goto out;
1063         }
1064 out:
1065         para_munmap(map, size);
1066         return ret;
1067 }
1068
1069 static int com_select(void)
1070 {
1071         int ret;
1072
1073         ret = open_dir_table();
1074         if (ret < 0)
1075                 return ret;
1076         ret = read_uid_file();
1077         if (ret < 0)
1078                 return ret;
1079         ret = print_statistics();
1080         close_all_tables();
1081         return ret;
1082 }
1083
1084 static int check_args(void)
1085 {
1086         int i, ret;
1087
1088         /* remove trailing slashes from base-dir arg */
1089         if (conf.base_dir_given) {
1090                 size_t len = strlen(conf.base_dir_arg);
1091                 for (;;) {
1092                         if (!len) /* empty string */
1093                                 return -ERRNO_TO_ERROR(EINVAL);
1094                         if (!--len) /* length 1 is always OK */
1095                                 break;
1096                         if (conf.base_dir_arg[len] != '/')
1097                                 break; /* no trailing slash, also OK */
1098                         conf.base_dir_arg[len] = '\0';
1099                 }
1100         }
1101         if (!conf.uid_given)
1102                 return 0;
1103         admissible_uids = para_malloc(conf.uid_given * sizeof(*admissible_uids));
1104         for (i = 0; i < conf.uid_given; i++) {
1105                 ret = parse_uid_range(conf.uid_arg[i], admissible_uids + i);
1106                 if (ret < 0)
1107                         goto err;
1108         }
1109         return 1;
1110 err:
1111         free(admissible_uids);
1112         admissible_uids = NULL;
1113         return ret;
1114 }
1115
1116 int main(int argc, char **argv)
1117 {
1118         int ret;
1119         struct cmdline_parser_params params = {
1120                 .override = 0,
1121                 .initialize = 1,
1122                 .check_required = 0,
1123                 .check_ambiguity = 0,
1124                 .print_errors = 1
1125         };
1126
1127         cmdline_parser_ext(argc, argv, &conf, &params); /* aborts on errors */
1128         ret = check_args();
1129         if (ret < 0)
1130                 goto out;
1131         ret = -E_SYNTAX;
1132         if (conf.select_given)
1133                 ret = com_select();
1134         else
1135                 ret = com_create();
1136         if (ret < 0)
1137                 goto out;
1138 out:
1139         free(admissible_uids);
1140         if (ret < 0) {
1141                 ERROR_LOG("%s\n", adu_strerror(-ret));
1142                 return -EXIT_FAILURE;
1143         }
1144         return EXIT_SUCCESS;
1145 }