main.cpp 30 KB

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