main.cpp 28 KB

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