Shell.cpp 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682
  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 "Formatter.h"
  29. #include <AK/Function.h>
  30. #include <AK/LexicalPath.h>
  31. #include <AK/ScopeGuard.h>
  32. #include <AK/StringBuilder.h>
  33. #include <AK/TemporaryChange.h>
  34. #include <LibCore/ArgsParser.h>
  35. #include <LibCore/DirIterator.h>
  36. #include <LibCore/Event.h>
  37. #include <LibCore/EventLoop.h>
  38. #include <LibCore/File.h>
  39. #include <LibLine/Editor.h>
  40. #include <errno.h>
  41. #include <fcntl.h>
  42. #include <inttypes.h>
  43. #include <pwd.h>
  44. #include <signal.h>
  45. #include <stdio.h>
  46. #include <stdlib.h>
  47. #include <string.h>
  48. #include <sys/mman.h>
  49. #include <sys/stat.h>
  50. #include <sys/utsname.h>
  51. #include <sys/wait.h>
  52. #include <termios.h>
  53. #include <unistd.h>
  54. static bool s_disable_hyperlinks = false;
  55. extern char** environ;
  56. //#define SH_DEBUG
  57. namespace Shell {
  58. // FIXME: This should eventually be removed once we've established that
  59. // waitpid() is not passed the same job twice.
  60. #ifdef __serenity__
  61. # define ENSURE_WAITID_ONCE
  62. #endif
  63. void Shell::setup_signals()
  64. {
  65. Core::EventLoop::register_signal(SIGCHLD, [this](int) {
  66. #ifdef SH_DEBUG
  67. dbg() << "SIGCHLD!";
  68. #endif
  69. notify_child_event();
  70. });
  71. Core::EventLoop::register_signal(SIGTSTP, [this](auto) {
  72. auto job = current_job();
  73. kill_job(job, SIGTSTP);
  74. if (job) {
  75. job->set_is_suspended(true);
  76. job->unblock();
  77. }
  78. });
  79. }
  80. void Shell::print_path(const String& path)
  81. {
  82. if (s_disable_hyperlinks || !m_is_interactive) {
  83. printf("%s", path.characters());
  84. return;
  85. }
  86. printf("\033]8;;file://%s%s\033\\%s\033]8;;\033\\", hostname, path.characters(), path.characters());
  87. }
  88. String Shell::prompt() const
  89. {
  90. auto build_prompt = [&]() -> String {
  91. auto* ps1 = getenv("PROMPT");
  92. if (!ps1) {
  93. if (uid == 0)
  94. return "# ";
  95. StringBuilder builder;
  96. builder.appendf("\033]0;%s@%s:%s\007", username.characters(), hostname, cwd.characters());
  97. 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());
  98. return builder.to_string();
  99. }
  100. StringBuilder builder;
  101. for (char* ptr = ps1; *ptr; ++ptr) {
  102. if (*ptr == '\\') {
  103. ++ptr;
  104. if (!*ptr)
  105. break;
  106. switch (*ptr) {
  107. case 'X':
  108. builder.append("\033]0;");
  109. break;
  110. case 'a':
  111. builder.append(0x07);
  112. break;
  113. case 'e':
  114. builder.append(0x1b);
  115. break;
  116. case 'u':
  117. builder.append(username);
  118. break;
  119. case 'h':
  120. builder.append(hostname);
  121. break;
  122. case 'w': {
  123. String home_path = getenv("HOME");
  124. if (cwd.starts_with(home_path)) {
  125. builder.append('~');
  126. builder.append(cwd.substring_view(home_path.length(), cwd.length() - home_path.length()));
  127. } else {
  128. builder.append(cwd);
  129. }
  130. break;
  131. }
  132. case 'p':
  133. builder.append(uid == 0 ? '#' : '$');
  134. break;
  135. }
  136. continue;
  137. }
  138. builder.append(*ptr);
  139. }
  140. return builder.to_string();
  141. };
  142. return build_prompt();
  143. }
  144. String Shell::expand_tilde(const String& expression)
  145. {
  146. ASSERT(expression.starts_with('~'));
  147. StringBuilder login_name;
  148. size_t first_slash_index = expression.length();
  149. for (size_t i = 1; i < expression.length(); ++i) {
  150. if (expression[i] == '/') {
  151. first_slash_index = i;
  152. break;
  153. }
  154. login_name.append(expression[i]);
  155. }
  156. StringBuilder path;
  157. for (size_t i = first_slash_index; i < expression.length(); ++i)
  158. path.append(expression[i]);
  159. if (login_name.is_empty()) {
  160. const char* home = getenv("HOME");
  161. if (!home) {
  162. auto passwd = getpwuid(getuid());
  163. ASSERT(passwd && passwd->pw_dir);
  164. return String::format("%s/%s", passwd->pw_dir, path.to_string().characters());
  165. }
  166. return String::format("%s/%s", home, path.to_string().characters());
  167. }
  168. auto passwd = getpwnam(login_name.to_string().characters());
  169. if (!passwd)
  170. return expression;
  171. ASSERT(passwd->pw_dir);
  172. return String::format("%s/%s", passwd->pw_dir, path.to_string().characters());
  173. }
  174. bool Shell::is_glob(const StringView& s)
  175. {
  176. for (size_t i = 0; i < s.length(); i++) {
  177. char c = s.characters_without_null_termination()[i];
  178. if (c == '*' || c == '?')
  179. return true;
  180. }
  181. return false;
  182. }
  183. Vector<StringView> Shell::split_path(const StringView& path)
  184. {
  185. Vector<StringView> parts;
  186. size_t substart = 0;
  187. for (size_t i = 0; i < path.length(); i++) {
  188. char ch = path[i];
  189. if (ch != '/')
  190. continue;
  191. size_t sublen = i - substart;
  192. if (sublen != 0)
  193. parts.append(path.substring_view(substart, sublen));
  194. substart = i + 1;
  195. }
  196. size_t taillen = path.length() - substart;
  197. if (taillen != 0)
  198. parts.append(path.substring_view(substart, taillen));
  199. return parts;
  200. }
  201. Vector<String> Shell::expand_globs(const StringView& path, StringView base)
  202. {
  203. auto explicitly_set_base = false;
  204. if (path.starts_with('/')) {
  205. base = "/";
  206. explicitly_set_base = true;
  207. }
  208. auto parts = split_path(path);
  209. String base_string = base;
  210. struct stat statbuf;
  211. if (lstat(base_string.characters(), &statbuf) < 0) {
  212. perror("lstat");
  213. return {};
  214. }
  215. StringBuilder resolved_base_path_builder;
  216. resolved_base_path_builder.append(Core::File::real_path_for(base));
  217. if (S_ISDIR(statbuf.st_mode))
  218. resolved_base_path_builder.append('/');
  219. auto resolved_base = resolved_base_path_builder.string_view();
  220. auto results = expand_globs(move(parts), resolved_base);
  221. if (explicitly_set_base && base == "/")
  222. resolved_base = resolved_base.substring_view(1, resolved_base.length() - 1);
  223. for (auto& entry : results) {
  224. entry = entry.substring(resolved_base.length(), entry.length() - resolved_base.length());
  225. if (entry.is_empty())
  226. entry = ".";
  227. }
  228. // Make the output predictable and nice.
  229. quick_sort(results);
  230. return results;
  231. }
  232. Vector<String> Shell::expand_globs(Vector<StringView> path_segments, const StringView& base)
  233. {
  234. if (path_segments.is_empty()) {
  235. String base_str = base;
  236. if (access(base_str.characters(), F_OK) == 0)
  237. return { move(base_str) };
  238. return {};
  239. }
  240. auto first_segment = path_segments.take_first();
  241. if (is_glob(first_segment)) {
  242. Vector<String> result;
  243. Core::DirIterator di(base, Core::DirIterator::SkipParentAndBaseDir);
  244. if (di.has_error())
  245. return {};
  246. while (di.has_next()) {
  247. String path = di.next_path();
  248. // Dotfiles have to be explicitly requested
  249. if (path[0] == '.' && first_segment[0] != '.')
  250. continue;
  251. if (path.matches(first_segment, CaseSensitivity::CaseSensitive)) {
  252. StringBuilder builder;
  253. builder.append(base);
  254. if (!base.ends_with('/'))
  255. builder.append('/');
  256. builder.append(path);
  257. result.append(expand_globs(path_segments, builder.string_view()));
  258. }
  259. }
  260. return result;
  261. } else {
  262. StringBuilder builder;
  263. builder.append(base);
  264. if (!base.ends_with('/'))
  265. builder.append('/');
  266. builder.append(first_segment);
  267. return expand_globs(move(path_segments), builder.string_view());
  268. }
  269. }
  270. Vector<AST::Command> Shell::expand_aliases(Vector<AST::Command> initial_commands)
  271. {
  272. Vector<AST::Command> commands;
  273. Function<void(AST::Command&)> resolve_aliases_and_append = [&](auto& command) {
  274. if (!command.argv.is_empty()) {
  275. auto alias = resolve_alias(command.argv[0]);
  276. if (!alias.is_null()) {
  277. auto argv0 = command.argv.take_first();
  278. auto subcommand_ast = Parser { alias }.parse();
  279. if (subcommand_ast) {
  280. while (subcommand_ast->is_execute()) {
  281. auto* ast = static_cast<AST::Execute*>(subcommand_ast.ptr());
  282. subcommand_ast = ast->command();
  283. }
  284. auto subcommand_nonnull = subcommand_ast.release_nonnull();
  285. NonnullRefPtr<AST::Node> substitute = adopt(*new AST::Join(subcommand_nonnull->position(),
  286. subcommand_nonnull,
  287. adopt(*new AST::CommandLiteral(subcommand_nonnull->position(), command))));
  288. auto res = substitute->run(*this);
  289. for (auto& subst_command : res->resolve_as_commands(*this)) {
  290. if (!subst_command.argv.is_empty() && subst_command.argv.first() == argv0) // Disallow an alias resolving to itself.
  291. commands.append(subst_command);
  292. else
  293. resolve_aliases_and_append(subst_command);
  294. }
  295. } else {
  296. commands.append(command);
  297. }
  298. } else {
  299. commands.append(command);
  300. }
  301. } else {
  302. commands.append(command);
  303. }
  304. };
  305. for (auto& command : initial_commands)
  306. resolve_aliases_and_append(command);
  307. return commands;
  308. }
  309. String Shell::resolve_path(String path) const
  310. {
  311. if (!path.starts_with('/'))
  312. path = String::format("%s/%s", cwd.characters(), path.characters());
  313. return Core::File::real_path_for(path);
  314. }
  315. Shell::LocalFrame* Shell::find_frame_containing_local_variable(const String& name)
  316. {
  317. for (auto& frame : m_local_frames) {
  318. if (frame.local_variables.contains(name))
  319. return &frame;
  320. }
  321. return nullptr;
  322. }
  323. RefPtr<AST::Value> Shell::lookup_local_variable(const String& name)
  324. {
  325. if (auto* frame = find_frame_containing_local_variable(name))
  326. return frame->local_variables.get(name).value();
  327. if (auto index = name.to_uint(); index.has_value())
  328. return get_argument(index.value());
  329. return nullptr;
  330. }
  331. RefPtr<AST::Value> Shell::get_argument(size_t index)
  332. {
  333. if (index == 0)
  334. return adopt(*new AST::StringValue(current_script));
  335. --index;
  336. if (auto argv = lookup_local_variable("ARGV")) {
  337. if (argv->is_list_without_resolution()) {
  338. AST::ListValue* list = static_cast<AST::ListValue*>(argv.ptr());
  339. if (list->values().size() <= index)
  340. return nullptr;
  341. return list->values().at(index);
  342. }
  343. if (index != 0)
  344. return nullptr;
  345. return argv;
  346. }
  347. return nullptr;
  348. }
  349. String Shell::local_variable_or(const String& name, const String& replacement)
  350. {
  351. auto value = lookup_local_variable(name);
  352. if (value) {
  353. StringBuilder builder;
  354. builder.join(" ", value->resolve_as_list(*this));
  355. return builder.to_string();
  356. }
  357. return replacement;
  358. }
  359. void Shell::set_local_variable(const String& name, RefPtr<AST::Value> value)
  360. {
  361. if (auto* frame = find_frame_containing_local_variable(name))
  362. frame->local_variables.set(name, move(value));
  363. else
  364. m_local_frames.last().local_variables.set(name, move(value));
  365. }
  366. void Shell::unset_local_variable(const String& name)
  367. {
  368. if (auto* frame = find_frame_containing_local_variable(name))
  369. frame->local_variables.remove(name);
  370. }
  371. void Shell::define_function(String name, Vector<String> argnames, RefPtr<AST::Node> body)
  372. {
  373. add_entry_to_cache(name);
  374. m_functions.set(name, { name, move(argnames), move(body) });
  375. }
  376. bool Shell::has_function(const String& name)
  377. {
  378. return m_functions.contains(name);
  379. }
  380. bool Shell::invoke_function(const AST::Command& command, int& retval)
  381. {
  382. if (command.argv.is_empty())
  383. return false;
  384. StringView name = command.argv.first();
  385. TemporaryChange<String> script_change { current_script, name };
  386. auto function_option = m_functions.get(name);
  387. if (!function_option.has_value())
  388. return false;
  389. auto& function = function_option.value();
  390. if (!function.body) {
  391. retval = 0;
  392. return true;
  393. }
  394. if (command.argv.size() - 1 < function.arguments.size()) {
  395. fprintf(stderr, "Shell: expected at least %zu arguments to %s, but got %zu\n", function.arguments.size(), function.name.characters(), command.argv.size() - 1);
  396. retval = 1;
  397. return true;
  398. }
  399. auto frame = push_frame();
  400. size_t index = 0;
  401. for (auto& arg : function.arguments) {
  402. ++index;
  403. set_local_variable(arg, adopt(*new AST::StringValue(command.argv[index])));
  404. }
  405. auto argv = command.argv;
  406. argv.take_first();
  407. set_local_variable("ARGV", adopt(*new AST::ListValue(move(argv))));
  408. function.body->run(*this);
  409. retval = last_return_code;
  410. return true;
  411. }
  412. String Shell::format(const StringView& source, ssize_t& cursor) const
  413. {
  414. Formatter formatter(source, cursor);
  415. auto result = formatter.format();
  416. cursor = formatter.cursor();
  417. return result;
  418. }
  419. Shell::Frame Shell::push_frame()
  420. {
  421. m_local_frames.empend();
  422. return { m_local_frames, m_local_frames.last() };
  423. }
  424. void Shell::pop_frame()
  425. {
  426. ASSERT(m_local_frames.size() > 1);
  427. m_local_frames.take_last();
  428. }
  429. Shell::Frame::~Frame()
  430. {
  431. if (!should_destroy_frame)
  432. return;
  433. ASSERT(&frames.last() == &frame);
  434. frames.take_last();
  435. }
  436. String Shell::resolve_alias(const String& name) const
  437. {
  438. return m_aliases.get(name).value_or({});
  439. }
  440. bool Shell::is_runnable(const StringView& name)
  441. {
  442. if (access(name.to_string().characters(), X_OK) == 0)
  443. return true;
  444. return !!binary_search(cached_path.span(), name.to_string(), [](const String& name, const String& program) -> int {
  445. return strcmp(name.characters(), program.characters());
  446. });
  447. }
  448. int Shell::run_command(const StringView& cmd)
  449. {
  450. // The default-constructed mode of the shell
  451. // should not be used for execution!
  452. ASSERT(!m_default_constructed);
  453. if (cmd.is_empty())
  454. return 0;
  455. auto command = Parser(cmd).parse();
  456. if (!command)
  457. return 0;
  458. #ifdef SH_DEBUG
  459. dbg() << "Command follows";
  460. command->dump(0);
  461. #endif
  462. if (command->is_syntax_error()) {
  463. auto& error_node = command->syntax_error_node();
  464. auto& position = error_node.position();
  465. fprintf(stderr, "Shell: Syntax error in command: %s\n", error_node.error_text().characters());
  466. 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);
  467. return 1;
  468. }
  469. tcgetattr(0, &termios);
  470. command->run(*this);
  471. return last_return_code;
  472. }
  473. RefPtr<Job> Shell::run_command(const AST::Command& command)
  474. {
  475. FileDescriptionCollector fds;
  476. if (options.verbose) {
  477. fprintf(stderr, "+ ");
  478. for (auto& arg : command.argv)
  479. fprintf(stderr, "%s ", escape_token(arg).characters());
  480. fprintf(stderr, "\n");
  481. fflush(stderr);
  482. }
  483. // If the command is empty, store the redirections and apply them to all later commands.
  484. if (command.argv.is_empty() && !command.should_immediately_execute_next) {
  485. m_global_redirections.append(command.redirections);
  486. return nullptr;
  487. }
  488. // Resolve redirections.
  489. NonnullRefPtrVector<AST::Rewiring> rewirings;
  490. auto resolve_redirection = [&](auto& redirection) -> IterationDecision {
  491. auto rewiring_result = redirection.apply();
  492. if (rewiring_result.is_error()) {
  493. if (!rewiring_result.error().is_empty())
  494. fprintf(stderr, "error: %s\n", rewiring_result.error().characters());
  495. return IterationDecision::Continue;
  496. }
  497. auto& rewiring = rewiring_result.value();
  498. if (rewiring->fd_action != AST::Rewiring::Close::ImmediatelyCloseDestination)
  499. rewirings.append(*rewiring);
  500. if (rewiring->fd_action == AST::Rewiring::Close::Source) {
  501. fds.add(rewiring->source_fd);
  502. } else if (rewiring->fd_action == AST::Rewiring::Close::Destination) {
  503. if (rewiring->dest_fd != -1)
  504. fds.add(rewiring->dest_fd);
  505. } else if (rewiring->fd_action == AST::Rewiring::Close::ImmediatelyCloseDestination) {
  506. fds.add(rewiring->dest_fd);
  507. } else if (rewiring->fd_action == AST::Rewiring::Close::RefreshDestination) {
  508. ASSERT(rewiring->other_pipe_end);
  509. int pipe_fd[2];
  510. int rc = pipe(pipe_fd);
  511. if (rc < 0) {
  512. perror("pipe(RedirRefresh)");
  513. return IterationDecision::Break;
  514. }
  515. rewiring->dest_fd = pipe_fd[1];
  516. rewiring->other_pipe_end->dest_fd = pipe_fd[0]; // This fd will be added to the collection on one of the next iterations.
  517. fds.add(pipe_fd[1]);
  518. }
  519. return IterationDecision::Continue;
  520. };
  521. auto apply_rewirings = [&] {
  522. for (auto& rewiring : rewirings) {
  523. #ifdef SH_DEBUG
  524. dbgprintf("in %s<%d>, dup2(%d, %d)\n", command.argv.is_empty() ? "(<Empty>)" : command.argv[0].characters(), getpid(), rewiring.dest_fd, rewiring.source_fd);
  525. #endif
  526. int rc = dup2(rewiring.dest_fd, rewiring.source_fd);
  527. if (rc < 0) {
  528. perror("dup2(run)");
  529. return IterationDecision::Break;
  530. }
  531. // dest_fd is closed via the `fds` collector, but rewiring.other_pipe_end->dest_fd
  532. // isn't yet in that collector when the first child spawns.
  533. if (rewiring.other_pipe_end && close(rewiring.other_pipe_end->dest_fd) < 0)
  534. perror("close other pipe end");
  535. }
  536. return IterationDecision::Continue;
  537. };
  538. for (auto& redirection : m_global_redirections) {
  539. if (resolve_redirection(redirection) == IterationDecision::Break)
  540. return nullptr;
  541. }
  542. for (auto& redirection : command.redirections) {
  543. if (resolve_redirection(redirection) == IterationDecision::Break)
  544. return nullptr;
  545. }
  546. if (run_builtin(command, rewirings, last_return_code)) {
  547. for (auto& next_in_chain : command.next_chain)
  548. run_tail(next_in_chain, last_return_code);
  549. return nullptr;
  550. }
  551. auto can_be_run_in_current_process = command.should_wait && !command.pipeline;
  552. if (can_be_run_in_current_process && has_function(command.argv.first())) {
  553. SavedFileDescriptors fds { rewirings };
  554. for (auto& rewiring : rewirings) {
  555. int rc = dup2(rewiring.dest_fd, rewiring.source_fd);
  556. if (rc < 0) {
  557. perror("dup2(run)");
  558. return nullptr;
  559. }
  560. }
  561. if (invoke_function(command, last_return_code)) {
  562. for (auto& next_in_chain : command.next_chain)
  563. run_tail(next_in_chain, last_return_code);
  564. return nullptr;
  565. }
  566. }
  567. Vector<const char*> argv;
  568. Vector<String> copy_argv = command.argv;
  569. argv.ensure_capacity(command.argv.size() + 1);
  570. for (auto& arg : copy_argv)
  571. argv.append(arg.characters());
  572. argv.append(nullptr);
  573. int sync_pipe[2];
  574. if (pipe(sync_pipe) < 0) {
  575. perror("pipe");
  576. return nullptr;
  577. }
  578. pid_t child = fork();
  579. if (child < 0) {
  580. perror("fork");
  581. return nullptr;
  582. }
  583. if (child == 0) {
  584. close(sync_pipe[1]);
  585. m_is_subshell = true;
  586. m_pid = getpid();
  587. Core::EventLoop::notify_forked(Core::EventLoop::ForkEvent::Child);
  588. jobs.clear();
  589. if (apply_rewirings() == IterationDecision::Break)
  590. _exit(126);
  591. fds.collect();
  592. u8 c;
  593. while (read(sync_pipe[0], &c, 1) < 0) {
  594. if (errno != EINTR) {
  595. perror("read");
  596. // There's nothing interesting we can do here.
  597. break;
  598. }
  599. dbg() << "Oof";
  600. }
  601. #ifdef SH_DEBUG
  602. dbg() << "Synced up with parent, we're good to exec()";
  603. #endif
  604. close(sync_pipe[0]);
  605. if (!m_is_subshell && command.should_wait)
  606. tcsetattr(0, TCSANOW, &default_termios);
  607. Core::EventLoop mainloop;
  608. setup_signals();
  609. if (command.should_immediately_execute_next) {
  610. ASSERT(command.argv.is_empty());
  611. for (auto& next_in_chain : command.next_chain)
  612. run_tail(next_in_chain, 0);
  613. _exit(last_return_code);
  614. }
  615. if (invoke_function(command, last_return_code))
  616. _exit(last_return_code);
  617. int rc = execvp(argv[0], const_cast<char* const*>(argv.data()));
  618. if (rc < 0) {
  619. if (errno == ENOENT) {
  620. int shebang_fd = open(argv[0], O_RDONLY);
  621. auto close_argv = ScopeGuard([shebang_fd]() { if (shebang_fd >= 0) close(shebang_fd); });
  622. char shebang[256] {};
  623. ssize_t num_read = -1;
  624. if ((shebang_fd >= 0) && ((num_read = read(shebang_fd, shebang, sizeof(shebang))) >= 2) && (StringView(shebang).starts_with("#!"))) {
  625. StringView shebang_path_view(&shebang[2], num_read - 2);
  626. Optional<size_t> newline_pos = shebang_path_view.find_first_of("\n\r");
  627. shebang[newline_pos.has_value() ? (newline_pos.value() + 2) : num_read] = '\0';
  628. fprintf(stderr, "%s: Invalid interpreter \"%s\": %s\n", argv[0], &shebang[2], strerror(ENOENT));
  629. } else
  630. fprintf(stderr, "%s: Command not found.\n", argv[0]);
  631. } else {
  632. int saved_errno = errno;
  633. struct stat st;
  634. if (stat(argv[0], &st) == 0 && S_ISDIR(st.st_mode)) {
  635. fprintf(stderr, "Shell: %s: Is a directory\n", argv[0]);
  636. _exit(126);
  637. }
  638. fprintf(stderr, "execvp(%s): %s\n", argv[0], strerror(saved_errno));
  639. }
  640. _exit(126);
  641. }
  642. ASSERT_NOT_REACHED();
  643. }
  644. close(sync_pipe[0]);
  645. bool is_first = !command.pipeline || (command.pipeline && command.pipeline->pgid == -1);
  646. if (command.pipeline) {
  647. if (is_first) {
  648. command.pipeline->pgid = child;
  649. }
  650. }
  651. pid_t pgid = is_first ? child : (command.pipeline ? command.pipeline->pgid : child);
  652. if ((!m_is_subshell && command.should_wait) || command.pipeline) {
  653. if (setpgid(child, pgid) < 0)
  654. perror("setpgid");
  655. if (!m_is_subshell) {
  656. if (tcsetpgrp(STDOUT_FILENO, pgid) != 0)
  657. perror("tcsetpgrp(OUT)");
  658. if (tcsetpgrp(STDIN_FILENO, pgid) != 0)
  659. perror("tcsetpgrp(IN)");
  660. }
  661. }
  662. while (write(sync_pipe[1], "x", 1) < 0) {
  663. if (errno != EINTR) {
  664. perror("write");
  665. // There's nothing interesting we can do here.
  666. break;
  667. }
  668. dbg() << "Oof";
  669. }
  670. close(sync_pipe[1]);
  671. StringBuilder cmd;
  672. cmd.join(" ", command.argv);
  673. auto command_copy = AST::Command(command);
  674. // Clear the next chain if it's to be immediately executed
  675. // as the child will run this chain.
  676. if (command.should_immediately_execute_next)
  677. command_copy.next_chain.clear();
  678. auto job = Job::create(child, pgid, cmd.build(), find_last_job_id() + 1, move(command_copy));
  679. jobs.set((u64)child, job);
  680. job->on_exit = [this](auto job) {
  681. if (!job->exited())
  682. return;
  683. if (job->is_running_in_background() && job->should_announce_exit())
  684. fprintf(stderr, "Shell: Job %" PRIu64 "(%s) exited\n", job->job_id(), job->cmd().characters());
  685. last_return_code = job->exit_code();
  686. job->disown();
  687. run_tail(job);
  688. };
  689. fds.collect();
  690. return *job;
  691. }
  692. void Shell::run_tail(const AST::NodeWithAction& next_in_chain, int head_exit_code)
  693. {
  694. auto evaluate = [&] {
  695. if (next_in_chain.node->would_execute()) {
  696. next_in_chain.node->run(*this);
  697. return;
  698. }
  699. auto commands = next_in_chain.node->to_lazy_evaluated_commands(*this);
  700. run_commands(commands);
  701. };
  702. switch (next_in_chain.action) {
  703. case AST::NodeWithAction::And:
  704. if (head_exit_code == 0)
  705. evaluate();
  706. break;
  707. case AST::NodeWithAction::Or:
  708. if (head_exit_code != 0)
  709. evaluate();
  710. break;
  711. case AST::NodeWithAction::Sequence:
  712. evaluate();
  713. break;
  714. }
  715. }
  716. void Shell::run_tail(RefPtr<Job> job)
  717. {
  718. if (auto cmd = job->command_ptr()) {
  719. deferred_invoke([=, this](auto&) {
  720. for (auto& next_in_chain : cmd->next_chain) {
  721. run_tail(next_in_chain, job->exit_code());
  722. }
  723. });
  724. }
  725. }
  726. NonnullRefPtrVector<Job> Shell::run_commands(Vector<AST::Command>& commands)
  727. {
  728. NonnullRefPtrVector<Job> spawned_jobs;
  729. for (auto& command : commands) {
  730. #ifdef SH_DEBUG
  731. dbg() << "Command";
  732. for (auto& arg : command.argv)
  733. dbg() << "argv: " << arg;
  734. for (auto& redir : command.redirections) {
  735. if (redir.is_path_redirection()) {
  736. auto path_redir = (const AST::PathRedirection*)&redir;
  737. dbg() << "redir path " << (int)path_redir->direction << " " << path_redir->path << " <-> " << path_redir->fd;
  738. } else if (redir.is_fd_redirection()) {
  739. auto* fdredir = (const AST::FdRedirection*)&redir;
  740. dbg() << "redir fd " << fdredir->source_fd << " -> " << fdredir->dest_fd;
  741. } else if (redir.is_close_redirection()) {
  742. auto close_redir = (const AST::CloseRedirection*)&redir;
  743. dbg() << "close fd " << close_redir->fd;
  744. } else {
  745. ASSERT_NOT_REACHED();
  746. }
  747. }
  748. #endif
  749. auto job = run_command(command);
  750. if (!job)
  751. continue;
  752. spawned_jobs.append(*job);
  753. if (command.should_wait) {
  754. block_on_job(job);
  755. } else {
  756. job->set_running_in_background(true);
  757. if (!command.is_pipe_source && command.should_notify_if_in_background)
  758. job->set_should_announce_exit(true);
  759. }
  760. }
  761. return spawned_jobs;
  762. }
  763. bool Shell::run_file(const String& filename, bool explicitly_invoked)
  764. {
  765. TemporaryChange script_change { current_script, filename };
  766. TemporaryChange interactive_change { m_is_interactive, false };
  767. auto file_result = Core::File::open(filename, Core::File::ReadOnly);
  768. if (file_result.is_error()) {
  769. if (explicitly_invoked)
  770. fprintf(stderr, "Failed to open %s: %s\n", filename.characters(), file_result.error().characters());
  771. else
  772. dbg() << "open() failed for '" << filename << "' with " << file_result.error();
  773. return false;
  774. }
  775. auto file = file_result.value();
  776. auto data = file->read_all();
  777. run_command(data);
  778. return true;
  779. }
  780. void Shell::restore_ios()
  781. {
  782. if (m_is_subshell)
  783. return;
  784. tcsetattr(0, TCSANOW, &termios);
  785. tcsetpgrp(STDOUT_FILENO, m_pid);
  786. tcsetpgrp(STDIN_FILENO, m_pid);
  787. }
  788. void Shell::block_on_job(RefPtr<Job> job)
  789. {
  790. TemporaryChange<const Job*> current_job { m_current_job, job.ptr() };
  791. if (!job)
  792. return;
  793. if (job->is_suspended())
  794. return; // We cannot wait for a suspended job.
  795. ScopeGuard io_restorer { [&]() {
  796. if (job->exited() && !job->is_running_in_background()) {
  797. restore_ios();
  798. }
  799. } };
  800. Core::EventLoop loop;
  801. job->on_exit = [&, old_exit = move(job->on_exit)](auto job) {
  802. if (old_exit)
  803. old_exit(job);
  804. loop.quit(0);
  805. };
  806. if (job->exited())
  807. return;
  808. loop.exec();
  809. }
  810. String Shell::get_history_path()
  811. {
  812. StringBuilder builder;
  813. builder.append(home);
  814. builder.append("/.history");
  815. return builder.to_string();
  816. }
  817. String Shell::escape_token(const String& token)
  818. {
  819. StringBuilder builder;
  820. for (auto c : token) {
  821. switch (c) {
  822. case '\'':
  823. case '"':
  824. case '$':
  825. case '|':
  826. case '>':
  827. case '<':
  828. case '&':
  829. case '\\':
  830. case ' ':
  831. builder.append('\\');
  832. break;
  833. default:
  834. break;
  835. }
  836. builder.append(c);
  837. }
  838. return builder.build();
  839. }
  840. String Shell::unescape_token(const String& token)
  841. {
  842. StringBuilder builder;
  843. enum {
  844. Free,
  845. Escaped
  846. } state { Free };
  847. for (auto c : token) {
  848. switch (state) {
  849. case Escaped:
  850. builder.append(c);
  851. state = Free;
  852. break;
  853. case Free:
  854. if (c == '\\')
  855. state = Escaped;
  856. else
  857. builder.append(c);
  858. break;
  859. }
  860. }
  861. if (state == Escaped)
  862. builder.append('\\');
  863. return builder.build();
  864. }
  865. void Shell::cache_path()
  866. {
  867. if (!cached_path.is_empty())
  868. cached_path.clear_with_capacity();
  869. // Add shell builtins to the cache.
  870. for (const auto& builtin_name : builtin_names)
  871. cached_path.append(escape_token(builtin_name));
  872. // Add aliases to the cache.
  873. for (const auto& alias : m_aliases) {
  874. auto name = escape_token(alias.key);
  875. if (cached_path.contains_slow(name))
  876. continue;
  877. cached_path.append(name);
  878. }
  879. String path = getenv("PATH");
  880. if (!path.is_empty()) {
  881. auto directories = path.split(':');
  882. for (const auto& directory : directories) {
  883. Core::DirIterator programs(directory.characters(), Core::DirIterator::SkipDots);
  884. while (programs.has_next()) {
  885. auto program = programs.next_path();
  886. String program_path = String::format("%s/%s", directory.characters(), program.characters());
  887. auto escaped_name = escape_token(program);
  888. if (cached_path.contains_slow(escaped_name))
  889. continue;
  890. if (access(program_path.characters(), X_OK) == 0)
  891. cached_path.append(escaped_name);
  892. }
  893. }
  894. }
  895. quick_sort(cached_path);
  896. }
  897. void Shell::add_entry_to_cache(const String& entry)
  898. {
  899. size_t index = 0;
  900. auto match = binary_search(
  901. cached_path.span(), entry, [](const String& name, const String& program) -> int {
  902. return strcmp(name.characters(), program.characters());
  903. },
  904. &index);
  905. if (match)
  906. return;
  907. while (index < cached_path.size() && strcmp(cached_path[index].characters(), entry.characters()) < 0) {
  908. index++;
  909. }
  910. cached_path.insert(index, entry);
  911. }
  912. void Shell::highlight(Line::Editor& editor) const
  913. {
  914. auto line = editor.line();
  915. Parser parser(line);
  916. auto ast = parser.parse();
  917. if (!ast)
  918. return;
  919. ast->highlight_in_editor(editor, const_cast<Shell&>(*this));
  920. }
  921. Vector<Line::CompletionSuggestion> Shell::complete()
  922. {
  923. auto line = m_editor->line(m_editor->cursor());
  924. Parser parser(line);
  925. auto ast = parser.parse();
  926. if (!ast)
  927. return {};
  928. return ast->complete_for_editor(*this, line.length());
  929. }
  930. Vector<Line::CompletionSuggestion> Shell::complete_path(const String& base, const String& part, size_t offset)
  931. {
  932. auto token = offset ? part.substring_view(0, offset) : "";
  933. StringView original_token = token;
  934. String path;
  935. ssize_t last_slash = token.length() - 1;
  936. while (last_slash >= 0 && token[last_slash] != '/')
  937. --last_slash;
  938. StringBuilder path_builder;
  939. auto init_slash_part = token.substring_view(0, last_slash + 1);
  940. auto last_slash_part = token.substring_view(last_slash + 1, token.length() - last_slash - 1);
  941. // Depending on the base, we will have to prepend cwd.
  942. if (base.is_empty()) {
  943. // '' /foo -> absolute
  944. // '' foo -> relative
  945. if (!token.starts_with('/'))
  946. path_builder.append(cwd);
  947. path_builder.append('/');
  948. path_builder.append(init_slash_part);
  949. } else {
  950. // /foo * -> absolute
  951. // foo * -> relative
  952. if (!base.starts_with('/'))
  953. path_builder.append(cwd);
  954. path_builder.append('/');
  955. path_builder.append(base);
  956. path_builder.append('/');
  957. path_builder.append(init_slash_part);
  958. }
  959. path = path_builder.build();
  960. token = last_slash_part;
  961. // the invariant part of the token is actually just the last segment
  962. // e. in `cd /foo/bar', 'bar' is the invariant
  963. // since we are not suggesting anything starting with
  964. // `/foo/', but rather just `bar...'
  965. auto token_length = escape_token(token).length();
  966. if (m_editor)
  967. m_editor->suggest(token_length, original_token.length() - token_length);
  968. // only suggest dot-files if path starts with a dot
  969. Core::DirIterator files(path,
  970. token.starts_with('.') ? Core::DirIterator::SkipParentAndBaseDir : Core::DirIterator::SkipDots);
  971. Vector<Line::CompletionSuggestion> suggestions;
  972. while (files.has_next()) {
  973. auto file = files.next_path();
  974. if (file.starts_with(token)) {
  975. struct stat program_status;
  976. String file_path = String::format("%s/%s", path.characters(), file.characters());
  977. int stat_error = stat(file_path.characters(), &program_status);
  978. if (!stat_error) {
  979. if (S_ISDIR(program_status.st_mode)) {
  980. suggestions.append({ escape_token(file), "/" });
  981. } else {
  982. suggestions.append({ escape_token(file), " " });
  983. }
  984. suggestions.last().input_offset = token_length;
  985. }
  986. }
  987. }
  988. return suggestions;
  989. }
  990. Vector<Line::CompletionSuggestion> Shell::complete_program_name(const String& name, size_t offset)
  991. {
  992. auto match = binary_search(cached_path.span(), name, [](const String& name, const String& program) -> int {
  993. return strncmp(name.characters(), program.characters(), name.length());
  994. });
  995. if (!match)
  996. return complete_path("", name, offset);
  997. String completion = *match;
  998. auto token_length = escape_token(name).length();
  999. if (m_editor)
  1000. m_editor->suggest(token_length, 0);
  1001. // Now that we have a program name starting with our token, we look at
  1002. // other program names starting with our token and cut off any mismatching
  1003. // characters.
  1004. Vector<Line::CompletionSuggestion> suggestions;
  1005. int index = match - cached_path.data();
  1006. for (int i = index - 1; i >= 0 && cached_path[i].starts_with(name); --i) {
  1007. suggestions.append({ cached_path[i], " " });
  1008. suggestions.last().input_offset = token_length;
  1009. }
  1010. for (size_t i = index + 1; i < cached_path.size() && cached_path[i].starts_with(name); ++i) {
  1011. suggestions.append({ cached_path[i], " " });
  1012. suggestions.last().input_offset = token_length;
  1013. }
  1014. suggestions.append({ cached_path[index], " " });
  1015. suggestions.last().input_offset = token_length;
  1016. return suggestions;
  1017. }
  1018. Vector<Line::CompletionSuggestion> Shell::complete_variable(const String& name, size_t offset)
  1019. {
  1020. Vector<Line::CompletionSuggestion> suggestions;
  1021. auto pattern = offset ? name.substring_view(0, offset) : "";
  1022. if (m_editor)
  1023. m_editor->suggest(offset);
  1024. // Look at local variables.
  1025. for (auto& frame : m_local_frames) {
  1026. for (auto& variable : frame.local_variables) {
  1027. if (variable.key.starts_with(pattern) && !suggestions.contains_slow(variable.key))
  1028. suggestions.append(variable.key);
  1029. }
  1030. }
  1031. // Look at the environment.
  1032. for (auto i = 0; environ[i]; ++i) {
  1033. auto entry = StringView { environ[i] };
  1034. if (entry.starts_with(pattern)) {
  1035. auto parts = entry.split_view('=');
  1036. if (parts.is_empty() || parts.first().is_empty())
  1037. continue;
  1038. String name = parts.first();
  1039. if (suggestions.contains_slow(name))
  1040. continue;
  1041. suggestions.append(move(name));
  1042. suggestions.last().input_offset = offset;
  1043. }
  1044. }
  1045. return suggestions;
  1046. }
  1047. Vector<Line::CompletionSuggestion> Shell::complete_user(const String& name, size_t offset)
  1048. {
  1049. Vector<Line::CompletionSuggestion> suggestions;
  1050. auto pattern = offset ? name.substring_view(0, offset) : "";
  1051. if (m_editor)
  1052. m_editor->suggest(offset);
  1053. Core::DirIterator di("/home", Core::DirIterator::SkipParentAndBaseDir);
  1054. if (di.has_error())
  1055. return suggestions;
  1056. while (di.has_next()) {
  1057. String name = di.next_path();
  1058. if (name.starts_with(pattern)) {
  1059. suggestions.append(name);
  1060. suggestions.last().input_offset = offset;
  1061. }
  1062. }
  1063. return suggestions;
  1064. }
  1065. Vector<Line::CompletionSuggestion> Shell::complete_option(const String& program_name, const String& option, size_t offset)
  1066. {
  1067. size_t start = 0;
  1068. while (start < option.length() && option[start] == '-' && start < 2)
  1069. ++start;
  1070. auto option_pattern = offset > start ? option.substring_view(start, offset - start) : "";
  1071. if (m_editor)
  1072. m_editor->suggest(offset);
  1073. Vector<Line::CompletionSuggestion> suggestions;
  1074. dbg() << "Shell::complete_option(" << program_name << ", " << option_pattern << ")";
  1075. // FIXME: Figure out how to do this stuff.
  1076. if (has_builtin(program_name)) {
  1077. // Complete builtins.
  1078. if (program_name == "setopt") {
  1079. bool negate = false;
  1080. if (option_pattern.starts_with("no_")) {
  1081. negate = true;
  1082. option_pattern = option_pattern.substring_view(3, option_pattern.length() - 3);
  1083. }
  1084. auto maybe_negate = [&](const StringView& view) {
  1085. static StringBuilder builder;
  1086. builder.clear();
  1087. builder.append("--");
  1088. if (negate)
  1089. builder.append("no_");
  1090. builder.append(view);
  1091. return builder.to_string();
  1092. };
  1093. #define __ENUMERATE_SHELL_OPTION(name, d_, descr_) \
  1094. if (StringView { #name }.starts_with(option_pattern)) { \
  1095. suggestions.append(maybe_negate(#name)); \
  1096. suggestions.last().input_offset = offset; \
  1097. }
  1098. ENUMERATE_SHELL_OPTIONS();
  1099. #undef __ENUMERATE_SHELL_OPTION
  1100. return suggestions;
  1101. }
  1102. }
  1103. return suggestions;
  1104. }
  1105. void Shell::bring_cursor_to_beginning_of_a_line() const
  1106. {
  1107. struct winsize ws;
  1108. if (m_editor) {
  1109. ws = m_editor->terminal_size();
  1110. } else {
  1111. if (ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) < 0) {
  1112. // Very annoying assumptions.
  1113. ws.ws_col = 80;
  1114. ws.ws_row = 25;
  1115. }
  1116. }
  1117. // Black with Cyan background.
  1118. constexpr auto default_mark = "\e[30;46m%\e[0m";
  1119. String eol_mark = getenv("PROMPT_EOL_MARK");
  1120. if (eol_mark.is_null())
  1121. eol_mark = default_mark;
  1122. size_t eol_mark_length = Line::Editor::actual_rendered_string_metrics(eol_mark).line_lengths.last();
  1123. if (eol_mark_length >= ws.ws_col) {
  1124. eol_mark = default_mark;
  1125. eol_mark_length = 1;
  1126. }
  1127. fputs(eol_mark.characters(), stderr);
  1128. for (auto i = eol_mark_length; i < ws.ws_col; ++i)
  1129. putc(' ', stderr);
  1130. putc('\r', stderr);
  1131. }
  1132. bool Shell::read_single_line()
  1133. {
  1134. restore_ios();
  1135. bring_cursor_to_beginning_of_a_line();
  1136. auto line_result = m_editor->get_line(prompt());
  1137. if (line_result.is_error()) {
  1138. if (line_result.error() == Line::Editor::Error::Eof || line_result.error() == Line::Editor::Error::Empty) {
  1139. // Pretend the user tried to execute builtin_exit()
  1140. m_complete_line_builder.clear();
  1141. run_command("exit");
  1142. return read_single_line();
  1143. } else {
  1144. m_complete_line_builder.clear();
  1145. Core::EventLoop::current().quit(1);
  1146. return false;
  1147. }
  1148. }
  1149. auto& line = line_result.value();
  1150. if (line.is_empty())
  1151. return true;
  1152. if (!m_complete_line_builder.is_empty())
  1153. m_complete_line_builder.append("\n");
  1154. m_complete_line_builder.append(line);
  1155. run_command(m_complete_line_builder.string_view());
  1156. m_editor->add_to_history(m_complete_line_builder.build());
  1157. m_complete_line_builder.clear();
  1158. return true;
  1159. }
  1160. void Shell::custom_event(Core::CustomEvent& event)
  1161. {
  1162. if (event.custom_type() == ReadLine) {
  1163. if (read_single_line())
  1164. Core::EventLoop::current().post_event(*this, make<Core::CustomEvent>(ShellEventType::ReadLine));
  1165. return;
  1166. }
  1167. }
  1168. void Shell::notify_child_event()
  1169. {
  1170. #ifdef ENSURE_WAITID_ONCE
  1171. static HashTable<pid_t> s_waited_for_pids;
  1172. #endif
  1173. Vector<u64> disowned_jobs;
  1174. // Workaround the fact that we can't receive *who* exactly changed state.
  1175. // The child might still be alive (and even running) when this signal is dispatched to us
  1176. // so just...repeat until we find a suitable child.
  1177. // This, of course, will mean that someone can send us a SIGCHILD and we'd be spinning here
  1178. // until the next child event we can actually handle.
  1179. bool found_child = false;
  1180. do {
  1181. // Ignore stray SIGCHLD when there are no jobs.
  1182. if (jobs.is_empty())
  1183. return;
  1184. for (auto& it : jobs) {
  1185. auto job_id = it.key;
  1186. auto& job = *it.value;
  1187. #ifdef ENSURE_WAITID_ONCE
  1188. // Theoretically, this should never trip, as jobs are removed from
  1189. // the job table when waitpid() succeeds *and* the child is dead.
  1190. ASSERT(!s_waited_for_pids.contains(job.pid()));
  1191. #endif
  1192. int wstatus = 0;
  1193. #ifdef SH_DEBUG
  1194. dbgln("waitpid({}) = ...", job.pid());
  1195. #endif
  1196. auto child_pid = waitpid(job.pid(), &wstatus, WNOHANG | WUNTRACED);
  1197. #ifdef SH_DEBUG
  1198. dbgln("... = {} - {}", child_pid, wstatus);
  1199. #endif
  1200. if (child_pid < 0) {
  1201. if (errno == ECHILD) {
  1202. // The child process went away before we could process its death, just assume it exited all ok.
  1203. // FIXME: This should never happen, the child should stay around until we do the waitpid above.
  1204. dbg() << "Child process gone, cannot get exit code for " << job_id;
  1205. child_pid = job.pid();
  1206. } else {
  1207. ASSERT_NOT_REACHED();
  1208. }
  1209. }
  1210. if (child_pid == 0) {
  1211. // If the child existed, but wasn't dead.
  1212. continue;
  1213. }
  1214. if (child_pid == job.pid()) {
  1215. if (WIFSIGNALED(wstatus) && !WIFSTOPPED(wstatus)) {
  1216. job.set_signalled(WTERMSIG(wstatus));
  1217. } else if (WIFEXITED(wstatus)) {
  1218. job.set_has_exit(WEXITSTATUS(wstatus));
  1219. } else if (WIFSTOPPED(wstatus)) {
  1220. job.unblock();
  1221. job.set_is_suspended(true);
  1222. }
  1223. found_child = true;
  1224. #ifdef ENSURE_WAITID_ONCE
  1225. s_waited_for_pids.set(child_pid);
  1226. #endif
  1227. }
  1228. if (job.should_be_disowned())
  1229. disowned_jobs.append(job_id);
  1230. }
  1231. for (auto job_id : disowned_jobs) {
  1232. jobs.remove(job_id);
  1233. }
  1234. } while (!found_child);
  1235. }
  1236. Shell::Shell()
  1237. : m_default_constructed(true)
  1238. {
  1239. push_frame().leak_frame();
  1240. int rc = gethostname(hostname, Shell::HostNameSize);
  1241. if (rc < 0)
  1242. perror("gethostname");
  1243. {
  1244. auto* pw = getpwuid(getuid());
  1245. if (pw) {
  1246. username = pw->pw_name;
  1247. home = pw->pw_dir;
  1248. setenv("HOME", pw->pw_dir, 1);
  1249. }
  1250. endpwent();
  1251. }
  1252. // For simplicity, start at the user's home directory.
  1253. this->cwd = home;
  1254. setenv("PWD", home.characters(), 1);
  1255. // Add the default PATH vars.
  1256. {
  1257. StringBuilder path;
  1258. path.append(getenv("PATH"));
  1259. if (path.length())
  1260. path.append(":");
  1261. path.append("/bin:/usr/bin:/usr/local/bin");
  1262. setenv("PATH", path.to_string().characters(), true);
  1263. }
  1264. cache_path();
  1265. }
  1266. Shell::Shell(Line::Editor& editor)
  1267. : m_editor(editor)
  1268. {
  1269. uid = getuid();
  1270. tcsetpgrp(0, getpgrp());
  1271. m_pid = getpid();
  1272. push_frame().leak_frame();
  1273. int rc = gethostname(hostname, Shell::HostNameSize);
  1274. if (rc < 0)
  1275. perror("gethostname");
  1276. auto istty = isatty(STDIN_FILENO);
  1277. m_is_interactive = istty;
  1278. if (istty) {
  1279. rc = ttyname_r(0, ttyname, Shell::TTYNameSize);
  1280. if (rc < 0)
  1281. perror("ttyname_r");
  1282. } else {
  1283. ttyname[0] = 0;
  1284. }
  1285. {
  1286. auto* cwd = getcwd(nullptr, 0);
  1287. this->cwd = cwd;
  1288. setenv("PWD", cwd, 1);
  1289. free(cwd);
  1290. }
  1291. {
  1292. auto* pw = getpwuid(getuid());
  1293. if (pw) {
  1294. username = pw->pw_name;
  1295. home = pw->pw_dir;
  1296. setenv("HOME", pw->pw_dir, 1);
  1297. }
  1298. endpwent();
  1299. }
  1300. directory_stack.append(cwd);
  1301. m_editor->load_history(get_history_path());
  1302. cache_path();
  1303. }
  1304. Shell::~Shell()
  1305. {
  1306. if (m_default_constructed)
  1307. return;
  1308. stop_all_jobs();
  1309. m_editor->save_history(get_history_path());
  1310. }
  1311. void Shell::stop_all_jobs()
  1312. {
  1313. if (!jobs.is_empty()) {
  1314. printf("Killing active jobs\n");
  1315. for (auto& entry : jobs) {
  1316. if (!entry.value->is_running_in_background()) {
  1317. #ifdef SH_DEBUG
  1318. dbg() << "Job " << entry.value->pid() << " is not running in background";
  1319. #endif
  1320. kill_job(entry.value, SIGCONT);
  1321. }
  1322. kill_job(entry.value, SIGHUP);
  1323. }
  1324. usleep(10000); // Wait for a bit before killing the job
  1325. for (auto& entry : jobs) {
  1326. #ifdef SH_DEBUG
  1327. dbg() << "Actively killing " << entry.value->pid() << "(" << entry.value->cmd() << ")";
  1328. #endif
  1329. if (killpg(entry.value->pgid(), SIGKILL) < 0) {
  1330. if (errno == ESRCH)
  1331. continue; // The process has exited all by itself.
  1332. perror("killpg(KILL)");
  1333. }
  1334. }
  1335. }
  1336. }
  1337. u64 Shell::find_last_job_id() const
  1338. {
  1339. u64 job_id = 0;
  1340. for (auto& entry : jobs) {
  1341. if (entry.value->job_id() > job_id)
  1342. job_id = entry.value->job_id();
  1343. }
  1344. return job_id;
  1345. }
  1346. const Job* Shell::find_job(u64 id)
  1347. {
  1348. for (auto& entry : jobs) {
  1349. if (entry.value->job_id() == id)
  1350. return entry.value;
  1351. }
  1352. return nullptr;
  1353. }
  1354. void Shell::kill_job(const Job* job, int sig)
  1355. {
  1356. if (!job)
  1357. return;
  1358. if (killpg(job->pgid(), sig) < 0)
  1359. perror("killpg(job)");
  1360. }
  1361. void Shell::save_to(JsonObject& object)
  1362. {
  1363. Core::Object::save_to(object);
  1364. object.set("working_directory", cwd);
  1365. object.set("username", username);
  1366. object.set("user_home_path", home);
  1367. object.set("user_id", uid);
  1368. object.set("directory_stack_size", directory_stack.size());
  1369. object.set("cd_history_size", cd_history.size());
  1370. // Jobs.
  1371. JsonArray job_objects;
  1372. for (auto& job_entry : jobs) {
  1373. JsonObject job_object;
  1374. job_object.set("pid", job_entry.value->pid());
  1375. job_object.set("pgid", job_entry.value->pgid());
  1376. job_object.set("running_time", job_entry.value->timer().elapsed());
  1377. job_object.set("command", job_entry.value->cmd());
  1378. job_object.set("is_running_in_background", job_entry.value->is_running_in_background());
  1379. job_objects.append(move(job_object));
  1380. }
  1381. object.set("jobs", move(job_objects));
  1382. }
  1383. void FileDescriptionCollector::collect()
  1384. {
  1385. for (auto fd : m_fds)
  1386. close(fd);
  1387. m_fds.clear();
  1388. }
  1389. FileDescriptionCollector::~FileDescriptionCollector()
  1390. {
  1391. collect();
  1392. }
  1393. void FileDescriptionCollector::add(int fd)
  1394. {
  1395. m_fds.append(fd);
  1396. }
  1397. SavedFileDescriptors::SavedFileDescriptors(const NonnullRefPtrVector<AST::Rewiring>& intended_rewirings)
  1398. {
  1399. for (auto& rewiring : intended_rewirings) {
  1400. int new_fd = dup(rewiring.source_fd);
  1401. if (new_fd < 0) {
  1402. if (errno != EBADF)
  1403. perror("dup");
  1404. // The fd that will be overwritten isn't open right now,
  1405. // it will be cleaned up by the exec()-side collector
  1406. // and we have nothing to do here, so just ignore this error.
  1407. continue;
  1408. }
  1409. auto flags = fcntl(new_fd, F_GETFL);
  1410. auto rc = fcntl(new_fd, F_SETFL, flags | FD_CLOEXEC);
  1411. ASSERT(rc == 0);
  1412. m_saves.append({ rewiring.source_fd, new_fd });
  1413. m_collector.add(new_fd);
  1414. }
  1415. }
  1416. SavedFileDescriptors::~SavedFileDescriptors()
  1417. {
  1418. for (auto& save : m_saves) {
  1419. if (dup2(save.saved, save.original) < 0) {
  1420. perror("dup2(~SavedFileDescriptors)");
  1421. continue;
  1422. }
  1423. }
  1424. }
  1425. }