main.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  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 int sh_umask(int argc, char** argv)
  110. {
  111. if (argc == 1) {
  112. mode_t old_mask = umask(0);
  113. printf("%#o\n", old_mask);
  114. umask(old_mask);
  115. return 0;
  116. }
  117. if (argc == 2) {
  118. unsigned mask;
  119. int matches = sscanf(argv[1], "%o", &mask);
  120. if (matches == 1) {
  121. umask(mask);
  122. return 0;
  123. }
  124. }
  125. printf("usage: umask <octal-mask>\n");
  126. return 0;
  127. }
  128. static bool handle_builtin(int argc, char** argv, int& retval)
  129. {
  130. if (argc == 0)
  131. return false;
  132. if (!strcmp(argv[0], "cd")) {
  133. retval = sh_cd(argc, argv);
  134. return true;
  135. }
  136. if (!strcmp(argv[0], "pwd")) {
  137. retval = sh_pwd(argc, argv);
  138. return true;
  139. }
  140. if (!strcmp(argv[0], "exit")) {
  141. retval = sh_exit(argc, argv);
  142. return true;
  143. }
  144. if (!strcmp(argv[0], "export")) {
  145. retval = sh_export(argc, argv);
  146. return true;
  147. }
  148. if (!strcmp(argv[0], "history")) {
  149. retval = sh_history(argc, argv);
  150. return true;
  151. }
  152. if (!strcmp(argv[0], "umask")) {
  153. retval = sh_umask(argc, argv);
  154. return true;
  155. }
  156. return false;
  157. }
  158. class FileDescriptorCollector {
  159. public:
  160. FileDescriptorCollector() { }
  161. ~FileDescriptorCollector() { collect(); }
  162. void collect()
  163. {
  164. for (auto fd : m_fds)
  165. close(fd);
  166. m_fds.clear();
  167. }
  168. void add(int fd) { m_fds.append(fd); }
  169. private:
  170. Vector<int, 32> m_fds;
  171. };
  172. struct CommandTimer {
  173. CommandTimer()
  174. {
  175. timer.start();
  176. }
  177. ~CommandTimer()
  178. {
  179. dbgprintf("sh: command finished in %d ms\n", timer.elapsed());
  180. }
  181. CElapsedTimer timer;
  182. };
  183. static int run_command(const String& cmd)
  184. {
  185. if (cmd.is_empty())
  186. return 0;
  187. auto subcommands = Parser(cmd).parse();
  188. #ifdef SH_DEBUG
  189. for (int i = 0; i < subcommands.size(); ++i) {
  190. for (int j = 0; j < i; ++j)
  191. printf(" ");
  192. for (auto& arg : subcommands[i].args) {
  193. printf("<%s> ", arg.characters());
  194. }
  195. printf("\n");
  196. for (auto& redirecton : subcommands[i].redirections) {
  197. for (int j = 0; j < i; ++j)
  198. printf(" ");
  199. printf(" ");
  200. switch (redirecton.type) {
  201. case Redirection::Pipe:
  202. printf("Pipe\n");
  203. break;
  204. case Redirection::FileRead:
  205. printf("fd:%d = FileRead: %s\n", redirecton.fd, redirecton.path.characters());
  206. break;
  207. case Redirection::FileWrite:
  208. printf("fd:%d = FileWrite: %s\n", redirecton.fd, redirecton.path.characters());
  209. break;
  210. default:
  211. break;
  212. }
  213. }
  214. }
  215. #endif
  216. if (subcommands.is_empty())
  217. return 0;
  218. FileDescriptorCollector fds;
  219. for (int i = 0; i < subcommands.size(); ++i) {
  220. auto& subcommand = subcommands[i];
  221. for (auto& redirection : subcommand.redirections) {
  222. if (redirection.type == Redirection::Pipe) {
  223. int pipefd[2];
  224. int rc = pipe(pipefd);
  225. if (rc < 0) {
  226. perror("pipe");
  227. return 1;
  228. }
  229. subcommand.redirections.append({ Redirection::Rewire, STDOUT_FILENO, pipefd[1] });
  230. auto& next_command = subcommands[i + 1];
  231. next_command.redirections.append({ Redirection::Rewire, STDIN_FILENO, pipefd[0] });
  232. fds.add(pipefd[0]);
  233. fds.add(pipefd[1]);
  234. }
  235. if (redirection.type == Redirection::FileWrite) {
  236. int fd = open(redirection.path.characters(), O_WRONLY | O_CREAT, 0666);
  237. if (fd < 0) {
  238. perror("open");
  239. return 1;
  240. }
  241. subcommand.redirections.append({ Redirection::Rewire, redirection.fd, fd });
  242. fds.add(fd);
  243. }
  244. if (redirection.type == Redirection::FileRead) {
  245. int fd = open(redirection.path.characters(), O_RDONLY);
  246. if (fd < 0) {
  247. perror("open");
  248. return 1;
  249. }
  250. subcommand.redirections.append({ Redirection::Rewire, redirection.fd, fd });
  251. fds.add(fd);
  252. }
  253. }
  254. }
  255. struct termios trm;
  256. tcgetattr(0, &trm);
  257. Vector<pid_t> children;
  258. CommandTimer timer;
  259. for (int i = 0; i < subcommands.size(); ++i) {
  260. auto& subcommand = subcommands[i];
  261. Vector<const char*> argv;
  262. for (auto& arg : subcommand.args)
  263. argv.append(arg.characters());
  264. argv.append(nullptr);
  265. int retval = 0;
  266. if (handle_builtin(argv.size() - 1, const_cast<char**>(argv.data()), retval))
  267. return retval;
  268. pid_t child = fork();
  269. if (!child) {
  270. setpgid(0, 0);
  271. tcsetpgrp(0, getpid());
  272. for (auto& redirection : subcommand.redirections) {
  273. if (redirection.type == Redirection::Rewire) {
  274. #ifdef SH_DEBUGsh
  275. dbgprintf("in %s<%d>, dup2(%d, %d)\n", argv[0], getpid(), redirection.rewire_fd, redirection.fd);
  276. #endif
  277. int rc = dup2(redirection.rewire_fd, redirection.fd);
  278. if (rc < 0) {
  279. perror("dup2");
  280. return 1;
  281. }
  282. }
  283. }
  284. fds.collect();
  285. int rc = execvp(argv[0], const_cast<char* const*>(argv.data()));
  286. if (rc < 0) {
  287. fprintf(stderr, "execvp(%s): %s\n", argv[0], strerror(errno));
  288. exit(1);
  289. }
  290. ASSERT_NOT_REACHED();
  291. }
  292. children.append(child);
  293. }
  294. #ifdef SH_DEBUG
  295. dbgprintf("Closing fds in shell process:\n");
  296. #endif
  297. fds.collect();
  298. #ifdef SH_DEBUG
  299. dbgprintf("Now we gotta wait on children:\n");
  300. for (auto& child : children)
  301. dbgprintf(" %d\n", child);
  302. #endif
  303. int wstatus = 0;
  304. int rc;
  305. for (auto& child : children) {
  306. do {
  307. rc = waitpid(child, &wstatus, 0);
  308. if (rc < 0 && errno != EINTR) {
  309. perror("waitpid");
  310. break;
  311. }
  312. } while(errno == EINTR);
  313. }
  314. // FIXME: Should I really have to tcsetpgrp() after my child has exited?
  315. // Is the terminal controlling pgrp really still the PGID of the dead process?
  316. tcsetpgrp(0, getpid());
  317. tcsetattr(0, TCSANOW, &trm);
  318. if (WIFEXITED(wstatus)) {
  319. if (WEXITSTATUS(wstatus) != 0)
  320. printf("Exited with status %d\n", WEXITSTATUS(wstatus));
  321. return WEXITSTATUS(wstatus);
  322. } else {
  323. if (WIFSIGNALED(wstatus)) {
  324. switch (WTERMSIG(wstatus)) {
  325. case SIGINT:
  326. printf("Interrupted\n");
  327. break;
  328. default:
  329. printf("Terminated by signal %d\n", WTERMSIG(wstatus));
  330. break;
  331. }
  332. } else {
  333. printf("Exited abnormally\n");
  334. return 1;
  335. }
  336. }
  337. return 0;
  338. }
  339. int main(int argc, char** argv)
  340. {
  341. g.uid = getuid();
  342. g.sid = setsid();
  343. tcsetpgrp(0, getpgrp());
  344. tcgetattr(0, &g.termios);
  345. {
  346. struct sigaction sa;
  347. sa.sa_handler = handle_sigint;
  348. sa.sa_flags = 0;
  349. sa.sa_mask = 0;
  350. int rc = sigaction(SIGINT, &sa, nullptr);
  351. assert(rc == 0);
  352. }
  353. int rc = gethostname(g.hostname, sizeof(g.hostname));
  354. if (rc < 0)
  355. perror("gethostname");
  356. rc = ttyname_r(0, g.ttyname, sizeof(g.ttyname));
  357. if (rc < 0)
  358. perror("ttyname_r");
  359. {
  360. auto* pw = getpwuid(getuid());
  361. if (pw) {
  362. g.username = pw->pw_name;
  363. g.home = pw->pw_dir;
  364. putenv(const_cast<char*>(String::format("HOME=%s", pw->pw_dir).characters()));
  365. }
  366. endpwent();
  367. }
  368. if (argc > 1 && !strcmp(argv[1], "-c")) {
  369. fprintf(stderr, "FIXME: Implement /bin/sh -c\n");
  370. return 1;
  371. }
  372. {
  373. auto* cwd = getcwd(nullptr, 0);
  374. g.cwd = cwd;
  375. free(cwd);
  376. }
  377. for (;;) {
  378. prompt();
  379. auto line = editor.get_line();
  380. if (line.is_empty())
  381. continue;
  382. run_command(line);
  383. editor.add_to_history(line);
  384. }
  385. return 0;
  386. }