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