|
| 1 | +use std::{ |
| 2 | + io, |
| 3 | + pin::Pin, |
| 4 | + sync::{Arc, Mutex, TryLockError}, |
| 5 | + task::{Context, Poll}, |
| 6 | +}; |
| 7 | + |
| 8 | +use tokio::{ |
| 9 | + io::AsyncWrite, |
| 10 | + sync::mpsc::{self, error::TrySendError}, |
| 11 | +}; |
| 12 | + |
| 13 | +use russh_cryptovec::CryptoVec; |
| 14 | + |
| 15 | +use super::ChannelMsg; |
| 16 | +use crate::ChannelId; |
| 17 | + |
| 18 | +pub struct ChannelTx<S> { |
| 19 | + sender: mpsc::Sender<S>, |
| 20 | + id: ChannelId, |
| 21 | + |
| 22 | + window_size: Arc<Mutex<u32>>, |
| 23 | + max_packet_size: u32, |
| 24 | +} |
| 25 | + |
| 26 | +impl<S> ChannelTx<S> { |
| 27 | + pub fn new( |
| 28 | + sender: mpsc::Sender<S>, |
| 29 | + id: ChannelId, |
| 30 | + window_size: Arc<Mutex<u32>>, |
| 31 | + max_packet_size: u32, |
| 32 | + ) -> Self { |
| 33 | + Self { |
| 34 | + sender, |
| 35 | + id, |
| 36 | + window_size, |
| 37 | + max_packet_size, |
| 38 | + } |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +impl<S> AsyncWrite for ChannelTx<S> |
| 43 | +where |
| 44 | + S: From<(ChannelId, ChannelMsg)> + 'static, |
| 45 | +{ |
| 46 | + fn poll_write( |
| 47 | + self: Pin<&mut Self>, |
| 48 | + cx: &mut Context<'_>, |
| 49 | + buf: &[u8], |
| 50 | + ) -> Poll<Result<usize, io::Error>> { |
| 51 | + let mut window_size = match self.window_size.try_lock() { |
| 52 | + Ok(window_size) => window_size, |
| 53 | + Err(TryLockError::WouldBlock) => { |
| 54 | + cx.waker().wake_by_ref(); |
| 55 | + return Poll::Pending; |
| 56 | + } |
| 57 | + Err(TryLockError::Poisoned(err)) => { |
| 58 | + return Poll::Ready(Err(io::Error::new(io::ErrorKind::Other, err.to_string()))) |
| 59 | + } |
| 60 | + }; |
| 61 | + |
| 62 | + let writable = self.max_packet_size.min(*window_size).min(buf.len() as u32) as usize; |
| 63 | + if writable == 0 { |
| 64 | + cx.waker().wake_by_ref(); |
| 65 | + return Poll::Pending; |
| 66 | + } |
| 67 | + |
| 68 | + let mut data = CryptoVec::new_zeroed(writable); |
| 69 | + #[allow(clippy::indexing_slicing)] // Clamped to maximum `buf.len()` with `.min` |
| 70 | + data.copy_from_slice(&buf[..writable]); |
| 71 | + data.resize(writable); |
| 72 | + |
| 73 | + *window_size -= writable as u32; |
| 74 | + drop(window_size); |
| 75 | + |
| 76 | + match self |
| 77 | + .sender |
| 78 | + .try_send((self.id, ChannelMsg::Data { data }).into()) |
| 79 | + { |
| 80 | + Ok(_) => Poll::Ready(Ok(writable)), |
| 81 | + Err(TrySendError::Closed(_)) => Poll::Ready(Ok(0)), |
| 82 | + Err(TrySendError::Full(_)) => { |
| 83 | + cx.waker().wake_by_ref(); |
| 84 | + Poll::Pending |
| 85 | + } |
| 86 | + } |
| 87 | + } |
| 88 | + |
| 89 | + fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> { |
| 90 | + Poll::Ready(Ok(())) |
| 91 | + } |
| 92 | + |
| 93 | + fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> { |
| 94 | + self.poll_flush(cx) |
| 95 | + } |
| 96 | +} |
0 commit comments