Merge branch 'master' into bloom
[adu.git] / select.c
1 /*
2  * Copyright (C) 2008 Andre Noll <maan@systemlinux.org>
3  *
4  * Licensed under the GPL v2. For licencing details see COPYING.
5  */
6
7 /** \file select.c \brief The select mode of adu. */
8
9 #include <dirent.h> /* readdir() */
10 #include <sys/types.h>
11 #include <regex.h>
12
13 #include "format.h"
14 #include "adu.h"
15 #include "gcc-compat.h"
16 #include "cmdline.h"
17 #include "fd.h"
18 #include "string.h"
19 #include "error.h"
20 #include "user.h"
21 #include "select.cmdline.h"
22
23 /** \cond */
24 /* global list */
25 #define GLOBAL_LIST_ATOMS \
26         ATOM(size, SIZE) \
27         ATOM(files, COUNT) \
28         ATOM(dirname, STRING) \
29
30 #define ATOM(x, y) { .name = #x, .type = AT_ ## y},
31 struct atom global_list_atoms[] = {
32         GLOBAL_LIST_ATOMS
33         {.name = NULL}
34 };
35 #undef ATOM
36 #define ATOM(x, y) gla_ ## x,
37 enum global_list_atoms {GLOBAL_LIST_ATOMS};
38 #undef ATOM
39
40 /* global summary */
41 #define GLOBAL_SUMMARY_ATOMS \
42         ATOM(dirs, COUNT) \
43         ATOM(files, COUNT) \
44         ATOM(size, SIZE)
45
46 #define ATOM(x, y) { .name = #x, .type = AT_ ## y},
47 struct atom global_summary_atoms[] = {
48         GLOBAL_SUMMARY_ATOMS
49         {.name = NULL}
50 };
51 #undef ATOM
52 #define ATOM(x, y) gsa_ ## x,
53 enum global_summary_atoms {GLOBAL_SUMMARY_ATOMS};
54 #undef ATOM
55
56 /* user list */
57 #define USER_LIST_ATOMS \
58         ATOM(pw_name, STRING) \
59         ATOM(uid, ID) \
60         ATOM(size, SIZE) \
61         ATOM(files, COUNT) \
62         ATOM(dirname, STRING) \
63
64 #define ATOM(x, y) { .name = #x, .type = AT_ ## y},
65 struct atom user_list_atoms[] = {
66         USER_LIST_ATOMS
67         {.name = NULL}
68 };
69 #undef ATOM
70 #define ATOM(x, y) ula_ ## x,
71 enum user_list_atoms {USER_LIST_ATOMS};
72 #undef ATOM
73
74 /* user list header */
75 #define USER_LIST_HEADER_ATOMS \
76         ATOM(pw_name, STRING) \
77         ATOM(uid, ID)
78
79 #define ATOM(x, y) { .name = #x, .type = AT_ ## y},
80 struct atom user_list_header_atoms[] = {
81         USER_LIST_HEADER_ATOMS
82         {.name = NULL}
83 };
84 #undef ATOM
85 #define ATOM(x, y) ulha_ ## x,
86 enum user_list_header_atoms {USER_LIST_HEADER_ATOMS};
87 #undef ATOM
88
89 /* user summary */
90 #define USER_SUMMARY_ATOMS \
91         ATOM(pw_name, STRING) \
92         ATOM(uid, ID) \
93         ATOM(dirs, COUNT) \
94         ATOM(files, COUNT) \
95         ATOM(size, SIZE)
96
97 #define ATOM(x, y) { .name = #x, .type = AT_ ## y},
98 struct atom user_summary_atoms[] = {
99         USER_SUMMARY_ATOMS
100         {.name = NULL}
101 };
102 #undef ATOM
103 #define ATOM(x, y) usa_ ## x,
104 enum user_summary_atoms {USER_SUMMARY_ATOMS};
105 #undef ATOM
106
107 /** \endcond */
108
109 struct global_list_info {
110         uint32_t count;
111         int ret;
112         int osl_errno;
113         struct format_info *fi;
114         regex_t *preg;
115         int inverse_matching;
116 };
117
118 struct global_summary_info {
119         /** Global dir count. */
120         uint64_t num_dirs;
121         /** Global files count. */
122         uint64_t num_files;
123         /** Global bytes count. */
124         uint64_t num_bytes;
125         regex_t *preg;
126         int inverse_matching;
127         int ret;
128         int osl_errno;
129 };
130
131 struct user_list_info {
132         uint32_t count;
133         struct user_info *ui;
134         struct format_info *fi;
135         regex_t *preg;
136         int inverse_matching;
137         int ret;
138         int osl_errno;
139 };
140
141 struct user_list_format_info {
142         struct format_info *fi;
143         struct format_info *header_fi;
144 };
145
146 struct user_summary_info {
147         struct user_info *ui;
148         /** Total number of files owned by this user. */
149         uint64_t files;
150         /** Total number of bytes owned by this user. */
151         uint64_t bytes;
152         /** Total number of directories that contain at least one file */
153         uint64_t dirs;
154         int ret;
155         int osl_errno;
156         regex_t *preg;
157         int inverse_matching;
158 };
159
160 struct user_summary_loop_data {
161         unsigned num_admissible_users;
162         struct user_summary_info *usis;
163         struct user_summary_info *current;
164         struct format_info *fi;
165 };
166
167 static FILE *output_file;
168
169 __printf_1_2 static int output(const char const *fmt, ...)
170 {
171         va_list argp;
172         int ret;
173
174         va_start(argp, fmt);
175         ret = vfprintf(output_file, fmt, argp);
176         va_end(argp);
177         return ret < 0? -E_OUTPUT : 1;
178 }
179
180 static int get_dir_name_by_number(uint64_t *dirnum, char **name)
181 {
182         char *result = NULL, *tmp;
183         struct osl_row *row;
184         uint64_t val = *dirnum;
185         struct osl_object obj;
186         int ret;
187         char *pfx;
188
189 again:
190         obj.data = &val;
191         obj.size = sizeof(val);
192         ret = osl(osl_get_row(dir_table, DT_NUM, &obj, &row));
193         if (ret < 0)
194                 goto out;
195         ret = osl(osl_get_object(dir_table, row, DT_PARENT_NUM, &obj));
196         if (ret < 0)
197                 goto out;
198         val = *(uint64_t *)obj.data;
199         ret = osl(osl_get_object(dir_table, row, DT_NAME, &obj));
200         if (ret < 0)
201                 goto out;
202         pfx = (select_conf.print_base_dir_given || val)? (char *)obj.data :  ".";
203         tmp = make_message("%s/%s", pfx, result? result : "");
204         free(result);
205         result = tmp;
206         if (val)
207                 goto again;
208 out:
209         if (ret < 0) {
210                 free(result);
211                 *name = NULL;
212         } else {
213                 assert(result);
214                 *name = result;
215         }
216         return ret;
217 }
218
219 static int get_dir_name_of_row(struct osl_row *dir_table_row, char **name)
220 {
221         struct osl_object obj;
222         int ret;
223
224         *name = NULL;
225         ret = osl(osl_get_object(dir_table, dir_table_row, DT_NUM, &obj));
226         if (ret < 0)
227                 return ret;
228         return get_dir_name_by_number((uint64_t *)obj.data, name);
229 }
230
231 static int get_dir_name_of_user_row(struct osl_row *user_table_row,
232                 struct user_info *ui, char **dirname)
233 {
234         struct osl_object obj;
235         int ret = osl(osl_get_object(ui->table, user_table_row,
236                 UT_DIR_NUM, &obj));
237
238         if (ret < 0)
239                 return ret;
240         return get_dir_name_by_number((uint64_t *)obj.data, dirname);
241 }
242
243 static int get_num_files_of_row(struct osl_row *row, uint64_t *num_files)
244 {
245         struct osl_object obj;
246         int ret = osl(osl_get_object(dir_table, row, DT_FILES, &obj));
247         if (ret < 0)
248                 return ret;
249         *num_files = *(uint64_t *)obj.data;
250         return 1;
251 }
252
253 static int get_num_user_files(struct osl_row *row, struct user_info *ui,
254                 uint64_t *num_files)
255 {
256         struct osl_object obj;
257         int ret = osl(osl_get_object(ui->table, row, UT_FILES, &obj));
258
259         if (ret < 0)
260                 return ret;
261         *num_files = *(uint64_t *)obj.data;
262         return 1;
263 }
264
265 static int get_num_bytes_of_row(struct osl_row *row, uint64_t *num_bytes)
266 {
267         struct osl_object obj;
268         int ret = osl(osl_get_object(dir_table, row, DT_BYTES, &obj));
269         if (ret < 0)
270                 return ret;
271         *num_bytes = *(uint64_t *)obj.data;
272         return 1;
273 }
274
275 static int get_num_user_bytes(struct osl_row *row, struct user_info *ui,
276                 uint64_t *num_bytes)
277 {
278         struct osl_object obj;
279         int ret = osl(osl_get_object(ui->table, row, UT_BYTES, &obj));
280
281         if (ret < 0)
282                 return ret;
283         *num_bytes = *(uint64_t *)obj.data;
284         return 1;
285 }
286
287 static void free_regex(regex_t *preg)
288 {
289         if (!preg)
290                 return;
291         regfree(preg);
292         free(preg);
293 }
294
295 static int compile_regex(regex_t **preg, int *invert)
296 {
297         int ret;
298         size_t size;
299         char *buf, *p = select_conf.pattern_arg;
300
301         if (!select_conf.pattern_given || !p[0]) {
302                 *preg = NULL;
303                 return 0;
304         }
305         if (p[0] == '!') {
306                 if (!p[1]) {
307                         *preg = NULL;
308                         return -E_REGEX;
309                 }
310                 *invert = 1;
311                 p++;
312         } else
313                 *invert = 0;
314         *preg = adu_malloc(sizeof(regex_t));
315         ret = regcomp(*preg, p, 0);
316         if (!ret)
317                 return 1;
318         size = regerror(ret, *preg, NULL, 0);
319         buf = adu_malloc(size);
320         regerror(ret, *preg, buf, size);
321         ERROR_LOG("%s\n", buf);
322         free(buf);
323         free_regex(*preg);
324         *preg = NULL;
325         return -E_REGEX;
326 }
327
328 static int dir_is_admissible(char *dirname, regex_t *preg, int inverse_matching)
329 {
330         int ret;
331
332         if (!preg)
333                 return 1;
334         ret = regexec(preg, dirname, 0, NULL, 0);
335         if (ret == REG_NOMATCH && !inverse_matching)
336                 return 0;
337         if (ret != REG_NOMATCH && inverse_matching)
338                 return 0;
339         return 1;
340 }
341
342 static int check_loop_return(int ret, int loop_ret, int loop_osl_errno)
343 {
344         if (ret >= 0)
345                 return ret;
346         assert(ret == -E_OSL);
347         if (osl_errno != E_OSL_LOOP)
348                 /* error not caused by loop function returning negative. */
349                 return ret;
350         assert(loop_ret < 0);
351         if (loop_ret == -E_LOOP_COMPLETE) /* no error */
352                 return 1;
353         if (loop_ret == -E_OSL) { /* osl error in loop function */
354                 assert(loop_osl_errno);
355                 osl_errno = loop_osl_errno;
356         }
357         return loop_ret;
358 }
359
360 static int adu_loop_reverse(struct osl_table *t, unsigned col_num, void *private_data,
361                 osl_rbtree_loop_func *func, int *loop_ret, int *loop_osl_errno)
362 {
363         int ret = osl(osl_rbtree_loop_reverse(t, col_num, private_data, func));
364         return check_loop_return(ret, *loop_ret, *loop_osl_errno);
365 }
366
367 static int global_summary_loop_function(struct osl_row *row, void *data)
368 {
369         struct global_summary_info *gsi = data;
370         int ret;
371         uint64_t num;
372
373         if (gsi->preg) {
374                 char *dirname;
375                 ret = get_dir_name_of_row(row, &dirname);
376                 if (ret < 0)
377                         goto err;
378                 ret = dir_is_admissible(dirname, gsi->preg, gsi->inverse_matching);
379                 free(dirname);
380                 if (!ret)
381                         return 1;
382         }
383
384         ret = get_num_files_of_row(row, &num);
385         if (ret < 0)
386                 goto err;
387         gsi->num_files += num;
388
389         ret = get_num_bytes_of_row(row, &num);
390         if (ret < 0)
391                 goto err;
392         gsi->num_bytes += num;
393         gsi->num_dirs++;
394         return 1;
395 err:
396         gsi->ret = ret;
397         gsi->osl_errno = (ret == -E_OSL)? osl_errno : 0;
398         return ret;
399 }
400
401 static int print_global_summary(struct format_info *fi)
402 {
403         int ret;
404         char *buf;
405         struct global_summary_info gsi = {.num_dirs = 0};
406         char *header = select_conf.header_given? select_conf.header_arg :
407                 "Global summary\n";
408
409         union atom_value values[] = {
410                 [gsa_dirs] = {.num_value = 0ULL},
411                 [gsa_files] = {.num_value =  0ULL},
412                 [gsa_size] = {.num_value =  0ULL}
413         };
414
415         ret = compile_regex(&gsi.preg, &gsi.inverse_matching);
416         if (ret < 0)
417                 return ret;
418         ret = adu_loop_reverse(dir_table, DT_BYTES, &gsi,
419                 global_summary_loop_function, &gsi.ret, &gsi.osl_errno);
420         free_regex(gsi.preg);
421         if (ret < 0)
422                 return ret;
423         values[gsa_dirs].num_value = (long long unsigned)gsi.num_dirs;
424         values[gsa_files].num_value = (long long unsigned)gsi.num_files;
425         values[gsa_size].num_value = (long long unsigned)gsi.num_bytes;
426
427         ret = output("%s", header);
428         if (ret < 0)
429                 return ret;
430         buf = format_items(fi, values);
431         ret = output("%s", buf);
432         free(buf);
433         return ret;
434 }
435
436 static int user_summary_loop_function(struct osl_row *row, void *data)
437 {
438         struct user_summary_info *usi = data;
439         uint64_t num;
440         int ret;
441
442         if (usi->preg) {
443                 char *dirname;
444                 ret = get_dir_name_of_row(row, &dirname);
445                 if (ret < 0)
446                         goto err;
447                 ret = dir_is_admissible(dirname, usi->preg, usi->inverse_matching);
448                 free(dirname);
449                 if (!ret)
450                         return 1;
451         }
452         ret = get_num_user_files(row, usi->ui, &num);
453         if (ret < 0)
454                 goto err;
455         usi->files += num;
456         ret = get_num_user_bytes(row, usi->ui, &num);
457         if (ret < 0)
458                 goto err;
459         usi->bytes += num;
460         usi->dirs++;
461         return 1;
462 err:
463         usi->ret = ret;
464         usi->osl_errno = (ret == -E_OSL)? osl_errno : 0;
465         return ret;
466 }
467
468 static int compute_user_summary(struct user_info *ui, void *data)
469 {
470         struct user_summary_loop_data *usld = data;
471         struct user_summary_info *usi = usld->current++;
472         int ret = compile_regex(&usi->preg, &usi->inverse_matching);
473
474         if (ret < 0)
475                 return ret;
476         usi->ui = ui;
477         ret = adu_loop_reverse(ui->table, UT_BYTES, usi, user_summary_loop_function,
478                 &usi->ret, &usi->osl_errno);
479         free_regex(usi->preg);
480         return ret;
481 }
482
483 static int print_user_summary_line(struct user_summary_info *usi,
484                 struct format_info *fi)
485 {
486         struct user_info *ui = usi->ui;
487         union atom_value values[] = {
488                 [usa_pw_name] = {.string_value = ui->pw_name?
489                         ui->pw_name : "?"},
490                 [usa_uid] = {.num_value = (long long unsigned)ui->uid},
491                 [usa_dirs] = {.num_value = (long long unsigned)usi->dirs},
492                 [usa_files] = {.num_value = (long long unsigned)usi->files},
493                 [usa_size] = {.num_value =  (long long unsigned)usi->bytes}
494         };
495         char *buf = format_items(fi, values);
496         int ret = output("%s", buf);
497
498         free(buf);
499         return ret;
500 }
501
502 static int name_comp(const void *a, const void *b)
503 {
504         const struct user_summary_info *x = a, *y = b;
505         char *n1 = x->ui->pw_name;
506         char *n2 = y->ui->pw_name;
507
508         if (!n1)
509                 return 1;
510         if (!n2)
511                 return -1;
512         return strcmp(n1, n2);
513 }
514
515 static int uid_comp(const void *a, const void *b)
516 {
517         const struct user_summary_info *x = a, *y = b;
518         return -NUM_COMPARE(x->ui->uid, y->ui->uid);
519 }
520
521 static int dir_count_comp(const void *a, const void *b)
522 {
523         const struct user_summary_info *x = a, *y = b;
524         return NUM_COMPARE(x->dirs, y->dirs);
525 }
526
527 static int file_count_comp(const void *a, const void *b)
528 {
529         const struct user_summary_info *x = a, *y = b;
530         return NUM_COMPARE(x->files, y->files);
531 }
532
533 static int size_comp(const void *a, const void *b)
534 {
535         const struct user_summary_info *x = a, *y = b;
536         return NUM_COMPARE(x->bytes, y->bytes);
537 }
538
539 static int count_admissible_users(__a_unused struct user_info *ui, void *data)
540 {
541         struct user_summary_loop_data *usld = data;
542         usld->num_admissible_users++;
543         return 1;
544 }
545
546 static int print_user_summary(struct format_info *fi)
547 {
548         int i, ret;
549         int (*comp)(const void *a, const void *b);
550         struct user_summary_loop_data usld = { .fi = fi};
551         char *header = select_conf.header_given? select_conf.header_arg :
552                 "User summary\n";
553
554         ret = output("%s", header);
555         if (ret < 0)
556                 return ret;
557         ret = for_each_admissible_user(count_admissible_users, &usld);
558         if (ret < 0)
559                 return ret;
560         if (usld.num_admissible_users == 0)
561                 return 1;
562         usld.usis = adu_calloc(usld.num_admissible_users
563                 * sizeof(struct user_summary_info));
564         usld.current = usld.usis;
565         ret = for_each_admissible_user(compute_user_summary, &usld);
566         if (ret < 0)
567                 goto out;
568         switch (select_conf.user_summary_sort_arg) {
569         case user_summary_sort_arg_name:
570                 comp = name_comp;
571                 break;
572         case user_summary_sort_arg_uid:
573                 comp = uid_comp;
574                 break;
575         case user_summary_sort_arg_dir_count:
576                 comp = dir_count_comp;
577                 break;
578         case user_summary_sort_arg_file_count:
579                 comp = file_count_comp;
580                 break;
581         case user_summary_sort_arg_size:
582                 comp = size_comp;
583                 break;
584         default: /* this should never happen, but anyway */
585                 comp = size_comp;
586                 break;
587         }
588         qsort(usld.usis, usld.num_admissible_users,
589                 sizeof(struct user_summary_info), comp);
590         for (i = 0; i < usld.num_admissible_users; i++) {
591                 if (select_conf.limit_arg >= 0 && i > select_conf.limit_arg)
592                         break;
593                 print_user_summary_line(usld.usis + i, usld.fi);
594         }
595 out:
596         free(usld.usis);
597         return ret;
598 }
599
600 static int user_list_loop_function(struct osl_row *row, void *data)
601 {
602         struct user_list_info *uli = data;
603         union atom_value values[] = {
604                 [ula_pw_name] = {.string_value = uli->ui->pw_name?
605                         uli->ui->pw_name : "?"},
606                 [ula_uid] = {.num_value = (long long unsigned)uli->ui->uid},
607                 [ula_files] = {.num_value = 0ULL},
608                 [ula_size] = {.num_value =  0ULL},
609                 [ula_dirname] = {.string_value = NULL}
610         };
611         uint64_t num;
612         int ret;
613         char *dirname = NULL, *buf;
614
615         check_signals();
616         ret = -E_LOOP_COMPLETE;
617         if (!uli->count)
618                 goto err;
619
620         ret = get_dir_name_of_user_row(row, uli->ui, &dirname);
621         if (ret < 0)
622                 goto err;
623         if (!dir_is_admissible(dirname, uli->preg, uli->inverse_matching)) {
624                 free(dirname);
625                 return 1;
626         }
627         values[ula_dirname].string_value = dirname;
628
629         ret = get_num_user_files(row, uli->ui, &num);
630         if (ret < 0)
631                 goto err;
632         values[ula_files].num_value = num;
633
634         ret = get_num_user_bytes(row, uli->ui, &num);
635         if (ret < 0)
636                 goto err;
637         values[ula_size].num_value = num;
638
639         buf = format_items(uli->fi, values);
640         free(dirname);
641         dirname = NULL;
642         ret = output("%s", buf);
643         free(buf);
644         if (ret < 0)
645                 goto err;
646         uli->count--;
647         return ret;
648 err:
649         free(dirname);
650         uli->ret = ret;
651         uli->osl_errno = (ret == -E_OSL)? osl_errno : 0;
652         return ret;
653 }
654
655 static int print_user_list(struct user_info *ui, void *data)
656 {
657         struct user_list_format_info *ulfi = data;
658         int ret;
659         enum user_table_columns sort_column;
660         struct user_list_info uli = {
661                 .ui = ui,
662                 .fi = ulfi->fi,
663                 .count = select_conf.limit_arg
664         };
665         union atom_value header_values[] = {
666                 [ulha_uid] = {.num_value = (long long unsigned)ui->uid},
667                 [ulha_pw_name] = {.string_value = ui->pw_name?
668                         ui->pw_name : "?"}
669         };
670         char *buf = format_items(ulfi->header_fi, header_values);
671
672         ret = output("%s", buf);
673         free(buf);
674         if (ret < 0)
675                 return ret;
676         if (select_conf.list_sort_arg == list_sort_arg_file_count)
677                 sort_column = UT_FILES;
678         else
679                 sort_column = UT_BYTES;
680
681         ret = compile_regex(&uli.preg, &uli.inverse_matching);
682         if (ret < 0)
683                 return ret;
684         ret = adu_loop_reverse(ui->table, sort_column, &uli,
685                 user_list_loop_function, &uli.ret, &uli.osl_errno);
686         free_regex(uli.preg);
687         return ret;
688 }
689
690 static int print_user_lists(struct format_info *fi)
691 {
692         struct user_list_format_info ulfi = {.fi = fi};
693         char *header_fmt = select_conf.header_given?
694                 select_conf.header_arg : "uid %(uid)(%(pw_name)):\n";
695         int ret = parse_format_string(header_fmt,
696                 user_list_header_atoms, &ulfi.header_fi);
697         if (ret < 0)
698                 return ret;
699         ret = for_each_admissible_user(print_user_list, &ulfi);
700         free_format_info(ulfi.header_fi);
701         return ret;
702 }
703
704 static int global_list_loop_function(struct osl_row *row, void *data)
705 {
706         struct global_list_info *gli = data;
707         union atom_value values[] = {
708                 [gla_size] = {.num_value = 0ULL},
709                 [gla_files] = {.num_value =  0ULL},
710                 [gla_dirname] = {.string_value = NULL}
711         };
712         uint64_t num_files, num_bytes;
713         char *dirname = NULL, *buf;
714         int ret;
715
716         check_signals();
717         ret = -E_LOOP_COMPLETE;
718         if (!gli->count)
719                 goto err;
720
721         ret = get_dir_name_of_row(row, &dirname);
722         if (ret < 0)
723                 goto err;
724         if (!dir_is_admissible(dirname, gli->preg, gli->inverse_matching)) {
725                 free(dirname);
726                 return 1;
727         }
728         values[gla_dirname].string_value = dirname;
729
730         ret = get_num_files_of_row(row, &num_files);
731         if (ret < 0)
732                 goto err;
733         values[gla_files].num_value = (long long unsigned)num_files;
734
735         ret = get_num_bytes_of_row(row, &num_bytes);
736         if (ret < 0)
737                 goto err;
738         values[gla_size].num_value = (long long unsigned)num_bytes;
739
740         buf = format_items(gli->fi, values);
741         free(dirname);
742         dirname = NULL;
743         ret = output("%s", buf);
744         free(buf);
745         if (ret < 0)
746                 goto err;
747         if (gli->count > 0)
748                 gli->count--;
749         return ret;
750 err:
751         free(dirname);
752         gli->ret = ret;
753         gli->osl_errno = (ret == -E_OSL)? osl_errno : 0;
754         return -1;
755 }
756
757 static int print_global_list(struct format_info *fi)
758 {
759         int ret;
760         enum dir_table_columns sort_column;
761         struct global_list_info gli = {
762                 .fi = fi,
763                 .count = select_conf.limit_arg
764         };
765         char *header = select_conf.header_given?
766                 select_conf.header_arg : "Global list\n";
767
768         ret = output("%s", header);
769         if (ret < 0)
770                 return ret;
771         if (select_conf.list_sort_arg == list_sort_arg_file_count)
772                 sort_column = DT_FILES;
773         else
774                 sort_column = DT_BYTES;
775         ret = compile_regex(&gli.preg, &gli.inverse_matching);
776         if (ret < 0)
777                 return ret;
778         ret = adu_loop_reverse(dir_table, sort_column, &gli,
779                 global_list_loop_function, &gli.ret, &gli.osl_errno);
780         free_regex(gli.preg);
781         return ret;
782 }
783
784 static int print_statistics(struct format_info *fi)
785 {
786         switch (select_conf.select_mode_arg) {
787         case select_mode_arg_global_list:
788                 return print_global_list(fi);
789         case select_mode_arg_global_summary:
790                 return print_global_summary(fi);
791         case select_mode_arg_user_list:
792                 return print_user_lists(fi);
793         case select_mode_arg_user_summary:
794                 return print_user_summary(fi);
795         };
796         ERROR_LOG("bad select mode\n");
797         return -ERRNO_TO_ERROR(EINVAL);
798 }
799
800 static int open_pipe(char *path)
801 {
802         int p[2], ret, argc;
803         char **argv;
804
805         ret = pipe(p);
806         if (ret < 0)
807                 return ERRNO_TO_ERROR(errno);
808         ret = fork();
809         if (ret < 0)
810                 return ERRNO_TO_ERROR(errno);
811         if (ret) { /* parent */
812                 DEBUG_LOG("created process %d\n", ret);
813                 close(p[0]);
814                 output_file = fdopen(p[1], "w");
815                 if (!output_file)
816                         return ERRNO_TO_ERROR(errno);
817                 return 1;
818         }
819         close(p[1]);
820         if (p[0] != STDIN_FILENO)
821                 dup2(p[0], STDIN_FILENO);
822         DEBUG_LOG("executing %s\n", path);
823         argc = split_args(path, &argv, " \t");
824         execvp(argv[0], argv);
825         ERROR_LOG("error executing %s: %s\n", path,
826                 adu_strerror(ERRNO_TO_ERROR(errno)));
827         _exit(EXIT_FAILURE);
828 }
829
830 static int open_output_stream(void)
831 {
832         char *p;
833         int ret, flags = O_WRONLY | O_CREAT;
834
835         if (!select_conf.output_given)
836                 goto use_stdout;
837         p = select_conf.output_arg;
838         switch (p[0]) {
839         case '\0': /* empty string */
840                 goto bad_output_arg;
841         case '-':
842                 if (!p[1]) /* "-" means stdout */
843                         goto use_stdout;
844                 /* string starting with a dash */
845                 flags |= O_EXCL;
846                 goto open_file;
847         case '>':
848                 if (!p[1]) /* ">" is invalid */
849                         goto bad_output_arg;
850                 if (p[1] != '>') {
851                         p++;
852                         flags |= O_TRUNC;
853                         goto open_file;
854                 }
855                 /* string starting with ">>" */
856                 if (!p[2]) /* ">>" is invalid */
857                         goto bad_output_arg;
858                 flags |= O_APPEND;
859                 p += 2;
860                 goto open_file;
861         case '|':
862                 if (!p[1]) /* "|" is invalid */
863                         goto bad_output_arg;
864                 p++;
865                 return open_pipe(p);
866         default: /* args starts with no magic character */
867                 flags |= O_EXCL;
868                 goto open_file;
869         }
870 use_stdout:
871         output_file = stdout;
872         return 1;
873 bad_output_arg:
874         output_file = NULL;
875         return -E_BAD_OUTPUT_ARG;
876 open_file:
877         /*
878          * glibc's 'x' mode to fopen is not portable, so use open() and
879          * fdopen().
880          */
881         ret = open(p, flags, 0644);
882         if (ret < 0)
883                 return -ERRNO_TO_ERROR(errno);
884         output_file = fdopen(ret, "w");
885         if (!output_file)
886                 return -ERRNO_TO_ERROR(errno);
887         return 1;
888 }
889
890 /**
891  * Execute a select query.
892  *
893  * \param admissible_uids User IDs to take into account.
894  * \param fi Format information.
895  *
896  * Called once in select mode or for each \a run command in interactive mode.
897  *
898  * Open the output stream and the dir table if not already open. For each
899  * admissible uid, the user table is opened if necessary. After these
900  * preparations, the output according to \a select_mode and \a fi is written to
901  * the output stream.
902  *
903  * \return Standard.
904  */
905 int run_select_query(struct uid_range *admissible_uids, struct format_info *fi)
906 {
907         int ret = open_output_stream();
908
909         if (ret < 0)
910                 goto out;
911         ret = open_dir_table(0);
912         if (ret < 0)
913                 goto out;
914         check_signals();
915         ret = open_admissible_user_tables(conf.database_dir_arg,
916                 admissible_uids);
917         if (ret < 0)
918                 goto out;
919         check_signals();
920         ret = print_statistics(fi);
921 out:
922         if (output_file && output_file != stdout) {
923                 fclose(output_file);
924                 output_file = NULL;
925         }
926         return ret;
927 }
928
929 /** Default format string for global_list mode. */
930 #define GLOBAL_LIST_DFLT_FMT "%(size:r:8) %(files:r:8) %(dirname)\n"
931 /** Default format string for global_summary mode. */
932 #define GLOBAL_SUMMARY_DFLT_FMT "#directories: %(dirs), #files: %(files), size: %(size)\n\n"
933 /** Default format string for user_list mode. */
934 #define USER_LIST_DFLT_FMT "%(size:r:5) %(files:r:5) %(dirname)\n"
935 /** Default format string for user_summary mode. */
936 #define USER_SUMMARY_DFLT_FMT "%(pw_name:l:16) %(uid:r:5) %(dirs:r:5) %(files:r:5) %(size:r:5)\n"
937
938 static int setup_format_string(char *fmt, struct format_info **fi)
939 {
940         struct atom *atoms;
941
942         if (!fmt)
943                 INFO_LOG("using default format string\n");
944         switch (select_conf.select_mode_arg) {
945         case select_mode_arg_global_list:
946                 if (!fmt)
947                         fmt = GLOBAL_LIST_DFLT_FMT;
948                 atoms = global_list_atoms;
949                 break;
950         case select_mode_arg_global_summary:
951                 if (!fmt)
952                         fmt = GLOBAL_SUMMARY_DFLT_FMT;
953                 atoms = global_summary_atoms;
954                 break;
955         case select_mode_arg_user_list:
956                 if (!fmt)
957                         fmt = USER_LIST_DFLT_FMT;
958                 atoms = user_list_atoms;
959                 break;
960         case select_mode_arg_user_summary:
961                 if (!fmt)
962                         fmt = USER_SUMMARY_DFLT_FMT;
963                 atoms = user_summary_atoms;
964                 break;
965         default:
966                 ERROR_LOG("bad select mode\n");
967                 return -ERRNO_TO_ERROR(EINVAL);
968         };
969         INFO_LOG("format string: %s\n", fmt);
970         return parse_format_string(fmt, atoms, fi);
971 }
972
973 /**
974  * Parse a given format string.
975  *
976  * \param string The format string to parse.
977  * \param params gengetopt parameters.
978  * \param admissible_uids The array of admissible uid ranges.
979  * \param fi The format info to be used with format_items().
980  *
981  * If \a string is not \p NULL, it is broken down into its components using
982  * \ref create_argv() and the resulting argument vector is passed together with
983  * \a params to gengetopt's command line parser. If --help or --detailed-help
984  * was specified in \a string, the corresponding help text is printed and the
985  * function returns zero.
986  *
987  * Otherwise, any --uid or --user options are parsed and transformed into an
988  * array of admissible uids which is returned via \a admissible_uids.
989  *
990  * Finally, the format string given by --format (or the default format string
991  * for the given select mode if no --format option was given in \a string) is
992  * parsed as well resulting in a format_info structure which is returned via
993  * \a fi. The caller uses the \a fi pointer later to format each output line.
994  *
995  * \return Negative on errors, zero if --help or --detailed-help was given,
996  * positive otherwise.
997  *
998  * \sa format_items().
999  */
1000 int parse_select_options(char *string, struct select_cmdline_parser_params *params,
1001                 struct uid_range **admissible_uids, struct format_info **fi)
1002 {
1003         int ret, num_uid_ranges;
1004         const char **line;
1005         char *fmt = NULL;
1006
1007         if (string) {
1008                 int argc;
1009                 char **argv;
1010
1011                 ret = create_argv(string, &argv);
1012                 if (ret < 0)
1013                         return ret;
1014                 argc = ret;
1015                 ret = select_cmdline_parser_ext(argc, argv, &select_conf, params);
1016                 free_argv(argv);
1017                 if (ret)
1018                         return -E_SYNTAX;
1019                 if (select_conf.help_given || select_conf.detailed_help_given)
1020                         goto help;
1021                 fmt = select_conf.format_arg;
1022         }
1023         ret = parse_uid_arg(select_conf.uid_arg, admissible_uids);
1024         if (ret < 0)
1025                 return ret;
1026         num_uid_ranges = ret;
1027         ret = append_users(select_conf.user_arg, select_conf.user_given,
1028                 admissible_uids, num_uid_ranges);
1029         if (ret < 0)
1030                 return ret;
1031         return setup_format_string(fmt, fi);
1032 help:
1033         line = select_conf.detailed_help_given?
1034                 select_args_info_detailed_help : select_args_info_help;
1035         if (!output_file)
1036                 output_file = stdout;
1037         for (; *line; line++) {
1038                 ret = output("%s\n", *line);
1039                 if (ret < 0)
1040                         return ret;
1041         }
1042         return 0;
1043 }
1044
1045 /**
1046  * Main function for select mode.
1047  *
1048  * \return Standard.
1049  */
1050 int com_select(void)
1051 {
1052         struct uid_range *admissible_uids = NULL;
1053         int ret;
1054         struct format_info *fi;
1055         struct select_cmdline_parser_params params = {
1056                 .override = 1,
1057                 .initialize = 1,
1058                 .check_required = 1,
1059                 .check_ambiguity = 1,
1060                 .print_errors = 1
1061         };
1062
1063         ret = parse_select_options(conf.select_options_arg, &params,
1064                 &admissible_uids, &fi);
1065         if (ret > 0) {
1066                 ret = read_uid_file(conf.database_dir_arg);
1067                 if (ret < 0)
1068                         goto out;
1069                 ret = run_select_query(admissible_uids, fi);
1070                 free_format_info(fi);
1071         }
1072 out:
1073         select_cmdline_parser_free(&select_conf);
1074         return ret;
1075 }