Some work-in-progress code for extracting trigger traffic
[pingpong.git] / Code / Projects / SmartPlugDetector / src / main / java / edu / uci / iotproject / analysis / PcapHandleReader.java
1 package edu.uci.iotproject.analysis;
2
3 import org.pcap4j.core.*;
4
5 import java.io.EOFException;
6 import java.util.concurrent.TimeoutException;
7
8 /**
9  * Reads packets from a {@link PcapHandle} (online or offline) and delivers those packets that pass the test exercised
10  * by the provided {@link PcapPacketFilter} onto the provided {@link PacketListener}s.
11  *
12  * @author Janus Varmarken
13  */
14 public class PcapHandleReader {
15
16     private final PcapPacketFilter mPacketFilter;
17     private final PcapHandle mHandle;
18     private final PacketListener[] mPacketListeners;
19
20     public PcapHandleReader(PcapHandle handle, PcapPacketFilter packetFilter, PacketListener... packetListeners) {
21         mHandle = handle;
22         mPacketFilter = packetFilter;
23         mPacketListeners = packetListeners;
24     }
25
26
27     /**
28      * Start reading (and filtering) packets from the provided {@link PcapHandle}.
29      * @throws PcapNativeException if an error occurs in the pcap native library.
30      * @throws NotOpenException if the provided {@code PcapHandle} is not open.
31      * @throws TimeoutException if packets are being read from a live capture and the timeout expired.
32      */
33     public void readFromHandle() throws PcapNativeException, NotOpenException, TimeoutException {
34         try {
35             PcapPacket prevPacket = null;
36             PcapPacket packet;
37             while ((packet = mHandle.getNextPacketEx()) != null) {
38                 if (prevPacket != null && packet.getTimestamp().isBefore(prevPacket.getTimestamp())) {
39                     // Fail early if assumption doesn't hold.
40                     mHandle.close();
41                     throw new AssertionError("Packets not in ascending temporal order");
42                 }
43                 if (mPacketFilter.shouldIncludePacket(packet)) {
44                     // Packet accepted for inclusion; deliver it to observing client code.
45                     for (PacketListener consumer : mPacketListeners) {
46                         consumer.gotPacket(packet);
47                     }
48                 }
49                 prevPacket = packet;
50             }
51         } catch (EOFException eof) {
52             // Reached end of file. All good.
53             System.out.println(String.format("%s: finished reading pcap file", getClass().getSimpleName()));
54         }
55         mHandle.close();
56     }
57
58 }