chroot.cpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. #include <AK/String.h>
  2. #include <AK/StringView.h>
  3. #include <stdio.h>
  4. #include <unistd.h>
  5. struct Options {
  6. const char* path;
  7. const char* program { "/bin/Shell" };
  8. int flags { -1 };
  9. };
  10. void print_usage(const char* argv0)
  11. {
  12. fprintf(
  13. stderr,
  14. "Usage:\n"
  15. "\t%s <path> [program] [-o options]\n",
  16. argv0
  17. );
  18. }
  19. Options parse_options(int argc, char** argv)
  20. {
  21. Options options;
  22. if (argc < 2) {
  23. print_usage(argv[0]);
  24. exit(1);
  25. }
  26. options.path = argv[1];
  27. int i = 2;
  28. if (i < argc && argv[i][0] != '-')
  29. options.program = argv[i++];
  30. if (i >= argc)
  31. return options;
  32. if (strcmp(argv[i], "-o") != 0) {
  33. print_usage(argv[0]);
  34. exit(1);
  35. }
  36. i++;
  37. if (i >= argc) {
  38. print_usage(argv[0]);
  39. exit(1);
  40. }
  41. options.flags = 0;
  42. StringView arg = argv[i];
  43. Vector<StringView> parts = arg.split_view(',');
  44. for (auto& part : parts) {
  45. if (part == "defaults")
  46. continue;
  47. else if (part == "nodev")
  48. options.flags |= MS_NODEV;
  49. else if (part == "noexec")
  50. options.flags |= MS_NOEXEC;
  51. else if (part == "nosuid")
  52. options.flags |= MS_NOSUID;
  53. else if (part == "bind")
  54. fprintf(stderr, "Ignoring -o bind, as it doesn't make sense for chroot");
  55. else
  56. fprintf(stderr, "Ignoring invalid option: %s\n", String(part).characters());
  57. }
  58. return options;
  59. }
  60. int main(int argc, char** argv)
  61. {
  62. Options options = parse_options(argc, argv);
  63. if (chroot_with_mount_flags(options.path, options.flags) < 0) {
  64. perror("chroot");
  65. return 1;
  66. }
  67. if (chdir("/") < 0) {
  68. perror("chdir(/)");
  69. return 1;
  70. }
  71. execl(options.program, options.program, nullptr);
  72. perror("execl");
  73. return 1;
  74. }