main.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  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.redirections.append({ Redirection::Rewire, STDOUT_FILENO, pipefd[1] });
  282. auto& next_command = subcommands[i + 1];
  283. next_command.redirections.append({ Redirection::Rewire, 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.redirections.append({ Redirection::Rewire, 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.redirections.append({ Redirection::Rewire, 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.redirections.append({ Redirection::Rewire, redirection.fd, fd });
  315. fds.add(fd);
  316. break;
  317. }
  318. case Redirection::Rewire:
  319. break; // ignore
  320. }
  321. }
  322. }
  323. struct termios trm;
  324. tcgetattr(0, &trm);
  325. Vector<pid_t> children;
  326. CommandTimer timer;
  327. for (int i = 0; i < subcommands.size(); ++i) {
  328. auto& subcommand = subcommands[i];
  329. Vector<String> argv_string = process_arguments(subcommand.args);
  330. Vector<const char*> argv;
  331. argv.ensure_capacity(argv_string.size());
  332. for (const auto& s : argv_string) {
  333. argv.append(s.characters());
  334. }
  335. argv.append(nullptr);
  336. #ifdef SH_DEBUG
  337. for (auto& arg : argv) {
  338. dbgprintf("<%s> ", arg);
  339. }
  340. dbgprintf("\n");
  341. #endif
  342. int retval = 0;
  343. if (handle_builtin(argv.size() - 1, const_cast<char**>(argv.data()), retval))
  344. return retval;
  345. pid_t child = fork();
  346. if (!child) {
  347. setpgid(0, 0);
  348. tcsetpgrp(0, getpid());
  349. for (auto& redirection : subcommand.redirections) {
  350. if (redirection.type == Redirection::Rewire) {
  351. #ifdef SH_DEBUGsh
  352. dbgprintf("in %s<%d>, dup2(%d, %d)\n", argv[0], getpid(), redirection.rewire_fd, redirection.fd);
  353. #endif
  354. int rc = dup2(redirection.rewire_fd, redirection.fd);
  355. if (rc < 0) {
  356. perror("dup2");
  357. return 1;
  358. }
  359. }
  360. }
  361. fds.collect();
  362. int rc = execvp(argv[0], const_cast<char* const*>(argv.data()));
  363. if (rc < 0) {
  364. fprintf(stderr, "execvp(%s): %s\n", argv[0], strerror(errno));
  365. exit(1);
  366. }
  367. ASSERT_NOT_REACHED();
  368. }
  369. children.append(child);
  370. }
  371. #ifdef SH_DEBUG
  372. dbgprintf("Closing fds in shell process:\n");
  373. #endif
  374. fds.collect();
  375. #ifdef SH_DEBUG
  376. dbgprintf("Now we gotta wait on children:\n");
  377. for (auto& child : children)
  378. dbgprintf(" %d\n", child);
  379. #endif
  380. int wstatus = 0;
  381. int rc;
  382. for (auto& child : children) {
  383. do {
  384. rc = waitpid(child, &wstatus, 0);
  385. if (rc < 0 && errno != EINTR) {
  386. perror("waitpid");
  387. break;
  388. }
  389. } while(errno == EINTR);
  390. }
  391. // FIXME: Should I really have to tcsetpgrp() after my child has exited?
  392. // Is the terminal controlling pgrp really still the PGID of the dead process?
  393. tcsetpgrp(0, getpid());
  394. tcsetattr(0, TCSANOW, &trm);
  395. if (WIFEXITED(wstatus)) {
  396. if (WEXITSTATUS(wstatus) != 0)
  397. printf("Exited with status %d\n", WEXITSTATUS(wstatus));
  398. return WEXITSTATUS(wstatus);
  399. } else {
  400. if (WIFSIGNALED(wstatus)) {
  401. puts(strsignal(WTERMSIG(wstatus)));
  402. } else {
  403. printf("Exited abnormally\n");
  404. return 1;
  405. }
  406. }
  407. return 0;
  408. }
  409. int main(int argc, char** argv)
  410. {
  411. g.uid = getuid();
  412. g.sid = setsid();
  413. tcsetpgrp(0, getpgrp());
  414. tcgetattr(0, &g.termios);
  415. {
  416. struct sigaction sa;
  417. sa.sa_handler = handle_sigint;
  418. sa.sa_flags = 0;
  419. sa.sa_mask = 0;
  420. int rc = sigaction(SIGINT, &sa, nullptr);
  421. assert(rc == 0);
  422. }
  423. int rc = gethostname(g.hostname, sizeof(g.hostname));
  424. if (rc < 0)
  425. perror("gethostname");
  426. rc = ttyname_r(0, g.ttyname, sizeof(g.ttyname));
  427. if (rc < 0)
  428. perror("ttyname_r");
  429. {
  430. auto* pw = getpwuid(getuid());
  431. if (pw) {
  432. g.username = pw->pw_name;
  433. g.home = pw->pw_dir;
  434. setenv("HOME", pw->pw_dir, 1);
  435. }
  436. endpwent();
  437. }
  438. if (argc > 2 && !strcmp(argv[1], "-c")) {
  439. dbgprintf("sh -c '%s'\n", argv[2]);
  440. run_command(argv[2]);
  441. return 0;
  442. }
  443. {
  444. auto* cwd = getcwd(nullptr, 0);
  445. g.cwd = cwd;
  446. free(cwd);
  447. }
  448. for (;;) {
  449. prompt();
  450. auto line = editor.get_line();
  451. if (line.is_empty())
  452. continue;
  453. run_command(line);
  454. editor.add_to_history(line);
  455. }
  456. return 0;
  457. }