main.cpp 10 KB

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