TTY.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2022, the SerenityOS developers.
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/ScopeGuard.h>
  8. #include <AK/StringView.h>
  9. #include <Kernel/API/POSIX/errno.h>
  10. #include <Kernel/Arch/InterruptDisabler.h>
  11. #include <Kernel/Debug.h>
  12. #include <Kernel/Process.h>
  13. #include <Kernel/TTY/TTY.h>
  14. #include <LibC/signal_numbers.h>
  15. #include <LibC/sys/ioctl_numbers.h>
  16. #define TTYDEFCHARS
  17. #include <LibC/sys/ttydefaults.h>
  18. #undef TTYDEFCHARS
  19. namespace Kernel {
  20. TTY::TTY(MajorNumber major, MinorNumber minor)
  21. : CharacterDevice(major, minor)
  22. {
  23. set_default_termios();
  24. }
  25. TTY::~TTY() = default;
  26. void TTY::set_default_termios()
  27. {
  28. memset(&m_termios, 0, sizeof(m_termios));
  29. m_termios.c_iflag = TTYDEF_IFLAG;
  30. m_termios.c_oflag = TTYDEF_OFLAG;
  31. m_termios.c_cflag = TTYDEF_CFLAG;
  32. m_termios.c_lflag = TTYDEF_LFLAG;
  33. m_termios.c_ispeed = TTYDEF_SPEED;
  34. m_termios.c_ospeed = TTYDEF_SPEED;
  35. memcpy(m_termios.c_cc, ttydefchars, sizeof(ttydefchars));
  36. }
  37. ErrorOr<size_t> TTY::read(OpenFileDescription&, u64, UserOrKernelBuffer& buffer, size_t size)
  38. {
  39. if (Process::current().pgid() != pgid()) {
  40. // FIXME: Should we propagate this error path somehow?
  41. [[maybe_unused]] auto rc = Process::current().send_signal(SIGTTIN, nullptr);
  42. return EINTR;
  43. }
  44. if (m_input_buffer.size() < static_cast<size_t>(size))
  45. size = m_input_buffer.size();
  46. bool need_evaluate_block_conditions = false;
  47. auto result = buffer.write_buffered<512>(size, [&](Bytes data) {
  48. size_t bytes_written = 0;
  49. for (; bytes_written < data.size(); ++bytes_written) {
  50. auto bit_index = m_input_buffer.head_index();
  51. bool is_special_character = m_special_character_bitmask[bit_index / 8] & (1 << (bit_index % 8));
  52. if (in_canonical_mode() && is_special_character) {
  53. u8 ch = m_input_buffer.dequeue();
  54. if (ch == '\0') {
  55. // EOF
  56. m_available_lines--;
  57. need_evaluate_block_conditions = true;
  58. break;
  59. } else {
  60. // '\n' or EOL
  61. data[bytes_written++] = ch;
  62. m_available_lines--;
  63. break;
  64. }
  65. }
  66. data[bytes_written] = m_input_buffer.dequeue();
  67. }
  68. return bytes_written;
  69. });
  70. if ((!result.is_error() && result.value() > 0) || need_evaluate_block_conditions)
  71. evaluate_block_conditions();
  72. return result;
  73. }
  74. ErrorOr<size_t> TTY::write(OpenFileDescription&, u64, UserOrKernelBuffer const& buffer, size_t size)
  75. {
  76. if (m_termios.c_lflag & TOSTOP && Process::current().pgid() != pgid()) {
  77. [[maybe_unused]] auto rc = Process::current().send_signal(SIGTTOU, nullptr);
  78. return EINTR;
  79. }
  80. constexpr size_t num_chars = 256;
  81. return buffer.read_buffered<num_chars>(size, [&](ReadonlyBytes bytes) -> ErrorOr<size_t> {
  82. u8 modified_data[num_chars * 2];
  83. size_t modified_data_size = 0;
  84. for (const auto& byte : bytes) {
  85. process_output(byte, [&modified_data, &modified_data_size](u8 out_ch) {
  86. modified_data[modified_data_size++] = out_ch;
  87. });
  88. }
  89. auto bytes_written_or_error = on_tty_write(UserOrKernelBuffer::for_kernel_buffer(modified_data), modified_data_size);
  90. if (bytes_written_or_error.is_error() || !(m_termios.c_oflag & OPOST) || !(m_termios.c_oflag & ONLCR))
  91. return bytes_written_or_error;
  92. auto bytes_written = bytes_written_or_error.value();
  93. if (bytes_written == modified_data_size)
  94. return bytes.size();
  95. // Degenerate case where we converted some newlines and encountered a partial write
  96. // Calculate where in the input buffer the last character would have been
  97. size_t pos_data = 0;
  98. for (size_t pos_modified_data = 0; pos_modified_data < bytes_written; ++pos_data) {
  99. if (bytes[pos_data] == '\n')
  100. pos_modified_data += 2;
  101. else
  102. pos_modified_data += 1;
  103. // Handle case where the '\r' got written but not the '\n'
  104. // FIXME: Our strategy is to retry writing both. We should really be queuing a write for the corresponding '\n'
  105. if (pos_modified_data > bytes_written)
  106. --pos_data;
  107. }
  108. return pos_data;
  109. });
  110. }
  111. void TTY::echo_with_processing(u8 ch)
  112. {
  113. process_output(ch, [this](u8 out_ch) { echo(out_ch); });
  114. }
  115. template<typename Functor>
  116. void TTY::process_output(u8 ch, Functor put_char)
  117. {
  118. if (m_termios.c_oflag & OPOST) {
  119. if (ch == '\n' && (m_termios.c_oflag & ONLCR))
  120. put_char('\r');
  121. put_char(ch);
  122. } else {
  123. put_char(ch);
  124. }
  125. }
  126. bool TTY::can_read(OpenFileDescription const&, u64) const
  127. {
  128. if (in_canonical_mode()) {
  129. return m_available_lines > 0;
  130. }
  131. return !m_input_buffer.is_empty();
  132. }
  133. bool TTY::can_write(OpenFileDescription const&, u64) const
  134. {
  135. return true;
  136. }
  137. bool TTY::is_eol(u8 ch) const
  138. {
  139. return ch == m_termios.c_cc[VEOL];
  140. }
  141. bool TTY::is_eof(u8 ch) const
  142. {
  143. return ch == m_termios.c_cc[VEOF];
  144. }
  145. bool TTY::is_kill(u8 ch) const
  146. {
  147. return ch == m_termios.c_cc[VKILL];
  148. }
  149. bool TTY::is_erase(u8 ch) const
  150. {
  151. return ch == m_termios.c_cc[VERASE];
  152. }
  153. bool TTY::is_werase(u8 ch) const
  154. {
  155. return ch == m_termios.c_cc[VWERASE];
  156. }
  157. void TTY::emit(u8 ch, bool do_evaluate_block_conditions)
  158. {
  159. if (m_termios.c_iflag & ISTRIP)
  160. ch &= 0x7F;
  161. if (should_generate_signals()) {
  162. if (ch == m_termios.c_cc[VINFO]) {
  163. generate_signal(SIGINFO);
  164. return;
  165. }
  166. if (ch == m_termios.c_cc[VINTR]) {
  167. generate_signal(SIGINT);
  168. return;
  169. }
  170. if (ch == m_termios.c_cc[VQUIT]) {
  171. generate_signal(SIGQUIT);
  172. return;
  173. }
  174. if (ch == m_termios.c_cc[VSUSP]) {
  175. generate_signal(SIGTSTP);
  176. if (auto original_process_parent = m_original_process_parent.strong_ref()) {
  177. [[maybe_unused]] auto rc = original_process_parent->send_signal(SIGCHLD, nullptr);
  178. }
  179. // TODO: Else send it to the session leader maybe?
  180. return;
  181. }
  182. }
  183. ScopeGuard guard([&]() {
  184. if (do_evaluate_block_conditions)
  185. evaluate_block_conditions();
  186. });
  187. if (ch == '\r' && (m_termios.c_iflag & ICRNL))
  188. ch = '\n';
  189. else if (ch == '\n' && (m_termios.c_iflag & INLCR))
  190. ch = '\r';
  191. auto current_char_head_index = (m_input_buffer.head_index() + m_input_buffer.size()) % TTY_BUFFER_SIZE;
  192. m_special_character_bitmask[current_char_head_index / 8] &= ~(1u << (current_char_head_index % 8));
  193. auto set_special_bit = [&] {
  194. m_special_character_bitmask[current_char_head_index / 8] |= (1u << (current_char_head_index % 8));
  195. };
  196. if (in_canonical_mode()) {
  197. if (is_eof(ch)) {
  198. // Since EOF might change between when the data came in and when it is read,
  199. // we use '\0' along with the bitmask to signal EOF. Any non-zero byte with
  200. // the special bit set signals an end-of-line.
  201. set_special_bit();
  202. m_available_lines++;
  203. m_input_buffer.enqueue('\0');
  204. return;
  205. }
  206. if (is_kill(ch) && m_termios.c_lflag & ECHOK) {
  207. kill_line();
  208. return;
  209. }
  210. if (is_erase(ch) && m_termios.c_lflag & ECHOE) {
  211. do_backspace();
  212. return;
  213. }
  214. if (is_werase(ch)) {
  215. erase_word();
  216. return;
  217. }
  218. if (ch == '\n') {
  219. if (m_termios.c_lflag & ECHO || m_termios.c_lflag & ECHONL)
  220. echo_with_processing('\n');
  221. set_special_bit();
  222. m_input_buffer.enqueue('\n');
  223. m_available_lines++;
  224. return;
  225. }
  226. if (is_eol(ch)) {
  227. set_special_bit();
  228. m_available_lines++;
  229. }
  230. }
  231. m_input_buffer.enqueue(ch);
  232. if (m_termios.c_lflag & ECHO)
  233. echo_with_processing(ch);
  234. }
  235. bool TTY::can_do_backspace() const
  236. {
  237. // can't do back space if we're empty. Plus, we don't want to
  238. // remove any lines "committed" by newlines or ^D.
  239. if (!m_input_buffer.is_empty() && !is_eol(m_input_buffer.last()) && m_input_buffer.last() != '\0') {
  240. return true;
  241. }
  242. return false;
  243. }
  244. static size_t length_with_tabs(CircularDeque<u8, TTY_BUFFER_SIZE> const& line)
  245. {
  246. size_t length = 0;
  247. for (auto& ch : line) {
  248. length += (ch == '\t') ? 8 - (length % 8) : 1;
  249. }
  250. return length;
  251. }
  252. void TTY::do_backspace()
  253. {
  254. if (can_do_backspace()) {
  255. auto ch = m_input_buffer.dequeue_end();
  256. size_t to_delete = 1;
  257. if (ch == '\t') {
  258. auto length = length_with_tabs(m_input_buffer);
  259. to_delete = 8 - (length % 8);
  260. }
  261. for (size_t i = 0; i < to_delete; ++i) {
  262. // We deliberately don't process the output here.
  263. echo('\b');
  264. echo(' ');
  265. echo('\b');
  266. }
  267. evaluate_block_conditions();
  268. }
  269. }
  270. // TODO: Currently, both erase_word() and kill_line work by sending
  271. // a lot of VERASE characters; this is done because Terminal.cpp
  272. // doesn't currently support VWERASE and VKILL. When these are
  273. // implemented we could just send a VKILL or VWERASE.
  274. void TTY::erase_word()
  275. {
  276. // Note: if we have leading whitespace before the word
  277. // we want to delete we have to also delete that.
  278. bool first_char = false;
  279. bool did_dequeue = false;
  280. while (can_do_backspace()) {
  281. u8 ch = m_input_buffer.last();
  282. if (ch == ' ' && first_char)
  283. break;
  284. if (ch != ' ')
  285. first_char = true;
  286. m_input_buffer.dequeue_end();
  287. did_dequeue = true;
  288. erase_character();
  289. }
  290. if (did_dequeue)
  291. evaluate_block_conditions();
  292. }
  293. void TTY::kill_line()
  294. {
  295. bool did_dequeue = false;
  296. while (can_do_backspace()) {
  297. m_input_buffer.dequeue_end();
  298. did_dequeue = true;
  299. erase_character();
  300. }
  301. if (did_dequeue)
  302. evaluate_block_conditions();
  303. }
  304. void TTY::erase_character()
  305. {
  306. // We deliberately don't process the output here.
  307. echo(m_termios.c_cc[VERASE]);
  308. echo(' ');
  309. echo(m_termios.c_cc[VERASE]);
  310. }
  311. void TTY::generate_signal(int signal)
  312. {
  313. if (!pgid())
  314. return;
  315. if (should_flush_on_signal())
  316. flush_input();
  317. dbgln_if(TTY_DEBUG, "Send signal {} to everyone in pgrp {}", signal, pgid().value());
  318. InterruptDisabler disabler; // FIXME: Iterate over a set of process handles instead?
  319. Process::for_each_in_pgrp(pgid(), [&](auto& process) {
  320. dbgln_if(TTY_DEBUG, "Send signal {} to {}", signal, process);
  321. // FIXME: Should this error be propagated somehow?
  322. [[maybe_unused]] auto rc = process.send_signal(signal, nullptr);
  323. });
  324. }
  325. void TTY::flush_input()
  326. {
  327. m_available_lines = 0;
  328. m_input_buffer.clear();
  329. evaluate_block_conditions();
  330. }
  331. ErrorOr<void> TTY::set_termios(termios const& t)
  332. {
  333. ErrorOr<void> rc;
  334. m_termios = t;
  335. dbgln_if(TTY_DEBUG, "set_termios: ECHO={}, ISIG={}, ICANON={}, ECHOE={}, ECHOK={}, ECHONL={}, ISTRIP={}, ICRNL={}, INLCR={}, IGNCR={}, OPOST={}, ONLCR={}",
  336. should_echo_input(),
  337. should_generate_signals(),
  338. in_canonical_mode(),
  339. ((m_termios.c_lflag & ECHOE) != 0),
  340. ((m_termios.c_lflag & ECHOK) != 0),
  341. ((m_termios.c_lflag & ECHONL) != 0),
  342. ((m_termios.c_iflag & ISTRIP) != 0),
  343. ((m_termios.c_iflag & ICRNL) != 0),
  344. ((m_termios.c_iflag & INLCR) != 0),
  345. ((m_termios.c_iflag & IGNCR) != 0),
  346. ((m_termios.c_oflag & OPOST) != 0),
  347. ((m_termios.c_oflag & ONLCR) != 0));
  348. struct FlagDescription {
  349. tcflag_t value;
  350. StringView name;
  351. };
  352. constexpr FlagDescription unimplemented_iflags[] = {
  353. { IGNBRK, "IGNBRK" },
  354. { BRKINT, "BRKINT" },
  355. { IGNPAR, "IGNPAR" },
  356. { PARMRK, "PARMRK" },
  357. { INPCK, "INPCK" },
  358. { IGNCR, "IGNCR" },
  359. { IUCLC, "IUCLC" },
  360. { IXON, "IXON" },
  361. { IXANY, "IXANY" },
  362. { IXOFF, "IXOFF" },
  363. { IMAXBEL, "IMAXBEL" },
  364. { IUTF8, "IUTF8" }
  365. };
  366. for (auto flag : unimplemented_iflags) {
  367. if (m_termios.c_iflag & flag.value) {
  368. dbgln("FIXME: iflag {} unimplemented", flag.name);
  369. rc = ENOTIMPL;
  370. }
  371. }
  372. constexpr FlagDescription unimplemented_oflags[] = {
  373. { OLCUC, "OLCUC" },
  374. { ONOCR, "ONOCR" },
  375. { ONLRET, "ONLRET" },
  376. { OFILL, "OFILL" },
  377. { OFDEL, "OFDEL" }
  378. };
  379. for (auto flag : unimplemented_oflags) {
  380. if (m_termios.c_oflag & flag.value) {
  381. dbgln("FIXME: oflag {} unimplemented", flag.name);
  382. rc = ENOTIMPL;
  383. }
  384. }
  385. if ((m_termios.c_cflag & CSIZE) != CS8) {
  386. dbgln("FIXME: Character sizes other than 8 bits are not supported");
  387. rc = ENOTIMPL;
  388. }
  389. constexpr FlagDescription unimplemented_cflags[] = {
  390. { CSTOPB, "CSTOPB" },
  391. { CREAD, "CREAD" },
  392. { PARENB, "PARENB" },
  393. { PARODD, "PARODD" },
  394. { HUPCL, "HUPCL" },
  395. { CLOCAL, "CLOCAL" }
  396. };
  397. for (auto flag : unimplemented_cflags) {
  398. if (m_termios.c_cflag & flag.value) {
  399. dbgln("FIXME: cflag {} unimplemented", flag.name);
  400. rc = ENOTIMPL;
  401. }
  402. }
  403. constexpr FlagDescription unimplemented_lflags[] = {
  404. { TOSTOP, "TOSTOP" },
  405. { IEXTEN, "IEXTEN" }
  406. };
  407. for (auto flag : unimplemented_lflags) {
  408. if (m_termios.c_lflag & flag.value) {
  409. dbgln("FIXME: lflag {} unimplemented", flag.name);
  410. rc = ENOTIMPL;
  411. }
  412. }
  413. return rc;
  414. }
  415. ErrorOr<void> TTY::ioctl(OpenFileDescription&, unsigned request, Userspace<void*> arg)
  416. {
  417. auto& current_process = Process::current();
  418. TRY(current_process.require_promise(Pledge::tty));
  419. #if 0
  420. // FIXME: When should we block things?
  421. // How do we make this work together with MasterPTY forwarding to us?
  422. if (current_process.tty() && current_process.tty() != this) {
  423. return ENOTTY;
  424. }
  425. #endif
  426. switch (request) {
  427. case TIOCGPGRP: {
  428. auto user_pgid = static_ptr_cast<pid_t*>(arg);
  429. auto pgid = this->pgid().value();
  430. return copy_to_user(user_pgid, &pgid);
  431. }
  432. case TIOCSPGRP: {
  433. ProcessGroupID pgid = static_cast<pid_t>(arg.ptr());
  434. if (pgid <= 0)
  435. return EINVAL;
  436. InterruptDisabler disabler;
  437. auto process_group = ProcessGroup::from_pgid(pgid);
  438. // Disallow setting a nonexistent PGID.
  439. if (!process_group)
  440. return EINVAL;
  441. auto process = Process::from_pid(ProcessID(pgid.value()));
  442. SessionID new_sid = process ? process->sid() : Process::get_sid_from_pgid(pgid);
  443. if (!new_sid || new_sid != current_process.sid())
  444. return EPERM;
  445. if (process && pgid != process->pgid())
  446. return EPERM;
  447. m_pg = process_group;
  448. if (process) {
  449. if (auto parent = Process::from_pid(process->ppid())) {
  450. m_original_process_parent = *parent;
  451. return {};
  452. }
  453. }
  454. m_original_process_parent = nullptr;
  455. return {};
  456. }
  457. case TCGETS: {
  458. auto user_termios = static_ptr_cast<termios*>(arg);
  459. return copy_to_user(user_termios, &m_termios);
  460. }
  461. case TCSETS:
  462. case TCSETSF:
  463. case TCSETSW: {
  464. auto user_termios = static_ptr_cast<termios const*>(arg);
  465. auto termios = TRY(copy_typed_from_user(user_termios));
  466. auto rc = set_termios(termios);
  467. if (request == TCSETSF)
  468. flush_input();
  469. return rc;
  470. }
  471. case TCFLSH: {
  472. // Serenity's TTY implementation does not use an output buffer, so ignore TCOFLUSH.
  473. auto operation = static_cast<u8>(arg.ptr());
  474. if (operation == TCIFLUSH || operation == TCIOFLUSH) {
  475. flush_input();
  476. } else if (operation != TCOFLUSH) {
  477. return EINVAL;
  478. }
  479. return {};
  480. }
  481. case TIOCGWINSZ: {
  482. auto user_winsize = static_ptr_cast<winsize*>(arg);
  483. winsize ws {};
  484. ws.ws_row = m_rows;
  485. ws.ws_col = m_columns;
  486. ws.ws_xpixel = 0;
  487. ws.ws_ypixel = 0;
  488. return copy_to_user(user_winsize, &ws);
  489. }
  490. case TIOCSWINSZ: {
  491. auto user_winsize = static_ptr_cast<winsize const*>(arg);
  492. auto ws = TRY(copy_typed_from_user(user_winsize));
  493. if (ws.ws_col == m_columns && ws.ws_row == m_rows)
  494. return {};
  495. m_rows = ws.ws_row;
  496. m_columns = ws.ws_col;
  497. generate_signal(SIGWINCH);
  498. return {};
  499. }
  500. case TIOCSCTTY:
  501. current_process.set_tty(this);
  502. return {};
  503. case TIOCSTI:
  504. return EIO;
  505. case TIOCNOTTY:
  506. current_process.set_tty(nullptr);
  507. return {};
  508. case KDSETMODE: {
  509. auto mode = static_cast<unsigned int>(arg.ptr());
  510. if (mode != KD_TEXT && mode != KD_GRAPHICS)
  511. return EINVAL;
  512. set_graphical(mode == KD_GRAPHICS);
  513. return {};
  514. }
  515. case KDGETMODE: {
  516. auto mode_ptr = static_ptr_cast<int*>(arg);
  517. int mode = (is_graphical()) ? KD_GRAPHICS : KD_TEXT;
  518. return copy_to_user(mode_ptr, &mode);
  519. }
  520. }
  521. return EINVAL;
  522. }
  523. void TTY::set_size(unsigned short columns, unsigned short rows)
  524. {
  525. m_rows = rows;
  526. m_columns = columns;
  527. }
  528. void TTY::hang_up()
  529. {
  530. generate_signal(SIGHUP);
  531. }
  532. }