2 use std
::collections
::HashMap
;
3 use std
::ffi
::{OsStr, OsString}
;
4 use std
::io
::{ErrorKind, Write}
;
5 use std
::os
::unix
::io
::{AsRawFd, FromRawFd}
;
6 use std
::os
::unix
::process
::CommandExt
;
7 use std
::process
::Command
;
8 use std
::time
::{Duration, Instant}
;
10 use anyhow
::{bail, format_err, Result}
;
11 use clap
::{App, AppSettings, Arg}
;
12 use mio
::net
::{TcpListener, TcpStream}
;
13 use mio
::unix
::SourceFd
;
14 use mio
::{Events, Interest, Poll, Token}
;
16 use proxmox_io
::ByteBuffer
;
17 use proxmox_lang
::error
::io_err_other
;
18 use proxmox_sys
::linux
::pty
::{make_controlling_terminal, PTY}
;
20 const MSG_TYPE_DATA
: u8 = 0;
21 const MSG_TYPE_RESIZE
: u8 = 1;
22 //const MSG_TYPE_PING: u8 = 2;
24 fn remove_number(buf
: &mut ByteBuffer
) -> Option
<usize> {
26 if let Some(pos
) = &buf
.iter().position(|&x
| x
== b'
:'
) {
27 let data
= buf
.remove_data(*pos
);
28 buf
.consume(1); // the ':'
29 let len
= match std
::str::from_utf8(&data
) {
30 Ok(lenstring
) => match lenstring
.parse() {
33 eprintln
!("error parsing number: '{}'", err
);
38 eprintln
!("error parsing number: '{}'", err
);
43 } else if buf
.len() > 20 {
52 fn process_queue(buf
: &mut ByteBuffer
, pty
: &mut PTY
) -> Option
<usize> {
62 let msgtype
= buf
[0] - b'
0'
;
64 if msgtype
== MSG_TYPE_DATA
{
66 if let Some(len
) = remove_number(buf
) {
69 } else if msgtype
== MSG_TYPE_RESIZE
{
71 if let Some(cols
) = remove_number(buf
) {
72 if let Some(rows
) = remove_number(buf
) {
73 pty
.set_size(cols
as u16, rows
as u16).ok()?
;
76 // ignore incomplete messages
79 // ignore invalid or ping (msgtype 2)
86 type TicketResult
= Result
<(Box
<[u8]>, Box
<[u8]>)>;
88 /// Reads from the stream and returns the first line and the rest
90 stream
: &mut TcpStream
,
94 let mut poll
= Poll
::new()?
;
96 .register(stream
, Token(0), Interest
::READABLE
)?
;
97 let mut events
= Events
::with_capacity(1);
99 let now
= Instant
::now();
100 let mut elapsed
= Duration
::new(0, 0);
103 poll
.poll(&mut events
, Some(timeout
- elapsed
))?
;
104 if !events
.is_empty() {
105 match buf
.read_from(stream
) {
108 bail
!("connection closed before authentication");
111 Err(err
) if err
.kind() == ErrorKind
::WouldBlock
=> {}
112 Err(err
) => return Err(err
.into()),
115 if buf
[..].contains(&b'
\n'
) {
120 bail
!("authentication data is incomplete: {:?}", &buf
[..]);
124 elapsed
= now
.elapsed();
125 if elapsed
> timeout
{
130 let newline_idx
= &buf
[..].iter().position(|&x
| x
== b'
\n'
).unwrap();
132 let line
= buf
.remove_data(*newline_idx
);
133 buf
.consume(1); // discard newline
135 match line
.iter().position(|&b
| b
== b'
:'
) {
137 let (username
, ticket
) = line
.split_at(pos
);
138 Ok((username
.into(), ticket
[1..].into()))
140 None
=> bail
!("authentication data is invalid"),
152 let mut post_fields
: Vec
<(&str, &str)> = Vec
::with_capacity(5);
153 post_fields
.push(("username", std
::str::from_utf8(username
)?
));
154 post_fields
.push(("password", std
::str::from_utf8(ticket
)?
));
155 post_fields
.push(("path", path
));
156 if let Some(perm
) = perm
{
157 post_fields
.push(("privs", perm
));
160 if let Some(port
) = port
{
161 port_str
= port
.to_string();
162 post_fields
.push(("port", &port_str
));
165 let url
= format
!("http://localhost:{}/api2/json/access/ticket", authport
);
167 match ureq
::post(&url
).send_form(&post_fields
[..]) {
168 Ok(res
) if res
.status() == 200 => Ok(()),
169 Ok(res
) | Err(ureq
::Error
::Status(_
, res
)) => {
170 let code
= res
.status();
171 bail
!("invalid authentication - {} {}", code
, res
.status_text())
173 Err(err
) => bail
!("authentication request failed - {}", err
),
177 fn listen_and_accept(
182 ) -> Result
<(TcpStream
, u16)> {
183 let listener
= if port_as_fd
{
184 unsafe { std::net::TcpListener::from_raw_fd(port as i32) }
186 std
::net
::TcpListener
::bind((hostname
, port
as u16))?
188 let port
= listener
.local_addr()?
.port();
189 let mut listener
= TcpListener
::from_std(listener
);
190 let mut poll
= Poll
::new()?
;
193 .register(&mut listener
, Token(0), Interest
::READABLE
)?
;
195 let mut events
= Events
::with_capacity(1);
197 let now
= Instant
::now();
198 let mut elapsed
= Duration
::new(0, 0);
201 poll
.poll(&mut events
, Some(timeout
- elapsed
))?
;
202 if !events
.is_empty() {
203 let (stream
, client
) = listener
.accept()?
;
204 println
!("client connection: {:?}", client
);
205 return Ok((stream
, port
));
208 elapsed
= now
.elapsed();
209 if elapsed
> timeout
{
215 fn run_pty(cmd
: &OsStr
, params
: clap
::OsValues
) -> Result
<PTY
> {
216 let (mut pty
, secondary_name
) = PTY
::new().map_err(io_err_other
)?
;
218 let mut filtered_env
: HashMap
<OsString
, OsString
> = std
::env
::vars_os()
219 .filter(|&(ref k
, _
)| {
225 || k
.to_string_lossy().starts_with("LC_")
228 filtered_env
.insert("TERM".into(), "xterm-256color".into());
230 let mut command
= Command
::new(cmd
);
232 command
.args(params
).env_clear().envs(&filtered_env
);
235 command
.pre_exec(move || {
236 make_controlling_terminal(&secondary_name
).map_err(io_err_other
)?
;
243 pty
.set_size(80, 20)?
;
247 const TCP
: Token
= Token(0);
248 const PTY
: Token
= Token(1);
250 fn do_main() -> Result
<()> {
251 let matches
= App
::new("termproxy")
252 .setting(AppSettings
::TrailingVarArg
)
253 .arg(Arg
::with_name("port").takes_value(true).required(true))
255 Arg
::with_name("authport")
259 .arg(Arg
::with_name("use-port-as-fd").long("port-as-fd"))
261 Arg
::with_name("path")
266 .arg(Arg
::with_name("perm").takes_value(true).long("perm"))
268 Arg
::with_name("cmd")
269 .allow_invalid_utf8(true)
275 let port
: u64 = matches
279 .map_err(io_err_other
)?
;
280 let path
= matches
.value_of("path").unwrap();
281 let perm
: Option
<&str> = matches
.value_of("perm");
282 let mut cmdparams
= matches
.values_of_os("cmd").unwrap();
283 let cmd
= cmdparams
.next().unwrap();
284 let authport
: u16 = matches
285 .value_of("authport")
288 .map_err(io_err_other
)?
;
289 let mut pty_buf
= ByteBuffer
::new();
290 let mut tcp_buf
= ByteBuffer
::new();
292 let use_port_as_fd
= matches
.is_present("use-port-as-fd");
294 if use_port_as_fd
&& port
> u16::MAX
as u64 {
295 return Err(format_err
!("port too big"));
296 } else if port
> i32::MAX
as u64 {
297 return Err(format_err
!("Invalid FD number"));
300 let (mut tcp_handle
, port
) =
301 listen_and_accept("localhost", port
, use_port_as_fd
, Duration
::new(10, 0))
302 .map_err(|err
| format_err
!("failed waiting for client: {}", err
))?
;
304 let (username
, ticket
) = read_ticket_line(&mut tcp_handle
, &mut pty_buf
, Duration
::new(10, 0))
305 .map_err(|err
| format_err
!("failed reading ticket: {}", err
))?
;
306 let port
= if use_port_as_fd { Some(port) }
else { None }
;
307 authenticate(&username
, &ticket
, path
, perm
, authport
, port
)?
;
308 tcp_handle
.write_all(b
"OK").expect("error writing response");
310 let mut poll
= Poll
::new()?
;
311 let mut events
= Events
::with_capacity(128);
313 let mut pty
= run_pty(cmd
, cmdparams
)?
;
315 poll
.registry().register(
318 Interest
::READABLE
| Interest
::WRITABLE
,
320 poll
.registry().register(
321 &mut SourceFd(&pty
.as_raw_fd()),
323 Interest
::READABLE
| Interest
::WRITABLE
,
326 let mut tcp_writable
= true;
327 let mut pty_writable
= true;
328 let mut tcp_readable
= true;
329 let mut pty_readable
= true;
330 let mut remaining
= 0;
331 let mut finished
= false;
334 if tcp_readable
&& !pty_buf
.is_full() || pty_readable
&& !tcp_buf
.is_full() {
335 poll
.poll(&mut events
, Some(Duration
::new(0, 0)))?
;
337 poll
.poll(&mut events
, None
)?
;
340 for event
in &events
{
341 let writable
= event
.is_writable();
342 let readable
= event
.is_readable();
343 if event
.is_read_closed() {
346 match event
.token() {
367 while tcp_readable
&& !pty_buf
.is_full() {
368 let bytes
= match pty_buf
.read_from(&mut tcp_handle
) {
370 Err(err
) if err
.kind() == ErrorKind
::WouldBlock
=> {
371 tcp_readable
= false;
376 return Err(format_err
!("error reading from tcp: {}", err
));
387 while pty_readable
&& !tcp_buf
.is_full() {
388 let bytes
= match tcp_buf
.read_from(&mut pty
) {
390 Err(err
) if err
.kind() == ErrorKind
::WouldBlock
=> {
391 pty_readable
= false;
396 return Err(format_err
!("error reading from pty: {}", err
));
407 while !tcp_buf
.is_empty() && tcp_writable
{
408 let bytes
= match tcp_handle
.write(&tcp_buf
[..]) {
410 Err(err
) if err
.kind() == ErrorKind
::WouldBlock
=> {
411 tcp_writable
= false;
416 return Err(format_err
!("error writing to tcp : {}", err
));
421 tcp_buf
.consume(bytes
);
424 while !pty_buf
.is_empty() && pty_writable
{
426 remaining
= match process_queue(&mut pty_buf
, &mut pty
) {
431 let len
= min(remaining
, pty_buf
.len());
432 let bytes
= match pty
.write(&pty_buf
[..len
]) {
434 Err(err
) if err
.kind() == ErrorKind
::WouldBlock
=> {
435 pty_writable
= false;
440 return Err(format_err
!("error writing to pty : {}", err
));
446 pty_buf
.consume(bytes
);
454 std
::process
::exit(match do_main() {
457 eprintln
!("{}", err
);