Shell.cpp 37 KB

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