TTY.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/ScopeGuard.h>
  27. #include <Kernel/Debug.h>
  28. #include <Kernel/Process.h>
  29. #include <Kernel/TTY/TTY.h>
  30. #include <LibC/errno_numbers.h>
  31. #include <LibC/signal_numbers.h>
  32. #include <LibC/sys/ioctl_numbers.h>
  33. namespace Kernel {
  34. TTY::TTY(unsigned major, unsigned minor)
  35. : CharacterDevice(major, minor)
  36. {
  37. set_default_termios();
  38. }
  39. TTY::~TTY()
  40. {
  41. }
  42. void TTY::set_default_termios()
  43. {
  44. memset(&m_termios, 0, sizeof(m_termios));
  45. m_termios.c_lflag |= ISIG | ECHO | ICANON;
  46. static const char default_cc[32] = "\003\034\010\025\004\0\1\0\021\023\032\0\022\017\027\026\0\024";
  47. memcpy(m_termios.c_cc, default_cc, sizeof(default_cc));
  48. }
  49. KResultOr<size_t> TTY::read(FileDescription&, size_t, UserOrKernelBuffer& buffer, size_t size)
  50. {
  51. if (Process::current()->pgid() != pgid()) {
  52. // FIXME: Should we propagate this error path somehow?
  53. [[maybe_unused]] auto rc = Process::current()->send_signal(SIGTTIN, nullptr);
  54. return EINTR;
  55. }
  56. if (m_input_buffer.size() < static_cast<size_t>(size))
  57. size = m_input_buffer.size();
  58. ssize_t nwritten;
  59. bool need_evaluate_block_conditions = false;
  60. if (in_canonical_mode()) {
  61. nwritten = buffer.write_buffered<512>(size, [&](u8* data, size_t data_size) {
  62. size_t i = 0;
  63. for (; i < data_size; i++) {
  64. u8 ch = m_input_buffer.dequeue();
  65. if (ch == '\0') {
  66. //Here we handle a ^D line, so we don't add the
  67. //character to the output.
  68. m_available_lines--;
  69. need_evaluate_block_conditions = true;
  70. break;
  71. } else if (ch == '\n' || is_eol(ch)) {
  72. data[i] = ch;
  73. i++;
  74. m_available_lines--;
  75. break;
  76. }
  77. data[i] = ch;
  78. }
  79. return (ssize_t)i;
  80. });
  81. } else {
  82. nwritten = buffer.write_buffered<512>(size, [&](u8* data, size_t data_size) {
  83. for (size_t i = 0; i < data_size; i++)
  84. data[i] = m_input_buffer.dequeue();
  85. return (ssize_t)data_size;
  86. });
  87. }
  88. if (nwritten < 0)
  89. return KResult((ErrnoCode)-nwritten);
  90. if (nwritten > 0 || need_evaluate_block_conditions)
  91. evaluate_block_conditions();
  92. return (size_t)nwritten;
  93. }
  94. KResultOr<size_t> TTY::write(FileDescription&, size_t, const UserOrKernelBuffer& buffer, size_t size)
  95. {
  96. if (m_termios.c_lflag & TOSTOP && Process::current()->pgid() != pgid()) {
  97. [[maybe_unused]] auto rc = Process::current()->send_signal(SIGTTOU, nullptr);
  98. return EINTR;
  99. }
  100. on_tty_write(buffer, size);
  101. return size;
  102. }
  103. bool TTY::can_read(const FileDescription&, size_t) const
  104. {
  105. if (in_canonical_mode()) {
  106. return m_available_lines > 0;
  107. }
  108. return !m_input_buffer.is_empty();
  109. }
  110. bool TTY::can_write(const FileDescription&, size_t) const
  111. {
  112. return true;
  113. }
  114. bool TTY::is_eol(u8 ch) const
  115. {
  116. return ch == m_termios.c_cc[VEOL];
  117. }
  118. bool TTY::is_eof(u8 ch) const
  119. {
  120. return ch == m_termios.c_cc[VEOF];
  121. }
  122. bool TTY::is_kill(u8 ch) const
  123. {
  124. return ch == m_termios.c_cc[VKILL];
  125. }
  126. bool TTY::is_erase(u8 ch) const
  127. {
  128. return ch == m_termios.c_cc[VERASE];
  129. }
  130. bool TTY::is_werase(u8 ch) const
  131. {
  132. return ch == m_termios.c_cc[VWERASE];
  133. }
  134. void TTY::emit(u8 ch, bool do_evaluate_block_conditions)
  135. {
  136. if (should_generate_signals()) {
  137. if (ch == m_termios.c_cc[VINFO]) {
  138. dbgln("{}: VINFO pressed!", tty_name());
  139. generate_signal(SIGINFO);
  140. return;
  141. }
  142. if (ch == m_termios.c_cc[VINTR]) {
  143. dbgln("{}: VINTR pressed!", tty_name());
  144. generate_signal(SIGINT);
  145. return;
  146. }
  147. if (ch == m_termios.c_cc[VQUIT]) {
  148. dbgln("{}: VQUIT pressed!", tty_name());
  149. generate_signal(SIGQUIT);
  150. return;
  151. }
  152. if (ch == m_termios.c_cc[VSUSP]) {
  153. dbgln("{}: VSUSP pressed!", tty_name());
  154. generate_signal(SIGTSTP);
  155. if (auto original_process_parent = m_original_process_parent.strong_ref()) {
  156. [[maybe_unused]] auto rc = original_process_parent->send_signal(SIGCHLD, nullptr);
  157. }
  158. // TODO: Else send it to the session leader maybe?
  159. return;
  160. }
  161. }
  162. ScopeGuard guard([&]() {
  163. if (do_evaluate_block_conditions)
  164. evaluate_block_conditions();
  165. });
  166. if (in_canonical_mode()) {
  167. if (is_eof(ch)) {
  168. m_available_lines++;
  169. //We use '\0' to delimit the end
  170. //of a line.
  171. m_input_buffer.enqueue('\0');
  172. return;
  173. }
  174. if (is_kill(ch)) {
  175. kill_line();
  176. return;
  177. }
  178. if (is_erase(ch)) {
  179. do_backspace();
  180. return;
  181. }
  182. if (is_werase(ch)) {
  183. erase_word();
  184. return;
  185. }
  186. if (ch == '\n' || is_eol(ch)) {
  187. m_available_lines++;
  188. }
  189. }
  190. m_input_buffer.enqueue(ch);
  191. echo(ch);
  192. }
  193. bool TTY::can_do_backspace() const
  194. {
  195. // can't do back space if we're empty. Plus, we don't want to
  196. // remove any lines "committed" by newlines or ^D.
  197. if (!m_input_buffer.is_empty() && !is_eol(m_input_buffer.last()) && m_input_buffer.last() != '\0') {
  198. return true;
  199. }
  200. return false;
  201. }
  202. void TTY::do_backspace()
  203. {
  204. if (can_do_backspace()) {
  205. m_input_buffer.dequeue_end();
  206. echo(8);
  207. echo(' ');
  208. echo(8);
  209. evaluate_block_conditions();
  210. }
  211. }
  212. // TODO: Currently, both erase_word() and kill_line work by sending
  213. // a lot of VERASE characters; this is done because Terminal.cpp
  214. // doesn't currently support VWERASE and VKILL. When these are
  215. // implemented we could just send a VKILL or VWERASE.
  216. void TTY::erase_word()
  217. {
  218. //Note: if we have leading whitespace before the word
  219. //we want to delete we have to also delete that.
  220. bool first_char = false;
  221. bool did_dequeue = false;
  222. while (can_do_backspace()) {
  223. u8 ch = m_input_buffer.last();
  224. if (ch == ' ' && first_char)
  225. break;
  226. if (ch != ' ')
  227. first_char = true;
  228. m_input_buffer.dequeue_end();
  229. did_dequeue = true;
  230. erase_character();
  231. }
  232. if (did_dequeue)
  233. evaluate_block_conditions();
  234. }
  235. void TTY::kill_line()
  236. {
  237. bool did_dequeue = false;
  238. while (can_do_backspace()) {
  239. m_input_buffer.dequeue_end();
  240. did_dequeue = true;
  241. erase_character();
  242. }
  243. if (did_dequeue)
  244. evaluate_block_conditions();
  245. }
  246. void TTY::erase_character()
  247. {
  248. echo(m_termios.c_cc[VERASE]);
  249. echo(' ');
  250. echo(m_termios.c_cc[VERASE]);
  251. }
  252. void TTY::generate_signal(int signal)
  253. {
  254. if (!pgid())
  255. return;
  256. if (should_flush_on_signal())
  257. flush_input();
  258. dbgln("{}: Send signal {} to everyone in pgrp {}", tty_name(), signal, pgid().value());
  259. InterruptDisabler disabler; // FIXME: Iterate over a set of process handles instead?
  260. Process::for_each_in_pgrp(pgid(), [&](auto& process) {
  261. dbgln("{}: Send signal {} to {}", tty_name(), signal, process);
  262. // FIXME: Should this error be propagated somehow?
  263. [[maybe_unused]] auto rc = process.send_signal(signal, nullptr);
  264. return IterationDecision::Continue;
  265. });
  266. }
  267. void TTY::flush_input()
  268. {
  269. m_available_lines = 0;
  270. m_input_buffer.clear();
  271. evaluate_block_conditions();
  272. }
  273. void TTY::set_termios(const termios& t)
  274. {
  275. m_termios = t;
  276. dbgln<TTY_DEBUG>("{} set_termios: ECHO={}, ISIG={}, ICANON={}, ECHOE={}, ECHOK={}, ECHONL={}, ISTRIP={}, ICRNL={}, INLCR={}, IGNCR={}",
  277. tty_name(),
  278. should_echo_input(),
  279. should_generate_signals(),
  280. in_canonical_mode(),
  281. ((m_termios.c_lflag & ECHOE) != 0),
  282. ((m_termios.c_lflag & ECHOK) != 0),
  283. ((m_termios.c_lflag & ECHONL) != 0),
  284. ((m_termios.c_iflag & ISTRIP) != 0),
  285. ((m_termios.c_iflag & ICRNL) != 0),
  286. ((m_termios.c_iflag & INLCR) != 0),
  287. ((m_termios.c_iflag & IGNCR) != 0));
  288. }
  289. int TTY::ioctl(FileDescription&, unsigned request, FlatPtr arg)
  290. {
  291. REQUIRE_PROMISE(tty);
  292. auto& current_process = *Process::current();
  293. termios* user_termios;
  294. winsize* user_winsize;
  295. #if 0
  296. // FIXME: When should we block things?
  297. // How do we make this work together with MasterPTY forwarding to us?
  298. if (current_process.tty() && current_process.tty() != this) {
  299. return -ENOTTY;
  300. }
  301. #endif
  302. switch (request) {
  303. case TIOCGPGRP:
  304. return this->pgid().value();
  305. case TIOCSPGRP: {
  306. ProcessGroupID pgid = static_cast<pid_t>(arg);
  307. if (pgid <= 0)
  308. return -EINVAL;
  309. InterruptDisabler disabler;
  310. auto process_group = ProcessGroup::from_pgid(pgid);
  311. // Disallow setting a nonexistent PGID.
  312. if (!process_group)
  313. return -EINVAL;
  314. auto process = Process::from_pid(ProcessID(pgid.value()));
  315. SessionID new_sid = process ? process->sid() : Process::get_sid_from_pgid(pgid);
  316. if (!new_sid || new_sid != current_process.sid())
  317. return -EPERM;
  318. if (process && pgid != process->pgid())
  319. return -EPERM;
  320. m_pg = process_group;
  321. if (process) {
  322. if (auto parent = Process::from_pid(process->ppid())) {
  323. m_original_process_parent = *parent;
  324. return 0;
  325. }
  326. }
  327. m_original_process_parent = nullptr;
  328. return 0;
  329. }
  330. case TCGETS: {
  331. user_termios = reinterpret_cast<termios*>(arg);
  332. if (!copy_to_user(user_termios, &m_termios))
  333. return -EFAULT;
  334. return 0;
  335. }
  336. case TCSETS:
  337. case TCSETSF:
  338. case TCSETSW: {
  339. user_termios = reinterpret_cast<termios*>(arg);
  340. termios termios;
  341. if (!copy_from_user(&termios, user_termios))
  342. return -EFAULT;
  343. set_termios(termios);
  344. if (request == TCSETSF)
  345. flush_input();
  346. return 0;
  347. }
  348. case TCFLSH:
  349. // Serenity's TTY implementation does not use an output buffer, so ignore TCOFLUSH.
  350. if (arg == TCIFLUSH || arg == TCIOFLUSH) {
  351. flush_input();
  352. } else if (arg != TCOFLUSH) {
  353. return -EINVAL;
  354. }
  355. return 0;
  356. case TIOCGWINSZ:
  357. user_winsize = reinterpret_cast<winsize*>(arg);
  358. winsize ws;
  359. ws.ws_row = m_rows;
  360. ws.ws_col = m_columns;
  361. ws.ws_xpixel = 0;
  362. ws.ws_ypixel = 0;
  363. if (!copy_to_user(user_winsize, &ws))
  364. return -EFAULT;
  365. return 0;
  366. case TIOCSWINSZ: {
  367. user_winsize = reinterpret_cast<winsize*>(arg);
  368. winsize ws;
  369. if (!copy_from_user(&ws, user_winsize))
  370. return -EFAULT;
  371. if (ws.ws_col == m_columns && ws.ws_row == m_rows)
  372. return 0;
  373. m_rows = ws.ws_row;
  374. m_columns = ws.ws_col;
  375. generate_signal(SIGWINCH);
  376. return 0;
  377. }
  378. case TIOCSCTTY:
  379. current_process.set_tty(this);
  380. return 0;
  381. case TIOCNOTTY:
  382. current_process.set_tty(nullptr);
  383. return 0;
  384. }
  385. return -EINVAL;
  386. }
  387. void TTY::set_size(unsigned short columns, unsigned short rows)
  388. {
  389. m_rows = rows;
  390. m_columns = columns;
  391. }
  392. void TTY::hang_up()
  393. {
  394. generate_signal(SIGHUP);
  395. }
  396. }