2 use std
::collections
::HashMap
;
3 use std
::ffi
::{OsStr, OsString}
;
4 use std
::io
::{ErrorKind, Result, 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 clap
::{App, AppSettings, Arg}
;
12 use mio
::net
::{TcpListener, TcpStream}
;
13 use mio
::{Events, Poll, Token, Interest}
;
14 use mio
::unix
::SourceFd
;
16 use proxmox
::sys
::error
::io_err_other
;
17 use proxmox
::sys
::linux
::pty
::{make_controlling_terminal, PTY}
;
18 use proxmox
::tools
::byte_buffer
::ByteBuffer
;
19 use proxmox
::{io_bail, io_format_err}
;
21 const MSG_TYPE_DATA
: u8 = 0;
22 const MSG_TYPE_RESIZE
: u8 = 1;
23 //const MSG_TYPE_PING: u8 = 2;
25 fn remove_number(buf
: &mut ByteBuffer
) -> Option
<usize> {
27 if let Some(pos
) = &buf
.iter().position(|&x
| x
== b'
:'
) {
28 let data
= buf
.remove_data(*pos
);
29 buf
.consume(1); // the ':'
30 let len
= match std
::str::from_utf8(&data
) {
31 Ok(lenstring
) => match lenstring
.parse() {
34 eprintln
!("error parsing number: '{}'", err
);
39 eprintln
!("error parsing number: '{}'", err
);
44 } else if buf
.len() > 20 {
53 fn process_queue(buf
: &mut ByteBuffer
, pty
: &mut PTY
) -> Option
<usize> {
63 let msgtype
= buf
[0] - b'
0'
;
65 if msgtype
== MSG_TYPE_DATA
{
67 if let Some(len
) = remove_number(buf
) {
70 } else if msgtype
== MSG_TYPE_RESIZE
{
72 if let Some(cols
) = remove_number(buf
) {
73 if let Some(rows
) = remove_number(buf
) {
74 pty
.set_size(cols
as u16, rows
as u16).ok()?
;
77 // ignore incomplete messages
80 // ignore invalid or ping (msgtype 2)
87 type TicketResult
= Result
<(Box
<[u8]>, Box
<[u8]>)>;
89 /// Reads from the stream and returns the first line and the rest
91 stream
: &mut TcpStream
,
96 let mut poll
= Poll
::new()?
;
97 poll
.registry().register(stream
, Token(0), Interest
::READABLE
)?
;
98 let mut events
= Events
::with_capacity(1);
100 let now
= Instant
::now();
101 let mut elapsed
= Duration
::new(0, 0);
104 poll
.poll(&mut events
, Some(timeout
- elapsed
))?
;
105 if !events
.is_empty() {
106 match buf
.read_from(stream
) {
109 io_bail
!("connection closed before authentication");
112 Err(err
) if err
.kind() == ErrorKind
::WouldBlock
=> {}
113 Err(err
) => return Err(err
),
116 if buf
[..].contains(&b'
\n'
) {
121 io_bail
!("authentication data is incomplete: {:?}", &buf
[..]);
125 elapsed
= now
.elapsed();
126 if elapsed
> timeout
{
127 io_bail
!("timed out");
131 let newline_idx
= &buf
[..].iter().position(|&x
| x
== b'
\n'
).unwrap();
133 let line
= buf
.remove_data(*newline_idx
);
134 buf
.consume(1); // discard newline
136 match line
.iter().position(|&b
| b
== b'
:'
) {
138 let (username
, ticket
) = line
.split_at(pos
);
139 Ok((username
.into(), ticket
[1..].into()))
141 None
=> io_bail
!("authentication data is invalid"),
153 let mut curl
= Easy
::new();
155 "http://localhost:{}/api2/json/access/ticket",
159 let username
= curl
.url_encode(username
);
160 let ticket
= curl
.url_encode(ticket
);
161 let path
= curl
.url_encode(path
.as_bytes());
163 let mut post_fields
= Vec
::with_capacity(5);
164 post_fields
.push(format
!("username={}", username
));
165 post_fields
.push(format
!("password={}", ticket
));
166 post_fields
.push(format
!("path={}", path
));
168 if let Some(perm
) = perm
{
169 let perm
= curl
.url_encode(perm
.as_bytes());
170 post_fields
.push(format
!("privs={}", perm
));
173 if let Some(port
) = port
{
174 post_fields
.push(format
!("port={}", port
));
177 curl
.post_fields_copy(post_fields
.join("&").as_bytes())?
;
181 let response_code
= curl
.response_code()?
;
183 if response_code
!= 200 {
184 io_bail
!("invalid authentication, code {}", response_code
);
190 fn listen_and_accept(
195 ) -> Result
<(TcpStream
, u16)> {
196 let listener
= if port_as_fd
{
197 unsafe { std::net::TcpListener::from_raw_fd(port as i32) }
199 std
::net
::TcpListener
::bind((hostname
, port
as u16))?
201 let port
= listener
.local_addr()?
.port();
202 let mut listener
= TcpListener
::from_std(listener
);
203 let mut poll
= Poll
::new()?
;
205 poll
.registry().register(&mut listener
, Token(0), Interest
::READABLE
)?
;
207 let mut events
= Events
::with_capacity(1);
209 let now
= Instant
::now();
210 let mut elapsed
= Duration
::new(0, 0);
213 poll
.poll(&mut events
, Some(timeout
- elapsed
))?
;
214 if !events
.is_empty() {
215 let (stream
, client
) = listener
.accept()?
;
216 println
!("client connection: {:?}", client
);
217 return Ok((stream
, port
));
220 elapsed
= now
.elapsed();
221 if elapsed
> timeout
{
222 io_bail
!("timed out");
227 fn run_pty(cmd
: &OsStr
, params
: clap
::OsValues
) -> Result
<PTY
> {
228 let (mut pty
, secondary_name
) = PTY
::new().map_err(io_err_other
)?
;
230 let mut filtered_env
: HashMap
<OsString
, OsString
> = std
::env
::vars_os()
231 .filter(|&(ref k
, _
)| {
237 || k
.to_string_lossy().starts_with("LC_")
240 filtered_env
.insert("TERM".into(), "xterm-256color".into());
242 let mut command
= Command
::new(cmd
);
244 command
.args(params
).env_clear().envs(&filtered_env
);
247 command
.pre_exec(move || {
248 make_controlling_terminal(&secondary_name
).map_err(io_err_other
)?
;
255 pty
.set_size(80, 20).map_err(|x
| x
.as_errno().unwrap())?
;
259 const TCP
: Token
= Token(0);
260 const PTY
: Token
= Token(1);
262 fn do_main() -> Result
<()> {
263 let matches
= App
::new("termproxy")
264 .setting(AppSettings
::TrailingVarArg
)
265 .arg(Arg
::with_name("port").takes_value(true).required(true))
267 Arg
::with_name("authport")
271 .arg(Arg
::with_name("use-port-as-fd").long("port-as-fd"))
273 Arg
::with_name("path")
278 .arg(Arg
::with_name("perm").takes_value(true).long("perm"))
279 .arg(Arg
::with_name("cmd").multiple(true).required(true))
282 let port
: u64 = matches
286 .map_err(io_err_other
)?
;
287 let path
= matches
.value_of("path").unwrap();
288 let perm
: Option
<&str> = matches
.value_of("perm");
289 let mut cmdparams
= matches
.values_of_os("cmd").unwrap();
290 let cmd
= cmdparams
.next().unwrap();
291 let authport
: u16 = matches
292 .value_of("authport")
295 .map_err(io_err_other
)?
;
296 let mut pty_buf
= ByteBuffer
::new();
297 let mut tcp_buf
= ByteBuffer
::new();
299 let use_port_as_fd
= matches
.is_present("use-port-as-fd");
301 if use_port_as_fd
&& port
> u16::MAX
as u64 {
302 return Err(io_format_err
!("port too big"));
303 } else if port
> i32::MAX
as u64 {
304 return Err(io_format_err
!("Invalid FD number"));
307 let (mut tcp_handle
, port
) =
308 listen_and_accept("localhost", port
, use_port_as_fd
, Duration
::new(10, 0))
309 .map_err(|err
| io_format_err
!("failed waiting for client: {}", err
))?
;
311 let (username
, ticket
) = read_ticket_line(&mut tcp_handle
, &mut pty_buf
, Duration
::new(10, 0))
312 .map_err(|err
| io_format_err
!("failed reading ticket: {}", err
))?
;
313 let port
= if use_port_as_fd { Some(port) }
else { None }
;
314 authenticate(&username
, &ticket
, path
, perm
, authport
, port
)?
;
315 tcp_handle
.write_all(b
"OK").expect("error writing response");
317 let mut poll
= Poll
::new()?
;
318 let mut events
= Events
::with_capacity(128);
320 let mut pty
= run_pty(cmd
, cmdparams
)?
;
322 poll
.registry().register(
325 Interest
::READABLE
.add(Interest
::WRITABLE
)
327 poll
.registry().register(
328 &mut SourceFd(&pty
.as_raw_fd()),
330 Interest
::READABLE
.add(Interest
::WRITABLE
)
333 let mut tcp_writable
= true;
334 let mut pty_writable
= true;
335 let mut tcp_readable
= true;
336 let mut pty_readable
= true;
337 let mut remaining
= 0;
338 let mut finished
= false;
341 if tcp_readable
&& !pty_buf
.is_full() || pty_readable
&& !tcp_buf
.is_full() {
342 poll
.poll(&mut events
, Some(Duration
::new(0, 0)))?
;
344 poll
.poll(&mut events
, None
)?
;
347 for event
in &events
{
348 let writable
= event
.is_writable();
349 let readable
= event
.is_readable();
350 if event
.is_read_closed() {
353 match event
.token() {
374 while tcp_readable
&& !pty_buf
.is_full() {
375 let bytes
= match pty_buf
.read_from(&mut tcp_handle
) {
377 Err(err
) if err
.kind() == ErrorKind
::WouldBlock
=> {
378 tcp_readable
= false;
383 return Err(io_format_err
!("error reading from tcp: {}", err
));
394 while pty_readable
&& !tcp_buf
.is_full() {
395 let bytes
= match tcp_buf
.read_from(&mut pty
) {
397 Err(err
) if err
.kind() == ErrorKind
::WouldBlock
=> {
398 pty_readable
= false;
403 return Err(io_format_err
!("error reading from pty: {}", err
));
414 while !tcp_buf
.is_empty() && tcp_writable
{
415 let bytes
= match tcp_handle
.write(&tcp_buf
[..]) {
417 Err(err
) if err
.kind() == ErrorKind
::WouldBlock
=> {
418 tcp_writable
= false;
423 return Err(io_format_err
!("error writing to tcp : {}", err
));
428 tcp_buf
.consume(bytes
);
431 while !pty_buf
.is_empty() && pty_writable
{
433 remaining
= match process_queue(&mut pty_buf
, &mut pty
) {
438 let len
= min(remaining
, pty_buf
.len());
439 let bytes
= match pty
.write(&pty_buf
[..len
]) {
441 Err(err
) if err
.kind() == ErrorKind
::WouldBlock
=> {
442 pty_writable
= false;
447 return Err(io_format_err
!("error writing to pty : {}", err
));
453 pty_buf
.consume(bytes
);
461 std
::process
::exit(match do_main() {
464 eprintln
!("{}", err
);