| 1 |
// Copyright 2018 Yuya Nishihara <[email protected]> |
| 2 |
// |
| 3 |
// This software may be used and distributed according to the terms of the |
| 4 |
// GNU General Public License version 2 or any later version. |
| 5 |
|
| 6 |
//! Functions to send client-side fds over the command server channel. |
| 7 |
|
| 8 |
use std::io; |
| 9 |
use std::os::unix::io::AsRawFd; |
| 10 |
|
| 11 |
use tokio_hglib::codec::ChannelMessage; |
| 12 |
use tokio_hglib::Connection; |
| 13 |
use tokio_hglib::Protocol; |
| 14 |
|
| 15 |
use crate::message; |
| 16 |
use crate::procutil; |
| 17 |
|
| 18 |
/// Sends client-side fds over the command server channel. |
| 19 |
/// |
| 20 |
/// This works as follows: |
| 21 |
/// 1. Client sends "attachio" request. |
| 22 |
/// 2. Server sends back 1-byte input request. |
| 23 |
/// 3. Client sends fds with 1-byte dummy payload in response. |
| 24 |
/// 4. Server returns the number of the fds received. |
| 25 |
/// |
| 26 |
/// The client-side fds may be dropped once duplicated to the server. |
| 27 |
pub async fn attach_io( |
| 28 |
proto: &mut Protocol<impl Connection + AsRawFd>, |
| 29 |
stdin: &impl AsRawFd, |
| 30 |
stdout: &impl AsRawFd, |
| 31 |
stderr: &impl AsRawFd, |
| 32 |
) -> io::Result<()> { |
| 33 |
proto.send_command("attachio").await?; |
| 34 |
loop { |
| 35 |
match proto.fetch_response().await? { |
| 36 |
ChannelMessage::Data(b'r', data) => { |
| 37 |
let fd_cnt = message::parse_result_code(data)?; |
| 38 |
if fd_cnt == 3 { |
| 39 |
return Ok(()); |
| 40 |
} else { |
| 41 |
return Err(io::Error::new( |
| 42 |
io::ErrorKind::InvalidData, |
| 43 |
"unexpected attachio result", |
| 44 |
)); |
| 45 |
} |
| 46 |
} |
| 47 |
ChannelMessage::Data(..) => { |
| 48 |
// just ignore data sent to uninteresting (optional) channel |
| 49 |
} |
| 50 |
ChannelMessage::InputRequest(1) => { |
| 51 |
// this may fail with EWOULDBLOCK in theory, but the |
| 52 |
// payload is quite small, and the send buffer should |
| 53 |
// be empty so the operation will complete immediately |
| 54 |
let sock_fd = proto.as_raw_fd(); |
| 55 |
let ifd = stdin.as_raw_fd(); |
| 56 |
let ofd = stdout.as_raw_fd(); |
| 57 |
let efd = stderr.as_raw_fd(); |
| 58 |
procutil::send_raw_fds(sock_fd, &[ifd, ofd, efd])?; |
| 59 |
} |
| 60 |
ChannelMessage::InputRequest(..) |
| 61 |
| ChannelMessage::LineRequest(..) |
| 62 |
| ChannelMessage::SystemRequest(..) => { |
| 63 |
return Err(io::Error::new( |
| 64 |
io::ErrorKind::InvalidData, |
| 65 |
"unsupported request while attaching io", |
| 66 |
)); |
| 67 |
} |
| 68 |
} |
| 69 |
} |
| 70 |
} |