Shell.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929
  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. //#define SH_DEBUG
  54. void Shell::print_path(const String& path)
  55. {
  56. if (s_disable_hyperlinks) {
  57. printf("%s", path.characters());
  58. return;
  59. }
  60. printf("\033]8;;file://%s%s\033\\%s\033]8;;\033\\", hostname, path.characters(), path.characters());
  61. }
  62. String Shell::prompt() const
  63. {
  64. auto build_prompt = [&]() -> String {
  65. auto* ps1 = getenv("PROMPT");
  66. if (!ps1) {
  67. if (uid == 0)
  68. return "# ";
  69. StringBuilder builder;
  70. builder.appendf("\033]0;%s@%s:%s\007", username.characters(), hostname, cwd.characters());
  71. 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());
  72. return builder.to_string();
  73. }
  74. StringBuilder builder;
  75. for (char* ptr = ps1; *ptr; ++ptr) {
  76. if (*ptr == '\\') {
  77. ++ptr;
  78. if (!*ptr)
  79. break;
  80. switch (*ptr) {
  81. case 'X':
  82. builder.append("\033]0;");
  83. break;
  84. case 'a':
  85. builder.append(0x07);
  86. break;
  87. case 'e':
  88. builder.append(0x1b);
  89. break;
  90. case 'u':
  91. builder.append(username);
  92. break;
  93. case 'h':
  94. builder.append(hostname);
  95. break;
  96. case 'w': {
  97. String home_path = getenv("HOME");
  98. if (cwd.starts_with(home_path)) {
  99. builder.append('~');
  100. builder.append(cwd.substring_view(home_path.length(), cwd.length() - home_path.length()));
  101. } else {
  102. builder.append(cwd);
  103. }
  104. break;
  105. }
  106. case 'p':
  107. builder.append(uid == 0 ? '#' : '$');
  108. break;
  109. }
  110. continue;
  111. }
  112. builder.append(*ptr);
  113. }
  114. return builder.to_string();
  115. };
  116. return build_prompt();
  117. }
  118. String Shell::expand_tilde(const String& expression)
  119. {
  120. ASSERT(expression.starts_with('~'));
  121. StringBuilder login_name;
  122. size_t first_slash_index = expression.length();
  123. for (size_t i = 1; i < expression.length(); ++i) {
  124. if (expression[i] == '/') {
  125. first_slash_index = i;
  126. break;
  127. }
  128. login_name.append(expression[i]);
  129. }
  130. StringBuilder path;
  131. for (size_t i = first_slash_index; i < expression.length(); ++i)
  132. path.append(expression[i]);
  133. if (login_name.is_empty()) {
  134. const char* home = getenv("HOME");
  135. if (!home) {
  136. auto passwd = getpwuid(getuid());
  137. ASSERT(passwd && passwd->pw_dir);
  138. return String::format("%s/%s", passwd->pw_dir, path.to_string().characters());
  139. }
  140. return String::format("%s/%s", home, path.to_string().characters());
  141. }
  142. auto passwd = getpwnam(login_name.to_string().characters());
  143. if (!passwd)
  144. return expression;
  145. ASSERT(passwd->pw_dir);
  146. return String::format("%s/%s", passwd->pw_dir, path.to_string().characters());
  147. }
  148. bool Shell::is_glob(const StringView& s)
  149. {
  150. for (size_t i = 0; i < s.length(); i++) {
  151. char c = s.characters_without_null_termination()[i];
  152. if (c == '*' || c == '?')
  153. return true;
  154. }
  155. return false;
  156. }
  157. Vector<StringView> Shell::split_path(const StringView& path)
  158. {
  159. Vector<StringView> parts;
  160. size_t substart = 0;
  161. for (size_t i = 0; i < path.length(); i++) {
  162. char ch = path[i];
  163. if (ch != '/')
  164. continue;
  165. size_t sublen = i - substart;
  166. if (sublen != 0)
  167. parts.append(path.substring_view(substart, sublen));
  168. substart = i + 1;
  169. }
  170. size_t taillen = path.length() - substart;
  171. if (taillen != 0)
  172. parts.append(path.substring_view(substart, taillen));
  173. return parts;
  174. }
  175. Vector<String> Shell::expand_globs(const StringView& path, StringView base)
  176. {
  177. if (path.starts_with('/'))
  178. base = "/";
  179. auto parts = split_path(path);
  180. String base_string = base;
  181. struct stat statbuf;
  182. if (lstat(base_string.characters(), &statbuf) < 0) {
  183. perror("lstat");
  184. return {};
  185. }
  186. StringBuilder resolved_base_path_builder;
  187. resolved_base_path_builder.append(Core::File::real_path_for(base));
  188. if (S_ISDIR(statbuf.st_mode))
  189. resolved_base_path_builder.append('/');
  190. auto resolved_base = resolved_base_path_builder.string_view();
  191. auto results = expand_globs(move(parts), resolved_base);
  192. for (auto& entry : results) {
  193. entry = entry.substring(resolved_base.length(), entry.length() - resolved_base.length());
  194. if (entry.is_empty())
  195. entry = ".";
  196. }
  197. // Make the output predictable and nice.
  198. quick_sort(results);
  199. return results;
  200. }
  201. Vector<String> Shell::expand_globs(Vector<StringView> path_segments, const StringView& base)
  202. {
  203. if (path_segments.is_empty()) {
  204. String base_str = base;
  205. if (access(base_str.characters(), F_OK) == 0)
  206. return { move(base_str) };
  207. return {};
  208. }
  209. auto first_segment = path_segments.take_first();
  210. if (is_glob(first_segment)) {
  211. Vector<String> result;
  212. Core::DirIterator di(base, Core::DirIterator::SkipParentAndBaseDir);
  213. if (di.has_error())
  214. return {};
  215. while (di.has_next()) {
  216. String path = di.next_path();
  217. // Dotfiles have to be explicitly requested
  218. if (path[0] == '.' && first_segment[0] != '.')
  219. continue;
  220. if (path.matches(first_segment, CaseSensitivity::CaseSensitive)) {
  221. StringBuilder builder;
  222. builder.append(base);
  223. if (!base.ends_with('/'))
  224. builder.append('/');
  225. builder.append(path);
  226. result.append(expand_globs(path_segments, builder.string_view()));
  227. }
  228. }
  229. return result;
  230. } else {
  231. StringBuilder builder;
  232. builder.append(base);
  233. if (!base.ends_with('/'))
  234. builder.append('/');
  235. builder.append(first_segment);
  236. return expand_globs(move(path_segments), builder.string_view());
  237. }
  238. }
  239. String Shell::resolve_path(String path) const
  240. {
  241. if (!path.starts_with('/'))
  242. path = String::format("%s/%s", cwd.characters(), path.characters());
  243. return Core::File::real_path_for(path);
  244. }
  245. RefPtr<AST::Value> Shell::lookup_local_variable(const String& name)
  246. {
  247. auto value = m_local_variables.get(name).value_or(nullptr);
  248. return value;
  249. }
  250. String Shell::local_variable_or(const String& name, const String& replacement)
  251. {
  252. auto value = lookup_local_variable(name);
  253. if (value) {
  254. StringBuilder builder;
  255. builder.join(" ", value->resolve_as_list(*this));
  256. return builder.to_string();
  257. }
  258. return replacement;
  259. }
  260. void Shell::set_local_variable(const String& name, RefPtr<AST::Value> value)
  261. {
  262. m_local_variables.set(name, move(value));
  263. }
  264. void Shell::unset_local_variable(const String& name)
  265. {
  266. m_local_variables.remove(name);
  267. }
  268. String Shell::resolve_alias(const String& name) const
  269. {
  270. return m_aliases.get(name).value_or({});
  271. }
  272. int Shell::run_command(const StringView& cmd)
  273. {
  274. if (cmd.is_empty())
  275. return 0;
  276. if (cmd.starts_with("#"))
  277. return 0;
  278. auto command = Parser(cmd).parse();
  279. if (!command)
  280. return 0;
  281. #ifndef SH_DEBUG
  282. dbg() << "Command follows";
  283. command->dump(0);
  284. #endif
  285. tcgetattr(0, &termios);
  286. auto result = command->run(*this);
  287. if (result->is_job()) {
  288. auto job_result = static_cast<AST::JobValue*>(result.ptr());
  289. auto job = job_result->job();
  290. if (!job)
  291. last_return_code = 0;
  292. else if (job->exited())
  293. last_return_code = job->exit_code();
  294. }
  295. return last_return_code;
  296. }
  297. RefPtr<Job> Shell::run_command(AST::Command& command)
  298. {
  299. FileDescriptionCollector fds;
  300. // Resolve redirections.
  301. Vector<AST::Rewiring> rewirings;
  302. for (auto& redirection : command.redirections) {
  303. auto rewiring_result = redirection->apply();
  304. if (rewiring_result.is_error()) {
  305. if (!rewiring_result.error().is_empty())
  306. fprintf(stderr, "error: %s\n", rewiring_result.error().characters());
  307. continue;
  308. }
  309. auto& rewiring = rewiring_result.value();
  310. rewirings.append(rewiring);
  311. if (rewiring.must_be_closed == AST::Rewiring::Close::Source) {
  312. fds.add(rewiring.source_fd);
  313. } else if (rewiring.must_be_closed == AST::Rewiring::Close::Destination) {
  314. fds.add(rewiring.dest_fd);
  315. }
  316. }
  317. // If the command is empty, do all the rewirings in the current process and return.
  318. // This allows the user to mess with the shell internals, but is apparently useful?
  319. // We'll just allow the users to shoot themselves until they get tired of doing so.
  320. if (command.argv.is_empty()) {
  321. for (auto& rewiring : rewirings) {
  322. #ifdef SH_DEBUG
  323. dbgprintf("in %d, dup2(%d, %d)\n", getpid(), rewiring.dest_fd, rewiring.source_fd);
  324. #endif
  325. int rc = dup2(rewiring.dest_fd, rewiring.source_fd);
  326. if (rc < 0) {
  327. perror("dup2");
  328. return nullptr;
  329. }
  330. }
  331. fds.collect();
  332. return nullptr;
  333. }
  334. Vector<const char*> argv;
  335. Vector<String> copy_argv = command.argv;
  336. argv.ensure_capacity(command.argv.size() + 1);
  337. for (auto& arg : copy_argv)
  338. argv.append(arg.characters());
  339. argv.append(nullptr);
  340. int retval = 0;
  341. if (run_builtin(argv.size() - 1, argv.data(), retval))
  342. return nullptr;
  343. pid_t child = fork();
  344. if (!child) {
  345. setpgid(0, 0);
  346. tcsetpgrp(0, getpid());
  347. tcsetattr(0, TCSANOW, &default_termios);
  348. for (auto& rewiring : rewirings) {
  349. #ifdef SH_DEBUG
  350. dbgprintf("in %s<%d>, dup2(%d, %d)\n", argv[0], getpid(), rewiring.dest_fd, rewiring.source_fd);
  351. #endif
  352. int rc = dup2(rewiring.dest_fd, rewiring.source_fd);
  353. if (rc < 0) {
  354. perror("dup2");
  355. return nullptr;
  356. }
  357. }
  358. fds.collect();
  359. int rc = execvp(argv[0], const_cast<char* const*>(argv.data()));
  360. if (rc < 0) {
  361. if (errno == ENOENT) {
  362. int shebang_fd = open(argv[0], O_RDONLY);
  363. auto close_argv = ScopeGuard([shebang_fd]() { if (shebang_fd >= 0) close(shebang_fd); });
  364. char shebang[256] {};
  365. ssize_t num_read = -1;
  366. if ((shebang_fd >= 0) && ((num_read = read(shebang_fd, shebang, sizeof(shebang))) >= 2) && (StringView(shebang).starts_with("#!"))) {
  367. StringView shebang_path_view(&shebang[2], num_read - 2);
  368. Optional<size_t> newline_pos = shebang_path_view.find_first_of("\n\r");
  369. shebang[newline_pos.has_value() ? (newline_pos.value() + 2) : num_read] = '\0';
  370. fprintf(stderr, "%s: Invalid interpreter \"%s\": %s\n", argv[0], &shebang[2], strerror(ENOENT));
  371. } else
  372. fprintf(stderr, "%s: Command not found.\n", argv[0]);
  373. } else {
  374. int saved_errno = errno;
  375. struct stat st;
  376. if (stat(argv[0], &st) == 0 && S_ISDIR(st.st_mode)) {
  377. fprintf(stderr, "Shell: %s: Is a directory\n", argv[0]);
  378. _exit(126);
  379. }
  380. fprintf(stderr, "execvp(%s): %s\n", argv[0], strerror(saved_errno));
  381. }
  382. _exit(126);
  383. }
  384. ASSERT_NOT_REACHED();
  385. }
  386. StringBuilder cmd;
  387. cmd.join(" ", command.argv);
  388. auto job = adopt(*new Job(child, (unsigned)child, cmd.build(), find_last_job_id() + 1));
  389. jobs.set((u64)child, job);
  390. job->on_exit = [](auto job) {
  391. if (job->is_running_in_background())
  392. fprintf(stderr, "Shell: Job %d(%s) exited\n", job->pid(), job->cmd().characters());
  393. job->disown();
  394. };
  395. return *job;
  396. }
  397. bool Shell::run_file(const String& filename)
  398. {
  399. auto file_result = Core::File::open(filename, Core::File::ReadOnly);
  400. if (file_result.is_error()) {
  401. fprintf(stderr, "Failed to open %s: %s\n", filename.characters(), file_result.error().characters());
  402. return false;
  403. }
  404. auto file = file_result.value();
  405. for (;;) {
  406. auto line = file->read_line(4096);
  407. if (line.is_null())
  408. break;
  409. run_command(String::copy(line, Chomp));
  410. }
  411. return true;
  412. }
  413. void Shell::take_back_stdin()
  414. {
  415. tcsetpgrp(0, m_pid);
  416. tcsetattr(0, TCSANOW, &termios);
  417. }
  418. void Shell::block_on_job(RefPtr<Job> job)
  419. {
  420. if (!job)
  421. return;
  422. Core::EventLoop loop;
  423. job->on_exit = [&, old_exit = move(job->on_exit)](auto job) {
  424. if (old_exit)
  425. old_exit(job);
  426. loop.quit(0);
  427. };
  428. if (job->exited()) {
  429. take_back_stdin();
  430. return;
  431. }
  432. loop.exec();
  433. take_back_stdin();
  434. }
  435. String Shell::get_history_path()
  436. {
  437. StringBuilder builder;
  438. builder.append(home);
  439. builder.append("/.history");
  440. return builder.to_string();
  441. }
  442. void Shell::load_history()
  443. {
  444. auto history_file = Core::File::construct(get_history_path());
  445. if (!history_file->open(Core::IODevice::ReadOnly))
  446. return;
  447. while (history_file->can_read_line()) {
  448. auto b = history_file->read_line(1024);
  449. // skip the newline and terminating bytes
  450. editor->add_to_history(String(reinterpret_cast<const char*>(b.data()), b.size() - 2));
  451. }
  452. }
  453. void Shell::save_history()
  454. {
  455. auto file_or_error = Core::File::open(get_history_path(), Core::IODevice::WriteOnly, 0600);
  456. if (file_or_error.is_error())
  457. return;
  458. auto& file = *file_or_error.value();
  459. for (const auto& line : editor->history()) {
  460. file.write(line);
  461. file.write("\n");
  462. }
  463. }
  464. String Shell::escape_token(const String& token)
  465. {
  466. StringBuilder builder;
  467. for (auto c : token) {
  468. switch (c) {
  469. case '\'':
  470. case '"':
  471. case '$':
  472. case '|':
  473. case '>':
  474. case '<':
  475. case '&':
  476. case '\\':
  477. case ' ':
  478. builder.append('\\');
  479. break;
  480. default:
  481. break;
  482. }
  483. builder.append(c);
  484. }
  485. return builder.build();
  486. }
  487. String Shell::unescape_token(const String& token)
  488. {
  489. StringBuilder builder;
  490. enum {
  491. Free,
  492. Escaped
  493. } state { Free };
  494. for (auto c : token) {
  495. switch (state) {
  496. case Escaped:
  497. builder.append(c);
  498. state = Free;
  499. break;
  500. case Free:
  501. if (c == '\\')
  502. state = Escaped;
  503. else
  504. builder.append(c);
  505. break;
  506. }
  507. }
  508. if (state == Escaped)
  509. builder.append('\\');
  510. return builder.build();
  511. }
  512. void Shell::cache_path()
  513. {
  514. if (!cached_path.is_empty())
  515. cached_path.clear_with_capacity();
  516. String path = getenv("PATH");
  517. if (path.is_empty())
  518. return;
  519. auto directories = path.split(':');
  520. for (const auto& directory : directories) {
  521. Core::DirIterator programs(directory.characters(), Core::DirIterator::SkipDots);
  522. while (programs.has_next()) {
  523. auto program = programs.next_path();
  524. String program_path = String::format("%s/%s", directory.characters(), program.characters());
  525. auto escaped_name = escape_token(program);
  526. if (cached_path.contains_slow(escaped_name))
  527. continue;
  528. if (access(program_path.characters(), X_OK) == 0)
  529. cached_path.append(escaped_name);
  530. }
  531. }
  532. // add shell builtins to the cache
  533. for (const auto& builtin_name : builtin_names)
  534. cached_path.append(escape_token(builtin_name));
  535. quick_sort(cached_path);
  536. }
  537. void Shell::highlight(Line::Editor& editor) const
  538. {
  539. auto line = editor.line();
  540. Parser parser(line);
  541. auto ast = parser.parse();
  542. if (!ast)
  543. return;
  544. ast->highlight_in_editor(editor, const_cast<Shell&>(*this));
  545. }
  546. Vector<Line::CompletionSuggestion> Shell::complete(const Line::Editor& editor)
  547. {
  548. auto line = editor.line(editor.cursor());
  549. Parser parser(line);
  550. auto ast = parser.parse();
  551. if (!ast)
  552. return {};
  553. return ast->complete_for_editor(*this, line.length());
  554. }
  555. Vector<Line::CompletionSuggestion> Shell::complete_path(const String& part, size_t offset)
  556. {
  557. auto token = part.substring_view(0, offset);
  558. StringView original_token = token;
  559. String path;
  560. ssize_t last_slash = token.length() - 1;
  561. while (last_slash >= 0 && token[last_slash] != '/')
  562. --last_slash;
  563. if (last_slash >= 0) {
  564. // Split on the last slash. We'll use the first part as the directory
  565. // to search and the second part as the token to complete.
  566. path = token.substring_view(0, last_slash + 1);
  567. if (path[0] != '/')
  568. path = String::format("%s/%s", cwd.characters(), path.characters());
  569. path = LexicalPath::canonicalized_path(path);
  570. token = token.substring_view(last_slash + 1, token.length() - last_slash - 1);
  571. } else {
  572. // We have no slashes, so the directory to search is the current
  573. // directory and the token to complete is just the original token.
  574. path = cwd;
  575. }
  576. // the invariant part of the token is actually just the last segment
  577. // e. in `cd /foo/bar', 'bar' is the invariant
  578. // since we are not suggesting anything starting with
  579. // `/foo/', but rather just `bar...'
  580. auto token_length = escape_token(token).length();
  581. editor->suggest(token_length, original_token.length() - token_length);
  582. // only suggest dot-files if path starts with a dot
  583. Core::DirIterator files(path,
  584. token.starts_with('.') ? Core::DirIterator::SkipParentAndBaseDir : Core::DirIterator::SkipDots);
  585. Vector<Line::CompletionSuggestion> suggestions;
  586. while (files.has_next()) {
  587. auto file = files.next_path();
  588. if (file.starts_with(token)) {
  589. struct stat program_status;
  590. String file_path = String::format("%s/%s", path.characters(), file.characters());
  591. int stat_error = stat(file_path.characters(), &program_status);
  592. if (!stat_error) {
  593. if (S_ISDIR(program_status.st_mode)) {
  594. suggestions.append({ escape_token(file), "/" });
  595. } else {
  596. suggestions.append({ escape_token(file), " " });
  597. }
  598. }
  599. }
  600. }
  601. return suggestions;
  602. }
  603. Vector<Line::CompletionSuggestion> Shell::complete_program_name(const String& name, size_t offset)
  604. {
  605. auto match = binary_search(cached_path.data(), cached_path.size(), name, [](const String& name, const String& program) -> int {
  606. return strncmp(name.characters(), program.characters(), name.length());
  607. });
  608. if (!match)
  609. return complete_path(name, offset);
  610. String completion = *match;
  611. editor->suggest(escape_token(name).length(), 0);
  612. // Now that we have a program name starting with our token, we look at
  613. // other program names starting with our token and cut off any mismatching
  614. // characters.
  615. Vector<Line::CompletionSuggestion> suggestions;
  616. int index = match - cached_path.data();
  617. for (int i = index - 1; i >= 0 && cached_path[i].starts_with(name); --i) {
  618. suggestions.append({ cached_path[i], " " });
  619. }
  620. for (size_t i = index + 1; i < cached_path.size() && cached_path[i].starts_with(name); ++i) {
  621. suggestions.append({ cached_path[i], " " });
  622. }
  623. suggestions.append({ cached_path[index], " " });
  624. return suggestions;
  625. }
  626. Vector<Line::CompletionSuggestion> Shell::complete_variable(const String& name, size_t offset)
  627. {
  628. Vector<Line::CompletionSuggestion> suggestions;
  629. auto pattern = name.substring_view(0, offset);
  630. editor->suggest(offset);
  631. // Look at local variables.
  632. for (auto& variable : m_local_variables) {
  633. if (variable.key.starts_with(pattern))
  634. suggestions.append(variable.key);
  635. }
  636. // Look at the environment.
  637. for (auto i = 0; environ[i]; ++i) {
  638. auto entry = StringView { environ[i] };
  639. if (entry.starts_with(pattern)) {
  640. auto parts = entry.split_view('=');
  641. if (parts.is_empty() || parts.first().is_empty())
  642. continue;
  643. String name = parts.first();
  644. if (suggestions.contains_slow(name))
  645. continue;
  646. suggestions.append(move(name));
  647. }
  648. }
  649. return suggestions;
  650. }
  651. bool Shell::read_single_line()
  652. {
  653. take_back_stdin();
  654. auto line_result = editor->get_line(prompt());
  655. if (line_result.is_error()) {
  656. if (line_result.error() == Line::Editor::Error::Eof || line_result.error() == Line::Editor::Error::Empty) {
  657. // Pretend the user tried to execute builtin_exit()
  658. m_complete_line_builder.clear();
  659. run_command("exit");
  660. return read_single_line();
  661. } else {
  662. m_complete_line_builder.clear();
  663. Core::EventLoop::current().quit(1);
  664. return false;
  665. }
  666. }
  667. auto& line = line_result.value();
  668. if (line.is_empty())
  669. return true;
  670. if (!m_complete_line_builder.is_empty())
  671. m_complete_line_builder.append("\n");
  672. m_complete_line_builder.append(line);
  673. run_command(m_complete_line_builder.string_view());
  674. editor->add_to_history(m_complete_line_builder.build());
  675. m_complete_line_builder.clear();
  676. return true;
  677. }
  678. void Shell::custom_event(Core::CustomEvent& event)
  679. {
  680. if (event.custom_type() == ReadLine) {
  681. if (read_single_line())
  682. Core::EventLoop::current().post_event(*this, make<Core::CustomEvent>(ShellEventType::ReadLine));
  683. return;
  684. }
  685. event.ignore();
  686. }
  687. Shell::Shell()
  688. {
  689. uid = getuid();
  690. tcsetpgrp(0, getpgrp());
  691. m_pid = getpid();
  692. int rc = gethostname(hostname, Shell::HostNameSize);
  693. if (rc < 0)
  694. perror("gethostname");
  695. rc = ttyname_r(0, ttyname, Shell::TTYNameSize);
  696. if (rc < 0)
  697. perror("ttyname_r");
  698. {
  699. auto* cwd = getcwd(nullptr, 0);
  700. this->cwd = cwd;
  701. setenv("PWD", cwd, 1);
  702. free(cwd);
  703. }
  704. {
  705. auto* pw = getpwuid(getuid());
  706. if (pw) {
  707. username = pw->pw_name;
  708. home = pw->pw_dir;
  709. setenv("HOME", pw->pw_dir, 1);
  710. }
  711. endpwent();
  712. }
  713. directory_stack.append(cwd);
  714. load_history();
  715. cache_path();
  716. }
  717. Shell::~Shell()
  718. {
  719. stop_all_jobs();
  720. save_history();
  721. }
  722. void Shell::stop_all_jobs()
  723. {
  724. if (!jobs.is_empty()) {
  725. printf("Killing active jobs\n");
  726. for (auto& entry : jobs) {
  727. if (!entry.value->is_running_in_background()) {
  728. #ifdef SH_DEBUG
  729. dbg() << "Job " << entry.value->pid() << " is not running in background";
  730. #endif
  731. if (killpg(entry.value->pgid(), SIGCONT) < 0) {
  732. perror("killpg(CONT)");
  733. }
  734. }
  735. if (killpg(entry.value->pgid(), SIGHUP) < 0) {
  736. perror("killpg(HUP)");
  737. }
  738. if (killpg(entry.value->pgid(), SIGTERM) < 0) {
  739. perror("killpg(TERM)");
  740. }
  741. }
  742. usleep(10000); // Wait for a bit before killing the job
  743. for (auto& entry : jobs) {
  744. #ifdef SH_DEBUG
  745. dbg() << "Actively killing " << entry.value->pid() << "(" << entry.value->cmd() << ")";
  746. #endif
  747. if (killpg(entry.value->pgid(), SIGKILL) < 0) {
  748. if (errno == ESRCH)
  749. continue; // The process has exited all by itself.
  750. perror("killpg(KILL)");
  751. }
  752. }
  753. }
  754. }
  755. u64 Shell::find_last_job_id() const
  756. {
  757. u64 job_id = 0;
  758. for (auto& entry : jobs) {
  759. if (entry.value->job_id() > job_id)
  760. job_id = entry.value->job_id();
  761. }
  762. return job_id;
  763. }
  764. const Job* Shell::find_job(u64 id)
  765. {
  766. for (auto& entry : jobs) {
  767. if (entry.value->job_id() == id)
  768. return entry.value;
  769. }
  770. return nullptr;
  771. }
  772. void Shell::save_to(JsonObject& object)
  773. {
  774. Core::Object::save_to(object);
  775. object.set("working_directory", cwd);
  776. object.set("username", username);
  777. object.set("user_home_path", home);
  778. object.set("user_id", uid);
  779. object.set("directory_stack_size", directory_stack.size());
  780. object.set("cd_history_size", cd_history.size());
  781. // Jobs.
  782. JsonArray job_objects;
  783. for (auto& job_entry : jobs) {
  784. JsonObject job_object;
  785. job_object.set("pid", job_entry.value->pid());
  786. job_object.set("pgid", job_entry.value->pgid());
  787. job_object.set("running_time", job_entry.value->timer().elapsed());
  788. job_object.set("command", job_entry.value->cmd());
  789. job_object.set("is_running_in_background", job_entry.value->is_running_in_background());
  790. job_objects.append(move(job_object));
  791. }
  792. object.set("jobs", move(job_objects));
  793. }