Shell.cpp 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872
  1. /*
  2. * Copyright (c) 2020, The SerenityOS developers.
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include "Shell.h"
  27. #include "Execution.h"
  28. #include <AK/Function.h>
  29. #include <AK/LexicalPath.h>
  30. #include <AK/ScopeGuard.h>
  31. #include <AK/StringBuilder.h>
  32. #include <LibCore/ArgsParser.h>
  33. #include <LibCore/DirIterator.h>
  34. #include <LibCore/ElapsedTimer.h>
  35. #include <LibCore/Event.h>
  36. #include <LibCore/EventLoop.h>
  37. #include <LibCore/File.h>
  38. #include <LibLine/Editor.h>
  39. #include <errno.h>
  40. #include <fcntl.h>
  41. #include <pwd.h>
  42. #include <signal.h>
  43. #include <stdio.h>
  44. #include <stdlib.h>
  45. #include <string.h>
  46. #include <sys/mman.h>
  47. #include <sys/stat.h>
  48. #include <sys/utsname.h>
  49. #include <sys/wait.h>
  50. #include <termios.h>
  51. #include <unistd.h>
  52. // FIXME: We do not expand variables inside strings
  53. // if we want to be more sh-like, we should do that some day
  54. static constexpr bool HighlightVariablesInsideStrings = false;
  55. static bool s_disable_hyperlinks = false;
  56. extern RefPtr<Line::Editor> editor;
  57. //#define SH_DEBUG
  58. void Shell::print_path(const String& path)
  59. {
  60. if (s_disable_hyperlinks) {
  61. printf("%s", path.characters());
  62. return;
  63. }
  64. printf("\033]8;;file://%s%s\033\\%s\033]8;;\033\\", hostname, path.characters(), path.characters());
  65. }
  66. String Shell::prompt() const
  67. {
  68. auto build_prompt = [&]() -> String {
  69. auto* ps1 = getenv("PROMPT");
  70. if (!ps1) {
  71. if (uid == 0)
  72. return "# ";
  73. StringBuilder builder;
  74. builder.appendf("\033]0;%s@%s:%s\007", username.characters(), hostname, cwd.characters());
  75. 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());
  76. return builder.to_string();
  77. }
  78. StringBuilder builder;
  79. for (char* ptr = ps1; *ptr; ++ptr) {
  80. if (*ptr == '\\') {
  81. ++ptr;
  82. if (!*ptr)
  83. break;
  84. switch (*ptr) {
  85. case 'X':
  86. builder.append("\033]0;");
  87. break;
  88. case 'a':
  89. builder.append(0x07);
  90. break;
  91. case 'e':
  92. builder.append(0x1b);
  93. break;
  94. case 'u':
  95. builder.append(username);
  96. break;
  97. case 'h':
  98. builder.append(hostname);
  99. break;
  100. case 'w': {
  101. String home_path = getenv("HOME");
  102. if (cwd.starts_with(home_path)) {
  103. builder.append('~');
  104. builder.append(cwd.substring_view(home_path.length(), cwd.length() - home_path.length()));
  105. } else {
  106. builder.append(cwd);
  107. }
  108. break;
  109. }
  110. case 'p':
  111. builder.append(uid == 0 ? '#' : '$');
  112. break;
  113. }
  114. continue;
  115. }
  116. builder.append(*ptr);
  117. }
  118. return builder.to_string();
  119. };
  120. auto the_prompt = build_prompt();
  121. auto prompt_length = editor->actual_rendered_string_length(the_prompt);
  122. if (m_should_continue != ExitCodeOrContinuationRequest::Nothing) {
  123. const auto format_string = "\033[34m%.*-s\033[m";
  124. switch (m_should_continue) {
  125. case ExitCodeOrContinuationRequest::Pipe:
  126. return String::format(format_string, prompt_length, "pipe> ");
  127. case ExitCodeOrContinuationRequest::DoubleQuotedString:
  128. return String::format(format_string, prompt_length, "dquote> ");
  129. case ExitCodeOrContinuationRequest::SingleQuotedString:
  130. return String::format(format_string, prompt_length, "squote> ");
  131. default:
  132. break;
  133. }
  134. }
  135. return the_prompt;
  136. }
  137. int Shell::builtin_bg(int argc, const char** argv)
  138. {
  139. int job_id = -1;
  140. Core::ArgsParser parser;
  141. parser.add_positional_argument(job_id, "Job id to run in background", "job_id", Core::ArgsParser::Required::No);
  142. if (!parser.parse(argc, const_cast<char**>(argv), false))
  143. return 1;
  144. if (job_id == -1 && !jobs.is_empty())
  145. job_id = find_last_job_id();
  146. Job* job = nullptr;
  147. for (auto& entry : jobs) {
  148. if (entry.value->job_id() == (u64)job_id) {
  149. job = entry.value;
  150. break;
  151. }
  152. }
  153. if (!job) {
  154. if (job_id == -1) {
  155. printf("bg: no current job\n");
  156. } else {
  157. printf("bg: job with id %d not found\n", job_id);
  158. }
  159. return 1;
  160. }
  161. job->set_running_in_background(true);
  162. dbg() << "Resuming " << job->pid() << " (" << job->cmd() << ")";
  163. printf("Resuming job %llu - %s\n", job->job_id(), job->cmd().characters());
  164. if (killpg(job->pgid(), SIGCONT) < 0) {
  165. perror("killpg");
  166. return 1;
  167. }
  168. return 0;
  169. }
  170. int Shell::builtin_cd(int argc, const char** argv)
  171. {
  172. const char* arg_path = nullptr;
  173. Core::ArgsParser parser;
  174. parser.add_positional_argument(arg_path, "Path to change to", "path", Core::ArgsParser::Required::No);
  175. if (!parser.parse(argc, const_cast<char**>(argv), false))
  176. return 1;
  177. String new_path;
  178. if (!arg_path) {
  179. new_path = home;
  180. if (cd_history.is_empty() || cd_history.last() != home)
  181. cd_history.enqueue(home);
  182. } else {
  183. if (cd_history.is_empty() || cd_history.last() != arg_path)
  184. cd_history.enqueue(arg_path);
  185. if (strcmp(argv[1], "-") == 0) {
  186. char* oldpwd = getenv("OLDPWD");
  187. if (oldpwd == nullptr)
  188. return 1;
  189. new_path = oldpwd;
  190. } else if (arg_path[0] == '/') {
  191. new_path = argv[1];
  192. } else {
  193. StringBuilder builder;
  194. builder.append(cwd);
  195. builder.append('/');
  196. builder.append(arg_path);
  197. new_path = builder.to_string();
  198. }
  199. }
  200. LexicalPath lexical_path(new_path);
  201. if (!lexical_path.is_valid()) {
  202. printf("LexicalPath failed to canonicalize '%s'\n", new_path.characters());
  203. return 1;
  204. }
  205. const char* path = lexical_path.string().characters();
  206. struct stat st;
  207. int rc = stat(path, &st);
  208. if (rc < 0) {
  209. printf("stat(%s) failed: %s\n", path, strerror(errno));
  210. return 1;
  211. }
  212. if (!S_ISDIR(st.st_mode)) {
  213. printf("Not a directory: %s\n", path);
  214. return 1;
  215. }
  216. rc = chdir(path);
  217. if (rc < 0) {
  218. printf("chdir(%s) failed: %s\n", path, strerror(errno));
  219. return 1;
  220. }
  221. setenv("OLDPWD", cwd.characters(), 1);
  222. cwd = lexical_path.string();
  223. setenv("PWD", cwd.characters(), 1);
  224. return 0;
  225. }
  226. int Shell::builtin_cdh(int argc, const char** argv)
  227. {
  228. int index = -1;
  229. Core::ArgsParser parser;
  230. parser.add_positional_argument(index, "Index of the cd history entry (leave out for a list)", "index", Core::ArgsParser::Required::No);
  231. if (!parser.parse(argc, const_cast<char**>(argv), false))
  232. return 1;
  233. if (index == -1) {
  234. if (cd_history.size() == 0) {
  235. printf("cdh: no history available\n");
  236. return 0;
  237. }
  238. for (int i = cd_history.size() - 1; i >= 0; --i)
  239. printf("%lu: %s\n", cd_history.size() - i, cd_history.at(i).characters());
  240. return 0;
  241. }
  242. if (index < 1 || (size_t)index > cd_history.size()) {
  243. fprintf(stderr, "cdh: history index out of bounds: %d not in (0, %zu)\n", index, cd_history.size());
  244. return 1;
  245. }
  246. const char* path = cd_history.at(cd_history.size() - index).characters();
  247. const char* cd_args[] = { "cd", path };
  248. return Shell::builtin_cd(2, cd_args);
  249. }
  250. int Shell::builtin_dirs(int argc, const char** argv)
  251. {
  252. // The first directory in the stack is ALWAYS the current directory
  253. directory_stack.at(0) = cwd.characters();
  254. if (argc == 1) {
  255. for (auto& directory : directory_stack) {
  256. print_path(directory);
  257. fputc(' ', stdout);
  258. }
  259. printf("\n");
  260. return 0;
  261. }
  262. bool clear = false;
  263. bool print = false;
  264. bool number_when_printing = false;
  265. Vector<const char*> paths;
  266. Core::ArgsParser parser;
  267. parser.add_option(clear, "Clear the directory stack", "clear", 'c');
  268. parser.add_option(print, "Print directory entries", "print", 'p');
  269. parser.add_option(number_when_printing, "Number the directories in the stack when printing", "number", 'v');
  270. parser.add_positional_argument(paths, "Extra paths to put on the stack", "paths", Core::ArgsParser::Required::No);
  271. if (!parser.parse(argc, const_cast<char**>(argv), false))
  272. return 1;
  273. // -v implies -p
  274. print = print || number_when_printing;
  275. if (clear) {
  276. for (size_t i = 1; i < directory_stack.size(); i++)
  277. directory_stack.remove(i);
  278. }
  279. for (auto& path : paths)
  280. directory_stack.append(path);
  281. if (print) {
  282. auto idx = 0;
  283. for (auto& directory : directory_stack) {
  284. if (number_when_printing)
  285. printf("%d ", idx++);
  286. print_path(directory);
  287. fputc('\n', stdout);
  288. }
  289. }
  290. return 0;
  291. }
  292. int Shell::builtin_exit(int, const char**)
  293. {
  294. if (!jobs.is_empty()) {
  295. if (!m_should_ignore_jobs_on_next_exit) {
  296. printf("Shell: Hey dude, you have %zu active job%s, run 'exit' again to really exit.\n", jobs.size(), jobs.size() > 1 ? "s" : "");
  297. m_should_ignore_jobs_on_next_exit = true;
  298. return 1;
  299. }
  300. }
  301. stop_all_jobs();
  302. save_history();
  303. printf("Good-bye!\n");
  304. exit(0);
  305. return 0;
  306. }
  307. int Shell::builtin_export(int argc, const char** argv)
  308. {
  309. Vector<const char*> vars;
  310. Core::ArgsParser parser;
  311. parser.add_positional_argument(vars, "List of variable[=value]'s", "values", Core::ArgsParser::Required::No);
  312. if (!parser.parse(argc, const_cast<char**>(argv), false))
  313. return 1;
  314. if (vars.size() == 0) {
  315. for (int i = 0; environ[i]; ++i)
  316. puts(environ[i]);
  317. return 0;
  318. }
  319. int return_value = 0;
  320. for (auto& value : vars) {
  321. auto parts = String { value }.split_limit('=', 2);
  322. if (parts.size() == 1) {
  323. parts.append("");
  324. }
  325. int setenv_return = setenv(parts[0].characters(), parts[1].characters(), 1);
  326. if (setenv_return != 0) {
  327. perror("setenv");
  328. return_value = 1;
  329. break;
  330. }
  331. if (parts[0] == "PATH")
  332. cache_path();
  333. }
  334. return return_value;
  335. }
  336. int Shell::builtin_fg(int argc, const char** argv)
  337. {
  338. int job_id = -1;
  339. Core::ArgsParser parser;
  340. parser.add_positional_argument(job_id, "Job id to bring to foreground", "job_id", Core::ArgsParser::Required::No);
  341. if (!parser.parse(argc, const_cast<char**>(argv), false))
  342. return 1;
  343. if (job_id == -1 && !jobs.is_empty())
  344. job_id = find_last_job_id();
  345. Job* job = nullptr;
  346. for (auto& entry : jobs) {
  347. if (entry.value->job_id() == (u64)job_id) {
  348. job = entry.value;
  349. break;
  350. }
  351. }
  352. if (!job) {
  353. if (job_id == -1) {
  354. printf("fg: no current job\n");
  355. } else {
  356. printf("fg: job with id %d not found\n", job_id);
  357. }
  358. return 1;
  359. }
  360. job->set_running_in_background(false);
  361. dbg() << "Resuming " << job->pid() << " (" << job->cmd() << ")";
  362. printf("Resuming job %llu - %s\n", job->job_id(), job->cmd().characters());
  363. if (killpg(job->pgid(), SIGCONT) < 0) {
  364. perror("killpg");
  365. return 1;
  366. }
  367. int return_value = 0;
  368. auto current_pid = getpid();
  369. auto current_pgid = getpgid(current_pid);
  370. setpgid(job->pid(), job->pgid());
  371. tcsetpgrp(0, job->pgid());
  372. SpawnedProcess process { job->cmd(), job->pid() };
  373. do {
  374. if (wait_for_pid(process, true, return_value) == IterationDecision::Break)
  375. break;
  376. } while (errno == EINTR);
  377. setpgid(current_pid, current_pgid);
  378. tcsetpgrp(0, current_pgid);
  379. return return_value;
  380. }
  381. int Shell::builtin_disown(int argc, const char** argv)
  382. {
  383. Vector<const char*> str_job_ids;
  384. Core::ArgsParser parser;
  385. parser.add_positional_argument(str_job_ids, "Id of the jobs to disown (omit for current job)", "job_ids", Core::ArgsParser::Required::No);
  386. if (!parser.parse(argc, const_cast<char**>(argv), false))
  387. return 1;
  388. Vector<size_t> job_ids;
  389. for (auto& job_id : str_job_ids) {
  390. bool ok;
  391. auto id = StringView { job_id }.to_uint(ok);
  392. if (ok)
  393. job_ids.append(id);
  394. else
  395. printf("Invalid job id: %s\n", job_id);
  396. }
  397. if (job_ids.is_empty())
  398. job_ids.append(jobs.size() - 1);
  399. Vector<size_t> keys_of_jobs_to_disown;
  400. for (auto id : job_ids) {
  401. bool found = false;
  402. for (auto& entry : jobs) {
  403. if (entry.value->job_id() == id) {
  404. keys_of_jobs_to_disown.append(entry.key);
  405. found = true;
  406. break;
  407. }
  408. }
  409. if (!found) {
  410. printf("job with id %zu not found\n", id);
  411. }
  412. }
  413. if (keys_of_jobs_to_disown.is_empty()) {
  414. if (str_job_ids.is_empty()) {
  415. printf("disown: no current job\n");
  416. }
  417. // An error message has already been printed about the nonexistence of each listed job.
  418. return 1;
  419. }
  420. for (auto job_index : keys_of_jobs_to_disown) {
  421. auto job = jobs.get(job_index).value();
  422. job->deactivate();
  423. if (!job->is_running_in_background())
  424. printf("disown warning: job %llu is currently not running, 'kill -%d %d' to make it continue\n", job->job_id(), SIGCONT, job->pid());
  425. jobs.remove(job_index);
  426. }
  427. return 0;
  428. }
  429. int Shell::builtin_history(int, const char**)
  430. {
  431. for (size_t i = 0; i < editor->history().size(); ++i) {
  432. printf("%6zu %s\n", i, editor->history()[i].characters());
  433. }
  434. return 0;
  435. }
  436. int Shell::builtin_jobs(int argc, const char** argv)
  437. {
  438. bool list = false, show_pid = false;
  439. Core::ArgsParser parser;
  440. parser.add_option(list, "List all information about jobs", "list", 'l');
  441. parser.add_option(show_pid, "Display the PID of the jobs", "pid", 'p');
  442. if (!parser.parse(argc, const_cast<char**>(argv), false))
  443. return 1;
  444. enum {
  445. Basic,
  446. OnlyPID,
  447. ListAll,
  448. } mode { Basic };
  449. if (show_pid)
  450. mode = OnlyPID;
  451. if (list)
  452. mode = ListAll;
  453. for (auto& job : jobs) {
  454. auto pid = job.value->pid();
  455. int wstatus;
  456. auto rc = waitpid(pid, &wstatus, WNOHANG);
  457. if (rc == -1) {
  458. perror("waitpid");
  459. return 1;
  460. }
  461. auto status = "running";
  462. if (rc != 0) {
  463. if (WIFEXITED(wstatus))
  464. status = "exited";
  465. if (WIFSTOPPED(wstatus))
  466. status = "stopped";
  467. if (WIFSIGNALED(wstatus))
  468. status = "signaled";
  469. }
  470. char background_indicator = '-';
  471. if (job.value->is_running_in_background())
  472. background_indicator = '+';
  473. switch (mode) {
  474. case Basic:
  475. printf("[%llu] %c %s %s\n", job.value->job_id(), background_indicator, status, job.value->cmd().characters());
  476. break;
  477. case OnlyPID:
  478. printf("[%llu] %c %d %s %s\n", job.value->job_id(), background_indicator, pid, status, job.value->cmd().characters());
  479. break;
  480. case ListAll:
  481. printf("[%llu] %c %d %d %s %s\n", job.value->job_id(), background_indicator, pid, job.value->pgid(), status, job.value->cmd().characters());
  482. break;
  483. }
  484. }
  485. return 0;
  486. }
  487. int Shell::builtin_popd(int argc, const char** argv)
  488. {
  489. if (directory_stack.size() <= 1) {
  490. fprintf(stderr, "Shell: popd: directory stack empty\n");
  491. return 1;
  492. }
  493. bool should_not_switch = false;
  494. String path = directory_stack.take_last();
  495. Core::ArgsParser parser;
  496. parser.add_option(should_not_switch, "Do not switch dirs", "no-switch", 'n');
  497. if (!parser.parse(argc, const_cast<char**>(argv), false))
  498. return 1;
  499. bool should_switch = !should_not_switch;
  500. // When no arguments are given, popd removes the top directory from the stack and performs a cd to the new top directory.
  501. if (argc == 1) {
  502. int rc = chdir(path.characters());
  503. if (rc < 0) {
  504. fprintf(stderr, "chdir(%s) failed: %s\n", path.characters(), strerror(errno));
  505. return 1;
  506. }
  507. cwd = path;
  508. return 0;
  509. }
  510. LexicalPath lexical_path(path.characters());
  511. if (!lexical_path.is_valid()) {
  512. fprintf(stderr, "LexicalPath failed to canonicalize '%s'\n", path.characters());
  513. return 1;
  514. }
  515. const char* real_path = lexical_path.string().characters();
  516. struct stat st;
  517. int rc = stat(real_path, &st);
  518. if (rc < 0) {
  519. fprintf(stderr, "stat(%s) failed: %s\n", real_path, strerror(errno));
  520. return 1;
  521. }
  522. if (!S_ISDIR(st.st_mode)) {
  523. fprintf(stderr, "Not a directory: %s\n", real_path);
  524. return 1;
  525. }
  526. if (should_switch) {
  527. int rc = chdir(real_path);
  528. if (rc < 0) {
  529. fprintf(stderr, "chdir(%s) failed: %s\n", real_path, strerror(errno));
  530. return 1;
  531. }
  532. cwd = lexical_path.string();
  533. }
  534. return 0;
  535. }
  536. int Shell::builtin_pushd(int argc, const char** argv)
  537. {
  538. StringBuilder path_builder;
  539. bool should_switch = true;
  540. // From the BASH reference manual: https://www.gnu.org/software/bash/manual/html_node/Directory-Stack-Builtins.html
  541. // With no arguments, pushd exchanges the top two directories and makes the new top the current directory.
  542. if (argc == 1) {
  543. if (directory_stack.size() < 2) {
  544. fprintf(stderr, "pushd: no other directory\n");
  545. return 1;
  546. }
  547. String dir1 = directory_stack.take_first();
  548. String dir2 = directory_stack.take_first();
  549. directory_stack.insert(0, dir2);
  550. directory_stack.insert(1, dir1);
  551. int rc = chdir(dir2.characters());
  552. if (rc < 0) {
  553. fprintf(stderr, "chdir(%s) failed: %s\n", dir2.characters(), strerror(errno));
  554. return 1;
  555. }
  556. cwd = dir2;
  557. return 0;
  558. }
  559. // Let's assume the user's typed in 'pushd <dir>'
  560. if (argc == 2) {
  561. directory_stack.append(cwd.characters());
  562. if (argv[1][0] == '/') {
  563. path_builder.append(argv[1]);
  564. } else {
  565. path_builder.appendf("%s/%s", cwd.characters(), argv[1]);
  566. }
  567. } else if (argc == 3) {
  568. directory_stack.append(cwd.characters());
  569. for (int i = 1; i < argc; i++) {
  570. const char* arg = argv[i];
  571. if (arg[0] != '-') {
  572. if (arg[0] == '/') {
  573. path_builder.append(arg);
  574. } else
  575. path_builder.appendf("%s/%s", cwd.characters(), arg);
  576. }
  577. if (!strcmp(arg, "-n"))
  578. should_switch = false;
  579. }
  580. }
  581. LexicalPath lexical_path(path_builder.to_string());
  582. if (!lexical_path.is_valid()) {
  583. fprintf(stderr, "LexicalPath failed to canonicalize '%s'\n", path_builder.to_string().characters());
  584. return 1;
  585. }
  586. const char* real_path = lexical_path.string().characters();
  587. struct stat st;
  588. int rc = stat(real_path, &st);
  589. if (rc < 0) {
  590. fprintf(stderr, "stat(%s) failed: %s\n", real_path, strerror(errno));
  591. return 1;
  592. }
  593. if (!S_ISDIR(st.st_mode)) {
  594. fprintf(stderr, "Not a directory: %s\n", real_path);
  595. return 1;
  596. }
  597. if (should_switch) {
  598. int rc = chdir(real_path);
  599. if (rc < 0) {
  600. fprintf(stderr, "chdir(%s) failed: %s\n", real_path, strerror(errno));
  601. return 1;
  602. }
  603. cwd = lexical_path.string();
  604. }
  605. return 0;
  606. }
  607. int Shell::builtin_pwd(int, const char**)
  608. {
  609. print_path(cwd);
  610. fputc('\n', stdout);
  611. return 0;
  612. }
  613. int Shell::builtin_time(int argc, const char** argv)
  614. {
  615. Vector<const char*> args;
  616. Core::ArgsParser parser;
  617. parser.add_positional_argument(args, "Command to execute with arguments", "command", Core::ArgsParser::Required::Yes);
  618. if (!parser.parse(argc, const_cast<char**>(argv), false))
  619. return 1;
  620. StringBuilder builder;
  621. builder.join(' ', args);
  622. Core::ElapsedTimer timer;
  623. timer.start();
  624. auto exit_code = run_command(builder.string_view());
  625. if (!exit_code.has_value()) {
  626. printf("Shell: Incomplete command: %s\n", builder.to_string().characters());
  627. exit_code = 1;
  628. }
  629. printf("Time: %d ms\n", timer.elapsed());
  630. return exit_code.value();
  631. }
  632. int Shell::builtin_umask(int argc, const char** argv)
  633. {
  634. const char* mask_text = nullptr;
  635. Core::ArgsParser parser;
  636. parser.add_positional_argument(mask_text, "New mask (omit to get current mask)", "octal-mask", Core::ArgsParser::Required::No);
  637. if (!parser.parse(argc, const_cast<char**>(argv), false))
  638. return 1;
  639. if (!mask_text) {
  640. mode_t old_mask = umask(0);
  641. printf("%#o\n", old_mask);
  642. umask(old_mask);
  643. return 0;
  644. }
  645. unsigned mask;
  646. int matches = sscanf(mask_text, "%o", &mask);
  647. if (matches == 1) {
  648. umask(mask);
  649. return 0;
  650. }
  651. return 0;
  652. }
  653. int Shell::builtin_unset(int argc, const char** argv)
  654. {
  655. Vector<const char*> vars;
  656. Core::ArgsParser parser;
  657. parser.add_positional_argument(vars, "List of variables", "variables", Core::ArgsParser::Required::Yes);
  658. if (!parser.parse(argc, const_cast<char**>(argv), false))
  659. return 1;
  660. for (auto& value : vars)
  661. unsetenv(value);
  662. return 0;
  663. }
  664. bool Shell::run_builtin(int argc, const char** argv, int& retval)
  665. {
  666. if (argc == 0)
  667. return false;
  668. StringView name { argv[0] };
  669. #define __ENUMERATE_SHELL_BUILTIN(builtin) \
  670. if (name == #builtin) { \
  671. retval = builtin_##builtin(argc, argv); \
  672. return true; \
  673. }
  674. ENUMERATE_SHELL_BUILTINS();
  675. #undef __ENUMERATE_SHELL_BUILTIN
  676. return false;
  677. }
  678. String Shell::expand_tilde(const String& expression)
  679. {
  680. ASSERT(expression.starts_with('~'));
  681. StringBuilder login_name;
  682. size_t first_slash_index = expression.length();
  683. for (size_t i = 1; i < expression.length(); ++i) {
  684. if (expression[i] == '/') {
  685. first_slash_index = i;
  686. break;
  687. }
  688. login_name.append(expression[i]);
  689. }
  690. StringBuilder path;
  691. for (size_t i = first_slash_index; i < expression.length(); ++i)
  692. path.append(expression[i]);
  693. if (login_name.is_empty()) {
  694. const char* home = getenv("HOME");
  695. if (!home) {
  696. auto passwd = getpwuid(getuid());
  697. ASSERT(passwd && passwd->pw_dir);
  698. return String::format("%s/%s", passwd->pw_dir, path.to_string().characters());
  699. }
  700. return String::format("%s/%s", home, path.to_string().characters());
  701. }
  702. auto passwd = getpwnam(login_name.to_string().characters());
  703. if (!passwd)
  704. return expression;
  705. ASSERT(passwd->pw_dir);
  706. return String::format("%s/%s", passwd->pw_dir, path.to_string().characters());
  707. }
  708. bool Shell::is_glob(const StringView& s)
  709. {
  710. for (size_t i = 0; i < s.length(); i++) {
  711. char c = s.characters_without_null_termination()[i];
  712. if (c == '*' || c == '?')
  713. return true;
  714. }
  715. return false;
  716. }
  717. Vector<StringView> Shell::split_path(const StringView& path)
  718. {
  719. Vector<StringView> parts;
  720. size_t substart = 0;
  721. for (size_t i = 0; i < path.length(); i++) {
  722. char ch = path.characters_without_null_termination()[i];
  723. if (ch != '/')
  724. continue;
  725. size_t sublen = i - substart;
  726. if (sublen != 0)
  727. parts.append(path.substring_view(substart, sublen));
  728. parts.append(path.substring_view(i, 1));
  729. substart = i + 1;
  730. }
  731. size_t taillen = path.length() - substart;
  732. if (taillen != 0)
  733. parts.append(path.substring_view(substart, taillen));
  734. return parts;
  735. }
  736. Vector<String> Shell::expand_globs(const StringView& path, const StringView& base)
  737. {
  738. auto parts = split_path(path);
  739. StringBuilder builder;
  740. builder.append(base);
  741. Vector<String> res;
  742. for (size_t i = 0; i < parts.size(); ++i) {
  743. auto& part = parts[i];
  744. if (!is_glob(part)) {
  745. builder.append(part);
  746. continue;
  747. }
  748. // Found a glob.
  749. String new_base = builder.to_string();
  750. StringView new_base_v = new_base;
  751. if (new_base_v.is_empty())
  752. new_base_v = ".";
  753. Core::DirIterator di(new_base_v, Core::DirIterator::SkipParentAndBaseDir);
  754. if (di.has_error()) {
  755. return res;
  756. }
  757. while (di.has_next()) {
  758. String name = di.next_path();
  759. // Dotfiles have to be explicitly requested
  760. if (name[0] == '.' && part[0] != '.')
  761. continue;
  762. if (name.matches(part, CaseSensitivity::CaseSensitive)) {
  763. StringBuilder nested_base;
  764. nested_base.append(new_base);
  765. nested_base.append(name);
  766. StringView remaining_path = path.substring_view_starting_after_substring(part);
  767. Vector<String> nested_res = expand_globs(remaining_path, nested_base.to_string());
  768. for (auto& s : nested_res)
  769. res.append(s);
  770. }
  771. }
  772. return res;
  773. }
  774. // Found no globs.
  775. String new_path = builder.to_string();
  776. if (access(new_path.characters(), F_OK) == 0)
  777. res.append(new_path);
  778. return res;
  779. }
  780. Vector<String> Shell::expand_parameters(const StringView& param) const
  781. {
  782. if (!param.starts_with('$'))
  783. return { param };
  784. String variable_name = String(param.substring_view(1, param.length() - 1));
  785. if (variable_name == "?")
  786. return { String::number(last_return_code) };
  787. else if (variable_name == "$")
  788. return { String::number(getpid()) };
  789. char* env_value = getenv(variable_name.characters());
  790. if (env_value == nullptr)
  791. return { "" };
  792. Vector<String> res;
  793. String str_env_value = String(env_value);
  794. const auto& split_text = str_env_value.split_view(' ');
  795. for (auto& part : split_text)
  796. res.append(part);
  797. return res;
  798. }
  799. Vector<String> Shell::process_arguments(const Vector<Token>& args)
  800. {
  801. Vector<String> argv_string;
  802. for (auto& arg : args) {
  803. if (arg.type == Token::Comment)
  804. continue;
  805. // This will return the text passed in if it wasn't a variable
  806. // This lets us just loop over its values
  807. auto expanded_parameters = expand_parameters(arg.text);
  808. for (auto& exp_arg : expanded_parameters) {
  809. if (exp_arg.starts_with('~'))
  810. exp_arg = expand_tilde(exp_arg);
  811. auto expanded_globs = expand_globs(exp_arg, "");
  812. for (auto& path : expanded_globs)
  813. argv_string.append(path);
  814. if (expanded_globs.is_empty())
  815. argv_string.append(exp_arg);
  816. }
  817. }
  818. return argv_string;
  819. }
  820. ContinuationRequest Shell::is_complete(const Vector<Command>& commands)
  821. {
  822. // check if the last command ends with a pipe, or an unterminated string
  823. auto& last_command = commands.last();
  824. auto& subcommands = last_command.subcommands;
  825. if (subcommands.size() == 0)
  826. return ContinuationRequest::Nothing;
  827. auto& last_subcommand = subcommands.last();
  828. if (!last_subcommand.redirections.find([](auto& redirection) { return redirection.type == Redirection::Pipe; }).is_end())
  829. return ContinuationRequest::Pipe;
  830. if (!last_subcommand.args.find([](auto& token) { return token.type == Token::UnterminatedSingleQuoted; }).is_end())
  831. return ContinuationRequest::SingleQuotedString;
  832. if (!last_subcommand.args.find([](auto& token) { return token.type == Token::UnterminatedDoubleQuoted; }).is_end())
  833. return ContinuationRequest::DoubleQuotedString;
  834. return ContinuationRequest::Nothing;
  835. }
  836. IterationDecision Shell::wait_for_pid(const Shell::SpawnedProcess& process, bool is_first_command_in_chain, int& return_value)
  837. {
  838. if (is_first_command_in_chain)
  839. m_waiting_for_pid = process.pid;
  840. int wstatus = 0;
  841. int rc = waitpid(process.pid, &wstatus, WSTOPPED);
  842. auto errno_save = errno;
  843. if (is_first_command_in_chain)
  844. m_waiting_for_pid = -1;
  845. errno = errno_save;
  846. if (rc < 0 && errno != EINTR) {
  847. if (errno != ECHILD)
  848. perror("waitpid");
  849. return IterationDecision::Break;
  850. }
  851. const Job* job = nullptr;
  852. u64 job_id = 0;
  853. auto maybe_job = jobs.get(process.pid);
  854. if (maybe_job.has_value()) {
  855. job = maybe_job.value();
  856. job_id = job->job_id();
  857. }
  858. if (WIFEXITED(wstatus)) {
  859. if (WEXITSTATUS(wstatus) != 0)
  860. dbg() << "Shell: " << process.name << ":" << process.pid << " exited with status " << WEXITSTATUS(wstatus);
  861. return_value = WEXITSTATUS(wstatus);
  862. if (job) {
  863. auto* mutable_job = const_cast<Job*>(job);
  864. mutable_job->set_has_exit(return_value);
  865. Core::EventLoop::current().post_event(*this, make<Core::CustomEvent>(ChildExited, mutable_job));
  866. }
  867. return IterationDecision::Break;
  868. }
  869. if (WIFSTOPPED(wstatus)) {
  870. fprintf(stderr, "Shell: [%llu] %s(%d) %s\n", job_id, process.name.characters(), process.pid, strsignal(WSTOPSIG(wstatus)));
  871. return IterationDecision::Continue;
  872. }
  873. if (WIFSIGNALED(wstatus)) {
  874. printf("Shell: [%llu] %s(%d) exited due to signal '%s'\n", job_id, process.name.characters(), process.pid, strsignal(WTERMSIG(wstatus)));
  875. } else {
  876. printf("Shell: [%llu] %s(%d) exited abnormally\n", job_id, process.name.characters(), process.pid);
  877. }
  878. if (job) {
  879. auto* mutable_job = const_cast<Job*>(job);
  880. mutable_job->set_has_exit(-1);
  881. Core::EventLoop::current().post_event(*this, make<Core::CustomEvent>(ChildExited, mutable_job));
  882. }
  883. return IterationDecision::Break;
  884. }
  885. ExitCodeOrContinuationRequest Shell::run_command(const StringView& cmd)
  886. {
  887. if (cmd.is_empty())
  888. return 0;
  889. if (cmd.starts_with("#"))
  890. return 0;
  891. auto commands = Parser(cmd).parse();
  892. if (!commands.size())
  893. return 1;
  894. auto needs_more = is_complete(commands);
  895. if (needs_more != ExitCodeOrContinuationRequest::Nothing)
  896. return needs_more;
  897. #ifdef SH_DEBUG
  898. for (auto& command : commands) {
  899. for (size_t i = 0; i < command.subcommands.size(); ++i) {
  900. for (size_t j = 0; j < i; ++j)
  901. dbgprintf(" ");
  902. for (auto& arg : command.subcommands[i].args) {
  903. switch (arg.type) {
  904. case Token::Bare:
  905. dbgprintf("<%s> ", arg.text.characters());
  906. break;
  907. case Token::SingleQuoted:
  908. dbgprintf("'<%s>' ", arg.text.characters());
  909. break;
  910. case Token::DoubleQuoted:
  911. dbgprintf("\"<%s>\" ", arg.text.characters());
  912. break;
  913. case Token::UnterminatedSingleQuoted:
  914. dbgprintf("\'<%s> ", arg.text.characters());
  915. break;
  916. case Token::UnterminatedDoubleQuoted:
  917. dbgprintf("\"<%s> ", arg.text.characters());
  918. break;
  919. case Token::Special:
  920. dbgprintf("<%s> ", arg.text.characters());
  921. break;
  922. case Token::Comment:
  923. dbgprintf("<%s> ", arg.text.characters());
  924. break;
  925. }
  926. }
  927. dbgprintf("\n");
  928. for (auto& redirecton : command.subcommands[i].redirections) {
  929. for (size_t j = 0; j < i; ++j)
  930. dbgprintf(" ");
  931. dbgprintf(" ");
  932. switch (redirecton.type) {
  933. case Redirection::Pipe:
  934. dbgprintf("Pipe\n");
  935. break;
  936. case Redirection::FileRead:
  937. dbgprintf("fd:%d = FileRead: %s\n", redirecton.fd, redirecton.path.characters());
  938. break;
  939. case Redirection::FileWrite:
  940. dbgprintf("fd:%d = FileWrite: %s\n", redirecton.fd, redirecton.path.characters());
  941. break;
  942. case Redirection::FileWriteAppend:
  943. dbgprintf("fd:%d = FileWriteAppend: %s\n", redirecton.fd, redirecton.path.characters());
  944. break;
  945. default:
  946. break;
  947. }
  948. }
  949. }
  950. if (auto attributes = command.attributes) {
  951. dbgprintf("\n ");
  952. if (attributes & Attributes::InBackground)
  953. dbgprintf("InBackground ");
  954. if (attributes & Attributes::ShortCircuitOnFailure)
  955. dbgprintf("ShortCircuitOnFailure ");
  956. }
  957. dbgprintf("\n");
  958. }
  959. #endif
  960. struct termios trm;
  961. tcgetattr(0, &trm);
  962. int return_value = 0;
  963. bool fail_short_circuits = false;
  964. for (auto& command : commands) {
  965. if (fail_short_circuits) {
  966. if (command.attributes & Attributes::ShortCircuitOnFailure)
  967. continue;
  968. // Do not fail any command after this one, as we've reached the end of a short-circuit chain,
  969. // e.g. foo && bar && baz ; foobar
  970. // ^ we reached this command.
  971. fail_short_circuits = false;
  972. continue;
  973. }
  974. if (command.subcommands.is_empty())
  975. continue;
  976. FileDescriptionCollector fds;
  977. for (size_t i = 0; i < command.subcommands.size(); ++i) {
  978. auto& subcommand = command.subcommands[i];
  979. for (auto& redirection : subcommand.redirections) {
  980. switch (redirection.type) {
  981. case Redirection::Pipe: {
  982. int pipefd[2];
  983. int rc = pipe(pipefd);
  984. if (rc < 0) {
  985. perror("pipe");
  986. return 1;
  987. }
  988. subcommand.rewirings.append({ STDOUT_FILENO, pipefd[1] });
  989. auto& next_command = command.subcommands[i + 1];
  990. next_command.rewirings.append({ STDIN_FILENO, pipefd[0] });
  991. fds.add(pipefd[0]);
  992. fds.add(pipefd[1]);
  993. break;
  994. }
  995. case Redirection::FileWriteAppend: {
  996. int fd = open(redirection.path.characters(), O_WRONLY | O_CREAT | O_APPEND, 0666);
  997. if (fd < 0) {
  998. perror("open");
  999. return 1;
  1000. }
  1001. subcommand.rewirings.append({ redirection.fd, fd });
  1002. fds.add(fd);
  1003. break;
  1004. }
  1005. case Redirection::FileWrite: {
  1006. int fd = open(redirection.path.characters(), O_WRONLY | O_CREAT | O_TRUNC, 0666);
  1007. if (fd < 0) {
  1008. perror("open");
  1009. return 1;
  1010. }
  1011. subcommand.rewirings.append({ redirection.fd, fd });
  1012. fds.add(fd);
  1013. break;
  1014. }
  1015. case Redirection::FileRead: {
  1016. int fd = open(redirection.path.characters(), O_RDONLY);
  1017. if (fd < 0) {
  1018. perror("open");
  1019. return 1;
  1020. }
  1021. subcommand.rewirings.append({ redirection.fd, fd });
  1022. fds.add(fd);
  1023. break;
  1024. }
  1025. }
  1026. }
  1027. }
  1028. Vector<SpawnedProcess> children;
  1029. for (size_t i = 0; i < command.subcommands.size(); ++i) {
  1030. auto& subcommand = command.subcommands[i];
  1031. Vector<String> argv_string = process_arguments(subcommand.args);
  1032. Vector<const char*> argv;
  1033. argv.ensure_capacity(argv_string.size());
  1034. for (const auto& s : argv_string) {
  1035. argv.append(s.characters());
  1036. }
  1037. argv.append(nullptr);
  1038. #ifdef SH_DEBUG
  1039. for (auto& arg : argv) {
  1040. dbgprintf("<%s> ", arg);
  1041. }
  1042. dbgprintf("\n");
  1043. #endif
  1044. int retval = 0;
  1045. if (run_builtin(argv.size() - 1, argv.data(), retval))
  1046. return retval;
  1047. pid_t child = fork();
  1048. if (!child) {
  1049. setpgid(0, 0);
  1050. tcsetpgrp(0, getpid());
  1051. tcsetattr(0, TCSANOW, &default_termios);
  1052. for (auto& rewiring : subcommand.rewirings) {
  1053. #ifdef SH_DEBUG
  1054. dbgprintf("in %s<%d>, dup2(%d, %d)\n", argv[0], getpid(), rewiring.rewire_fd, rewiring.fd);
  1055. #endif
  1056. int rc = dup2(rewiring.rewire_fd, rewiring.fd);
  1057. if (rc < 0) {
  1058. perror("dup2");
  1059. return 1;
  1060. }
  1061. }
  1062. fds.collect();
  1063. int rc = execvp(argv[0], const_cast<char* const*>(argv.data()));
  1064. if (rc < 0) {
  1065. if (errno == ENOENT) {
  1066. int shebang_fd = open(argv[0], O_RDONLY);
  1067. auto close_argv = ScopeGuard([shebang_fd]() { if (shebang_fd >= 0) close(shebang_fd); });
  1068. char shebang[256] {};
  1069. ssize_t num_read = -1;
  1070. if ((shebang_fd >= 0) && ((num_read = read(shebang_fd, shebang, sizeof(shebang))) >= 2) && (StringView(shebang).starts_with("#!"))) {
  1071. StringView shebang_path_view(&shebang[2], num_read - 2);
  1072. Optional<size_t> newline_pos = shebang_path_view.find_first_of("\n\r");
  1073. shebang[newline_pos.has_value() ? (newline_pos.value() + 2) : num_read] = '\0';
  1074. fprintf(stderr, "%s: Invalid interpreter \"%s\": %s\n", argv[0], &shebang[2], strerror(ENOENT));
  1075. } else
  1076. fprintf(stderr, "%s: Command not found.\n", argv[0]);
  1077. } else {
  1078. int saved_errno = errno;
  1079. struct stat st;
  1080. if (stat(argv[0], &st) == 0 && S_ISDIR(st.st_mode)) {
  1081. fprintf(stderr, "Shell: %s: Is a directory\n", argv[0]);
  1082. _exit(126);
  1083. }
  1084. fprintf(stderr, "execvp(%s): %s\n", argv[0], strerror(saved_errno));
  1085. }
  1086. _exit(126);
  1087. }
  1088. ASSERT_NOT_REACHED();
  1089. }
  1090. children.append({ argv[0], child });
  1091. StringBuilder cmd;
  1092. cmd.join(" ", argv_string);
  1093. auto job = make<Job>(child, (unsigned)child, cmd.build(), find_last_job_id() + 1);
  1094. jobs.set((u64)child, move(job));
  1095. }
  1096. #ifdef SH_DEBUG
  1097. dbgprintf("Closing fds in shell process:\n");
  1098. #endif
  1099. fds.collect();
  1100. #ifdef SH_DEBUG
  1101. dbgprintf("Now we gotta wait on children:\n");
  1102. for (auto& child : children)
  1103. dbgprintf(" %d (%s)\n", child.pid, child.name.characters());
  1104. #endif
  1105. if (command.attributes & Attributes::InBackground) {
  1106. // Set the jobs as running in background and continue without waiting.
  1107. for (auto& child : children)
  1108. const_cast<Job*>(jobs.get(child.pid).value())->set_running_in_background(true);
  1109. continue;
  1110. }
  1111. for (size_t i = 0; i < children.size(); ++i) {
  1112. auto& child = children[i];
  1113. dbg() << "Now waiting for " << child.name << " (" << child.pid << ")";
  1114. do {
  1115. if (wait_for_pid(child, i != children.size() - 1, return_value) == IterationDecision::Break)
  1116. break;
  1117. } while (errno == EINTR);
  1118. }
  1119. if (command.attributes & Attributes::ShortCircuitOnFailure) {
  1120. if (return_value != 0) {
  1121. fail_short_circuits = true;
  1122. }
  1123. }
  1124. }
  1125. last_return_code = return_value;
  1126. // FIXME: Should I really have to tcsetpgrp() after my child has exited?
  1127. // Is the terminal controlling pgrp really still the PGID of the dead process?
  1128. tcsetpgrp(0, getpid());
  1129. tcsetattr(0, TCSANOW, &trm);
  1130. // Clear the exit flag after any non-exit command has been executed.
  1131. m_should_ignore_jobs_on_next_exit = false;
  1132. return return_value;
  1133. }
  1134. String Shell::get_history_path()
  1135. {
  1136. StringBuilder builder;
  1137. builder.append(home);
  1138. builder.append("/.history");
  1139. return builder.to_string();
  1140. }
  1141. void Shell::load_history()
  1142. {
  1143. auto history_file = Core::File::construct(get_history_path());
  1144. if (!history_file->open(Core::IODevice::ReadOnly))
  1145. return;
  1146. while (history_file->can_read_line()) {
  1147. auto b = history_file->read_line(1024);
  1148. // skip the newline and terminating bytes
  1149. editor->add_to_history(String(reinterpret_cast<const char*>(b.data()), b.size() - 2));
  1150. }
  1151. }
  1152. void Shell::save_history()
  1153. {
  1154. auto file_or_error = Core::File::open(get_history_path(), Core::IODevice::WriteOnly, 0600);
  1155. if (file_or_error.is_error())
  1156. return;
  1157. auto& file = *file_or_error.value();
  1158. for (const auto& line : editor->history()) {
  1159. file.write(line);
  1160. file.write("\n");
  1161. }
  1162. }
  1163. String Shell::escape_token(const String& token)
  1164. {
  1165. StringBuilder builder;
  1166. for (auto c : token) {
  1167. switch (c) {
  1168. case '\'':
  1169. case '"':
  1170. case '$':
  1171. case '|':
  1172. case '>':
  1173. case '<':
  1174. case '&':
  1175. case '\\':
  1176. case ' ':
  1177. builder.append('\\');
  1178. break;
  1179. default:
  1180. break;
  1181. }
  1182. builder.append(c);
  1183. }
  1184. return builder.build();
  1185. }
  1186. String Shell::unescape_token(const String& token)
  1187. {
  1188. StringBuilder builder;
  1189. enum {
  1190. Free,
  1191. Escaped
  1192. } state { Free };
  1193. for (auto c : token) {
  1194. switch (state) {
  1195. case Escaped:
  1196. builder.append(c);
  1197. state = Free;
  1198. break;
  1199. case Free:
  1200. if (c == '\\')
  1201. state = Escaped;
  1202. else
  1203. builder.append(c);
  1204. break;
  1205. }
  1206. }
  1207. if (state == Escaped)
  1208. builder.append('\\');
  1209. return builder.build();
  1210. }
  1211. void Shell::cache_path()
  1212. {
  1213. if (!cached_path.is_empty())
  1214. cached_path.clear_with_capacity();
  1215. String path = getenv("PATH");
  1216. if (path.is_empty())
  1217. return;
  1218. auto directories = path.split(':');
  1219. for (const auto& directory : directories) {
  1220. Core::DirIterator programs(directory.characters(), Core::DirIterator::SkipDots);
  1221. while (programs.has_next()) {
  1222. auto program = programs.next_path();
  1223. String program_path = String::format("%s/%s", directory.characters(), program.characters());
  1224. if (access(program_path.characters(), X_OK) == 0)
  1225. cached_path.append(escape_token(program.characters()));
  1226. }
  1227. }
  1228. // add shell builtins to the cache
  1229. for (const auto& builtin_name : builtin_names)
  1230. cached_path.append(escape_token(builtin_name));
  1231. quick_sort(cached_path);
  1232. }
  1233. void Shell::highlight(Line::Editor& editor) const
  1234. {
  1235. StringBuilder builder;
  1236. if (m_should_continue == ExitCodeOrContinuationRequest::DoubleQuotedString) {
  1237. builder.append('"');
  1238. }
  1239. if (m_should_continue == ExitCodeOrContinuationRequest::SingleQuotedString) {
  1240. builder.append('\'');
  1241. }
  1242. builder.append(editor.line());
  1243. auto commands = Parser { builder.string_view() }.parse();
  1244. auto first_command { true };
  1245. for (auto& command : commands) {
  1246. for (auto& subcommand : command.subcommands) {
  1247. auto first { true };
  1248. for (auto& arg : subcommand.args) {
  1249. auto start = arg.end - arg.length;
  1250. if (arg.type == Token::Comment) {
  1251. editor.stylize({ start, arg.end }, { Line::Style::Foreground(150, 150, 150) }); // light gray
  1252. continue;
  1253. }
  1254. if (m_should_continue == ExitCodeOrContinuationRequest::DoubleQuotedString || m_should_continue == ExitCodeOrContinuationRequest::SingleQuotedString) {
  1255. if (!first_command)
  1256. --start;
  1257. --arg.end;
  1258. }
  1259. if (first) {
  1260. first = false;
  1261. // only treat this as a command name if we're not continuing strings
  1262. if (!first_command || (m_should_continue == ExitCodeOrContinuationRequest::Nothing || m_should_continue == ExitCodeOrContinuationRequest::Pipe)) {
  1263. editor.stylize({ start, arg.end }, { Line::Style::Bold });
  1264. first_command = false;
  1265. continue;
  1266. }
  1267. first_command = false;
  1268. }
  1269. if (arg.type == Token::SingleQuoted || arg.type == Token::UnterminatedSingleQuoted) {
  1270. editor.stylize({ start - 1, arg.end + (arg.type != Token::UnterminatedSingleQuoted) }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
  1271. continue;
  1272. }
  1273. if (arg.type == Token::DoubleQuoted || arg.type == Token::UnterminatedDoubleQuoted) {
  1274. editor.stylize({ start - 1, arg.end + (arg.type != Token::UnterminatedDoubleQuoted) }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
  1275. if constexpr (HighlightVariablesInsideStrings)
  1276. goto highlight_variables;
  1277. else
  1278. continue;
  1279. }
  1280. if (is_glob(arg.text)) {
  1281. editor.stylize({ start, arg.end }, { Line::Style::Foreground(59, 142, 234) }); // bright-ish blue
  1282. continue;
  1283. }
  1284. if (arg.text.starts_with("--")) {
  1285. if (arg.length == 2)
  1286. editor.stylize({ start, arg.end }, { Line::Style::Foreground(Line::Style::XtermColor::Green) });
  1287. else
  1288. editor.stylize({ start, arg.end }, { Line::Style::Foreground(Line::Style::XtermColor::Cyan) });
  1289. } else if (arg.text.starts_with("-") && arg.length > 1) {
  1290. editor.stylize({ start, arg.end }, { Line::Style::Foreground(Line::Style::XtermColor::Cyan) });
  1291. }
  1292. highlight_variables:;
  1293. size_t slice_index = 0;
  1294. Optional<size_t> maybe_index;
  1295. while (slice_index < arg.length) {
  1296. maybe_index = arg.text.substring_view(slice_index, arg.length - slice_index).find_first_of('$');
  1297. if (!maybe_index.has_value())
  1298. break;
  1299. auto index = maybe_index.value() + 1;
  1300. auto end_index = index;
  1301. if (index >= arg.length)
  1302. break;
  1303. for (; end_index < arg.length; ++end_index) {
  1304. if (!is_word_character(arg.text[end_index]))
  1305. break;
  1306. }
  1307. editor.stylize({ index + start - 1, end_index + start }, { Line::Style::Foreground(214, 112, 214) });
  1308. slice_index = end_index + 1;
  1309. }
  1310. }
  1311. }
  1312. }
  1313. }
  1314. Vector<Line::CompletionSuggestion> Shell::complete(const Line::Editor& editor)
  1315. {
  1316. auto line = editor.line(editor.cursor());
  1317. Parser parser(line);
  1318. auto commands = parser.parse();
  1319. if (commands.size() == 0)
  1320. return {};
  1321. // get the last token and whether it's the first in its subcommand
  1322. String token;
  1323. bool is_first_in_subcommand = false;
  1324. auto& subcommand = commands.last().subcommands;
  1325. if (subcommand.size() == 0) {
  1326. // foo bar; <tab>
  1327. token = "";
  1328. is_first_in_subcommand = true;
  1329. } else {
  1330. auto& last_command = subcommand.last();
  1331. if (last_command.args.size() == 0) {
  1332. // foo bar | <tab>
  1333. token = "";
  1334. is_first_in_subcommand = true;
  1335. } else {
  1336. auto& args = last_command.args;
  1337. if (args.last().type == Token::Comment) // we cannot complete comments
  1338. return {};
  1339. if (args.last().end != line.length()) {
  1340. // There was a token separator at the end
  1341. is_first_in_subcommand = false;
  1342. token = "";
  1343. } else {
  1344. is_first_in_subcommand = args.size() == 1;
  1345. token = last_command.args.last().text;
  1346. }
  1347. }
  1348. }
  1349. Vector<Line::CompletionSuggestion> suggestions;
  1350. bool should_suggest_only_executables = false;
  1351. if (is_first_in_subcommand) {
  1352. auto match = binary_search(cached_path.data(), cached_path.size(), token, [](const String& token, const String& program) -> int {
  1353. return strncmp(token.characters(), program.characters(), token.length());
  1354. });
  1355. if (match) {
  1356. String completion = *match;
  1357. editor.suggest(escape_token(token).length(), 0);
  1358. // Now that we have a program name starting with our token, we look at
  1359. // other program names starting with our token and cut off any mismatching
  1360. // characters.
  1361. int index = match - cached_path.data();
  1362. for (int i = index - 1; i >= 0 && cached_path[i].starts_with(token); --i) {
  1363. suggestions.append({ cached_path[i], " " });
  1364. }
  1365. for (size_t i = index + 1; i < cached_path.size() && cached_path[i].starts_with(token); ++i) {
  1366. suggestions.append({ cached_path[i], " " });
  1367. }
  1368. suggestions.append({ cached_path[index], " " });
  1369. return suggestions;
  1370. }
  1371. // fallthrough to suggesting local files, but make sure to only suggest executables
  1372. should_suggest_only_executables = true;
  1373. }
  1374. String path;
  1375. String original_token = token;
  1376. ssize_t last_slash = token.length() - 1;
  1377. while (last_slash >= 0 && token[last_slash] != '/')
  1378. --last_slash;
  1379. if (last_slash >= 0) {
  1380. // Split on the last slash. We'll use the first part as the directory
  1381. // to search and the second part as the token to complete.
  1382. path = token.substring(0, last_slash + 1);
  1383. if (path[0] != '/')
  1384. path = String::format("%s/%s", cwd.characters(), path.characters());
  1385. path = LexicalPath::canonicalized_path(path);
  1386. token = token.substring(last_slash + 1, token.length() - last_slash - 1);
  1387. } else {
  1388. // We have no slashes, so the directory to search is the current
  1389. // directory and the token to complete is just the original token.
  1390. path = cwd;
  1391. }
  1392. // the invariant part of the token is actually just the last segment
  1393. // e. in `cd /foo/bar', 'bar' is the invariant
  1394. // since we are not suggesting anything starting with
  1395. // `/foo/', but rather just `bar...'
  1396. auto token_length = escape_token(token).length();
  1397. editor.suggest(token_length, original_token.length() - token_length);
  1398. // only suggest dot-files if path starts with a dot
  1399. Core::DirIterator files(path,
  1400. token.starts_with('.') ? Core::DirIterator::SkipParentAndBaseDir : Core::DirIterator::SkipDots);
  1401. while (files.has_next()) {
  1402. auto file = files.next_path();
  1403. if (file.starts_with(token)) {
  1404. struct stat program_status;
  1405. String file_path = String::format("%s/%s", path.characters(), file.characters());
  1406. int stat_error = stat(file_path.characters(), &program_status);
  1407. if (!stat_error) {
  1408. if (S_ISDIR(program_status.st_mode)) {
  1409. if (!should_suggest_only_executables)
  1410. suggestions.append({ escape_token(file), "/", { Line::Style::Hyperlink(String::format("file://%s", file_path.characters())), Line::Style::Anchored } });
  1411. } else {
  1412. suggestions.append({ escape_token(file), " ", { Line::Style::Hyperlink(String::format("file://%s", file_path.characters())), Line::Style::Anchored } });
  1413. }
  1414. }
  1415. }
  1416. }
  1417. return suggestions;
  1418. }
  1419. bool Shell::read_single_line()
  1420. {
  1421. auto line_result = editor->get_line(prompt());
  1422. if (line_result.is_error()) {
  1423. m_complete_line_builder.clear();
  1424. m_should_continue = ContinuationRequest::Nothing;
  1425. m_should_break_current_command = false;
  1426. Core::EventLoop::current().quit(line_result.error() == Line::Editor::Error::Eof ? 0 : 1);
  1427. return false;
  1428. }
  1429. auto& line = line_result.value();
  1430. if (m_should_break_current_command) {
  1431. m_complete_line_builder.clear();
  1432. m_should_continue = ContinuationRequest::Nothing;
  1433. m_should_break_current_command = false;
  1434. return true;
  1435. }
  1436. if (line.is_empty())
  1437. return true;
  1438. // FIXME: This might be a bit counter-intuitive, since we put nothing
  1439. // between the two lines, even though the user has pressed enter
  1440. // but since the LineEditor cannot yet handle literal newlines
  1441. // inside the text, we opt to do this the wrong way (for the time being)
  1442. m_complete_line_builder.append(line);
  1443. auto complete_or_exit_code = run_command(m_complete_line_builder.string_view());
  1444. m_should_continue = complete_or_exit_code.continuation;
  1445. if (!complete_or_exit_code.has_value())
  1446. return true;
  1447. editor->add_to_history(m_complete_line_builder.build());
  1448. m_complete_line_builder.clear();
  1449. return true;
  1450. }
  1451. void Shell::custom_event(Core::CustomEvent& event)
  1452. {
  1453. if (event.custom_type() == ReadLine) {
  1454. if (read_single_line())
  1455. Core::EventLoop::current().post_event(*this, make<Core::CustomEvent>(ShellEventType::ReadLine));
  1456. return;
  1457. }
  1458. if (event.custom_type() == ChildExited) {
  1459. auto* job_ptr = event.data();
  1460. if (job_ptr) {
  1461. auto& job = *(Job*)job_ptr;
  1462. if (job.is_running_in_background())
  1463. fprintf(stderr, "Shell: Job %d(%s) exited\n", job.pid(), job.cmd().characters());
  1464. jobs.remove(job.pid());
  1465. }
  1466. return;
  1467. }
  1468. event.ignore();
  1469. }
  1470. Shell::Shell()
  1471. {
  1472. uid = getuid();
  1473. tcsetpgrp(0, getpgrp());
  1474. int rc = gethostname(hostname, Shell::HostNameSize);
  1475. if (rc < 0)
  1476. perror("gethostname");
  1477. rc = ttyname_r(0, ttyname, Shell::TTYNameSize);
  1478. if (rc < 0)
  1479. perror("ttyname_r");
  1480. {
  1481. auto* cwd = getcwd(nullptr, 0);
  1482. this->cwd = cwd;
  1483. setenv("PWD", cwd, 1);
  1484. free(cwd);
  1485. }
  1486. {
  1487. auto* pw = getpwuid(getuid());
  1488. if (pw) {
  1489. username = pw->pw_name;
  1490. home = pw->pw_dir;
  1491. setenv("HOME", pw->pw_dir, 1);
  1492. }
  1493. endpwent();
  1494. }
  1495. directory_stack.append(cwd);
  1496. load_history();
  1497. cache_path();
  1498. }
  1499. Shell::~Shell()
  1500. {
  1501. stop_all_jobs();
  1502. save_history();
  1503. }
  1504. void Shell::stop_all_jobs()
  1505. {
  1506. if (!jobs.is_empty()) {
  1507. printf("Killing active jobs\n");
  1508. for (auto& entry : jobs) {
  1509. if (!entry.value->is_running_in_background()) {
  1510. #ifdef SH_DEBUG
  1511. dbg() << "Job " << entry.value->pid() << " is not running in background";
  1512. #endif
  1513. if (killpg(entry.value->pgid(), SIGCONT) < 0) {
  1514. perror("killpg(CONT)");
  1515. }
  1516. }
  1517. if (killpg(entry.value->pgid(), SIGHUP) < 0) {
  1518. perror("killpg(HUP)");
  1519. }
  1520. if (killpg(entry.value->pgid(), SIGTERM) < 0) {
  1521. perror("killpg(TERM)");
  1522. }
  1523. }
  1524. usleep(10000); // Wait for a bit before killing the job
  1525. for (auto& entry : jobs) {
  1526. #ifdef SH_DEBUG
  1527. dbg() << "Actively killing " << entry.value->pid() << "(" << entry.value->cmd() << ")";
  1528. #endif
  1529. if (killpg(entry.value->pgid(), SIGKILL) < 0) {
  1530. if (errno == ESRCH)
  1531. continue; // The process has exited all by itself.
  1532. perror("killpg(KILL)");
  1533. }
  1534. }
  1535. }
  1536. }
  1537. u64 Shell::find_last_job_id() const
  1538. {
  1539. u64 job_id = 0;
  1540. for (auto& entry : jobs) {
  1541. if (entry.value->job_id() > job_id)
  1542. job_id = entry.value->job_id();
  1543. }
  1544. return job_id;
  1545. }
  1546. void Shell::save_to(JsonObject& object)
  1547. {
  1548. Core::Object::save_to(object);
  1549. object.set("working_directory", cwd);
  1550. object.set("username", username);
  1551. object.set("user_home_path", home);
  1552. object.set("user_id", uid);
  1553. object.set("directory_stack_size", directory_stack.size());
  1554. object.set("cd_history_size", cd_history.size());
  1555. // Jobs.
  1556. JsonArray job_objects;
  1557. for (auto& job_entry : jobs) {
  1558. JsonObject job_object;
  1559. job_object.set("pid", job_entry.value->pid());
  1560. job_object.set("pgid", job_entry.value->pgid());
  1561. job_object.set("running_time", job_entry.value->timer().elapsed());
  1562. job_object.set("command", job_entry.value->cmd());
  1563. job_object.set("is_running_in_background", job_entry.value->is_running_in_background());
  1564. job_objects.append(move(job_object));
  1565. }
  1566. object.set("jobs", move(job_objects));
  1567. }