Shell.cpp 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213
  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. restore_ios();
  588. }
  589. String Shell::get_history_path()
  590. {
  591. StringBuilder builder;
  592. builder.append(home);
  593. builder.append("/.history");
  594. return builder.to_string();
  595. }
  596. void Shell::load_history()
  597. {
  598. auto history_file = Core::File::construct(get_history_path());
  599. if (!history_file->open(Core::IODevice::ReadOnly))
  600. return;
  601. while (history_file->can_read_line()) {
  602. auto b = history_file->read_line(1024);
  603. // skip the newline and terminating bytes
  604. editor->add_to_history(String(reinterpret_cast<const char*>(b.data()), b.size() - 2));
  605. }
  606. }
  607. void Shell::save_history()
  608. {
  609. auto file_or_error = Core::File::open(get_history_path(), Core::IODevice::WriteOnly, 0600);
  610. if (file_or_error.is_error())
  611. return;
  612. auto& file = *file_or_error.value();
  613. for (const auto& line : editor->history()) {
  614. file.write(line);
  615. file.write("\n");
  616. }
  617. }
  618. String Shell::escape_token(const String& token)
  619. {
  620. StringBuilder builder;
  621. for (auto c : token) {
  622. switch (c) {
  623. case '\'':
  624. case '"':
  625. case '$':
  626. case '|':
  627. case '>':
  628. case '<':
  629. case '&':
  630. case '\\':
  631. case ' ':
  632. builder.append('\\');
  633. break;
  634. default:
  635. break;
  636. }
  637. builder.append(c);
  638. }
  639. return builder.build();
  640. }
  641. String Shell::unescape_token(const String& token)
  642. {
  643. StringBuilder builder;
  644. enum {
  645. Free,
  646. Escaped
  647. } state { Free };
  648. for (auto c : token) {
  649. switch (state) {
  650. case Escaped:
  651. builder.append(c);
  652. state = Free;
  653. break;
  654. case Free:
  655. if (c == '\\')
  656. state = Escaped;
  657. else
  658. builder.append(c);
  659. break;
  660. }
  661. }
  662. if (state == Escaped)
  663. builder.append('\\');
  664. return builder.build();
  665. }
  666. void Shell::cache_path()
  667. {
  668. if (!cached_path.is_empty())
  669. cached_path.clear_with_capacity();
  670. // Add shell builtins to the cache.
  671. for (const auto& builtin_name : builtin_names)
  672. cached_path.append(escape_token(builtin_name));
  673. // Add aliases to the cache.
  674. for (const auto& alias : m_aliases) {
  675. auto name = escape_token(alias.key);
  676. if (cached_path.contains_slow(name))
  677. continue;
  678. cached_path.append(name);
  679. }
  680. String path = getenv("PATH");
  681. if (!path.is_empty()) {
  682. auto directories = path.split(':');
  683. for (const auto& directory : directories) {
  684. Core::DirIterator programs(directory.characters(), Core::DirIterator::SkipDots);
  685. while (programs.has_next()) {
  686. auto program = programs.next_path();
  687. String program_path = String::format("%s/%s", directory.characters(), program.characters());
  688. auto escaped_name = escape_token(program);
  689. if (cached_path.contains_slow(escaped_name))
  690. continue;
  691. if (access(program_path.characters(), X_OK) == 0)
  692. cached_path.append(escaped_name);
  693. }
  694. }
  695. }
  696. quick_sort(cached_path);
  697. }
  698. void Shell::add_entry_to_cache(const String& entry)
  699. {
  700. size_t index = 0;
  701. auto match = binary_search(
  702. cached_path.span(), entry, [](const String& name, const String& program) -> int {
  703. return strcmp(name.characters(), program.characters());
  704. },
  705. &index);
  706. if (match)
  707. return;
  708. while (strcmp(cached_path[index].characters(), entry.characters()) < 0) {
  709. index++;
  710. }
  711. cached_path.insert(index, entry);
  712. }
  713. void Shell::highlight(Line::Editor& editor) const
  714. {
  715. auto line = editor.line();
  716. Parser parser(line);
  717. auto ast = parser.parse();
  718. if (!ast)
  719. return;
  720. ast->highlight_in_editor(editor, const_cast<Shell&>(*this));
  721. }
  722. Vector<Line::CompletionSuggestion> Shell::complete(const Line::Editor& editor)
  723. {
  724. auto line = editor.line(editor.cursor());
  725. Parser parser(line);
  726. auto ast = parser.parse();
  727. if (!ast)
  728. return {};
  729. return ast->complete_for_editor(*this, line.length());
  730. }
  731. Vector<Line::CompletionSuggestion> Shell::complete_path(const String& base, const String& part, size_t offset)
  732. {
  733. auto token = offset ? part.substring_view(0, offset) : "";
  734. StringView original_token = token;
  735. String path;
  736. ssize_t last_slash = token.length() - 1;
  737. while (last_slash >= 0 && token[last_slash] != '/')
  738. --last_slash;
  739. StringBuilder path_builder;
  740. auto init_slash_part = token.substring_view(0, last_slash + 1);
  741. auto last_slash_part = token.substring_view(last_slash + 1, token.length() - last_slash - 1);
  742. // Depending on the base, we will have to prepend cwd.
  743. if (base.is_empty()) {
  744. // '' /foo -> absolute
  745. // '' foo -> relative
  746. if (!token.starts_with('/'))
  747. path_builder.append(cwd);
  748. path_builder.append('/');
  749. path_builder.append(init_slash_part);
  750. } else {
  751. // /foo * -> absolute
  752. // foo * -> relative
  753. if (!base.starts_with('/'))
  754. path_builder.append(cwd);
  755. path_builder.append('/');
  756. path_builder.append(base);
  757. path_builder.append('/');
  758. path_builder.append(init_slash_part);
  759. }
  760. path = path_builder.build();
  761. token = last_slash_part;
  762. // the invariant part of the token is actually just the last segment
  763. // e. in `cd /foo/bar', 'bar' is the invariant
  764. // since we are not suggesting anything starting with
  765. // `/foo/', but rather just `bar...'
  766. auto token_length = escape_token(token).length();
  767. editor->suggest(token_length, original_token.length() - token_length);
  768. // only suggest dot-files if path starts with a dot
  769. Core::DirIterator files(path,
  770. token.starts_with('.') ? Core::DirIterator::SkipParentAndBaseDir : Core::DirIterator::SkipDots);
  771. Vector<Line::CompletionSuggestion> suggestions;
  772. while (files.has_next()) {
  773. auto file = files.next_path();
  774. if (file.starts_with(token)) {
  775. struct stat program_status;
  776. String file_path = String::format("%s/%s", path.characters(), file.characters());
  777. int stat_error = stat(file_path.characters(), &program_status);
  778. if (!stat_error) {
  779. if (S_ISDIR(program_status.st_mode)) {
  780. suggestions.append({ escape_token(file), "/" });
  781. } else {
  782. suggestions.append({ escape_token(file), " " });
  783. }
  784. }
  785. }
  786. }
  787. return suggestions;
  788. }
  789. Vector<Line::CompletionSuggestion> Shell::complete_program_name(const String& name, size_t offset)
  790. {
  791. auto match = binary_search(cached_path.span(), name, [](const String& name, const String& program) -> int {
  792. return strncmp(name.characters(), program.characters(), name.length());
  793. });
  794. if (!match)
  795. return complete_path("", name, offset);
  796. String completion = *match;
  797. editor->suggest(escape_token(name).length(), 0);
  798. // Now that we have a program name starting with our token, we look at
  799. // other program names starting with our token and cut off any mismatching
  800. // characters.
  801. Vector<Line::CompletionSuggestion> suggestions;
  802. int index = match - cached_path.data();
  803. for (int i = index - 1; i >= 0 && cached_path[i].starts_with(name); --i) {
  804. suggestions.append({ cached_path[i], " " });
  805. }
  806. for (size_t i = index + 1; i < cached_path.size() && cached_path[i].starts_with(name); ++i) {
  807. suggestions.append({ cached_path[i], " " });
  808. }
  809. suggestions.append({ cached_path[index], " " });
  810. return suggestions;
  811. }
  812. Vector<Line::CompletionSuggestion> Shell::complete_variable(const String& name, size_t offset)
  813. {
  814. Vector<Line::CompletionSuggestion> suggestions;
  815. auto pattern = offset ? name.substring_view(0, offset) : "";
  816. editor->suggest(offset);
  817. // Look at local variables.
  818. for (auto& frame : m_local_frames) {
  819. for (auto& variable : frame.local_variables) {
  820. if (variable.key.starts_with(pattern) && !suggestions.contains_slow(variable.key))
  821. suggestions.append(variable.key);
  822. }
  823. }
  824. // Look at the environment.
  825. for (auto i = 0; environ[i]; ++i) {
  826. auto entry = StringView { environ[i] };
  827. if (entry.starts_with(pattern)) {
  828. auto parts = entry.split_view('=');
  829. if (parts.is_empty() || parts.first().is_empty())
  830. continue;
  831. String name = parts.first();
  832. if (suggestions.contains_slow(name))
  833. continue;
  834. suggestions.append(move(name));
  835. }
  836. }
  837. return suggestions;
  838. }
  839. Vector<Line::CompletionSuggestion> Shell::complete_user(const String& name, size_t offset)
  840. {
  841. Vector<Line::CompletionSuggestion> suggestions;
  842. auto pattern = offset ? name.substring_view(0, offset) : "";
  843. editor->suggest(offset);
  844. Core::DirIterator di("/home", Core::DirIterator::SkipParentAndBaseDir);
  845. if (di.has_error())
  846. return suggestions;
  847. while (di.has_next()) {
  848. String name = di.next_path();
  849. if (name.starts_with(pattern))
  850. suggestions.append(name);
  851. }
  852. return suggestions;
  853. }
  854. Vector<Line::CompletionSuggestion> Shell::complete_option(const String& program_name, const String& option, size_t offset)
  855. {
  856. size_t start = 0;
  857. while (start < option.length() && option[start] == '-' && start < 2)
  858. ++start;
  859. auto option_pattern = offset > start ? option.substring_view(start, offset - start) : "";
  860. editor->suggest(offset);
  861. Vector<Line::CompletionSuggestion> suggestions;
  862. dbg() << "Shell::complete_option(" << program_name << ", " << option_pattern << ")";
  863. // FIXME: Figure out how to do this stuff.
  864. if (has_builtin(program_name)) {
  865. // Complete builtins.
  866. if (program_name == "setopt") {
  867. bool negate = false;
  868. if (option_pattern.starts_with("no_")) {
  869. negate = true;
  870. option_pattern = option_pattern.substring_view(3, option_pattern.length() - 3);
  871. }
  872. auto maybe_negate = [&](const StringView& view) {
  873. static StringBuilder builder;
  874. builder.clear();
  875. builder.append("--");
  876. if (negate)
  877. builder.append("no_");
  878. builder.append(view);
  879. return builder.to_string();
  880. };
  881. #define __ENUMERATE_SHELL_OPTION(name, d_, descr_) \
  882. if (StringView { #name }.starts_with(option_pattern)) \
  883. suggestions.append(maybe_negate(#name));
  884. ENUMERATE_SHELL_OPTIONS();
  885. #undef __ENUMERATE_SHELL_OPTION
  886. return suggestions;
  887. }
  888. }
  889. return suggestions;
  890. }
  891. bool Shell::read_single_line()
  892. {
  893. restore_ios();
  894. auto line_result = editor->get_line(prompt());
  895. if (line_result.is_error()) {
  896. if (line_result.error() == Line::Editor::Error::Eof || line_result.error() == Line::Editor::Error::Empty) {
  897. // Pretend the user tried to execute builtin_exit()
  898. m_complete_line_builder.clear();
  899. run_command("exit");
  900. return read_single_line();
  901. } else {
  902. m_complete_line_builder.clear();
  903. Core::EventLoop::current().quit(1);
  904. return false;
  905. }
  906. }
  907. auto& line = line_result.value();
  908. if (line.is_empty())
  909. return true;
  910. if (!m_complete_line_builder.is_empty())
  911. m_complete_line_builder.append("\n");
  912. m_complete_line_builder.append(line);
  913. run_command(m_complete_line_builder.string_view());
  914. editor->add_to_history(m_complete_line_builder.build());
  915. m_complete_line_builder.clear();
  916. return true;
  917. }
  918. void Shell::custom_event(Core::CustomEvent& event)
  919. {
  920. if (event.custom_type() == ReadLine) {
  921. if (read_single_line())
  922. Core::EventLoop::current().post_event(*this, make<Core::CustomEvent>(ShellEventType::ReadLine));
  923. return;
  924. }
  925. }
  926. Shell::Shell()
  927. {
  928. uid = getuid();
  929. tcsetpgrp(0, getpgrp());
  930. m_pid = getpid();
  931. push_frame().leak_frame();
  932. int rc = gethostname(hostname, Shell::HostNameSize);
  933. if (rc < 0)
  934. perror("gethostname");
  935. auto istty = isatty(STDIN_FILENO);
  936. m_is_interactive = istty;
  937. if (istty) {
  938. rc = ttyname_r(0, ttyname, Shell::TTYNameSize);
  939. if (rc < 0)
  940. perror("ttyname_r");
  941. } else {
  942. ttyname[0] = 0;
  943. }
  944. {
  945. auto* cwd = getcwd(nullptr, 0);
  946. this->cwd = cwd;
  947. setenv("PWD", cwd, 1);
  948. free(cwd);
  949. }
  950. {
  951. auto* pw = getpwuid(getuid());
  952. if (pw) {
  953. username = pw->pw_name;
  954. home = pw->pw_dir;
  955. setenv("HOME", pw->pw_dir, 1);
  956. }
  957. endpwent();
  958. }
  959. directory_stack.append(cwd);
  960. load_history();
  961. cache_path();
  962. }
  963. Shell::~Shell()
  964. {
  965. stop_all_jobs();
  966. save_history();
  967. }
  968. void Shell::stop_all_jobs()
  969. {
  970. if (!jobs.is_empty()) {
  971. printf("Killing active jobs\n");
  972. for (auto& entry : jobs) {
  973. if (!entry.value->is_running_in_background()) {
  974. #ifdef SH_DEBUG
  975. dbg() << "Job " << entry.value->pid() << " is not running in background";
  976. #endif
  977. kill_job(entry.value, SIGCONT);
  978. }
  979. kill_job(entry.value, SIGHUP);
  980. }
  981. usleep(10000); // Wait for a bit before killing the job
  982. for (auto& entry : jobs) {
  983. #ifdef SH_DEBUG
  984. dbg() << "Actively killing " << entry.value->pid() << "(" << entry.value->cmd() << ")";
  985. #endif
  986. if (killpg(entry.value->pgid(), SIGKILL) < 0) {
  987. if (errno == ESRCH)
  988. continue; // The process has exited all by itself.
  989. perror("killpg(KILL)");
  990. }
  991. }
  992. }
  993. }
  994. u64 Shell::find_last_job_id() const
  995. {
  996. u64 job_id = 0;
  997. for (auto& entry : jobs) {
  998. if (entry.value->job_id() > job_id)
  999. job_id = entry.value->job_id();
  1000. }
  1001. return job_id;
  1002. }
  1003. const Job* Shell::find_job(u64 id)
  1004. {
  1005. for (auto& entry : jobs) {
  1006. if (entry.value->job_id() == id)
  1007. return entry.value;
  1008. }
  1009. return nullptr;
  1010. }
  1011. void Shell::kill_job(const Job* job, int sig)
  1012. {
  1013. if (!job)
  1014. return;
  1015. if (killpg(job->pgid(), sig) < 0)
  1016. perror("killpg(job)");
  1017. }
  1018. void Shell::save_to(JsonObject& object)
  1019. {
  1020. Core::Object::save_to(object);
  1021. object.set("working_directory", cwd);
  1022. object.set("username", username);
  1023. object.set("user_home_path", home);
  1024. object.set("user_id", uid);
  1025. object.set("directory_stack_size", directory_stack.size());
  1026. object.set("cd_history_size", cd_history.size());
  1027. // Jobs.
  1028. JsonArray job_objects;
  1029. for (auto& job_entry : jobs) {
  1030. JsonObject job_object;
  1031. job_object.set("pid", job_entry.value->pid());
  1032. job_object.set("pgid", job_entry.value->pgid());
  1033. job_object.set("running_time", job_entry.value->timer().elapsed());
  1034. job_object.set("command", job_entry.value->cmd());
  1035. job_object.set("is_running_in_background", job_entry.value->is_running_in_background());
  1036. job_objects.append(move(job_object));
  1037. }
  1038. object.set("jobs", move(job_objects));
  1039. }