Shell.cpp 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370
  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/Event.h>
  35. #include <LibCore/EventLoop.h>
  36. #include <LibCore/File.h>
  37. #include <LibLine/Editor.h>
  38. #include <errno.h>
  39. #include <fcntl.h>
  40. #include <inttypes.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. extern char** environ;
  54. //#define SH_DEBUG
  55. void Shell::print_path(const String& path)
  56. {
  57. if (s_disable_hyperlinks || !m_is_interactive) {
  58. printf("%s", path.characters());
  59. return;
  60. }
  61. printf("\033]8;;file://%s%s\033\\%s\033]8;;\033\\", hostname, path.characters(), path.characters());
  62. }
  63. String Shell::prompt() const
  64. {
  65. auto build_prompt = [&]() -> String {
  66. auto* ps1 = getenv("PROMPT");
  67. if (!ps1) {
  68. if (uid == 0)
  69. return "# ";
  70. StringBuilder builder;
  71. builder.appendf("\033]0;%s@%s:%s\007", username.characters(), hostname, cwd.characters());
  72. 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());
  73. return builder.to_string();
  74. }
  75. StringBuilder builder;
  76. for (char* ptr = ps1; *ptr; ++ptr) {
  77. if (*ptr == '\\') {
  78. ++ptr;
  79. if (!*ptr)
  80. break;
  81. switch (*ptr) {
  82. case 'X':
  83. builder.append("\033]0;");
  84. break;
  85. case 'a':
  86. builder.append(0x07);
  87. break;
  88. case 'e':
  89. builder.append(0x1b);
  90. break;
  91. case 'u':
  92. builder.append(username);
  93. break;
  94. case 'h':
  95. builder.append(hostname);
  96. break;
  97. case 'w': {
  98. String home_path = getenv("HOME");
  99. if (cwd.starts_with(home_path)) {
  100. builder.append('~');
  101. builder.append(cwd.substring_view(home_path.length(), cwd.length() - home_path.length()));
  102. } else {
  103. builder.append(cwd);
  104. }
  105. break;
  106. }
  107. case 'p':
  108. builder.append(uid == 0 ? '#' : '$');
  109. break;
  110. }
  111. continue;
  112. }
  113. builder.append(*ptr);
  114. }
  115. return builder.to_string();
  116. };
  117. return build_prompt();
  118. }
  119. String Shell::expand_tilde(const String& expression)
  120. {
  121. ASSERT(expression.starts_with('~'));
  122. StringBuilder login_name;
  123. size_t first_slash_index = expression.length();
  124. for (size_t i = 1; i < expression.length(); ++i) {
  125. if (expression[i] == '/') {
  126. first_slash_index = i;
  127. break;
  128. }
  129. login_name.append(expression[i]);
  130. }
  131. StringBuilder path;
  132. for (size_t i = first_slash_index; i < expression.length(); ++i)
  133. path.append(expression[i]);
  134. if (login_name.is_empty()) {
  135. const char* home = getenv("HOME");
  136. if (!home) {
  137. auto passwd = getpwuid(getuid());
  138. ASSERT(passwd && passwd->pw_dir);
  139. return String::format("%s/%s", passwd->pw_dir, path.to_string().characters());
  140. }
  141. return String::format("%s/%s", home, path.to_string().characters());
  142. }
  143. auto passwd = getpwnam(login_name.to_string().characters());
  144. if (!passwd)
  145. return expression;
  146. ASSERT(passwd->pw_dir);
  147. return String::format("%s/%s", passwd->pw_dir, path.to_string().characters());
  148. }
  149. bool Shell::is_glob(const StringView& s)
  150. {
  151. for (size_t i = 0; i < s.length(); i++) {
  152. char c = s.characters_without_null_termination()[i];
  153. if (c == '*' || c == '?')
  154. return true;
  155. }
  156. return false;
  157. }
  158. Vector<StringView> Shell::split_path(const StringView& path)
  159. {
  160. Vector<StringView> parts;
  161. size_t substart = 0;
  162. for (size_t i = 0; i < path.length(); i++) {
  163. char ch = path[i];
  164. if (ch != '/')
  165. continue;
  166. size_t sublen = i - substart;
  167. if (sublen != 0)
  168. parts.append(path.substring_view(substart, sublen));
  169. substart = i + 1;
  170. }
  171. size_t taillen = path.length() - substart;
  172. if (taillen != 0)
  173. parts.append(path.substring_view(substart, taillen));
  174. return parts;
  175. }
  176. Vector<String> Shell::expand_globs(const StringView& path, StringView base)
  177. {
  178. if (path.starts_with('/'))
  179. base = "/";
  180. auto parts = split_path(path);
  181. String base_string = base;
  182. struct stat statbuf;
  183. if (lstat(base_string.characters(), &statbuf) < 0) {
  184. perror("lstat");
  185. return {};
  186. }
  187. StringBuilder resolved_base_path_builder;
  188. resolved_base_path_builder.append(Core::File::real_path_for(base));
  189. if (S_ISDIR(statbuf.st_mode))
  190. resolved_base_path_builder.append('/');
  191. auto resolved_base = resolved_base_path_builder.string_view();
  192. auto results = expand_globs(move(parts), resolved_base);
  193. for (auto& entry : results) {
  194. entry = entry.substring(resolved_base.length(), entry.length() - resolved_base.length());
  195. if (entry.is_empty())
  196. entry = ".";
  197. }
  198. // Make the output predictable and nice.
  199. quick_sort(results);
  200. return results;
  201. }
  202. Vector<String> Shell::expand_globs(Vector<StringView> path_segments, const StringView& base)
  203. {
  204. if (path_segments.is_empty()) {
  205. String base_str = base;
  206. if (access(base_str.characters(), F_OK) == 0)
  207. return { move(base_str) };
  208. return {};
  209. }
  210. auto first_segment = path_segments.take_first();
  211. if (is_glob(first_segment)) {
  212. Vector<String> result;
  213. Core::DirIterator di(base, Core::DirIterator::SkipParentAndBaseDir);
  214. if (di.has_error())
  215. return {};
  216. while (di.has_next()) {
  217. String path = di.next_path();
  218. // Dotfiles have to be explicitly requested
  219. if (path[0] == '.' && first_segment[0] != '.')
  220. continue;
  221. if (path.matches(first_segment, CaseSensitivity::CaseSensitive)) {
  222. StringBuilder builder;
  223. builder.append(base);
  224. if (!base.ends_with('/'))
  225. builder.append('/');
  226. builder.append(path);
  227. result.append(expand_globs(path_segments, builder.string_view()));
  228. }
  229. }
  230. return result;
  231. } else {
  232. StringBuilder builder;
  233. builder.append(base);
  234. if (!base.ends_with('/'))
  235. builder.append('/');
  236. builder.append(first_segment);
  237. return expand_globs(move(path_segments), builder.string_view());
  238. }
  239. }
  240. Vector<AST::Command> Shell::expand_aliases(Vector<AST::Command> initial_commands)
  241. {
  242. Vector<AST::Command> commands;
  243. Function<void(AST::Command&)> resolve_aliases_and_append = [&](auto& command) {
  244. if (!command.argv.is_empty()) {
  245. auto alias = resolve_alias(command.argv[0]);
  246. if (!alias.is_null()) {
  247. auto argv0 = command.argv.take_first();
  248. auto subcommand_ast = Parser { alias }.parse();
  249. if (subcommand_ast) {
  250. while (subcommand_ast->is_execute()) {
  251. auto* ast = static_cast<AST::Execute*>(subcommand_ast.ptr());
  252. subcommand_ast = ast->command();
  253. }
  254. RefPtr<AST::Node> substitute = adopt(*new AST::Join(subcommand_ast->position(), subcommand_ast, adopt(*new AST::CommandLiteral(subcommand_ast->position(), command))));
  255. for (auto& subst_command : substitute->run(*this)->resolve_as_commands(*this)) {
  256. if (!subst_command.argv.is_empty() && subst_command.argv.first() == argv0) // Disallow an alias resolving to itself.
  257. commands.append(subst_command);
  258. else
  259. resolve_aliases_and_append(subst_command);
  260. }
  261. } else {
  262. commands.append(command);
  263. }
  264. } else {
  265. commands.append(command);
  266. }
  267. } else {
  268. commands.append(command);
  269. }
  270. };
  271. for (auto& command : initial_commands)
  272. resolve_aliases_and_append(command);
  273. return commands;
  274. }
  275. String Shell::resolve_path(String path) const
  276. {
  277. if (!path.starts_with('/'))
  278. path = String::format("%s/%s", cwd.characters(), path.characters());
  279. return Core::File::real_path_for(path);
  280. }
  281. Shell::LocalFrame* Shell::find_frame_containing_local_variable(const String& name)
  282. {
  283. for (auto& frame : m_local_frames) {
  284. if (frame.local_variables.contains(name))
  285. return &frame;
  286. }
  287. return nullptr;
  288. }
  289. RefPtr<AST::Value> Shell::lookup_local_variable(const String& name)
  290. {
  291. if (auto* frame = find_frame_containing_local_variable(name))
  292. return frame->local_variables.get(name).value();
  293. return nullptr;
  294. }
  295. String Shell::local_variable_or(const String& name, const String& replacement)
  296. {
  297. auto value = lookup_local_variable(name);
  298. if (value) {
  299. StringBuilder builder;
  300. builder.join(" ", value->resolve_as_list(*this));
  301. return builder.to_string();
  302. }
  303. return replacement;
  304. }
  305. void Shell::set_local_variable(const String& name, RefPtr<AST::Value> value)
  306. {
  307. if (auto* frame = find_frame_containing_local_variable(name))
  308. frame->local_variables.set(name, move(value));
  309. else
  310. m_local_frames.last().local_variables.set(name, move(value));
  311. }
  312. void Shell::unset_local_variable(const String& name)
  313. {
  314. if (auto* frame = find_frame_containing_local_variable(name))
  315. frame->local_variables.remove(name);
  316. }
  317. Shell::Frame Shell::push_frame()
  318. {
  319. m_local_frames.empend();
  320. return { m_local_frames, m_local_frames.last() };
  321. }
  322. void Shell::pop_frame()
  323. {
  324. ASSERT(m_local_frames.size() > 1);
  325. m_local_frames.take_last();
  326. }
  327. Shell::Frame::~Frame()
  328. {
  329. if (!should_destroy_frame)
  330. return;
  331. ASSERT(&frames.last() == &frame);
  332. frames.take_last();
  333. }
  334. String Shell::resolve_alias(const String& name) const
  335. {
  336. return m_aliases.get(name).value_or({});
  337. }
  338. bool Shell::is_runnable(const StringView& name)
  339. {
  340. if (access(name.to_string().characters(), X_OK) == 0)
  341. return true;
  342. return !!binary_search(cached_path.span(), name.to_string(), [](const String& name, const String& program) -> int {
  343. return strcmp(name.characters(), program.characters());
  344. });
  345. }
  346. int Shell::run_command(const StringView& cmd)
  347. {
  348. if (cmd.is_empty())
  349. return 0;
  350. auto command = Parser(cmd).parse();
  351. if (!command)
  352. return 0;
  353. #ifdef SH_DEBUG
  354. dbg() << "Command follows";
  355. command->dump(0);
  356. #endif
  357. if (command->is_syntax_error()) {
  358. auto& error_node = command->syntax_error_node();
  359. auto& position = error_node.position();
  360. fprintf(stderr, "Shell: Syntax error in command: %s\n", error_node.error_text().characters());
  361. fprintf(stderr, "Around '%.*s' at %zu:%zu\n", (int)min(position.end_offset - position.start_offset, (size_t)10), cmd.characters_without_null_termination() + position.start_offset, position.start_offset, position.end_offset);
  362. return 1;
  363. }
  364. tcgetattr(0, &termios);
  365. command->run(*this);
  366. return last_return_code;
  367. }
  368. RefPtr<Job> Shell::run_command(const AST::Command& command)
  369. {
  370. FileDescriptionCollector fds;
  371. if (options.verbose) {
  372. fprintf(stderr, "+ ");
  373. for (auto& arg : command.argv)
  374. fprintf(stderr, "%s ", escape_token(arg).characters());
  375. fprintf(stderr, "\n");
  376. fflush(stderr);
  377. }
  378. // If the command is empty, store the redirections and apply them to all later commands.
  379. if (command.argv.is_empty() && !command.should_immediately_execute_next) {
  380. m_global_redirections.append(command.redirections);
  381. return nullptr;
  382. }
  383. // Resolve redirections.
  384. NonnullRefPtrVector<AST::Rewiring> rewirings;
  385. auto resolve_redirection = [&](auto& redirection) -> IterationDecision {
  386. auto rewiring_result = redirection.apply();
  387. if (rewiring_result.is_error()) {
  388. if (!rewiring_result.error().is_empty())
  389. fprintf(stderr, "error: %s\n", rewiring_result.error().characters());
  390. return IterationDecision::Continue;
  391. }
  392. auto& rewiring = rewiring_result.value();
  393. if (rewiring->fd_action != AST::Rewiring::Close::ImmediatelyCloseDestination)
  394. rewirings.append(*rewiring);
  395. if (rewiring->fd_action == AST::Rewiring::Close::Source) {
  396. fds.add(rewiring->source_fd);
  397. } else if (rewiring->fd_action == AST::Rewiring::Close::Destination) {
  398. if (rewiring->dest_fd != -1)
  399. fds.add(rewiring->dest_fd);
  400. } else if (rewiring->fd_action == AST::Rewiring::Close::ImmediatelyCloseDestination) {
  401. fds.add(rewiring->dest_fd);
  402. } else if (rewiring->fd_action == AST::Rewiring::Close::RefreshDestination) {
  403. ASSERT(rewiring->other_pipe_end);
  404. int pipe_fd[2];
  405. int rc = pipe(pipe_fd);
  406. if (rc < 0) {
  407. perror("pipe(RedirRefresh)");
  408. return IterationDecision::Break;
  409. }
  410. rewiring->dest_fd = pipe_fd[1];
  411. rewiring->other_pipe_end->dest_fd = pipe_fd[0]; // This fd will be added to the collection on one of the next iterations.
  412. fds.add(pipe_fd[1]);
  413. }
  414. return IterationDecision::Continue;
  415. };
  416. auto apply_rewirings = [&] {
  417. for (auto& rewiring : rewirings) {
  418. #ifdef SH_DEBUG
  419. dbgprintf("in %s<%d>, dup2(%d, %d)\n", command.argv.is_empty() ? "(<Empty>)" : command.argv[0].characters(), getpid(), rewiring.dest_fd, rewiring.source_fd);
  420. #endif
  421. int rc = dup2(rewiring.dest_fd, rewiring.source_fd);
  422. if (rc < 0) {
  423. perror("dup2(run)");
  424. return IterationDecision::Break;
  425. }
  426. // dest_fd is closed via the `fds` collector, but rewiring.other_pipe_end->dest_fd
  427. // isn't yet in that collector when the first child spawns.
  428. if (rewiring.other_pipe_end && close(rewiring.other_pipe_end->dest_fd) < 0)
  429. perror("close other pipe end");
  430. }
  431. return IterationDecision::Continue;
  432. };
  433. for (auto& redirection : m_global_redirections) {
  434. if (resolve_redirection(redirection) == IterationDecision::Break)
  435. return nullptr;
  436. }
  437. for (auto& redirection : command.redirections) {
  438. if (resolve_redirection(redirection) == IterationDecision::Break)
  439. return nullptr;
  440. }
  441. int retval = 0;
  442. if (run_builtin(command, rewirings, retval)) {
  443. for (auto& next_in_chain : command.next_chain)
  444. run_tail(next_in_chain, retval);
  445. return nullptr;
  446. }
  447. Vector<const char*> argv;
  448. Vector<String> copy_argv = command.argv;
  449. argv.ensure_capacity(command.argv.size() + 1);
  450. for (auto& arg : copy_argv)
  451. argv.append(arg.characters());
  452. argv.append(nullptr);
  453. int sync_pipe[2];
  454. if (pipe(sync_pipe) < 0) {
  455. perror("pipe");
  456. return nullptr;
  457. }
  458. pid_t child = fork();
  459. if (child < 0) {
  460. perror("fork");
  461. return nullptr;
  462. }
  463. if (child == 0) {
  464. close(sync_pipe[1]);
  465. m_is_subshell = true;
  466. m_pid = getpid();
  467. Core::EventLoop::notify_forked(Core::EventLoop::ForkEvent::Child);
  468. jobs.clear();
  469. if (apply_rewirings() == IterationDecision::Break)
  470. _exit(126);
  471. fds.collect();
  472. u8 c;
  473. while (read(sync_pipe[0], &c, 1) < 0) {
  474. if (errno != EINTR) {
  475. perror("read");
  476. // There's nothing interesting we can do here.
  477. break;
  478. }
  479. dbg() << "Oof";
  480. }
  481. #ifdef SH_DEBUG
  482. dbg() << "Synced up with parent, we're good to exec()";
  483. #endif
  484. close(sync_pipe[0]);
  485. if (!m_is_subshell && command.should_wait)
  486. tcsetattr(0, TCSANOW, &default_termios);
  487. if (command.should_immediately_execute_next) {
  488. ASSERT(command.argv.is_empty());
  489. Core::EventLoop mainloop;
  490. setup_signals();
  491. for (auto& next_in_chain : command.next_chain)
  492. run_tail(next_in_chain, 0);
  493. _exit(last_return_code);
  494. }
  495. int rc = execvp(argv[0], const_cast<char* const*>(argv.data()));
  496. if (rc < 0) {
  497. if (errno == ENOENT) {
  498. int shebang_fd = open(argv[0], O_RDONLY);
  499. auto close_argv = ScopeGuard([shebang_fd]() { if (shebang_fd >= 0) close(shebang_fd); });
  500. char shebang[256] {};
  501. ssize_t num_read = -1;
  502. if ((shebang_fd >= 0) && ((num_read = read(shebang_fd, shebang, sizeof(shebang))) >= 2) && (StringView(shebang).starts_with("#!"))) {
  503. StringView shebang_path_view(&shebang[2], num_read - 2);
  504. Optional<size_t> newline_pos = shebang_path_view.find_first_of("\n\r");
  505. shebang[newline_pos.has_value() ? (newline_pos.value() + 2) : num_read] = '\0';
  506. fprintf(stderr, "%s: Invalid interpreter \"%s\": %s\n", argv[0], &shebang[2], strerror(ENOENT));
  507. } else
  508. fprintf(stderr, "%s: Command not found.\n", argv[0]);
  509. } else {
  510. int saved_errno = errno;
  511. struct stat st;
  512. if (stat(argv[0], &st) == 0 && S_ISDIR(st.st_mode)) {
  513. fprintf(stderr, "Shell: %s: Is a directory\n", argv[0]);
  514. _exit(126);
  515. }
  516. fprintf(stderr, "execvp(%s): %s\n", argv[0], strerror(saved_errno));
  517. }
  518. _exit(126);
  519. }
  520. ASSERT_NOT_REACHED();
  521. }
  522. close(sync_pipe[0]);
  523. bool is_first = !command.pipeline || (command.pipeline && command.pipeline->pgid == -1);
  524. if (command.pipeline) {
  525. if (is_first) {
  526. command.pipeline->pgid = child;
  527. }
  528. }
  529. pid_t pgid = is_first ? child : (command.pipeline ? command.pipeline->pgid : child);
  530. if ((!m_is_subshell && command.should_wait) || command.pipeline) {
  531. if (setpgid(child, pgid) < 0)
  532. perror("setpgid");
  533. if (!m_is_subshell) {
  534. tcsetpgrp(STDOUT_FILENO, pgid);
  535. tcsetpgrp(STDIN_FILENO, pgid);
  536. }
  537. }
  538. while (write(sync_pipe[1], "x", 1) < 0) {
  539. if (errno != EINTR) {
  540. perror("write");
  541. // There's nothing interesting we can do here.
  542. break;
  543. }
  544. dbg() << "Oof";
  545. }
  546. close(sync_pipe[1]);
  547. StringBuilder cmd;
  548. cmd.join(" ", command.argv);
  549. auto command_copy = AST::Command(command);
  550. // Clear the next chain if it's to be immediately executed
  551. // as the child will run this chain.
  552. if (command.should_immediately_execute_next)
  553. command_copy.next_chain.clear();
  554. auto job = Job::create(child, pgid, cmd.build(), find_last_job_id() + 1, move(command_copy));
  555. jobs.set((u64)child, job);
  556. job->on_exit = [this](auto job) {
  557. if (!job->exited())
  558. return;
  559. if (job->is_running_in_background() && job->should_announce_exit())
  560. fprintf(stderr, "Shell: Job %" PRIu64 "(%s) exited\n", job->job_id(), job->cmd().characters());
  561. last_return_code = job->exit_code();
  562. job->disown();
  563. run_tail(job);
  564. };
  565. fds.collect();
  566. return *job;
  567. }
  568. void Shell::run_tail(const AST::NodeWithAction& next_in_chain, int head_exit_code)
  569. {
  570. auto evaluate = [&] {
  571. if (next_in_chain.node->would_execute()) {
  572. next_in_chain.node->run(*this);
  573. return;
  574. }
  575. auto commands = next_in_chain.node->to_lazy_evaluated_commands(*this);
  576. run_commands(commands);
  577. };
  578. switch (next_in_chain.action) {
  579. case AST::NodeWithAction::And:
  580. if (head_exit_code == 0)
  581. evaluate();
  582. break;
  583. case AST::NodeWithAction::Or:
  584. if (head_exit_code != 0)
  585. evaluate();
  586. break;
  587. case AST::NodeWithAction::Sequence:
  588. evaluate();
  589. break;
  590. }
  591. }
  592. void Shell::run_tail(RefPtr<Job> job)
  593. {
  594. if (auto cmd = job->command_ptr()) {
  595. deferred_invoke([=, this](auto&) {
  596. for (auto& next_in_chain : cmd->next_chain) {
  597. run_tail(next_in_chain, job->exit_code());
  598. }
  599. });
  600. }
  601. }
  602. NonnullRefPtrVector<Job> Shell::run_commands(Vector<AST::Command>& commands)
  603. {
  604. NonnullRefPtrVector<Job> spawned_jobs;
  605. for (auto& command : commands) {
  606. #ifdef SH_DEBUG
  607. dbg() << "Command";
  608. for (auto& arg : command.argv)
  609. dbg() << "argv: " << arg;
  610. for (auto& redir : command.redirections) {
  611. if (redir.is_path_redirection()) {
  612. auto path_redir = (const AST::PathRedirection*)&redir;
  613. dbg() << "redir path " << (int)path_redir->direction << " " << path_redir->path << " <-> " << path_redir->fd;
  614. } else if (redir.is_fd_redirection()) {
  615. auto* fdredir = (const AST::FdRedirection*)&redir;
  616. dbg() << "redir fd " << fdredir->source_fd << " -> " << fdredir->dest_fd;
  617. } else if (redir.is_close_redirection()) {
  618. auto close_redir = (const AST::CloseRedirection*)&redir;
  619. dbg() << "close fd " << close_redir->fd;
  620. } else {
  621. ASSERT_NOT_REACHED();
  622. }
  623. }
  624. #endif
  625. auto job = run_command(command);
  626. if (!job)
  627. continue;
  628. spawned_jobs.append(*job);
  629. if (command.should_wait) {
  630. block_on_job(job);
  631. } else {
  632. job->set_running_in_background(true);
  633. if (!command.is_pipe_source && command.should_notify_if_in_background)
  634. job->set_should_announce_exit(true);
  635. }
  636. }
  637. return spawned_jobs;
  638. }
  639. bool Shell::run_file(const String& filename, bool explicitly_invoked)
  640. {
  641. auto file_result = Core::File::open(filename, Core::File::ReadOnly);
  642. if (file_result.is_error()) {
  643. if (explicitly_invoked)
  644. fprintf(stderr, "Failed to open %s: %s\n", filename.characters(), file_result.error().characters());
  645. else
  646. dbg() << "open() failed for '" << filename << "' with " << file_result.error();
  647. return false;
  648. }
  649. auto file = file_result.value();
  650. auto data = file->read_all();
  651. run_command(data);
  652. return true;
  653. }
  654. void Shell::restore_ios()
  655. {
  656. if (m_is_subshell)
  657. return;
  658. tcsetattr(0, TCSANOW, &termios);
  659. tcsetpgrp(STDOUT_FILENO, m_pid);
  660. tcsetpgrp(STDIN_FILENO, m_pid);
  661. }
  662. void Shell::block_on_job(RefPtr<Job> job)
  663. {
  664. TemporaryChange<const Job*> current_job { m_current_job, job.ptr() };
  665. if (!job)
  666. return;
  667. if (job->is_suspended())
  668. return; // We cannot wait for a suspended job.
  669. ScopeGuard io_restorer { [&]() {
  670. if (job->exited() && !job->is_running_in_background()) {
  671. restore_ios();
  672. }
  673. } };
  674. Core::EventLoop loop;
  675. job->on_exit = [&, old_exit = move(job->on_exit)](auto job) {
  676. if (old_exit)
  677. old_exit(job);
  678. loop.quit(0);
  679. };
  680. if (job->exited())
  681. return;
  682. loop.exec();
  683. }
  684. String Shell::get_history_path()
  685. {
  686. StringBuilder builder;
  687. builder.append(home);
  688. builder.append("/.history");
  689. return builder.to_string();
  690. }
  691. void Shell::load_history()
  692. {
  693. auto history_file = Core::File::construct(get_history_path());
  694. if (!history_file->open(Core::IODevice::ReadOnly))
  695. return;
  696. while (history_file->can_read_line()) {
  697. auto b = history_file->read_line(1024);
  698. // skip the newline and terminating bytes
  699. editor->add_to_history(String(reinterpret_cast<const char*>(b.data()), b.size() - 2));
  700. }
  701. }
  702. void Shell::save_history()
  703. {
  704. auto file_or_error = Core::File::open(get_history_path(), Core::IODevice::WriteOnly, 0600);
  705. if (file_or_error.is_error())
  706. return;
  707. auto& file = *file_or_error.value();
  708. for (const auto& line : editor->history()) {
  709. file.write(line);
  710. file.write("\n");
  711. }
  712. }
  713. String Shell::escape_token(const String& token)
  714. {
  715. StringBuilder builder;
  716. for (auto c : token) {
  717. switch (c) {
  718. case '\'':
  719. case '"':
  720. case '$':
  721. case '|':
  722. case '>':
  723. case '<':
  724. case '&':
  725. case '\\':
  726. case ' ':
  727. builder.append('\\');
  728. break;
  729. default:
  730. break;
  731. }
  732. builder.append(c);
  733. }
  734. return builder.build();
  735. }
  736. String Shell::unescape_token(const String& token)
  737. {
  738. StringBuilder builder;
  739. enum {
  740. Free,
  741. Escaped
  742. } state { Free };
  743. for (auto c : token) {
  744. switch (state) {
  745. case Escaped:
  746. builder.append(c);
  747. state = Free;
  748. break;
  749. case Free:
  750. if (c == '\\')
  751. state = Escaped;
  752. else
  753. builder.append(c);
  754. break;
  755. }
  756. }
  757. if (state == Escaped)
  758. builder.append('\\');
  759. return builder.build();
  760. }
  761. void Shell::cache_path()
  762. {
  763. if (!cached_path.is_empty())
  764. cached_path.clear_with_capacity();
  765. // Add shell builtins to the cache.
  766. for (const auto& builtin_name : builtin_names)
  767. cached_path.append(escape_token(builtin_name));
  768. // Add aliases to the cache.
  769. for (const auto& alias : m_aliases) {
  770. auto name = escape_token(alias.key);
  771. if (cached_path.contains_slow(name))
  772. continue;
  773. cached_path.append(name);
  774. }
  775. String path = getenv("PATH");
  776. if (!path.is_empty()) {
  777. auto directories = path.split(':');
  778. for (const auto& directory : directories) {
  779. Core::DirIterator programs(directory.characters(), Core::DirIterator::SkipDots);
  780. while (programs.has_next()) {
  781. auto program = programs.next_path();
  782. String program_path = String::format("%s/%s", directory.characters(), program.characters());
  783. auto escaped_name = escape_token(program);
  784. if (cached_path.contains_slow(escaped_name))
  785. continue;
  786. if (access(program_path.characters(), X_OK) == 0)
  787. cached_path.append(escaped_name);
  788. }
  789. }
  790. }
  791. quick_sort(cached_path);
  792. }
  793. void Shell::add_entry_to_cache(const String& entry)
  794. {
  795. size_t index = 0;
  796. auto match = binary_search(
  797. cached_path.span(), entry, [](const String& name, const String& program) -> int {
  798. return strcmp(name.characters(), program.characters());
  799. },
  800. &index);
  801. if (match)
  802. return;
  803. while (strcmp(cached_path[index].characters(), entry.characters()) < 0) {
  804. index++;
  805. }
  806. cached_path.insert(index, entry);
  807. }
  808. void Shell::highlight(Line::Editor& editor) const
  809. {
  810. auto line = editor.line();
  811. Parser parser(line);
  812. auto ast = parser.parse();
  813. if (!ast)
  814. return;
  815. ast->highlight_in_editor(editor, const_cast<Shell&>(*this));
  816. }
  817. Vector<Line::CompletionSuggestion> Shell::complete(const Line::Editor& editor)
  818. {
  819. auto line = editor.line(editor.cursor());
  820. Parser parser(line);
  821. auto ast = parser.parse();
  822. if (!ast)
  823. return {};
  824. return ast->complete_for_editor(*this, line.length());
  825. }
  826. Vector<Line::CompletionSuggestion> Shell::complete_path(const String& base, const String& part, size_t offset)
  827. {
  828. auto token = offset ? part.substring_view(0, offset) : "";
  829. StringView original_token = token;
  830. String path;
  831. ssize_t last_slash = token.length() - 1;
  832. while (last_slash >= 0 && token[last_slash] != '/')
  833. --last_slash;
  834. StringBuilder path_builder;
  835. auto init_slash_part = token.substring_view(0, last_slash + 1);
  836. auto last_slash_part = token.substring_view(last_slash + 1, token.length() - last_slash - 1);
  837. // Depending on the base, we will have to prepend cwd.
  838. if (base.is_empty()) {
  839. // '' /foo -> absolute
  840. // '' foo -> relative
  841. if (!token.starts_with('/'))
  842. path_builder.append(cwd);
  843. path_builder.append('/');
  844. path_builder.append(init_slash_part);
  845. } else {
  846. // /foo * -> absolute
  847. // foo * -> relative
  848. if (!base.starts_with('/'))
  849. path_builder.append(cwd);
  850. path_builder.append('/');
  851. path_builder.append(base);
  852. path_builder.append('/');
  853. path_builder.append(init_slash_part);
  854. }
  855. path = path_builder.build();
  856. token = last_slash_part;
  857. // the invariant part of the token is actually just the last segment
  858. // e. in `cd /foo/bar', 'bar' is the invariant
  859. // since we are not suggesting anything starting with
  860. // `/foo/', but rather just `bar...'
  861. auto token_length = escape_token(token).length();
  862. editor->suggest(token_length, original_token.length() - token_length);
  863. // only suggest dot-files if path starts with a dot
  864. Core::DirIterator files(path,
  865. token.starts_with('.') ? Core::DirIterator::SkipParentAndBaseDir : Core::DirIterator::SkipDots);
  866. Vector<Line::CompletionSuggestion> suggestions;
  867. while (files.has_next()) {
  868. auto file = files.next_path();
  869. if (file.starts_with(token)) {
  870. struct stat program_status;
  871. String file_path = String::format("%s/%s", path.characters(), file.characters());
  872. int stat_error = stat(file_path.characters(), &program_status);
  873. if (!stat_error) {
  874. if (S_ISDIR(program_status.st_mode)) {
  875. suggestions.append({ escape_token(file), "/" });
  876. } else {
  877. suggestions.append({ escape_token(file), " " });
  878. }
  879. }
  880. }
  881. }
  882. return suggestions;
  883. }
  884. Vector<Line::CompletionSuggestion> Shell::complete_program_name(const String& name, size_t offset)
  885. {
  886. auto match = binary_search(cached_path.span(), name, [](const String& name, const String& program) -> int {
  887. return strncmp(name.characters(), program.characters(), name.length());
  888. });
  889. if (!match)
  890. return complete_path("", name, offset);
  891. String completion = *match;
  892. editor->suggest(escape_token(name).length(), 0);
  893. // Now that we have a program name starting with our token, we look at
  894. // other program names starting with our token and cut off any mismatching
  895. // characters.
  896. Vector<Line::CompletionSuggestion> suggestions;
  897. int index = match - cached_path.data();
  898. for (int i = index - 1; i >= 0 && cached_path[i].starts_with(name); --i) {
  899. suggestions.append({ cached_path[i], " " });
  900. }
  901. for (size_t i = index + 1; i < cached_path.size() && cached_path[i].starts_with(name); ++i) {
  902. suggestions.append({ cached_path[i], " " });
  903. }
  904. suggestions.append({ cached_path[index], " " });
  905. return suggestions;
  906. }
  907. Vector<Line::CompletionSuggestion> Shell::complete_variable(const String& name, size_t offset)
  908. {
  909. Vector<Line::CompletionSuggestion> suggestions;
  910. auto pattern = offset ? name.substring_view(0, offset) : "";
  911. editor->suggest(offset);
  912. // Look at local variables.
  913. for (auto& frame : m_local_frames) {
  914. for (auto& variable : frame.local_variables) {
  915. if (variable.key.starts_with(pattern) && !suggestions.contains_slow(variable.key))
  916. suggestions.append(variable.key);
  917. }
  918. }
  919. // Look at the environment.
  920. for (auto i = 0; environ[i]; ++i) {
  921. auto entry = StringView { environ[i] };
  922. if (entry.starts_with(pattern)) {
  923. auto parts = entry.split_view('=');
  924. if (parts.is_empty() || parts.first().is_empty())
  925. continue;
  926. String name = parts.first();
  927. if (suggestions.contains_slow(name))
  928. continue;
  929. suggestions.append(move(name));
  930. }
  931. }
  932. return suggestions;
  933. }
  934. Vector<Line::CompletionSuggestion> Shell::complete_user(const String& name, size_t offset)
  935. {
  936. Vector<Line::CompletionSuggestion> suggestions;
  937. auto pattern = offset ? name.substring_view(0, offset) : "";
  938. editor->suggest(offset);
  939. Core::DirIterator di("/home", Core::DirIterator::SkipParentAndBaseDir);
  940. if (di.has_error())
  941. return suggestions;
  942. while (di.has_next()) {
  943. String name = di.next_path();
  944. if (name.starts_with(pattern))
  945. suggestions.append(name);
  946. }
  947. return suggestions;
  948. }
  949. Vector<Line::CompletionSuggestion> Shell::complete_option(const String& program_name, const String& option, size_t offset)
  950. {
  951. size_t start = 0;
  952. while (start < option.length() && option[start] == '-' && start < 2)
  953. ++start;
  954. auto option_pattern = offset > start ? option.substring_view(start, offset - start) : "";
  955. editor->suggest(offset);
  956. Vector<Line::CompletionSuggestion> suggestions;
  957. dbg() << "Shell::complete_option(" << program_name << ", " << option_pattern << ")";
  958. // FIXME: Figure out how to do this stuff.
  959. if (has_builtin(program_name)) {
  960. // Complete builtins.
  961. if (program_name == "setopt") {
  962. bool negate = false;
  963. if (option_pattern.starts_with("no_")) {
  964. negate = true;
  965. option_pattern = option_pattern.substring_view(3, option_pattern.length() - 3);
  966. }
  967. auto maybe_negate = [&](const StringView& view) {
  968. static StringBuilder builder;
  969. builder.clear();
  970. builder.append("--");
  971. if (negate)
  972. builder.append("no_");
  973. builder.append(view);
  974. return builder.to_string();
  975. };
  976. #define __ENUMERATE_SHELL_OPTION(name, d_, descr_) \
  977. if (StringView { #name }.starts_with(option_pattern)) \
  978. suggestions.append(maybe_negate(#name));
  979. ENUMERATE_SHELL_OPTIONS();
  980. #undef __ENUMERATE_SHELL_OPTION
  981. return suggestions;
  982. }
  983. }
  984. return suggestions;
  985. }
  986. void Shell::bring_cursor_to_beginning_of_a_line() const
  987. {
  988. struct winsize ws;
  989. if (editor) {
  990. ws = editor->terminal_size();
  991. } else {
  992. if (ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) < 0) {
  993. // Very annoying assumptions.
  994. ws.ws_col = 80;
  995. ws.ws_row = 25;
  996. }
  997. }
  998. // Black with Cyan background.
  999. constexpr auto default_mark = "\e[30;46m%\e[0m";
  1000. String eol_mark = getenv("PROMPT_EOL_MARK");
  1001. if (eol_mark.is_null())
  1002. eol_mark = default_mark;
  1003. size_t eol_mark_length = Line::Editor::actual_rendered_string_metrics(eol_mark).line_lengths.last();
  1004. if (eol_mark_length >= ws.ws_col) {
  1005. eol_mark = default_mark;
  1006. eol_mark_length = 1;
  1007. }
  1008. fputs(eol_mark.characters(), stderr);
  1009. for (auto i = 1 + eol_mark_length; i < ws.ws_col; ++i)
  1010. putc(' ', stderr);
  1011. putc('\r', stderr);
  1012. }
  1013. bool Shell::read_single_line()
  1014. {
  1015. restore_ios();
  1016. bring_cursor_to_beginning_of_a_line();
  1017. auto line_result = editor->get_line(prompt());
  1018. if (line_result.is_error()) {
  1019. if (line_result.error() == Line::Editor::Error::Eof || line_result.error() == Line::Editor::Error::Empty) {
  1020. // Pretend the user tried to execute builtin_exit()
  1021. m_complete_line_builder.clear();
  1022. run_command("exit");
  1023. return read_single_line();
  1024. } else {
  1025. m_complete_line_builder.clear();
  1026. Core::EventLoop::current().quit(1);
  1027. return false;
  1028. }
  1029. }
  1030. auto& line = line_result.value();
  1031. if (line.is_empty())
  1032. return true;
  1033. if (!m_complete_line_builder.is_empty())
  1034. m_complete_line_builder.append("\n");
  1035. m_complete_line_builder.append(line);
  1036. run_command(m_complete_line_builder.string_view());
  1037. editor->add_to_history(m_complete_line_builder.build());
  1038. m_complete_line_builder.clear();
  1039. return true;
  1040. }
  1041. void Shell::custom_event(Core::CustomEvent& event)
  1042. {
  1043. if (event.custom_type() == ReadLine) {
  1044. if (read_single_line())
  1045. Core::EventLoop::current().post_event(*this, make<Core::CustomEvent>(ShellEventType::ReadLine));
  1046. return;
  1047. }
  1048. }
  1049. Shell::Shell()
  1050. {
  1051. uid = getuid();
  1052. tcsetpgrp(0, getpgrp());
  1053. m_pid = getpid();
  1054. push_frame().leak_frame();
  1055. int rc = gethostname(hostname, Shell::HostNameSize);
  1056. if (rc < 0)
  1057. perror("gethostname");
  1058. auto istty = isatty(STDIN_FILENO);
  1059. m_is_interactive = istty;
  1060. if (istty) {
  1061. rc = ttyname_r(0, ttyname, Shell::TTYNameSize);
  1062. if (rc < 0)
  1063. perror("ttyname_r");
  1064. } else {
  1065. ttyname[0] = 0;
  1066. }
  1067. {
  1068. auto* cwd = getcwd(nullptr, 0);
  1069. this->cwd = cwd;
  1070. setenv("PWD", cwd, 1);
  1071. free(cwd);
  1072. }
  1073. {
  1074. auto* pw = getpwuid(getuid());
  1075. if (pw) {
  1076. username = pw->pw_name;
  1077. home = pw->pw_dir;
  1078. setenv("HOME", pw->pw_dir, 1);
  1079. }
  1080. endpwent();
  1081. }
  1082. directory_stack.append(cwd);
  1083. load_history();
  1084. cache_path();
  1085. }
  1086. Shell::~Shell()
  1087. {
  1088. stop_all_jobs();
  1089. save_history();
  1090. }
  1091. void Shell::stop_all_jobs()
  1092. {
  1093. if (!jobs.is_empty()) {
  1094. printf("Killing active jobs\n");
  1095. for (auto& entry : jobs) {
  1096. if (!entry.value->is_running_in_background()) {
  1097. #ifdef SH_DEBUG
  1098. dbg() << "Job " << entry.value->pid() << " is not running in background";
  1099. #endif
  1100. kill_job(entry.value, SIGCONT);
  1101. }
  1102. kill_job(entry.value, SIGHUP);
  1103. }
  1104. usleep(10000); // Wait for a bit before killing the job
  1105. for (auto& entry : jobs) {
  1106. #ifdef SH_DEBUG
  1107. dbg() << "Actively killing " << entry.value->pid() << "(" << entry.value->cmd() << ")";
  1108. #endif
  1109. if (killpg(entry.value->pgid(), SIGKILL) < 0) {
  1110. if (errno == ESRCH)
  1111. continue; // The process has exited all by itself.
  1112. perror("killpg(KILL)");
  1113. }
  1114. }
  1115. }
  1116. }
  1117. u64 Shell::find_last_job_id() const
  1118. {
  1119. u64 job_id = 0;
  1120. for (auto& entry : jobs) {
  1121. if (entry.value->job_id() > job_id)
  1122. job_id = entry.value->job_id();
  1123. }
  1124. return job_id;
  1125. }
  1126. const Job* Shell::find_job(u64 id)
  1127. {
  1128. for (auto& entry : jobs) {
  1129. if (entry.value->job_id() == id)
  1130. return entry.value;
  1131. }
  1132. return nullptr;
  1133. }
  1134. void Shell::kill_job(const Job* job, int sig)
  1135. {
  1136. if (!job)
  1137. return;
  1138. if (killpg(job->pgid(), sig) < 0)
  1139. perror("killpg(job)");
  1140. }
  1141. void Shell::save_to(JsonObject& object)
  1142. {
  1143. Core::Object::save_to(object);
  1144. object.set("working_directory", cwd);
  1145. object.set("username", username);
  1146. object.set("user_home_path", home);
  1147. object.set("user_id", uid);
  1148. object.set("directory_stack_size", directory_stack.size());
  1149. object.set("cd_history_size", cd_history.size());
  1150. // Jobs.
  1151. JsonArray job_objects;
  1152. for (auto& job_entry : jobs) {
  1153. JsonObject job_object;
  1154. job_object.set("pid", job_entry.value->pid());
  1155. job_object.set("pgid", job_entry.value->pgid());
  1156. job_object.set("running_time", job_entry.value->timer().elapsed());
  1157. job_object.set("command", job_entry.value->cmd());
  1158. job_object.set("is_running_in_background", job_entry.value->is_running_in_background());
  1159. job_objects.append(move(job_object));
  1160. }
  1161. object.set("jobs", move(job_objects));
  1162. }