summaryrefslogtreecommitdiff
path: root/runtime/ops/tty.rs
blob: 465fb1679aee601d0c2d58254aa3d39f361bb145 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.

use super::io::StdFileResource;
use deno_core::error::bad_resource_id;
use deno_core::error::not_supported;
use deno_core::error::resource_unavailable;
use deno_core::error::AnyError;
use deno_core::op;
use deno_core::Extension;
use deno_core::OpState;
use deno_core::RcRef;
use deno_core::ResourceId;
use serde::Deserialize;
use serde::Serialize;
use std::io::Error;

#[cfg(unix)]
use nix::sys::termios;

#[cfg(windows)]
use deno_core::error::custom_error;
#[cfg(windows)]
use winapi::shared::minwindef::DWORD;
#[cfg(windows)]
use winapi::um::wincon;
#[cfg(windows)]
const RAW_MODE_MASK: DWORD = wincon::ENABLE_LINE_INPUT
  | wincon::ENABLE_ECHO_INPUT
  | wincon::ENABLE_PROCESSED_INPUT;

#[cfg(windows)]
fn get_windows_handle(
  f: &std::fs::File,
) -> Result<std::os::windows::io::RawHandle, AnyError> {
  use std::os::windows::io::AsRawHandle;
  use winapi::um::handleapi;

  let handle = f.as_raw_handle();
  if handle == handleapi::INVALID_HANDLE_VALUE {
    return Err(Error::last_os_error().into());
  } else if handle.is_null() {
    return Err(custom_error("ReferenceError", "null handle"));
  }
  Ok(handle)
}

