Shell.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986
  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. if (command->is_syntax_error()) {
  282. // FIXME: Provide descriptive messages for syntax errors.
  283. fprintf(stderr, "Shell: Syntax error in command\n");
  284. return 1;
  285. }
  286. #ifdef SH_DEBUG
  287. dbg() << "Command follows";
  288. command->dump(0);
  289. #endif
  290. tcgetattr(0, &termios);
  291. auto result = command->run(*this);
  292. if (result->is_job()) {
  293. auto job_result = static_cast<AST::JobValue*>(result.ptr());
  294. auto job = job_result->job();
  295. if (!job)
  296. last_return_code = 0;
  297. else if (job->exited())
  298. last_return_code = job->exit_code();
  299. }
  300. return last_return_code;
  301. }
  302. RefPtr<Job> Shell::run_command(AST::Command& command)
  303. {
  304. FileDescriptionCollector fds;
  305. // Resolve redirections.
  306. NonnullRefPtrVector<AST::Rewiring> rewirings;
  307. for (auto& redirection : command.redirections) {
  308. auto rewiring_result = redirection->apply();
  309. if (rewiring_result.is_error()) {
  310. if (!rewiring_result.error().is_empty())
  311. fprintf(stderr, "error: %s\n", rewiring_result.error().characters());
  312. continue;
  313. }
  314. auto& rewiring = rewiring_result.value();
  315. if (rewiring->fd_action != AST::Rewiring::Close::ImmediatelyCloseDestination)
  316. rewirings.append(*rewiring);
  317. if (rewiring->fd_action == AST::Rewiring::Close::Source) {
  318. fds.add(rewiring->source_fd);
  319. } else if (rewiring->fd_action == AST::Rewiring::Close::Destination) {
  320. if (rewiring->dest_fd != -1)
  321. fds.add(rewiring->dest_fd);
  322. } else if (rewiring->fd_action == AST::Rewiring::Close::ImmediatelyCloseDestination) {
  323. fds.add(rewiring->dest_fd);
  324. } else if (rewiring->fd_action == AST::Rewiring::Close::RefreshDestination) {
  325. ASSERT(rewiring->other_pipe_end);
  326. int pipe_fd[2];
  327. int rc = pipe(pipe_fd);
  328. if (rc < 0) {
  329. perror("pipe(RedirRefresh)");
  330. return nullptr;
  331. }
  332. rewiring->dest_fd = pipe_fd[1];
  333. rewiring->other_pipe_end->dest_fd = pipe_fd[0]; // This fd will be added to the collection on one of the next iterations.
  334. fds.add(pipe_fd[1]);
  335. }
  336. }
  337. // If the command is empty, do all the rewirings in the current process and return.
  338. // This allows the user to mess with the shell internals, but is apparently useful?
  339. // We'll just allow the users to shoot themselves until they get tired of doing so.
  340. if (command.argv.is_empty()) {
  341. for (auto& rewiring : rewirings) {
  342. #ifdef SH_DEBUG
  343. dbgprintf("in %d, dup2(%d, %d)\n", getpid(), rewiring.dest_fd, rewiring.source_fd);
  344. #endif
  345. int rc = dup2(rewiring.dest_fd, rewiring.source_fd);
  346. if (rc < 0) {
  347. perror("dup2(run)");
  348. return nullptr;
  349. }
  350. }
  351. fds.collect();
  352. return nullptr;
  353. }
  354. Vector<const char*> argv;
  355. Vector<String> copy_argv = command.argv;
  356. argv.ensure_capacity(command.argv.size() + 1);
  357. for (auto& arg : copy_argv)
  358. argv.append(arg.characters());
  359. argv.append(nullptr);
  360. int retval = 0;
  361. if (run_builtin(argv.size() - 1, argv.data(), retval))
  362. return nullptr;
  363. pid_t child = fork();
  364. if (child < 0) {
  365. perror("fork");
  366. return nullptr;
  367. }
  368. if (child == 0) {
  369. setpgid(0, 0);
  370. tcsetpgrp(0, getpid());
  371. tcsetattr(0, TCSANOW, &default_termios);
  372. for (auto& rewiring : rewirings) {
  373. #ifdef SH_DEBUG
  374. dbgprintf("in %s<%d>, dup2(%d, %d)\n", argv[0], getpid(), rewiring.dest_fd, rewiring.source_fd);
  375. #endif
  376. int rc = dup2(rewiring.dest_fd, rewiring.source_fd);
  377. if (rc < 0) {
  378. perror("dup2(run)");
  379. return nullptr;
  380. }
  381. }
  382. fds.collect();
  383. int rc = execvp(argv[0], const_cast<char* const*>(argv.data()));
  384. if (rc < 0) {
  385. if (errno == ENOENT) {
  386. int shebang_fd = open(argv[0], O_RDONLY);
  387. auto close_argv = ScopeGuard([shebang_fd]() { if (shebang_fd >= 0) close(shebang_fd); });
  388. char shebang[256] {};
  389. ssize_t num_read = -1;
  390. if ((shebang_fd >= 0) && ((num_read = read(shebang_fd, shebang, sizeof(shebang))) >= 2) && (StringView(shebang).starts_with("#!"))) {
  391. StringView shebang_path_view(&shebang[2], num_read - 2);
  392. Optional<size_t> newline_pos = shebang_path_view.find_first_of("\n\r");
  393. shebang[newline_pos.has_value() ? (newline_pos.value() + 2) : num_read] = '\0';
  394. fprintf(stderr, "%s: Invalid interpreter \"%s\": %s\n", argv[0], &shebang[2], strerror(ENOENT));
  395. } else
  396. fprintf(stderr, "%s: Command not found.\n", argv[0]);
  397. } else {
  398. int saved_errno = errno;
  399. struct stat st;
  400. if (stat(argv[0], &st) == 0 && S_ISDIR(st.st_mode)) {
  401. fprintf(stderr, "Shell: %s: Is a directory\n", argv[0]);
  402. _exit(126);
  403. }
  404. fprintf(stderr, "execvp(%s): %s\n", argv[0], strerror(saved_errno));
  405. }
  406. _exit(126);
  407. }
  408. ASSERT_NOT_REACHED();
  409. }
  410. StringBuilder cmd;
  411. cmd.join(" ", command.argv);
  412. auto job = adopt(*new Job(child, (unsigned)child, cmd.build(), find_last_job_id() + 1));
  413. jobs.set((u64)child, job);
  414. job->on_exit = [](auto job) {
  415. if (job->is_running_in_background())
  416. fprintf(stderr, "Shell: Job %d(%s) exited\n", job->pid(), job->cmd().characters());
  417. job->disown();
  418. };
  419. fds.collect();
  420. return *job;
  421. }
  422. bool Shell::run_file(const String& filename)
  423. {
  424. auto file_result = Core::File::open(filename, Core::File::ReadOnly);
  425. if (file_result.is_error()) {
  426. fprintf(stderr, "Failed to open %s: %s\n", filename.characters(), file_result.error().characters());
  427. return false;
  428. }
  429. auto file = file_result.value();
  430. auto data = file->read_all();
  431. run_command(data);
  432. return true;
  433. }
  434. void Shell::take_back_stdin()
  435. {
  436. tcsetpgrp(0, m_pid);
  437. tcsetattr(0, TCSANOW, &termios);
  438. }
  439. void Shell::block_on_job(RefPtr<Job> job)
  440. {
  441. if (!job)
  442. return;
  443. Core::EventLoop loop;
  444. job->on_exit = [&, old_exit = move(job->on_exit)](auto job) {
  445. if (old_exit)
  446. old_exit(job);
  447. loop.quit(0);
  448. };
  449. if (job->exited()) {
  450. take_back_stdin();
  451. return;
  452. }
  453. loop.exec();
  454. take_back_stdin();
  455. }
  456. String Shell::get_history_path()
  457. {
  458. StringBuilder builder;
  459. builder.append(home);
  460. builder.append("/.history");
  461. return builder.to_string();
  462. }
  463. void Shell::load_history()
  464. {
  465. auto history_file = Core::File::construct(get_history_path());
  466. if (!history_file->open(Core::IODevice::ReadOnly))
  467. return;
  468. while (history_file->can_read_line()) {
  469. auto b = history_file->read_line(1024);
  470. // skip the newline and terminating bytes
  471. editor->add_to_history(String(reinterpret_cast<const char*>(b.data()), b.size() - 2));
  472. }
  473. }
  474. void Shell::save_history()
  475. {
  476. auto file_or_error = Core::File::open(get_history_path(), Core::IODevice::WriteOnly, 0600);
  477. if (file_or_error.is_error())
  478. return;
  479. auto& file = *file_or_error.value();
  480. for (const auto& line : editor->history()) {
  481. file.write(line);
  482. file.write("\n");
  483. }
  484. }
  485. String Shell::escape_token(const String& token)
  486. {
  487. StringBuilder builder;
  488. for (auto c : token) {
  489. switch (c) {
  490. case '\'':
  491. case '"':
  492. case '$':
  493. case '|':
  494. case '>':
  495. case '<':
  496. case '&':
  497. case '\\':
  498. case ' ':
  499. builder.append('\\');
  500. break;
  501. default:
  502. break;
  503. }
  504. builder.append(c);
  505. }
  506. return builder.build();
  507. }
  508. String Shell::unescape_token(const String& token)
  509. {
  510. StringBuilder builder;
  511. enum {
  512. Free,
  513. Escaped
  514. } state { Free };
  515. for (auto c : token) {
  516. switch (state) {
  517. case Escaped:
  518. builder.append(c);
  519. state = Free;
  520. break;
  521. case Free:
  522. if (c == '\\')
  523. state = Escaped;
  524. else
  525. builder.append(c);
  526. break;
  527. }
  528. }
  529. if (state == Escaped)
  530. builder.append('\\');
  531. return builder.build();
  532. }
  533. void Shell::cache_path()
  534. {
  535. if (!cached_path.is_empty())
  536. cached_path.clear_with_capacity();
  537. String path = getenv("PATH");
  538. if (path.is_empty())
  539. return;
  540. auto directories = path.split(':');
  541. for (const auto& directory : directories) {
  542. Core::DirIterator programs(directory.characters(), Core::DirIterator::SkipDots);
  543. while (programs.has_next()) {
  544. auto program = programs.next_path();
  545. String program_path = String::format("%s/%s", directory.characters(), program.characters());
  546. auto escaped_name = escape_token(program);
  547. if (cached_path.contains_slow(escaped_name))
  548. continue;
  549. if (access(program_path.characters(), X_OK) == 0)
  550. cached_path.append(escaped_name);
  551. }
  552. }
  553. // add shell builtins to the cache
  554. for (const auto& builtin_name : builtin_names)
  555. cached_path.append(escape_token(builtin_name));
  556. quick_sort(cached_path);
  557. }
  558. void Shell::highlight(Line::Editor& editor) const
  559. {
  560. auto line = editor.line();
  561. Parser parser(line);
  562. auto ast = parser.parse();
  563. if (!ast)
  564. return;
  565. ast->highlight_in_editor(editor, const_cast<Shell&>(*this));
  566. }
  567. Vector<Line::CompletionSuggestion> Shell::complete(const Line::Editor& editor)
  568. {
  569. auto line = editor.line(editor.cursor());
  570. Parser parser(line);
  571. auto ast = parser.parse();
  572. if (!ast)
  573. return {};
  574. return ast->complete_for_editor(*this, line.length());
  575. }
  576. Vector<Line::CompletionSuggestion> Shell::complete_path(const String& base, const String& part, size_t offset)
  577. {
  578. auto token = offset ? part.substring_view(0, offset) : "";
  579. StringView original_token = token;
  580. String path;
  581. ssize_t last_slash = token.length() - 1;
  582. while (last_slash >= 0 && token[last_slash] != '/')
  583. --last_slash;
  584. StringBuilder path_builder;
  585. auto init_slash_part = token.substring_view(0, last_slash + 1);
  586. auto last_slash_part = token.substring_view(last_slash + 1, token.length() - last_slash - 1);
  587. // Depending on the base, we will have to prepend cwd.
  588. if (base.is_empty()) {
  589. // '' /foo -> absolute
  590. // '' foo -> relative
  591. if (!token.starts_with('/'))
  592. path_builder.append(cwd);
  593. path_builder.append('/');
  594. path_builder.append(init_slash_part);
  595. } else {
  596. // /foo * -> absolute
  597. // foo * -> relative
  598. if (!base.starts_with('/'))
  599. path_builder.append(cwd);
  600. path_builder.append('/');
  601. path_builder.append(base);
  602. path_builder.append('/');
  603. path_builder.append(init_slash_part);
  604. }
  605. path = path_builder.build();
  606. token = last_slash_part;
  607. // the invariant part of the token is actually just the last segment
  608. // e. in `cd /foo/bar', 'bar' is the invariant
  609. // since we are not suggesting anything starting with
  610. // `/foo/', but rather just `bar...'
  611. auto token_length = escape_token(token).length();
  612. editor->suggest(token_length, original_token.length() - token_length);
  613. // only suggest dot-files if path starts with a dot
  614. Core::DirIterator files(path,
  615. token.starts_with('.') ? Core::DirIterator::SkipParentAndBaseDir : Core::DirIterator::SkipDots);
  616. Vector<Line::CompletionSuggestion> suggestions;
  617. while (files.has_next()) {
  618. auto file = files.next_path();
  619. if (file.starts_with(token)) {
  620. struct stat program_status;
  621. String file_path = String::format("%s/%s", path.characters(), file.characters());
  622. int stat_error = stat(file_path.characters(), &program_status);
  623. if (!stat_error) {
  624. if (S_ISDIR(program_status.st_mode)) {
  625. suggestions.append({ escape_token(file), "/" });
  626. } else {
  627. suggestions.append({ escape_token(file), " " });
  628. }
  629. }
  630. }
  631. }
  632. return suggestions;
  633. }
  634. Vector<Line::CompletionSuggestion> Shell::complete_program_name(const String& name, size_t offset)
  635. {
  636. auto match = binary_search(cached_path.data(), cached_path.size(), name, [](const String& name, const String& program) -> int {
  637. return strncmp(name.characters(), program.characters(), name.length());
  638. });
  639. if (!match)
  640. return complete_path("", name, offset);
  641. String completion = *match;
  642. editor->suggest(escape_token(name).length(), 0);
  643. // Now that we have a program name starting with our token, we look at
  644. // other program names starting with our token and cut off any mismatching
  645. // characters.
  646. Vector<Line::CompletionSuggestion> suggestions;
  647. int index = match - cached_path.data();
  648. for (int i = index - 1; i >= 0 && cached_path[i].starts_with(name); --i) {
  649. suggestions.append({ cached_path[i], " " });
  650. }
  651. for (size_t i = index + 1; i < cached_path.size() && cached_path[i].starts_with(name); ++i) {
  652. suggestions.append({ cached_path[i], " " });
  653. }
  654. suggestions.append({ cached_path[index], " " });
  655. return suggestions;
  656. }
  657. Vector<Line::CompletionSuggestion> Shell::complete_variable(const String& name, size_t offset)
  658. {
  659. Vector<Line::CompletionSuggestion> suggestions;
  660. auto pattern = offset ? name.substring_view(0, offset) : "";
  661. editor->suggest(offset);
  662. // Look at local variables.
  663. for (auto& variable : m_local_variables) {
  664. if (variable.key.starts_with(pattern))
  665. suggestions.append(variable.key);
  666. }
  667. // Look at the environment.
  668. for (auto i = 0; environ[i]; ++i) {
  669. auto entry = StringView { environ[i] };
  670. if (entry.starts_with(pattern)) {
  671. auto parts = entry.split_view('=');
  672. if (parts.is_empty() || parts.first().is_empty())
  673. continue;
  674. String name = parts.first();
  675. if (suggestions.contains_slow(name))
  676. continue;
  677. suggestions.append(move(name));
  678. }
  679. }
  680. return suggestions;
  681. }
  682. Vector<Line::CompletionSuggestion> Shell::complete_user(const String& name, size_t offset)
  683. {
  684. Vector<Line::CompletionSuggestion> suggestions;
  685. auto pattern = offset ? name.substring_view(0, offset) : "";
  686. editor->suggest(offset);
  687. Core::DirIterator di("/home", Core::DirIterator::SkipParentAndBaseDir);
  688. if (di.has_error())
  689. return suggestions;
  690. while (di.has_next()) {
  691. String name = di.next_path();
  692. if (name.starts_with(pattern))
  693. suggestions.append(name);
  694. }
  695. return suggestions;
  696. }
  697. bool Shell::read_single_line()
  698. {
  699. take_back_stdin();
  700. auto line_result = editor->get_line(prompt());
  701. if (line_result.is_error()) {
  702. if (line_result.error() == Line::Editor::Error::Eof || line_result.error() == Line::Editor::Error::Empty) {
  703. // Pretend the user tried to execute builtin_exit()
  704. m_complete_line_builder.clear();
  705. run_command("exit");
  706. return read_single_line();
  707. } else {
  708. m_complete_line_builder.clear();
  709. Core::EventLoop::current().quit(1);
  710. return false;
  711. }
  712. }
  713. auto& line = line_result.value();
  714. if (line.is_empty())
  715. return true;
  716. if (!m_complete_line_builder.is_empty())
  717. m_complete_line_builder.append("\n");
  718. m_complete_line_builder.append(line);
  719. run_command(m_complete_line_builder.string_view());
  720. editor->add_to_history(m_complete_line_builder.build());
  721. m_complete_line_builder.clear();
  722. return true;
  723. }
  724. void Shell::custom_event(Core::CustomEvent& event)
  725. {
  726. if (event.custom_type() == ReadLine) {
  727. if (read_single_line())
  728. Core::EventLoop::current().post_event(*this, make<Core::CustomEvent>(ShellEventType::ReadLine));
  729. return;
  730. }
  731. event.ignore();
  732. }
  733. Shell::Shell()
  734. {
  735. uid = getuid();
  736. tcsetpgrp(0, getpgrp());
  737. m_pid = getpid();
  738. int rc = gethostname(hostname, Shell::HostNameSize);
  739. if (rc < 0)
  740. perror("gethostname");
  741. rc = ttyname_r(0, ttyname, Shell::TTYNameSize);
  742. if (rc < 0)
  743. perror("ttyname_r");
  744. {
  745. auto* cwd = getcwd(nullptr, 0);
  746. this->cwd = cwd;
  747. setenv("PWD", cwd, 1);
  748. free(cwd);
  749. }
  750. {
  751. auto* pw = getpwuid(getuid());
  752. if (pw) {
  753. username = pw->pw_name;
  754. home = pw->pw_dir;
  755. setenv("HOME", pw->pw_dir, 1);
  756. }
  757. endpwent();
  758. }
  759. directory_stack.append(cwd);
  760. load_history();
  761. cache_path();
  762. }
  763. Shell::~Shell()
  764. {
  765. stop_all_jobs();
  766. save_history();
  767. }
  768. void Shell::stop_all_jobs()
  769. {
  770. if (!jobs.is_empty()) {
  771. printf("Killing active jobs\n");
  772. for (auto& entry : jobs) {
  773. if (!entry.value->is_running_in_background()) {
  774. #ifdef SH_DEBUG
  775. dbg() << "Job " << entry.value->pid() << " is not running in background";
  776. #endif
  777. if (killpg(entry.value->pgid(), SIGCONT) < 0) {
  778. perror("killpg(CONT)");
  779. }
  780. }
  781. if (killpg(entry.value->pgid(), SIGHUP) < 0) {
  782. perror("killpg(HUP)");
  783. }
  784. if (killpg(entry.value->pgid(), SIGTERM) < 0) {
  785. perror("killpg(TERM)");
  786. }
  787. }
  788. usleep(10000); // Wait for a bit before killing the job
  789. for (auto& entry : jobs) {
  790. #ifdef SH_DEBUG
  791. dbg() << "Actively killing " << entry.value->pid() << "(" << entry.value->cmd() << ")";
  792. #endif
  793. if (killpg(entry.value->pgid(), SIGKILL) < 0) {
  794. if (errno == ESRCH)
  795. continue; // The process has exited all by itself.
  796. perror("killpg(KILL)");
  797. }
  798. }
  799. }
  800. }
  801. u64 Shell::find_last_job_id() const
  802. {
  803. u64 job_id = 0;
  804. for (auto& entry : jobs) {
  805. if (entry.value->job_id() > job_id)
  806. job_id = entry.value->job_id();
  807. }
  808. return job_id;
  809. }
  810. const Job* Shell::find_job(u64 id)
  811. {
  812. for (auto& entry : jobs) {
  813. if (entry.value->job_id() == id)
  814. return entry.value;
  815. }
  816. return nullptr;
  817. }
  818. void Shell::save_to(JsonObject& object)
  819. {
  820. Core::Object::save_to(object);
  821. object.set("working_directory", cwd);
  822. object.set("username", username);
  823. object.set("user_home_path", home);
  824. object.set("user_id", uid);
  825. object.set("directory_stack_size", directory_stack.size());
  826. object.set("cd_history_size", cd_history.size());
  827. // Jobs.
  828. JsonArray job_objects;
  829. for (auto& job_entry : jobs) {
  830. JsonObject job_object;
  831. job_object.set("pid", job_entry.value->pid());
  832. job_object.set("pgid", job_entry.value->pgid());
  833. job_object.set("running_time", job_entry.value->timer().elapsed());
  834. job_object.set("command", job_entry.value->cmd());
  835. job_object.set("is_running_in_background", job_entry.value->is_running_in_background());
  836. job_objects.append(move(job_object));
  837. }
  838. object.set("jobs", move(job_objects));
  839. }