]> git.tuebingen.mpg.de Git - adu.git/blob - select.c
interactive.c: Return proper error on icom_set() failure.
[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 /* row: a pointer to a row of the *user* table */
440 static int user_summary_loop_function(struct osl_row *row, void *data)
441 {
442         struct user_summary_info *usi = data;
443         uint64_t num;
444         int ret;
445
446         if (usi->preg) {
447                 char *dirname;
448                 ret = get_dir_name_of_user_row(row, usi->ui, &dirname);
449                 if (ret < 0)
450                         goto err;
451                 ret = dir_is_admissible(dirname, usi->preg, usi->inverse_matching);
452                 free(dirname);
453                 if (!ret)
454                         return 1;
455         }
456         ret = get_num_user_files(row, usi->ui, &num);
457         if (ret < 0)
458                 goto err;
459         usi->files += num;
460         ret = get_num_user_bytes(row, usi->ui, &num);
461         if (ret < 0)
462                 goto err;
463         usi->bytes += num;
464         usi->dirs++;
465         return 1;
466 err:
467         usi->ret = ret;
468         usi->osl_errno = (ret == -E_OSL)? osl_errno : 0;
469         return ret;
470 }
471
472 static int compute_user_summary(struct user_info *ui, void *data)
473 {
474         struct user_summary_loop_data *usld = data;
475         struct user_summary_info *usi = usld->current++;
476         int ret = compile_regex(&usi->preg, &usi->inverse_matching);
477
478         if (ret < 0)
479                 return ret;
480         usi->ui = ui;
481         ret = adu_loop_reverse(ui->table, UT_BYTES, usi, user_summary_loop_function,
482                 &usi->ret, &usi->osl_errno);
483         free_regex(usi->preg);
484         return ret;
485 }
486
487 static int print_user_summary_line(struct user_summary_info *usi,
488                 struct format_info *fi)
489 {
490         struct user_info *ui = usi->ui;
491         union atom_value values[] = {
492                 [usa_pw_name] = {.string_value = ui->pw_name?
493                         ui->pw_name : "?"},
494                 [usa_uid] = {.num_value = (long long unsigned)ui->uid},
495                 [usa_dirs] = {.num_value = (long long unsigned)usi->dirs},
496                 [usa_files] = {.num_value = (long long unsigned)usi->files},
497                 [usa_size] = {.num_value =  (long long unsigned)usi->bytes}
498         };
499         char *buf = format_items(fi, values);
500         int ret = output("%s", buf);
501
502         free(buf);
503         return ret;
504 }
505
506 static int name_comp(const void *a, const void *b)
507 {
508         const struct user_summary_info *x = a, *y = b;
509         char *n1 = x->ui->pw_name;
510         char *n2 = y->ui->pw_name;
511
512         if (!n1)
513                 return 1;
514         if (!n2)
515                 return -1;
516         return strcmp(n1, n2);
517 }
518
519 static int uid_comp(const void *a, const void *b)
520 {
521         const struct user_summary_info *x = a, *y = b;
522         return -NUM_COMPARE(x->ui->uid, y->ui->uid);
523 }
524
525 static int dir_count_comp(const void *a, const void *b)
526 {
527         const struct user_summary_info *x = a, *y = b;
528         return NUM_COMPARE(x->dirs, y->dirs);
529 }
530
531 static int file_count_comp(const void *a, const void *b)
532 {
533         const struct user_summary_info *x = a, *y = b;
534         return NUM_COMPARE(x->files, y->files);
535 }
536
537 static int size_comp(const void *a, const void *b)
538 {
539         const struct user_summary_info *x = a, *y = b;
540         return NUM_COMPARE(x->bytes, y->bytes);
541 }
542
543 static int count_admissible_users(__a_unused struct user_info *ui, void *data)
544 {
545         struct user_summary_loop_data *usld = data;
546         usld->num_admissible_users++;
547         return 1;
548 }
549
550 static int print_user_summary(struct format_info *fi)
551 {
552         int i, ret;
553         int (*comp)(const void *a, const void *b);
554         struct user_summary_loop_data usld = { .fi = fi};
555         char *header = select_conf.header_given? select_conf.header_arg :
556                 "User summary\n";
557
558         ret = output("%s", header);
559         if (ret < 0)
560                 return ret;
561         ret = for_each_admissible_user(count_admissible_users, &usld);
562         if (ret < 0)
563                 return ret;
564         if (usld.num_admissible_users == 0)
565                 return 1;
566         usld.usis = adu_calloc(usld.num_admissible_users
567                 * sizeof(struct user_summary_info));
568         usld.current = usld.usis;
569         ret = for_each_admissible_user(compute_user_summary, &usld);
570         if (ret < 0)
571                 goto out;
572         switch (select_conf.user_summary_sort_arg) {
573         case user_summary_sort_arg_name:
574                 comp = name_comp;
575                 break;
576         case user_summary_sort_arg_uid:
577                 comp = uid_comp;
578                 break;
579         case user_summary_sort_arg_dir_count:
580                 comp = dir_count_comp;
581                 break;
582         case user_summary_sort_arg_file_count:
583                 comp = file_count_comp;
584                 break;
585         case user_summary_sort_arg_size:
586                 comp = size_comp;
587                 break;
588         default: /* this should never happen, but anyway */
589                 comp = size_comp;
590                 break;
591         }
592         qsort(usld.usis, usld.num_admissible_users,
593                 sizeof(struct user_summary_info), comp);
594         for (i = 0; i < usld.num_admissible_users; i++) {
595                 if (select_conf.limit_arg >= 0 && i > select_conf.limit_arg)
596                         break;
597                 ret = print_user_summary_line(usld.usis + i, usld.fi);
598                 if (ret < 0)
599                         goto out;
600         }
601         ret = output("%s", select_conf.trailer_arg);
602 out:
603         free(usld.usis);
604         return ret;
605 }
606
607 static int user_list_loop_function(struct osl_row *row, void *data)
608 {
609         struct user_list_info *uli = data;
610         union atom_value values[] = {
611                 [ula_pw_name] = {.string_value = uli->ui->pw_name?
612                         uli->ui->pw_name : "?"},
613                 [ula_uid] = {.num_value = (long long unsigned)uli->ui->uid},
614                 [ula_files] = {.num_value = 0ULL},
615                 [ula_size] = {.num_value =  0ULL},
616                 [ula_dirname] = {.string_value = NULL}
617         };
618         uint64_t num;
619         int ret;
620         char *dirname = NULL, *buf;
621
622         check_signals();
623         ret = -E_LOOP_COMPLETE;
624         if (!uli->count)
625                 goto err;
626
627         ret = get_dir_name_of_user_row(row, uli->ui, &dirname);
628         if (ret < 0)
629                 goto err;
630         if (!dir_is_admissible(dirname, uli->preg, uli->inverse_matching)) {
631                 free(dirname);
632                 return 1;
633         }
634         values[ula_dirname].string_value = dirname;
635
636         ret = get_num_user_files(row, uli->ui, &num);
637         if (ret < 0)
638                 goto err;
639         values[ula_files].num_value = num;
640
641         ret = get_num_user_bytes(row, uli->ui, &num);
642         if (ret < 0)
643                 goto err;
644         values[ula_size].num_value = num;
645
646         buf = format_items(uli->fi, values);
647         free(dirname);
648         dirname = NULL;
649         ret = output("%s", buf);
650         free(buf);
651         if (ret < 0)
652                 goto err;
653         uli->count--;
654         return ret;
655 err:
656         free(dirname);
657         uli->ret = ret;
658         uli->osl_errno = (ret == -E_OSL)? osl_errno : 0;
659         return ret;
660 }
661
662 static int print_user_list(struct user_info *ui, void *data)
663 {
664         struct user_list_format_info *ulfi = data;
665         int ret;
666         enum user_table_columns sort_column;
667         struct user_list_info uli = {
668                 .ui = ui,
669                 .fi = ulfi->fi,
670                 .count = select_conf.limit_arg
671         };
672         union atom_value header_trailer_values[] = {
673                 [ulha_uid] = {.num_value = (long long unsigned)ui->uid},
674                 [ulha_pw_name] = {.string_value = ui->pw_name?
675                         ui->pw_name : "?"}
676         };
677         char *buf = format_items(ulfi->header_fi, header_trailer_values);
678
679         ret = output("%s", buf);
680         free(buf);
681         if (ret < 0)
682                 return ret;
683         if (select_conf.list_sort_arg == list_sort_arg_file_count)
684                 sort_column = UT_FILES;
685         else
686                 sort_column = UT_BYTES;
687
688         ret = compile_regex(&uli.preg, &uli.inverse_matching);
689         if (ret < 0)
690                 return ret;
691         ret = adu_loop_reverse(ui->table, sort_column, &uli,
692                 user_list_loop_function, &uli.ret, &uli.osl_errno);
693         free_regex(uli.preg);
694         if (ret < 0)
695                 return ret;
696         buf = format_items(ulfi->trailer_fi, header_trailer_values);
697         ret = output("%s", buf);
698         free(buf);
699         return ret;
700 }
701
702 static int print_user_lists(struct format_info *fi)
703 {
704         struct user_list_format_info ulfi = {.fi = fi};
705         char *header_fmt = select_conf.header_given?
706                 select_conf.header_arg : "uid %(uid)(%(pw_name)):\n";
707         char *trailer_fmt = select_conf.trailer_arg;
708         int ret = parse_format_string(header_fmt,
709                 user_list_header_trailer_atoms, &ulfi.header_fi);
710         if (ret < 0)
711                 return ret;
712         ret = parse_format_string(trailer_fmt,
713                 user_list_header_trailer_atoms, &ulfi.trailer_fi);
714         if (ret < 0)
715                 return ret;
716         ret = for_each_admissible_user(print_user_list, &ulfi);
717         free_format_info(ulfi.header_fi);
718         free_format_info(ulfi.trailer_fi);
719         return ret;
720 }
721
722 static int global_list_loop_function(struct osl_row *row, void *data)
723 {
724         struct global_list_info *gli = data;
725         union atom_value values[] = {
726                 [gla_size] = {.num_value = 0ULL},
727                 [gla_files] = {.num_value =  0ULL},
728                 [gla_dirname] = {.string_value = NULL}
729         };
730         uint64_t num_files, num_bytes;
731         char *dirname = NULL, *buf;
732         int ret;
733
734         check_signals();
735         ret = -E_LOOP_COMPLETE;
736         if (!gli->count)
737                 goto err;
738
739         ret = get_dir_name_of_row(row, &dirname);
740         if (ret < 0)
741                 goto err;
742         if (!dir_is_admissible(dirname, gli->preg, gli->inverse_matching)) {
743                 free(dirname);
744                 return 1;
745         }
746         values[gla_dirname].string_value = dirname;
747
748         ret = get_num_files_of_row(row, &num_files);
749         if (ret < 0)
750                 goto err;
751         values[gla_files].num_value = (long long unsigned)num_files;
752
753         ret = get_num_bytes_of_row(row, &num_bytes);
754         if (ret < 0)
755                 goto err;
756         values[gla_size].num_value = (long long unsigned)num_bytes;
757
758         buf = format_items(gli->fi, values);
759         free(dirname);
760         dirname = NULL;
761         ret = output("%s", buf);
762         free(buf);
763         if (ret < 0)
764                 goto err;
765         if (gli->count > 0)
766                 gli->count--;
767         return ret;
768 err:
769         free(dirname);
770         gli->ret = ret;
771         gli->osl_errno = (ret == -E_OSL)? osl_errno : 0;
772         return -1;
773 }
774
775 static int print_global_list(struct format_info *fi)
776 {
777         int ret;
778         enum dir_table_columns sort_column;
779         struct global_list_info gli = {
780                 .fi = fi,
781                 .count = select_conf.limit_arg
782         };
783         char *header = select_conf.header_given?
784                 select_conf.header_arg : "Global list\n";
785
786         ret = output("%s", header);
787         if (ret < 0)
788                 return ret;
789         if (select_conf.list_sort_arg == list_sort_arg_file_count)
790                 sort_column = DT_FILES;
791         else
792                 sort_column = DT_BYTES;
793         ret = compile_regex(&gli.preg, &gli.inverse_matching);
794         if (ret < 0)
795                 return ret;
796         ret = adu_loop_reverse(dir_table, sort_column, &gli,
797                 global_list_loop_function, &gli.ret, &gli.osl_errno);
798         free_regex(gli.preg);
799         if (ret < 0)
800                 return ret;
801         return output("%s", select_conf.trailer_arg);
802 }
803
804 static int print_statistics(struct format_info *fi)
805 {
806         switch (select_conf.select_mode_arg) {
807         case select_mode_arg_global_list:
808                 return print_global_list(fi);
809         case select_mode_arg_global_summary:
810                 return print_global_summary(fi);
811         case select_mode_arg_user_list:
812                 return print_user_lists(fi);
813         case select_mode_arg_user_summary:
814                 return print_user_summary(fi);
815         default:
816                 ERROR_LOG("bad select mode\n");
817                 return -ERRNO_TO_ERROR(EINVAL);
818         };
819 }
820
821 static int open_pipe(char *path)
822 {
823         int p[2], ret;
824         char **argv;
825
826         ret = pipe(p);
827         if (ret < 0)
828                 return ERRNO_TO_ERROR(errno);
829         ret = fork();
830         if (ret < 0)
831                 return ERRNO_TO_ERROR(errno);
832         if (ret) { /* parent */
833                 DEBUG_LOG("created process %d\n", ret);
834                 close(p[0]);
835                 output_file = fdopen(p[1], "w");
836                 if (!output_file)
837                         return ERRNO_TO_ERROR(errno);
838                 return 1;
839         }
840         close(p[1]);
841         if (p[0] != STDIN_FILENO)
842                 dup2(p[0], STDIN_FILENO);
843         DEBUG_LOG("executing %s\n", path);
844         split_args(path, &argv, " \t");
845         execvp(argv[0], argv);
846         ERROR_LOG("error executing %s: %s\n", path,
847                 adu_strerror(ERRNO_TO_ERROR(errno)));
848         _exit(EXIT_FAILURE);
849 }
850
851 static int open_output_stream(void)
852 {
853         char *p;
854         int ret, flags = O_WRONLY | O_CREAT;
855
856         if (!select_conf.output_given)
857                 goto use_stdout;
858         p = select_conf.output_arg;
859         switch (p[0]) {
860         case '\0': /* empty string */
861                 goto bad_output_arg;
862         case '-':
863                 if (!p[1]) /* "-" means stdout */
864                         goto use_stdout;
865                 /* string starting with a dash */
866                 flags |= O_EXCL;
867                 goto open_file;
868         case '>':
869                 if (!p[1]) /* ">" is invalid */
870                         goto bad_output_arg;
871                 if (p[1] != '>') {
872                         p++;
873                         flags |= O_TRUNC;
874                         goto open_file;
875                 }
876                 /* string starting with ">>" */
877                 if (!p[2]) /* ">>" is invalid */
878                         goto bad_output_arg;
879                 flags |= O_APPEND;
880                 p += 2;
881                 goto open_file;
882         case '|':
883                 if (!p[1]) /* "|" is invalid */
884                         goto bad_output_arg;
885                 p++;
886                 return open_pipe(p);
887         default: /* args starts with no magic character */
888                 flags |= O_EXCL;
889                 goto open_file;
890         }
891 use_stdout:
892         output_file = stdout;
893         return 1;
894 bad_output_arg:
895         output_file = NULL;
896         return -E_BAD_OUTPUT_ARG;
897 open_file:
898         /*
899          * glibc's 'x' mode to fopen is not portable, so use open() and
900          * fdopen().
901          */
902         ret = open(p, flags, 0644);
903         if (ret < 0)
904                 return -ERRNO_TO_ERROR(errno);
905         output_file = fdopen(ret, "w");
906         if (!output_file)
907                 return -ERRNO_TO_ERROR(errno);
908         return 1;
909 }
910
911 /**
912  * Execute a select query.
913  *
914  * \param admissible_uids User IDs to take into account.
915  * \param fi Format information.
916  *
917  * Called once in select mode or for each \a run command in interactive mode.
918  *
919  * Open the output stream and the dir table if not already open. For each
920  * admissible uid, the user table is opened if necessary. After these
921  * preparations, the output according to \a select_mode and \a fi is written to
922  * the output stream.
923  *
924  * \return Standard.
925  */
926 int run_select_query(struct uid_range *admissible_uids, struct format_info *fi)
927 {
928         int ret = open_output_stream();
929
930         if (ret < 0)
931                 goto out;
932         ret = open_dir_table(0);
933         if (ret < 0)
934                 goto out;
935         check_signals();
936         ret = open_admissible_user_tables(admissible_uids);
937         if (ret < 0)
938                 goto out;
939         check_signals();
940         ret = print_statistics(fi);
941 out:
942         if (output_file && output_file != stdout) {
943                 fclose(output_file);
944                 output_file = NULL;
945         }
946         return ret;
947 }
948
949 /** Default format string for global_list mode. */
950 #define GLOBAL_LIST_DFLT_FMT "%(size:r:8) %(files:r:8) %(dirname)\n"
951 /** Default format string for global_summary mode. */
952 #define GLOBAL_SUMMARY_DFLT_FMT "#directories: %(dirs), #files: %(files), size: %(size)\n"
953 /** Default format string for user_list mode. */
954 #define USER_LIST_DFLT_FMT "%(size:r:5) %(files:r:5) %(dirname)\n"
955 /** Default format string for user_summary mode. */
956 #define USER_SUMMARY_DFLT_FMT "%(pw_name:l:16) %(uid:r:6) %(dirs:r:5) %(files:r:5) %(size:r:5)\n"
957
958 static int setup_format_string(char *fmt, struct format_info **fi)
959 {
960         struct atom *atoms;
961
962         if (!fmt)
963                 INFO_LOG("using default format string\n");
964         switch (select_conf.select_mode_arg) {
965         case select_mode_arg_global_list:
966                 if (!fmt)
967                         fmt = GLOBAL_LIST_DFLT_FMT;
968                 atoms = global_list_atoms;
969                 break;
970         case select_mode_arg_global_summary:
971                 if (!fmt)
972                         fmt = GLOBAL_SUMMARY_DFLT_FMT;
973                 atoms = global_summary_atoms;
974                 break;
975         case select_mode_arg_user_list:
976                 if (!fmt)
977                         fmt = USER_LIST_DFLT_FMT;
978                 atoms = user_list_atoms;
979                 break;
980         case select_mode_arg_user_summary:
981                 if (!fmt)
982                         fmt = USER_SUMMARY_DFLT_FMT;
983                 atoms = user_summary_atoms;
984                 break;
985         default:
986                 ERROR_LOG("bad select mode\n");
987                 return -ERRNO_TO_ERROR(EINVAL);
988         };
989         INFO_LOG("format string: %s\n", fmt);
990         return parse_format_string(fmt, atoms, fi);
991 }
992
993 /**
994  * Parse a given format string.
995  *
996  * \param string The format string to parse.
997  * \param params gengetopt parameters.
998  * \param admissible_uids The array of admissible uid ranges.
999  * \param fi The format info to be used with format_items().
1000  *
1001  * If \a string is not \p NULL, it is broken down into its components using
1002  * \ref create_argv() and the resulting argument vector is passed together with
1003  * \a params to gengetopt's command line parser. If --help or --detailed-help
1004  * was specified in \a string, the corresponding help text is printed and the
1005  * function returns zero.
1006  *
1007  * Otherwise, any --uid or --user options are parsed and transformed into an
1008  * array of admissible uids which is returned via \a admissible_uids.
1009  *
1010  * Finally, the format string given by --format (or the default format string
1011  * for the given select mode if no --format option was given in \a string) is
1012  * parsed as well resulting in a format_info structure which is returned via
1013  * \a fi. The caller uses the \a fi pointer later to format each output line.
1014  *
1015  * \return Negative on errors, zero if --help or --detailed-help was given,
1016  * positive otherwise.
1017  *
1018  * \sa format_items().
1019  */
1020 int parse_select_options(char *string, struct select_cmdline_parser_params *params,
1021                 struct uid_range **admissible_uids, struct format_info **fi)
1022 {
1023         int ret, num_uid_ranges;
1024         const char **line;
1025         char *fmt = NULL;
1026
1027         if (string) {
1028                 int argc;
1029                 char **argv;
1030
1031                 ret = create_argv(string, &argv);
1032                 if (ret < 0)
1033                         return ret;
1034                 argc = ret;
1035                 ret = select_cmdline_parser_ext(argc, argv, &select_conf, params);
1036                 free_argv(argv);
1037                 if (ret)
1038                         return -E_SYNTAX;
1039                 if (select_conf.help_given || select_conf.detailed_help_given)
1040                         goto help;
1041                 fmt = select_conf.format_arg;
1042         }
1043         ret = parse_uid_arg(select_conf.uid_arg, admissible_uids);
1044         if (ret < 0)
1045                 return ret;
1046         num_uid_ranges = ret;
1047         ret = append_users(select_conf.user_arg, select_conf.user_given,
1048                 admissible_uids, num_uid_ranges);
1049         if (ret < 0)
1050                 return ret;
1051         return setup_format_string(fmt, fi);
1052 help:
1053         line = select_conf.detailed_help_given?
1054                 select_args_info_detailed_help : select_args_info_help;
1055         if (!output_file)
1056                 output_file = stdout;
1057         for (; *line; line++) {
1058                 ret = output("%s\n", *line);
1059                 if (ret < 0)
1060                         return ret;
1061         }
1062         return 0;
1063 }
1064
1065 /**
1066  * Main function for select mode.
1067  *
1068  * \return Standard.
1069  */
1070 int com_select(void)
1071 {
1072         struct uid_range *admissible_uids = NULL;
1073         int ret;
1074         struct format_info *fi;
1075         struct select_cmdline_parser_params params = {
1076                 .override = 1,
1077                 .initialize = 1,
1078                 .check_required = 1,
1079                 .check_ambiguity = 1,
1080                 .print_errors = 1
1081         };
1082
1083         ret = parse_select_options(conf.select_options_arg, &params,
1084                 &admissible_uids, &fi);
1085         if (ret > 0) {
1086                 ret = read_uid_file();
1087                 if (ret < 0)
1088                         goto out;
1089                 ret = run_select_query(admissible_uids, fi);
1090                 free_format_info(fi);
1091         }
1092 out:
1093         select_cmdline_parser_free(&select_conf);
1094         return ret;
1095 }