6fa3549af9d36d20356feb2999ab28b6edda8352
[pingpong.git] / Code / Projects / SmartPlugDetector / src / main / java / edu / uci / iotproject / detection / SignatureDetector.java
1 package edu.uci.iotproject.detection;
2
3 import edu.uci.iotproject.analysis.TriggerTrafficExtractor;
4 import edu.uci.iotproject.analysis.UserAction;
5 import edu.uci.iotproject.io.PcapHandleReader;
6 import edu.uci.iotproject.util.PrintUtils;
7 import org.jgrapht.GraphPath;
8 import org.jgrapht.alg.shortestpath.DijkstraShortestPath;
9 import org.jgrapht.graph.DefaultWeightedEdge;
10 import org.jgrapht.graph.SimpleDirectedWeightedGraph;
11 import org.pcap4j.core.*;
12
13 import java.time.Duration;
14 import java.time.Instant;
15 import java.time.ZoneId;
16 import java.time.format.DateTimeFormatter;
17 import java.time.format.FormatStyle;
18 import java.util.*;
19 import java.util.function.Consumer;
20
21 /**
22  * Detects an event signature that spans one or multiple TCP connections.
23  *
24  * @author Janus Varmarken {@literal <jvarmark@uci.edu>}
25  * @author Rahmadi Trimananda {@literal <rtrimana@uci.edu>}
26  */
27 public class SignatureDetector implements PacketListener, ClusterMatcher.ClusterMatchObserver {
28
29     // Test client
30     public static void main(String[] args) throws PcapNativeException, NotOpenException {
31         String path = "/scratch/July-2018"; // Rahmadi
32         //String path = "/Users/varmarken/temp/UCI IoT Project/experiments"; // Janus
33
34         // No activity test
35         //final String inputPcapFile = path + "/evaluation/no-activity/no-activity.wlan1.pcap";
36
37         // D-Link Siren experiment
38 //        final String inputPcapFile = path + "/evaluation/dlink-siren/dlink-siren.data.wlan1.pcap";
39 //        final String inputPcapFile = path + "/evaluation/dlink-siren/dlink-siren.eth0.local.pcap";
40         // D-Link Siren DEVICE signatures
41 //        final String onSignatureFile = path + "/2018-08/dlink-siren/onSignature-DLink-Siren-device.sig";
42 //        final String offSignatureFile = path + "/2018-08/dlink-siren/offSignature-DLink-Siren-device.sig";
43         // D-Link Siren PHONE signatures
44 //        final String onSignatureFile = path + "/2018-08/dlink-siren/onSignature-DLink-Siren-phone.sig";
45 //        final String offSignatureFile = path + "/2018-08/dlink-siren/offSignature-DLink-Siren-phone.sig";
46
47         /*
48         // Kwikset Doorlock Sep 12 experiment
49 //        final String inputPcapFile = path + "/evaluation/kwikset-doorlock/kwikset-doorlock.data.wlan1.pcap";
50         final String inputPcapFile = path + "/evaluation/kwikset-doorlock/kwikset-doorlock.data.eth0.pcap";
51 //        // Kwikset Doorlock PHONE signatures
52         final String onSignatureFile = path + "/2018-08/kwikset-doorlock/onSignature-Kwikset-Doorlock-phone-new.sig";
53         final String offSignatureFile = path + "/2018-08/kwikset-doorlock/offSignature-Kwikset-Doorlock-phone-new.sig";
54         */
55
56         // D-Link Plug experiment
57         //final String inputPcapFile = path + "/evaluation/dlink/dlink-plug.data.wlan1.pcap";
58 //        final String inputPcapFile = path + "/evaluation/dlink/dlink-plug.data.eth0.pcap";
59
60         // D-Link Plug DEVICE signatures
61 //        final String onSignatureFile = path + "/2018-07/dlink/onSignature-DLink-Plug-device.sig";
62 //        final String offSignatureFile = path + "/2018-07/dlink/offSignature-DLink-Plug-device.sig";
63         // D-Link Plug PHONE signatures
64 //        final String onSignatureFile = path + "/2018-07/dlink/onSignature-DLink-Plug-phone.sig";
65 //        final String offSignatureFile = path + "/2018-07/dlink/offSignature-DLink-Plug-phone.sig";
66
67
68         // TODO: The following are tests for signatures against training data
69
70         /*
71         // D-Link Plug experiment
72         final String inputPcapFile = path + "/training/dlink-plug/wlan1/dlink-plug.wlan1.local.pcap";
73         // D-Link Plug DEVICE signatures
74         //final String onSignatureFile = path + "/training/dlink-plug/signatures/dlink-plug-onSignature-device-side.sig";
75         //final String offSignatureFile = path + "/training/dlink-plug/signatures/dlink-plug-offSignature-device-side.sig";
76         // D-Link Plug PHONE signatures
77         final String onSignatureFile = path + "/training/dlink-plug/signatures/dlink-plug-onSignature-phone-side.sig";
78         final String offSignatureFile = path + "/training/dlink-plug/signatures/dlink-plug-offSignature-phone-side.sig";
79         */
80
81         /*
82         // TP-Link Plug experiment
83         final String inputPcapFile = path + "/training/tplink-plug/wlan1/tplink-plug.wlan1.local.pcap";
84         // TP-Link Plug DEVICE signatures
85         //final String onSignatureFile = path + "/training/tplink-plug/signatures/tplink-plug-onSignature-device-side.sig";
86         //final String offSignatureFile = path + "/training/tplink-plug/signatures/tplink-plug-offSignature-device-side.sig";
87         */
88
89         // Arlo camera experiment
90 //        final String inputPcapFile = path + "/training/arlo-camera/wlan1/arlo-camera.wlan1.local.pcap";
91 //        // TP-Link Plug DEVICE signatures
92 //        final String onSignatureFile = path + "/training/arlo-camera/signatures/arlo-camera-onSignature-phone-side.sig";
93 //        final String offSignatureFile = path + "/training/arlo-camera/signatures/arlo-camera-offSignature-phone-side.sig";
94
95         // Amazon Alexa experiment
96 //        final String inputPcapFile = path + "/training/amazon-alexa/wlan1/alexa2.wlan1.local.pcap";
97 //        // TP-Link Plug DEVICE signatures
98 //        final String onSignatureFile = path + "/training/amazon-alexa/signatures/amazon-alexa-onSignature-device-side.sig";
99 //        final String offSignatureFile = path + "/training/amazon-alexa/signatures/amazon-alexa-offSignature-device-side.sig";
100
101         // SmartThings Plug experiment
102 //        final String inputPcapFile = path + "/training/st-plug/wlan1/st-plug.wlan1.local.pcap";
103         // TP-Link Plug DEVICE signatures
104         //final String onSignatureFile = path + "/training/st-plug/signatures/st-plug-onSignature-device-side.sig";
105         //final String offSignatureFile = path + "/training/st-plug/signatures/st-plug-offSignature-device-side.sig";
106         // TP-Link Plug PHONE signatures
107 //        final String onSignatureFile = path + "/training/st-plug/signatures/st-plug-onSignature-phone-side.sig";
108 //        final String offSignatureFile = path + "/training/st-plug/signatures/st-plug-offSignature-phone-side.sig";
109
110
111         // LiFX Bulb experiment
112 //        final String inputPcapFile = path + "/training/lifx-bulb/wlan1/lifx-bulb.wlan1.local.pcap";
113 //        // LiFX Bulb DEVICE signatures
114 //        final String onSignatureFile = path + "/training/lifx-bulb/signatures/lifx-bulb-onSignature-device-side.sig";
115 //        final String offSignatureFile = path + "/training/lifx-bulb/signatures/lifx-bulb-offSignature-device-side.sig";
116         // LiFX Bulb PHONE signatures
117 //        final String onSignatureFile = path + "/training/lifx-bulb/signatures/lifx-bulb-onSignature-phone-side.sig";
118 //        final String offSignatureFile = path + "/training/lifx-bulb/signatures/lifx-bulb-offSignature-phone-side.sig";
119
120
121         /*
122         // Blossom Sprinkler experiment
123         //final String inputPcapFile = path + "/training/blossom-sprinkler/wlan1/blossom-sprinkler.wlan1.local.pcap";
124         final String inputPcapFile = path + "/training/blossom-sprinkler/eth0/blossom-sprinkler.eth0.local.pcap";
125         // Blossom Sprinkler DEVICE signatures
126         final String onSignatureFile = path + "/training/blossom-sprinkler/signatures/blossom-sprinkler-onSignature-device-side.sig";
127         final String offSignatureFile = path + "/training/blossom-sprinkler/signatures/blossom-sprinkler-offSignature-device-side.sig";
128         */
129
130         // Nest Thermostat experiment
131         final String inputPcapFile = path + "/training/nest-thermostat/wlan1/nest-thermostat.wlan1.local.pcap";
132         // Nest Thermostat DEVICE signatures
133 //        final String onSignatureFile = path + "/training/nest-thermostat/signatures/nest-thermostat-onSignature-device-side.sig";
134 //        final String offSignatureFile = path + "/training/nest-thermostat/signatures/nest-thermostat-offSignature-device-side.sig";
135         // Nest Thermostat PHONE signatures
136         final String onSignatureFile = path + "/training/nest-thermostat/signatures/nest-thermostat-onSignature-phone-side.sig";
137         final String offSignatureFile = path + "/training/nest-thermostat/signatures/nest-thermostat-offSignature-phone-side.sig";
138
139         /*
140         // Hue Bulb experiment
141         final String inputPcapFile = path + "/training/hue-bulb/wlan1/hue-bulb.wlan1.local.pcap";
142         // Hue Bulb PHONE signatures
143         final String onSignatureFile = path + "/training/hue-bulb/signatures/hue-bulb-onSignature-phone-side.sig";
144         final String offSignatureFile = path + "/training/hue-bulb/signatures/hue-bulb-offSignature-phone-side.sig";
145         */
146
147         /*
148         // TP-Link Bulb experiment
149         final String inputPcapFile = path + "/training/tplink-bulb/wlan1/tplink-bulb.wlan1.local.pcap";
150         // TP-Link Bulb PHONE signatures
151         final String onSignatureFile = path + "/training/tplink-bulb/signatures/tplink-bulb-onSignature-phone-side.sig";
152         final String offSignatureFile = path + "/training/tplink-bulb/signatures/tplink-bulb-offSignature-phone-side.sig";
153         */
154
155         /*
156         // WeMo Plug experiment
157         final String inputPcapFile = path + "/training/wemo-plug/wlan1/wemo-plug.wlan1.local.pcap";
158         // WeMo Plug PHONE signatures
159         final String onSignatureFile = path + "/training/wemo-plug/signatures/wemo-plug-onSignature-device-side.sig";
160         final String offSignatureFile = path + "/training/wemo-plug/signatures/wemo-plug-offSignature-device-side.sig";
161         */
162
163         /*
164         // WeMo Insight Plug experiment
165         final String inputPcapFile = path + "/training/wemo-insight-plug/wlan1/wemo-insight-plug.wlan1.local.pcap";
166         // WeMo Insight Plug PHONE signatures
167         final String onSignatureFile = path + "/training/wemo-insight-plug/signatures/wemo-insight-plug-onSignature-device-side.sig";
168         final String offSignatureFile = path + "/training/wemo-insight-plug/signatures/wemo-insight-plug-offSignature-device-side.sig";
169         */
170
171
172         // Kwikset Doorlock Sep 12 experiment
173 //        final String inputPcapFile = path + "/2018-08/kwikset-doorlock/kwikset3.wlan1.local.pcap";
174 //        // Kwikset Doorlock PHONE signatures
175 //        final String onSignatureFile = path + "/2018-08/kwikset-doorlock/onSignature-Kwikset-Doorlock-phone.sig";
176 //        final String offSignatureFile = path + "/2018-08/kwikset-doorlock/offSignature-Kwikset-Doorlock-phone.sig";
177
178
179         /*
180         // D-Link Siren experiment
181         final String inputPcapFile = path + "/2018-08/dlink-siren/dlink-siren.wlan1.local.pcap";
182         // D-Link Siren DEVICE signatures
183         //final String onSignatureFile = path + "/2018-08/dlink-siren/onSignature-DLink-Siren-device.sig";
184         //final String offSignatureFile = path + "/2018-08/dlink-siren/offSignature-DLink-Siren-device.sig";
185         // D-Link Siren PHONE signatures
186         final String onSignatureFile = path + "/2018-08/dlink-siren/onSignature-DLink-Siren-phone.sig";
187         final String offSignatureFile = path + "/2018-08/dlink-siren/offSignature-DLink-Siren-phone.sig";
188         */
189
190         List<List<List<PcapPacket>>> onSignature = PrintUtils.deserializeSignatureFromFile(onSignatureFile);
191         List<List<List<PcapPacket>>> offSignature = PrintUtils.deserializeSignatureFromFile(offSignatureFile);
192
193         // LAN
194         SignatureDetector onDetector = new SignatureDetector(onSignature, null);
195         SignatureDetector offDetector = new SignatureDetector(offSignature, null);
196         // WAN
197 //        SignatureDetector onDetector = new SignatureDetector(onSignature, "128.195.205.105");
198 //        SignatureDetector offDetector = new SignatureDetector(offSignature, "128.195.205.105");
199
200         final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM).
201                 withLocale(Locale.US).withZone(ZoneId.of("America/Los_Angeles"));
202
203         // Outputs information about a detected event to std.out
204         final Consumer<UserAction> outputter = ua -> {
205             String eventDescription;
206             switch (ua.getType()) {
207                 case TOGGLE_ON:
208                     eventDescription = "ON";
209                     break;
210                 case TOGGLE_OFF:
211                     eventDescription = "OFF";
212                     break;
213                 default:
214                     throw new AssertionError("unhandled event type");
215             }
216             //String output = String.format("[ !!! %s SIGNATURE DETECTED at %s !!! ]",
217             //      eventDescription, dateTimeFormatter.format(ua.getTimestamp()));
218             String output = String.format("%s",
219                     dateTimeFormatter.format(ua.getTimestamp()));
220             System.out.println(output);
221         };
222
223         // Let's create observers that construct a UserAction representing the detected event.
224         final List<UserAction> detectedEvents = new ArrayList<>();
225         onDetector.addObserver((searched, match) -> {
226             PcapPacket firstPkt = match.get(0).get(0);
227             detectedEvents.add(new UserAction(UserAction.Type.TOGGLE_ON, firstPkt.getTimestamp()));
228         });
229         offDetector.addObserver((searched, match) -> {
230             PcapPacket firstPkt = match.get(0).get(0);
231             detectedEvents.add(new UserAction(UserAction.Type.TOGGLE_OFF, firstPkt.getTimestamp()));
232         });
233
234         PcapHandle handle;
235         try {
236             handle = Pcaps.openOffline(inputPcapFile, PcapHandle.TimestampPrecision.NANO);
237         } catch (PcapNativeException pne) {
238             handle = Pcaps.openOffline(inputPcapFile);
239         }
240         PcapHandleReader reader = new PcapHandleReader(handle, p -> true, onDetector, offDetector);
241         reader.readFromHandle();
242
243         // TODO: need a better way of triggering detection than this...
244         onDetector.mClusterMatchers.forEach(cm -> cm.performDetection());
245         offDetector.mClusterMatchers.forEach(cm -> cm.performDetection());
246
247         // Sort the list of detected events by timestamp to make it easier to compare it line-by-line with the trigger
248         // times file.
249         Collections.sort(detectedEvents, Comparator.comparing(UserAction::getTimestamp));
250
251
252         // Output the detected events
253         //detectedEvents.forEach(outputter);
254
255         // TODO: Temporary clean up until we clean the pipeline
256         List<UserAction> cleanedDetectedEvents = SignatureDetector.removeDuplicates(detectedEvents);
257         cleanedDetectedEvents.forEach(outputter);
258     }
259
260     /**
261      * The signature that this {@link SignatureDetector} is searching for.
262      */
263     private final List<List<List<PcapPacket>>> mSignature;
264
265     /**
266      * The {@link ClusterMatcher}s in charge of detecting each individual sequence of packets that together make up the
267      * the signature.
268      */
269     private final List<ClusterMatcher> mClusterMatchers;
270
271     /**
272      * For each {@code i} ({@code i >= 0 && i < pendingMatches.length}), {@code pendingMatches[i]} holds the matches
273      * found by the {@link ClusterMatcher} at {@code mClusterMatchers.get(i)} that have yet to be "consumed", i.e.,
274      * have yet to be included in a signature detected by this {@link SignatureDetector} (a signature can be encompassed
275      * of multiple packet sequences occurring shortly after one another on multiple connections).
276      */
277     private final List<List<PcapPacket>>[] pendingMatches;
278
279     /**
280      * Maps a {@link ClusterMatcher} to its corresponding index in {@link #pendingMatches}.
281      */
282     private final Map<ClusterMatcher, Integer> mClusterMatcherIds;
283
284     private final List<SignatureDetectionObserver> mObservers = new ArrayList<>();
285
286     /**
287      * Remove duplicates in {@code List} of {@code UserAction} objects. We need to clean this up for user actions
288      * that appear multiple times.
289      * TODO: This static method is probably just for temporary and we could get rid of this after we clean up
290      * TODO:    the pipeline
291      *
292      * @param listUserAction A {@link List} of {@code UserAction}.
293      *
294      */
295     public static List<UserAction> removeDuplicates(List<UserAction> listUserAction) {
296
297         // Iterate and check for duplicates (check timestamps)
298         Set<Long> epochSecondSet = new HashSet<>();
299         // Create a target list for cleaned up list
300         List<UserAction> listUserActionClean = new ArrayList<>();
301         for(UserAction userAction : listUserAction) {
302             // Don't insert if any duplicate is found
303             if(!epochSecondSet.contains(userAction.getTimestamp().getEpochSecond())) {
304                 listUserActionClean.add(userAction);
305                 epochSecondSet.add(userAction.getTimestamp().getEpochSecond());
306             }
307         }
308         return listUserActionClean;
309     }
310
311     public SignatureDetector(List<List<List<PcapPacket>>> searchedSignature, String routerWanIp) {
312         // note: doesn't protect inner lists from changes :'(
313         mSignature = Collections.unmodifiableList(searchedSignature);
314         // Generate corresponding/appropriate ClusterMatchers based on the provided signature
315         List<ClusterMatcher> clusterMatchers = new ArrayList<>();
316         for (List<List<PcapPacket>> cluster : mSignature) {
317             clusterMatchers.add(new ClusterMatcher(cluster, routerWanIp, this));
318         }
319         mClusterMatchers = Collections.unmodifiableList(clusterMatchers);
320
321         // < exploratory >
322         pendingMatches = new List[mClusterMatchers.size()];
323         for (int i = 0; i < pendingMatches.length; i++) {
324             pendingMatches[i] = new ArrayList<>();
325         }
326         Map<ClusterMatcher, Integer> clusterMatcherIds = new HashMap<>();
327         for (int i = 0; i < mClusterMatchers.size(); i++) {
328             clusterMatcherIds.put(mClusterMatchers.get(i), i);
329         }
330         mClusterMatcherIds = Collections.unmodifiableMap(clusterMatcherIds);
331     }
332
333     public void addObserver(SignatureDetectionObserver observer) {
334         mObservers.add(observer);
335     }
336
337     public boolean removeObserver(SignatureDetectionObserver observer) {
338         return mObservers.remove(observer);
339     }
340
341     @Override
342     public void gotPacket(PcapPacket packet) {
343         // simply delegate packet reception to all ClusterMatchers.
344         mClusterMatchers.forEach(cm -> cm.gotPacket(packet));
345     }
346
347     @Override
348     public void onMatch(ClusterMatcher clusterMatcher, List<PcapPacket> match) {
349         // Add the match at the corresponding index
350         pendingMatches[mClusterMatcherIds.get(clusterMatcher)].add(match);
351         checkSignatureMatch();
352     }
353
354     private void checkSignatureMatch() {
355         // << Graph-based approach using Balint's idea. >>
356         // This implementation assumes that the packets in the inner lists (the sequences) are ordered by asc timestamp.
357
358         // There cannot be a signature match until each ClusterMatcher has found a match of its respective sequence.
359         if (Arrays.stream(pendingMatches).noneMatch(l -> l.isEmpty())) {
360             // Construct the DAG
361             final SimpleDirectedWeightedGraph<Vertex, DefaultWeightedEdge> graph =
362                     new SimpleDirectedWeightedGraph<>(DefaultWeightedEdge.class);
363             // Add a vertex for each match found by all ClusterMatchers
364             // And maintain an array to keep track of what cluster matcher each vertex corresponds to
365             final List<Vertex>[] vertices = new List[pendingMatches.length];
366             for (int i = 0; i < pendingMatches.length; i++) {
367                 vertices[i] = new ArrayList<>();
368                 for (List<PcapPacket> sequence : pendingMatches[i]) {
369                     Vertex v = new Vertex(sequence);
370                     vertices[i].add(v); // retain reference for later when we are to add edges
371                     graph.addVertex(v); // add to vertex to graph
372                 }
373             }
374             // Add dummy source and sink vertices to facilitate search.
375             final Vertex source = new Vertex(null);
376             final Vertex sink = new Vertex(null);
377             graph.addVertex(source);
378             graph.addVertex(sink);
379             // The source is connected to all vertices that wrap the sequences detected by ClusterMatcher at index 0.
380             // Note: zero cost edges as this is just a dummy link to facilitate search from a common start node.
381             for (Vertex v : vertices[0]) {
382                 DefaultWeightedEdge edge = graph.addEdge(source, v);
383                 graph.setEdgeWeight(edge, 0.0);
384             }
385             // Similarly, all vertices that wrap the sequences detected by the last ClusterMatcher of the signature
386             // are connected to the sink node.
387             for (Vertex v : vertices[vertices.length-1]) {
388                 DefaultWeightedEdge edge = graph.addEdge(v, sink);
389                 graph.setEdgeWeight(edge, 0.0);
390             }
391             // Now link sequences detected by ClusterMatcher at index i to sequences detected by ClusterMatcher at index
392             // i+1 if they obey the timestamp constraint (i.e., that the latter is later in time than the former).
393             for (int i = 0; i < vertices.length; i++) {
394                 int j = i + 1;
395                 if (j < vertices.length) {
396                     for (Vertex iv : vertices[i]) {
397                         PcapPacket ivLast = iv.sequence.get(iv.sequence.size()-1);
398                         for (Vertex jv : vertices[j]) {
399                             PcapPacket jvFirst = jv.sequence.get(jv.sequence.size()-1);
400                             if (ivLast.getTimestamp().isBefore(jvFirst.getTimestamp())) {
401                                 DefaultWeightedEdge edge = graph.addEdge(iv, jv);
402                                 // The weight is the duration of the i'th sequence plus the duration between the i'th
403                                 // and i+1'th sequence.
404                                 Duration d = Duration.
405                                         between(iv.sequence.get(0).getTimestamp(), jvFirst.getTimestamp());
406                                 // Unfortunately weights are double values, so must convert from long to double.
407                                 // TODO: need nano second precision? If so, use d.toNanos().
408                                 // TODO: risk of overflow when converting from long to double..?
409                                 graph.setEdgeWeight(edge, Long.valueOf(d.toMillis()).doubleValue());
410                             }
411                             // Alternative version if we cannot assume that sequences are ordered by timestamp:
412 //                            if (iv.sequence.stream().max(Comparator.comparing(PcapPacket::getTimestamp)).get()
413 //                                    .getTimestamp().isBefore(jv.sequence.stream().min(
414 //                                            Comparator.comparing(PcapPacket::getTimestamp)).get().getTimestamp())) {
415 //
416 //                            }
417                         }
418                     }
419                 }
420             }
421             // Graph construction complete, run shortest-path to find a (potential) signature match.
422             DijkstraShortestPath<Vertex, DefaultWeightedEdge> dijkstra = new DijkstraShortestPath<>(graph);
423             GraphPath<Vertex, DefaultWeightedEdge> shortestPath = dijkstra.getPath(source, sink);
424             if (shortestPath != null) {
425                 // The total weight is the duration between the first packet of the first sequence and the last packet
426                 // of the last sequence, so we simply have to compare the weight against the timeframe that we allow
427                 // the signature to span. For now we just use the inclusion window we defined for training purposes.
428                 // Note however, that we must convert back from double to long as the weight is stored as a double in
429                 // JGraphT's API.
430                 if (((long)shortestPath.getWeight()) < TriggerTrafficExtractor.INCLUSION_WINDOW_MILLIS) {
431                     // There's a signature match!
432                     // Extract the match from the vertices
433                     List<List<PcapPacket>> signatureMatch = new ArrayList<>();
434                     for(Vertex v : shortestPath.getVertexList()) {
435                         if (v == source || v == sink) {
436                             // Skip the dummy source and sink nodes.
437                             continue;
438                         }
439                         signatureMatch.add(v.sequence);
440                         // As there is a one-to-one correspondence between vertices[] and pendingMatches[], we know that
441                         // the sequence we've "consumed" for index i of the matched signature is also at index i in
442                         // pendingMatches. We must remove it from pendingMatches so that we don't use it to construct
443                         // another signature match in a later call.
444                         pendingMatches[signatureMatch.size()-1].remove(v.sequence);
445                     }
446                     // Declare success: notify observers
447                     mObservers.forEach(obs -> obs.onSignatureDetected(mSignature,
448                             Collections.unmodifiableList(signatureMatch)));
449                 }
450             }
451         }
452     }
453
454     /**
455      * Used for registering for notifications of signatures detected by a {@link SignatureDetector}.
456      */
457     interface SignatureDetectionObserver {
458
459         /**
460          * Invoked when the {@link SignatureDetector} detects the presence of a signature in the traffic that it's
461          * examining.
462          * @param searchedSignature The signature that the {@link SignatureDetector} reporting the match is searching
463          *                          for.
464          * @param matchingTraffic The actual traffic trace that matches the searched signature.
465          */
466         void onSignatureDetected(List<List<List<PcapPacket>>> searchedSignature,
467                                  List<List<PcapPacket>> matchingTraffic);
468     }
469
470     /**
471      * Encapsulates a {@code List<PcapPacket>} so as to allow the list to be used as a vertex in a graph while avoiding
472      * the expensive {@link AbstractList#equals(Object)} calls when adding vertices to the graph.
473      * Using this wrapper makes the incurred {@code equals(Object)} calls delegate to {@link Object#equals(Object)}
474      * instead of {@link AbstractList#equals(Object)}. The net effect is a faster implementation, but the graph will not
475      * recognize two lists that contain the same items--from a value and not reference point of view--as the same
476      * vertex. However, this is fine for our purposes -- in fact restricting it to reference equality seems more
477      * appropriate.
478      */
479     private static class Vertex {
480         private final List<PcapPacket> sequence;
481         private Vertex(List<PcapPacket> wrappedSequence) {
482             sequence = wrappedSequence;
483         }
484     }
485 }