Shell.cpp 31 KB

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