对How do I read the entire body of a Tokio-based Hyper request?的回答表明:
您可能希望对[使用
futures::Stream::concat2
时读取的字节数设置某种上限
我该如何实际实现?例如,以下代码可模仿向我的服务发送无限数量数据的恶意用户:
extern crate futures; // 0.1.25
use futures::{prelude::*, stream};
fn some_bytes() -> impl Stream<Item = Vec<u8>, Error = ()> {
stream::repeat(b"0123456789ABCDEF".to_vec())
}
fn limited() -> impl Future<Item = Vec<u8>, Error = ()> {
some_bytes().concat2()
}
fn main() {
let v = limited().wait().unwrap();
println!("{}", v.len());
}
答案 0 :(得分:3)
一种解决方案是创建一个流组合器,一旦超过某个字节阈值,该组合器就会终止该流。这是一种可能的实现方式:
struct TakeBytes<S> {
inner: S,
seen: usize,
limit: usize,
}
impl<S> Stream for TakeBytes<S>
where
S: Stream<Item = Vec<u8>>,
{
type Item = Vec<u8>;
type Error = S::Error;
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
if self.seen >= self.limit {
return Ok(Async::Ready(None)); // Stream is over
}
let inner = self.inner.poll();
if let Ok(Async::Ready(Some(ref v))) = inner {
self.seen += v.len();
}
inner
}
}
trait TakeBytesExt: Sized {
fn take_bytes(self, limit: usize) -> TakeBytes<Self>;
}
impl<S> TakeBytesExt for S
where
S: Stream<Item = Vec<u8>>,
{
fn take_bytes(self, limit: usize) -> TakeBytes<Self> {
TakeBytes {
inner: self,
limit,
seen: 0,
}
}
}
然后可以将其链接到concat2
之前的流上:
fn limited() -> impl Future<Item = Vec<u8>, Error = ()> {
some_bytes().take_bytes(999).concat2()
}
此实现有一些警告:
Vec<u8>
。当然,您可以引入泛型以使其更广泛地适用。要记住的另一件事是,您希望尝试解决尽可能低的问题—如果数据源已经分配了1 GB的内存,则设置限制将无济于事。 / p>