TTY.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/ScopeGuard.h>
  7. #include <Kernel/Debug.h>
  8. #include <Kernel/Process.h>
  9. #include <Kernel/TTY/TTY.h>
  10. #include <LibC/errno_numbers.h>
  11. #include <LibC/signal_numbers.h>
  12. #include <LibC/sys/ioctl_numbers.h>
  13. namespace Kernel {
  14. TTY::TTY(unsigned major, unsigned minor)
  15. : CharacterDevice(major, minor)
  16. {
  17. set_default_termios();
  18. }
  19. TTY::~TTY()
  20. {
  21. }
  22. void TTY::set_default_termios()
  23. {
  24. memset(&m_termios, 0, sizeof(m_termios));
  25. m_termios.c_lflag |= ISIG | ECHO | ICANON;
  26. static const char default_cc[32] = "\003\034\010\025\004\0\1\0\021\023\032\0\022\017\027\026\0\024";
  27. memcpy(m_termios.c_cc, default_cc, sizeof(default_cc));
  28. }
  29. KResultOr<size_t> TTY::read(FileDescription&, u64, UserOrKernelBuffer& buffer, size_t size)
  30. {
  31. if (Process::current()->pgid() != pgid()) {
  32. // FIXME: Should we propagate this error path somehow?
  33. [[maybe_unused]] auto rc = Process::current()->send_signal(SIGTTIN, nullptr);
  34. return EINTR;
  35. }
  36. if (m_input_buffer.size() < static_cast<size_t>(size))
  37. size = m_input_buffer.size();
  38. ssize_t nwritten;
  39. bool need_evaluate_block_conditions = false;
  40. if (in_canonical_mode()) {
  41. nwritten = buffer.write_buffered<512>(size, [&](u8* data, size_t data_size) {
  42. size_t i = 0;
  43. for (; i < data_size; i++) {
  44. u8 ch = m_input_buffer.dequeue();
  45. if (ch == '\0') {
  46. //Here we handle a ^D line, so we don't add the
  47. //character to the output.
  48. m_available_lines--;
  49. need_evaluate_block_conditions = true;
  50. break;
  51. } else if (ch == '\n' || is_eol(ch)) {
  52. data[i] = ch;
  53. i++;
  54. m_available_lines--;
  55. break;
  56. }
  57. data[i] = ch;
  58. }
  59. return (ssize_t)i;
  60. });
  61. } else {
  62. nwritten = buffer.write_buffered<512>(size, [&](u8* data, size_t data_size) {
  63. for (size_t i = 0; i < data_size; i++) {
  64. auto ch = m_input_buffer.dequeue();
  65. if (ch == '\r' && m_termios.c_iflag & ICRNL)
  66. ch = '\n';
  67. else if (ch == '\n' && m_termios.c_iflag & INLCR)
  68. ch = '\r';
  69. data[i] = ch;
  70. }
  71. return (ssize_t)data_size;
  72. });
  73. }
  74. if (nwritten < 0)
  75. return KResult((ErrnoCode)-nwritten);
  76. if (nwritten > 0 || need_evaluate_block_conditions)
  77. evaluate_block_conditions();
  78. return (size_t)nwritten;
  79. }
  80. KResultOr<size_t> TTY::write(FileDescription&, u64, const UserOrKernelBuffer& buffer, size_t size)
  81. {
  82. if (m_termios.c_lflag & TOSTOP && Process::current()->pgid() != pgid()) {
  83. [[maybe_unused]] auto rc = Process::current()->send_signal(SIGTTOU, nullptr);
  84. return EINTR;
  85. }
  86. const size_t num_chars = 256;
  87. ssize_t nread = buffer.read_buffered<num_chars>((size_t)size, [&](const u8* data, size_t buffer_bytes) {
  88. u8 modified_data[num_chars * 2];
  89. size_t extra_chars = 0;
  90. for (size_t i = 0; i < buffer_bytes; ++i) {
  91. auto ch = data[i];
  92. if (ch == '\n' && (m_termios.c_oflag & (OPOST | ONLCR))) {
  93. modified_data[i + extra_chars] = '\r';
  94. extra_chars++;
  95. }
  96. modified_data[i + extra_chars] = ch;
  97. }
  98. on_tty_write(UserOrKernelBuffer::for_kernel_buffer(modified_data), buffer_bytes + extra_chars);
  99. return (ssize_t)buffer_bytes;
  100. });
  101. return nread;
  102. }
  103. bool TTY::can_read(const FileDescription&, size_t) const
  104. {
  105. if (in_canonical_mode()) {
  106. return m_available_lines > 0;
  107. }
  108. return !m_input_buffer.is_empty();
  109. }
  110. bool TTY::can_write(const FileDescription&, size_t) const
  111. {
  112. return true;
  113. }
  114. bool TTY::is_eol(u8 ch) const
  115. {
  116. return ch == m_termios.c_cc[VEOL];
  117. }
  118. bool TTY::is_eof(u8 ch) const
  119. {
  120. return ch == m_termios.c_cc[VEOF];
  121. }
  122. bool TTY::is_kill(u8 ch) const
  123. {
  124. return ch == m_termios.c_cc[VKILL];
  125. }
  126. bool TTY::is_erase(u8 ch) const
  127. {
  128. return ch == m_termios.c_cc[VERASE];
  129. }
  130. bool TTY::is_werase(u8 ch) const
  131. {
  132. return ch == m_termios.c_cc[VWERASE];
  133. }
  134. void TTY::emit(u8 ch, bool do_evaluate_block_conditions)
  135. {
  136. if (should_generate_signals()) {
  137. if (ch == m_termios.c_cc[VINFO]) {
  138. dbgln("{}: VINFO pressed!", tty_name());
  139. generate_signal(SIGINFO);
  140. return;
  141. }
  142. if (ch == m_termios.c_cc[VINTR]) {
  143. dbgln("{}: VINTR pressed!", tty_name());
  144. generate_signal(SIGINT);
  145. return;
  146. }
  147. if (ch == m_termios.c_cc[VQUIT]) {
  148. dbgln("{}: VQUIT pressed!", tty_name());
  149. generate_signal(SIGQUIT);
  150. return;
  151. }
  152. if (ch == m_termios.c_cc[VSUSP]) {
  153. dbgln("{}: VSUSP pressed!", tty_name());
  154. generate_signal(SIGTSTP);
  155. if (auto original_process_parent = m_original_process_parent.strong_ref()) {
  156. [[maybe_unused]] auto rc = original_process_parent->send_signal(SIGCHLD, nullptr);
  157. }
  158. // TODO: Else send it to the session leader maybe?
  159. return;
  160. }
  161. }
  162. ScopeGuard guard([&]() {
  163. if (do_evaluate_block_conditions)
  164. evaluate_block_conditions();
  165. });
  166. if (in_canonical_mode()) {
  167. if (is_eof(ch)) {
  168. m_available_lines++;
  169. //We use '\0' to delimit the end
  170. //of a line.
  171. m_input_buffer.enqueue('\0');
  172. return;
  173. }
  174. if (is_kill(ch)) {
  175. kill_line();
  176. return;
  177. }
  178. if (is_erase(ch)) {
  179. do_backspace();
  180. return;
  181. }
  182. if (is_werase(ch)) {
  183. erase_word();
  184. return;
  185. }
  186. if (ch == '\n' || is_eol(ch)) {
  187. m_available_lines++;
  188. }
  189. }
  190. m_input_buffer.enqueue(ch);
  191. echo(ch);
  192. }
  193. bool TTY::can_do_backspace() const
  194. {
  195. // can't do back space if we're empty. Plus, we don't want to
  196. // remove any lines "committed" by newlines or ^D.
  197. if (!m_input_buffer.is_empty() && !is_eol(m_input_buffer.last()) && m_input_buffer.last() != '\0') {
  198. return true;
  199. }
  200. return false;
  201. }
  202. void TTY::do_backspace()
  203. {
  204. if (can_do_backspace()) {
  205. m_input_buffer.dequeue_end();
  206. echo(8);
  207. echo(' ');
  208. echo(8);
  209. evaluate_block_conditions();
  210. }
  211. }
  212. // TODO: Currently, both erase_word() and kill_line work by sending
  213. // a lot of VERASE characters; this is done because Terminal.cpp
  214. // doesn't currently support VWERASE and VKILL. When these are
  215. // implemented we could just send a VKILL or VWERASE.
  216. void TTY::erase_word()
  217. {
  218. //Note: if we have leading whitespace before the word
  219. //we want to delete we have to also delete that.
  220. bool first_char = false;
  221. bool did_dequeue = false;
  222. while (can_do_backspace()) {
  223. u8 ch = m_input_buffer.last();
  224. if (ch == ' ' && first_char)
  225. break;
  226. if (ch != ' ')
  227. first_char = true;
  228. m_input_buffer.dequeue_end();
  229. did_dequeue = true;
  230. erase_character();
  231. }
  232. if (did_dequeue)
  233. evaluate_block_conditions();
  234. }
  235. void TTY::kill_line()
  236. {
  237. bool did_dequeue = false;
  238. while (can_do_backspace()) {
  239. m_input_buffer.dequeue_end();
  240. did_dequeue = true;
  241. erase_character();
  242. }
  243. if (did_dequeue)
  244. evaluate_block_conditions();
  245. }
  246. void TTY::erase_character()
  247. {
  248. echo(m_termios.c_cc[VERASE]);
  249. echo(' ');
  250. echo(m_termios.c_cc[VERASE]);
  251. }
  252. void TTY::generate_signal(int signal)
  253. {
  254. if (!pgid())
  255. return;
  256. if (should_flush_on_signal())
  257. flush_input();
  258. dbgln_if(TTY_DEBUG, "{}: Send signal {} to everyone in pgrp {}", tty_name(), signal, pgid().value());
  259. InterruptDisabler disabler; // FIXME: Iterate over a set of process handles instead?
  260. Process::for_each_in_pgrp(pgid(), [&](auto& process) {
  261. dbgln_if(TTY_DEBUG, "{}: Send signal {} to {}", tty_name(), signal, process);
  262. // FIXME: Should this error be propagated somehow?
  263. [[maybe_unused]] auto rc = process.send_signal(signal, nullptr);
  264. return IterationDecision::Continue;
  265. });
  266. }
  267. void TTY::flush_input()
  268. {
  269. m_available_lines = 0;
  270. m_input_buffer.clear();
  271. evaluate_block_conditions();
  272. }
  273. void TTY::set_termios(const termios& t)
  274. {
  275. m_termios = t;
  276. dbgln_if(TTY_DEBUG, "{} set_termios: ECHO={}, ISIG={}, ICANON={}, ECHOE={}, ECHOK={}, ECHONL={}, ISTRIP={}, ICRNL={}, INLCR={}, IGNCR={}, OPOST={}, ONLCR={}",
  277. tty_name(),
  278. should_echo_input(),
  279. should_generate_signals(),
  280. in_canonical_mode(),
  281. ((m_termios.c_lflag & ECHOE) != 0),
  282. ((m_termios.c_lflag & ECHOK) != 0),
  283. ((m_termios.c_lflag & ECHONL) != 0),
  284. ((m_termios.c_iflag & ISTRIP) != 0),
  285. ((m_termios.c_iflag & ICRNL) != 0),
  286. ((m_termios.c_iflag & INLCR) != 0),
  287. ((m_termios.c_iflag & IGNCR) != 0),
  288. ((m_termios.c_oflag & OPOST) != 0),
  289. ((m_termios.c_oflag & ONLCR) != 0));
  290. }
  291. int TTY::ioctl(FileDescription&, unsigned request, FlatPtr arg)
  292. {
  293. REQUIRE_PROMISE(tty);
  294. auto& current_process = *Process::current();
  295. termios* user_termios;
  296. winsize* user_winsize;
  297. #if 0
  298. // FIXME: When should we block things?
  299. // How do we make this work together with MasterPTY forwarding to us?
  300. if (current_process.tty() && current_process.tty() != this) {
  301. return -ENOTTY;
  302. }
  303. #endif
  304. switch (request) {
  305. case TIOCGPGRP:
  306. return this->pgid().value();
  307. case TIOCSPGRP: {
  308. ProcessGroupID pgid = static_cast<pid_t>(arg);
  309. if (pgid <= 0)
  310. return -EINVAL;
  311. InterruptDisabler disabler;
  312. auto process_group = ProcessGroup::from_pgid(pgid);
  313. // Disallow setting a nonexistent PGID.
  314. if (!process_group)
  315. return -EINVAL;
  316. auto process = Process::from_pid(ProcessID(pgid.value()));
  317. SessionID new_sid = process ? process->sid() : Process::get_sid_from_pgid(pgid);
  318. if (!new_sid || new_sid != current_process.sid())
  319. return -EPERM;
  320. if (process && pgid != process->pgid())
  321. return -EPERM;
  322. m_pg = process_group;
  323. if (process) {
  324. if (auto parent = Process::from_pid(process->ppid())) {
  325. m_original_process_parent = *parent;
  326. return 0;
  327. }
  328. }
  329. m_original_process_parent = nullptr;
  330. return 0;
  331. }
  332. case TCGETS: {
  333. user_termios = reinterpret_cast<termios*>(arg);
  334. if (!copy_to_user(user_termios, &m_termios))
  335. return -EFAULT;
  336. return 0;
  337. }
  338. case TCSETS:
  339. case TCSETSF:
  340. case TCSETSW: {
  341. user_termios = reinterpret_cast<termios*>(arg);
  342. termios termios;
  343. if (!copy_from_user(&termios, user_termios))
  344. return -EFAULT;
  345. set_termios(termios);
  346. if (request == TCSETSF)
  347. flush_input();
  348. return 0;
  349. }
  350. case TCFLSH:
  351. // Serenity's TTY implementation does not use an output buffer, so ignore TCOFLUSH.
  352. if (arg == TCIFLUSH || arg == TCIOFLUSH) {
  353. flush_input();
  354. } else if (arg != TCOFLUSH) {
  355. return -EINVAL;
  356. }
  357. return 0;
  358. case TIOCGWINSZ:
  359. user_winsize = reinterpret_cast<winsize*>(arg);
  360. winsize ws;
  361. ws.ws_row = m_rows;
  362. ws.ws_col = m_columns;
  363. ws.ws_xpixel = 0;
  364. ws.ws_ypixel = 0;
  365. if (!copy_to_user(user_winsize, &ws))
  366. return -EFAULT;
  367. return 0;
  368. case TIOCSWINSZ: {
  369. user_winsize = reinterpret_cast<winsize*>(arg);
  370. winsize ws;
  371. if (!copy_from_user(&ws, user_winsize))
  372. return -EFAULT;
  373. if (ws.ws_col == m_columns && ws.ws_row == m_rows)
  374. return 0;
  375. m_rows = ws.ws_row;
  376. m_columns = ws.ws_col;
  377. generate_signal(SIGWINCH);
  378. return 0;
  379. }
  380. case TIOCSCTTY:
  381. current_process.set_tty(this);
  382. return 0;
  383. case TIOCSTI:
  384. return -EIO;
  385. case TIOCNOTTY:
  386. current_process.set_tty(nullptr);
  387. return 0;
  388. }
  389. return -EINVAL;
  390. }
  391. void TTY::set_size(unsigned short columns, unsigned short rows)
  392. {
  393. m_rows = rows;
  394. m_columns = columns;
  395. }
  396. void TTY::hang_up()
  397. {
  398. generate_signal(SIGHUP);
  399. }
  400. }