losetup.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. #include <getopt.h>
  10. #include "libbb.h"
  11. int losetup_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  12. int losetup_main(int argc, char **argv)
  13. {
  14. char dev[] = LOOP_NAME"0";
  15. unsigned opt;
  16. char *opt_o;
  17. char *s;
  18. unsigned long long offset = 0;
  19. /* max 2 args, all opts are mutially exclusive */
  20. opt_complementary = "?2:d--of:o--df:f-do";
  21. opt = getopt32(argv, "do:f", &opt_o);
  22. argc -= optind;
  23. argv += optind;
  24. if (opt == 0x2) // -o
  25. offset = xatoull(opt_o);
  26. if (opt == 0x4 && argc) // -f does not take any argument
  27. bb_show_usage();
  28. if (opt == 0x1) { // -d
  29. /* detach takes exactly one argument */
  30. if (argc != 1)
  31. bb_show_usage();
  32. if (del_loop(argv[0]))
  33. bb_perror_nomsg_and_die();
  34. return EXIT_SUCCESS;
  35. }
  36. if (argc == 2) {
  37. /* -o or no option */
  38. if (set_loop(&argv[0], argv[1], offset) < 0)
  39. bb_perror_nomsg_and_die();
  40. return EXIT_SUCCESS;
  41. }
  42. if (argc == 1) {
  43. /* -o or no option */
  44. s = query_loop(argv[0]);
  45. if (!s)
  46. bb_perror_nomsg_and_die();
  47. printf("%s: %s\n", argv[0], s);
  48. if (ENABLE_FEATURE_CLEAN_UP)
  49. free(s);
  50. return EXIT_SUCCESS;
  51. }
  52. /* -o, -f or no option */
  53. while (1) {
  54. s = query_loop(dev);
  55. if (!s) {
  56. if (opt == 0x4) {
  57. puts(dev);
  58. return EXIT_SUCCESS;
  59. }
  60. } else {
  61. if (opt != 0x4)
  62. printf("%s: %s\n", dev, s);
  63. if (ENABLE_FEATURE_CLEAN_UP)
  64. free(s);
  65. }
  66. if (++dev[sizeof(dev) - 2] > '9')
  67. break;
  68. }
  69. return EXIT_SUCCESS;
  70. }