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