main.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. #include "GlobalState.h"
  2. #include "LineEditor.h"
  3. #include "Parser.h"
  4. #include <AK/FileSystemPath.h>
  5. #include <LibCore/CDirIterator.h>
  6. #include <LibCore/CElapsedTimer.h>
  7. #include <errno.h>
  8. #include <fcntl.h>
  9. #include <pwd.h>
  10. #include <signal.h>
  11. #include <stdio.h>
  12. #include <stdlib.h>
  13. #include <string.h>
  14. #include <sys/mman.h>
  15. #include <sys/stat.h>
  16. #include <sys/utsname.h>
  17. #include <sys/wait.h>
  18. #include <termios.h>
  19. #include <unistd.h>
  20. //#define SH_DEBUG
  21. GlobalState g;
  22. static LineEditor editor;
  23. static void prompt()
  24. {
  25. if (g.uid == 0)
  26. printf("# ");
  27. else {
  28. printf("\033]0;%s@%s:%s\007", g.username.characters(), g.hostname, g.cwd.characters());
  29. printf("\033[31;1m%s\033[0m@\033[37;1m%s\033[0m:\033[32;1m%s\033[0m$> ", g.username.characters(), g.hostname, g.cwd.characters());
  30. }
  31. fflush(stdout);
  32. }
  33. static int sh_pwd(int, char**)
  34. {
  35. printf("%s\n", g.cwd.characters());
  36. return 0;
  37. }
  38. static volatile bool g_got_signal = false;
  39. void did_receive_signal(int signum)
  40. {
  41. printf("\nMy word, I've received a signal with number %d\n", signum);
  42. g_got_signal = true;
  43. }
  44. void handle_sigint(int)
  45. {
  46. g.was_interrupted = true;
  47. }
  48. static int sh_exit(int, char**)
  49. {
  50. printf("Good-bye!\n");
  51. exit(0);
  52. return 0;
  53. }
  54. static int sh_export(int argc, char** argv)
  55. {
  56. if (argc == 1) {
  57. for (int i = 0; environ[i]; ++i)
  58. puts(environ[i]);
  59. return 0;
  60. }
  61. auto parts = String(argv[1]).split('=');
  62. if (parts.size() != 2) {
  63. fprintf(stderr, "usage: export variable=value\n");
  64. return 1;
  65. }
  66. return setenv(parts[0].characters(), parts[1].characters(), 1);
  67. }
  68. static int sh_unset(int argc, char** argv)
  69. {
  70. if (argc != 2) {
  71. fprintf(stderr, "usage: unset variable\n");
  72. return 1;
  73. }
  74. unsetenv(argv[1]);
  75. return 0;
  76. }
  77. static int sh_cd(int argc, char** argv)
  78. {
  79. char pathbuf[PATH_MAX];
  80. if (argc == 1) {
  81. strcpy(pathbuf, g.home.characters());
  82. } else {
  83. if (argv[1][0] == '/')
  84. memcpy(pathbuf, argv[1], strlen(argv[1]) + 1);
  85. else
  86. sprintf(pathbuf, "%s/%s", g.cwd.characters(), argv[1]);
  87. }
  88. FileSystemPath canonical_path(pathbuf);
  89. if (!canonical_path.is_valid()) {
  90. printf("FileSystemPath failed to canonicalize '%s'\n", pathbuf);
  91. return 1;
  92. }
  93. const char* path = canonical_path.string().characters();
  94. struct stat st;
  95. int rc = stat(path, &st);
  96. if (rc < 0) {
  97. printf("stat(%s) failed: %s\n", path, strerror(errno));
  98. return 1;
  99. }
  100. if (!S_ISDIR(st.st_mode)) {
  101. printf("Not a directory: %s\n", path);
  102. return 1;
  103. }
  104. rc = chdir(path);
  105. if (rc < 0) {
  106. printf("chdir(%s) failed: %s\n", path, strerror(errno));
  107. return 1;
  108. }
  109. g.cwd = canonical_path.string();
  110. return 0;
  111. }
  112. static int sh_history(int, char**)
  113. {
  114. for (int i = 0; i < editor.history().size(); ++i) {
  115. printf("%6d %s\n", i, editor.history()[i].characters());
  116. }
  117. return 0;
  118. }
  119. static int sh_umask(int argc, char** argv)
  120. {
  121. if (argc == 1) {
  122. mode_t old_mask = umask(0);
  123. printf("%#o\n", old_mask);
  124. umask(old_mask);
  125. return 0;
  126. }
  127. if (argc == 2) {
  128. unsigned mask;
  129. int matches = sscanf(argv[1], "%o", &mask);
  130. if (matches == 1) {
  131. umask(mask);
  132. return 0;
  133. }
  134. }
  135. printf("usage: umask <octal-mask>\n");
  136. return 0;
  137. }
  138. static bool handle_builtin(int argc, char** argv, int& retval)
  139. {
  140. if (argc == 0)
  141. return false;
  142. if (!strcmp(argv[0], "cd")) {
  143. retval = sh_cd(argc, argv);
  144. return true;
  145. }
  146. if (!strcmp(argv[0], "pwd")) {
  147. retval = sh_pwd(argc, argv);
  148. return true;
  149. }
  150. if (!strcmp(argv[0], "exit")) {
  151. retval = sh_exit(argc, argv);
  152. return true;
  153. }
  154. if (!strcmp(argv[0], "export")) {
  155. retval = sh_export(argc, argv);
  156. return true;
  157. }
  158. if (!strcmp(argv[0], "unset")) {
  159. retval = sh_unset(argc, argv);
  160. return true;
  161. }
  162. if (!strcmp(argv[0], "history")) {
  163. retval = sh_history(argc, argv);
  164. return true;
  165. }
  166. if (!strcmp(argv[0], "umask")) {
  167. retval = sh_umask(argc, argv);
  168. return true;
  169. }
  170. return false;
  171. }
  172. class FileDescriptorCollector {
  173. public:
  174. FileDescriptorCollector() { }
  175. ~FileDescriptorCollector() { collect(); }
  176. void collect()
  177. {
  178. for (auto fd : m_fds)
  179. close(fd);
  180. m_fds.clear();
  181. }
  182. void add(int fd) { m_fds.append(fd); }
  183. private:
  184. Vector<int, 32> m_fds;
  185. };
  186. struct CommandTimer {
  187. CommandTimer()
  188. {
  189. timer.start();
  190. }
  191. ~CommandTimer()
  192. {
  193. dbgprintf("sh: command finished in %d ms\n", timer.elapsed());
  194. }
  195. CElapsedTimer timer;
  196. };
  197. static Vector<String> process_arguments(const Vector<String>& args)
  198. {
  199. Vector<String> argv_string;
  200. for (auto& arg : args) {
  201. bool is_glob = false;
  202. for (int i = 0; i < arg.length(); i++) {
  203. char c = arg.characters()[i];
  204. if (c == '*' || c == '?') {
  205. is_glob = true;
  206. }
  207. }
  208. if (is_glob == false) {
  209. argv_string.append(arg.characters());
  210. } else {
  211. CDirIterator di(".", CDirIterator::NoFlags);
  212. if (di.has_error()) {
  213. fprintf(stderr, "CDirIterator: %s\n", di.error_string());
  214. continue;
  215. }
  216. while (di.has_next()) {
  217. String name = di.next_path();
  218. // Dotfiles have to be explicitly requested
  219. if (name[0] == '.' && arg[0] != '.')
  220. continue;
  221. // And even if they are, skip . and ..
  222. if (name == "." || name == "..")
  223. continue;
  224. if (name.matches(arg, String::CaseSensitivity::CaseSensitive))
  225. argv_string.append(name);
  226. }
  227. }
  228. }
  229. return argv_string;
  230. }
  231. static int run_command(const String& cmd)
  232. {
  233. if (cmd.is_empty())
  234. return 0;
  235. auto subcommands = Parser(cmd).parse();
  236. #ifdef SH_DEBUG
  237. for (int i = 0; i < subcommands.size(); ++i) {
  238. for (int j = 0; j < i; ++j)
  239. dbgprintf(" ");
  240. for (auto& arg : subcommands[i].args) {
  241. dbgprintf("<%s> ", arg.characters());
  242. }
  243. dbgprintf("\n");
  244. for (auto& redirecton : subcommands[i].redirections) {
  245. for (int j = 0; j < i; ++j)
  246. dbgprintf(" ");
  247. dbgprintf(" ");
  248. switch (redirecton.type) {
  249. case Redirection::Pipe:
  250. dbgprintf("Pipe\n");
  251. break;
  252. case Redirection::FileRead:
  253. dbgprintf("fd:%d = FileRead: %s\n", redirecton.fd, redirecton.path.characters());
  254. break;
  255. case Redirection::FileWrite:
  256. dbgprintf("fd:%d = FileWrite: %s\n", redirecton.fd, redirecton.path.characters());
  257. break;
  258. case Redirection::FileWriteAppend:
  259. dbgprintf("fd:%d = FileWriteAppend: %s\n", redirecton.fd, redirecton.path.characters());
  260. break;
  261. default:
  262. break;
  263. }
  264. }
  265. }
  266. #endif
  267. if (subcommands.is_empty())
  268. return 0;
  269. FileDescriptorCollector fds;
  270. for (int i = 0; i < subcommands.size(); ++i) {
  271. auto& subcommand = subcommands[i];
  272. for (auto& redirection : subcommand.redirections) {
  273. switch (redirection.type) {
  274. case Redirection::Pipe: {
  275. int pipefd[2];
  276. int rc = pipe(pipefd);
  277. if (rc < 0) {
  278. perror("pipe");
  279. return 1;
  280. }
  281. subcommand.rewirings.append({ STDOUT_FILENO, pipefd[1] });
  282. auto& next_command = subcommands[i + 1];
  283. next_command.rewirings.append({ STDIN_FILENO, pipefd[0] });
  284. fds.add(pipefd[0]);
  285. fds.add(pipefd[1]);
  286. break;
  287. }
  288. case Redirection::FileWriteAppend: {
  289. int fd = open(redirection.path.characters(), O_WRONLY | O_CREAT | O_APPEND, 0666);
  290. if (fd < 0) {
  291. perror("open");
  292. return 1;
  293. }
  294. subcommand.rewirings.append({ redirection.fd, fd });
  295. fds.add(fd);
  296. break;
  297. }
  298. case Redirection::FileWrite: {
  299. int fd = open(redirection.path.characters(), O_WRONLY | O_CREAT | O_TRUNC, 0666);
  300. if (fd < 0) {
  301. perror("open");
  302. return 1;
  303. }
  304. subcommand.rewirings.append({ redirection.fd, fd });
  305. fds.add(fd);
  306. break;
  307. }
  308. case Redirection::FileRead: {
  309. int fd = open(redirection.path.characters(), O_RDONLY);
  310. if (fd < 0) {
  311. perror("open");
  312. return 1;
  313. }
  314. subcommand.rewirings.append({ redirection.fd, fd });
  315. fds.add(fd);
  316. break;
  317. }
  318. }
  319. }
  320. }
  321. struct termios trm;
  322. tcgetattr(0, &trm);
  323. Vector<pid_t> children;
  324. CommandTimer timer;
  325. for (int i = 0; i < subcommands.size(); ++i) {
  326. auto& subcommand = subcommands[i];
  327. Vector<String> argv_string = process_arguments(subcommand.args);
  328. Vector<const char*> argv;
  329. argv.ensure_capacity(argv_string.size());
  330. for (const auto& s : argv_string) {
  331. argv.append(s.characters());
  332. }
  333. argv.append(nullptr);
  334. #ifdef SH_DEBUG
  335. for (auto& arg : argv) {
  336. dbgprintf("<%s> ", arg);
  337. }
  338. dbgprintf("\n");
  339. #endif
  340. int retval = 0;
  341. if (handle_builtin(argv.size() - 1, const_cast<char**>(argv.data()), retval))
  342. return retval;
  343. pid_t child = fork();
  344. if (!child) {
  345. setpgid(0, 0);
  346. tcsetpgrp(0, getpid());
  347. for (auto& rewiring : subcommand.rewirings) {
  348. #ifdef SH_DEBUG
  349. dbgprintf("in %s<%d>, dup2(%d, %d)\n", argv[0], getpid(), redirection.rewire_fd, redirection.fd);
  350. #endif
  351. int rc = dup2(rewiring.rewire_fd, rewiring.fd);
  352. if (rc < 0) {
  353. perror("dup2");
  354. return 1;
  355. }
  356. }
  357. fds.collect();
  358. int rc = execvp(argv[0], const_cast<char* const*>(argv.data()));
  359. if (rc < 0) {
  360. fprintf(stderr, "execvp(%s): %s\n", argv[0], strerror(errno));
  361. exit(1);
  362. }
  363. ASSERT_NOT_REACHED();
  364. }
  365. children.append(child);
  366. }
  367. #ifdef SH_DEBUG
  368. dbgprintf("Closing fds in shell process:\n");
  369. #endif
  370. fds.collect();
  371. #ifdef SH_DEBUG
  372. dbgprintf("Now we gotta wait on children:\n");
  373. for (auto& child : children)
  374. dbgprintf(" %d\n", child);
  375. #endif
  376. int wstatus = 0;
  377. int return_value = 0;
  378. for (int i = 0; i < children.size(); ++i) {
  379. auto& child = children[i];
  380. do {
  381. int rc = waitpid(child, &wstatus, 0);
  382. if (rc < 0 && errno != EINTR) {
  383. if (errno != ECHILD)
  384. perror("waitpid");
  385. break;
  386. }
  387. if (WIFEXITED(wstatus)) {
  388. if (WEXITSTATUS(wstatus) != 0)
  389. printf("Shell: Child %d exited with status %d\n", child, WEXITSTATUS(wstatus));
  390. if (i == 0)
  391. return_value = WEXITSTATUS(wstatus);
  392. } else {
  393. if (WIFSIGNALED(wstatus)) {
  394. printf("Shell: Child %d exited due to signal '%s'\n", child, strsignal(WTERMSIG(wstatus)));
  395. } else {
  396. printf("Shell: Child %d exited abnormally\n", child);
  397. }
  398. }
  399. } while(errno == EINTR);
  400. }
  401. // FIXME: Should I really have to tcsetpgrp() after my child has exited?
  402. // Is the terminal controlling pgrp really still the PGID of the dead process?
  403. tcsetpgrp(0, getpid());
  404. tcsetattr(0, TCSANOW, &trm);
  405. return return_value;
  406. }
  407. int main(int argc, char** argv)
  408. {
  409. g.uid = getuid();
  410. g.sid = setsid();
  411. tcsetpgrp(0, getpgrp());
  412. tcgetattr(0, &g.termios);
  413. {
  414. struct sigaction sa;
  415. sa.sa_handler = handle_sigint;
  416. sa.sa_flags = 0;
  417. sa.sa_mask = 0;
  418. int rc = sigaction(SIGINT, &sa, nullptr);
  419. assert(rc == 0);
  420. }
  421. int rc = gethostname(g.hostname, sizeof(g.hostname));
  422. if (rc < 0)
  423. perror("gethostname");
  424. rc = ttyname_r(0, g.ttyname, sizeof(g.ttyname));
  425. if (rc < 0)
  426. perror("ttyname_r");
  427. {
  428. auto* pw = getpwuid(getuid());
  429. if (pw) {
  430. g.username = pw->pw_name;
  431. g.home = pw->pw_dir;
  432. setenv("HOME", pw->pw_dir, 1);
  433. }
  434. endpwent();
  435. }
  436. if (argc > 2 && !strcmp(argv[1], "-c")) {
  437. dbgprintf("sh -c '%s'\n", argv[2]);
  438. run_command(argv[2]);
  439. return 0;
  440. }
  441. {
  442. auto* cwd = getcwd(nullptr, 0);
  443. g.cwd = cwd;
  444. free(cwd);
  445. }
  446. for (;;) {
  447. prompt();
  448. auto line = editor.get_line();
  449. if (line.is_empty())
  450. continue;
  451. run_command(line);
  452. editor.add_to_history(line);
  453. }
  454. return 0;
  455. }