esh_main_loop.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. #include "esh_main_loop.h"
  2. #include "esh_misc.h"
  3. #include "esh_history.h"
  4. #include "esh_init.h"
  5. #include "esh_deinit.h"
  6. #include "string_misc.h"
  7. void EShRunLoop() {
  8. struct termios orig_term_attr;
  9. struct termios new_term_attr;
  10. /* set the terminal to semi-raw mode */
  11. tcgetattr(fileno(stdin), &orig_term_attr);
  12. memcpy(&new_term_attr, &orig_term_attr, sizeof(struct termios));
  13. new_term_attr.c_lflag &= ~(ECHO | ICANON | ISIG | IEXTEN);
  14. new_term_attr.c_cc[VTIME] = 0;
  15. new_term_attr.c_cc[VMIN] = 1;
  16. tcsetattr(fileno(stdin), TCSANOW, &new_term_attr);
  17. char* command = malloc(esh_info_global->max_command_length);
  18. char* uncomplete_command = malloc(esh_info_global->max_command_length); // Used to restore after moves history
  19. for (;;) {
  20. EShShowMsg();
  21. memset(command, 0, esh_info_global->max_command_length);
  22. int command_length = 0;
  23. int current_command_pos = 0;
  24. int current_history_step = 0;
  25. char input_char;
  26. memset(uncomplete_command, 0, esh_info_global->max_command_length);
  27. while (input_char = fgetc(stdin)) {
  28. if (input_char == 10) {
  29. printf("\n");
  30. break; // 'Enter' pressed;
  31. }
  32. if (input_char == EOF) {
  33. continue;
  34. }
  35. if (input_char == '\033') { // Arrow up/down/left/right sequence
  36. fgetc(stdin);
  37. switch(fgetc(stdin)) {
  38. case 'A':
  39. {
  40. if (current_history_step == 0) {
  41. strcpy(uncomplete_command, command);
  42. }
  43. const char* new_command = EShReceiveCommandFromHistory(current_history_step);
  44. if (new_command != NULL) {
  45. ++current_history_step;
  46. for (int i = current_command_pos; i < command_length; ++i) {
  47. printf(" ");
  48. ++current_command_pos;
  49. }
  50. for (int i = current_command_pos; i > 0; --i) {
  51. printf("\b \b");
  52. }
  53. strcpy(command, new_command);
  54. command_length = strlen(new_command);
  55. current_command_pos = command_length;
  56. for (int i = 0; i < command_length; ++i) {
  57. printf("%c", command[i]);
  58. }
  59. }
  60. break;
  61. }
  62. case 'B': // Down
  63. {
  64. const char* new_command;
  65. if (current_history_step > 0) {
  66. --current_history_step;
  67. }
  68. if (current_history_step > 0) {
  69. new_command = EShReceiveCommandFromHistory(current_history_step - 1);
  70. } else {
  71. new_command = uncomplete_command;
  72. }
  73. for (int i = current_command_pos; i < command_length; ++i) {
  74. printf(" ");
  75. ++current_command_pos;
  76. }
  77. for (int i = current_command_pos; i > 0; --i) {
  78. printf("\b \b");
  79. }
  80. strcpy(command, new_command);
  81. command_length = strlen(new_command);
  82. current_command_pos = command_length;
  83. for (int i = 0; i < command_length; ++i) {
  84. printf("%c", command[i]);
  85. }
  86. break;
  87. }
  88. case 'C': // Right
  89. if (current_command_pos < command_length) {
  90. printf("%c", command[current_command_pos]);
  91. ++current_command_pos;
  92. }
  93. break;
  94. case 'D': // Left
  95. if (current_command_pos > 0) {
  96. printf("\b");
  97. --current_command_pos;
  98. }
  99. break;
  100. }
  101. continue;
  102. }
  103. if (input_char == 4) {
  104. // Ctrl + d
  105. return;
  106. }
  107. if (input_char == 127) {
  108. // Backspace
  109. if (current_command_pos > 0) {
  110. for (int i = current_command_pos - 1; i < command_length; ++i) {
  111. command[i] = command[i + 1];
  112. }
  113. command[command_length - 1] = '\0';
  114. printf("\b");
  115. printf("%s", command + current_command_pos - 1);
  116. printf(" \b");
  117. --current_command_pos;
  118. --command_length;
  119. for (int i = command_length - 1; i >= current_command_pos; --i) {
  120. printf("\b");
  121. }
  122. }
  123. continue;
  124. }
  125. if (input_char == 3) {
  126. // Ctrl + c
  127. printf("\n");
  128. return;
  129. }
  130. if (EShIsShellLetter(input_char)) {
  131. for (int i = command_length; i >= current_command_pos; --i) {
  132. command[i + 1] = command[i];
  133. }
  134. command[current_command_pos] = input_char;
  135. printf("%s", command + current_command_pos);
  136. ++current_command_pos;
  137. ++command_length;
  138. for (int i = command_length; i > current_command_pos; --i) {
  139. printf("\b");
  140. }
  141. continue;
  142. }
  143. }
  144. if (command_length == 0) {
  145. printf("\n");
  146. continue;
  147. }
  148. EShAddCommandToHistory(command);
  149. int jobs_num = 0;
  150. EShJob* jobs = EShParseCommandIntoJobs(command, &jobs_num);
  151. // EShPrintJobsDebugInfo(command, jobs, jobs_num);
  152. EShExecuteJobs(jobs_num, jobs);
  153. EShFreeJobsList(jobs);
  154. }
  155. free(command);
  156. free(uncomplete_command);
  157. /* restore the original terminal attributes */
  158. tcsetattr(fileno(stdin), TCSANOW, &orig_term_attr);
  159. }
  160. void EShShowMsg() {
  161. EShUpdateInviteMessage();
  162. printf("%s", esh_info_global->invite_message);
  163. }
  164. EShJob* EShParseCommandIntoJobs(char* command, int* jobs_num) {
  165. EShJob* jobs = EShMakeJobsList();
  166. *jobs_num = 1;
  167. int current_job_cmd_length = 0;
  168. for (int i = 0; i < strlen(command); ++i) {
  169. ESH_JOB_DELIMITER delimiter = EshIsJobDelimiter(command + i);
  170. if (delimiter != NOT_A_DELIMITER) {
  171. EShSplitJobCommand(&jobs[*jobs_num - 1], ' ');
  172. if (delimiter == SEMICOLON) {
  173. jobs[*jobs_num].job_start_condition = NO_CONDITION;
  174. }
  175. if (delimiter == LOGIC_AND) {
  176. jobs[*jobs_num].job_start_condition = PREVIOUS_EXIT_SUCCESS;
  177. }
  178. if (delimiter == LOGIC_OR) {
  179. jobs[*jobs_num].job_start_condition = PREVIOUS_EXIT_FAILED;
  180. }
  181. if (delimiter == BIT_AND) {
  182. printf(ANSI_COLOR_RED "\nESh note: running processes in background is still not available, selected job will be running in foreground :(\n" ANSI_COLOR_RESET);
  183. fflush(stdout);
  184. }
  185. if (delimiter == BIT_OR) {
  186. int pipes[2];
  187. if (pipe(pipes) != 0) {
  188. printf(ANSI_COLOR_RED "\nESh error: cannot spawn pipe: %s\n" ANSI_COLOR_RESET, strerror(errno));
  189. fflush(stdout);
  190. }
  191. jobs[*jobs_num - 1].stdout_fd = pipes[1];
  192. jobs[*jobs_num].stdin_fd = pipes[0];
  193. }
  194. ++(*jobs_num);
  195. current_job_cmd_length = 0;
  196. i += EShGetJobDelimiterSize(EshIsJobDelimiter(command + i)) - 1;
  197. continue;
  198. }
  199. jobs[*jobs_num - 1].command[current_job_cmd_length] = command[i];
  200. ++current_job_cmd_length;
  201. }
  202. EShSplitJobCommand(&jobs[*jobs_num - 1], ' ');
  203. return jobs;
  204. }
  205. void EShSplitJobCommand(EShJob* job, char delim) {
  206. int token_status = 0; // 0 - token result[result_size] finished
  207. // 1 - token result[result_size] not finished
  208. int current_token_length = 0;
  209. for (int i = 0; i < strlen(job->command); ++i) {
  210. while (job->command[i] == delim && i < strlen(job->command)) {
  211. if (token_status == 1) {
  212. token_status = 0;
  213. }
  214. ++i;
  215. }
  216. if (i == strlen(job->command)) {
  217. if (token_status == 1) {
  218. ++job->command_tokens_num;
  219. }
  220. break;
  221. }
  222. if (token_status == 0) {
  223. token_status = 1;
  224. ++job->command_tokens_num;
  225. current_token_length = 0;
  226. }
  227. job->command_tokens[job->command_tokens_num - 1][current_token_length] = job->command[i];
  228. ++current_token_length;
  229. }
  230. for (int i = 0; i < job->command_tokens_num; ++i) {
  231. EShSubstituteShellValuesArgument(&job->command_tokens[i]);
  232. }
  233. }
  234. void EShExecuteJobs(int jobs_num, EShJob* jobs_list) {
  235. int prev_job_exit_code = 0;
  236. for (int i = 0; i < jobs_num; ++i) {
  237. if (strlen(jobs_list[i].command) == 0)
  238. continue;
  239. if (jobs_list[i].job_start_condition == NO_CONDITION ||
  240. (jobs_list[i].job_start_condition == PREVIOUS_EXIT_SUCCESS && prev_job_exit_code == 0) ||
  241. (jobs_list[i].job_start_condition == PREVIOUS_EXIT_FAILED && prev_job_exit_code != 0))
  242. {
  243. EShRunJob(&jobs_list[i]);
  244. }
  245. }
  246. }
  247. void EShSetJobCommandType(EShJob* job) {
  248. }
  249. int EShRunJob(EShJob* job) {
  250. if (EShIsInnerJob(job)) {
  251. return EShProcessInnerJob(job);
  252. } else {
  253. return EShProcessExecJob(job);
  254. }
  255. // TODO: PIPES INIT & BG PROCESS SUPPORT
  256. }
  257. int EShIsInnerJob(EShJob* job) {
  258. return strcmp(job->command_tokens[0], "cd") == 0 ||
  259. strcmp(job->command_tokens[0], "exit") == 0;
  260. // TODO: jobs, bg, fg (!)
  261. }
  262. int EShProcessInnerJob(EShJob* job) {
  263. if (strcmp(job->command_tokens[0], "cd") == 0) {
  264. if (chdir(job->command_tokens[1]) == -1) {
  265. printf(ANSI_COLOR_RED "Esh: cannot change directory: %s\n" ANSI_COLOR_RESET, strerror(errno));
  266. fflush(stdout);
  267. return -1;
  268. }
  269. getcwd(esh_info_global->current_working_dir, PATH_MAX);
  270. EShOptimiseCurrentWorkingDirectory();
  271. EShUpdateInviteMessage();
  272. return 0;
  273. }
  274. if (strcmp(job->command_tokens[0], "exit") == 0) {
  275. EShExit(0);
  276. return 0; // Actually, no need in it.
  277. }
  278. }
  279. int EShProcessExecJob(EShJob* job) {
  280. int pid = fork();
  281. if (pid == 0) {
  282. if (job->stdin_fd != -1) {
  283. dup2(job->stdin_fd, STDIN_FILENO);
  284. close(job->stdin_fd);
  285. job->stdin_fd = -1;
  286. }
  287. if (job->stdout_fd != -1) {
  288. dup2(job->stdout_fd, STDOUT_FILENO);
  289. close(job->stdout_fd);
  290. job->stdout_fd = -1;
  291. }
  292. if (job->stderr_fd != -1) {
  293. dup2(job->stderr_fd, STDERR_FILENO);
  294. close(job->stderr_fd);
  295. job->stderr_fd = -1;
  296. }
  297. for (int i = job->command_tokens_num; i < esh_info_global->max_command_tokens; ++i) {
  298. free(job->command_tokens[i]);
  299. job->command_tokens[i] = NULL;
  300. }
  301. execvp(job->command_tokens[0], job->command_tokens);
  302. printf(ANSI_COLOR_RED "Esh: run command %s failed.\n" ANSI_COLOR_RESET, job->command);
  303. fflush(stdout);
  304. exit(1); // execlp failed
  305. } else {
  306. if (job->stdin_fd != -1) {
  307. close(job->stdin_fd);
  308. job->stdin_fd = -1;
  309. }
  310. if (job->stdout_fd != -1) {
  311. close(job->stdout_fd);
  312. job->stdout_fd = -1;
  313. }
  314. if (job->stderr_fd != -1) {
  315. close(job->stderr_fd);
  316. job->stderr_fd = -1;
  317. }
  318. job->job_pid = pid;
  319. int status;
  320. waitpid(pid, &status, 0);
  321. if (WIFEXITED(status)) {
  322. return WEXITSTATUS(status);
  323. } else {
  324. return -1; // No exit status received;
  325. }
  326. }
  327. }
  328. void EShSubstituteShellValuesArgument(char** arg) {
  329. char* new_str = *arg;
  330. // Processing tilda
  331. new_str = repl_str(new_str, "~", esh_info_global->user_data->pw_dir);
  332. // Processing system variables
  333. char* envvar_begin = new_str - 1;
  334. while ((envvar_begin = strchr(envvar_begin + 1, '%')) != NULL) {
  335. char* envvar_end = strchr(envvar_begin + 1, '%');
  336. if (envvar_end == NULL)
  337. break;
  338. char envvar_name[1024 * 1024];
  339. memset(envvar_name, 0, 1024 * 1024);
  340. memcpy(envvar_name, envvar_begin + 1, (envvar_end - envvar_begin - 1));
  341. char* envvar_value = getenv(envvar_name);
  342. if (envvar_value == NULL) {
  343. continue;
  344. }
  345. char envvar_name_overed[1024 * 1024];
  346. memset(envvar_name_overed, 0, 1024 * 1024);
  347. strcat(envvar_name_overed, "%");
  348. strcat(envvar_name_overed, envvar_name);
  349. strcat(envvar_name_overed, "%");
  350. new_str = repl_str(new_str, envvar_name_overed, envvar_value);
  351. }
  352. free(*arg);
  353. *arg = new_str;
  354. }
  355. void EShPrintJobsDebugInfo(const char* command, EShJob* jobs, int jobs_num) {
  356. printf("\nD: Splitted command (%s) into %d jobs:\n", command, jobs_num);
  357. for (int i = 0; i < jobs_num; ++i) {
  358. printf("===================\n"
  359. "Job #%d:\n"
  360. "Cmd: %s\n"
  361. "Cmd tokens: %d ",
  362. i, jobs[i].command, jobs[i].command_tokens_num);
  363. for (int j = 0; j < jobs[i].command_tokens_num; ++j) {
  364. printf("{%s} ", jobs[i].command_tokens[j]);
  365. }
  366. printf("\n===================\n");
  367. }
  368. printf("\n");
  369. }