main.cpp 12 KB

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