1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
use crate::config::Config; use crate::errors::Error; use crate::handle::Handle; use crate::packet::Packet; use crate::packet_future::PacketFuture; use crate::pcap_util; use failure::Fail; use futures::stream::{Stream, StreamExt}; use log::*; use pin_project::pin_project; use std::future::Future; use std::marker::PhantomData; use std::pin::Pin; use std::sync::Arc; use std::task::{Context, Poll}; use tokio::time::Delay; pub type StreamItem<E> = Result<Vec<Packet>, E>; #[pin_project] pub struct PacketStream { config: Config, handle: Arc<Handle>, delaying: Option<Delay>, pending: Option<PacketFuture>, complete: bool, } impl PacketStream { pub fn new(config: Config, handle: Arc<Handle>) -> Result<PacketStream, Error> { let live_capture = handle.is_live_capture(); if live_capture { handle .set_snaplen(config.snaplen())? .set_non_block()? .set_promiscuous()? .set_timeout(config.timeout())? .set_buffer_size(config.buffer_size())? .activate()?; if let Some(bpf) = config.bpf() { let bpf = handle.compile_bpf(bpf)?; handle.set_bpf(bpf)?; } } Ok(PacketStream { config: config, handle: handle, delaying: None, pending: None, complete: false, }) } } impl Stream for PacketStream { type Item = StreamItem<Error>; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { let this = self.project(); if *this.complete { return Poll::Ready(None); } let mut was_delayed = false; if let Some(mut existing_delay) = this.delaying.take() { trace!("Checking delay"); if let Poll::Pending = Pin::new(&mut existing_delay).poll(cx) { *this.delaying = Some(existing_delay); return Poll::Pending; } was_delayed = true; } let mut existing_future = this .pending .take() .unwrap_or_else(|| PacketFuture::new(this.config, &this.handle)); match Pin::new(&mut existing_future).poll(cx) { Poll::Pending => { *this.pending = Some(existing_future); Poll::Pending } Poll::Ready(Err(e)) => Poll::Ready(Some(Err(e))), Poll::Ready(Ok(None)) => { debug!("Stream was complete"); *this.complete = true; Poll::Ready(None) } Poll::Ready(Ok(Some(v))) => { if v.is_empty() && !was_delayed { trace!("No packets returned, and haven't delayed"); *this.delaying = Some(tokio::time::delay_for(*this.config.retry_after())); Poll::Pending } else { trace!("Returning {} packets", v.len()); Poll::Ready(Some(Ok(v))) } } } } } #[cfg(test)] mod tests { use super::*; use byteorder::{ByteOrder, ReadBytesExt}; use futures::{Future, Stream}; use std::io::Cursor; use std::path::PathBuf; #[tokio::test] async fn packets_from_file() { let _ = env_logger::try_init(); let pcap_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) .join("resources") .join("canary.pcap"); info!("Testing against {:?}", pcap_path); let handle = Handle::file_capture(pcap_path.to_str().expect("No path found")) .expect("No handle created"); let packet_provider = PacketStream::new(Config::default(), Arc::clone(&handle)).expect("Failed to build"); let fut_packets = packet_provider.collect::<Vec<_>>(); let packets: Vec<_> = fut_packets .await .into_iter() .flatten() .flatten() .filter(|p| p.data().len() == p.actual_length() as _) .collect(); handle.interrupt(); assert_eq!(packets.len(), 10); let packet = packets.first().cloned().expect("No packets"); let data = packet .into_pcap_record::<byteorder::BigEndian>() .expect("Failed to convert to pcap record"); let mut cursor = Cursor::new(data); let ts_sec = cursor .read_u32::<byteorder::BigEndian>() .expect("Failed to read"); let ts_usec = cursor .read_u32::<byteorder::BigEndian>() .expect("Failed to read"); let actual_length = cursor .read_u32::<byteorder::BigEndian>() .expect("Failed to read"); assert_eq!( ts_sec as u64 * 1_000_000 as u64 + ts_usec as u64, 1513735120021685 ); assert_eq!(actual_length, 54); } #[tokio::test] async fn packets_from_file_next() { let _ = env_logger::try_init(); let pcap_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) .join("resources") .join("canary.pcap"); info!("Testing against {:?}", pcap_path); let handle = Handle::file_capture(pcap_path.to_str().expect("No path found")) .expect("No handle created"); let packet_provider = PacketStream::new(Config::default(), Arc::clone(&handle)).expect("Failed to build"); let fut_packets = async move { let mut packet_provider = packet_provider.boxed(); let mut packets = vec![]; while let Some(p) = packet_provider.next().await { packets.extend(p); } packets }; let packets = fut_packets .await .into_iter() .flatten() .filter(|p| p.data().len() == p.actual_length() as _) .count(); handle.interrupt(); assert_eq!(packets, 10); } #[test] fn packets_from_lookup() { let _ = env_logger::try_init(); let handle = Handle::lookup().expect("No handle created"); let stream = PacketStream::new(Config::default(), handle); assert!( stream.is_ok(), format!("Could not build stream {}", stream.err().unwrap()) ); } #[test] fn packets_from_lookup_with_bpf() { let _ = env_logger::try_init(); let mut cfg = Config::default(); cfg.with_bpf( "(not (net 172.16.0.0/16 and port 443)) and (not (host 172.17.76.33 and port 443))" .to_owned(), ); let handle = Handle::lookup().expect("No handle created"); let stream = PacketStream::new(cfg, handle); assert!( stream.is_ok(), format!("Could not build stream {}", stream.err().unwrap()) ); } }