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