main.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include "GlobalState.h"
  27. #include "LineEditor.h"
  28. #include "Parser.h"
  29. #include <AK/FileSystemPath.h>
  30. #include <AK/StringBuilder.h>
  31. #include <LibCore/DirIterator.h>
  32. #include <LibCore/ElapsedTimer.h>
  33. #include <LibCore/File.h>
  34. #include <errno.h>
  35. #include <fcntl.h>
  36. #include <pwd.h>
  37. #include <signal.h>
  38. #include <stdio.h>
  39. #include <stdlib.h>
  40. #include <string.h>
  41. #include <sys/mman.h>
  42. #include <sys/stat.h>
  43. #include <sys/utsname.h>
  44. #include <sys/wait.h>
  45. #include <termios.h>
  46. #include <unistd.h>
  47. //#define SH_DEBUG
  48. GlobalState g;
  49. static LineEditor editor;
  50. static int run_command(const String&);
  51. static String prompt()
  52. {
  53. auto* ps1 = getenv("PROMPT");
  54. if (!ps1) {
  55. if (g.uid == 0)
  56. return "# ";
  57. StringBuilder builder;
  58. builder.appendf("\033]0;%s@%s:%s\007", g.username.characters(), g.hostname, g.cwd.characters());
  59. 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());
  60. return builder.to_string();
  61. }
  62. StringBuilder builder;
  63. for (char* ptr = ps1; *ptr; ++ptr) {
  64. if (*ptr == '\\') {
  65. ++ptr;
  66. if (!*ptr)
  67. break;
  68. switch (*ptr) {
  69. case 'X':
  70. builder.append("\033]0;");
  71. break;
  72. case 'a':
  73. builder.append(0x07);
  74. break;
  75. case 'e':
  76. builder.append(0x1b);
  77. break;
  78. case 'u':
  79. builder.append(g.username);
  80. break;
  81. case 'h':
  82. builder.append(g.hostname);
  83. break;
  84. case 'w':
  85. builder.append(g.cwd);
  86. break;
  87. case 'p':
  88. builder.append(g.uid == 0 ? '#' : '$');
  89. break;
  90. }
  91. continue;
  92. }
  93. builder.append(*ptr);
  94. }
  95. return builder.to_string();
  96. }
  97. static int sh_pwd(int, const char**)
  98. {
  99. printf("%s\n", g.cwd.characters());
  100. return 0;
  101. }
  102. static int sh_exit(int, const char**)
  103. {
  104. printf("Good-bye!\n");
  105. exit(0);
  106. return 0;
  107. }
  108. static int sh_export(int argc, const char** argv)
  109. {
  110. if (argc == 1) {
  111. for (int i = 0; environ[i]; ++i)
  112. puts(environ[i]);
  113. return 0;
  114. }
  115. auto parts = String(argv[1]).split('=');
  116. if (parts.size() != 2) {
  117. fprintf(stderr, "usage: export variable=value\n");
  118. return 1;
  119. }
  120. int setenv_return = setenv(parts[0].characters(), parts[1].characters(), 1);
  121. if (setenv_return == 0 && parts[0] == "PATH")
  122. editor.cache_path();
  123. return setenv_return;
  124. }
  125. static int sh_unset(int argc, const char** argv)
  126. {
  127. if (argc != 2) {
  128. fprintf(stderr, "usage: unset variable\n");
  129. return 1;
  130. }
  131. unsetenv(argv[1]);
  132. return 0;
  133. }
  134. static String expand_tilde(const char* expression)
  135. {
  136. int len = strlen(expression);
  137. ASSERT(len > 0 && len + 1 <= PATH_MAX);
  138. ASSERT(expression[0] == '~');
  139. StringBuilder login_name;
  140. int first_slash_index = len;
  141. for (int i = 1; i < len; ++i) {
  142. if (expression[i] == '/') {
  143. first_slash_index = i;
  144. break;
  145. }
  146. login_name.append(expression[i]);
  147. }
  148. StringBuilder path;
  149. for (int i = first_slash_index; i < len; ++i)
  150. path.append(expression[i]);
  151. if (login_name.is_empty()) {
  152. const char* home = getenv("HOME");
  153. if (!home) {
  154. auto passwd = getpwuid(getuid());
  155. ASSERT(passwd && passwd->pw_dir);
  156. return String::format("%s/%s", passwd->pw_dir, path.to_string().characters());
  157. }
  158. return String::format("%s/%s", home, path.to_string().characters());
  159. }
  160. auto passwd = getpwnam(login_name.to_string().characters());
  161. if (!passwd)
  162. return String(expression);
  163. ASSERT(passwd->pw_dir);
  164. return String::format("%s/%s", passwd->pw_dir, path.to_string().characters());
  165. }
  166. static int sh_cd(int argc, const char** argv)
  167. {
  168. char pathbuf[PATH_MAX];
  169. if (argc == 1) {
  170. strcpy(pathbuf, g.home.characters());
  171. } else {
  172. if (strcmp(argv[1], "-") == 0) {
  173. char* oldpwd = getenv("OLDPWD");
  174. if (oldpwd == nullptr)
  175. return 1;
  176. size_t len = strlen(oldpwd);
  177. ASSERT(len + 1 <= PATH_MAX);
  178. memcpy(pathbuf, oldpwd, len + 1);
  179. } else if (argv[1][0] == '~') {
  180. auto path = expand_tilde(argv[1]);
  181. if (path.is_empty())
  182. return 1;
  183. strcpy(pathbuf, path.characters());
  184. } else if (argv[1][0] == '/') {
  185. memcpy(pathbuf, argv[1], strlen(argv[1]) + 1);
  186. } else {
  187. sprintf(pathbuf, "%s/%s", g.cwd.characters(), argv[1]);
  188. }
  189. }
  190. FileSystemPath canonical_path(pathbuf);
  191. if (!canonical_path.is_valid()) {
  192. printf("FileSystemPath failed to canonicalize '%s'\n", pathbuf);
  193. return 1;
  194. }
  195. const char* path = canonical_path.string().characters();
  196. struct stat st;
  197. int rc = stat(path, &st);
  198. if (rc < 0) {
  199. printf("stat(%s) failed: %s\n", path, strerror(errno));
  200. return 1;
  201. }
  202. if (!S_ISDIR(st.st_mode)) {
  203. printf("Not a directory: %s\n", path);
  204. return 1;
  205. }
  206. rc = chdir(path);
  207. if (rc < 0) {
  208. printf("chdir(%s) failed: %s\n", path, strerror(errno));
  209. return 1;
  210. }
  211. setenv("OLDPWD", g.cwd.characters(), 1);
  212. g.cwd = canonical_path.string();
  213. setenv("PWD", g.cwd.characters(), 1);
  214. return 0;
  215. }
  216. static int sh_history(int, const char**)
  217. {
  218. for (size_t i = 0; i < editor.history().size(); ++i) {
  219. printf("%6zu %s\n", i, editor.history()[i].characters());
  220. }
  221. return 0;
  222. }
  223. static int sh_time(int argc, const char** argv)
  224. {
  225. if (argc == 1) {
  226. printf("usage: time <command>\n");
  227. return 0;
  228. }
  229. StringBuilder builder;
  230. for (int i = 1; i < argc; ++i) {
  231. builder.append(argv[i]);
  232. if (i != argc - 1)
  233. builder.append(' ');
  234. }
  235. Core::ElapsedTimer timer;
  236. timer.start();
  237. int exit_code = run_command(builder.to_string());
  238. printf("Time: %d ms\n", timer.elapsed());
  239. return exit_code;
  240. }
  241. static int sh_umask(int argc, const char** argv)
  242. {
  243. if (argc == 1) {
  244. mode_t old_mask = umask(0);
  245. printf("%#o\n", old_mask);
  246. umask(old_mask);
  247. return 0;
  248. }
  249. if (argc == 2) {
  250. unsigned mask;
  251. int matches = sscanf(argv[1], "%o", &mask);
  252. if (matches == 1) {
  253. umask(mask);
  254. return 0;
  255. }
  256. }
  257. printf("usage: umask <octal-mask>\n");
  258. return 0;
  259. }
  260. static int sh_popd(int argc, const char** argv)
  261. {
  262. if (g.directory_stack.size() <= 1) {
  263. fprintf(stderr, "Shell: popd: directory stack empty\n");
  264. return 1;
  265. }
  266. bool should_switch = true;
  267. String path = g.directory_stack.take_last();
  268. // When no arguments are given, popd removes the top directory from the stack and performs a cd to the new top directory.
  269. if (argc == 1) {
  270. int rc = chdir(path.characters());
  271. if (rc < 0) {
  272. fprintf(stderr, "chdir(%s) failed: %s", path.characters(), strerror(errno));
  273. return 1;
  274. }
  275. g.cwd = path;
  276. return 0;
  277. }
  278. for (int i = 1; i < argc; i++) {
  279. const char* arg = argv[i];
  280. if (!strcmp(arg, "-n")) {
  281. should_switch = false;
  282. }
  283. }
  284. FileSystemPath canonical_path(path.characters());
  285. if (!canonical_path.is_valid()) {
  286. fprintf(stderr, "FileSystemPath failed to canonicalize '%s'\n", path.characters());
  287. return 1;
  288. }
  289. const char* real_path = canonical_path.string().characters();
  290. struct stat st;
  291. int rc = stat(real_path, &st);
  292. if (rc < 0) {
  293. fprintf(stderr, "stat(%s) failed: %s\n", real_path, strerror(errno));
  294. return 1;
  295. }
  296. if (!S_ISDIR(st.st_mode)) {
  297. fprintf(stderr, "Not a directory: %s\n", real_path);
  298. return 1;
  299. }
  300. if (should_switch) {
  301. int rc = chdir(real_path);
  302. if (rc < 0) {
  303. fprintf(stderr, "chdir(%s) failed: %s\n", real_path, strerror(errno));
  304. return 1;
  305. }
  306. g.cwd = canonical_path.string();
  307. }
  308. return 0;
  309. }
  310. static int sh_pushd(int argc, const char** argv)
  311. {
  312. StringBuilder path_builder;
  313. bool should_switch = true;
  314. // From the BASH reference manual: https://www.gnu.org/software/bash/manual/html_node/Directory-Stack-Builtins.html
  315. // With no arguments, pushd exchanges the top two directories and makes the new top the current directory.
  316. if (argc == 1) {
  317. if (g.directory_stack.size() < 2) {
  318. fprintf(stderr, "pushd: no other directory\n");
  319. return 1;
  320. }
  321. String dir1 = g.directory_stack.take_first();
  322. String dir2 = g.directory_stack.take_first();
  323. g.directory_stack.insert(0, dir2);
  324. g.directory_stack.insert(1, dir1);
  325. int rc = chdir(dir2.characters());
  326. if (rc < 0) {
  327. fprintf(stderr, "chdir(%s) failed: %s", dir2.characters(), strerror(errno));
  328. return 1;
  329. }
  330. g.cwd = dir2;
  331. return 0;
  332. }
  333. // Let's assume the user's typed in 'pushd <dir>'
  334. if (argc == 2) {
  335. g.directory_stack.append(g.cwd.characters());
  336. if (argv[1][0] == '/') {
  337. path_builder.append(argv[1]);
  338. } else {
  339. path_builder.appendf("%s/%s", g.cwd.characters(), argv[1]);
  340. }
  341. } else if (argc == 3) {
  342. g.directory_stack.append(g.cwd.characters());
  343. for (int i = 1; i < argc; i++) {
  344. const char* arg = argv[i];
  345. if (arg[0] != '-') {
  346. if (arg[0] == '/') {
  347. path_builder.append(arg);
  348. } else
  349. path_builder.appendf("%s/%s", g.cwd.characters(), arg);
  350. }
  351. if (!strcmp(arg, "-n"))
  352. should_switch = false;
  353. }
  354. }
  355. FileSystemPath canonical_path(path_builder.to_string());
  356. if (!canonical_path.is_valid()) {
  357. fprintf(stderr, "FileSystemPath failed to canonicalize '%s'\n", path_builder.to_string().characters());
  358. return 1;
  359. }
  360. const char* real_path = canonical_path.string().characters();
  361. struct stat st;
  362. int rc = stat(real_path, &st);
  363. if (rc < 0) {
  364. fprintf(stderr, "stat(%s) failed: %s\n", real_path, strerror(errno));
  365. return 1;
  366. }
  367. if (!S_ISDIR(st.st_mode)) {
  368. fprintf(stderr, "Not a directory: %s\n", real_path);
  369. return 1;
  370. }
  371. if (should_switch) {
  372. int rc = chdir(real_path);
  373. if (rc < 0) {
  374. fprintf(stderr, "chdir(%s) failed: %s\n", real_path, strerror(errno));
  375. return 1;
  376. }
  377. g.cwd = canonical_path.string();
  378. }
  379. return 0;
  380. }
  381. static int sh_dirs(int argc, const char** argv)
  382. {
  383. // The first directory in the stack is ALWAYS the current directory
  384. g.directory_stack.at(0) = g.cwd.characters();
  385. if (argc == 1) {
  386. for (String dir : g.directory_stack)
  387. printf("%s ", dir.characters());
  388. printf("\n");
  389. return 0;
  390. }
  391. bool printed = false;
  392. for (int i = 0; i < argc; i++) {
  393. const char* arg = argv[i];
  394. if (!strcmp(arg, "-c")) {
  395. for (size_t i = 1; i < g.directory_stack.size(); i++)
  396. g.directory_stack.remove(i);
  397. printed = true;
  398. continue;
  399. }
  400. if (!strcmp(arg, "-p") && !printed) {
  401. for (auto& directory : g.directory_stack)
  402. printf("%s\n", directory.characters());
  403. printed = true;
  404. continue;
  405. }
  406. if (!strcmp(arg, "-v") && !printed) {
  407. int idx = 0;
  408. for (auto& directory : g.directory_stack) {
  409. printf("%d %s\n", idx++, directory.characters());
  410. }
  411. printed = true;
  412. continue;
  413. }
  414. }
  415. return 0;
  416. }
  417. static bool handle_builtin(int argc, const char** argv, int& retval)
  418. {
  419. if (argc == 0)
  420. return false;
  421. if (!strcmp(argv[0], "cd")) {
  422. retval = sh_cd(argc, argv);
  423. return true;
  424. }
  425. if (!strcmp(argv[0], "pwd")) {
  426. retval = sh_pwd(argc, argv);
  427. return true;
  428. }
  429. if (!strcmp(argv[0], "exit")) {
  430. retval = sh_exit(argc, argv);
  431. return true;
  432. }
  433. if (!strcmp(argv[0], "export")) {
  434. retval = sh_export(argc, argv);
  435. return true;
  436. }
  437. if (!strcmp(argv[0], "unset")) {
  438. retval = sh_unset(argc, argv);
  439. return true;
  440. }
  441. if (!strcmp(argv[0], "history")) {
  442. retval = sh_history(argc, argv);
  443. return true;
  444. }
  445. if (!strcmp(argv[0], "umask")) {
  446. retval = sh_umask(argc, argv);
  447. return true;
  448. }
  449. if (!strcmp(argv[0], "dirs")) {
  450. retval = sh_dirs(argc, argv);
  451. return true;
  452. }
  453. if (!strcmp(argv[0], "pushd")) {
  454. retval = sh_pushd(argc, argv);
  455. return true;
  456. }
  457. if (!strcmp(argv[0], "popd")) {
  458. retval = sh_popd(argc, argv);
  459. return true;
  460. }
  461. if (!strcmp(argv[0], "time")) {
  462. retval = sh_time(argc, argv);
  463. return true;
  464. }
  465. return false;
  466. }
  467. class FileDescriptionCollector {
  468. public:
  469. FileDescriptionCollector() {}
  470. ~FileDescriptionCollector() { collect(); }
  471. void collect()
  472. {
  473. for (auto fd : m_fds)
  474. close(fd);
  475. m_fds.clear();
  476. }
  477. void add(int fd) { m_fds.append(fd); }
  478. private:
  479. Vector<int, 32> m_fds;
  480. };
  481. class CommandTimer {
  482. public:
  483. explicit CommandTimer(const String& command)
  484. : m_command(command)
  485. {
  486. m_timer.start();
  487. }
  488. ~CommandTimer()
  489. {
  490. dbg() << "Command \"" << m_command << "\" finished in " << m_timer.elapsed() << " ms";
  491. }
  492. private:
  493. Core::ElapsedTimer m_timer;
  494. String m_command;
  495. };
  496. static bool is_glob(const StringView& s)
  497. {
  498. for (size_t i = 0; i < s.length(); i++) {
  499. char c = s.characters_without_null_termination()[i];
  500. if (c == '*' || c == '?')
  501. return true;
  502. }
  503. return false;
  504. }
  505. static Vector<StringView> split_path(const StringView& path)
  506. {
  507. Vector<StringView> parts;
  508. size_t substart = 0;
  509. for (size_t i = 0; i < path.length(); i++) {
  510. char ch = path.characters_without_null_termination()[i];
  511. if (ch != '/')
  512. continue;
  513. size_t sublen = i - substart;
  514. if (sublen != 0)
  515. parts.append(path.substring_view(substart, sublen));
  516. parts.append(path.substring_view(i, 1));
  517. substart = i + 1;
  518. }
  519. size_t taillen = path.length() - substart;
  520. if (taillen != 0)
  521. parts.append(path.substring_view(substart, taillen));
  522. return parts;
  523. }
  524. static Vector<String> expand_globs(const StringView& path, const StringView& base)
  525. {
  526. auto parts = split_path(path);
  527. StringBuilder builder;
  528. builder.append(base);
  529. Vector<String> res;
  530. for (size_t i = 0; i < parts.size(); ++i) {
  531. auto& part = parts[i];
  532. if (!is_glob(part)) {
  533. builder.append(part);
  534. continue;
  535. }
  536. // Found a glob.
  537. String new_base = builder.to_string();
  538. StringView new_base_v = new_base;
  539. if (new_base_v.is_empty())
  540. new_base_v = ".";
  541. Core::DirIterator di(new_base_v, Core::DirIterator::SkipParentAndBaseDir);
  542. if (di.has_error()) {
  543. return res;
  544. }
  545. while (di.has_next()) {
  546. String name = di.next_path();
  547. // Dotfiles have to be explicitly requested
  548. if (name[0] == '.' && part[0] != '.')
  549. continue;
  550. if (name.matches(part, String::CaseSensitivity::CaseSensitive)) {
  551. StringBuilder nested_base;
  552. nested_base.append(new_base);
  553. nested_base.append(name);
  554. StringView remaining_path = path.substring_view_starting_after_substring(part);
  555. Vector<String> nested_res = expand_globs(remaining_path, nested_base.to_string());
  556. for (auto& s : nested_res)
  557. res.append(s);
  558. }
  559. }
  560. return res;
  561. }
  562. // Found no globs.
  563. String new_path = builder.to_string();
  564. if (access(new_path.characters(), F_OK) == 0)
  565. res.append(new_path);
  566. return res;
  567. }
  568. static Vector<String> expand_parameters(const StringView& param)
  569. {
  570. bool is_variable = param.length() > 1 && param[0] == '$';
  571. if (!is_variable)
  572. return { param };
  573. String variable_name = String(param.substring_view(1, param.length() - 1));
  574. if (variable_name == "?")
  575. return { String::number(g.last_return_code) };
  576. else if (variable_name == "$")
  577. return { String::number(getpid()) };
  578. char* env_value = getenv(variable_name.characters());
  579. if (env_value == nullptr)
  580. return { "" };
  581. Vector<String> res;
  582. String str_env_value = String(env_value);
  583. const auto& split_text = str_env_value.split_view(' ');
  584. for (auto& part : split_text)
  585. res.append(part);
  586. return res;
  587. }
  588. static Vector<String> process_arguments(const Vector<String>& args)
  589. {
  590. Vector<String> argv_string;
  591. for (auto& arg : args) {
  592. // This will return the text passed in if it wasn't a variable
  593. // This lets us just loop over its values
  594. auto expanded_parameters = expand_parameters(arg);
  595. for (auto& exp_arg : expanded_parameters) {
  596. auto expanded_globs = expand_globs(exp_arg, "");
  597. for (auto& path : expanded_globs)
  598. argv_string.append(path);
  599. if (expanded_globs.is_empty())
  600. argv_string.append(exp_arg);
  601. }
  602. }
  603. return argv_string;
  604. }
  605. static int run_command(const String& cmd)
  606. {
  607. if (cmd.is_empty())
  608. return 0;
  609. if (cmd.starts_with("#"))
  610. return 0;
  611. auto commands = Parser(cmd).parse();
  612. #ifdef SH_DEBUG
  613. for (auto& command : commands) {
  614. for (int i = 0; i < command.subcommands.size(); ++i) {
  615. for (int j = 0; j < i; ++j)
  616. dbgprintf(" ");
  617. for (auto& arg : command.subcommands[i].args) {
  618. dbgprintf("<%s> ", arg.characters());
  619. }
  620. dbgprintf("\n");
  621. for (auto& redirecton : command.subcommands[i].redirections) {
  622. for (int j = 0; j < i; ++j)
  623. dbgprintf(" ");
  624. dbgprintf(" ");
  625. switch (redirecton.type) {
  626. case Redirection::Pipe:
  627. dbgprintf("Pipe\n");
  628. break;
  629. case Redirection::FileRead:
  630. dbgprintf("fd:%d = FileRead: %s\n", redirecton.fd, redirecton.path.characters());
  631. break;
  632. case Redirection::FileWrite:
  633. dbgprintf("fd:%d = FileWrite: %s\n", redirecton.fd, redirecton.path.characters());
  634. break;
  635. case Redirection::FileWriteAppend:
  636. dbgprintf("fd:%d = FileWriteAppend: %s\n", redirecton.fd, redirecton.path.characters());
  637. break;
  638. default:
  639. break;
  640. }
  641. }
  642. }
  643. dbgprintf("\n");
  644. }
  645. #endif
  646. struct termios trm;
  647. tcgetattr(0, &trm);
  648. struct SpawnedProcess {
  649. String name;
  650. pid_t pid;
  651. };
  652. int return_value = 0;
  653. for (auto& command : commands) {
  654. if (command.subcommands.is_empty())
  655. continue;
  656. FileDescriptionCollector fds;
  657. for (size_t i = 0; i < command.subcommands.size(); ++i) {
  658. auto& subcommand = command.subcommands[i];
  659. for (auto& redirection : subcommand.redirections) {
  660. switch (redirection.type) {
  661. case Redirection::Pipe: {
  662. int pipefd[2];
  663. int rc = pipe(pipefd);
  664. if (rc < 0) {
  665. perror("pipe");
  666. return 1;
  667. }
  668. subcommand.rewirings.append({ STDOUT_FILENO, pipefd[1] });
  669. auto& next_command = command.subcommands[i + 1];
  670. next_command.rewirings.append({ STDIN_FILENO, pipefd[0] });
  671. fds.add(pipefd[0]);
  672. fds.add(pipefd[1]);
  673. break;
  674. }
  675. case Redirection::FileWriteAppend: {
  676. int fd = open(redirection.path.characters(), O_WRONLY | O_CREAT | O_APPEND, 0666);
  677. if (fd < 0) {
  678. perror("open");
  679. return 1;
  680. }
  681. subcommand.rewirings.append({ redirection.fd, fd });
  682. fds.add(fd);
  683. break;
  684. }
  685. case Redirection::FileWrite: {
  686. int fd = open(redirection.path.characters(), O_WRONLY | O_CREAT | O_TRUNC, 0666);
  687. if (fd < 0) {
  688. perror("open");
  689. return 1;
  690. }
  691. subcommand.rewirings.append({ redirection.fd, fd });
  692. fds.add(fd);
  693. break;
  694. }
  695. case Redirection::FileRead: {
  696. int fd = open(redirection.path.characters(), O_RDONLY);
  697. if (fd < 0) {
  698. perror("open");
  699. return 1;
  700. }
  701. subcommand.rewirings.append({ redirection.fd, fd });
  702. fds.add(fd);
  703. break;
  704. }
  705. }
  706. }
  707. }
  708. Vector<SpawnedProcess> children;
  709. CommandTimer timer(cmd);
  710. for (size_t i = 0; i < command.subcommands.size(); ++i) {
  711. auto& subcommand = command.subcommands[i];
  712. Vector<String> argv_string = process_arguments(subcommand.args);
  713. Vector<const char*> argv;
  714. argv.ensure_capacity(argv_string.size());
  715. for (const auto& s : argv_string) {
  716. argv.append(s.characters());
  717. }
  718. argv.append(nullptr);
  719. #ifdef SH_DEBUG
  720. for (auto& arg : argv) {
  721. dbgprintf("<%s> ", arg);
  722. }
  723. dbgprintf("\n");
  724. #endif
  725. int retval = 0;
  726. if (handle_builtin(argv.size() - 1, argv.data(), retval))
  727. return retval;
  728. pid_t child = fork();
  729. if (!child) {
  730. setpgid(0, 0);
  731. tcsetpgrp(0, getpid());
  732. tcsetattr(0, TCSANOW, &g.default_termios);
  733. for (auto& rewiring : subcommand.rewirings) {
  734. #ifdef SH_DEBUG
  735. dbgprintf("in %s<%d>, dup2(%d, %d)\n", argv[0], getpid(), rewiring.rewire_fd, rewiring.fd);
  736. #endif
  737. int rc = dup2(rewiring.rewire_fd, rewiring.fd);
  738. if (rc < 0) {
  739. perror("dup2");
  740. return 1;
  741. }
  742. }
  743. fds.collect();
  744. int rc = execvp(argv[0], const_cast<char* const*>(argv.data()));
  745. if (rc < 0) {
  746. if (errno == ENOENT)
  747. fprintf(stderr, "%s: Command not found.\n", argv[0]);
  748. else
  749. fprintf(stderr, "execvp(%s): %s\n", argv[0], strerror(errno));
  750. _exit(1);
  751. }
  752. ASSERT_NOT_REACHED();
  753. }
  754. children.append({ argv[0], child });
  755. }
  756. #ifdef SH_DEBUG
  757. dbgprintf("Closing fds in shell process:\n");
  758. #endif
  759. fds.collect();
  760. #ifdef SH_DEBUG
  761. dbgprintf("Now we gotta wait on children:\n");
  762. for (auto& child : children)
  763. dbgprintf(" %d (%s)\n", child.pid, child.name.characters());
  764. #endif
  765. int wstatus = 0;
  766. for (size_t i = 0; i < children.size(); ++i) {
  767. auto& child = children[i];
  768. do {
  769. int rc = waitpid(child.pid, &wstatus, WEXITED | WSTOPPED);
  770. if (rc < 0 && errno != EINTR) {
  771. if (errno != ECHILD)
  772. perror("waitpid");
  773. break;
  774. }
  775. if (WIFEXITED(wstatus)) {
  776. if (WEXITSTATUS(wstatus) != 0)
  777. dbg() << "Shell: " << child.name << ":" << child.pid << " exited with status " << WEXITSTATUS(wstatus);
  778. if (i == 0)
  779. return_value = WEXITSTATUS(wstatus);
  780. } else if (WIFSTOPPED(wstatus)) {
  781. fprintf(stderr, "Shell: %s(%d) %s\n", child.name.characters(), child.pid, strsignal(WSTOPSIG(wstatus)));
  782. } else {
  783. if (WIFSIGNALED(wstatus)) {
  784. printf("Shell: %s(%d) exited due to signal '%s'\n", child.name.characters(), child.pid, strsignal(WTERMSIG(wstatus)));
  785. } else {
  786. printf("Shell: %s(%d) exited abnormally\n", child.name.characters(), child.pid);
  787. }
  788. }
  789. } while (errno == EINTR);
  790. }
  791. }
  792. g.last_return_code = return_value;
  793. // FIXME: Should I really have to tcsetpgrp() after my child has exited?
  794. // Is the terminal controlling pgrp really still the PGID of the dead process?
  795. tcsetpgrp(0, getpid());
  796. tcsetattr(0, TCSANOW, &trm);
  797. return return_value;
  798. }
  799. static String get_history_path()
  800. {
  801. StringBuilder builder;
  802. builder.append(g.home);
  803. builder.append("/.history");
  804. return builder.to_string();
  805. }
  806. void load_history()
  807. {
  808. auto history_file = Core::File::construct(get_history_path());
  809. if (!history_file->open(Core::IODevice::ReadOnly))
  810. return;
  811. while (history_file->can_read_line()) {
  812. auto b = history_file->read_line(1024);
  813. // skip the newline and terminating bytes
  814. editor.add_to_history(String(reinterpret_cast<const char*>(b.data()), b.size() - 2));
  815. }
  816. }
  817. void save_history()
  818. {
  819. auto history_file = Core::File::construct(get_history_path());
  820. if (!history_file->open(Core::IODevice::WriteOnly))
  821. return;
  822. for (const auto& line : editor.history()) {
  823. history_file->write(line);
  824. history_file->write("\n");
  825. }
  826. }
  827. int main(int argc, char** argv)
  828. {
  829. if (pledge("stdio rpath wpath cpath proc exec tty", nullptr) < 0) {
  830. perror("pledge");
  831. return 1;
  832. }
  833. g.uid = getuid();
  834. tcsetpgrp(0, getpgrp());
  835. tcgetattr(0, &g.default_termios);
  836. g.termios = g.default_termios;
  837. // Because we use our own line discipline which includes echoing,
  838. // we disable ICANON and ECHO.
  839. g.termios.c_lflag &= ~(ECHO | ICANON);
  840. tcsetattr(0, TCSANOW, &g.termios);
  841. signal(SIGINT, [](int) {
  842. g.was_interrupted = true;
  843. });
  844. signal(SIGHUP, [](int) {
  845. save_history();
  846. });
  847. signal(SIGWINCH, [](int) {
  848. g.was_resized = true;
  849. });
  850. int rc = gethostname(g.hostname, sizeof(g.hostname));
  851. if (rc < 0)
  852. perror("gethostname");
  853. rc = ttyname_r(0, g.ttyname, sizeof(g.ttyname));
  854. if (rc < 0)
  855. perror("ttyname_r");
  856. {
  857. auto* pw = getpwuid(getuid());
  858. if (pw) {
  859. g.username = pw->pw_name;
  860. g.home = pw->pw_dir;
  861. setenv("HOME", pw->pw_dir, 1);
  862. }
  863. endpwent();
  864. }
  865. if (argc > 2 && !strcmp(argv[1], "-c")) {
  866. dbgprintf("sh -c '%s'\n", argv[2]);
  867. run_command(argv[2]);
  868. return 0;
  869. }
  870. if (argc == 2 && argv[1][0] != '-') {
  871. auto file = Core::File::construct(argv[1]);
  872. if (!file->open(Core::IODevice::ReadOnly)) {
  873. fprintf(stderr, "Failed to open %s: %s\n", file->filename().characters(), file->error_string());
  874. return 1;
  875. }
  876. for (;;) {
  877. auto line = file->read_line(4096);
  878. if (line.is_null())
  879. break;
  880. run_command(String::copy(line, Chomp));
  881. }
  882. return 0;
  883. }
  884. {
  885. auto* cwd = getcwd(nullptr, 0);
  886. g.cwd = cwd;
  887. setenv("PWD", cwd, 1);
  888. free(cwd);
  889. }
  890. g.directory_stack.append(g.cwd);
  891. load_history();
  892. atexit(save_history);
  893. editor.cache_path();
  894. for (;;) {
  895. auto line = editor.get_line(prompt());
  896. if (line.is_empty())
  897. continue;
  898. run_command(line);
  899. editor.add_to_history(line);
  900. }
  901. return 0;
  902. }