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 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
use crate::config::Config; use crate::errors::Error; use crate::handle::Handle; use crate::packet::{Packet, PacketFuture}; use crate::pcap_util; 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}; pub type StreamItem<E> = Result<Vec<Packet>, E>; #[pin_project] pub struct PacketStream { config: Config, handle: Arc<Handle>, 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 { let h = handle .set_snaplen(config.snaplen())? .set_promiscuous()? .set_buffer_size(config.buffer_size())? .activate()?; if !config.blocking() { h.set_non_block()?; } if let Some(bpf) = config.bpf() { let bpf = handle.compile_bpf(bpf)?; handle.set_bpf(bpf)?; } } Ok(PacketStream { config: config, handle: handle, 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 f = if let Some(f) = this.pending.take() { f } else { match PacketFuture::new(this.config, this.handle) { Err(e) => { *this.complete = true; return Poll::Ready(Some(Err(e))); } Ok(f) => f, } }; match Pin::new(&mut f).poll(cx) { Poll::Pending => { *this.pending = Some(f); Poll::Pending } Poll::Ready(None) => { debug!("Stream was complete"); *this.complete = true; Poll::Ready(None) } Poll::Ready(Some(Err(e))) => { *this.complete = true; Poll::Ready(Some(Err(e))) } Poll::Ready(Some(Ok(packets))) => { trace!("Returning {} packets", packets.len()); Poll::Ready(Some(Ok(packets))) } } } } #[cfg(test)] mod tests { use super::*; use byteorder::{ByteOrder, ReadBytesExt}; use futures::{Future, Stream}; use std::io::Cursor; use std::path::PathBuf; #[test] 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 packets = smol::run(async move { 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 usize) .collect(); handle.interrupt(); packets }); 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); } #[test] fn packets_from_large_file() { let _ = env_logger::try_init(); let pcap_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) .join("resources") .join("4SICS-GeekLounge-151020.pcap"); info!("Testing against {:?}", pcap_path); let handle = Handle::file_capture(pcap_path.to_str().expect("No path found")) .expect("No handle created"); let packets = smol::run(async move { 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 usize) .collect(); handle.interrupt(); packets }); assert_eq!(packets.len(), 246137); } #[test] 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 packets = smol::run(async move { 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(); packets }); 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()) ); let mut stream = stream.unwrap(); smol::run(async move { stream.next().await }) .unwrap() .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()) ); } }