Shell.cpp 38 KB

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