TTY.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  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 <AK/StringView.h>
  8. #include <Kernel/Debug.h>
  9. #include <Kernel/Process.h>
  10. #include <Kernel/TTY/TTY.h>
  11. #include <LibC/errno_numbers.h>
  12. #include <LibC/signal_numbers.h>
  13. #include <LibC/sys/ioctl_numbers.h>
  14. #define TTYDEFCHARS
  15. #include <LibC/sys/ttydefaults.h>
  16. #undef TTYDEFCHARS
  17. namespace Kernel {
  18. TTY::TTY(unsigned major, unsigned minor)
  19. : CharacterDevice(major, minor)
  20. {
  21. set_default_termios();
  22. }
  23. TTY::~TTY()
  24. {
  25. }
  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. KResultOr<size_t> TTY::read(FileDescription&, 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, [&](u8* data, size_t data_size) {
  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. KResultOr<size_t> TTY::write(FileDescription&, 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, [&](u8 const* data, size_t buffer_bytes) {
  82. u8 modified_data[num_chars * 2];
  83. size_t modified_data_size = 0;
  84. for (size_t i = 0; i < buffer_bytes; ++i) {
  85. process_output(data[i], [this, &modified_data, &modified_data_size](u8 out_ch) {
  86. modified_data[modified_data_size++] = out_ch;
  87. });
  88. }
  89. ssize_t bytes_written = on_tty_write(UserOrKernelBuffer::for_kernel_buffer(modified_data), modified_data_size);
  90. VERIFY(bytes_written != 0);
  91. if (bytes_written < 0 || !(m_termios.c_oflag & OPOST) || !(m_termios.c_oflag & ONLCR))
  92. return bytes_written;
  93. if ((size_t)bytes_written == modified_data_size)
  94. return (ssize_t)buffer_bytes;
  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 (ssize_t pos_modified_data = 0; pos_modified_data < bytes_written; ++pos_data) {
  99. if (data[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 (ssize_t)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 FileDescription&, size_t) 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 FileDescription&, size_t) 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. void TTY::do_backspace()
  249. {
  250. if (can_do_backspace()) {
  251. m_input_buffer.dequeue_end();
  252. // We deliberately don't process the output here.
  253. echo(8);
  254. echo(' ');
  255. echo(8);
  256. evaluate_block_conditions();
  257. }
  258. }
  259. // TODO: Currently, both erase_word() and kill_line work by sending
  260. // a lot of VERASE characters; this is done because Terminal.cpp
  261. // doesn't currently support VWERASE and VKILL. When these are
  262. // implemented we could just send a VKILL or VWERASE.
  263. void TTY::erase_word()
  264. {
  265. //Note: if we have leading whitespace before the word
  266. //we want to delete we have to also delete that.
  267. bool first_char = false;
  268. bool did_dequeue = false;
  269. while (can_do_backspace()) {
  270. u8 ch = m_input_buffer.last();
  271. if (ch == ' ' && first_char)
  272. break;
  273. if (ch != ' ')
  274. first_char = true;
  275. m_input_buffer.dequeue_end();
  276. did_dequeue = true;
  277. erase_character();
  278. }
  279. if (did_dequeue)
  280. evaluate_block_conditions();
  281. }
  282. void TTY::kill_line()
  283. {
  284. bool did_dequeue = false;
  285. while (can_do_backspace()) {
  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::erase_character()
  294. {
  295. // We deliberately don't process the output here.
  296. echo(m_termios.c_cc[VERASE]);
  297. echo(' ');
  298. echo(m_termios.c_cc[VERASE]);
  299. }
  300. void TTY::generate_signal(int signal)
  301. {
  302. if (!pgid())
  303. return;
  304. if (should_flush_on_signal())
  305. flush_input();
  306. dbgln_if(TTY_DEBUG, "{}: Send signal {} to everyone in pgrp {}", tty_name(), signal, pgid().value());
  307. InterruptDisabler disabler; // FIXME: Iterate over a set of process handles instead?
  308. Process::for_each_in_pgrp(pgid(), [&](auto& process) {
  309. dbgln_if(TTY_DEBUG, "{}: Send signal {} to {}", tty_name(), signal, process);
  310. // FIXME: Should this error be propagated somehow?
  311. [[maybe_unused]] auto rc = process.send_signal(signal, nullptr);
  312. });
  313. }
  314. void TTY::flush_input()
  315. {
  316. m_available_lines = 0;
  317. m_input_buffer.clear();
  318. evaluate_block_conditions();
  319. }
  320. int TTY::set_termios(const termios& t)
  321. {
  322. int rc = 0;
  323. m_termios = t;
  324. dbgln_if(TTY_DEBUG, "{} set_termios: ECHO={}, ISIG={}, ICANON={}, ECHOE={}, ECHOK={}, ECHONL={}, ISTRIP={}, ICRNL={}, INLCR={}, IGNCR={}, OPOST={}, ONLCR={}",
  325. tty_name(),
  326. should_echo_input(),
  327. should_generate_signals(),
  328. in_canonical_mode(),
  329. ((m_termios.c_lflag & ECHOE) != 0),
  330. ((m_termios.c_lflag & ECHOK) != 0),
  331. ((m_termios.c_lflag & ECHONL) != 0),
  332. ((m_termios.c_iflag & ISTRIP) != 0),
  333. ((m_termios.c_iflag & ICRNL) != 0),
  334. ((m_termios.c_iflag & INLCR) != 0),
  335. ((m_termios.c_iflag & IGNCR) != 0),
  336. ((m_termios.c_oflag & OPOST) != 0),
  337. ((m_termios.c_oflag & ONLCR) != 0));
  338. struct FlagDescription {
  339. tcflag_t value;
  340. StringView name;
  341. };
  342. static constexpr FlagDescription unimplemented_iflags[] = {
  343. { IGNBRK, "IGNBRK" },
  344. { BRKINT, "BRKINT" },
  345. { IGNPAR, "IGNPAR" },
  346. { PARMRK, "PARMRK" },
  347. { INPCK, "INPCK" },
  348. { IGNCR, "IGNCR" },
  349. { IUCLC, "IUCLC" },
  350. { IXON, "IXON" },
  351. { IXANY, "IXANY" },
  352. { IXOFF, "IXOFF" },
  353. { IMAXBEL, "IMAXBEL" },
  354. { IUTF8, "IUTF8" }
  355. };
  356. for (auto flag : unimplemented_iflags) {
  357. if (m_termios.c_iflag & flag.value) {
  358. dbgln("FIXME: iflag {} unimplemented", flag.name);
  359. rc = -ENOTIMPL;
  360. }
  361. }
  362. static constexpr FlagDescription unimplemented_oflags[] = {
  363. { OLCUC, "OLCUC" },
  364. { ONOCR, "ONOCR" },
  365. { ONLRET, "ONLRET" },
  366. { OFILL, "OFILL" },
  367. { OFDEL, "OFDEL" }
  368. };
  369. for (auto flag : unimplemented_oflags) {
  370. if (m_termios.c_oflag & flag.value) {
  371. dbgln("FIXME: oflag {} unimplemented", flag.name);
  372. rc = -ENOTIMPL;
  373. }
  374. }
  375. static constexpr FlagDescription unimplemented_cflags[] = {
  376. { CSIZE, "CSIZE" },
  377. { CS5, "CS5" },
  378. { CS6, "CS6" },
  379. { CS7, "CS7" },
  380. { CS8, "CS8" },
  381. { CSTOPB, "CSTOPB" },
  382. { CREAD, "CREAD" },
  383. { PARENB, "PARENB" },
  384. { PARODD, "PARODD" },
  385. { HUPCL, "HUPCL" },
  386. { CLOCAL, "CLOCAL" }
  387. };
  388. for (auto flag : unimplemented_cflags) {
  389. if (m_termios.c_cflag & flag.value) {
  390. dbgln("FIXME: cflag {} unimplemented", flag.name);
  391. rc = -ENOTIMPL;
  392. }
  393. }
  394. static constexpr FlagDescription unimplemented_lflags[] = {
  395. { TOSTOP, "TOSTOP" },
  396. { IEXTEN, "IEXTEN" }
  397. };
  398. for (auto flag : unimplemented_lflags) {
  399. if (m_termios.c_lflag & flag.value) {
  400. dbgln("FIXME: lflag {} unimplemented", flag.name);
  401. rc = -ENOTIMPL;
  402. }
  403. }
  404. return rc;
  405. }
  406. int TTY::ioctl(FileDescription&, unsigned request, FlatPtr arg)
  407. {
  408. REQUIRE_PROMISE(tty);
  409. auto& current_process = *Process::current();
  410. termios* user_termios;
  411. winsize* user_winsize;
  412. #if 0
  413. // FIXME: When should we block things?
  414. // How do we make this work together with MasterPTY forwarding to us?
  415. if (current_process.tty() && current_process.tty() != this) {
  416. return -ENOTTY;
  417. }
  418. #endif
  419. switch (request) {
  420. case TIOCGPGRP:
  421. return this->pgid().value();
  422. case TIOCSPGRP: {
  423. ProcessGroupID pgid = static_cast<pid_t>(arg);
  424. if (pgid <= 0)
  425. return -EINVAL;
  426. InterruptDisabler disabler;
  427. auto process_group = ProcessGroup::from_pgid(pgid);
  428. // Disallow setting a nonexistent PGID.
  429. if (!process_group)
  430. return -EINVAL;
  431. auto process = Process::from_pid(ProcessID(pgid.value()));
  432. SessionID new_sid = process ? process->sid() : Process::get_sid_from_pgid(pgid);
  433. if (!new_sid || new_sid != current_process.sid())
  434. return -EPERM;
  435. if (process && pgid != process->pgid())
  436. return -EPERM;
  437. m_pg = process_group;
  438. if (process) {
  439. if (auto parent = Process::from_pid(process->ppid())) {
  440. m_original_process_parent = *parent;
  441. return 0;
  442. }
  443. }
  444. m_original_process_parent = nullptr;
  445. return 0;
  446. }
  447. case TCGETS: {
  448. user_termios = reinterpret_cast<termios*>(arg);
  449. if (!copy_to_user(user_termios, &m_termios))
  450. return -EFAULT;
  451. return 0;
  452. }
  453. case TCSETS:
  454. case TCSETSF:
  455. case TCSETSW: {
  456. user_termios = reinterpret_cast<termios*>(arg);
  457. termios termios;
  458. if (!copy_from_user(&termios, user_termios))
  459. return -EFAULT;
  460. int rc = set_termios(termios);
  461. if (request == TCSETSF)
  462. flush_input();
  463. return rc;
  464. }
  465. case TCFLSH:
  466. // Serenity's TTY implementation does not use an output buffer, so ignore TCOFLUSH.
  467. if (arg == TCIFLUSH || arg == TCIOFLUSH) {
  468. flush_input();
  469. } else if (arg != TCOFLUSH) {
  470. return -EINVAL;
  471. }
  472. return 0;
  473. case TIOCGWINSZ:
  474. user_winsize = reinterpret_cast<winsize*>(arg);
  475. winsize ws;
  476. ws.ws_row = m_rows;
  477. ws.ws_col = m_columns;
  478. ws.ws_xpixel = 0;
  479. ws.ws_ypixel = 0;
  480. if (!copy_to_user(user_winsize, &ws))
  481. return -EFAULT;
  482. return 0;
  483. case TIOCSWINSZ: {
  484. user_winsize = reinterpret_cast<winsize*>(arg);
  485. winsize ws;
  486. if (!copy_from_user(&ws, user_winsize))
  487. return -EFAULT;
  488. if (ws.ws_col == m_columns && ws.ws_row == m_rows)
  489. return 0;
  490. m_rows = ws.ws_row;
  491. m_columns = ws.ws_col;
  492. generate_signal(SIGWINCH);
  493. return 0;
  494. }
  495. case TIOCSCTTY:
  496. current_process.set_tty(this);
  497. return 0;
  498. case TIOCSTI:
  499. return -EIO;
  500. case TIOCNOTTY:
  501. current_process.set_tty(nullptr);
  502. return 0;
  503. }
  504. return -EINVAL;
  505. }
  506. void TTY::set_size(unsigned short columns, unsigned short rows)
  507. {
  508. m_rows = rows;
  509. m_columns = columns;
  510. }
  511. void TTY::hang_up()
  512. {
  513. generate_signal(SIGHUP);
  514. }
  515. }