Shell.cpp 44 KB

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