losetup.c 1.6 KB

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