Shell.cpp 44 KB

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