Adding a script to compare 2 timestamps files to validate the detection process.
[pingpong.git] / Code / Projects / SmartPlugDetector / src / main / java / edu / uci / iotproject / Main.java
1 package edu.uci.iotproject;
2
3 import static edu.uci.iotproject.analysis.UserAction.Type;
4
5 import edu.uci.iotproject.analysis.*;
6 import edu.uci.iotproject.comparison.seqalignment.ExtractedSequence;
7 import edu.uci.iotproject.comparison.seqalignment.SequenceAlignment;
8 import edu.uci.iotproject.comparison.seqalignment.SequenceExtraction;
9 import edu.uci.iotproject.io.TriggerTimesFileReader;
10 import edu.uci.iotproject.util.PcapPacketUtils;
11 import edu.uci.iotproject.util.PrintUtils;
12 import org.apache.commons.math3.stat.clustering.Cluster;
13 import org.apache.commons.math3.stat.clustering.DBSCANClusterer;
14 import org.pcap4j.core.*;
15 import org.pcap4j.packet.namednumber.DataLinkType;
16
17 import java.io.EOFException;
18 import java.io.File;
19 import java.io.PrintWriter;
20 import java.net.UnknownHostException;
21 import java.time.Instant;
22 import java.util.*;
23 import java.util.concurrent.TimeoutException;
24 import java.util.stream.Collectors;
25 import java.util.stream.Stream;
26
27 /**
28  * This is a system that reads PCAP files to compare
29  * patterns of DNS hostnames, packet sequences, and packet
30  * lengths with training data to determine certain events
31  * or actions for smart home devices.
32  *
33  * @author Janus Varmarken
34  * @author Rahmadi Trimananda (rtrimana@uci.edu)
35  * @version 0.1
36  */
37 public class Main {
38
39
40     public static void main(String[] args) throws PcapNativeException, NotOpenException, EOFException, TimeoutException, UnknownHostException {
41         // -------------------------------------------------------------------------------------------------------------
42         // ------------ # Code for extracting traffic generated by a device within x seconds of a trigger # ------------
43         // Paths to input and output files (consider supplying these as arguments instead) and IP of the device for
44         // which traffic is to be extracted:
45         String path = "/scratch/July-2018"; // Rahmadi
46 //        String path = "/Users/varmarken/temp/UCI IoT Project/experiments"; // Janus
47         boolean verbose = true;
48         final String onPairsPath = "/scratch/July-2018/on.txt";
49         final String offPairsPath = "/scratch/July-2018/off.txt";
50
51         // 1) D-Link July 26 experiment
52 //        final String inputPcapFile = path + "/2018-07/dlink/dlink.wlan1.local.pcap";
53 //        final String outputPcapFile = path + "/2018-07/dlink/dlink-processed.pcap";
54 //        final String triggerTimesFile = path + "/2018-07/dlink/dlink-july-26-2018.timestamps";
55 //        final String deviceIp = "192.168.1.199"; // .246 == phone; .199 == dlink plug?
56
57         // 2) TP-Link July 25 experiment
58 //        final String inputPcapFile = path + "/2018-07/tplink/tplink.wlan1.local.pcap";
59 //        final String outputPcapFile = path + "/2018-07/tplink/tplink-processed.pcap";
60 //        final String triggerTimesFile = path + "/2018-07/tplink/tplink-july-25-2018.timestamps";
61 //        final String deviceIp = "192.168.1.159";
62
63         // 2b) TP-Link July 25 experiment TRUNCATED:
64         // Only contains "true local" events, i.e., before the behavior changes to remote-like behavior.
65         // Last included event is at July 25 10:38:11; file filtered to only include packets with arrival time <= 10:38:27.
66 //        final String inputPcapFile = path + "/2018-07/tplink/tplink.wlan1.local.truncated.pcap";
67 //        final String outputPcapFile = path + "/2018-07/tplink/tplink-processed.truncated.pcap";
68 //        final String triggerTimesFile = path + "/2018-07/tplink/tplink-july-25-2018.truncated.timestamps";
69 //        final String deviceIp = "192.168.1.159";
70
71         // 3) SmartThings Plug July 25 experiment
72 //        final String inputPcapFile = path + "/2018-07/stplug/stplug.wlan1.local.pcap";
73 //        final String outputPcapFile = path + "/2018-07/stplug/stplug-processed.pcap";
74 //        final String triggerTimesFile = path + "/2018-07/stplug/smartthings-july-25-2018.timestamps";
75 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .142 == SmartThings Hub (note: use eth0 capture for this!)
76
77         // 4) Wemo July 30 experiment
78 //        final String inputPcapFile = path + "/2018-07/wemo/wemo.wlan1.local.pcap";
79 //        final String outputPcapFile = path + "/2018-07/wemo/wemo-processed.pcap";
80 //        final String triggerTimesFile = path + "/2018-07/wemo/wemo-july-30-2018.timestamps";
81 //        final String deviceIp = "192.168.1.145";
82
83         // 5) Wemo Insight July 31 experiment
84 //        final String inputPcapFile = path + "/2018-07/wemoinsight/wemoinsight.wlan1.local.pcap";
85 //        final String outputPcapFile = path + "/2018-07/wemoinsight/wemoinsight-processed.pcap";
86 //        final String triggerTimesFile = path + "/2018-07/wemoinsight/wemo-insight-july-31-2018.timestamps";
87 //        final String deviceIp = "192.168.1.135";
88
89         // 6) TP-Link Bulb August 1 experiment
90 //        final String inputPcapFile = path + "/2018-08/tplink-bulb/tplinkbulb.wlan1.local.pcap";
91 //        final String outputPcapFile = path + "/2018-08/tplink-bulb/tplinkbulb-processed.pcap";
92 //        final String triggerTimesFile = path + "/2018-08/tplink-bulb/tplink-bulb-aug-3-2018.timestamps";
93 //        final String deviceIp = "192.168.1.140"; // .246 == phone; .140 == TP-Link bulb
94
95         // 7) Kwikset Doorlock August 6 experiment
96 //        final String inputPcapFile = path + "/2018-08/kwikset-doorlock/kwikset-doorlock.wlan1.local.pcap";
97 //        final String outputPcapFile = path + "/2018-08/kwikset-doorlock/kwikset-doorlock-processed.pcap";
98 //        final String triggerTimesFile = path + "/2018-08/kwikset-doorlock/kwikset-doorlock-aug-6-2018.timestamps";
99 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .142 == SmartThings Hub (note: use eth0 capture for this!)
100
101         // September 12, 2018 - includes both wlan1 and eth1 interfaces
102 //        final String inputPcapFile = path + "/2018-08/kwikset-doorlock/kwikset3.wlan1.local.pcap";
103 //        //final String inputPcapFile = path + "/2018-08/kwikset-doorlock/kwikset3.eth1.local.pcap";
104 //        final String outputPcapFile = path + "/2018-08/kwikset-doorlock/kwikset3-processed.pcap";
105 //        final String triggerTimesFile = path + "/2018-08/kwikset-doorlock/kwikset-doorlock-sept-12-2018.timestamps";
106 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .142 == SmartThings Hub (note: use eth0 capture for this!)
107
108         // 8) Hue Bulb August 7 experiment
109 //        final String inputPcapFile = path + "/2018-08/hue-bulb/hue-bulb.wlan1.local.pcap";
110 //        final String outputPcapFile = path + "/2018-08/hue-bulb/hue-bulb-processed.pcap";
111 //        final String triggerTimesFile = path + "/2018-08/hue-bulb/hue-bulb-aug-7-2018.timestamps";
112 //        final String deviceIp = "192.168.1.246";
113
114         // 9) Lifx Bulb August 8 experiment
115 //        final String inputPcapFile = path + "/2018-08/lifx-bulb/lifx-bulb.wlan1.local.pcap";
116 //        final String outputPcapFile = path + "/2018-08/lifx-bulb/lifx-bulb-processed.pcap";
117 //        final String triggerTimesFile = path + "/2018-08/lifx-bulb/lifx-bulb-aug-8-2018.timestamps";
118 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .231 == Lifx
119
120         // 10) Amcrest Camera August 9 experiment
121 //        final String inputPcapFile = path + "/2018-08/amcrest-camera/amcrest-camera.wlan1.local.pcap";
122 //        final String outputPcapFile = path + "/2018-08/amcrest-camera/amcrest-camera-processed.pcap";
123 //        final String triggerTimesFile = path + "/2018-08/amcrest-camera/amcrest-camera-aug-9-2018.timestamps";
124 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .235 == camera
125
126         // 11) Arlo Camera August 10 experiment
127 //        final String inputPcapFile = path + "/2018-08/arlo-camera/arlo-camera.wlan1.local.pcap";
128 //        final String outputPcapFile = path + "/2018-08/arlo-camera/arlo-camera-processed.pcap";
129 //        final String triggerTimesFile = path + "/2018-08/arlo-camera/arlo-camera-aug-10-2018.timestamps";
130 //        final String deviceIp = "192.168.1.140"; // .246 == phone; .140 == camera
131
132         // 12) Blossom sprinkler August 13 experiment
133 //        final String inputPcapFile = path + "/2018-08/blossom/blossom.wlan1.local.pcap";
134 //        final String outputPcapFile = path + "/2018-08/blossom/blossom-processed.pcap";
135 //        final String triggerTimesFile = path + "/2018-08/blossom/blossom-aug-13-2018.timestamps";
136 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .229 == sprinkler
137
138 //        // 13) DLink siren August 14 experiment
139         final String inputPcapFile = path + "/2018-08/dlink-siren/dlink-siren.wlan1.local.pcap";
140         final String outputPcapFile = path + "/2018-08/dlink-siren/dlink-siren-processed.pcap";
141         final String triggerTimesFile = path + "/2018-08/dlink-siren/dlink-siren-aug-14-2018.timestamps";
142         final String deviceIp = "192.168.1.183"; // .246 == phone; .183 == siren
143
144         // 14) Nest thermostat August 15 experiment
145 //        final String inputPcapFile = path + "/2018-08/nest/nest.wlan1.local.pcap";
146 //        final String outputPcapFile = path + "/2018-08/nest/nest-processed.pcap";
147 //        final String triggerTimesFile = path + "/2018-08/nest/nest-aug-15-2018.timestamps";
148 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .127 == Nest thermostat
149
150         // 15) Alexa August 16 experiment
151 //        final String inputPcapFile = path + "/2018-08/alexa/alexa.wlan1.local.pcap";
152 //        final String outputPcapFile = path + "/2018-08/alexa/alexa-processed.pcap";
153 //        final String triggerTimesFile = path + "/2018-08/alexa/alexa-aug-16-2018.timestamps";
154 //        final String deviceIp = "192.168.1.225"; // .246 == phone; .225 == Alexa
155         // August 17
156 //        final String inputPcapFile = path + "/2018-08/alexa/alexa2.wlan1.local.pcap";
157 //        final String outputPcapFile = path + "/2018-08/alexa/alexa2-processed.pcap";
158 //        final String triggerTimesFile = path + "/2018-08/alexa/alexa-aug-17-2018.timestamps";
159 //        final String deviceIp = "192.168.1.225"; // .246 == phone; .225 == Alexa
160
161         // September 17
162 //        final String inputPcapFile = path + "/2018-08/noise/noise.eth1.pcap";
163 //        final String outputPcapFile = path + "/2018-08/noise/noise-processed.pcap";
164 //        final String triggerTimesFile = path + "/2018-08/noise/noise-sept-17-2018.timestamps";
165 //        final String deviceIp = "192.168.1.142"; //  .142 == SmartThings Hub; .199 == dlink plug; .183 == siren
166         // September 26 - D-Link noise
167 //        final String inputPcapFile = path + "/2018-08/noise/noise.dlink.wlan1.pcap";
168 //        final String outputPcapFile = path + "/2018-08/noise/noise-processed.pcap";
169 //        final String triggerTimesFile = path + "/2018-08/noise/dlink-noise-sept-26-2018.timestamps";
170 //        final String deviceIp = "192.168.1.183"; //  .199 == dlink plug; .183 == siren
171         // September 27 - Kwikset noise
172 //        final String inputPcapFile = path + "/2018-08/noise/noise.kwikset.eth1.pcap";
173 //        final String outputPcapFile = path + "/2018-08/noise/noise-processed.pcap";
174 //        final String triggerTimesFile = path + "/2018-08/noise/kwikset-doorlock-noise-sept-27-2018.timestamps";
175 //        final String deviceIp = "192.168.1.142"; //  .142 == SmartThings Hub;
176
177
178         TriggerTimesFileReader ttfr = new TriggerTimesFileReader();
179         List<Instant> triggerTimes = ttfr.readTriggerTimes(triggerTimesFile, false);
180         // Tag each trigger with "ON" or "OFF", assuming that the first trigger is an "ON" and that they alternate.
181         List<UserAction> userActions = new ArrayList<>();
182         for (int i = 0; i < triggerTimes.size(); i++) {
183             userActions.add(new UserAction(i % 2 == 0 ? Type.TOGGLE_ON : Type.TOGGLE_OFF, triggerTimes.get(i)));
184         }
185         TriggerTrafficExtractor tte = new TriggerTrafficExtractor(inputPcapFile, triggerTimes, deviceIp);
186         final PcapDumper outputter = Pcaps.openDead(DataLinkType.EN10MB, 65536).dumpOpen(outputPcapFile);
187         DnsMap dnsMap = new DnsMap();
188         TcpReassembler tcpReassembler = new TcpReassembler();
189         TrafficLabeler trafficLabeler = new TrafficLabeler(userActions);
190         tte.performExtraction(pkt -> {
191             try {
192                 outputter.dump(pkt);
193             } catch (NotOpenException e) {
194                 e.printStackTrace();
195             }
196         }, dnsMap, tcpReassembler, trafficLabeler);
197         outputter.flush();
198         outputter.close();
199
200         if (tte.getPacketsIncludedCount() != trafficLabeler.getTotalPacketCount()) {
201             // Sanity/debug check
202             throw new AssertionError(String.format("mismatch between packet count in %s and %s",
203                     TriggerTrafficExtractor.class.getSimpleName(), TrafficLabeler.class.getSimpleName()));
204         }
205
206         // Extract all conversations present in the filtered trace.
207         List<Conversation> allConversations = tcpReassembler.getTcpConversations();
208         // Group conversations by hostname.
209         Map<String, List<Conversation>> convsByHostname = TcpConversationUtils.groupConversationsByHostname(allConversations, dnsMap);
210         System.out.println("Grouped conversations by hostname.");
211         // For each hostname, count the frequencies of packet lengths exchanged with that hostname.
212         final Map<String, Map<Integer, Integer>> pktLenFreqsByHostname = new HashMap<>();
213         convsByHostname.forEach((host, convs) -> pktLenFreqsByHostname.put(host, TcpConversationUtils.countPacketLengthFrequencies(convs)));
214         System.out.println("Counted frequencies of packet lengths exchanged with each hostname.");
215         // For each hostname, count the frequencies of packet sequences (i.e., count how many conversations exchange a
216         // sequence of packets of some specific lengths).
217         final Map<String, Map<String, Integer>> pktSeqFreqsByHostname = new HashMap<>();
218         convsByHostname.forEach((host, convs) -> pktSeqFreqsByHostname.put(host, TcpConversationUtils.countPacketSequenceFrequencies(convs)));
219         System.out.println("Counted frequencies of packet sequences exchanged with each hostname.");
220         // For each hostname, count frequencies of packet pairs exchanged with that hostname across all conversations
221         final Map<String, Map<String, Integer>> pktPairFreqsByHostname =
222                 TcpConversationUtils.countPacketPairFrequenciesByHostname(allConversations, dnsMap);
223         System.out.println("Counted frequencies of packet pairs per hostname");
224         // For each user action, reassemble the set of TCP connections occurring shortly after
225         final Map<UserAction, List<Conversation>> userActionToConversations = trafficLabeler.getLabeledReassembledTcpTraffic();
226         final Map<UserAction, Map<String, List<Conversation>>> userActionsToConvsByHostname = trafficLabeler.getLabeledReassembledTcpTraffic(dnsMap);
227         System.out.println("Reassembled TCP conversations occurring shortly after each user event");
228
229
230
231         /*
232          * NOTE: no need to generate these more complex on/off maps that also contain mappings from hostname and
233          * sequence identifiers as we do not care about hostnames and sequences during clustering.
234          * We can simply use the UserAction->List<Conversation> map to generate ON/OFF groupings of conversations.
235          */
236         /*
237         // Contains all ON events: hostname -> sequence identifier -> list of conversations with that sequence
238         Map<String, Map<String, List<Conversation>>> ons = new HashMap<>();
239         // Contains all OFF events: hostname -> sequence identifier -> list of conversations with that sequence
240         Map<String, Map<String, List<Conversation>>> offs = new HashMap<>();
241         userActionsToConvsByHostname.forEach((ua, hostnameToConvs) -> {
242             Map<String, Map<String, List<Conversation>>> outer = ua.getType() == Type.TOGGLE_ON ? ons : offs;
243             hostnameToConvs.forEach((host, convs) -> {
244                 Map<String, List<Conversation>> seqsToConvs = TcpConversationUtils.
245                         groupConversationsByPacketSequence(convs, verbose);
246                 outer.merge(host, seqsToConvs, (oldMap, newMap) -> {
247                     newMap.forEach((sequence, cs) -> oldMap.merge(sequence, cs, (list1, list2) -> {
248                         list1.addAll(list2);
249                         return list1;
250                     }));
251                     return oldMap;
252                 });
253             });
254         });
255         */
256
257         // ================================================ CLUSTERING ================================================
258         // Note: no need to use the more convoluted on/off maps; can simply use the UserAction->List<Conversation> map
259         // when don't care about hostnames and sequences (see comment earlier).
260         List<Conversation> onConversations = userActionToConversations.entrySet().stream().
261                 filter(e -> e.getKey().getType() == Type.TOGGLE_ON). // drop all OFF events from stream
262                 map(e -> e.getValue()). // no longer interested in the UserActions
263                 flatMap(List::stream). // flatten List<List<T>> to a List<T>
264                 collect(Collectors.toList());
265         List<Conversation> offConversations = userActionToConversations.entrySet().stream().
266                 filter(e -> e.getKey().getType() == Type.TOGGLE_OFF).
267                 map(e -> e.getValue()).
268                 flatMap(List::stream).
269                 collect(Collectors.toList());
270         //Collections.sort(onConversations, (c1, c2) -> c1.getPackets().)
271
272         List<PcapPacketPair> onPairs = onConversations.stream().
273                 map(c -> c.isTls() ? TcpConversationUtils.extractTlsAppDataPacketPairs(c) :
274                         TcpConversationUtils.extractPacketPairs(c)).
275                 flatMap(List::stream). // flatten List<List<>> to List<>
276                 collect(Collectors.toList());
277         List<PcapPacketPair> offPairs = offConversations.stream().
278                 map(c -> c.isTls() ? TcpConversationUtils.extractTlsAppDataPacketPairs(c) :
279                         TcpConversationUtils.extractPacketPairs(c)).
280                 flatMap(List::stream). // flatten List<List<>> to List<>
281                 collect(Collectors.toList());
282         // Note: need to update the DnsMap of all PcapPacketPairs if we want to use the IP/hostname-sensitive distance.
283         Stream.concat(Stream.of(onPairs), Stream.of(offPairs)).flatMap(List::stream).forEach(p -> p.setDnsMap(dnsMap));
284         // Perform clustering on conversation logged as part of all ON events.
285         DBSCANClusterer<PcapPacketPair> onClusterer = new DBSCANClusterer<>(10.0, 45);
286         List<Cluster<PcapPacketPair>> onClusters = onClusterer.cluster(onPairs);
287         // Perform clustering on conversation logged as part of all OFF events.
288         DBSCANClusterer<PcapPacketPair> offClusterer = new DBSCANClusterer<>(10.0, 45);
289         List<Cluster<PcapPacketPair>> offClusters = offClusterer.cluster(offPairs);
290         // Sort the conversations as reference
291         List<Conversation> sortedAllConversation = TcpConversationUtils.sortConversationList(allConversations);
292         // Output clusters
293         System.out.println("========================================");
294         System.out.println("       Clustering results for ON        ");
295         System.out.println("       Number of clusters: " + onClusters.size());
296         int count = 0;
297         List<List<List<PcapPacket>>> ppListOfListReadOn = new ArrayList<>();
298         List<List<List<PcapPacket>>> ppListOfListListOn = new ArrayList<>();
299         for (Cluster<PcapPacketPair> c : onClusters) {
300             System.out.println(String.format("<<< Cluster #%02d (%03d points) >>>", ++count, c.getPoints().size()));
301             System.out.print(PrintUtils.toSummaryString(c));
302             if(c.getPoints().size() > 45 && c.getPoints().size() < 55) {
303                 // Print to file
304                 List<List<PcapPacket>> ppListOfList = PcapPacketUtils.clusterToListOfPcapPackets(c);
305                 ppListOfListListOn.add(ppListOfList);
306             }
307         }
308         // TODO: Merging test
309         PcapPacketUtils.mergeSignatures(ppListOfListListOn, sortedAllConversation);
310         PcapPacketUtils.sortSignatures(ppListOfListListOn);
311         count = 0;
312         /*for (List<List<PcapPacket>> ll : ppListOfListListOn) {
313             PrintUtils.serializeClustersIntoFile("./onSignature" + ++count + ".sig", ll);
314             ppListOfListReadOn.add(PrintUtils.deserializeClustersFromFile("./onSignature" + count + ".sig"));
315         }*/
316         PrintUtils.serializeSignatureIntoFile("./onSignature.sig", ppListOfListListOn);
317         ppListOfListReadOn = PrintUtils.deserializeSignatureFromFile("./onSignature.sig");
318
319         System.out.println("========================================");
320         System.out.println("       Clustering results for OFF       ");
321         System.out.println("       Number of clusters: " + offClusters.size());
322         count = 0;
323         List<List<List<PcapPacket>>> ppListOfListReadOff = new ArrayList<>();
324         List<List<List<PcapPacket>>> ppListOfListListOff = new ArrayList<>();
325         for (Cluster<PcapPacketPair> c : offClusters) {
326             System.out.println(String.format("<<< Cluster #%03d (%06d points) >>>", ++count, c.getPoints().size()));
327             System.out.print(PrintUtils.toSummaryString(c));
328             if(c.getPoints().size() > 45 && c.getPoints().size() < 55) {
329                 // Print to file
330                 List<List<PcapPacket>> ppListOfList = PcapPacketUtils.clusterToListOfPcapPackets(c);
331                 ppListOfListListOff.add(ppListOfList);
332             }
333         }
334         // TODO: Merging test
335         PcapPacketUtils.mergeSignatures(ppListOfListListOff, sortedAllConversation);
336         PcapPacketUtils.sortSignatures(ppListOfListListOff);
337         count = 0;
338         /*for (List<List<PcapPacket>> ll : ppListOfListListOff) {
339             PrintUtils.serializeClustersIntoFile("./offSignature" + ++count + ".sig", ll);
340             ppListOfListReadOff.add(PrintUtils.deserializeClustersFromFile("./offSignature" + count + ".sig"));
341         }*/
342         PrintUtils.serializeSignatureIntoFile("./offSignature.sig", ppListOfListListOff);
343         ppListOfListReadOff = PrintUtils.deserializeSignatureFromFile("./offSignature.sig");
344         System.out.println("========================================");
345         // ============================================================================================================
346
347         /*
348         System.out.println("==== ON ====");
349         // Print out all the pairs into a file for ON events
350         File fileOnEvents = new File(onPairsPath);
351         PrintWriter pwOn = null;
352         try {
353
354
355             pwOn = new PrintWriter(fileOnEvents);
356         } catch(Exception ex) {
357             ex.printStackTrace();
358         }
359         for(Map.Entry<String, Map<String, List<Conversation>>> entry : ons.entrySet()) {
360             Map<String, List<Conversation>> seqsToConvs = entry.getValue();
361             for(Map.Entry<String, List<Conversation>> entryConv : seqsToConvs.entrySet()) {
362                 List<Conversation> listConv = entryConv.getValue();
363                 // Just get the first Conversation because all Conversations in this group
364                 // should have the same pairs of Application Data.
365                 for(Conversation conv : listConv) {
366                     // Process only if it is a TLS packet
367                     if (conv.isTls()) {
368                         List<PcapPacketPair> tlsAppDataList = TcpConversationUtils.extractTlsAppDataPacketPairs(conv);
369                         for(PcapPacketPair pair: tlsAppDataList) {
370                             System.out.println(PrintUtils.toCsv(pair, dnsMap));
371                             pwOn.println(PrintUtils.toCsv(pair, dnsMap));
372                         }
373                     } else { // Non-TLS conversations
374                         List<PcapPacketPair> packetList = TcpConversationUtils.extractPacketPairs(conv);
375                         for(PcapPacketPair pair: packetList) {
376                             System.out.println(PrintUtils.toCsv(pair, dnsMap));
377                             pwOn.println(PrintUtils.toCsv(pair, dnsMap));
378                         }
379                     }
380                 }
381             }
382         }
383         pwOn.close();
384
385         System.out.println("==== OFF ====");
386         // Print out all the pairs into a file for ON events
387         File fileOffEvents = new File(offPairsPath);
388         PrintWriter pwOff = null;
389         try {
390             pwOff = new PrintWriter(fileOffEvents);
391         } catch(Exception ex) {
392             ex.printStackTrace();
393         }
394         for(Map.Entry<String, Map<String, List<Conversation>>> entry : offs.entrySet()) {
395             Map<String, List<Conversation>> seqsToConvs = entry.getValue();
396             for(Map.Entry<String, List<Conversation>> entryConv : seqsToConvs.entrySet()) {
397                 List<Conversation> listConv = entryConv.getValue();
398                 // Just get the first Conversation because all Conversations in this group
399                 // should have the same pairs of Application Data.
400                 for(Conversation conv : listConv) {
401                     // Process only if it is a TLS packet
402                     if (conv.isTls()) {
403                         List<PcapPacketPair> tlsAppDataList = TcpConversationUtils.extractTlsAppDataPacketPairs(conv);
404                         for(PcapPacketPair pair: tlsAppDataList) {
405                             System.out.println(PrintUtils.toCsv(pair, dnsMap));
406                             pwOff.println(PrintUtils.toCsv(pair, dnsMap));
407                         }
408                     } else { // Non-TLS conversations
409                         List<PcapPacketPair> packetList = TcpConversationUtils.extractPacketPairs(conv);
410                         for (PcapPacketPair pair : packetList) {
411                             System.out.println(PrintUtils.toCsv(pair, dnsMap));
412                             pwOff.println(PrintUtils.toCsv(pair, dnsMap));
413                         }
414                     }
415                 }
416             }
417         }
418         pwOff.close();
419         */
420
421 //        // ================================================================================================
422 //        // <<< Some work-in-progress/explorative code that extracts a "representative" sequence >>>
423 //        //
424 //        // Currently need to know relevant hostname in advance :(
425 //        String hostname = "events.tplinkra.com";
426 ////        String hostname = "rfe-us-west-1.dch.dlink.com";
427 //        // Conversations with 'hostname' for ON events.
428 //        List<Conversation> onsForHostname = new ArrayList<>();
429 //        // Conversations with 'hostname' for OFF events.
430 //        List<Conversation> offsForHostname = new ArrayList<>();
431 //        // "Unwrap" sequence groupings in ons/offs maps.
432 //        ons.get(hostname).forEach((k,v) -> onsForHostname.addAll(v));
433 //        offs.get(hostname).forEach((k,v) -> offsForHostname.addAll(v));
434 //
435 //
436 //        Map<String, List<Conversation>> onsForHostnameGroupedByTlsAppDataSequence = TcpConversationUtils.groupConversationsByTlsApplicationDataPacketSequence(onsForHostname);
437 //
438 //
439 //        // Extract representative sequence for ON and OFF by providing the list of conversations with
440 //        // 'hostname' observed for each event type (the training data).
441 //        SequenceExtraction seqExtraction = new SequenceExtraction();
442 ////        ExtractedSequence extractedSequenceForOn = seqExtraction.extract(onsForHostname);
443 ////        ExtractedSequence extractedSequenceForOff = seqExtraction.extract(offsForHostname);
444 //
445 //        ExtractedSequence extractedSequenceForOn = seqExtraction.extractByTlsAppData(onsForHostname);
446 //        ExtractedSequence extractedSequenceForOff = seqExtraction.extractByTlsAppData(offsForHostname);
447 //
448 //        // Let's check how many ONs align with OFFs and vice versa (that is, how many times an event is incorrectly
449 //        // labeled).
450 //        int onsLabeledAsOff = 0;
451 //        Integer[] representativeOnSeq = TcpConversationUtils.getPacketLengthSequence(extractedSequenceForOn.getRepresentativeSequence());
452 //        Integer[] representativeOffSeq = TcpConversationUtils.getPacketLengthSequence(extractedSequenceForOff.getRepresentativeSequence());
453 //        SequenceAlignment<Integer> seqAlg = seqExtraction.getAlignmentAlgorithm();
454 //        for (Conversation c : onsForHostname) {
455 //            Integer[] onSeq = TcpConversationUtils.getPacketLengthSequence(c);
456 //            if (seqAlg.calculateAlignment(representativeOffSeq, onSeq) <= extractedSequenceForOff.getMaxAlignmentCost()) {
457 //                onsLabeledAsOff++;
458 //            }
459 //        }
460 //        int offsLabeledAsOn = 0;
461 //        for (Conversation c : offsForHostname) {
462 //            Integer[] offSeq = TcpConversationUtils.getPacketLengthSequence(c);
463 //            if (seqAlg.calculateAlignment(representativeOnSeq, offSeq) <= extractedSequenceForOn.getMaxAlignmentCost()) {
464 //                offsLabeledAsOn++;
465 //            }
466 //        }
467 //        System.out.println("");
468 //        // ================================================================================================
469 //
470 //
471 //        // -------------------------------------------------------------------------------------------------------------
472 //        // -------------------------------------------------------------------------------------------------------------
473     }
474
475 }
476
477
478 // TP-Link MAC 50:c7:bf:33:1f:09 and usually IP 192.168.1.159 (remember to verify per file)
479 // frame.len >= 556 && frame.len <= 558 && ip.addr == 192.168.1.159