Shell.cpp 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216
  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 <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. auto result = command->run(*this);
  366. if (result->is_job()) {
  367. auto job_result = static_cast<AST::JobValue*>(result.ptr());
  368. auto job = job_result->job();
  369. if (!job)
  370. last_return_code = 0;
  371. else if (job->exited())
  372. last_return_code = job->exit_code();
  373. }
  374. return last_return_code;
  375. }
  376. RefPtr<Job> Shell::run_command(const AST::Command& command)
  377. {
  378. FileDescriptionCollector fds;
  379. if (options.verbose) {
  380. fprintf(stderr, "+ ");
  381. for (auto& arg : command.argv)
  382. fprintf(stderr, "%s ", escape_token(arg).characters());
  383. fprintf(stderr, "\n");
  384. fflush(stderr);
  385. }
  386. // Resolve redirections.
  387. NonnullRefPtrVector<AST::Rewiring> rewirings;
  388. for (auto& redirection : command.redirections) {
  389. auto rewiring_result = redirection->apply();
  390. if (rewiring_result.is_error()) {
  391. if (!rewiring_result.error().is_empty())
  392. fprintf(stderr, "error: %s\n", rewiring_result.error().characters());
  393. continue;
  394. }
  395. auto& rewiring = rewiring_result.value();
  396. if (rewiring->fd_action != AST::Rewiring::Close::ImmediatelyCloseDestination)
  397. rewirings.append(*rewiring);
  398. if (rewiring->fd_action == AST::Rewiring::Close::Source) {
  399. fds.add(rewiring->source_fd);
  400. } else if (rewiring->fd_action == AST::Rewiring::Close::Destination) {
  401. if (rewiring->dest_fd != -1)
  402. fds.add(rewiring->dest_fd);
  403. } else if (rewiring->fd_action == AST::Rewiring::Close::ImmediatelyCloseDestination) {
  404. fds.add(rewiring->dest_fd);
  405. } else if (rewiring->fd_action == AST::Rewiring::Close::RefreshDestination) {
  406. ASSERT(rewiring->other_pipe_end);
  407. int pipe_fd[2];
  408. int rc = pipe(pipe_fd);
  409. if (rc < 0) {
  410. perror("pipe(RedirRefresh)");
  411. return nullptr;
  412. }
  413. rewiring->dest_fd = pipe_fd[1];
  414. rewiring->other_pipe_end->dest_fd = pipe_fd[0]; // This fd will be added to the collection on one of the next iterations.
  415. fds.add(pipe_fd[1]);
  416. }
  417. }
  418. // If the command is empty, do all the rewirings in the current process and return.
  419. // This allows the user to mess with the shell internals, but is apparently useful?
  420. // We'll just allow the users to shoot themselves until they get tired of doing so.
  421. if (command.argv.is_empty()) {
  422. for (auto& rewiring : rewirings) {
  423. #ifdef SH_DEBUG
  424. dbgprintf("in %d, dup2(%d, %d)\n", getpid(), rewiring.dest_fd, rewiring.source_fd);
  425. #endif
  426. int rc = dup2(rewiring.dest_fd, rewiring.source_fd);
  427. if (rc < 0) {
  428. perror("dup2(run)");
  429. return nullptr;
  430. }
  431. }
  432. fds.collect();
  433. return nullptr;
  434. }
  435. Vector<const char*> argv;
  436. Vector<String> copy_argv = command.argv;
  437. argv.ensure_capacity(command.argv.size() + 1);
  438. for (auto& arg : copy_argv)
  439. argv.append(arg.characters());
  440. argv.append(nullptr);
  441. int retval = 0;
  442. if (run_builtin(argv.size() - 1, argv.data(), retval))
  443. return nullptr;
  444. pid_t child = fork();
  445. if (child < 0) {
  446. perror("fork");
  447. return nullptr;
  448. }
  449. if (child == 0) {
  450. setpgid(0, 0);
  451. tcsetattr(0, TCSANOW, &default_termios);
  452. if (command.should_wait) {
  453. auto pid = getpid();
  454. auto pgid = getpgid(pid);
  455. tcsetpgrp(STDOUT_FILENO, pgid);
  456. tcsetpgrp(STDIN_FILENO, pgid);
  457. }
  458. for (auto& rewiring : rewirings) {
  459. #ifdef SH_DEBUG
  460. dbgprintf("in %s<%d>, dup2(%d, %d)\n", argv[0], getpid(), rewiring.dest_fd, rewiring.source_fd);
  461. #endif
  462. int rc = dup2(rewiring.dest_fd, rewiring.source_fd);
  463. if (rc < 0) {
  464. perror("dup2(run)");
  465. return nullptr;
  466. }
  467. }
  468. fds.collect();
  469. int rc = execvp(argv[0], const_cast<char* const*>(argv.data()));
  470. if (rc < 0) {
  471. if (errno == ENOENT) {
  472. int shebang_fd = open(argv[0], O_RDONLY);
  473. auto close_argv = ScopeGuard([shebang_fd]() { if (shebang_fd >= 0) close(shebang_fd); });
  474. char shebang[256] {};
  475. ssize_t num_read = -1;
  476. if ((shebang_fd >= 0) && ((num_read = read(shebang_fd, shebang, sizeof(shebang))) >= 2) && (StringView(shebang).starts_with("#!"))) {
  477. StringView shebang_path_view(&shebang[2], num_read - 2);
  478. Optional<size_t> newline_pos = shebang_path_view.find_first_of("\n\r");
  479. shebang[newline_pos.has_value() ? (newline_pos.value() + 2) : num_read] = '\0';
  480. fprintf(stderr, "%s: Invalid interpreter \"%s\": %s\n", argv[0], &shebang[2], strerror(ENOENT));
  481. } else
  482. fprintf(stderr, "%s: Command not found.\n", argv[0]);
  483. } else {
  484. int saved_errno = errno;
  485. struct stat st;
  486. if (stat(argv[0], &st) == 0 && S_ISDIR(st.st_mode)) {
  487. fprintf(stderr, "Shell: %s: Is a directory\n", argv[0]);
  488. _exit(126);
  489. }
  490. fprintf(stderr, "execvp(%s): %s\n", argv[0], strerror(saved_errno));
  491. }
  492. _exit(126);
  493. }
  494. ASSERT_NOT_REACHED();
  495. }
  496. StringBuilder cmd;
  497. cmd.join(" ", command.argv);
  498. auto job = Job::create(child, (unsigned)child, cmd.build(), find_last_job_id() + 1);
  499. jobs.set((u64)child, job);
  500. job->on_exit = [](auto job) {
  501. if (!job->exited())
  502. return;
  503. if (job->is_running_in_background())
  504. fprintf(stderr, "Shell: Job %d(%s) exited\n", job->pid(), job->cmd().characters());
  505. job->disown();
  506. };
  507. fds.collect();
  508. return *job;
  509. }
  510. NonnullRefPtrVector<Job> Shell::run_commands(Vector<AST::Command>& commands)
  511. {
  512. NonnullRefPtrVector<Job> jobs_to_wait_for;
  513. for (auto& command : commands) {
  514. #ifdef SH_DEBUG
  515. dbg() << "Command";
  516. for (auto& arg : command.argv)
  517. dbg() << "argv: " << arg;
  518. for (auto& redir : command.redirections) {
  519. if (redir->is_path_redirection()) {
  520. auto path_redir = (const AST::PathRedirection*)redir.ptr();
  521. dbg() << "redir path " << (int)path_redir->direction << " " << path_redir->path << " <-> " << path_redir->fd;
  522. } else if (redir->is_fd_redirection()) {
  523. dbg() << "redir fd " << redir->source_fd << " -> " << redir->dest_fd;
  524. } else if (redir->is_close_redirection()) {
  525. auto close_redir = (const AST::CloseRedirection*)redir.ptr();
  526. dbg() << "close fd " << close_redir->fd;
  527. } else {
  528. ASSERT_NOT_REACHED();
  529. }
  530. }
  531. #endif
  532. auto job = run_command(command);
  533. if (!job)
  534. continue;
  535. if (command.should_wait) {
  536. block_on_job(job);
  537. if (!job->is_suspended())
  538. jobs_to_wait_for.append(*job);
  539. } else {
  540. if (command.is_pipe_source) {
  541. jobs_to_wait_for.append(*job);
  542. } else if (command.should_notify_if_in_background) {
  543. job->set_running_in_background(true);
  544. restore_ios();
  545. }
  546. }
  547. }
  548. return jobs_to_wait_for;
  549. }
  550. bool Shell::run_file(const String& filename, bool explicitly_invoked)
  551. {
  552. auto file_result = Core::File::open(filename, Core::File::ReadOnly);
  553. if (file_result.is_error()) {
  554. if (explicitly_invoked)
  555. fprintf(stderr, "Failed to open %s: %s\n", filename.characters(), file_result.error().characters());
  556. else
  557. dbg() << "open() failed for '" << filename << "' with " << file_result.error();
  558. return false;
  559. }
  560. auto file = file_result.value();
  561. auto data = file->read_all();
  562. run_command(data);
  563. return true;
  564. }
  565. void Shell::restore_ios()
  566. {
  567. tcsetattr(0, TCSANOW, &termios);
  568. tcsetpgrp(STDOUT_FILENO, m_pid);
  569. tcsetpgrp(STDIN_FILENO, m_pid);
  570. }
  571. void Shell::block_on_job(RefPtr<Job> job)
  572. {
  573. TemporaryChange<const Job*> current_job { m_current_job, job.ptr() };
  574. if (!job)
  575. return;
  576. Core::EventLoop loop;
  577. job->on_exit = [&, old_exit = move(job->on_exit)](auto job) {
  578. if (old_exit)
  579. old_exit(job);
  580. loop.quit(0);
  581. };
  582. if (job->exited()) {
  583. restore_ios();
  584. return;
  585. }
  586. loop.exec();
  587. if (job->is_suspended())
  588. job->print_status(Job::PrintStatusMode::Basic);
  589. restore_ios();
  590. }
  591. String Shell::get_history_path()
  592. {
  593. StringBuilder builder;
  594. builder.append(home);
  595. builder.append("/.history");
  596. return builder.to_string();
  597. }
  598. void Shell::load_history()
  599. {
  600. auto history_file = Core::File::construct(get_history_path());
  601. if (!history_file->open(Core::IODevice::ReadOnly))
  602. return;
  603. while (history_file->can_read_line()) {
  604. auto b = history_file->read_line(1024);
  605. // skip the newline and terminating bytes
  606. editor->add_to_history(String(reinterpret_cast<const char*>(b.data()), b.size() - 2));
  607. }
  608. }
  609. void Shell::save_history()
  610. {
  611. auto file_or_error = Core::File::open(get_history_path(), Core::IODevice::WriteOnly, 0600);
  612. if (file_or_error.is_error())
  613. return;
  614. auto& file = *file_or_error.value();
  615. for (const auto& line : editor->history()) {
  616. file.write(line);
  617. file.write("\n");
  618. }
  619. }
  620. String Shell::escape_token(const String& token)
  621. {
  622. StringBuilder builder;
  623. for (auto c : token) {
  624. switch (c) {
  625. case '\'':
  626. case '"':
  627. case '$':
  628. case '|':
  629. case '>':
  630. case '<':
  631. case '&':
  632. case '\\':
  633. case ' ':
  634. builder.append('\\');
  635. break;
  636. default:
  637. break;
  638. }
  639. builder.append(c);
  640. }
  641. return builder.build();
  642. }
  643. String Shell::unescape_token(const String& token)
  644. {
  645. StringBuilder builder;
  646. enum {
  647. Free,
  648. Escaped
  649. } state { Free };
  650. for (auto c : token) {
  651. switch (state) {
  652. case Escaped:
  653. builder.append(c);
  654. state = Free;
  655. break;
  656. case Free:
  657. if (c == '\\')
  658. state = Escaped;
  659. else
  660. builder.append(c);
  661. break;
  662. }
  663. }
  664. if (state == Escaped)
  665. builder.append('\\');
  666. return builder.build();
  667. }
  668. void Shell::cache_path()
  669. {
  670. if (!cached_path.is_empty())
  671. cached_path.clear_with_capacity();
  672. // Add shell builtins to the cache.
  673. for (const auto& builtin_name : builtin_names)
  674. cached_path.append(escape_token(builtin_name));
  675. // Add aliases to the cache.
  676. for (const auto& alias : m_aliases) {
  677. auto name = escape_token(alias.key);
  678. if (cached_path.contains_slow(name))
  679. continue;
  680. cached_path.append(name);
  681. }
  682. String path = getenv("PATH");
  683. if (!path.is_empty()) {
  684. auto directories = path.split(':');
  685. for (const auto& directory : directories) {
  686. Core::DirIterator programs(directory.characters(), Core::DirIterator::SkipDots);
  687. while (programs.has_next()) {
  688. auto program = programs.next_path();
  689. String program_path = String::format("%s/%s", directory.characters(), program.characters());
  690. auto escaped_name = escape_token(program);
  691. if (cached_path.contains_slow(escaped_name))
  692. continue;
  693. if (access(program_path.characters(), X_OK) == 0)
  694. cached_path.append(escaped_name);
  695. }
  696. }
  697. }
  698. quick_sort(cached_path);
  699. }
  700. void Shell::add_entry_to_cache(const String& entry)
  701. {
  702. size_t index = 0;
  703. auto match = binary_search(
  704. cached_path.span(), entry, [](const String& name, const String& program) -> int {
  705. return strcmp(name.characters(), program.characters());
  706. },
  707. &index);
  708. if (match)
  709. return;
  710. while (strcmp(cached_path[index].characters(), entry.characters()) < 0) {
  711. index++;
  712. }
  713. cached_path.insert(index, entry);
  714. }
  715. void Shell::highlight(Line::Editor& editor) const
  716. {
  717. auto line = editor.line();
  718. Parser parser(line);
  719. auto ast = parser.parse();
  720. if (!ast)
  721. return;
  722. ast->highlight_in_editor(editor, const_cast<Shell&>(*this));
  723. }
  724. Vector<Line::CompletionSuggestion> Shell::complete(const Line::Editor& editor)
  725. {
  726. auto line = editor.line(editor.cursor());
  727. Parser parser(line);
  728. auto ast = parser.parse();
  729. if (!ast)
  730. return {};
  731. return ast->complete_for_editor(*this, line.length());
  732. }
  733. Vector<Line::CompletionSuggestion> Shell::complete_path(const String& base, const String& part, size_t offset)
  734. {
  735. auto token = offset ? part.substring_view(0, offset) : "";
  736. StringView original_token = token;
  737. String path;
  738. ssize_t last_slash = token.length() - 1;
  739. while (last_slash >= 0 && token[last_slash] != '/')
  740. --last_slash;
  741. StringBuilder path_builder;
  742. auto init_slash_part = token.substring_view(0, last_slash + 1);
  743. auto last_slash_part = token.substring_view(last_slash + 1, token.length() - last_slash - 1);
  744. // Depending on the base, we will have to prepend cwd.
  745. if (base.is_empty()) {
  746. // '' /foo -> absolute
  747. // '' foo -> relative
  748. if (!token.starts_with('/'))
  749. path_builder.append(cwd);
  750. path_builder.append('/');
  751. path_builder.append(init_slash_part);
  752. } else {
  753. // /foo * -> absolute
  754. // foo * -> relative
  755. if (!base.starts_with('/'))
  756. path_builder.append(cwd);
  757. path_builder.append('/');
  758. path_builder.append(base);
  759. path_builder.append('/');
  760. path_builder.append(init_slash_part);
  761. }
  762. path = path_builder.build();
  763. token = last_slash_part;
  764. // the invariant part of the token is actually just the last segment
  765. // e. in `cd /foo/bar', 'bar' is the invariant
  766. // since we are not suggesting anything starting with
  767. // `/foo/', but rather just `bar...'
  768. auto token_length = escape_token(token).length();
  769. editor->suggest(token_length, original_token.length() - token_length);
  770. // only suggest dot-files if path starts with a dot
  771. Core::DirIterator files(path,
  772. token.starts_with('.') ? Core::DirIterator::SkipParentAndBaseDir : Core::DirIterator::SkipDots);
  773. Vector<Line::CompletionSuggestion> suggestions;
  774. while (files.has_next()) {
  775. auto file = files.next_path();
  776. if (file.starts_with(token)) {
  777. struct stat program_status;
  778. String file_path = String::format("%s/%s", path.characters(), file.characters());
  779. int stat_error = stat(file_path.characters(), &program_status);
  780. if (!stat_error) {
  781. if (S_ISDIR(program_status.st_mode)) {
  782. suggestions.append({ escape_token(file), "/" });
  783. } else {
  784. suggestions.append({ escape_token(file), " " });
  785. }
  786. }
  787. }
  788. }
  789. return suggestions;
  790. }
  791. Vector<Line::CompletionSuggestion> Shell::complete_program_name(const String& name, size_t offset)
  792. {
  793. auto match = binary_search(cached_path.span(), name, [](const String& name, const String& program) -> int {
  794. return strncmp(name.characters(), program.characters(), name.length());
  795. });
  796. if (!match)
  797. return complete_path("", name, offset);
  798. String completion = *match;
  799. editor->suggest(escape_token(name).length(), 0);
  800. // Now that we have a program name starting with our token, we look at
  801. // other program names starting with our token and cut off any mismatching
  802. // characters.
  803. Vector<Line::CompletionSuggestion> suggestions;
  804. int index = match - cached_path.data();
  805. for (int i = index - 1; i >= 0 && cached_path[i].starts_with(name); --i) {
  806. suggestions.append({ cached_path[i], " " });
  807. }
  808. for (size_t i = index + 1; i < cached_path.size() && cached_path[i].starts_with(name); ++i) {
  809. suggestions.append({ cached_path[i], " " });
  810. }
  811. suggestions.append({ cached_path[index], " " });
  812. return suggestions;
  813. }
  814. Vector<Line::CompletionSuggestion> Shell::complete_variable(const String& name, size_t offset)
  815. {
  816. Vector<Line::CompletionSuggestion> suggestions;
  817. auto pattern = offset ? name.substring_view(0, offset) : "";
  818. editor->suggest(offset);
  819. // Look at local variables.
  820. for (auto& frame : m_local_frames) {
  821. for (auto& variable : frame.local_variables) {
  822. if (variable.key.starts_with(pattern) && !suggestions.contains_slow(variable.key))
  823. suggestions.append(variable.key);
  824. }
  825. }
  826. // Look at the environment.
  827. for (auto i = 0; environ[i]; ++i) {
  828. auto entry = StringView { environ[i] };
  829. if (entry.starts_with(pattern)) {
  830. auto parts = entry.split_view('=');
  831. if (parts.is_empty() || parts.first().is_empty())
  832. continue;
  833. String name = parts.first();
  834. if (suggestions.contains_slow(name))
  835. continue;
  836. suggestions.append(move(name));
  837. }
  838. }
  839. return suggestions;
  840. }
  841. Vector<Line::CompletionSuggestion> Shell::complete_user(const String& name, size_t offset)
  842. {
  843. Vector<Line::CompletionSuggestion> suggestions;
  844. auto pattern = offset ? name.substring_view(0, offset) : "";
  845. editor->suggest(offset);
  846. Core::DirIterator di("/home", Core::DirIterator::SkipParentAndBaseDir);
  847. if (di.has_error())
  848. return suggestions;
  849. while (di.has_next()) {
  850. String name = di.next_path();
  851. if (name.starts_with(pattern))
  852. suggestions.append(name);
  853. }
  854. return suggestions;
  855. }
  856. Vector<Line::CompletionSuggestion> Shell::complete_option(const String& program_name, const String& option, size_t offset)
  857. {
  858. size_t start = 0;
  859. while (start < option.length() && option[start] == '-' && start < 2)
  860. ++start;
  861. auto option_pattern = offset > start ? option.substring_view(start, offset - start) : "";
  862. editor->suggest(offset);
  863. Vector<Line::CompletionSuggestion> suggestions;
  864. dbg() << "Shell::complete_option(" << program_name << ", " << option_pattern << ")";
  865. // FIXME: Figure out how to do this stuff.
  866. if (has_builtin(program_name)) {
  867. // Complete builtins.
  868. if (program_name == "setopt") {
  869. bool negate = false;
  870. if (option_pattern.starts_with("no_")) {
  871. negate = true;
  872. option_pattern = option_pattern.substring_view(3, option_pattern.length() - 3);
  873. }
  874. auto maybe_negate = [&](const StringView& view) {
  875. static StringBuilder builder;
  876. builder.clear();
  877. builder.append("--");
  878. if (negate)
  879. builder.append("no_");
  880. builder.append(view);
  881. return builder.to_string();
  882. };
  883. #define __ENUMERATE_SHELL_OPTION(name, d_, descr_) \
  884. if (StringView { #name }.starts_with(option_pattern)) \
  885. suggestions.append(maybe_negate(#name));
  886. ENUMERATE_SHELL_OPTIONS();
  887. #undef __ENUMERATE_SHELL_OPTION
  888. return suggestions;
  889. }
  890. }
  891. return suggestions;
  892. }
  893. bool Shell::read_single_line()
  894. {
  895. restore_ios();
  896. auto line_result = editor->get_line(prompt());
  897. if (line_result.is_error()) {
  898. if (line_result.error() == Line::Editor::Error::Eof || line_result.error() == Line::Editor::Error::Empty) {
  899. // Pretend the user tried to execute builtin_exit()
  900. m_complete_line_builder.clear();
  901. run_command("exit");
  902. return read_single_line();
  903. } else {
  904. m_complete_line_builder.clear();
  905. Core::EventLoop::current().quit(1);
  906. return false;
  907. }
  908. }
  909. auto& line = line_result.value();
  910. if (line.is_empty())
  911. return true;
  912. if (!m_complete_line_builder.is_empty())
  913. m_complete_line_builder.append("\n");
  914. m_complete_line_builder.append(line);
  915. run_command(m_complete_line_builder.string_view());
  916. editor->add_to_history(m_complete_line_builder.build());
  917. m_complete_line_builder.clear();
  918. return true;
  919. }
  920. void Shell::custom_event(Core::CustomEvent& event)
  921. {
  922. if (event.custom_type() == ReadLine) {
  923. if (read_single_line())
  924. Core::EventLoop::current().post_event(*this, make<Core::CustomEvent>(ShellEventType::ReadLine));
  925. return;
  926. }
  927. }
  928. Shell::Shell()
  929. {
  930. uid = getuid();
  931. tcsetpgrp(0, getpgrp());
  932. m_pid = getpid();
  933. push_frame().leak_frame();
  934. int rc = gethostname(hostname, Shell::HostNameSize);
  935. if (rc < 0)
  936. perror("gethostname");
  937. auto istty = isatty(STDIN_FILENO);
  938. m_is_interactive = istty;
  939. if (istty) {
  940. rc = ttyname_r(0, ttyname, Shell::TTYNameSize);
  941. if (rc < 0)
  942. perror("ttyname_r");
  943. } else {
  944. ttyname[0] = 0;
  945. }
  946. {
  947. auto* cwd = getcwd(nullptr, 0);
  948. this->cwd = cwd;
  949. setenv("PWD", cwd, 1);
  950. free(cwd);
  951. }
  952. {
  953. auto* pw = getpwuid(getuid());
  954. if (pw) {
  955. username = pw->pw_name;
  956. home = pw->pw_dir;
  957. setenv("HOME", pw->pw_dir, 1);
  958. }
  959. endpwent();
  960. }
  961. directory_stack.append(cwd);
  962. load_history();
  963. cache_path();
  964. }
  965. Shell::~Shell()
  966. {
  967. stop_all_jobs();
  968. save_history();
  969. }
  970. void Shell::stop_all_jobs()
  971. {
  972. if (!jobs.is_empty()) {
  973. printf("Killing active jobs\n");
  974. for (auto& entry : jobs) {
  975. if (!entry.value->is_running_in_background()) {
  976. #ifdef SH_DEBUG
  977. dbg() << "Job " << entry.value->pid() << " is not running in background";
  978. #endif
  979. kill_job(entry.value, SIGCONT);
  980. }
  981. kill_job(entry.value, SIGHUP);
  982. }
  983. usleep(10000); // Wait for a bit before killing the job
  984. for (auto& entry : jobs) {
  985. #ifdef SH_DEBUG
  986. dbg() << "Actively killing " << entry.value->pid() << "(" << entry.value->cmd() << ")";
  987. #endif
  988. if (killpg(entry.value->pgid(), SIGKILL) < 0) {
  989. if (errno == ESRCH)
  990. continue; // The process has exited all by itself.
  991. perror("killpg(KILL)");
  992. }
  993. }
  994. }
  995. }
  996. u64 Shell::find_last_job_id() const
  997. {
  998. u64 job_id = 0;
  999. for (auto& entry : jobs) {
  1000. if (entry.value->job_id() > job_id)
  1001. job_id = entry.value->job_id();
  1002. }
  1003. return job_id;
  1004. }
  1005. const Job* Shell::find_job(u64 id)
  1006. {
  1007. for (auto& entry : jobs) {
  1008. if (entry.value->job_id() == id)
  1009. return entry.value;
  1010. }
  1011. return nullptr;
  1012. }
  1013. void Shell::kill_job(const Job* job, int sig)
  1014. {
  1015. if (!job)
  1016. return;
  1017. if (killpg(job->pgid(), sig) < 0)
  1018. perror("killpg(job)");
  1019. }
  1020. void Shell::save_to(JsonObject& object)
  1021. {
  1022. Core::Object::save_to(object);
  1023. object.set("working_directory", cwd);
  1024. object.set("username", username);
  1025. object.set("user_home_path", home);
  1026. object.set("user_id", uid);
  1027. object.set("directory_stack_size", directory_stack.size());
  1028. object.set("cd_history_size", cd_history.size());
  1029. // Jobs.
  1030. JsonArray job_objects;
  1031. for (auto& job_entry : jobs) {
  1032. JsonObject job_object;
  1033. job_object.set("pid", job_entry.value->pid());
  1034. job_object.set("pgid", job_entry.value->pgid());
  1035. job_object.set("running_time", job_entry.value->timer().elapsed());
  1036. job_object.set("command", job_entry.value->cmd());
  1037. job_object.set("is_running_in_background", job_entry.value->is_running_in_background());
  1038. job_objects.append(move(job_object));
  1039. }
  1040. object.set("jobs", move(job_objects));
  1041. }