TTY.cpp 17 KB

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