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