Shell.cpp 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921
  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: 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. auto id = StringView(job_id).to_uint();
  391. if (id.has_value())
  392. job_ids.append(id.value());
  393. else
  394. printf("Invalid job id: %s\n", job_id);
  395. }
  396. if (job_ids.is_empty())
  397. job_ids.append(jobs.size() - 1);
  398. Vector<size_t> keys_of_jobs_to_disown;
  399. for (auto id : job_ids) {
  400. bool found = false;
  401. for (auto& entry : jobs) {
  402. if (entry.value->job_id() == id) {
  403. keys_of_jobs_to_disown.append(entry.key);
  404. found = true;
  405. break;
  406. }
  407. }
  408. if (!found) {
  409. printf("job with id %zu not found\n", id);
  410. }
  411. }
  412. if (keys_of_jobs_to_disown.is_empty()) {
  413. if (str_job_ids.is_empty()) {
  414. printf("disown: no current job\n");
  415. }
  416. // An error message has already been printed about the nonexistence of each listed job.
  417. return 1;
  418. }
  419. for (auto job_index : keys_of_jobs_to_disown) {
  420. auto job = jobs.get(job_index).value();
  421. job->deactivate();
  422. if (!job->is_running_in_background())
  423. printf("disown warning: job %llu is currently not running, 'kill -%d %d' to make it continue\n", job->job_id(), SIGCONT, job->pid());
  424. jobs.remove(job_index);
  425. }
  426. return 0;
  427. }
  428. int Shell::builtin_history(int, const char**)
  429. {
  430. for (size_t i = 0; i < editor->history().size(); ++i) {
  431. printf("%6zu %s\n", i, editor->history()[i].characters());
  432. }
  433. return 0;
  434. }
  435. int Shell::builtin_jobs(int argc, const char** argv)
  436. {
  437. bool list = false, show_pid = false;
  438. Core::ArgsParser parser;
  439. parser.add_option(list, "List all information about jobs", "list", 'l');
  440. parser.add_option(show_pid, "Display the PID of the jobs", "pid", 'p');
  441. if (!parser.parse(argc, const_cast<char**>(argv), false))
  442. return 1;
  443. enum {
  444. Basic,
  445. OnlyPID,
  446. ListAll,
  447. } mode { Basic };
  448. if (show_pid)
  449. mode = OnlyPID;
  450. if (list)
  451. mode = ListAll;
  452. for (auto& job : jobs) {
  453. auto pid = job.value->pid();
  454. int wstatus;
  455. auto rc = waitpid(pid, &wstatus, WNOHANG);
  456. if (rc == -1) {
  457. perror("waitpid");
  458. return 1;
  459. }
  460. auto status = "running";
  461. if (rc != 0) {
  462. if (WIFEXITED(wstatus))
  463. status = "exited";
  464. if (WIFSTOPPED(wstatus))
  465. status = "stopped";
  466. if (WIFSIGNALED(wstatus))
  467. status = "signaled";
  468. }
  469. char background_indicator = '-';
  470. if (job.value->is_running_in_background())
  471. background_indicator = '+';
  472. switch (mode) {
  473. case Basic:
  474. printf("[%llu] %c %s %s\n", job.value->job_id(), background_indicator, status, job.value->cmd().characters());
  475. break;
  476. case OnlyPID:
  477. printf("[%llu] %c %d %s %s\n", job.value->job_id(), background_indicator, pid, status, job.value->cmd().characters());
  478. break;
  479. case ListAll:
  480. printf("[%llu] %c %d %d %s %s\n", job.value->job_id(), background_indicator, pid, job.value->pgid(), status, job.value->cmd().characters());
  481. break;
  482. }
  483. }
  484. return 0;
  485. }
  486. int Shell::builtin_popd(int argc, const char** argv)
  487. {
  488. if (directory_stack.size() <= 1) {
  489. fprintf(stderr, "Shell: popd: directory stack empty\n");
  490. return 1;
  491. }
  492. bool should_not_switch = false;
  493. String path = directory_stack.take_last();
  494. Core::ArgsParser parser;
  495. parser.add_option(should_not_switch, "Do not switch dirs", "no-switch", 'n');
  496. if (!parser.parse(argc, const_cast<char**>(argv), false))
  497. return 1;
  498. bool should_switch = !should_not_switch;
  499. // When no arguments are given, popd removes the top directory from the stack and performs a cd to the new top directory.
  500. if (argc == 1) {
  501. int rc = chdir(path.characters());
  502. if (rc < 0) {
  503. fprintf(stderr, "chdir(%s) failed: %s\n", path.characters(), strerror(errno));
  504. return 1;
  505. }
  506. cwd = path;
  507. return 0;
  508. }
  509. LexicalPath lexical_path(path.characters());
  510. if (!lexical_path.is_valid()) {
  511. fprintf(stderr, "LexicalPath failed to canonicalize '%s'\n", path.characters());
  512. return 1;
  513. }
  514. const char* real_path = lexical_path.string().characters();
  515. struct stat st;
  516. int rc = stat(real_path, &st);
  517. if (rc < 0) {
  518. fprintf(stderr, "stat(%s) failed: %s\n", real_path, strerror(errno));
  519. return 1;
  520. }
  521. if (!S_ISDIR(st.st_mode)) {
  522. fprintf(stderr, "Not a directory: %s\n", real_path);
  523. return 1;
  524. }
  525. if (should_switch) {
  526. int rc = chdir(real_path);
  527. if (rc < 0) {
  528. fprintf(stderr, "chdir(%s) failed: %s\n", real_path, strerror(errno));
  529. return 1;
  530. }
  531. cwd = lexical_path.string();
  532. }
  533. return 0;
  534. }
  535. int Shell::builtin_pushd(int argc, const char** argv)
  536. {
  537. StringBuilder path_builder;
  538. bool should_switch = true;
  539. // From the BASH reference manual: https://www.gnu.org/software/bash/manual/html_node/Directory-Stack-Builtins.html
  540. // With no arguments, pushd exchanges the top two directories and makes the new top the current directory.
  541. if (argc == 1) {
  542. if (directory_stack.size() < 2) {
  543. fprintf(stderr, "pushd: no other directory\n");
  544. return 1;
  545. }
  546. String dir1 = directory_stack.take_first();
  547. String dir2 = directory_stack.take_first();
  548. directory_stack.insert(0, dir2);
  549. directory_stack.insert(1, dir1);
  550. int rc = chdir(dir2.characters());
  551. if (rc < 0) {
  552. fprintf(stderr, "chdir(%s) failed: %s\n", dir2.characters(), strerror(errno));
  553. return 1;
  554. }
  555. cwd = dir2;
  556. return 0;
  557. }
  558. // Let's assume the user's typed in 'pushd <dir>'
  559. if (argc == 2) {
  560. directory_stack.append(cwd.characters());
  561. if (argv[1][0] == '/') {
  562. path_builder.append(argv[1]);
  563. } else {
  564. path_builder.appendf("%s/%s", cwd.characters(), argv[1]);
  565. }
  566. } else if (argc == 3) {
  567. directory_stack.append(cwd.characters());
  568. for (int i = 1; i < argc; i++) {
  569. const char* arg = argv[i];
  570. if (arg[0] != '-') {
  571. if (arg[0] == '/') {
  572. path_builder.append(arg);
  573. } else
  574. path_builder.appendf("%s/%s", cwd.characters(), arg);
  575. }
  576. if (!strcmp(arg, "-n"))
  577. should_switch = false;
  578. }
  579. }
  580. LexicalPath lexical_path(path_builder.to_string());
  581. if (!lexical_path.is_valid()) {
  582. fprintf(stderr, "LexicalPath failed to canonicalize '%s'\n", path_builder.to_string().characters());
  583. return 1;
  584. }
  585. const char* real_path = lexical_path.string().characters();
  586. struct stat st;
  587. int rc = stat(real_path, &st);
  588. if (rc < 0) {
  589. fprintf(stderr, "stat(%s) failed: %s\n", real_path, strerror(errno));
  590. return 1;
  591. }
  592. if (!S_ISDIR(st.st_mode)) {
  593. fprintf(stderr, "Not a directory: %s\n", real_path);
  594. return 1;
  595. }
  596. if (should_switch) {
  597. int rc = chdir(real_path);
  598. if (rc < 0) {
  599. fprintf(stderr, "chdir(%s) failed: %s\n", real_path, strerror(errno));
  600. return 1;
  601. }
  602. cwd = lexical_path.string();
  603. }
  604. return 0;
  605. }
  606. int Shell::builtin_pwd(int, const char**)
  607. {
  608. print_path(cwd);
  609. fputc('\n', stdout);
  610. return 0;
  611. }
  612. int Shell::builtin_time(int argc, const char** argv)
  613. {
  614. Vector<const char*> args;
  615. Core::ArgsParser parser;
  616. parser.add_positional_argument(args, "Command to execute with arguments", "command", Core::ArgsParser::Required::Yes);
  617. if (!parser.parse(argc, const_cast<char**>(argv), false))
  618. return 1;
  619. StringBuilder builder;
  620. builder.join(' ', args);
  621. Core::ElapsedTimer timer;
  622. timer.start();
  623. auto exit_code = run_command(builder.string_view());
  624. if (!exit_code.has_value()) {
  625. printf("Shell: Incomplete command: %s\n", builder.to_string().characters());
  626. exit_code = 1;
  627. }
  628. printf("Time: %d ms\n", timer.elapsed());
  629. return exit_code.value();
  630. }
  631. int Shell::builtin_umask(int argc, const char** argv)
  632. {
  633. const char* mask_text = nullptr;
  634. Core::ArgsParser parser;
  635. parser.add_positional_argument(mask_text, "New mask (omit to get current mask)", "octal-mask", Core::ArgsParser::Required::No);
  636. if (!parser.parse(argc, const_cast<char**>(argv), false))
  637. return 1;
  638. if (!mask_text) {
  639. mode_t old_mask = umask(0);
  640. printf("%#o\n", old_mask);
  641. umask(old_mask);
  642. return 0;
  643. }
  644. unsigned mask;
  645. int matches = sscanf(mask_text, "%o", &mask);
  646. if (matches == 1) {
  647. umask(mask);
  648. return 0;
  649. }
  650. return 0;
  651. }
  652. int Shell::builtin_unset(int argc, const char** argv)
  653. {
  654. Vector<const char*> vars;
  655. Core::ArgsParser parser;
  656. parser.add_positional_argument(vars, "List of variables", "variables", Core::ArgsParser::Required::Yes);
  657. if (!parser.parse(argc, const_cast<char**>(argv), false))
  658. return 1;
  659. for (auto& value : vars)
  660. unsetenv(value);
  661. return 0;
  662. }
  663. bool Shell::run_builtin(int argc, const char** argv, int& retval)
  664. {
  665. if (argc == 0)
  666. return false;
  667. StringView name { argv[0] };
  668. #define __ENUMERATE_SHELL_BUILTIN(builtin) \
  669. if (name == #builtin) { \
  670. retval = builtin_##builtin(argc, argv); \
  671. return true; \
  672. }
  673. ENUMERATE_SHELL_BUILTINS();
  674. #undef __ENUMERATE_SHELL_BUILTIN
  675. return false;
  676. }
  677. String Shell::expand_tilde(const String& expression)
  678. {
  679. ASSERT(expression.starts_with('~'));
  680. StringBuilder login_name;
  681. size_t first_slash_index = expression.length();
  682. for (size_t i = 1; i < expression.length(); ++i) {
  683. if (expression[i] == '/') {
  684. first_slash_index = i;
  685. break;
  686. }
  687. login_name.append(expression[i]);
  688. }
  689. StringBuilder path;
  690. for (size_t i = first_slash_index; i < expression.length(); ++i)
  691. path.append(expression[i]);
  692. if (login_name.is_empty()) {
  693. const char* home = getenv("HOME");
  694. if (!home) {
  695. auto passwd = getpwuid(getuid());
  696. ASSERT(passwd && passwd->pw_dir);
  697. return String::format("%s/%s", passwd->pw_dir, path.to_string().characters());
  698. }
  699. return String::format("%s/%s", home, path.to_string().characters());
  700. }
  701. auto passwd = getpwnam(login_name.to_string().characters());
  702. if (!passwd)
  703. return expression;
  704. ASSERT(passwd->pw_dir);
  705. return String::format("%s/%s", passwd->pw_dir, path.to_string().characters());
  706. }
  707. bool Shell::is_glob(const StringView& s)
  708. {
  709. for (size_t i = 0; i < s.length(); i++) {
  710. char c = s.characters_without_null_termination()[i];
  711. if (c == '*' || c == '?')
  712. return true;
  713. }
  714. return false;
  715. }
  716. Vector<StringView> Shell::split_path(const StringView& path)
  717. {
  718. Vector<StringView> parts;
  719. size_t substart = 0;
  720. for (size_t i = 0; i < path.length(); i++) {
  721. char ch = path.characters_without_null_termination()[i];
  722. if (ch != '/')
  723. continue;
  724. size_t sublen = i - substart;
  725. if (sublen != 0)
  726. parts.append(path.substring_view(substart, sublen));
  727. parts.append(path.substring_view(i, 1));
  728. substart = i + 1;
  729. }
  730. size_t taillen = path.length() - substart;
  731. if (taillen != 0)
  732. parts.append(path.substring_view(substart, taillen));
  733. return parts;
  734. }
  735. Vector<String> Shell::expand_globs(const StringView& path, const StringView& base)
  736. {
  737. auto parts = split_path(path);
  738. StringBuilder builder;
  739. builder.append(base);
  740. Vector<String> res;
  741. for (size_t i = 0; i < parts.size(); ++i) {
  742. auto& part = parts[i];
  743. if (!is_glob(part)) {
  744. builder.append(part);
  745. continue;
  746. }
  747. // Found a glob.
  748. String new_base = builder.to_string();
  749. StringView new_base_v = new_base;
  750. if (new_base_v.is_empty())
  751. new_base_v = ".";
  752. Core::DirIterator di(new_base_v, Core::DirIterator::SkipParentAndBaseDir);
  753. if (di.has_error()) {
  754. return res;
  755. }
  756. while (di.has_next()) {
  757. String name = di.next_path();
  758. // Dotfiles have to be explicitly requested
  759. if (name[0] == '.' && part[0] != '.')
  760. continue;
  761. if (name.matches(part, CaseSensitivity::CaseSensitive)) {
  762. StringBuilder nested_base;
  763. nested_base.append(new_base);
  764. nested_base.append(name);
  765. StringView remaining_path = path.substring_view_starting_after_substring(part);
  766. Vector<String> nested_res = expand_globs(remaining_path, nested_base.to_string());
  767. for (auto& s : nested_res)
  768. res.append(s);
  769. }
  770. }
  771. return res;
  772. }
  773. // Found no globs.
  774. String new_path = builder.to_string();
  775. if (access(new_path.characters(), F_OK) == 0)
  776. res.append(new_path);
  777. return res;
  778. }
  779. Vector<String> Shell::expand_parameters(const StringView& param) const
  780. {
  781. if (!param.starts_with('$'))
  782. return { param };
  783. String variable_name = String(param.substring_view(1, param.length() - 1));
  784. if (variable_name == "?")
  785. return { String::number(last_return_code) };
  786. else if (variable_name == "$")
  787. return { String::number(getpid()) };
  788. char* env_value = getenv(variable_name.characters());
  789. if (env_value == nullptr)
  790. return { "" };
  791. Vector<String> res;
  792. String str_env_value = String(env_value);
  793. const auto& split_text = str_env_value.split_view(' ');
  794. for (auto& part : split_text)
  795. res.append(part);
  796. return res;
  797. }
  798. Vector<String> Shell::process_arguments(const Vector<Token>& args)
  799. {
  800. Vector<String> argv_string;
  801. for (auto& arg : args) {
  802. if (arg.type == Token::Comment)
  803. continue;
  804. // This will return the text passed in if it wasn't a variable
  805. // This lets us just loop over its values
  806. auto expanded_parameters = expand_parameters(arg.text);
  807. for (auto& exp_arg : expanded_parameters) {
  808. if (exp_arg.starts_with('~'))
  809. exp_arg = expand_tilde(exp_arg);
  810. auto expanded_globs = expand_globs(exp_arg, "");
  811. for (auto& path : expanded_globs)
  812. argv_string.append(path);
  813. if (expanded_globs.is_empty())
  814. argv_string.append(exp_arg);
  815. }
  816. }
  817. return argv_string;
  818. }
  819. ContinuationRequest Shell::is_complete(const Vector<Command>& commands)
  820. {
  821. // check if the last command ends with a pipe, or an unterminated string
  822. auto& last_command = commands.last();
  823. auto& subcommands = last_command.subcommands;
  824. if (subcommands.size() == 0)
  825. return ContinuationRequest::Nothing;
  826. auto& last_subcommand = subcommands.last();
  827. if (!last_subcommand.redirections.find([](auto& redirection) { return redirection.type == Redirection::Pipe; }).is_end())
  828. return ContinuationRequest::Pipe;
  829. if (!last_subcommand.args.find([](auto& token) { return token.type == Token::UnterminatedSingleQuoted; }).is_end())
  830. return ContinuationRequest::SingleQuotedString;
  831. if (!last_subcommand.args.find([](auto& token) { return token.type == Token::UnterminatedDoubleQuoted; }).is_end())
  832. return ContinuationRequest::DoubleQuotedString;
  833. return ContinuationRequest::Nothing;
  834. }
  835. IterationDecision Shell::wait_for_pid(const Shell::SpawnedProcess& process, bool is_first_command_in_chain, int& return_value)
  836. {
  837. if (is_first_command_in_chain)
  838. m_waiting_for_pid = process.pid;
  839. int wstatus = 0;
  840. int rc = waitpid(process.pid, &wstatus, WSTOPPED);
  841. auto errno_save = errno;
  842. if (is_first_command_in_chain)
  843. m_waiting_for_pid = -1;
  844. errno = errno_save;
  845. if (rc < 0 && errno != EINTR) {
  846. if (errno != ECHILD)
  847. perror("waitpid");
  848. return IterationDecision::Break;
  849. }
  850. const Job* job = nullptr;
  851. u64 job_id = 0;
  852. auto maybe_job = jobs.get(process.pid);
  853. if (maybe_job.has_value()) {
  854. job = maybe_job.value();
  855. job_id = job->job_id();
  856. }
  857. if (WIFEXITED(wstatus)) {
  858. if (WEXITSTATUS(wstatus) != 0)
  859. dbg() << "Shell: " << process.name << ":" << process.pid << " exited with status " << WEXITSTATUS(wstatus);
  860. return_value = WEXITSTATUS(wstatus);
  861. if (job) {
  862. auto* mutable_job = const_cast<Job*>(job);
  863. mutable_job->set_has_exit(return_value);
  864. Core::EventLoop::current().post_event(*this, make<Core::CustomEvent>(ChildExited, mutable_job));
  865. }
  866. return IterationDecision::Break;
  867. }
  868. if (WIFSTOPPED(wstatus)) {
  869. fprintf(stderr, "Shell: [%llu] %s(%d) %s\n", job_id, process.name.characters(), process.pid, strsignal(WSTOPSIG(wstatus)));
  870. return IterationDecision::Continue;
  871. }
  872. if (WIFSIGNALED(wstatus)) {
  873. printf("Shell: [%llu] %s(%d) exited due to signal '%s'\n", job_id, process.name.characters(), process.pid, strsignal(WTERMSIG(wstatus)));
  874. } else {
  875. printf("Shell: [%llu] %s(%d) exited abnormally\n", job_id, process.name.characters(), process.pid);
  876. }
  877. if (job) {
  878. auto* mutable_job = const_cast<Job*>(job);
  879. mutable_job->set_has_exit(-1);
  880. Core::EventLoop::current().post_event(*this, make<Core::CustomEvent>(ChildExited, mutable_job));
  881. }
  882. return IterationDecision::Break;
  883. }
  884. ExitCodeOrContinuationRequest Shell::run_command(const StringView& cmd)
  885. {
  886. if (cmd.is_empty())
  887. return 0;
  888. if (cmd.starts_with("#"))
  889. return 0;
  890. auto commands = Parser(cmd).parse();
  891. if (!commands.size())
  892. return 1;
  893. auto needs_more = is_complete(commands);
  894. if (needs_more != ExitCodeOrContinuationRequest::Nothing)
  895. return needs_more;
  896. #ifdef SH_DEBUG
  897. for (auto& command : commands) {
  898. for (size_t i = 0; i < command.subcommands.size(); ++i) {
  899. for (size_t j = 0; j < i; ++j)
  900. dbgprintf(" ");
  901. for (auto& arg : command.subcommands[i].args) {
  902. switch (arg.type) {
  903. case Token::Bare:
  904. dbgprintf("<%s> ", arg.text.characters());
  905. break;
  906. case Token::SingleQuoted:
  907. dbgprintf("'<%s>' ", arg.text.characters());
  908. break;
  909. case Token::DoubleQuoted:
  910. dbgprintf("\"<%s>\" ", arg.text.characters());
  911. break;
  912. case Token::UnterminatedSingleQuoted:
  913. dbgprintf("\'<%s> ", arg.text.characters());
  914. break;
  915. case Token::UnterminatedDoubleQuoted:
  916. dbgprintf("\"<%s> ", arg.text.characters());
  917. break;
  918. case Token::Special:
  919. dbgprintf("<%s> ", arg.text.characters());
  920. break;
  921. case Token::Comment:
  922. dbgprintf("<%s> ", arg.text.characters());
  923. break;
  924. }
  925. }
  926. dbgprintf("\n");
  927. for (auto& redirecton : command.subcommands[i].redirections) {
  928. for (size_t j = 0; j < i; ++j)
  929. dbgprintf(" ");
  930. dbgprintf(" ");
  931. switch (redirecton.type) {
  932. case Redirection::Pipe:
  933. dbgprintf("Pipe\n");
  934. break;
  935. case Redirection::FileRead:
  936. dbgprintf("fd:%d = FileRead: %s\n", redirecton.fd, redirecton.path.text.characters());
  937. break;
  938. case Redirection::FileWrite:
  939. dbgprintf("fd:%d = FileWrite: %s\n", redirecton.fd, redirecton.path.text.characters());
  940. break;
  941. case Redirection::FileWriteAppend:
  942. dbgprintf("fd:%d = FileWriteAppend: %s\n", redirecton.fd, redirecton.path.text.characters());
  943. break;
  944. default:
  945. break;
  946. }
  947. }
  948. }
  949. if (auto attributes = command.attributes) {
  950. dbgprintf("\n ");
  951. if (attributes & Attributes::InBackground)
  952. dbgprintf("InBackground ");
  953. if (attributes & Attributes::ShortCircuitOnFailure)
  954. dbgprintf("ShortCircuitOnFailure ");
  955. }
  956. dbgprintf("\n");
  957. }
  958. #endif
  959. struct termios trm;
  960. tcgetattr(0, &trm);
  961. int return_value = 0;
  962. bool fail_short_circuits = false;
  963. for (auto& command : commands) {
  964. if (fail_short_circuits) {
  965. if (command.attributes & Attributes::ShortCircuitOnFailure)
  966. continue;
  967. // Do not fail any command after this one, as we've reached the end of a short-circuit chain,
  968. // e.g. foo && bar && baz ; foobar
  969. // ^ we reached this command.
  970. fail_short_circuits = false;
  971. continue;
  972. }
  973. if (command.subcommands.is_empty())
  974. continue;
  975. FileDescriptionCollector fds;
  976. for (size_t i = 0; i < command.subcommands.size(); ++i) {
  977. auto& subcommand = command.subcommands[i];
  978. for (auto& redirection : subcommand.redirections) {
  979. switch (redirection.type) {
  980. case Redirection::Pipe: {
  981. int pipefd[2];
  982. int rc = pipe(pipefd);
  983. if (rc < 0) {
  984. perror("pipe");
  985. return 1;
  986. }
  987. subcommand.rewirings.append({ STDOUT_FILENO, pipefd[1] });
  988. auto& next_command = command.subcommands[i + 1];
  989. next_command.rewirings.append({ STDIN_FILENO, pipefd[0] });
  990. fds.add(pipefd[0]);
  991. fds.add(pipefd[1]);
  992. break;
  993. }
  994. case Redirection::FileWriteAppend: {
  995. int fd = open(redirection.path.text.characters(), O_WRONLY | O_CREAT | O_APPEND, 0666);
  996. if (fd < 0) {
  997. perror("open");
  998. return 1;
  999. }
  1000. subcommand.rewirings.append({ redirection.fd, fd });
  1001. fds.add(fd);
  1002. break;
  1003. }
  1004. case Redirection::FileWrite: {
  1005. int fd = open(redirection.path.text.characters(), O_WRONLY | O_CREAT | O_TRUNC, 0666);
  1006. if (fd < 0) {
  1007. perror("open");
  1008. return 1;
  1009. }
  1010. subcommand.rewirings.append({ redirection.fd, fd });
  1011. fds.add(fd);
  1012. break;
  1013. }
  1014. case Redirection::FileRead: {
  1015. int fd = open(redirection.path.text.characters(), O_RDONLY);
  1016. if (fd < 0) {
  1017. perror("open");
  1018. return 1;
  1019. }
  1020. subcommand.rewirings.append({ redirection.fd, fd });
  1021. fds.add(fd);
  1022. break;
  1023. }
  1024. }
  1025. }
  1026. }
  1027. Vector<SpawnedProcess> children;
  1028. for (size_t i = 0; i < command.subcommands.size(); ++i) {
  1029. auto& subcommand = command.subcommands[i];
  1030. Vector<String> argv_string = process_arguments(subcommand.args);
  1031. Vector<const char*> argv;
  1032. argv.ensure_capacity(argv_string.size());
  1033. for (const auto& s : argv_string) {
  1034. argv.append(s.characters());
  1035. }
  1036. argv.append(nullptr);
  1037. #ifdef SH_DEBUG
  1038. for (auto& arg : argv) {
  1039. dbgprintf("<%s> ", arg);
  1040. }
  1041. dbgprintf("\n");
  1042. #endif
  1043. int retval = 0;
  1044. if (run_builtin(argv.size() - 1, argv.data(), retval))
  1045. return retval;
  1046. pid_t child = fork();
  1047. if (!child) {
  1048. setpgid(0, 0);
  1049. tcsetpgrp(0, getpid());
  1050. tcsetattr(0, TCSANOW, &default_termios);
  1051. for (auto& rewiring : subcommand.rewirings) {
  1052. #ifdef SH_DEBUG
  1053. dbgprintf("in %s<%d>, dup2(%d, %d)\n", argv[0], getpid(), rewiring.rewire_fd, rewiring.fd);
  1054. #endif
  1055. int rc = dup2(rewiring.rewire_fd, rewiring.fd);
  1056. if (rc < 0) {
  1057. perror("dup2");
  1058. return 1;
  1059. }
  1060. }
  1061. fds.collect();
  1062. int rc = execvp(argv[0], const_cast<char* const*>(argv.data()));
  1063. if (rc < 0) {
  1064. if (errno == ENOENT) {
  1065. int shebang_fd = open(argv[0], O_RDONLY);
  1066. auto close_argv = ScopeGuard([shebang_fd]() { if (shebang_fd >= 0) close(shebang_fd); });
  1067. char shebang[256] {};
  1068. ssize_t num_read = -1;
  1069. if ((shebang_fd >= 0) && ((num_read = read(shebang_fd, shebang, sizeof(shebang))) >= 2) && (StringView(shebang).starts_with("#!"))) {
  1070. StringView shebang_path_view(&shebang[2], num_read - 2);
  1071. Optional<size_t> newline_pos = shebang_path_view.find_first_of("\n\r");
  1072. shebang[newline_pos.has_value() ? (newline_pos.value() + 2) : num_read] = '\0';
  1073. fprintf(stderr, "%s: Invalid interpreter \"%s\": %s\n", argv[0], &shebang[2], strerror(ENOENT));
  1074. } else
  1075. fprintf(stderr, "%s: Command not found.\n", argv[0]);
  1076. } else {
  1077. int saved_errno = errno;
  1078. struct stat st;
  1079. if (stat(argv[0], &st) == 0 && S_ISDIR(st.st_mode)) {
  1080. fprintf(stderr, "Shell: %s: Is a directory\n", argv[0]);
  1081. _exit(126);
  1082. }
  1083. fprintf(stderr, "execvp(%s): %s\n", argv[0], strerror(saved_errno));
  1084. }
  1085. _exit(126);
  1086. }
  1087. ASSERT_NOT_REACHED();
  1088. }
  1089. children.append({ argv[0], child });
  1090. StringBuilder cmd;
  1091. cmd.join(" ", argv_string);
  1092. auto job = make<Job>(child, (unsigned)child, cmd.build(), find_last_job_id() + 1);
  1093. jobs.set((u64)child, move(job));
  1094. }
  1095. #ifdef SH_DEBUG
  1096. dbgprintf("Closing fds in shell process:\n");
  1097. #endif
  1098. fds.collect();
  1099. #ifdef SH_DEBUG
  1100. dbgprintf("Now we gotta wait on children:\n");
  1101. for (auto& child : children)
  1102. dbgprintf(" %d (%s)\n", child.pid, child.name.characters());
  1103. #endif
  1104. if (command.attributes & Attributes::InBackground) {
  1105. // Set the jobs as running in background and continue without waiting.
  1106. for (auto& child : children)
  1107. const_cast<Job*>(jobs.get(child.pid).value())->set_running_in_background(true);
  1108. continue;
  1109. }
  1110. for (size_t i = 0; i < children.size(); ++i) {
  1111. auto& child = children[i];
  1112. dbg() << "Now waiting for " << child.name << " (" << child.pid << ")";
  1113. do {
  1114. if (wait_for_pid(child, i != children.size() - 1, return_value) == IterationDecision::Break)
  1115. break;
  1116. } while (errno == EINTR);
  1117. }
  1118. if (command.attributes & Attributes::ShortCircuitOnFailure) {
  1119. if (return_value != 0) {
  1120. fail_short_circuits = true;
  1121. }
  1122. }
  1123. }
  1124. last_return_code = return_value;
  1125. // FIXME: Should I really have to tcsetpgrp() after my child has exited?
  1126. // Is the terminal controlling pgrp really still the PGID of the dead process?
  1127. tcsetpgrp(0, getpid());
  1128. tcsetattr(0, TCSANOW, &trm);
  1129. // Clear the exit flag after any non-exit command has been executed.
  1130. m_should_ignore_jobs_on_next_exit = false;
  1131. return return_value;
  1132. }
  1133. String Shell::get_history_path()
  1134. {
  1135. StringBuilder builder;
  1136. builder.append(home);
  1137. builder.append("/.history");
  1138. return builder.to_string();
  1139. }
  1140. void Shell::load_history()
  1141. {
  1142. auto history_file = Core::File::construct(get_history_path());
  1143. if (!history_file->open(Core::IODevice::ReadOnly))
  1144. return;
  1145. while (history_file->can_read_line()) {
  1146. auto b = history_file->read_line(1024);
  1147. // skip the newline and terminating bytes
  1148. editor->add_to_history(String(reinterpret_cast<const char*>(b.data()), b.size() - 2));
  1149. }
  1150. }
  1151. void Shell::save_history()
  1152. {
  1153. auto file_or_error = Core::File::open(get_history_path(), Core::IODevice::WriteOnly, 0600);
  1154. if (file_or_error.is_error())
  1155. return;
  1156. auto& file = *file_or_error.value();
  1157. for (const auto& line : editor->history()) {
  1158. file.write(line);
  1159. file.write("\n");
  1160. }
  1161. }
  1162. String Shell::escape_token(const String& token)
  1163. {
  1164. StringBuilder builder;
  1165. for (auto c : token) {
  1166. switch (c) {
  1167. case '\'':
  1168. case '"':
  1169. case '$':
  1170. case '|':
  1171. case '>':
  1172. case '<':
  1173. case '&':
  1174. case '\\':
  1175. case ' ':
  1176. builder.append('\\');
  1177. break;
  1178. default:
  1179. break;
  1180. }
  1181. builder.append(c);
  1182. }
  1183. return builder.build();
  1184. }
  1185. String Shell::unescape_token(const String& token)
  1186. {
  1187. StringBuilder builder;
  1188. enum {
  1189. Free,
  1190. Escaped
  1191. } state { Free };
  1192. for (auto c : token) {
  1193. switch (state) {
  1194. case Escaped:
  1195. builder.append(c);
  1196. state = Free;
  1197. break;
  1198. case Free:
  1199. if (c == '\\')
  1200. state = Escaped;
  1201. else
  1202. builder.append(c);
  1203. break;
  1204. }
  1205. }
  1206. if (state == Escaped)
  1207. builder.append('\\');
  1208. return builder.build();
  1209. }
  1210. void Shell::cache_path()
  1211. {
  1212. if (!cached_path.is_empty())
  1213. cached_path.clear_with_capacity();
  1214. String path = getenv("PATH");
  1215. if (path.is_empty())
  1216. return;
  1217. auto directories = path.split(':');
  1218. for (const auto& directory : directories) {
  1219. Core::DirIterator programs(directory.characters(), Core::DirIterator::SkipDots);
  1220. while (programs.has_next()) {
  1221. auto program = programs.next_path();
  1222. String program_path = String::format("%s/%s", directory.characters(), program.characters());
  1223. if (access(program_path.characters(), X_OK) == 0)
  1224. cached_path.append(escape_token(program.characters()));
  1225. }
  1226. }
  1227. // add shell builtins to the cache
  1228. for (const auto& builtin_name : builtin_names)
  1229. cached_path.append(escape_token(builtin_name));
  1230. quick_sort(cached_path);
  1231. }
  1232. void Shell::highlight(Line::Editor& editor) const
  1233. {
  1234. StringBuilder builder;
  1235. bool is_offset_by_string_start = false;
  1236. if (m_should_continue == ExitCodeOrContinuationRequest::DoubleQuotedString) {
  1237. builder.append('"');
  1238. is_offset_by_string_start = true;
  1239. }
  1240. if (m_should_continue == ExitCodeOrContinuationRequest::SingleQuotedString) {
  1241. builder.append('\'');
  1242. is_offset_by_string_start = true;
  1243. }
  1244. builder.append(editor.line());
  1245. auto commands = Parser { builder.string_view() }.parse();
  1246. auto first_command { true };
  1247. for (auto& command : commands) {
  1248. for (auto& subcommand : command.subcommands) {
  1249. auto& redirections = subcommand.redirections;
  1250. for (auto& redirection : redirections) {
  1251. if (redirection.type == Redirection::Pipe)
  1252. continue;
  1253. if (redirection.path.length == 0)
  1254. continue;
  1255. Line::Style redirection_style { Line::Style::Foreground(0x87, 0x9b, 0xcd) }; // 25% darkened periwinkle :)
  1256. auto end = redirection.path.end;
  1257. auto redirection_op_start = redirection.redirection_op_start;
  1258. if (is_offset_by_string_start) {
  1259. end--;
  1260. redirection_op_start--;
  1261. }
  1262. editor.stylize({ redirection_op_start, end }, redirection_style);
  1263. }
  1264. auto first { true };
  1265. for (auto& arg : subcommand.args) {
  1266. auto start = arg.end - arg.length;
  1267. if (arg.type == Token::Comment) {
  1268. editor.stylize({ start, arg.end }, { Line::Style::Foreground(150, 150, 150) }); // light gray
  1269. continue;
  1270. }
  1271. if (m_should_continue == ExitCodeOrContinuationRequest::DoubleQuotedString || m_should_continue == ExitCodeOrContinuationRequest::SingleQuotedString) {
  1272. if (!first_command)
  1273. --start;
  1274. --arg.end;
  1275. }
  1276. if (first) {
  1277. first = false;
  1278. // only treat this as a command name if we're not continuing strings
  1279. if (!first_command || (m_should_continue == ExitCodeOrContinuationRequest::Nothing || m_should_continue == ExitCodeOrContinuationRequest::Pipe)) {
  1280. editor.stylize({ start, arg.end }, { Line::Style::Bold });
  1281. first_command = false;
  1282. continue;
  1283. }
  1284. first_command = false;
  1285. }
  1286. if (arg.type == Token::SingleQuoted || arg.type == Token::UnterminatedSingleQuoted) {
  1287. editor.stylize({ start - 1, arg.end + (arg.type != Token::UnterminatedSingleQuoted) }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
  1288. continue;
  1289. }
  1290. if (arg.type == Token::DoubleQuoted || arg.type == Token::UnterminatedDoubleQuoted) {
  1291. editor.stylize({ start - 1, arg.end + (arg.type != Token::UnterminatedDoubleQuoted) }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
  1292. if constexpr (HighlightVariablesInsideStrings)
  1293. goto highlight_variables;
  1294. else
  1295. continue;
  1296. }
  1297. if (is_glob(arg.text)) {
  1298. editor.stylize({ start, arg.end }, { Line::Style::Foreground(59, 142, 234) }); // bright-ish blue
  1299. continue;
  1300. }
  1301. if (arg.text.starts_with("--")) {
  1302. if (arg.length == 2)
  1303. editor.stylize({ start, arg.end }, { Line::Style::Foreground(Line::Style::XtermColor::Green) });
  1304. else
  1305. editor.stylize({ start, arg.end }, { Line::Style::Foreground(Line::Style::XtermColor::Cyan) });
  1306. } else if (arg.text.starts_with("-") && arg.length > 1) {
  1307. editor.stylize({ start, arg.end }, { Line::Style::Foreground(Line::Style::XtermColor::Cyan) });
  1308. }
  1309. highlight_variables:;
  1310. size_t slice_index = 0;
  1311. Optional<size_t> maybe_index;
  1312. while (slice_index < arg.length) {
  1313. maybe_index = arg.text.substring_view(slice_index, arg.length - slice_index).find_first_of('$');
  1314. if (!maybe_index.has_value())
  1315. break;
  1316. auto index = maybe_index.value() + 1;
  1317. auto end_index = index;
  1318. if (index >= arg.length)
  1319. break;
  1320. for (; end_index < arg.length; ++end_index) {
  1321. if (!is_word_character(arg.text[end_index]))
  1322. break;
  1323. }
  1324. editor.stylize({ index + start - 1, end_index + start }, { Line::Style::Foreground(214, 112, 214) });
  1325. slice_index = end_index + 1;
  1326. }
  1327. }
  1328. }
  1329. }
  1330. }
  1331. Vector<Line::CompletionSuggestion> Shell::complete(const Line::Editor& editor)
  1332. {
  1333. auto line = editor.line(editor.cursor());
  1334. Parser parser(line);
  1335. auto commands = parser.parse();
  1336. if (commands.size() == 0)
  1337. return {};
  1338. // Get the last token and whether it's the first in its subcommand.
  1339. String token;
  1340. bool is_first_in_subcommand = false;
  1341. auto& subcommand = commands.last().subcommands;
  1342. String file_token_trail = " ";
  1343. String directory_token_trail = "/";
  1344. if (subcommand.size() == 0) {
  1345. // foo bar; <tab>
  1346. token = "";
  1347. is_first_in_subcommand = true;
  1348. } else {
  1349. auto& last_command = subcommand.last();
  1350. if (!last_command.redirections.is_empty() && last_command.redirections.last().type != Redirection::Pipe) {
  1351. // foo > bar<tab>
  1352. const auto& redirection = last_command.redirections.last();
  1353. const auto& path = redirection.path;
  1354. if (path.end != line.length())
  1355. return {};
  1356. token = path.text;
  1357. is_first_in_subcommand = false;
  1358. if (path.type == Token::UnterminatedDoubleQuoted)
  1359. file_token_trail = "\"";
  1360. else if (path.type == Token::UnterminatedSingleQuoted)
  1361. file_token_trail = "'";
  1362. } else {
  1363. if (last_command.args.size() == 0) {
  1364. // foo bar | <tab>
  1365. token = "";
  1366. is_first_in_subcommand = true;
  1367. } else {
  1368. auto& args = last_command.args;
  1369. if (args.last().type == Token::Comment) // we cannot complete comments
  1370. return {};
  1371. if (args.last().end != line.length()) {
  1372. // There was a token separator at the end
  1373. is_first_in_subcommand = false;
  1374. token = "";
  1375. } else {
  1376. is_first_in_subcommand = args.size() == 1;
  1377. token = last_command.args.last().text;
  1378. }
  1379. }
  1380. }
  1381. }
  1382. Vector<Line::CompletionSuggestion> suggestions;
  1383. bool should_suggest_only_executables = false;
  1384. if (is_first_in_subcommand) {
  1385. auto match = binary_search(cached_path.data(), cached_path.size(), token, [](const String& token, const String& program) -> int {
  1386. return strncmp(token.characters(), program.characters(), token.length());
  1387. });
  1388. if (match) {
  1389. String completion = *match;
  1390. editor.suggest(escape_token(token).length(), 0);
  1391. // Now that we have a program name starting with our token, we look at
  1392. // other program names starting with our token and cut off any mismatching
  1393. // characters.
  1394. int index = match - cached_path.data();
  1395. for (int i = index - 1; i >= 0 && cached_path[i].starts_with(token); --i) {
  1396. suggestions.append({ cached_path[i], " " });
  1397. }
  1398. for (size_t i = index + 1; i < cached_path.size() && cached_path[i].starts_with(token); ++i) {
  1399. suggestions.append({ cached_path[i], " " });
  1400. }
  1401. suggestions.append({ cached_path[index], " " });
  1402. return suggestions;
  1403. }
  1404. // fallthrough to suggesting local files, but make sure to only suggest executables
  1405. should_suggest_only_executables = true;
  1406. }
  1407. String path;
  1408. String original_token = token;
  1409. ssize_t last_slash = token.length() - 1;
  1410. while (last_slash >= 0 && token[last_slash] != '/')
  1411. --last_slash;
  1412. if (last_slash >= 0) {
  1413. // Split on the last slash. We'll use the first part as the directory
  1414. // to search and the second part as the token to complete.
  1415. path = token.substring(0, last_slash + 1);
  1416. if (path[0] != '/')
  1417. path = String::format("%s/%s", cwd.characters(), path.characters());
  1418. path = LexicalPath::canonicalized_path(path);
  1419. token = token.substring(last_slash + 1, token.length() - last_slash - 1);
  1420. } else {
  1421. // We have no slashes, so the directory to search is the current
  1422. // directory and the token to complete is just the original token.
  1423. path = cwd;
  1424. }
  1425. // the invariant part of the token is actually just the last segment
  1426. // e. in `cd /foo/bar', 'bar' is the invariant
  1427. // since we are not suggesting anything starting with
  1428. // `/foo/', but rather just `bar...'
  1429. auto token_length = escape_token(token).length();
  1430. editor.suggest(token_length, original_token.length() - token_length);
  1431. // only suggest dot-files if path starts with a dot
  1432. Core::DirIterator files(path,
  1433. token.starts_with('.') ? Core::DirIterator::SkipParentAndBaseDir : Core::DirIterator::SkipDots);
  1434. while (files.has_next()) {
  1435. auto file = files.next_path();
  1436. if (file.starts_with(token)) {
  1437. struct stat program_status;
  1438. String file_path = String::format("%s/%s", path.characters(), file.characters());
  1439. int stat_error = stat(file_path.characters(), &program_status);
  1440. if (!stat_error) {
  1441. if (S_ISDIR(program_status.st_mode)) {
  1442. if (!should_suggest_only_executables)
  1443. suggestions.append({ escape_token(file), directory_token_trail, { Line::Style::Hyperlink(String::format("file://%s", file_path.characters())), Line::Style::Anchored } });
  1444. } else {
  1445. suggestions.append({ escape_token(file), file_token_trail, { Line::Style::Hyperlink(String::format("file://%s", file_path.characters())), Line::Style::Anchored } });
  1446. }
  1447. }
  1448. }
  1449. }
  1450. return suggestions;
  1451. }
  1452. bool Shell::read_single_line()
  1453. {
  1454. auto line_result = editor->get_line(prompt());
  1455. if (line_result.is_error()) {
  1456. if (line_result.error() == Line::Editor::Error::Eof || line_result.error() == Line::Editor::Error::Empty) {
  1457. // Pretend the user tried to execute builtin_exit()
  1458. // but only if there's no continuation.
  1459. if (m_should_continue == ContinuationRequest::Nothing) {
  1460. m_complete_line_builder.clear();
  1461. run_command("exit");
  1462. return read_single_line();
  1463. } else {
  1464. // Ignore the Eof.
  1465. return true;
  1466. }
  1467. } else {
  1468. m_complete_line_builder.clear();
  1469. m_should_continue = ContinuationRequest::Nothing;
  1470. m_should_break_current_command = false;
  1471. Core::EventLoop::current().quit(1);
  1472. return false;
  1473. }
  1474. }
  1475. auto& line = line_result.value();
  1476. if (m_should_break_current_command) {
  1477. m_complete_line_builder.clear();
  1478. m_should_continue = ContinuationRequest::Nothing;
  1479. m_should_break_current_command = false;
  1480. return true;
  1481. }
  1482. if (line.is_empty())
  1483. return true;
  1484. // FIXME: This might be a bit counter-intuitive, since we put nothing
  1485. // between the two lines, even though the user has pressed enter
  1486. // but since the LineEditor cannot yet handle literal newlines
  1487. // inside the text, we opt to do this the wrong way (for the time being)
  1488. m_complete_line_builder.append(line);
  1489. auto complete_or_exit_code = run_command(m_complete_line_builder.string_view());
  1490. m_should_continue = complete_or_exit_code.continuation;
  1491. if (!complete_or_exit_code.has_value())
  1492. return true;
  1493. editor->add_to_history(m_complete_line_builder.build());
  1494. m_complete_line_builder.clear();
  1495. return true;
  1496. }
  1497. void Shell::custom_event(Core::CustomEvent& event)
  1498. {
  1499. if (event.custom_type() == ReadLine) {
  1500. if (read_single_line())
  1501. Core::EventLoop::current().post_event(*this, make<Core::CustomEvent>(ShellEventType::ReadLine));
  1502. return;
  1503. }
  1504. if (event.custom_type() == ChildExited) {
  1505. auto* job_ptr = event.data();
  1506. if (job_ptr) {
  1507. auto& job = *(Job*)job_ptr;
  1508. if (job.is_running_in_background())
  1509. fprintf(stderr, "Shell: Job %d(%s) exited\n", job.pid(), job.cmd().characters());
  1510. jobs.remove(job.pid());
  1511. }
  1512. return;
  1513. }
  1514. event.ignore();
  1515. }
  1516. Shell::Shell()
  1517. {
  1518. uid = getuid();
  1519. tcsetpgrp(0, getpgrp());
  1520. int rc = gethostname(hostname, Shell::HostNameSize);
  1521. if (rc < 0)
  1522. perror("gethostname");
  1523. rc = ttyname_r(0, ttyname, Shell::TTYNameSize);
  1524. if (rc < 0)
  1525. perror("ttyname_r");
  1526. {
  1527. auto* cwd = getcwd(nullptr, 0);
  1528. this->cwd = cwd;
  1529. setenv("PWD", cwd, 1);
  1530. free(cwd);
  1531. }
  1532. {
  1533. auto* pw = getpwuid(getuid());
  1534. if (pw) {
  1535. username = pw->pw_name;
  1536. home = pw->pw_dir;
  1537. setenv("HOME", pw->pw_dir, 1);
  1538. }
  1539. endpwent();
  1540. }
  1541. directory_stack.append(cwd);
  1542. load_history();
  1543. cache_path();
  1544. }
  1545. Shell::~Shell()
  1546. {
  1547. stop_all_jobs();
  1548. save_history();
  1549. }
  1550. void Shell::stop_all_jobs()
  1551. {
  1552. if (!jobs.is_empty()) {
  1553. printf("Killing active jobs\n");
  1554. for (auto& entry : jobs) {
  1555. if (!entry.value->is_running_in_background()) {
  1556. #ifdef SH_DEBUG
  1557. dbg() << "Job " << entry.value->pid() << " is not running in background";
  1558. #endif
  1559. if (killpg(entry.value->pgid(), SIGCONT) < 0) {
  1560. perror("killpg(CONT)");
  1561. }
  1562. }
  1563. if (killpg(entry.value->pgid(), SIGHUP) < 0) {
  1564. perror("killpg(HUP)");
  1565. }
  1566. if (killpg(entry.value->pgid(), SIGTERM) < 0) {
  1567. perror("killpg(TERM)");
  1568. }
  1569. }
  1570. usleep(10000); // Wait for a bit before killing the job
  1571. for (auto& entry : jobs) {
  1572. #ifdef SH_DEBUG
  1573. dbg() << "Actively killing " << entry.value->pid() << "(" << entry.value->cmd() << ")";
  1574. #endif
  1575. if (killpg(entry.value->pgid(), SIGKILL) < 0) {
  1576. if (errno == ESRCH)
  1577. continue; // The process has exited all by itself.
  1578. perror("killpg(KILL)");
  1579. }
  1580. }
  1581. }
  1582. }
  1583. u64 Shell::find_last_job_id() const
  1584. {
  1585. u64 job_id = 0;
  1586. for (auto& entry : jobs) {
  1587. if (entry.value->job_id() > job_id)
  1588. job_id = entry.value->job_id();
  1589. }
  1590. return job_id;
  1591. }
  1592. void Shell::save_to(JsonObject& object)
  1593. {
  1594. Core::Object::save_to(object);
  1595. object.set("working_directory", cwd);
  1596. object.set("username", username);
  1597. object.set("user_home_path", home);
  1598. object.set("user_id", uid);
  1599. object.set("directory_stack_size", directory_stack.size());
  1600. object.set("cd_history_size", cd_history.size());
  1601. // Jobs.
  1602. JsonArray job_objects;
  1603. for (auto& job_entry : jobs) {
  1604. JsonObject job_object;
  1605. job_object.set("pid", job_entry.value->pid());
  1606. job_object.set("pgid", job_entry.value->pgid());
  1607. job_object.set("running_time", job_entry.value->timer().elapsed());
  1608. job_object.set("command", job_entry.value->cmd());
  1609. job_object.set("is_running_in_background", job_entry.value->is_running_in_background());
  1610. job_objects.append(move(job_object));
  1611. }
  1612. object.set("jobs", move(job_objects));
  1613. }