TTY.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  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/x86/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, const UserOrKernelBuffer& 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(const OpenFileDescription&, 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(const OpenFileDescription&, 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. dbgln("{}: VINFO pressed!", tty_name());
  164. generate_signal(SIGINFO);
  165. return;
  166. }
  167. if (ch == m_termios.c_cc[VINTR]) {
  168. dbgln("{}: VINTR pressed!", tty_name());
  169. generate_signal(SIGINT);
  170. return;
  171. }
  172. if (ch == m_termios.c_cc[VQUIT]) {
  173. dbgln("{}: VQUIT pressed!", tty_name());
  174. generate_signal(SIGQUIT);
  175. return;
  176. }
  177. if (ch == m_termios.c_cc[VSUSP]) {
  178. dbgln("{}: VSUSP pressed!", tty_name());
  179. generate_signal(SIGTSTP);
  180. if (auto original_process_parent = m_original_process_parent.strong_ref()) {
  181. [[maybe_unused]] auto rc = original_process_parent->send_signal(SIGCHLD, nullptr);
  182. }
  183. // TODO: Else send it to the session leader maybe?
  184. return;
  185. }
  186. }
  187. ScopeGuard guard([&]() {
  188. if (do_evaluate_block_conditions)
  189. evaluate_block_conditions();
  190. });
  191. if (ch == '\r' && (m_termios.c_iflag & ICRNL))
  192. ch = '\n';
  193. else if (ch == '\n' && (m_termios.c_iflag & INLCR))
  194. ch = '\r';
  195. auto current_char_head_index = (m_input_buffer.head_index() + m_input_buffer.size()) % TTY_BUFFER_SIZE;
  196. m_special_character_bitmask[current_char_head_index / 8] &= ~(1u << (current_char_head_index % 8));
  197. auto set_special_bit = [&] {
  198. m_special_character_bitmask[current_char_head_index / 8] |= (1u << (current_char_head_index % 8));
  199. };
  200. if (in_canonical_mode()) {
  201. if (is_eof(ch)) {
  202. // Since EOF might change between when the data came in and when it is read,
  203. // we use '\0' along with the bitmask to signal EOF. Any non-zero byte with
  204. // the special bit set signals an end-of-line.
  205. set_special_bit();
  206. m_available_lines++;
  207. m_input_buffer.enqueue('\0');
  208. return;
  209. }
  210. if (is_kill(ch) && m_termios.c_lflag & ECHOK) {
  211. kill_line();
  212. return;
  213. }
  214. if (is_erase(ch) && m_termios.c_lflag & ECHOE) {
  215. do_backspace();
  216. return;
  217. }
  218. if (is_werase(ch)) {
  219. erase_word();
  220. return;
  221. }
  222. if (ch == '\n') {
  223. if (m_termios.c_lflag & ECHO || m_termios.c_lflag & ECHONL)
  224. echo_with_processing('\n');
  225. set_special_bit();
  226. m_input_buffer.enqueue('\n');
  227. m_available_lines++;
  228. return;
  229. }
  230. if (is_eol(ch)) {
  231. set_special_bit();
  232. m_available_lines++;
  233. }
  234. }
  235. m_input_buffer.enqueue(ch);
  236. if (m_termios.c_lflag & ECHO)
  237. echo_with_processing(ch);
  238. }
  239. bool TTY::can_do_backspace() const
  240. {
  241. // can't do back space if we're empty. Plus, we don't want to
  242. // remove any lines "committed" by newlines or ^D.
  243. if (!m_input_buffer.is_empty() && !is_eol(m_input_buffer.last()) && m_input_buffer.last() != '\0') {
  244. return true;
  245. }
  246. return false;
  247. }
  248. static size_t length_with_tabs(CircularDeque<u8, TTY_BUFFER_SIZE> const& line)
  249. {
  250. size_t length = 0;
  251. for (auto& ch : line) {
  252. length += (ch == '\t') ? 8 - (length % 8) : 1;
  253. }
  254. return length;
  255. }
  256. void TTY::do_backspace()
  257. {
  258. if (can_do_backspace()) {
  259. auto ch = m_input_buffer.dequeue_end();
  260. size_t to_delete = 1;
  261. if (ch == '\t') {
  262. auto length = length_with_tabs(m_input_buffer);
  263. to_delete = 8 - (length % 8);
  264. }
  265. for (size_t i = 0; i < to_delete; ++i) {
  266. // We deliberately don't process the output here.
  267. echo('\b');
  268. echo(' ');
  269. echo('\b');
  270. }
  271. evaluate_block_conditions();
  272. }
  273. }
  274. // TODO: Currently, both erase_word() and kill_line work by sending
  275. // a lot of VERASE characters; this is done because Terminal.cpp
  276. // doesn't currently support VWERASE and VKILL. When these are
  277. // implemented we could just send a VKILL or VWERASE.
  278. void TTY::erase_word()
  279. {
  280. //Note: if we have leading whitespace before the word
  281. //we want to delete we have to also delete that.
  282. bool first_char = false;
  283. bool did_dequeue = false;
  284. while (can_do_backspace()) {
  285. u8 ch = m_input_buffer.last();
  286. if (ch == ' ' && first_char)
  287. break;
  288. if (ch != ' ')
  289. first_char = true;
  290. m_input_buffer.dequeue_end();
  291. did_dequeue = true;
  292. erase_character();
  293. }
  294. if (did_dequeue)
  295. evaluate_block_conditions();
  296. }
  297. void TTY::kill_line()
  298. {
  299. bool did_dequeue = false;
  300. while (can_do_backspace()) {
  301. m_input_buffer.dequeue_end();
  302. did_dequeue = true;
  303. erase_character();
  304. }
  305. if (did_dequeue)
  306. evaluate_block_conditions();
  307. }
  308. void TTY::erase_character()
  309. {
  310. // We deliberately don't process the output here.
  311. echo(m_termios.c_cc[VERASE]);
  312. echo(' ');
  313. echo(m_termios.c_cc[VERASE]);
  314. }
  315. void TTY::generate_signal(int signal)
  316. {
  317. if (!pgid())
  318. return;
  319. if (should_flush_on_signal())
  320. flush_input();
  321. dbgln_if(TTY_DEBUG, "{}: Send signal {} to everyone in pgrp {}", tty_name(), signal, pgid().value());
  322. InterruptDisabler disabler; // FIXME: Iterate over a set of process handles instead?
  323. Process::for_each_in_pgrp(pgid(), [&](auto& process) {
  324. dbgln_if(TTY_DEBUG, "{}: Send signal {} to {}", tty_name(), signal, process);
  325. // FIXME: Should this error be propagated somehow?
  326. [[maybe_unused]] auto rc = process.send_signal(signal, nullptr);
  327. });
  328. }
  329. void TTY::flush_input()
  330. {
  331. m_available_lines = 0;
  332. m_input_buffer.clear();
  333. evaluate_block_conditions();
  334. }
  335. ErrorOr<void> TTY::set_termios(const termios& t)
  336. {
  337. ErrorOr<void> rc;
  338. m_termios = t;
  339. dbgln_if(TTY_DEBUG, "{} set_termios: ECHO={}, ISIG={}, ICANON={}, ECHOE={}, ECHOK={}, ECHONL={}, ISTRIP={}, ICRNL={}, INLCR={}, IGNCR={}, OPOST={}, ONLCR={}",
  340. tty_name(),
  341. should_echo_input(),
  342. should_generate_signals(),
  343. in_canonical_mode(),
  344. ((m_termios.c_lflag & ECHOE) != 0),
  345. ((m_termios.c_lflag & ECHOK) != 0),
  346. ((m_termios.c_lflag & ECHONL) != 0),
  347. ((m_termios.c_iflag & ISTRIP) != 0),
  348. ((m_termios.c_iflag & ICRNL) != 0),
  349. ((m_termios.c_iflag & INLCR) != 0),
  350. ((m_termios.c_iflag & IGNCR) != 0),
  351. ((m_termios.c_oflag & OPOST) != 0),
  352. ((m_termios.c_oflag & ONLCR) != 0));
  353. struct FlagDescription {
  354. tcflag_t value;
  355. StringView name;
  356. };
  357. constexpr FlagDescription unimplemented_iflags[] = {
  358. { IGNBRK, "IGNBRK" },
  359. { BRKINT, "BRKINT" },
  360. { IGNPAR, "IGNPAR" },
  361. { PARMRK, "PARMRK" },
  362. { INPCK, "INPCK" },
  363. { IGNCR, "IGNCR" },
  364. { IUCLC, "IUCLC" },
  365. { IXON, "IXON" },
  366. { IXANY, "IXANY" },
  367. { IXOFF, "IXOFF" },
  368. { IMAXBEL, "IMAXBEL" },
  369. { IUTF8, "IUTF8" }
  370. };
  371. for (auto flag : unimplemented_iflags) {
  372. if (m_termios.c_iflag & flag.value) {
  373. dbgln("FIXME: iflag {} unimplemented", flag.name);
  374. rc = ENOTIMPL;
  375. }
  376. }
  377. constexpr FlagDescription unimplemented_oflags[] = {
  378. { OLCUC, "OLCUC" },
  379. { ONOCR, "ONOCR" },
  380. { ONLRET, "ONLRET" },
  381. { OFILL, "OFILL" },
  382. { OFDEL, "OFDEL" }
  383. };
  384. for (auto flag : unimplemented_oflags) {
  385. if (m_termios.c_oflag & flag.value) {
  386. dbgln("FIXME: oflag {} unimplemented", flag.name);
  387. rc = ENOTIMPL;
  388. }
  389. }
  390. if ((m_termios.c_cflag & CSIZE) != CS8) {
  391. dbgln("FIXME: Character sizes other than 8 bits are not supported");
  392. rc = ENOTIMPL;
  393. }
  394. constexpr FlagDescription unimplemented_cflags[] = {
  395. { CSTOPB, "CSTOPB" },
  396. { CREAD, "CREAD" },
  397. { PARENB, "PARENB" },
  398. { PARODD, "PARODD" },
  399. { HUPCL, "HUPCL" },
  400. { CLOCAL, "CLOCAL" }
  401. };
  402. for (auto flag : unimplemented_cflags) {
  403. if (m_termios.c_cflag & flag.value) {
  404. dbgln("FIXME: cflag {} unimplemented", flag.name);
  405. rc = ENOTIMPL;
  406. }
  407. }
  408. constexpr FlagDescription unimplemented_lflags[] = {
  409. { TOSTOP, "TOSTOP" },
  410. { IEXTEN, "IEXTEN" }
  411. };
  412. for (auto flag : unimplemented_lflags) {
  413. if (m_termios.c_lflag & flag.value) {
  414. dbgln("FIXME: lflag {} unimplemented", flag.name);
  415. rc = ENOTIMPL;
  416. }
  417. }
  418. return rc;
  419. }
  420. ErrorOr<void> TTY::ioctl(OpenFileDescription&, unsigned request, Userspace<void*> arg)
  421. {
  422. auto& current_process = Process::current();
  423. TRY(current_process.require_promise(Pledge::tty));
  424. #if 0
  425. // FIXME: When should we block things?
  426. // How do we make this work together with MasterPTY forwarding to us?
  427. if (current_process.tty() && current_process.tty() != this) {
  428. return ENOTTY;
  429. }
  430. #endif
  431. switch (request) {
  432. case TIOCGPGRP: {
  433. auto user_pgid = static_ptr_cast<pid_t*>(arg);
  434. auto pgid = this->pgid().value();
  435. return copy_to_user(user_pgid, &pgid);
  436. }
  437. case TIOCSPGRP: {
  438. ProcessGroupID pgid = static_cast<pid_t>(arg.ptr());
  439. if (pgid <= 0)
  440. return EINVAL;
  441. InterruptDisabler disabler;
  442. auto process_group = ProcessGroup::from_pgid(pgid);
  443. // Disallow setting a nonexistent PGID.
  444. if (!process_group)
  445. return EINVAL;
  446. auto process = Process::from_pid(ProcessID(pgid.value()));
  447. SessionID new_sid = process ? process->sid() : Process::get_sid_from_pgid(pgid);
  448. if (!new_sid || new_sid != current_process.sid())
  449. return EPERM;
  450. if (process && pgid != process->pgid())
  451. return EPERM;
  452. m_pg = process_group;
  453. if (process) {
  454. if (auto parent = Process::from_pid(process->ppid())) {
  455. m_original_process_parent = *parent;
  456. return {};
  457. }
  458. }
  459. m_original_process_parent = nullptr;
  460. return {};
  461. }
  462. case TCGETS: {
  463. auto user_termios = static_ptr_cast<termios*>(arg);
  464. return copy_to_user(user_termios, &m_termios);
  465. }
  466. case TCSETS:
  467. case TCSETSF:
  468. case TCSETSW: {
  469. auto user_termios = static_ptr_cast<termios const*>(arg);
  470. auto termios = TRY(copy_typed_from_user(user_termios));
  471. auto rc = set_termios(termios);
  472. if (request == TCSETSF)
  473. flush_input();
  474. return rc;
  475. }
  476. case TCFLSH: {
  477. // Serenity's TTY implementation does not use an output buffer, so ignore TCOFLUSH.
  478. auto operation = static_cast<u8>(arg.ptr());
  479. if (operation == TCIFLUSH || operation == TCIOFLUSH) {
  480. flush_input();
  481. } else if (operation != TCOFLUSH) {
  482. return EINVAL;
  483. }
  484. return {};
  485. }
  486. case TIOCGWINSZ: {
  487. auto user_winsize = static_ptr_cast<winsize*>(arg);
  488. winsize ws {};
  489. ws.ws_row = m_rows;
  490. ws.ws_col = m_columns;
  491. ws.ws_xpixel = 0;
  492. ws.ws_ypixel = 0;
  493. return copy_to_user(user_winsize, &ws);
  494. }
  495. case TIOCSWINSZ: {
  496. auto user_winsize = static_ptr_cast<winsize const*>(arg);
  497. auto ws = TRY(copy_typed_from_user(user_winsize));
  498. if (ws.ws_col == m_columns && ws.ws_row == m_rows)
  499. return {};
  500. m_rows = ws.ws_row;
  501. m_columns = ws.ws_col;
  502. generate_signal(SIGWINCH);
  503. return {};
  504. }
  505. case TIOCSCTTY:
  506. current_process.set_tty(this);
  507. return {};
  508. case TIOCSTI:
  509. return EIO;
  510. case TIOCNOTTY:
  511. current_process.set_tty(nullptr);
  512. return {};
  513. }
  514. return EINVAL;
  515. }
  516. ErrorOr<NonnullOwnPtr<KString>> TTY::pseudo_path(const OpenFileDescription&) const
  517. {
  518. return tty_name().try_clone();
  519. }
  520. void TTY::set_size(unsigned short columns, unsigned short rows)
  521. {
  522. m_rows = rows;
  523. m_columns = columns;
  524. }
  525. void TTY::hang_up()
  526. {
  527. generate_signal(SIGHUP);
  528. }
  529. }