revert last two commits. vfork cannot be used in subroutine,
[oweals/busybox.git] / util-linux / losetup.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Mini losetup implementation for busybox
4  *
5  * Copyright (C) 2002  Matt Kraai.
6  *
7  * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
8  */
9
10 #include "libbb.h"
11
12 int losetup_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13 int losetup_main(int argc, char **argv)
14 {
15         char dev[] = LOOP_NAME"0";
16         unsigned opt;
17         char *opt_o;
18         char *s;
19         unsigned long long offset = 0;
20
21         /* max 2 args, all opts are mutially exclusive */
22         opt_complementary = "?2:d--of:o--df:f-do";
23         opt = getopt32(argv, "do:f", &opt_o);
24         argc -= optind;
25         argv += optind;
26
27         if (opt == 0x2) // -o
28                 offset = xatoull(opt_o);
29
30         if (opt == 0x4 && argc) // -f does not take any argument
31                 bb_show_usage();
32
33         if (opt == 0x1) { // -d
34                 /* detach takes exactly one argument */
35                 if (argc != 1)
36                         bb_show_usage();
37                 if (del_loop(argv[0]))
38                         bb_simple_perror_msg_and_die(argv[0]);
39                 return EXIT_SUCCESS;
40         }
41
42         if (argc == 2) {
43                 /* -o or no option */
44                 if (set_loop(&argv[0], argv[1], offset) < 0)
45                         bb_simple_perror_msg_and_die(argv[0]);
46                 return EXIT_SUCCESS;
47         }
48
49         if (argc == 1) {
50                 /* -o or no option */
51                 s = query_loop(argv[0]);
52                 if (!s)
53                         bb_simple_perror_msg_and_die(argv[0]);
54                 printf("%s: %s\n", argv[0], s);
55                 if (ENABLE_FEATURE_CLEAN_UP)
56                         free(s);
57                 return EXIT_SUCCESS;
58         }
59
60         /* -o, -f or no option */
61         while (1) {
62                 s = query_loop(dev);
63                 if (!s) {
64                         if (opt == 0x4) {
65                                 puts(dev);
66                                 return EXIT_SUCCESS;
67                         }
68                 } else {
69                         if (opt != 0x4)
70                                 printf("%s: %s\n", dev, s);
71                         if (ENABLE_FEATURE_CLEAN_UP)
72                                 free(s);
73                 }
74
75                 if (++dev[sizeof(dev) - 2] > '9')
76                         break;
77         }
78         return EXIT_SUCCESS;
79 }