main.cpp 18 KB

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