pub fn init() -> Extension {
  Extension::builder()
    .ops(vec![
      op_set_raw::decl(),
      op_isatty::decl(),
      op_console_size::decl(),
    ])
    .build()
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SetRawOptions {
  cbreak: bool,
}

#[derive(Deserialize)]
pub struct SetRawArgs {
  rid: ResourceId,
  mode: bool,
  options: SetRawOptions,
}

#[op]
fn op_set_raw(state: &mut OpState, args: SetRawArgs) -> Result<(), AnyError> {
  super::check_unstable(state, "Deno.setRaw");

  let rid = args.rid;
  let is_raw = args.mode;
  let cbreak = args.options.cbreak;

  // From https://github.com/kkawakam/rustyline/blob/master/src/tty/windows.rs
  // and https://github.com/kkawakam/rustyline/blob/master/src/tty/unix.rs
  // and https://github.com/crossterm-rs/crossterm/blob/e35d4d2c1cc4c919e36d242e014af75f6127ab50/src/terminal/sys/windows.rs
  // Copyright (c) 2015 Katsu Kawakami & Rustyline authors. MIT license.
  // Copyright (c) 2019 Timon. MIT license.
  #[cfg(windows)]
  {
    use std::os::windows::io::AsRawHandle;
    use winapi::shared::minwindef::FALSE;
    use winapi::um::{consoleapi, handleapi};

    let resource = state.resource_table.get::<StdFileResource>(rid)?;

    if cbreak {
      return Err(not_supported());
    }

    if resource.fs_file.is_none() {
      return Err(bad_resource_id());
    }

    let fs_file_resource =
      RcRef::map(&resource, |r| r.fs_file.as_ref().unwrap()).try_borrow_mut();

    let handle_result = if let Some(mut fs_file) = fs_file_resource {
      let tokio_file = fs_file.0.take().unwrap();
      match tokio_file.try_into_std() {
        Ok(std_file) => {
          let raw_handle = std_file.as_raw_handle();
          // Turn the std_file handle back into a tokio file, put it back
          // in the resource table.
          let tokio_file = tokio::fs::File::from_std(std_file);
          fs_file.0 = Some(tokio_file);
          // return the result.
          Ok(raw_handle)
        }
        Err(tokio_file) => {
          // This function will return an error containing the file if
          // some operation is in-flight.
          fs_file.0 = Some(tokio_file);
          Err(resource_unavailable())
        }
      }
    } else {
      Err(resource_unavailable())
    };

    let handle = handle_result?;

    if handle == handleapi::INVALID_HANDLE_VALUE {
      return Err(Error::last_os_error().into());
    } else if handle.is_null() {
      return Err(custom_error("ReferenceError", "null handle"));
    }
    let mut original_mode: DWORD = 0;
    if unsafe { consoleapi::GetConsoleMode(handle, &mut original_mode) }
      == FALSE
    {
      return Err(Error::last_os_error().into());
    }
    let new_mode = if is_raw {
      original_mode & !RAW_MODE_MASK
    } else {
      original_mode | RAW_MODE_MASK
    };
    if unsafe { consoleapi::SetConsoleMode(handle, new_mode) } == FALSE {
      return Err(Error::last_os_error().into());
    }

    Ok(())
  }
  #[cfg(unix)]
  {
    use std::os::unix::io::AsRawFd;

    let resource = state.resource_table.get::<StdFileResource>(rid)?;

    if resource.fs_file.is_none() {
      return Err(not_supported());
    }

    let maybe_fs_file_resource =
      RcRef::map(&resource, |r| r.fs_file.as_ref().unwrap()).try_borrow_mut();

    if maybe_fs_file_resource.is_none() {
      return Err(resource_unavailable());
    }

    let mut fs_file_resource = maybe_fs_file_resource.unwrap();
    if fs_file_resource.0.is_none() {
      return Err(resource_unavailable());
    }

    let raw_fd = fs_file_resource.0.as_ref().unwrap().as_raw_fd();
    let maybe_tty_mode = &mut fs_file_resource.1.as_mut().unwrap().tty.mode;

    if is_raw {
      if maybe_tty_mode.is_none() {
        // Save original mode.
        let original_mode = termios::tcgetattr(raw_fd)?;
        maybe_tty_mode.replace(original_mode);
      }

      let mut raw = maybe_tty_mode.clone().unwrap();

      raw.input_flags &= !(termios::InputFlags::BRKINT
        | termios::InputFlags::ICRNL
        | termios::InputFlags::INPCK
        | termios::InputFlags::ISTRIP
        | termios::InputFlags::IXON);

      raw.control_flags |= termios::ControlFlags::CS8;

      raw.local_flags &= !(termios::LocalFlags::ECHO
        | termios::LocalFlags::ICANON
        | termios::LocalFlags::IEXTEN);
      if !cbreak {
        raw.local_flags &= !(termios::LocalFlags::ISIG);
      }
      raw.control_chars[termios::SpecialCharacterIndices::VMIN as usize] = 1;
      raw.control_chars[termios::SpecialCharacterIndices::VTIME as usize] = 0;
      termios::tcsetattr(raw_fd, termios::SetArg::TCSADRAIN, &raw)?;
    } else {
      // Try restore saved mode.
      if let Some(mode) = maybe_tty_mode.take() {
        termios::tcsetattr(raw_fd, termios::SetArg::TCSADRAIN, &mode)?;
      }
    }

    Ok(())
  }
}

#[op]
fn op_isatty(state: &mut OpState, rid: ResourceId) -> Result<bool, AnyError> {
  let isatty: bool = StdFileResource::with(state, rid, move |r| match r {
    Ok(std_file) => {
      #[cfg(windows)]
      {
        use winapi::um::consoleapi;

        let handle = get_windows_handle(std_file)?;
        let mut test_mode: DWORD = 0;
        // If I cannot get mode out of console, it is not a console.
        Ok(unsafe { consoleapi::GetConsoleMode(handle, &mut test_mode) != 0 })
      }
      #[cfg(unix)]
      {
        use std::os::unix::io::AsRawFd;
        let raw_fd = std_file.as_raw_fd();
        Ok(unsafe { libc::isatty(raw_fd as libc::c_int) == 1 })
      }
    }
    _ => Ok(false),
  })?;
  Ok(isatty)
}

#[derive(Serialize)]
struct ConsoleSize {
  columns: u32,
  rows: u32,
}

#[op]
fn op_console_size(
  state: &mut OpState,
  rid: ResourceId,
) -> Result<ConsoleSize, AnyError> {
  super::check_unstable(state, "Deno.consoleSize");

  let size = StdFileResource::with(state, rid, move |r| match r {
    Ok(std_file) => {
      #[cfg(windows)]
      {
        use std::os::windows::io::AsRawHandle;
        let handle = std_file.as_raw_handle();

        unsafe {
          let mut bufinfo: winapi::um::wincon::CONSOLE_SCREEN_BUFFER_INFO =
            std::mem::zeroed();

          if winapi::um::wincon::GetConsoleScreenBufferInfo(
            handle,
            &mut bufinfo,
          ) == 0
          {
            return Err(Error::last_os_error().into());
          }

          Ok(ConsoleSize {
            columns: bufinfo.dwSize.X as u32,
            rows: bufinfo.dwSize.Y as u32,
          })
        }
      }

      #[cfg(unix)]
      {
        use std::os::unix::io::AsRawFd;

        let fd = std_file.as_raw_fd();
        unsafe {
          let mut size: libc::winsize = std::mem::zeroed();
          if libc::ioctl(fd, libc::TIOCGWINSZ, &mut size as *mut _) != 0 {
            return Err(Error::last_os_error().into());
          }

          // TODO (caspervonb) return a tuple instead
          Ok(ConsoleSize {
            columns: size.ws_col as u32,
            rows: size.ws_row as u32,
          })
        }
      }
    }
    Err(_) => Err(bad_resource_id()),
  })?;

  Ok(size)
}