Shell.cpp 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348
  1. /*
  2. * Copyright (c) 2020, The SerenityOS developers.
  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 "Shell.h"
  27. #include "Execution.h"
  28. #include <AK/Function.h>
  29. #include <AK/LexicalPath.h>
  30. #include <AK/ScopeGuard.h>
  31. #include <AK/StringBuilder.h>
  32. #include <LibCore/ArgsParser.h>
  33. #include <LibCore/DirIterator.h>
  34. #include <LibCore/Event.h>
  35. #include <LibCore/EventLoop.h>
  36. #include <LibCore/File.h>
  37. #include <LibLine/Editor.h>
  38. #include <errno.h>
  39. #include <fcntl.h>
  40. #include <inttypes.h>
  41. #include <pwd.h>
  42. #include <signal.h>
  43. #include <stdio.h>
  44. #include <stdlib.h>
  45. #include <string.h>
  46. #include <sys/mman.h>
  47. #include <sys/stat.h>
  48. #include <sys/utsname.h>
  49. #include <termios.h>
  50. #include <unistd.h>
  51. static bool s_disable_hyperlinks = false;
  52. extern RefPtr<Line::Editor> editor;
  53. extern char** environ;
  54. //#define SH_DEBUG
  55. void Shell::print_path(const String& path)
  56. {
  57. if (s_disable_hyperlinks || !m_is_interactive) {
  58. printf("%s", path.characters());
  59. return;
  60. }
  61. printf("\033]8;;file://%s%s\033\\%s\033]8;;\033\\", hostname, path.characters(), path.characters());
  62. }
  63. String Shell::prompt() const
  64. {
  65. auto build_prompt = [&]() -> String {
  66. auto* ps1 = getenv("PROMPT");
  67. if (!ps1) {
  68. if (uid == 0)
  69. return "# ";
  70. StringBuilder builder;
  71. builder.appendf("\033]0;%s@%s:%s\007", username.characters(), hostname, cwd.characters());
  72. builder.appendf("\033[31;1m%s\033[0m@\033[37;1m%s\033[0m:\033[32;1m%s\033[0m$> ", username.characters(), hostname, cwd.characters());
  73. return builder.to_string();
  74. }
  75. StringBuilder builder;
  76. for (char* ptr = ps1; *ptr; ++ptr) {
  77. if (*ptr == '\\') {
  78. ++ptr;
  79. if (!*ptr)
  80. break;
  81. switch (*ptr) {
  82. case 'X':
  83. builder.append("\033]0;");
  84. break;
  85. case 'a':
  86. builder.append(0x07);
  87. break;
  88. case 'e':
  89. builder.append(0x1b);
  90. break;
  91. case 'u':
  92. builder.append(username);
  93. break;
  94. case 'h':
  95. builder.append(hostname);
  96. break;
  97. case 'w': {
  98. String home_path = getenv("HOME");
  99. if (cwd.starts_with(home_path)) {
  100. builder.append('~');
  101. builder.append(cwd.substring_view(home_path.length(), cwd.length() - home_path.length()));
  102. } else {
  103. builder.append(cwd);
  104. }
  105. break;
  106. }
  107. case 'p':
  108. builder.append(uid == 0 ? '#' : '$');
  109. break;
  110. }
  111. continue;
  112. }
  113. builder.append(*ptr);
  114. }
  115. return builder.to_string();
  116. };
  117. return build_prompt();
  118. }
  119. String Shell::expand_tilde(const String& expression)
  120. {
  121. ASSERT(expression.starts_with('~'));
  122. StringBuilder login_name;
  123. size_t first_slash_index = expression.length();
  124. for (size_t i = 1; i < expression.length(); ++i) {
  125. if (expression[i] == '/') {
  126. first_slash_index = i;
  127. break;
  128. }
  129. login_name.append(expression[i]);
  130. }
  131. StringBuilder path;
  132. for (size_t i = first_slash_index; i < expression.length(); ++i)
  133. path.append(expression[i]);
  134. if (login_name.is_empty()) {
  135. const char* home = getenv("HOME");
  136. if (!home) {
  137. auto passwd = getpwuid(getuid());
  138. ASSERT(passwd && passwd->pw_dir);
  139. return String::format("%s/%s", passwd->pw_dir, path.to_string().characters());
  140. }
  141. return String::format("%s/%s", home, path.to_string().characters());
  142. }
  143. auto passwd = getpwnam(login_name.to_string().characters());
  144. if (!passwd)
  145. return expression;
  146. ASSERT(passwd->pw_dir);
  147. return String::format("%s/%s", passwd->pw_dir, path.to_string().characters());
  148. }
  149. bool Shell::is_glob(const StringView& s)
  150. {
  151. for (size_t i = 0; i < s.length(); i++) {
  152. char c = s.characters_without_null_termination()[i];
  153. if (c == '*' || c == '?')
  154. return true;
  155. }
  156. return false;
  157. }
  158. Vector<StringView> Shell::split_path(const StringView& path)
  159. {
  160. Vector<StringView> parts;
  161. size_t substart = 0;
  162. for (size_t i = 0; i < path.length(); i++) {
  163. char ch = path[i];
  164. if (ch != '/')
  165. continue;
  166. size_t sublen = i - substart;
  167. if (sublen != 0)
  168. parts.append(path.substring_view(substart, sublen));
  169. substart = i + 1;
  170. }
  171. size_t taillen = path.length() - substart;
  172. if (taillen != 0)
  173. parts.append(path.substring_view(substart, taillen));
  174. return parts;
  175. }
  176. Vector<String> Shell::expand_globs(const StringView& path, StringView base)
  177. {
  178. if (path.starts_with('/'))
  179. base = "/";
  180. auto parts = split_path(path);
  181. String base_string = base;
  182. struct stat statbuf;
  183. if (lstat(base_string.characters(), &statbuf) < 0) {
  184. perror("lstat");
  185. return {};
  186. }
  187. StringBuilder resolved_base_path_builder;
  188. resolved_base_path_builder.append(Core::File::real_path_for(base));
  189. if (S_ISDIR(statbuf.st_mode))
  190. resolved_base_path_builder.append('/');
  191. auto resolved_base = resolved_base_path_builder.string_view();
  192. auto results = expand_globs(move(parts), resolved_base);
  193. for (auto& entry : results) {
  194. entry = entry.substring(resolved_base.length(), entry.length() - resolved_base.length());
  195. if (entry.is_empty())
  196. entry = ".";
  197. }
  198. // Make the output predictable and nice.
  199. quick_sort(results);
  200. return results;
  201. }
  202. Vector<String> Shell::expand_globs(Vector<StringView> path_segments, const StringView& base)
  203. {
  204. if (path_segments.is_empty()) {
  205. String base_str = base;
  206. if (access(base_str.characters(), F_OK) == 0)
  207. return { move(base_str) };
  208. return {};
  209. }
  210. auto first_segment = path_segments.take_first();
  211. if (is_glob(first_segment)) {
  212. Vector<String> result;
  213. Core::DirIterator di(base, Core::DirIterator::SkipParentAndBaseDir);
  214. if (di.has_error())
  215. return {};
  216. while (di.has_next()) {
  217. String path = di.next_path();
  218. // Dotfiles have to be explicitly requested
  219. if (path[0] == '.' && first_segment[0] != '.')
  220. continue;
  221. if (path.matches(first_segment, CaseSensitivity::CaseSensitive)) {
  222. StringBuilder builder;
  223. builder.append(base);
  224. if (!base.ends_with('/'))
  225. builder.append('/');
  226. builder.append(path);
  227. result.append(expand_globs(path_segments, builder.string_view()));
  228. }
  229. }
  230. return result;
  231. } else {
  232. StringBuilder builder;
  233. builder.append(base);
  234. if (!base.ends_with('/'))
  235. builder.append('/');
  236. builder.append(first_segment);
  237. return expand_globs(move(path_segments), builder.string_view());
  238. }
  239. }
  240. Vector<AST::Command> Shell::expand_aliases(Vector<AST::Command> initial_commands)
  241. {
  242. Vector<AST::Command> commands;
  243. Function<void(AST::Command&)> resolve_aliases_and_append = [&](auto& command) {
  244. if (!command.argv.is_empty()) {
  245. auto alias = resolve_alias(command.argv[0]);
  246. if (!alias.is_null()) {
  247. auto argv0 = command.argv.take_first();
  248. auto subcommand_ast = Parser { alias }.parse();
  249. if (subcommand_ast) {
  250. while (subcommand_ast->is_execute()) {
  251. auto* ast = static_cast<AST::Execute*>(subcommand_ast.ptr());
  252. subcommand_ast = ast->command();
  253. }
  254. RefPtr<AST::Node> substitute = adopt(*new AST::Join(subcommand_ast->position(), subcommand_ast, adopt(*new AST::CommandLiteral(subcommand_ast->position(), command))));
  255. for (auto& subst_command : substitute->run(*this)->resolve_as_commands(*this)) {
  256. if (!subst_command.argv.is_empty() && subst_command.argv.first() == argv0) // Disallow an alias resolving to itself.
  257. commands.append(subst_command);
  258. else
  259. resolve_aliases_and_append(subst_command);
  260. }
  261. } else {
  262. commands.append(command);
  263. }
  264. } else {
  265. commands.append(command);
  266. }
  267. } else {
  268. commands.append(command);
  269. }
  270. };
  271. for (auto& command : initial_commands)
  272. resolve_aliases_and_append(command);
  273. return commands;
  274. }
  275. String Shell::resolve_path(String path) const
  276. {
  277. if (!path.starts_with('/'))
  278. path = String::format("%s/%s", cwd.characters(), path.characters());
  279. return Core::File::real_path_for(path);
  280. }
  281. Shell::LocalFrame* Shell::find_frame_containing_local_variable(const String& name)
  282. {
  283. for (auto& frame : m_local_frames) {
  284. if (frame.local_variables.contains(name))
  285. return &frame;
  286. }
  287. return nullptr;
  288. }
  289. RefPtr<AST::Value> Shell::lookup_local_variable(const String& name)
  290. {
  291. if (auto* frame = find_frame_containing_local_variable(name))
  292. return frame->local_variables.get(name).value();
  293. return nullptr;
  294. }
  295. String Shell::local_variable_or(const String& name, const String& replacement)
  296. {
  297. auto value = lookup_local_variable(name);
  298. if (value) {
  299. StringBuilder builder;
  300. builder.join(" ", value->resolve_as_list(*this));
  301. return builder.to_string();
  302. }
  303. return replacement;
  304. }
  305. void Shell::set_local_variable(const String& name, RefPtr<AST::Value> value)
  306. {
  307. if (auto* frame = find_frame_containing_local_variable(name))
  308. frame->local_variables.set(name, move(value));
  309. else
  310. m_local_frames.last().local_variables.set(name, move(value));
  311. }
  312. void Shell::unset_local_variable(const String& name)
  313. {
  314. if (auto* frame = find_frame_containing_local_variable(name))
  315. frame->local_variables.remove(name);
  316. }
  317. Shell::Frame Shell::push_frame()
  318. {
  319. m_local_frames.empend();
  320. return { m_local_frames, m_local_frames.last() };
  321. }
  322. void Shell::pop_frame()
  323. {
  324. ASSERT(m_local_frames.size() > 1);
  325. m_local_frames.take_last();
  326. }
  327. Shell::Frame::~Frame()
  328. {
  329. if (!should_destroy_frame)
  330. return;
  331. ASSERT(&frames.last() == &frame);
  332. frames.take_last();
  333. }
  334. String Shell::resolve_alias(const String& name) const
  335. {
  336. return m_aliases.get(name).value_or({});
  337. }
  338. bool Shell::is_runnable(const StringView& name)
  339. {
  340. if (access(name.to_string().characters(), X_OK) == 0)
  341. return true;
  342. return !!binary_search(cached_path.span(), name.to_string(), [](const String& name, const String& program) -> int {
  343. return strcmp(name.characters(), program.characters());
  344. });
  345. }
  346. int Shell::run_command(const StringView& cmd)
  347. {
  348. if (cmd.is_empty())
  349. return 0;
  350. auto command = Parser(cmd).parse();
  351. if (!command)
  352. return 0;
  353. #ifdef SH_DEBUG
  354. dbg() << "Command follows";
  355. command->dump(0);
  356. #endif
  357. if (command->is_syntax_error()) {
  358. auto& error_node = command->syntax_error_node();
  359. auto& position = error_node.position();
  360. fprintf(stderr, "Shell: Syntax error in command: %s\n", error_node.error_text().characters());
  361. fprintf(stderr, "Around '%.*s' at %zu:%zu\n", (int)min(position.end_offset - position.start_offset, (size_t)10), cmd.characters_without_null_termination() + position.start_offset, position.start_offset, position.end_offset);
  362. return 1;
  363. }
  364. tcgetattr(0, &termios);
  365. command->run(*this);
  366. return last_return_code;
  367. }
  368. RefPtr<Job> Shell::run_command(const AST::Command& command)
  369. {
  370. FileDescriptionCollector fds;
  371. if (options.verbose) {
  372. fprintf(stderr, "+ ");
  373. for (auto& arg : command.argv)
  374. fprintf(stderr, "%s ", escape_token(arg).characters());
  375. fprintf(stderr, "\n");
  376. fflush(stderr);
  377. }
  378. // If the command is empty, store the redirections and apply them to all later commands.
  379. if (command.argv.is_empty() && !command.should_immediately_execute_next) {
  380. m_global_redirections.append(command.redirections);
  381. return nullptr;
  382. }
  383. // Resolve redirections.
  384. NonnullRefPtrVector<AST::Rewiring> rewirings;
  385. auto resolve_redirection = [&](auto& redirection) -> IterationDecision {
  386. auto rewiring_result = redirection.apply();
  387. if (rewiring_result.is_error()) {
  388. if (!rewiring_result.error().is_empty())
  389. fprintf(stderr, "error: %s\n", rewiring_result.error().characters());
  390. return IterationDecision::Continue;
  391. }
  392. auto& rewiring = rewiring_result.value();
  393. if (rewiring->fd_action != AST::Rewiring::Close::ImmediatelyCloseDestination)
  394. rewirings.append(*rewiring);
  395. if (rewiring->fd_action == AST::Rewiring::Close::Source) {
  396. fds.add(rewiring->source_fd);
  397. } else if (rewiring->fd_action == AST::Rewiring::Close::Destination) {
  398. if (rewiring->dest_fd != -1)
  399. fds.add(rewiring->dest_fd);
  400. } else if (rewiring->fd_action == AST::Rewiring::Close::ImmediatelyCloseDestination) {
  401. fds.add(rewiring->dest_fd);
  402. } else if (rewiring->fd_action == AST::Rewiring::Close::RefreshDestination) {
  403. ASSERT(rewiring->other_pipe_end);
  404. int pipe_fd[2];
  405. int rc = pipe(pipe_fd);
  406. if (rc < 0) {
  407. perror("pipe(RedirRefresh)");
  408. return IterationDecision::Break;
  409. }
  410. rewiring->dest_fd = pipe_fd[1];
  411. rewiring->other_pipe_end->dest_fd = pipe_fd[0]; // This fd will be added to the collection on one of the next iterations.
  412. fds.add(pipe_fd[1]);
  413. }
  414. return IterationDecision::Continue;
  415. };
  416. auto apply_rewirings = [&] {
  417. for (auto& rewiring : rewirings) {
  418. #ifdef SH_DEBUG
  419. dbgprintf("in %s<%d>, dup2(%d, %d)\n", command.argv.is_empty() ? "(<Empty>)" : command.argv[0].characters(), getpid(), rewiring.dest_fd, rewiring.source_fd);
  420. #endif
  421. int rc = dup2(rewiring.dest_fd, rewiring.source_fd);
  422. if (rc < 0) {
  423. perror("dup2(run)");
  424. return IterationDecision::Break;
  425. }
  426. // dest_fd is closed via the `fds` collector, but rewiring.other_pipe_end->dest_fd
  427. // isn't yet in that collector when the first child spawns.
  428. if (rewiring.other_pipe_end && close(rewiring.other_pipe_end->dest_fd) < 0)
  429. perror("close other pipe end");
  430. }
  431. return IterationDecision::Continue;
  432. };
  433. for (auto& redirection : m_global_redirections) {
  434. if (resolve_redirection(redirection) == IterationDecision::Break)
  435. return nullptr;
  436. }
  437. for (auto& redirection : command.redirections) {
  438. if (resolve_redirection(redirection) == IterationDecision::Break)
  439. return nullptr;
  440. }
  441. if (command.should_immediately_execute_next) {
  442. ASSERT(command.argv.is_empty());
  443. SavedFileDescriptors fds { rewirings };
  444. if (apply_rewirings() == IterationDecision::Break)
  445. return nullptr;
  446. for (auto& next_in_chain : command.next_chain)
  447. run_tail(next_in_chain, 0);
  448. return nullptr;
  449. }
  450. int retval = 0;
  451. if (run_builtin(command, rewirings, retval)) {
  452. for (auto& next_in_chain : command.next_chain)
  453. run_tail(next_in_chain, retval);
  454. return nullptr;
  455. }
  456. Vector<const char*> argv;
  457. Vector<String> copy_argv = command.argv;
  458. argv.ensure_capacity(command.argv.size() + 1);
  459. for (auto& arg : copy_argv)
  460. argv.append(arg.characters());
  461. argv.append(nullptr);
  462. int sync_pipe[2];
  463. if (pipe(sync_pipe) < 0) {
  464. perror("pipe");
  465. return nullptr;
  466. }
  467. pid_t child = fork();
  468. if (child < 0) {
  469. perror("fork");
  470. return nullptr;
  471. }
  472. if (child == 0) {
  473. close(sync_pipe[1]);
  474. tcsetattr(0, TCSANOW, &default_termios);
  475. if (apply_rewirings() == IterationDecision::Break)
  476. return nullptr;
  477. fds.collect();
  478. u8 c;
  479. while (read(sync_pipe[0], &c, 1) < 0) {
  480. if (errno != EINTR) {
  481. perror("read");
  482. // There's nothing interesting we can do here.
  483. break;
  484. }
  485. dbg() << "Oof";
  486. }
  487. close(sync_pipe[0]);
  488. int rc = execvp(argv[0], const_cast<char* const*>(argv.data()));
  489. if (rc < 0) {
  490. if (errno == ENOENT) {
  491. int shebang_fd = open(argv[0], O_RDONLY);
  492. auto close_argv = ScopeGuard([shebang_fd]() { if (shebang_fd >= 0) close(shebang_fd); });
  493. char shebang[256] {};
  494. ssize_t num_read = -1;
  495. if ((shebang_fd >= 0) && ((num_read = read(shebang_fd, shebang, sizeof(shebang))) >= 2) && (StringView(shebang).starts_with("#!"))) {
  496. StringView shebang_path_view(&shebang[2], num_read - 2);
  497. Optional<size_t> newline_pos = shebang_path_view.find_first_of("\n\r");
  498. shebang[newline_pos.has_value() ? (newline_pos.value() + 2) : num_read] = '\0';
  499. fprintf(stderr, "%s: Invalid interpreter \"%s\": %s\n", argv[0], &shebang[2], strerror(ENOENT));
  500. } else
  501. fprintf(stderr, "%s: Command not found.\n", argv[0]);
  502. } else {
  503. int saved_errno = errno;
  504. struct stat st;
  505. if (stat(argv[0], &st) == 0 && S_ISDIR(st.st_mode)) {
  506. fprintf(stderr, "Shell: %s: Is a directory\n", argv[0]);
  507. _exit(126);
  508. }
  509. fprintf(stderr, "execvp(%s): %s\n", argv[0], strerror(saved_errno));
  510. }
  511. _exit(126);
  512. }
  513. ASSERT_NOT_REACHED();
  514. }
  515. close(sync_pipe[0]);
  516. bool is_first = !command.pipeline || (command.pipeline && command.pipeline->pgid == -1);
  517. if (command.pipeline) {
  518. if (is_first) {
  519. command.pipeline->pgid = child;
  520. }
  521. }
  522. pid_t pgid = is_first ? child : (command.pipeline ? command.pipeline->pgid : child);
  523. if (setpgid(child, pgid) < 0)
  524. perror("setpgid");
  525. if (command.should_wait) {
  526. tcsetpgrp(STDOUT_FILENO, pgid);
  527. tcsetpgrp(STDIN_FILENO, pgid);
  528. }
  529. while (write(sync_pipe[1], "x", 1) < 0) {
  530. if (errno != EINTR) {
  531. perror("write");
  532. // There's nothing interesting we can do here.
  533. break;
  534. }
  535. dbg() << "Oof";
  536. }
  537. close(sync_pipe[1]);
  538. StringBuilder cmd;
  539. cmd.join(" ", command.argv);
  540. auto job = Job::create(child, pgid, cmd.build(), find_last_job_id() + 1, AST::Command(command));
  541. jobs.set((u64)child, job);
  542. job->on_exit = [this](auto job) {
  543. if (!job->exited())
  544. return;
  545. if (job->is_running_in_background() && job->should_announce_exit())
  546. fprintf(stderr, "Shell: Job %" PRIu64 "(%s) exited\n", job->job_id(), job->cmd().characters());
  547. last_return_code = job->exit_code();
  548. job->disown();
  549. run_tail(job);
  550. };
  551. fds.collect();
  552. return *job;
  553. }
  554. void Shell::run_tail(const AST::NodeWithAction& next_in_chain, int head_exit_code)
  555. {
  556. switch (next_in_chain.action) {
  557. case AST::NodeWithAction::And:
  558. if (head_exit_code == 0) {
  559. auto commands = next_in_chain.node->run(*this)->resolve_as_commands(*this);
  560. run_commands(commands);
  561. }
  562. break;
  563. case AST::NodeWithAction::Or:
  564. if (head_exit_code != 0) {
  565. auto commands = next_in_chain.node->run(*this)->resolve_as_commands(*this);
  566. run_commands(commands);
  567. }
  568. break;
  569. case AST::NodeWithAction::Sequence:
  570. auto commands = next_in_chain.node->run(*this)->resolve_as_commands(*this);
  571. run_commands(commands);
  572. break;
  573. }
  574. }
  575. void Shell::run_tail(RefPtr<Job> job)
  576. {
  577. if (auto cmd = job->command_ptr()) {
  578. deferred_invoke([=, this](auto&) {
  579. for (auto& next_in_chain : cmd->next_chain) {
  580. run_tail(next_in_chain, job->exit_code());
  581. }
  582. });
  583. }
  584. }
  585. NonnullRefPtrVector<Job> Shell::run_commands(Vector<AST::Command>& commands)
  586. {
  587. NonnullRefPtrVector<Job> spawned_jobs;
  588. for (auto& command : commands) {
  589. #ifdef SH_DEBUG
  590. dbg() << "Command";
  591. for (auto& arg : command.argv)
  592. dbg() << "argv: " << arg;
  593. for (auto& redir : command.redirections) {
  594. if (redir.is_path_redirection()) {
  595. auto path_redir = (const AST::PathRedirection*)&redir;
  596. dbg() << "redir path " << (int)path_redir->direction << " " << path_redir->path << " <-> " << path_redir->fd;
  597. } else if (redir.is_fd_redirection()) {
  598. auto* fdredir = (const AST::FdRedirection*)&redir;
  599. dbg() << "redir fd " << fdredir->source_fd << " -> " << fdredir->dest_fd;
  600. } else if (redir.is_close_redirection()) {
  601. auto close_redir = (const AST::CloseRedirection*)&redir;
  602. dbg() << "close fd " << close_redir->fd;
  603. } else {
  604. ASSERT_NOT_REACHED();
  605. }
  606. }
  607. #endif
  608. auto job = run_command(command);
  609. if (!job)
  610. continue;
  611. spawned_jobs.append(*job);
  612. if (command.should_wait) {
  613. block_on_job(job);
  614. } else {
  615. job->set_running_in_background(true);
  616. if (!command.is_pipe_source && command.should_notify_if_in_background)
  617. job->set_should_announce_exit(true);
  618. }
  619. }
  620. return spawned_jobs;
  621. }
  622. bool Shell::run_file(const String& filename, bool explicitly_invoked)
  623. {
  624. auto file_result = Core::File::open(filename, Core::File::ReadOnly);
  625. if (file_result.is_error()) {
  626. if (explicitly_invoked)
  627. fprintf(stderr, "Failed to open %s: %s\n", filename.characters(), file_result.error().characters());
  628. else
  629. dbg() << "open() failed for '" << filename << "' with " << file_result.error();
  630. return false;
  631. }
  632. auto file = file_result.value();
  633. auto data = file->read_all();
  634. run_command(data);
  635. return true;
  636. }
  637. void Shell::restore_ios()
  638. {
  639. tcsetattr(0, TCSANOW, &termios);
  640. tcsetpgrp(STDOUT_FILENO, m_pid);
  641. tcsetpgrp(STDIN_FILENO, m_pid);
  642. }
  643. void Shell::block_on_job(RefPtr<Job> job)
  644. {
  645. TemporaryChange<const Job*> current_job { m_current_job, job.ptr() };
  646. if (!job)
  647. return;
  648. if (job->is_suspended())
  649. return; // We cannot wait for a suspended job.
  650. ScopeGuard io_restorer { [&]() {
  651. if (job->exited() && !job->is_running_in_background()) {
  652. restore_ios();
  653. }
  654. } };
  655. Core::EventLoop loop;
  656. job->on_exit = [&, old_exit = move(job->on_exit)](auto job) {
  657. if (old_exit)
  658. old_exit(job);
  659. loop.quit(0);
  660. };
  661. if (job->exited())
  662. return;
  663. loop.exec();
  664. }
  665. String Shell::get_history_path()
  666. {
  667. StringBuilder builder;
  668. builder.append(home);
  669. builder.append("/.history");
  670. return builder.to_string();
  671. }
  672. void Shell::load_history()
  673. {
  674. auto history_file = Core::File::construct(get_history_path());
  675. if (!history_file->open(Core::IODevice::ReadOnly))
  676. return;
  677. while (history_file->can_read_line()) {
  678. auto b = history_file->read_line(1024);
  679. // skip the newline and terminating bytes
  680. editor->add_to_history(String(reinterpret_cast<const char*>(b.data()), b.size() - 2));
  681. }
  682. }
  683. void Shell::save_history()
  684. {
  685. auto file_or_error = Core::File::open(get_history_path(), Core::IODevice::WriteOnly, 0600);
  686. if (file_or_error.is_error())
  687. return;
  688. auto& file = *file_or_error.value();
  689. for (const auto& line : editor->history()) {
  690. file.write(line);
  691. file.write("\n");
  692. }
  693. }
  694. String Shell::escape_token(const String& token)
  695. {
  696. StringBuilder builder;
  697. for (auto c : token) {
  698. switch (c) {
  699. case '\'':
  700. case '"':
  701. case '$':
  702. case '|':
  703. case '>':
  704. case '<':
  705. case '&':
  706. case '\\':
  707. case ' ':
  708. builder.append('\\');
  709. break;
  710. default:
  711. break;
  712. }
  713. builder.append(c);
  714. }
  715. return builder.build();
  716. }
  717. String Shell::unescape_token(const String& token)
  718. {
  719. StringBuilder builder;
  720. enum {
  721. Free,
  722. Escaped
  723. } state { Free };
  724. for (auto c : token) {
  725. switch (state) {
  726. case Escaped:
  727. builder.append(c);
  728. state = Free;
  729. break;
  730. case Free:
  731. if (c == '\\')
  732. state = Escaped;
  733. else
  734. builder.append(c);
  735. break;
  736. }
  737. }
  738. if (state == Escaped)
  739. builder.append('\\');
  740. return builder.build();
  741. }
  742. void Shell::cache_path()
  743. {
  744. if (!cached_path.is_empty())
  745. cached_path.clear_with_capacity();
  746. // Add shell builtins to the cache.
  747. for (const auto& builtin_name : builtin_names)
  748. cached_path.append(escape_token(builtin_name));
  749. // Add aliases to the cache.
  750. for (const auto& alias : m_aliases) {
  751. auto name = escape_token(alias.key);
  752. if (cached_path.contains_slow(name))
  753. continue;
  754. cached_path.append(name);
  755. }
  756. String path = getenv("PATH");
  757. if (!path.is_empty()) {
  758. auto directories = path.split(':');
  759. for (const auto& directory : directories) {
  760. Core::DirIterator programs(directory.characters(), Core::DirIterator::SkipDots);
  761. while (programs.has_next()) {
  762. auto program = programs.next_path();
  763. String program_path = String::format("%s/%s", directory.characters(), program.characters());
  764. auto escaped_name = escape_token(program);
  765. if (cached_path.contains_slow(escaped_name))
  766. continue;
  767. if (access(program_path.characters(), X_OK) == 0)
  768. cached_path.append(escaped_name);
  769. }
  770. }
  771. }
  772. quick_sort(cached_path);
  773. }
  774. void Shell::add_entry_to_cache(const String& entry)
  775. {
  776. size_t index = 0;
  777. auto match = binary_search(
  778. cached_path.span(), entry, [](const String& name, const String& program) -> int {
  779. return strcmp(name.characters(), program.characters());
  780. },
  781. &index);
  782. if (match)
  783. return;
  784. while (strcmp(cached_path[index].characters(), entry.characters()) < 0) {
  785. index++;
  786. }
  787. cached_path.insert(index, entry);
  788. }
  789. void Shell::highlight(Line::Editor& editor) const
  790. {
  791. auto line = editor.line();
  792. Parser parser(line);
  793. auto ast = parser.parse();
  794. if (!ast)
  795. return;
  796. ast->highlight_in_editor(editor, const_cast<Shell&>(*this));
  797. }
  798. Vector<Line::CompletionSuggestion> Shell::complete(const Line::Editor& editor)
  799. {
  800. auto line = editor.line(editor.cursor());
  801. Parser parser(line);
  802. auto ast = parser.parse();
  803. if (!ast)
  804. return {};
  805. return ast->complete_for_editor(*this, line.length());
  806. }
  807. Vector<Line::CompletionSuggestion> Shell::complete_path(const String& base, const String& part, size_t offset)
  808. {
  809. auto token = offset ? part.substring_view(0, offset) : "";
  810. StringView original_token = token;
  811. String path;
  812. ssize_t last_slash = token.length() - 1;
  813. while (last_slash >= 0 && token[last_slash] != '/')
  814. --last_slash;
  815. StringBuilder path_builder;
  816. auto init_slash_part = token.substring_view(0, last_slash + 1);
  817. auto last_slash_part = token.substring_view(last_slash + 1, token.length() - last_slash - 1);
  818. // Depending on the base, we will have to prepend cwd.
  819. if (base.is_empty()) {
  820. // '' /foo -> absolute
  821. // '' foo -> relative
  822. if (!token.starts_with('/'))
  823. path_builder.append(cwd);
  824. path_builder.append('/');
  825. path_builder.append(init_slash_part);
  826. } else {
  827. // /foo * -> absolute
  828. // foo * -> relative
  829. if (!base.starts_with('/'))
  830. path_builder.append(cwd);
  831. path_builder.append('/');
  832. path_builder.append(base);
  833. path_builder.append('/');
  834. path_builder.append(init_slash_part);
  835. }
  836. path = path_builder.build();
  837. token = last_slash_part;
  838. // the invariant part of the token is actually just the last segment
  839. // e. in `cd /foo/bar', 'bar' is the invariant
  840. // since we are not suggesting anything starting with
  841. // `/foo/', but rather just `bar...'
  842. auto token_length = escape_token(token).length();
  843. editor->suggest(token_length, original_token.length() - token_length);
  844. // only suggest dot-files if path starts with a dot
  845. Core::DirIterator files(path,
  846. token.starts_with('.') ? Core::DirIterator::SkipParentAndBaseDir : Core::DirIterator::SkipDots);
  847. Vector<Line::CompletionSuggestion> suggestions;
  848. while (files.has_next()) {
  849. auto file = files.next_path();
  850. if (file.starts_with(token)) {
  851. struct stat program_status;
  852. String file_path = String::format("%s/%s", path.characters(), file.characters());
  853. int stat_error = stat(file_path.characters(), &program_status);
  854. if (!stat_error) {
  855. if (S_ISDIR(program_status.st_mode)) {
  856. suggestions.append({ escape_token(file), "/" });
  857. } else {
  858. suggestions.append({ escape_token(file), " " });
  859. }
  860. }
  861. }
  862. }
  863. return suggestions;
  864. }
  865. Vector<Line::CompletionSuggestion> Shell::complete_program_name(const String& name, size_t offset)
  866. {
  867. auto match = binary_search(cached_path.span(), name, [](const String& name, const String& program) -> int {
  868. return strncmp(name.characters(), program.characters(), name.length());
  869. });
  870. if (!match)
  871. return complete_path("", name, offset);
  872. String completion = *match;
  873. editor->suggest(escape_token(name).length(), 0);
  874. // Now that we have a program name starting with our token, we look at
  875. // other program names starting with our token and cut off any mismatching
  876. // characters.
  877. Vector<Line::CompletionSuggestion> suggestions;
  878. int index = match - cached_path.data();
  879. for (int i = index - 1; i >= 0 && cached_path[i].starts_with(name); --i) {
  880. suggestions.append({ cached_path[i], " " });
  881. }
  882. for (size_t i = index + 1; i < cached_path.size() && cached_path[i].starts_with(name); ++i) {
  883. suggestions.append({ cached_path[i], " " });
  884. }
  885. suggestions.append({ cached_path[index], " " });
  886. return suggestions;
  887. }
  888. Vector<Line::CompletionSuggestion> Shell::complete_variable(const String& name, size_t offset)
  889. {
  890. Vector<Line::CompletionSuggestion> suggestions;
  891. auto pattern = offset ? name.substring_view(0, offset) : "";
  892. editor->suggest(offset);
  893. // Look at local variables.
  894. for (auto& frame : m_local_frames) {
  895. for (auto& variable : frame.local_variables) {
  896. if (variable.key.starts_with(pattern) && !suggestions.contains_slow(variable.key))
  897. suggestions.append(variable.key);
  898. }
  899. }
  900. // Look at the environment.
  901. for (auto i = 0; environ[i]; ++i) {
  902. auto entry = StringView { environ[i] };
  903. if (entry.starts_with(pattern)) {
  904. auto parts = entry.split_view('=');
  905. if (parts.is_empty() || parts.first().is_empty())
  906. continue;
  907. String name = parts.first();
  908. if (suggestions.contains_slow(name))
  909. continue;
  910. suggestions.append(move(name));
  911. }
  912. }
  913. return suggestions;
  914. }
  915. Vector<Line::CompletionSuggestion> Shell::complete_user(const String& name, size_t offset)
  916. {
  917. Vector<Line::CompletionSuggestion> suggestions;
  918. auto pattern = offset ? name.substring_view(0, offset) : "";
  919. editor->suggest(offset);
  920. Core::DirIterator di("/home", Core::DirIterator::SkipParentAndBaseDir);
  921. if (di.has_error())
  922. return suggestions;
  923. while (di.has_next()) {
  924. String name = di.next_path();
  925. if (name.starts_with(pattern))
  926. suggestions.append(name);
  927. }
  928. return suggestions;
  929. }
  930. Vector<Line::CompletionSuggestion> Shell::complete_option(const String& program_name, const String& option, size_t offset)
  931. {
  932. size_t start = 0;
  933. while (start < option.length() && option[start] == '-' && start < 2)
  934. ++start;
  935. auto option_pattern = offset > start ? option.substring_view(start, offset - start) : "";
  936. editor->suggest(offset);
  937. Vector<Line::CompletionSuggestion> suggestions;
  938. dbg() << "Shell::complete_option(" << program_name << ", " << option_pattern << ")";
  939. // FIXME: Figure out how to do this stuff.
  940. if (has_builtin(program_name)) {
  941. // Complete builtins.
  942. if (program_name == "setopt") {
  943. bool negate = false;
  944. if (option_pattern.starts_with("no_")) {
  945. negate = true;
  946. option_pattern = option_pattern.substring_view(3, option_pattern.length() - 3);
  947. }
  948. auto maybe_negate = [&](const StringView& view) {
  949. static StringBuilder builder;
  950. builder.clear();
  951. builder.append("--");
  952. if (negate)
  953. builder.append("no_");
  954. builder.append(view);
  955. return builder.to_string();
  956. };
  957. #define __ENUMERATE_SHELL_OPTION(name, d_, descr_) \
  958. if (StringView { #name }.starts_with(option_pattern)) \
  959. suggestions.append(maybe_negate(#name));
  960. ENUMERATE_SHELL_OPTIONS();
  961. #undef __ENUMERATE_SHELL_OPTION
  962. return suggestions;
  963. }
  964. }
  965. return suggestions;
  966. }
  967. void Shell::bring_cursor_to_beginning_of_a_line() const
  968. {
  969. struct winsize ws;
  970. if (editor) {
  971. ws = editor->terminal_size();
  972. } else {
  973. if (ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) < 0) {
  974. // Very annoying assumptions.
  975. ws.ws_col = 80;
  976. ws.ws_row = 25;
  977. }
  978. }
  979. // Black with Cyan background.
  980. constexpr auto default_mark = "\e[30;46m%\e[0m";
  981. String eol_mark = getenv("PROMPT_EOL_MARK");
  982. if (eol_mark.is_null())
  983. eol_mark = default_mark;
  984. size_t eol_mark_length = Line::Editor::actual_rendered_string_metrics(eol_mark).line_lengths.last();
  985. if (eol_mark_length >= ws.ws_col) {
  986. eol_mark = default_mark;
  987. eol_mark_length = 1;
  988. }
  989. fputs(eol_mark.characters(), stderr);
  990. for (auto i = 1 + eol_mark_length; i < ws.ws_col; ++i)
  991. putc(' ', stderr);
  992. putc('\r', stderr);
  993. }
  994. bool Shell::read_single_line()
  995. {
  996. restore_ios();
  997. bring_cursor_to_beginning_of_a_line();
  998. auto line_result = editor->get_line(prompt());
  999. if (line_result.is_error()) {
  1000. if (line_result.error() == Line::Editor::Error::Eof || line_result.error() == Line::Editor::Error::Empty) {
  1001. // Pretend the user tried to execute builtin_exit()
  1002. m_complete_line_builder.clear();
  1003. run_command("exit");
  1004. return read_single_line();
  1005. } else {
  1006. m_complete_line_builder.clear();
  1007. Core::EventLoop::current().quit(1);
  1008. return false;
  1009. }
  1010. }
  1011. auto& line = line_result.value();
  1012. if (line.is_empty())
  1013. return true;
  1014. if (!m_complete_line_builder.is_empty())
  1015. m_complete_line_builder.append("\n");
  1016. m_complete_line_builder.append(line);
  1017. run_command(m_complete_line_builder.string_view());
  1018. editor->add_to_history(m_complete_line_builder.build());
  1019. m_complete_line_builder.clear();
  1020. return true;
  1021. }
  1022. void Shell::custom_event(Core::CustomEvent& event)
  1023. {
  1024. if (event.custom_type() == ReadLine) {
  1025. if (read_single_line())
  1026. Core::EventLoop::current().post_event(*this, make<Core::CustomEvent>(ShellEventType::ReadLine));
  1027. return;
  1028. }
  1029. }
  1030. Shell::Shell()
  1031. {
  1032. uid = getuid();
  1033. tcsetpgrp(0, getpgrp());
  1034. m_pid = getpid();
  1035. push_frame().leak_frame();
  1036. int rc = gethostname(hostname, Shell::HostNameSize);
  1037. if (rc < 0)
  1038. perror("gethostname");
  1039. auto istty = isatty(STDIN_FILENO);
  1040. m_is_interactive = istty;
  1041. if (istty) {
  1042. rc = ttyname_r(0, ttyname, Shell::TTYNameSize);
  1043. if (rc < 0)
  1044. perror("ttyname_r");
  1045. } else {
  1046. ttyname[0] = 0;
  1047. }
  1048. {
  1049. auto* cwd = getcwd(nullptr, 0);
  1050. this->cwd = cwd;
  1051. setenv("PWD", cwd, 1);
  1052. free(cwd);
  1053. }
  1054. {
  1055. auto* pw = getpwuid(getuid());
  1056. if (pw) {
  1057. username = pw->pw_name;
  1058. home = pw->pw_dir;
  1059. setenv("HOME", pw->pw_dir, 1);
  1060. }
  1061. endpwent();
  1062. }
  1063. directory_stack.append(cwd);
  1064. load_history();
  1065. cache_path();
  1066. }
  1067. Shell::~Shell()
  1068. {
  1069. stop_all_jobs();
  1070. save_history();
  1071. }
  1072. void Shell::stop_all_jobs()
  1073. {
  1074. if (!jobs.is_empty()) {
  1075. printf("Killing active jobs\n");
  1076. for (auto& entry : jobs) {
  1077. if (!entry.value->is_running_in_background()) {
  1078. #ifdef SH_DEBUG
  1079. dbg() << "Job " << entry.value->pid() << " is not running in background";
  1080. #endif
  1081. kill_job(entry.value, SIGCONT);
  1082. }
  1083. kill_job(entry.value, SIGHUP);
  1084. }
  1085. usleep(10000); // Wait for a bit before killing the job
  1086. for (auto& entry : jobs) {
  1087. #ifdef SH_DEBUG
  1088. dbg() << "Actively killing " << entry.value->pid() << "(" << entry.value->cmd() << ")";
  1089. #endif
  1090. if (killpg(entry.value->pgid(), SIGKILL) < 0) {
  1091. if (errno == ESRCH)
  1092. continue; // The process has exited all by itself.
  1093. perror("killpg(KILL)");
  1094. }
  1095. }
  1096. }
  1097. }
  1098. u64 Shell::find_last_job_id() const
  1099. {
  1100. u64 job_id = 0;
  1101. for (auto& entry : jobs) {
  1102. if (entry.value->job_id() > job_id)
  1103. job_id = entry.value->job_id();
  1104. }
  1105. return job_id;
  1106. }
  1107. const Job* Shell::find_job(u64 id)
  1108. {
  1109. for (auto& entry : jobs) {
  1110. if (entry.value->job_id() == id)
  1111. return entry.value;
  1112. }
  1113. return nullptr;
  1114. }
  1115. void Shell::kill_job(const Job* job, int sig)
  1116. {
  1117. if (!job)
  1118. return;
  1119. if (killpg(job->pgid(), sig) < 0)
  1120. perror("killpg(job)");
  1121. }
  1122. void Shell::save_to(JsonObject& object)
  1123. {
  1124. Core::Object::save_to(object);
  1125. object.set("working_directory", cwd);
  1126. object.set("username", username);
  1127. object.set("user_home_path", home);
  1128. object.set("user_id", uid);
  1129. object.set("directory_stack_size", directory_stack.size());
  1130. object.set("cd_history_size", cd_history.size());
  1131. // Jobs.
  1132. JsonArray job_objects;
  1133. for (auto& job_entry : jobs) {
  1134. JsonObject job_object;
  1135. job_object.set("pid", job_entry.value->pid());
  1136. job_object.set("pgid", job_entry.value->pgid());
  1137. job_object.set("running_time", job_entry.value->timer().elapsed());
  1138. job_object.set("command", job_entry.value->cmd());
  1139. job_object.set("is_running_in_background", job_entry.value->is_running_in_background());
  1140. job_objects.append(move(job_object));
  1141. }
  1142. object.set("jobs", move(job_objects));
  1143. }