main.cpp 15 KB

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