Fixing bug in skipped packet analysis.
[pingpong.git] / Code / Projects / PacketLevelSignatureExtractor / src / main / java / edu / uci / iotproject / detection / layer2 / Layer2SignatureDetector.java
1 package edu.uci.iotproject.detection.layer2;
2
3 import edu.uci.iotproject.analysis.TriggerTrafficExtractor;
4 import edu.uci.iotproject.analysis.UserAction;
5 import edu.uci.iotproject.detection.AbstractClusterMatcher;
6 import edu.uci.iotproject.detection.ClusterMatcherObserver;
7 import edu.uci.iotproject.detection.SignatureDetectorObserver;
8 import edu.uci.iotproject.io.PcapHandleReader;
9 import edu.uci.iotproject.io.PrintWriterUtils;
10 import edu.uci.iotproject.trafficreassembly.layer2.Layer2Flow;
11 import edu.uci.iotproject.trafficreassembly.layer2.Layer2FlowReassembler;
12 import edu.uci.iotproject.util.PcapPacketUtils;
13 import edu.uci.iotproject.util.PrintUtils;
14 import org.jgrapht.GraphPath;
15 import org.jgrapht.alg.shortestpath.DijkstraShortestPath;
16 import org.jgrapht.graph.DefaultWeightedEdge;
17 import org.jgrapht.graph.SimpleDirectedWeightedGraph;
18 import org.pcap4j.core.*;
19
20 import java.io.File;
21 import java.io.FileWriter;
22 import java.io.IOException;
23 import java.io.PrintWriter;
24 import java.time.Duration;
25 import java.util.*;
26 import java.util.function.Function;
27 import java.util.regex.Pattern;
28
29 /**
30  * Performs layer 2 signature detection.
31  *
32  * @author Janus Varmarken {@literal <jvarmark@uci.edu>}
33  * @author Rahmadi Trimananda {@literal <rtrimana@uci.edu>}
34  */
35 public class Layer2SignatureDetector implements PacketListener, ClusterMatcherObserver {
36
37     /**
38      * If set to {@code true}, output written to the results file is also dumped to standard out.
39      */
40     private static boolean DUPLICATE_OUTPUT_TO_STD_OUT = true;
41
42     private static List<Function<Layer2Flow, Boolean>> parseSignatureMacFilters(String filtersString) {
43         List<Function<Layer2Flow, Boolean>> filters = new ArrayList<>();
44         String[] filterRegexes = filtersString.split(";");
45         for (String filterRegex : filterRegexes) {
46             final Pattern regex = Pattern.compile(filterRegex);
47             // Create a filter that includes all flows where one of the two MAC addresses match the regex.
48             filters.add(flow -> regex.matcher(flow.getEndpoint1().toString()).matches() || regex.matcher(flow.getEndpoint2().toString()).matches());
49         }
50         return filters;
51     }
52
53     public static void main(String[] args) throws PcapNativeException, NotOpenException, IOException {
54         // Parse required parameters.
55         if (args.length < 10) {
56             String errMsg = String.format("SPECTO version 1.0\n" +
57                             "Copyright (C) 2018-2019 Janus Varmarken and Rahmadi Trimananda.\n" +
58                             "University of California, Irvine.\n" +
59                             "All rights reserved.\n\n" +
60                             "Usage: %s inputPcapFile onAnalysisFile offAnalysisFile onSignatureFile offSignatureFile " +
61                             "resultsFile signatureDuration eps onMaxSkippedPackets offMaxSkippedPackets" +
62                             "\n  inputPcapFile: the target of the detection" +
63                             "\n  onAnalysisFile: the file that contains the ON clusters analysis" +
64                             "\n  offAnalysisFile: the file that contains the OFF clusters analysis" +
65                             "\n  onSignatureFile: the file that contains the ON signature to search for" +
66                             "\n  offSignatureFile: the file that contains the OFF signature to search for" +
67                             "\n  resultsFile: where to write the results of the detection" +
68                             "\n  signatureDuration: the maximum duration of signature detection" +
69                             "\n  eps: the epsilon value for the DBSCAN algorithm" +
70                             "\n  onMaxSkippedPackets: the maximum duration of ON signature detection (put -1 if not used)" +
71                             "\n  offMaxSkippedPackets: the maximum duration of OFF signature detection (put -1 if not used)",
72                     Layer2SignatureDetector.class.getSimpleName());
73             System.out.println(errMsg);
74             String optParamsExplained = "Above are the required, positional arguments. In addition to these, the " +
75                     "following options and associated positional arguments may be used:\n" +
76                     "  '-onmacfilters <regex>;<regex>;...;<regex>' which specifies that sequence matching should ONLY" +
77                     " be performed on flows where the MAC of one of the two endpoints matches the given regex. Note " +
78                     "that you MUST specify a regex for each cluster of the signature. This is to facilitate more " +
79                     "aggressive filtering on parts of the signature (e.g., the communication that involves the " +
80                     "smart home device itself as one can drop all flows that do not include an endpoint with a MAC " +
81                     "that matches the vendor's prefix).\n" +
82                     "  '-offmacfilters <regex>;<regex>;...;<regex>' works exactly the same as onmacfilters, but " +
83                     "applies to the OFF signature instead of the ON signature.\n" +
84                     "  '-sout <boolean literal>' true/false literal indicating if output should also be printed to std out; default is true.";
85             System.out.println(optParamsExplained);
86             return;
87         }
88         final String pcapFile = args[0];
89         final String onClusterAnalysisFile = args[1];
90         final String offClusterAnalysisFile = args[2];
91         final String onSignatureFile = args[3];
92         final String offSignatureFile = args[4];
93         final String resultsFile = args[5];
94         final int signatureDuration = Integer.parseInt(args[6]);
95         final double eps = Double.parseDouble(args[7]);
96         final int onMaxSkippedPackets = Integer.parseInt(args[8]);
97         final int offMaxSkippedPackets = Integer.parseInt(args[9]);
98
99         // Parse optional parameters.
100         List<Function<Layer2Flow, Boolean>> onSignatureMacFilters = null, offSignatureMacFilters = null;
101         final int optParamsStartIdx = 7;
102         if (args.length > optParamsStartIdx) {
103             for (int i = optParamsStartIdx; i < args.length; i++) {
104                 if (args[i].equalsIgnoreCase("-onMacFilters")) {
105                     // Next argument is the cluster-wise MAC filters (separated by semicolons).
106                     onSignatureMacFilters = parseSignatureMacFilters(args[i+1]);
107                 } else if (args[i].equalsIgnoreCase("-offMacFilters")) {
108                     // Next argument is the cluster-wise MAC filters (separated by semicolons).
109                     offSignatureMacFilters = parseSignatureMacFilters(args[i+1]);
110                 } else if (args[i].equalsIgnoreCase("-sout")) {
111                     // Next argument is a boolean true/false literal.
112                     DUPLICATE_OUTPUT_TO_STD_OUT = Boolean.parseBoolean(args[i+1]);
113                 }
114             }
115         }
116
117         // Prepare file outputter.
118         File outputFile = new File(resultsFile);
119         outputFile.getParentFile().mkdirs();
120         final PrintWriter resultsWriter = new PrintWriter(new FileWriter(outputFile));
121         // Include metadata as comments at the top
122         PrintWriterUtils.println("# Detection results for:", resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
123         PrintWriterUtils.println("# - inputPcapFile: " + pcapFile, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
124         PrintWriterUtils.println("# - onAnalysisFile: " + onClusterAnalysisFile, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
125         PrintWriterUtils.println("# - offAnalysisFile: " + offClusterAnalysisFile, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
126         PrintWriterUtils.println("# - onSignatureFile: " + onSignatureFile, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
127         PrintWriterUtils.println("# - offSignatureFile: " + offSignatureFile, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
128         resultsWriter.flush();
129
130         // Create signature detectors and add observers that output their detected events.
131         List<List<List<PcapPacket>>> onSignature = PrintUtils.deserializeFromFile(onSignatureFile);
132         List<List<List<PcapPacket>>> offSignature = PrintUtils.deserializeFromFile(offSignatureFile);
133         // Load signature analyses
134         List<List<List<PcapPacket>>> onClusterAnalysis = PrintUtils.deserializeFromFile(onClusterAnalysisFile);
135         List<List<List<PcapPacket>>> offClusterAnalysis = PrintUtils.deserializeFromFile(offClusterAnalysisFile);
136         // TODO: FOR NOW WE DECIDE PER SIGNATURE AND THEN WE OR THE BOOLEANS
137         // TODO: SINCE WE ONLY HAVE 2 SIGNATURES FOR NOW (ON AND OFF), THEN IT IS USUALLY EITHER RANGE-BASED OR
138         // TODO: STRICT MATCHING
139         // Check if we should use range-based matching
140         boolean isRangeBasedForOn = PcapPacketUtils.isRangeBasedMatching(onSignature, eps, offSignature);
141         boolean isRangeBasedForOff = PcapPacketUtils.isRangeBasedMatching(offSignature, eps, onSignature);
142         // TODO: WE DON'T DO RANGE-BASED FOR NOW BECAUSE THE RESULTS ARE TERRIBLE FOR LAYER 2 MATCHING
143         // TODO: THIS WOULD ONLY WORK FOR SIGNATURES LONGER THAN 2 PACKETS
144 //        boolean isRangeBasedForOn = false;
145 //        boolean isRangeBasedForOff = false;
146         // Update the signature with ranges if it is range-based
147         if (isRangeBasedForOn) {
148             onSignature = PcapPacketUtils.useRangeBasedMatching(onSignature, onClusterAnalysis);
149         }
150         if (isRangeBasedForOff) {
151             offSignature = PcapPacketUtils.useRangeBasedMatching(offSignature, offClusterAnalysis);
152         }
153         Layer2SignatureDetector onDetector = onSignatureMacFilters == null ?
154                 new Layer2SignatureDetector(onSignature, signatureDuration, isRangeBasedForOn, eps, onMaxSkippedPackets) :
155                 new Layer2SignatureDetector(onSignature, onSignatureMacFilters, signatureDuration,
156                         isRangeBasedForOn, eps, onMaxSkippedPackets);
157         Layer2SignatureDetector offDetector = offSignatureMacFilters == null ?
158                 new Layer2SignatureDetector(offSignature, signatureDuration, isRangeBasedForOff, eps, offMaxSkippedPackets) :
159                 new Layer2SignatureDetector(offSignature, offSignatureMacFilters, signatureDuration,
160                         isRangeBasedForOff, eps, offMaxSkippedPackets);
161         final List<UserAction> detectedEvents = new ArrayList<>();
162         onDetector.addObserver((signature, match) -> {
163             UserAction event = new UserAction(UserAction.Type.TOGGLE_ON, match.get(0).get(0).getTimestamp());
164             PrintWriterUtils.println(event, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
165             detectedEvents.add(event);
166         });
167         offDetector.addObserver((signature, match) -> {
168             UserAction event = new UserAction(UserAction.Type.TOGGLE_OFF, match.get(0).get(0).getTimestamp());
169             PrintWriterUtils.println(event, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
170             detectedEvents.add(event);
171         });
172
173         // Load the PCAP file
174         PcapHandle handle;
175         try {
176             handle = Pcaps.openOffline(pcapFile, PcapHandle.TimestampPrecision.NANO);
177         } catch (PcapNativeException pne) {
178             handle = Pcaps.openOffline(pcapFile);
179         }
180         PcapHandleReader reader = new PcapHandleReader(handle, p -> true, onDetector, offDetector);
181         // Parse the file
182         reader.readFromHandle();
183
184         String resultOn = "# Number of detected events of type " + UserAction.Type.TOGGLE_ON + ": " +
185                 detectedEvents.stream().filter(ua -> ua.getType() == UserAction.Type.TOGGLE_ON).count();
186         String resultOff = "# Number of detected events of type " + UserAction.Type.TOGGLE_OFF + ": " +
187                 detectedEvents.stream().filter(ua -> ua.getType() == UserAction.Type.TOGGLE_OFF).count();
188         String onMaximumSkippedPackets = "# Maximum number of skipped packets in ON signature " +
189                 Integer.toString(onDetector.getMaxSkippedPackets());
190         String offMaximumSkippedPackets = "# Maximum number of skipped packets in OFF signature " +
191                 Integer.toString(offDetector.getMaxSkippedPackets());
192         PrintWriterUtils.println(resultOn, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
193         PrintWriterUtils.println(resultOff, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
194         PrintWriterUtils.println(onMaximumSkippedPackets, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
195         for(Integer skippedPackets : onDetector.getSkippedPackets()) {
196             PrintWriterUtils.println(skippedPackets, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
197         }
198         PrintWriterUtils.println(offMaximumSkippedPackets, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
199         for(Integer skippedPackets : offDetector.getSkippedPackets()) {
200             PrintWriterUtils.println(skippedPackets, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
201         }
202         // Flush output to results file and close it.
203         resultsWriter.flush();
204         resultsWriter.close();
205     }
206
207     /**
208      * The signature that this {@link Layer2SignatureDetector} is searching for.
209      */
210     private final List<List<List<PcapPacket>>> mSignature;
211
212     /**
213      * The {@link Layer2ClusterMatcher}s in charge of detecting each individual sequence of packets that together make
214      * up the the signature.
215      */
216     private final List<Layer2ClusterMatcher> mClusterMatchers;
217
218     /**
219      * For each {@code i} ({@code i >= 0 && i < mPendingMatches.length}), {@code mPendingMatches[i]} holds the matches
220      * found by the {@link Layer2ClusterMatcher} at {@code mClusterMatchers.get(i)} that have yet to be "consumed",
221      * i.e., have yet to be included in a signature detected by this {@link Layer2SignatureDetector} (a signature can
222      * be encompassed of multiple packet sequences occurring shortly after one another on multiple connections).
223      */
224     private final List<List<PcapPacket>>[] mPendingMatches;
225
226     /**
227      * Maps a {@link Layer2ClusterMatcher} to its corresponding index in {@link #mPendingMatches}.
228      */
229     private final Map<Layer2ClusterMatcher, Integer> mClusterMatcherIds;
230
231     /**
232      * In charge of reassembling layer 2 packet flows.
233      */
234     private final Layer2FlowReassembler mFlowReassembler = new Layer2FlowReassembler();
235
236     private final List<SignatureDetectorObserver> mObservers = new ArrayList<>();
237
238     private int mInclusionTimeMillis;
239
240     /**
241      * Skipped-packet analysis.
242      */
243     private int mMaxSkippedPackets;
244     private List<Integer> mSkippedPackets;
245
246     public Layer2SignatureDetector(List<List<List<PcapPacket>>> searchedSignature, int signatureDuration,
247                                    boolean isRangeBased, double eps, int limitSkippedPackets) {
248         this(searchedSignature, null, signatureDuration, isRangeBased, eps, limitSkippedPackets);
249     }
250
251     public Layer2SignatureDetector(List<List<List<PcapPacket>>> searchedSignature, List<Function<Layer2Flow,
252             Boolean>> flowFilters, int inclusionTimeMillis, boolean isRangeBased, double eps, int limitSkippedPackets) {
253         if (flowFilters != null && flowFilters.size() != searchedSignature.size()) {
254             throw new IllegalArgumentException("If flow filters are used, there must be a flow filter for each cluster " +
255                     "of the signature.");
256         }
257         mSignature = Collections.unmodifiableList(searchedSignature);
258         List<Layer2ClusterMatcher> clusterMatchers = new ArrayList<>();
259         for (int i = 0; i < mSignature.size(); i++) {
260             List<List<PcapPacket>> cluster = mSignature.get(i);
261             Layer2ClusterMatcher clusterMatcher = flowFilters == null ?
262                     new Layer2ClusterMatcher(cluster, inclusionTimeMillis, isRangeBased, eps, limitSkippedPackets) :
263                     new Layer2ClusterMatcher(cluster, flowFilters.get(i), inclusionTimeMillis, isRangeBased,
264                             eps, limitSkippedPackets);
265             clusterMatcher.addObserver(this);
266             clusterMatchers.add(clusterMatcher);
267         }
268         mClusterMatchers = Collections.unmodifiableList(clusterMatchers);
269         mPendingMatches = new List[mClusterMatchers.size()];
270         for (int i = 0; i < mPendingMatches.length; i++) {
271             mPendingMatches[i] = new ArrayList<>();
272         }
273         Map<Layer2ClusterMatcher, Integer> clusterMatcherIds = new HashMap<>();
274         for (int i = 0; i < mClusterMatchers.size(); i++) {
275             clusterMatcherIds.put(mClusterMatchers.get(i), i);
276         }
277         mClusterMatcherIds = Collections.unmodifiableMap(clusterMatcherIds);
278         // Register all cluster matchers to receive a notification whenever a new flow is encountered.
279         mClusterMatchers.forEach(cm -> mFlowReassembler.addObserver(cm));
280         mInclusionTimeMillis =
281                 inclusionTimeMillis == 0 ? TriggerTrafficExtractor.INCLUSION_WINDOW_MILLIS : inclusionTimeMillis;
282         mMaxSkippedPackets = 0;
283         mSkippedPackets = new ArrayList<>();
284     }
285
286     public int getMaxSkippedPackets() {
287         return mMaxSkippedPackets;
288     }
289
290     public List<Integer> getSkippedPackets() {
291         for (Layer2ClusterMatcher matcher : mClusterMatchers) {
292             mSkippedPackets.addAll(matcher.getSkippedPackets());
293         }
294         return mSkippedPackets;
295     }
296
297     @Override
298     public void gotPacket(PcapPacket packet) {
299         // Forward packet processing to the flow reassembler that in turn notifies the cluster matchers as appropriate
300         mFlowReassembler.gotPacket(packet);
301     }
302
303     @Override
304     public void onMatch(AbstractClusterMatcher clusterMatcher, List<PcapPacket> match) {
305         // TODO: a cluster matcher found a match
306         if (clusterMatcher instanceof Layer2ClusterMatcher) {
307             // Add the match at the corresponding index
308             mPendingMatches[mClusterMatcherIds.get(clusterMatcher)].add(match);
309             checkSignatureMatch();
310             // Update maximum number of skipped packets
311             if (mMaxSkippedPackets < ((Layer2ClusterMatcher) clusterMatcher).getMaxSkippedPackets()) {
312                 mMaxSkippedPackets = ((Layer2ClusterMatcher) clusterMatcher).getMaxSkippedPackets();
313             }
314             //if (mSkippedPackets.size() < ((Layer2ClusterMatcher) clusterMatcher).getSkippedPackets().size()) {
315             //    mSkippedPackets = ((Layer2ClusterMatcher) clusterMatcher).getSkippedPackets();
316             //}
317             //mSkippedPackets.addAll(((Layer2ClusterMatcher) clusterMatcher).getSkippedPackets());
318         }
319     }
320
321     public void addObserver(SignatureDetectorObserver observer) {
322         mObservers.add(observer);
323     }
324
325     public boolean removeObserver(SignatureDetectorObserver observer) {
326         return mObservers.remove(observer);
327     }
328
329
330     @SuppressWarnings("Duplicates")
331     private void checkSignatureMatch() {
332         // << Graph-based approach using Balint's idea. >>
333         // This implementation assumes that the packets in the inner lists (the sequences) are ordered by asc timestamp.
334
335         // There cannot be a signature match until each Layer3ClusterMatcher has found a match of its respective sequence.
336         if (Arrays.stream(mPendingMatches).noneMatch(l -> l.isEmpty())) {
337             // Construct the DAG
338             final SimpleDirectedWeightedGraph<Vertex, DefaultWeightedEdge> graph =
339                     new SimpleDirectedWeightedGraph<>(DefaultWeightedEdge.class);
340             // Add a vertex for each match found by all cluster matchers.
341             // And maintain an array to keep track of what cluster matcher each vertex corresponds to
342             final List<Vertex>[] vertices = new List[mPendingMatches.length];
343             for (int i = 0; i < mPendingMatches.length; i++) {
344                 vertices[i] = new ArrayList<>();
345                 for (List<PcapPacket> sequence : mPendingMatches[i]) {
346                     Vertex v = new Vertex(sequence);
347                     vertices[i].add(v); // retain reference for later when we are to add edges
348                     graph.addVertex(v); // add to vertex to graph
349                 }
350             }
351             // Add dummy source and sink vertices to facilitate search.
352             final Vertex source = new Vertex(null);
353             final Vertex sink = new Vertex(null);
354             graph.addVertex(source);
355             graph.addVertex(sink);
356             // The source is connected to all vertices that wrap the sequences detected by cluster matcher at index 0.
357             // Note: zero cost edges as this is just a dummy link to facilitate search from a common start node.
358             for (Vertex v : vertices[0]) {
359                 DefaultWeightedEdge edge = graph.addEdge(source, v);
360                 graph.setEdgeWeight(edge, 0.0);
361             }
362             // Similarly, all vertices that wrap the sequences detected by the last cluster matcher of the signature
363             // are connected to the sink node.
364             for (Vertex v : vertices[vertices.length-1]) {
365                 DefaultWeightedEdge edge = graph.addEdge(v, sink);
366                 graph.setEdgeWeight(edge, 0.0);
367             }
368             // Now link sequences detected by the cluster matcher at index i to sequences detected by the cluster
369             // matcher at index i+1 if they obey the timestamp constraint (i.e., that the latter is later in time than
370             // the former).
371             for (int i = 0; i < vertices.length; i++) {
372                 int j = i + 1;
373                 if (j < vertices.length) {
374                     for (Vertex iv : vertices[i]) {
375                         PcapPacket ivLast = iv.sequence.get(iv.sequence.size()-1);
376                         for (Vertex jv : vertices[j]) {
377                             PcapPacket jvFirst = jv.sequence.get(jv.sequence.size()-1);
378                             if (ivLast.getTimestamp().isBefore(jvFirst.getTimestamp())) {
379                                 DefaultWeightedEdge edge = graph.addEdge(iv, jv);
380                                 // The weight is the duration of the i'th sequence plus the duration between the i'th
381                                 // and i+1'th sequence.
382                                 Duration d = Duration.
383                                         between(iv.sequence.get(0).getTimestamp(), jvFirst.getTimestamp());
384                                 // Unfortunately weights are double values, so must convert from long to double.
385                                 // TODO: need nano second precision? If so, use d.toNanos().
386                                 // TODO: risk of overflow when converting from long to double..?
387                                 graph.setEdgeWeight(edge, Long.valueOf(d.toMillis()).doubleValue());
388                             }
389                             // Alternative version if we cannot assume that sequences are ordered by timestamp:
390 //                            if (iv.sequence.stream().max(Comparator.comparing(PcapPacket::getTimestamp)).get()
391 //                                    .getTimestamp().isBefore(jv.sequence.stream().min(
392 //                                            Comparator.comparing(PcapPacket::getTimestamp)).get().getTimestamp())) {
393 //
394 //                            }
395                         }
396                     }
397                 }
398             }
399             // Graph construction complete, run shortest-path to find a (potential) signature match.
400             DijkstraShortestPath<Vertex, DefaultWeightedEdge> dijkstra = new DijkstraShortestPath<>(graph);
401             GraphPath<Vertex, DefaultWeightedEdge> shortestPath = dijkstra.getPath(source, sink);
402             if (shortestPath != null) {
403                 // The total weight is the duration between the first packet of the first sequence and the last packet
404                 // of the last sequence, so we simply have to compare the weight against the timeframe that we allow
405                 // the signature to span. For now we just use the inclusion window we defined for training purposes.
406                 // Note however, that we must convert back from double to long as the weight is stored as a double in
407                 // JGraphT's API.
408                 if (((long)shortestPath.getWeight()) < mInclusionTimeMillis) {
409                     // There's a signature match!
410                     // Extract the match from the vertices
411                     List<List<PcapPacket>> signatureMatch = new ArrayList<>();
412                     for(Vertex v : shortestPath.getVertexList()) {
413                         if (v == source || v == sink) {
414                             // Skip the dummy source and sink nodes.
415                             continue;
416                         }
417                         signatureMatch.add(v.sequence);
418                         // As there is a one-to-one correspondence between vertices[] and pendingMatches[], we know that
419                         // the sequence we've "consumed" for index i of the matched signature is also at index i in
420                         // pendingMatches. We must remove it from pendingMatches so that we don't use it to construct
421                         // another signature match in a later call.
422                         mPendingMatches[signatureMatch.size()-1].remove(v.sequence);
423                     }
424                     // Declare success: notify observers
425                     mObservers.forEach(obs -> obs.onSignatureDetected(mSignature,
426                             Collections.unmodifiableList(signatureMatch)));
427                 }
428             }
429         }
430     }
431
432     /**
433      * Encapsulates a {@code List<PcapPacket>} so as to allow the list to be used as a vertex in a graph while avoiding
434      * the expensive {@link AbstractList#equals(Object)} calls when adding vertices to the graph.
435      * Using this wrapper makes the incurred {@code equals(Object)} calls delegate to {@link Object#equals(Object)}
436      * instead of {@link AbstractList#equals(Object)}. The net effect is a faster implementation, but the graph will not
437      * recognize two lists that contain the same items--from a value and not reference point of view--as the same
438      * vertex. However, this is fine for our purposes -- in fact restricting it to reference equality seems more
439      * appropriate.
440      */
441     private static class Vertex {
442         private final List<PcapPacket> sequence;
443         private Vertex(List<PcapPacket> wrappedSequence) {
444             sequence = wrappedSequence;
445         }
446     }
447 }