main.cpp 31 KB

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