TTY.cpp 12 KB

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