Shell.cpp 34 KB

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