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