main.cpp 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084
  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. bool is_variable = param.length() > 1 && param[0] == '$';
  610. if (!is_variable)
  611. return { param };
  612. String variable_name = String(param.substring_view(1, param.length() - 1));
  613. if (variable_name == "?")
  614. return { String::number(g.last_return_code) };
  615. else if (variable_name == "$")
  616. return { String::number(getpid()) };
  617. char* env_value = getenv(variable_name.characters());
  618. if (env_value == nullptr)
  619. return { "" };
  620. Vector<String> res;
  621. String str_env_value = String(env_value);
  622. const auto& split_text = str_env_value.split_view(' ');
  623. for (auto& part : split_text)
  624. res.append(part);
  625. return res;
  626. }
  627. static Vector<String> process_arguments(const Vector<String>& args)
  628. {
  629. Vector<String> argv_string;
  630. for (auto& arg : args) {
  631. // This will return the text passed in if it wasn't a variable
  632. // This lets us just loop over its values
  633. auto expanded_parameters = expand_parameters(arg);
  634. for (auto& exp_arg : expanded_parameters) {
  635. auto expanded_globs = expand_globs(exp_arg, "");
  636. for (auto& path : expanded_globs)
  637. argv_string.append(path);
  638. if (expanded_globs.is_empty())
  639. argv_string.append(exp_arg);
  640. }
  641. }
  642. return argv_string;
  643. }
  644. static int run_command(const String& cmd)
  645. {
  646. if (cmd.is_empty())
  647. return 0;
  648. if (cmd.starts_with("#"))
  649. return 0;
  650. auto commands = Parser(cmd).parse();
  651. #ifdef SH_DEBUG
  652. for (auto& command : commands) {
  653. for (int i = 0; i < command.subcommands.size(); ++i) {
  654. for (int j = 0; j < i; ++j)
  655. dbgprintf(" ");
  656. for (auto& arg : command.subcommands[i].args) {
  657. dbgprintf("<%s> ", arg.characters());
  658. }
  659. dbgprintf("\n");
  660. for (auto& redirecton : command.subcommands[i].redirections) {
  661. for (int j = 0; j < i; ++j)
  662. dbgprintf(" ");
  663. dbgprintf(" ");
  664. switch (redirecton.type) {
  665. case Redirection::Pipe:
  666. dbgprintf("Pipe\n");
  667. break;
  668. case Redirection::FileRead:
  669. dbgprintf("fd:%d = FileRead: %s\n", redirecton.fd, redirecton.path.characters());
  670. break;
  671. case Redirection::FileWrite:
  672. dbgprintf("fd:%d = FileWrite: %s\n", redirecton.fd, redirecton.path.characters());
  673. break;
  674. case Redirection::FileWriteAppend:
  675. dbgprintf("fd:%d = FileWriteAppend: %s\n", redirecton.fd, redirecton.path.characters());
  676. break;
  677. default:
  678. break;
  679. }
  680. }
  681. }
  682. dbgprintf("\n");
  683. }
  684. #endif
  685. struct termios trm;
  686. tcgetattr(0, &trm);
  687. struct SpawnedProcess {
  688. String name;
  689. pid_t pid;
  690. };
  691. int return_value = 0;
  692. for (auto& command : commands) {
  693. if (command.subcommands.is_empty())
  694. continue;
  695. FileDescriptionCollector fds;
  696. for (size_t i = 0; i < command.subcommands.size(); ++i) {
  697. auto& subcommand = command.subcommands[i];
  698. for (auto& redirection : subcommand.redirections) {
  699. switch (redirection.type) {
  700. case Redirection::Pipe: {
  701. int pipefd[2];
  702. int rc = pipe(pipefd);
  703. if (rc < 0) {
  704. perror("pipe");
  705. return 1;
  706. }
  707. subcommand.rewirings.append({ STDOUT_FILENO, pipefd[1] });
  708. auto& next_command = command.subcommands[i + 1];
  709. next_command.rewirings.append({ STDIN_FILENO, pipefd[0] });
  710. fds.add(pipefd[0]);
  711. fds.add(pipefd[1]);
  712. break;
  713. }
  714. case Redirection::FileWriteAppend: {
  715. int fd = open(redirection.path.characters(), O_WRONLY | O_CREAT | O_APPEND, 0666);
  716. if (fd < 0) {
  717. perror("open");
  718. return 1;
  719. }
  720. subcommand.rewirings.append({ redirection.fd, fd });
  721. fds.add(fd);
  722. break;
  723. }
  724. case Redirection::FileWrite: {
  725. int fd = open(redirection.path.characters(), O_WRONLY | O_CREAT | O_TRUNC, 0666);
  726. if (fd < 0) {
  727. perror("open");
  728. return 1;
  729. }
  730. subcommand.rewirings.append({ redirection.fd, fd });
  731. fds.add(fd);
  732. break;
  733. }
  734. case Redirection::FileRead: {
  735. int fd = open(redirection.path.characters(), O_RDONLY);
  736. if (fd < 0) {
  737. perror("open");
  738. return 1;
  739. }
  740. subcommand.rewirings.append({ redirection.fd, fd });
  741. fds.add(fd);
  742. break;
  743. }
  744. }
  745. }
  746. }
  747. Vector<SpawnedProcess> children;
  748. CommandTimer timer(cmd);
  749. for (size_t i = 0; i < command.subcommands.size(); ++i) {
  750. auto& subcommand = command.subcommands[i];
  751. Vector<String> argv_string = process_arguments(subcommand.args);
  752. Vector<const char*> argv;
  753. argv.ensure_capacity(argv_string.size());
  754. for (const auto& s : argv_string) {
  755. argv.append(s.characters());
  756. }
  757. argv.append(nullptr);
  758. #ifdef SH_DEBUG
  759. for (auto& arg : argv) {
  760. dbgprintf("<%s> ", arg);
  761. }
  762. dbgprintf("\n");
  763. #endif
  764. int retval = 0;
  765. if (handle_builtin(argv.size() - 1, argv.data(), retval))
  766. return retval;
  767. pid_t child = fork();
  768. if (!child) {
  769. setpgid(0, 0);
  770. tcsetpgrp(0, getpid());
  771. tcsetattr(0, TCSANOW, &g.default_termios);
  772. for (auto& rewiring : subcommand.rewirings) {
  773. #ifdef SH_DEBUG
  774. dbgprintf("in %s<%d>, dup2(%d, %d)\n", argv[0], getpid(), rewiring.rewire_fd, rewiring.fd);
  775. #endif
  776. int rc = dup2(rewiring.rewire_fd, rewiring.fd);
  777. if (rc < 0) {
  778. perror("dup2");
  779. return 1;
  780. }
  781. }
  782. fds.collect();
  783. int rc = execvp(argv[0], const_cast<char* const*>(argv.data()));
  784. if (rc < 0) {
  785. if (errno == ENOENT)
  786. fprintf(stderr, "%s: Command not found.\n", argv[0]);
  787. else
  788. fprintf(stderr, "execvp(%s): %s\n", argv[0], strerror(errno));
  789. _exit(1);
  790. }
  791. ASSERT_NOT_REACHED();
  792. }
  793. children.append({ argv[0], child });
  794. }
  795. #ifdef SH_DEBUG
  796. dbgprintf("Closing fds in shell process:\n");
  797. #endif
  798. fds.collect();
  799. #ifdef SH_DEBUG
  800. dbgprintf("Now we gotta wait on children:\n");
  801. for (auto& child : children)
  802. dbgprintf(" %d (%s)\n", child.pid, child.name.characters());
  803. #endif
  804. int wstatus = 0;
  805. for (size_t i = 0; i < children.size(); ++i) {
  806. auto& child = children[i];
  807. do {
  808. int rc = waitpid(child.pid, &wstatus, 0);
  809. if (rc < 0 && errno != EINTR) {
  810. if (errno != ECHILD)
  811. perror("waitpid");
  812. break;
  813. }
  814. if (WIFEXITED(wstatus)) {
  815. if (WEXITSTATUS(wstatus) != 0)
  816. dbg() << "Shell: " << child.name << ":" << child.pid << " exited with status " << WEXITSTATUS(wstatus);
  817. if (i == 0)
  818. return_value = WEXITSTATUS(wstatus);
  819. } else if (WIFSTOPPED(wstatus)) {
  820. fprintf(stderr, "Shell: %s(%d) %s\n", child.name.characters(), child.pid, strsignal(WSTOPSIG(wstatus)));
  821. } else {
  822. if (WIFSIGNALED(wstatus)) {
  823. printf("Shell: %s(%d) exited due to signal '%s'\n", child.name.characters(), child.pid, strsignal(WTERMSIG(wstatus)));
  824. } else {
  825. printf("Shell: %s(%d) exited abnormally\n", child.name.characters(), child.pid);
  826. }
  827. }
  828. } while (errno == EINTR);
  829. }
  830. }
  831. g.last_return_code = return_value;
  832. // FIXME: Should I really have to tcsetpgrp() after my child has exited?
  833. // Is the terminal controlling pgrp really still the PGID of the dead process?
  834. tcsetpgrp(0, getpid());
  835. tcsetattr(0, TCSANOW, &trm);
  836. return return_value;
  837. }
  838. static String get_history_path()
  839. {
  840. StringBuilder builder;
  841. builder.append(g.home);
  842. builder.append("/.history");
  843. return builder.to_string();
  844. }
  845. void load_history()
  846. {
  847. auto history_file = Core::File::construct(get_history_path());
  848. if (!history_file->open(Core::IODevice::ReadOnly))
  849. return;
  850. while (history_file->can_read_line()) {
  851. auto b = history_file->read_line(1024);
  852. // skip the newline and terminating bytes
  853. editor.add_to_history(String(reinterpret_cast<const char*>(b.data()), b.size() - 2));
  854. }
  855. }
  856. void save_history()
  857. {
  858. auto history_file = Core::File::construct(get_history_path());
  859. if (!history_file->open(Core::IODevice::WriteOnly))
  860. return;
  861. for (const auto& line : editor.history()) {
  862. history_file->write(line);
  863. history_file->write("\n");
  864. }
  865. }
  866. int main(int argc, char** argv)
  867. {
  868. if (pledge("stdio rpath wpath cpath proc exec tty", nullptr) < 0) {
  869. perror("pledge");
  870. return 1;
  871. }
  872. g.uid = getuid();
  873. tcsetpgrp(0, getpgrp());
  874. tcgetattr(0, &g.default_termios);
  875. g.termios = g.default_termios;
  876. // Because we use our own line discipline which includes echoing,
  877. // we disable ICANON and ECHO.
  878. g.termios.c_lflag &= ~(ECHO | ICANON);
  879. tcsetattr(0, TCSANOW, &g.termios);
  880. signal(SIGINT, [](int) {
  881. g.was_interrupted = true;
  882. });
  883. signal(SIGHUP, [](int) {
  884. save_history();
  885. });
  886. signal(SIGWINCH, [](int) {
  887. g.was_resized = true;
  888. });
  889. int rc = gethostname(g.hostname, sizeof(g.hostname));
  890. if (rc < 0)
  891. perror("gethostname");
  892. rc = ttyname_r(0, g.ttyname, sizeof(g.ttyname));
  893. if (rc < 0)
  894. perror("ttyname_r");
  895. {
  896. auto* cwd = getcwd(nullptr, 0);
  897. g.cwd = cwd;
  898. setenv("PWD", cwd, 1);
  899. free(cwd);
  900. }
  901. {
  902. auto* pw = getpwuid(getuid());
  903. if (pw) {
  904. g.username = pw->pw_name;
  905. g.home = pw->pw_dir;
  906. setenv("HOME", pw->pw_dir, 1);
  907. }
  908. endpwent();
  909. }
  910. if (argc > 2 && !strcmp(argv[1], "-c")) {
  911. dbgprintf("sh -c '%s'\n", argv[2]);
  912. run_command(argv[2]);
  913. return 0;
  914. }
  915. if (argc == 2 && argv[1][0] != '-') {
  916. auto file = Core::File::construct(argv[1]);
  917. if (!file->open(Core::IODevice::ReadOnly)) {
  918. fprintf(stderr, "Failed to open %s: %s\n", file->filename().characters(), file->error_string());
  919. return 1;
  920. }
  921. for (;;) {
  922. auto line = file->read_line(4096);
  923. if (line.is_null())
  924. break;
  925. run_command(String::copy(line, Chomp));
  926. }
  927. return 0;
  928. }
  929. g.directory_stack.append(g.cwd);
  930. load_history();
  931. atexit(save_history);
  932. editor.cache_path();
  933. for (;;) {
  934. auto line = editor.get_line(prompt());
  935. if (line.is_empty())
  936. continue;
  937. run_command(line);
  938. editor.add_to_history(line);
  939. }
  940. return 0;
  941. }