main.cpp 17 KB

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