main.cpp 29 KB

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