Adding new experiments for sensitivity analysis.
[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.io.TriggerTimesFileReader;
7 import edu.uci.iotproject.trafficreassembly.layer3.Conversation;
8 import edu.uci.iotproject.trafficreassembly.layer3.TcpReassembler;
9 import edu.uci.iotproject.util.PcapPacketUtils;
10 import edu.uci.iotproject.util.PrintUtils;
11 import org.apache.commons.math3.stat.clustering.Cluster;
12 import org.apache.commons.math3.stat.clustering.DBSCANClusterer;
13 import org.pcap4j.core.*;
14 import org.pcap4j.packet.namednumber.DataLinkType;
15
16 import java.io.EOFException;
17 import java.net.UnknownHostException;
18 import java.time.Duration;
19 import java.time.Instant;
20 import java.util.*;
21 import java.util.concurrent.TimeoutException;
22 import java.util.stream.Collectors;
23 import java.util.stream.Stream;
24
25 /**
26  * This is a system that reads PCAP files to compare
27  * patterns of DNS hostnames, packet sequences, and packet
28  * lengths with training data to determine certain events
29  * or actions for smart home devices.
30  *
31  * @author Janus Varmarken
32  * @author Rahmadi Trimananda (rtrimana@uci.edu)
33  * @version 0.1
34  */
35 public class Main {
36
37
38     public static void main(String[] args) throws PcapNativeException, NotOpenException, EOFException, TimeoutException, UnknownHostException {
39         // -------------------------------------------------------------------------------------------------------------
40         // ------------ # Code for extracting traffic generated by a device within x seconds of a trigger # ------------
41         // Paths to input and output files (consider supplying these as arguments instead) and IP of the device for
42         // which traffic is to be extracted:
43         String path = "/scratch/July-2018"; // Rahmadi
44 //        String path = "/Users/varmarken/temp/UCI IoT Project/experiments"; // Janus
45         boolean verbose = true;
46         final String onPairsPath = "/scratch/July-2018/on.txt";
47         final String offPairsPath = "/scratch/July-2018/off.txt";
48
49         // 1) D-Link July 26 experiment
50 //        final String inputPcapFile = path + "/2018-07/dlink/dlink.wlan1.local.pcap";
51 //        final String outputPcapFile = path + "/2018-07/dlink/dlink-processed.pcap";
52 //        final String triggerTimesFile = path + "/2018-07/dlink/dlink-july-26-2018.timestamps";
53 //        final String deviceIp = "192.168.1.199"; // .246 == phone; .199 == dlink plug?
54           // Actual training
55 //        final String inputPcapFile = path + "/2018-10/dlink-plug/dlink-plug.wlan1.local.pcap";
56 //        final String outputPcapFile = path + "/2018-10/dlink-plug/dlink-plug-processed.pcap";
57 //        final String triggerTimesFile = path + "/2018-10/dlink-plug/dlink-plug-oct-17-2018.timestamps";
58 //        final String deviceIp = "192.168.1.199"; // .246 == phone; .199 == dlink plug?
59         // TODO: EXPERIMENT - November 7, 2018
60 //        final String inputPcapFile = path + "/experimental_result/standalone/dlink-plug/wlan1/dlink-plug.wlan1.local.pcap";
61 //        final String outputPcapFile = path + "/experimental_result/standalone/dlink-plug/wlan1/dlink-plug-processed.pcap";
62 //        final String triggerTimesFile = path + "/experimental_result/standalone/dlink-plug/timestamps/dlink-plug-nov-7-2018.timestamps";
63 //        final String deviceIp = "192.168.1.199"; // .246 == phone; .199 == dlink plug?
64 ////        final String deviceIp = "192.168.1.246"; // .246 == phone; .199 == dlink plug?
65
66         // 2) TP-Link July 25 experiment
67 //        final String inputPcapFile = path + "/2018-07/tplink/tplink.wlan1.local.pcap";
68 //        final String outputPcapFile = path + "/2018-07/tplink/tplink-processed.pcap";
69 //        final String triggerTimesFile = path + "/2018-07/tplink/tplink-july-25-2018.timestamps";
70 //        final String deviceIp = "192.168.1.159";
71           // Actual training
72 //        final String inputPcapFile = path + "/2018-10/tplink-plug/tplink-plug.wlan1.local.pcap";
73 //        final String outputPcapFile = path + "/2018-10/tplink-plug/tplink-plug-processed.pcap";
74 //        final String triggerTimesFile = path + "/2018-10/tplink-plug/tplink-plug-oct-17-2018.timestamps";
75 //        final String deviceIp = "192.168.1.159"; // .246 == phone; .159 == tplink plug
76         // TODO: EXPERIMENT - November 8, 2018
77 //        final String inputPcapFile = path + "/experimental_result/standalone/tplink-plug/wlan1/tplink-plug.wlan1.local.pcap";
78 //        final String outputPcapFile = path + "/experimental_result/standalone/tplink-plug/wlan1/tplink-plug-processed.pcap";
79 //        final String triggerTimesFile = path + "/experimental_result/standalone/tplink-plug/timestamps/tplink-plug-nov-8-2018.timestamps";
80 //        final String deviceIp = "192.168.1.159"; // .246 == phone; .159 == tplink plug
81 ////        final String deviceIp = "192.168.1.246"; // .246 == phone; .159 == tplink plug
82
83         // 2b) TP-Link July 25 experiment TRUNCATED:
84         // Only contains "true local" events, i.e., before the behavior changes to remote-like behavior.
85         // Last included event is at July 25 10:38:11; file filtered to only include packets with arrival time <= 10:38:27.
86 //        final String inputPcapFile = path + "/2018-07/tplink/tplink.wlan1.local.truncated.pcap";
87 //        final String outputPcapFile = path + "/2018-07/tplink/tplink-processed.truncated.pcap";
88 //        final String triggerTimesFile = path + "/2018-07/tplink/tplink-july-25-2018.truncated.timestamps";
89 //        final String deviceIp = "192.168.1.159";
90
91         // 3) SmartThings Plug July 25 experiment
92 //        final String inputPcapFile = path + "/2018-07/stplug/stplug.wlan1.local.pcap";
93 //        final String outputPcapFile = path + "/2018-07/stplug/stplug-processed.pcap";
94 //        final String triggerTimesFile = path + "/2018-07/stplug/smartthings-july-25-2018.timestamps";
95 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .142 == SmartThings Hub (note: use eth0 capture for this!)
96         // October 18
97 //        final String inputPcapFile = path + "/2018-10/st-plug/st-plug.wlan1.local.pcap";
98 //        final String outputPcapFile = path + "/2018-10/st-plug/st-plug-processed.pcap";
99 //        final String triggerTimesFile = path + "/2018-10/st-plug/st-plug-oct-18-2018.timestamps";
100 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .142 == SmartThings Hub (note: use eth0 capture for this!)
101         // TODO: EXPERIMENT - November 12, 2018
102 //        final String inputPcapFile = path + "/experimental_result/standalone/st-plug/wlan1/st-plug.wlan1.local.pcap";
103 //        final String outputPcapFile = path + "/experimental_result/standalone/st-plug/wlan1/st-plug-processed.pcap";
104 ////        final String inputPcapFile = path + "/experimental_result/standalone/st-plug/eth1/st-plug.eth1.local.pcap";
105 ////        final String outputPcapFile = path + "/experimental_result/standalone/st-plug/eth1/st-plug-processed.pcap";
106 //        final String triggerTimesFile = path + "/experimental_result/standalone/st-plug/timestamps/st-plug-nov-12-2018.timestamps";
107 ////        final String deviceIp = "192.168.1.142"; // .246 == phone; .142 == SmartThings Hub (note: use eth0 capture for this!)
108 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .142 == SmartThings Hub (note: use eth0 capture for this!)
109
110         // 4) Wemo July 30 experiment
111 //        final String inputPcapFile = path + "/2018-07/wemo/wemo.wlan1.local.pcap";
112 //        final String outputPcapFile = path + "/2018-07/wemo/wemo-processed.pcap";
113 //        final String triggerTimesFile = path + "/2018-07/wemo/wemo-july-30-2018.timestamps";
114 //        final String deviceIp = "192.168.1.145";  // .246 == phone; .145 == WeMo
115         // TODO: EXPERIMENT - November 20, 2018
116 //        final String inputPcapFile = path + "/experimental_result/standalone/wemo-plug/wlan1/wemo-plug.wlan1.local.pcap";
117 //        final String outputPcapFile = path + "/experimental_result/standalone/wemo-plug/wlan1/wemo-plug-processed.pcap";
118 //        final String triggerTimesFile = path + "/experimental_result/standalone/wemo-plug/timestamps/wemo-plug-nov-20-2018.timestamps";
119 ////        final String deviceIp = "192.168.1.145"; // .246 == phone; .145 == WeMo
120 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .145 == WeMo
121
122         // 5) Wemo Insight July 31 experiment
123 //        final String inputPcapFile = path + "/2018-07/wemoinsight/wemoinsight.wlan1.local.pcap";
124 //        final String outputPcapFile = path + "/2018-07/wemoinsight/wemoinsight-processed.pcap";
125 //        final String triggerTimesFile = path + "/2018-07/wemoinsight/wemo-insight-july-31-2018.timestamps";
126 //        final String deviceIp = "192.168.1.135";
127         // TODO: EXPERIMENT - November 21, 2018
128 //        final String inputPcapFile = path + "/experimental_result/standalone/wemo-insight-plug/wlan1/wemo-insight-plug.wlan1.local.pcap";
129 //        final String outputPcapFile = path + "/experimental_result/standalone/wemo-insight-plug/wlan1/wemo-insight-plug-processed.pcap";
130 //        final String triggerTimesFile = path + "/experimental_result/standalone/wemo-insight-plug/timestamps/wemo-insight-plug-nov-21-2018.timestamps";
131 ////        final String deviceIp = "192.168.1.145"; // .246 == phone; .135 == WeMo Insight
132 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .135 == WeMo Insight
133
134         // 6) TP-Link Bulb August 1 experiment
135 //        final String inputPcapFile = path + "/2018-08/tplink-bulb/tplinkbulb.wlan1.local.pcap";
136 //        final String outputPcapFile = path + "/2018-08/tplink-bulb/tplinkbulb-processed.pcap";
137 //        final String triggerTimesFile = path + "/2018-08/tplink-bulb/tplink-bulb-aug-3-2018.timestamps";
138 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .140 == TP-Link bulb
139         // TODO: EXPERIMENT - November 16, 2018
140 //        final String inputPcapFile = path + "/experimental_result/standalone/tplink-bulb/wlan1/tplink-bulb.wlan1.local.pcap";
141 //        final String outputPcapFile = path + "/experimental_result/standalone/tplink-bulb/wlan1/tplink-bulb-processed.pcap";
142 ////        final String inputPcapFile = path + "/experimental_result/standalone/tplink-bulb/eth0/tplink-bulb.eth1.local.pcap";
143 ////        final String outputPcapFile = path + "/experimental_result/standalone/tplink-bulb/eth0/tplink-bulb-processed.pcap";
144 //        final String triggerTimesFile = path + "/experimental_result/standalone/tplink-bulb/timestamps/tplink-bulb-nov-16-2018.timestamps";
145 ////        final String deviceIp = "192.168.1.140"; // .246 == phone; .140 == TP-Link bulb
146 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .140 == TP-Link bulb
147
148         // 7) Kwikset Doorlock August 6 experiment
149 //        final String inputPcapFile = path + "/2018-08/kwikset-doorlock/kwikset-doorlock.data.wlan1.pcap";
150 ////        final String inputPcapFile = path + "/2018-08/kwikset-doorlock/kwikset-doorlock.wlan1.local.pcap";
151 //        final String outputPcapFile = path + "/2018-08/kwikset-doorlock/kwikset-doorlock-processed.pcap";
152 ////        final String triggerTimesFile = path + "/2018-08/kwikset-doorlock/kwikset-doorlock-aug-6-2018.timestamps";
153 //        final String triggerTimesFile = path + "/2018-08/kwikset-doorlock/kwikset-doorlock-8hr-data-oct-11-2018.timestamps";
154 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .142 == SmartThings Hub (note: use eth0 capture for this!)
155         // TODO: EXPERIMENT - November 10, 2018
156 //        final String inputPcapFile = path + "/experimental_result/standalone/kwikset-doorlock/wlan1/kwikset-doorlock.wlan1.local.pcap";
157 //        final String outputPcapFile = path + "/experimental_result/standalone/kwikset-doorlock/wlan1/kwikset-doorlock-processed.pcap";
158 ////        final String inputPcapFile = path + "/experimental_result/standalone/kwikset-doorlock/eth1/kwikset-doorlock.eth1.local.pcap";
159 ////        final String outputPcapFile = path + "/experimental_result/standalone/kwikset-doorlock/eth1/kwikset-doorlock-processed.pcap";
160 //        final String triggerTimesFile = path + "/experimental_result/standalone/kwikset-doorlock/timestamps/kwikset-doorlock-nov-10-2018.timestamps";
161 ////        final String deviceIp = "192.168.1.142"; // .246 == phone; .142 == SmartThings Hub (note: use eth0 capture for this!)
162 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .142 == SmartThings Hub (note: use eth0 capture for this!)
163
164         // September 12, 2018 - includes both wlan1 and eth1 interfaces
165 //        final String inputPcapFile = path + "/2018-08/kwikset-doorlock/kwikset3.wlan1.local.pcap";
166 //        //final String inputPcapFile = path + "/2018-08/kwikset-doorlock/kwikset3.eth1.local.pcap";
167 //        final String outputPcapFile = path + "/2018-08/kwikset-doorlock/kwikset3-processed.pcap";
168 //        final String triggerTimesFile = path + "/2018-08/kwikset-doorlock/kwikset-doorlock-sept-12-2018.timestamps";
169 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .142 == SmartThings Hub (note: use eth0 capture for this!)
170
171         // 8) Hue Bulb August 7 experiment
172 //        final String inputPcapFile = path + "/2018-08/hue-bulb/hue-bulb.wlan1.local.pcap";
173 //        final String outputPcapFile = path + "/2018-08/hue-bulb/hue-bulb-processed.pcap";
174 //        final String triggerTimesFile = path + "/2018-08/hue-bulb/hue-bulb-aug-7-2018.timestamps";
175 //        final String deviceIp = "192.168.1.246";
176         // October 30 experiment
177 //        final String inputPcapFile = path + "/2018-10/hue-bulb/hue-bulb.wlan1.local.pcap";
178 //        final String outputPcapFile = path + "/2018-10/hue-bulb/hue-bulb-processed.pcap";
179 //        final String triggerTimesFile = path + "/2018-10/hue-bulb/hue-bulb-oct-30-2018.timestamps";
180 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .100 == Hue hub
181         // TODO: EXPERIMENT - November 19, 2018
182 //        final String inputPcapFile = path + "/experimental_result/standalone/hue-bulb/wlan1/hue-bulb.wlan1.local.pcap";
183 //        final String outputPcapFile = path + "/experimental_result/standalone/hue-bulb/wlan1/hue-bulb-processed.pcap";
184 //        final String triggerTimesFile = path + "/experimental_result/standalone/hue-bulb/timestamps/hue-bulb-nov-19-2018.timestamps";
185 ////        final String deviceIp = "192.168.1.100"; // .246 == phone; .100 == Hue hub
186 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .100 == Hue hub
187
188         // 9) Lifx Bulb August 8 experiment
189 //        final String inputPcapFile = path + "/2018-08/lifx-bulb/lifx-bulb.wlan1.local.pcap";
190 //        final String outputPcapFile = path + "/2018-08/lifx-bulb/lifx-bulb-processed.pcap";
191 //        final String triggerTimesFile = path + "/2018-08/lifx-bulb/lifx-bulb-aug-8-2018.timestamps";
192 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .231 == Lifx
193         // October 18
194 //        final String inputPcapFile = path + "/2018-10/lifx-bulb/lifx-bulb.wlan1.local.pcap";
195 //        final String outputPcapFile = path + "/2018-10/lifx-bulb/lifx-bulb-processed.pcap";
196 //        final String triggerTimesFile = path + "/2018-10/lifx-bulb/lifx-bulb-oct-18-2018.timestamps";
197 //        final String deviceIp = "192.168.1.231"; // .246 == phone; .231 == Lifx
198         // November 1
199 //        final String inputPcapFile = path + "/2018-10/lifx-bulb/lifx-bulb.wlan1.local.pcap";
200 //        final String outputPcapFile = path + "/2018-10/lifx-bulb/lifx-bulb-processed.pcap";
201 //        final String triggerTimesFile = path + "/2018-10/lifx-bulb/lifx-bulb-nov-1-2018.timestamps";
202 //        final String deviceIp = "192.168.1.231"; // .246 == phone; .231 == Lifx
203
204         // 10) Amcrest Camera August 9 experiment
205 //        final String inputPcapFile = path + "/2018-08/amcrest-camera/amcrest-camera.wlan1.local.pcap";
206 //        final String outputPcapFile = path + "/2018-08/amcrest-camera/amcrest-camera-processed.pcap";
207 //        final String triggerTimesFile = path + "/2018-08/amcrest-camera/amcrest-camera-aug-9-2018.timestamps";
208 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .235 == camera
209
210         // 11) Arlo Camera August 10 experiment
211 //        final String inputPcapFile = path + "/2018-08/arlo-camera/arlo-camera.wlan1.local.pcap";
212 //        final String outputPcapFile = path + "/2018-08/arlo-camera/arlo-camera-processed.pcap";
213 //        final String triggerTimesFile = path + "/2018-08/arlo-camera/arlo-camera-aug-10-2018.timestamps";
214 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .140 == camera
215         // TODO: EXPERIMENT - November 13, 2018
216         final String inputPcapFile = path + "/experimental_result/standalone/arlo-camera/wlan1/arlo-camera.wlan1.local.pcap";
217         final String outputPcapFile = path + "/experimental_result/standalone/arlo-camera/wlan1/arlo-camera-processed.pcap";
218 //        final String inputPcapFile = path + "/experimental_result/standalone/arlo-camera/eth0/arlo-camera.eth1.local.pcap";
219 //        final String outputPcapFile = path + "/experimental_result/standalone/arlo-camera/eth0/arlo-camera-processed.pcap";
220         final String triggerTimesFile = path + "/experimental_result/standalone/arlo-camera/timestamps/arlo-camera-nov-13-2018.timestamps";
221 //        final String deviceIp = "192.168.1.140"; // .246 == phone; .140 == camera
222         final String deviceIp = "192.168.1.246"; // .246 == phone; .140 == camera
223
224         // 12) Blossom sprinkler August 13 experiment
225 //        final String inputPcapFile = path + "/2018-08/blossom/blossom.wlan1.local.pcap";
226 //        final String outputPcapFile = path + "/2018-08/blossom/blossom-processed.pcap";
227 //        final String triggerTimesFile = path + "/2018-08/blossom/blossom-aug-13-2018.timestamps";
228 //        final String deviceIp = "192.168.1.229"; // .246 == phone; .229 == sprinkler
229 //        // 2 November
230 //        final String inputPcapFile = path + "/2018-10/blossom-sprinkler/blossom-sprinkler.wlan1.local.pcap";
231 //        final String outputPcapFile = path + "/2018-10/blossom-sprinkler/blossom-sprinkler-processed.pcap";
232 //        final String triggerTimesFile = path + "/2018-10/blossom-sprinkler/blossom-sprinkler-nov-2-2018.timestamps";
233 //        final String deviceIp = "192.168.1.229"; // .246 == phone; .229 == sprinkler
234         // January 9, 11, 13, 14
235 //        final String inputPcapFile = path + "/experimental_result/standalone/blossom-sprinkler/wlan1/blossom-sprinkler.wlan1.local.pcap";
236 //        final String outputPcapFile = path + "/experimental_result/standalone/blossom-sprinkler/wlan1/blossom-sprinkler-processed.pcap";
237 //        final String triggerTimesFile = path + "/experimental_result/standalone/blossom-sprinkler/timestamps/blossom-sprinkler-standalone-jan-14-2019.timestamps";
238 ////        final String triggerTimesFile = path + "/experimental_result/standalone/blossom-sprinkler/timestamps/blossom-sprinkler-standalone-jan-11-2019.timestamps";
239 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .229 == sprinkler
240 ////        final String deviceIp = "192.168.1.229"; // .246 == phone; .229 == sprinkler
241
242 //        // 13) DLink siren August 14 experiment
243 //        final String inputPcapFile = path + "/2018-08/dlink-siren/dlink-siren.wlan1.local.pcap";
244 //        //final String inputPcapFile = path + "/evaluation/dlink-siren/dlink-siren.data.wlan1.pcap";
245 //        final String outputPcapFile = path + "/2018-08/dlink-siren/dlink-siren-processed.pcap";
246 //        final String triggerTimesFile = path + "/2018-08/dlink-siren/dlink-siren-oct-12-2018.timestamps";
247 //        //final String triggerTimesFile = path + "/2018-08/dlink-siren/dlink-siren-aug-14-2018.timestamps";
248 //        //final String triggerTimesFile = path + "/actual/timestamps/dlink-siren-8hr-data-oct-10-2018.timestamps";
249 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .183 == siren
250         // TODO: EXPERIMENT - November 9, 2018
251 //        final String inputPcapFile = path + "/experimental_result/standalone/dlink-siren/wlan1/dlink-siren.wlan1.local.pcap";
252 //        final String outputPcapFile = path + "/experimental_result/standalone/dlink-siren/wlan1/dlink-siren-processed.pcap";
253 //        final String triggerTimesFile = path + "/experimental_result/standalone/dlink-siren/timestamps/dlink-siren-nov-9-2018.timestamps";
254 ////        final String deviceIp = "192.168.1.183"; // .246 == phone; .183 == siren
255 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .183 == siren
256
257         // 14) Nest thermostat August 15 experiment
258 //        final String inputPcapFile = path + "/2018-08/nest/nest.wlan1.local.pcap";
259 //        final String outputPcapFile = path + "/2018-08/nest/nest-processed.pcap";
260 //        final String triggerTimesFile = path + "/2018-08/nest/nest-aug-15-2018.timestamps";
261 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .127 == Nest thermostat
262 //        // TODO: EXPERIMENT - November 14, 2018
263 //        final String inputPcapFile = path + "/experimental_result/standalone/nest-thermostat/wlan1/nest-thermostat.wlan1.local.pcap";
264 //        final String outputPcapFile = path + "/experimental_result/standalone/nest-thermostat/wlan1/nest-thermostat-processed.pcap";
265 ////        final String inputPcapFile = path + "/experimental_result/standalone/nest-thermostat/eth0/nest-thermostat.eth1.local.pcap";
266 ////        final String outputPcapFile = path + "/experimental_result/standalone/nest-thermostat/eth0/nest-thermostat-processed.pcap";
267 //        final String triggerTimesFile = path + "/experimental_result/standalone/nest-thermostat/timestamps/nest-thermostat-nov-15-2018.timestamps";
268 ////        final String deviceIp = "192.168.1.127"; // .246 == phone; .127 == Nest thermostat
269 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .127 == Nest thermostat
270
271         // 15) Alexa August 16 experiment
272 //        final String inputPcapFile = path + "/2018-08/alexa/alexa.wlan1.local.pcap";
273 //        final String outputPcapFile = path + "/2018-08/alexa/alexa-processed.pcap";
274 //        final String triggerTimesFile = path + "/2018-08/alexa/alexa-aug-16-2018.timestamps";
275 //        final String deviceIp = "192.168.1.225"; // .246 == phone; .225 == Alexa
276         // August 17
277 //        final String inputPcapFile = path + "/2018-08/alexa/alexa2.wlan1.local.pcap";
278 //        final String outputPcapFile = path + "/2018-08/alexa/alexa2-processed.pcap";
279 //        final String triggerTimesFile = path + "/2018-08/alexa/alexa-aug-17-2018.timestamps";
280 //        final String deviceIp = "192.168.1.225"; // .246 == phone; .225 == Alexa
281
282         // September 17
283 //        final String inputPcapFile = path + "/2018-08/noise/noise.eth1.pcap";
284 //        final String outputPcapFile = path + "/2018-08/noise/noise-processed.pcap";
285 //        final String triggerTimesFile = path + "/2018-08/noise/noise-sept-17-2018.timestamps";
286 //        final String deviceIp = "192.168.1.142"; //  .142 == SmartThings Hub; .199 == dlink plug; .183 == siren
287         // September 26 - D-Link noise
288 //        final String inputPcapFile = path + "/2018-08/noise/noise.dlink.wlan1.pcap";
289 //        final String outputPcapFile = path + "/2018-08/noise/noise-processed.pcap";
290 //        final String triggerTimesFile = path + "/2018-08/noise/dlink-noise-sept-26-2018.timestamps";
291 //        final String deviceIp = "192.168.1.183"; //  .199 == dlink plug; .183 == siren
292         // September 27 - Kwikset noise
293 //        final String inputPcapFile = path + "/2018-08/noise/noise.kwikset.eth1.pcap";
294 //        final String outputPcapFile = path + "/2018-08/noise/noise-processed.pcap";
295 //        final String triggerTimesFile = path + "/2018-08/noise/kwikset-doorlock-noise-sept-27-2018.timestamps";
296 //        final String deviceIp = "192.168.1.142"; //  .142 == SmartThings Hub;
297
298         // TODO: The below part is just for 15-second time sensitivity experiment
299         // TODO: The below part is just for 15-second time sensitivity experiment
300         // TODO: The below part is just for 15-second time sensitivity experiment
301         // D-Link plug
302 //        final String triggerTimesFile = path + "/experimental_result/standalone/dlink-plug/timestamps/dlink-plug-nov-7-2018.timestamps";
303 ////        final String onSignatureFile = path + "/experimental_result/standalone/dlink-plug/signatures/dlink-plug-onSignature-phone-side.sig";
304 ////        final String offSignatureFile = path + "/experimental_result/standalone/dlink-plug/signatures/dlink-plug-offSignature-phone-side.sig";
305 //        final String onSignatureFile = path + "/experimental_result/standalone/dlink-plug/signatures/dlink-plug-onSignature-device-side.sig";
306 //        final String offSignatureFile = path + "/experimental_result/standalone/dlink-plug/signatures/dlink-plug-offSignature-device-side.sig";
307         // TP-Link plug
308 //        final String triggerTimesFile = path + "/experimental_result/standalone/tplink-plug/timestamps/tplink-plug-nov-8-2018.timestamps";
309 ////        final String onSignatureFile = path + "/experimental_result/standalone/tplink-plug/signatures/tplink-plug-onSignature-phone-side.sig";
310 ////        final String offSignatureFile = path + "/experimental_result/standalone/tplink-plug/signatures/tplink-plug-offSignature-phone-side.sig";
311 //        final String onSignatureFile = path + "/experimental_result/standalone/tplink-plug/signatures/tplink-plug-onSignature-device-side-outbound.sig";
312 //        final String offSignatureFile = path + "/experimental_result/standalone/tplink-plug/signatures/tplink-plug-offSignature-device-side-outbound.sig";
313         // D-Link siren
314 //        final String triggerTimesFile = path + "/experimental_result/standalone/dlink-siren/timestamps/dlink-siren-nov-9-2018.timestamps";
315 //        final String onSignatureFile = path + "/experimental_result/standalone/dlink-siren/signatures/dlink-siren-onSignature-phone-side.sig";
316 //        final String offSignatureFile = path + "/experimental_result/standalone/dlink-siren/signatures/dlink-siren-offSignature-phone-side.sig";
317         // Kwikset door lock
318 //        final String triggerTimesFile = path + "/experimental_result/standalone/kwikset-doorlock/timestamps/kwikset-doorlock-nov-10-2018.timestamps";
319 //        final String onSignatureFile = path + "/experimental_result/standalone/kwikset-doorlock/signatures/kwikset-doorlock-onSignature-phone-side.sig";
320 //        final String offSignatureFile = path + "/experimental_result/standalone/kwikset-doorlock/signatures/kwikset-doorlock-offSignature-phone-side.sig";
321         // SmartThings plug
322 //        final String triggerTimesFile = path + "/experimental_result/standalone/st-plug/timestamps/st-plug-nov-12-2018.timestamps";
323 //        final String onSignatureFile = path + "/experimental_result/standalone/st-plug/signatures/st-plug-onSignature-phone-side.sig";
324 //        final String offSignatureFile = path + "/experimental_result/standalone/st-plug/signatures/st-plug-offSignature-phone-side.sig";
325         // Arlo Q
326 //        final String triggerTimesFile = path + "/experimental_result/standalone/arlo-camera/timestamps/arlo-camera-nov-13-2018.timestamps";
327 //        final String onSignatureFile = path + "/experimental_result/standalone/arlo-camera/signatures/arlo-camera-onSignature-phone-side.sig";
328 //        final String offSignatureFile = path + "/experimental_result/standalone/arlo-camera/signatures/arlo-camera-offSignature-phone-side.sig";
329         // Nest thermostat
330 //        final String triggerTimesFile = path + "/experimental_result/standalone/nest-thermostat/timestamps/nest-thermostat-nov-15-2018.timestamps";
331 //        final String onSignatureFile = path + "/experimental_result/standalone/nest-thermostat/signatures/nest-thermostat-onSignature-phone-side.sig";
332 //        final String offSignatureFile = path + "/experimental_result/standalone/nest-thermostat/signatures/nest-thermostat-offSignature-phone-side.sig";
333         // Blossom sprinkler
334 //        final String triggerTimesFile = path + "/experimental_result/standalone/blossom-sprinkler/timestamps/blossom-sprinkler-standalone-jan-14-2019.timestamps";
335 //        final String onSignatureFile = path + "/experimental_result/standalone/blossom-sprinkler/signatures/blossom-sprinkler-onSignature-device-side.sig";
336 //        final String offSignatureFile = path + "/experimental_result/standalone/blossom-sprinkler/signatures/blossom-sprinkler-offSignature-device-side.sig";
337 //        final String onSignatureFile = path + "/experimental_result/standalone/blossom-sprinkler/signatures/blossom-sprinkler-onSignature-phone-side.sig";
338 //        final String offSignatureFile = path + "/experimental_result/standalone/blossom-sprinkler/signatures/blossom-sprinkler-offSignature-phone-side.sig";
339         // TP-Link bulb
340 //        final String triggerTimesFile = path + "/experimental_result/standalone/tplink-bulb/timestamps/tplink-bulb-nov-16-2018.timestamps";
341 //        final String onSignatureFile = path + "/experimental_result/standalone/tplink-bulb/signatures/tplink-bulb-onSignature-phone-side.sig";
342 //        final String offSignatureFile = path + "/experimental_result/standalone/tplink-bulb/signatures/tplink-bulb-offSignature-phone-side.sig";
343         // Philips hue
344 //        final String triggerTimesFile = path + "/2018-08/hue-bulb/hue-bulb-aug-7-2018.timestamps";
345 //        final String onSignatureFile = path + "/training/hue-bulb/signatures/hue-bulb-onSignature-phone-side.sig";
346 //        final String offSignatureFile = path + "/training/hue-bulb/signatures/hue-bulb-offSignature-phone-side.sig";
347         // WeMo plug
348 //        final String triggerTimesFile = path + "/experimental_result/standalone/wemo-plug/timestamps/wemo-plug-nov-20-2018.timestamps";
349 //        final String onSignatureFile = path + "/experimental_result/standalone/wemo-plug/signatures/wemo-plug-onSignature-phone-side.sig";
350 //        final String offSignatureFile = path + "/experimental_result/standalone/wemo-plug/signatures/wemo-plug-offSignature-phone-side.sig";
351         // WeMo Insight plug
352 //        final String triggerTimesFile = path + "/experimental_result/standalone/wemo-insight-plug/timestamps/wemo-insight-plug-nov-21-2018.timestamps";
353 //        final String onSignatureFile = path + "/experimental_result/standalone/wemo-insight-plug/signatures/wemo-insight-plug-onSignature-phone-side.sig";
354 //        final String offSignatureFile = path + "/experimental_result/standalone/wemo-insight-plug/signatures/wemo-insight-plug-offSignature-phone-side.sig";
355
356
357 //        TriggerTimesFileReader ttfr = new TriggerTimesFileReader();
358 //        List<Instant> triggerTimes = ttfr.readTriggerTimes(triggerTimesFile, false);
359 //
360 //        System.out.println("ON signature file in use is " + onSignatureFile);
361 //        System.out.println("OFF signature file in use is " + offSignatureFile);
362 //
363 //        List<List<List<PcapPacket>>> onSignature = PrintUtils.deserializeSignatureFromFile(onSignatureFile);
364 //        List<List<List<PcapPacket>>> offSignature = PrintUtils.deserializeSignatureFromFile(offSignatureFile);
365 //
366 //        List<Instant> signatureTimestamps = new ArrayList<>();
367 //        // Load ON signature last packet's timestamp
368 //        // Get the last only
369 //        List<List<PcapPacket>> lastListOn = onSignature.get(onSignature.size()-1);
370 //        for (List<PcapPacket> list : lastListOn) {
371 //            // Get timestamp Instant from the last packet
372 //            int lastPacketIndex = list.size()-1;
373 //            signatureTimestamps.add(list.get(lastPacketIndex).getTimestamp());
374 //        }
375 //        // Load OFF signature last packet's timestamp
376 //        // Get the last only
377 //        List<List<PcapPacket>> lastListOff = offSignature.get(offSignature.size()-1);
378 //        for (List<PcapPacket> list : lastListOff) {
379 //            // Get timestamp Instant from the last packet
380 //            int lastPacketIndex = list.size()-1;
381 //            signatureTimestamps.add(list.get(lastPacketIndex).getTimestamp());
382 //        }
383 //        // Sort the timestamps
384 //        signatureTimestamps.sort((p1, p2) -> {
385 //            return p1.compareTo(p2);
386 //        });
387 //
388 //        Iterator<Instant> iterTrig = triggerTimes.iterator();
389 //        Iterator<Instant> iterSign = signatureTimestamps.iterator();
390 //        System.out.println("Trigger to Last Packet:");
391 //        while (iterTrig.hasNext() && iterSign.hasNext()) {
392 //            Instant trigInst = (Instant) iterTrig.next();
393 //            Instant signInst = (Instant) iterSign.next();
394 //            Duration dur = Duration.between(trigInst, signInst);
395 //            long duration = dur.toMillis();
396 //            // Check duration --- should be below 15 seconds
397 //            if (duration >= 0 && duration <= 15000) {
398 //                System.out.println(dur.toMillis());
399 //            } else if (duration > 15000) {
400 //                while (duration > 15000) { // that means we have to move to the next trigger
401 //                    trigInst = (Instant) iterTrig.next();
402 //                    dur = Duration.between(trigInst, signInst);
403 //                    duration = dur.toMillis();
404 //                }
405 //                System.out.println(dur.toMillis());
406 //            } else { // below 0 / negative --- that means we have to move to the next signature
407 //                while (duration < 0) { // that means we have to move to the next trigger
408 //                    signInst = (Instant) iterSign.next();
409 //                    dur = Duration.between(trigInst, signInst);
410 //                    duration = dur.toMillis();
411 //                }
412 //                System.out.println(dur.toMillis());
413 //            }
414 //        }
415 //
416 //
417 //        // ==========================================================================
418 //        List<Instant> firstSignatureTimestamps = new ArrayList<>();
419 //        List<Instant> lastSignatureTimestamps = new ArrayList<>();
420 //        List<List<PcapPacket>> firstListOnSign = onSignature.get(0);
421 //        List<List<PcapPacket>> lastListOnSign = onSignature.get(onSignature.size()-1);
422 //        // Load ON signature first and last packet's timestamps
423 //        for (List<PcapPacket> list : firstListOnSign) {
424 //            // Get timestamp Instant from the last packet
425 //            firstSignatureTimestamps.add(list.get(0).getTimestamp());
426 //        }
427 //        for (List<PcapPacket> list : lastListOnSign) {
428 //            // Get timestamp Instant from the last packet
429 //            int lastPacketIndex = list.size()-1;
430 //            lastSignatureTimestamps.add(list.get(lastPacketIndex).getTimestamp());
431 //        }
432 //
433 //        List<List<PcapPacket>> firstListOffSign = offSignature.get(0);
434 //        List<List<PcapPacket>> lastListOffSign = offSignature.get(offSignature.size()-1);
435 //        // Load OFF signature first and last packet's timestamps
436 //        for (List<PcapPacket> list : firstListOffSign) {
437 //            // Get timestamp Instant from the last packet
438 //            firstSignatureTimestamps.add(list.get(0).getTimestamp());
439 //        }
440 //        for (List<PcapPacket> list : lastListOffSign) {
441 //            // Get timestamp Instant from the last packet
442 //            int lastPacketIndex = list.size()-1;
443 //            lastSignatureTimestamps.add(list.get(lastPacketIndex).getTimestamp());
444 //        }
445 //        // Sort the timestamps
446 //        firstSignatureTimestamps.sort((p1, p2) -> {
447 //            return p1.compareTo(p2);
448 //        });
449 //        // Sort the timestamps
450 //        lastSignatureTimestamps.sort((p1, p2) -> {
451 //            return p1.compareTo(p2);
452 //        });
453 //
454 //        Iterator<Instant> iterFirst = firstSignatureTimestamps.iterator();
455 //        Iterator<Instant> iterLast = lastSignatureTimestamps.iterator();
456 //        System.out.println("First to Last Packet:");
457 //        while (iterFirst.hasNext() && iterLast.hasNext()) {
458 //            Instant firstInst = (Instant) iterFirst.next();
459 //            Instant lastInst = (Instant) iterLast.next();
460 //            Duration dur = Duration.between(firstInst, lastInst);
461 //            long duration = dur.toMillis();
462 //            // Check duration --- should be below 15 seconds
463 //            if (duration >= 0 && duration <= 15000) {
464 //                System.out.println(dur.toMillis());
465 //            } else if (duration > 15000) {
466 //                while (duration > 15000) { // that means we have to move to the next trigger
467 //                    firstInst = (Instant) iterFirst.next();
468 //                    dur = Duration.between(firstInst, lastInst);
469 //                    duration = dur.toMillis();
470 //                }
471 //                System.out.println(dur.toMillis());
472 //            } else { // below 0 / negative --- that means we have to move to the next signature
473 //                while (duration < 0) { // that means we have to move to the next trigger
474 //                    lastInst = (Instant) iterLast.next();
475 //                    dur = Duration.between(firstInst, lastInst);
476 //                    duration = dur.toMillis();
477 //                }
478 //                System.out.println(dur.toMillis());
479 //            }
480 //            if (duration > 8000) {
481 //                break;
482 //            }
483 //        }
484
485         // TODO: The above part is just for 15-second time sensitivity experiment
486         // TODO: The above part is just for 15-second time sensitivity experiment
487         // TODO: The above part is just for 15-second time sensitivity experiment
488
489
490
491
492         TriggerTimesFileReader ttfr = new TriggerTimesFileReader();
493         List<Instant> triggerTimes = ttfr.readTriggerTimes(triggerTimesFile, false);
494         // Tag each trigger with "ON" or "OFF", assuming that the first trigger is an "ON" and that they alternate.
495         List<UserAction> userActions = new ArrayList<>();
496         for (int i = 0; i < triggerTimes.size(); i++) {
497             userActions.add(new UserAction(i % 2 == 0 ? Type.TOGGLE_ON : Type.TOGGLE_OFF, triggerTimes.get(i)));
498         }
499         TriggerTrafficExtractor tte = new TriggerTrafficExtractor(inputPcapFile, triggerTimes, deviceIp);
500         final PcapDumper outputter = Pcaps.openDead(DataLinkType.EN10MB, 65536).dumpOpen(outputPcapFile);
501         DnsMap dnsMap = new DnsMap();
502         TcpReassembler tcpReassembler = new TcpReassembler();
503         TrafficLabeler trafficLabeler = new TrafficLabeler(userActions);
504         tte.performExtraction(pkt -> {
505             try {
506                 outputter.dump(pkt);
507             } catch (NotOpenException e) {
508                 e.printStackTrace();
509             }
510         }, dnsMap, tcpReassembler, trafficLabeler);
511         outputter.flush();
512         outputter.close();
513
514         if (tte.getPacketsIncludedCount() != trafficLabeler.getTotalPacketCount()) {
515             // Sanity/debug check
516             throw new AssertionError(String.format("mismatch between packet count in %s and %s",
517                     TriggerTrafficExtractor.class.getSimpleName(), TrafficLabeler.class.getSimpleName()));
518         }
519
520         // Extract all conversations present in the filtered trace.
521         List<Conversation> allConversations = tcpReassembler.getTcpConversations();
522         // Group conversations by hostname.
523         Map<String, List<Conversation>> convsByHostname = TcpConversationUtils.groupConversationsByHostname(allConversations, dnsMap);
524         System.out.println("Grouped conversations by hostname.");
525         // For each hostname, count the frequencies of packet lengths exchanged with that hostname.
526         final Map<String, Map<Integer, Integer>> pktLenFreqsByHostname = new HashMap<>();
527         convsByHostname.forEach((host, convs) -> pktLenFreqsByHostname.put(host, TcpConversationUtils.countPacketLengthFrequencies(convs)));
528         System.out.println("Counted frequencies of packet lengths exchanged with each hostname.");
529         // For each hostname, count the frequencies of packet sequences (i.e., count how many conversations exchange a
530         // sequence of packets of some specific lengths).
531         final Map<String, Map<String, Integer>> pktSeqFreqsByHostname = new HashMap<>();
532         convsByHostname.forEach((host, convs) -> pktSeqFreqsByHostname.put(host, TcpConversationUtils.countPacketSequenceFrequencies(convs)));
533         System.out.println("Counted frequencies of packet sequences exchanged with each hostname.");
534         // For each hostname, count frequencies of packet pairs exchanged with that hostname across all conversations
535         final Map<String, Map<String, Integer>> pktPairFreqsByHostname =
536                 TcpConversationUtils.countPacketPairFrequenciesByHostname(allConversations, dnsMap);
537         System.out.println("Counted frequencies of packet pairs per hostname");
538         // For each user action, reassemble the set of TCP connections occurring shortly after
539         final Map<UserAction, List<Conversation>> userActionToConversations = trafficLabeler.getLabeledReassembledTcpTraffic();
540         final Map<UserAction, Map<String, List<Conversation>>> userActionsToConvsByHostname = trafficLabeler.getLabeledReassembledTcpTraffic(dnsMap);
541         System.out.println("Reassembled TCP conversations occurring shortly after each user event");
542
543
544
545         /*
546          * NOTE: no need to generate these more complex on/off maps that also contain mappings from hostname and
547          * sequence identifiers as we do not care about hostnames and sequences during clustering.
548          * We can simply use the UserAction->List<Conversation> map to generate ON/OFF groupings of conversations.
549          */
550
551 //        // Contains all ON events: hostname -> sequence identifier -> list of conversations with that sequence
552 //        Map<String, Map<String, List<Conversation>>> ons = new HashMap<>();
553 //        // Contains all OFF events: hostname -> sequence identifier -> list of conversations with that sequence
554 //        Map<String, Map<String, List<Conversation>>> offs = new HashMap<>();
555 //        userActionsToConvsByHostname.forEach((ua, hostnameToConvs) -> {
556 //            Map<String, Map<String, List<Conversation>>> outer = ua.getType() == Type.TOGGLE_ON ? ons : offs;
557 //            hostnameToConvs.forEach((host, convs) -> {
558 //                Map<String, List<Conversation>> seqsToConvs = TcpConversationUtils.
559 //                        groupConversationsByPacketSequence(convs, verbose);
560 //                outer.merge(host, seqsToConvs, (oldMap, newMap) -> {
561 //                    newMap.forEach((sequence, cs) -> oldMap.merge(sequence, cs, (list1, list2) -> {
562 //                        list1.addAll(list2);
563 //                        return list1;
564 //                    }));
565 //                    return oldMap;
566 //                });
567 //            });
568 //        });
569 //
570 //        System.out.println("==== ON ====");
571 //        // Print out all the pairs into a file for ON events
572 //        File fileOnEvents = new File(onPairsPath);
573 //        PrintWriter pwOn = null;
574 //        try {
575 //            pwOn = new PrintWriter(fileOnEvents);
576 //        } catch(Exception ex) {
577 //            ex.printStackTrace();
578 //        }
579 //        for(Map.Entry<String, Map<String, List<Conversation>>> entry : ons.entrySet()) {
580 //            Map<String, List<Conversation>> seqsToConvs = entry.getValue();
581 //            for(Map.Entry<String, List<Conversation>> entryConv : seqsToConvs.entrySet()) {
582 //                List<Conversation> listConv = entryConv.getValue();
583 //                // Just get the first Conversation because all Conversations in this group
584 //                // should have the same pairs of Application Data.
585 //                for(Conversation conv : listConv) {
586 //                    // Process only if it is a TLS packet
587 //                    if (conv.isTls()) {
588 //                        List<PcapPacketPair> tlsAppDataList = TcpConversationUtils.extractTlsAppDataPacketPairs(conv);
589 //                        for(PcapPacketPair pair: tlsAppDataList) {
590 //                            System.out.println(PrintUtils.toCsv(pair, dnsMap));
591 //                            pwOn.println(PrintUtils.toCsv(pair, dnsMap));
592 //                        }
593 //                    } else { // Non-TLS conversations
594 //                        List<PcapPacketPair> packetList = TcpConversationUtils.extractPacketPairs(conv);
595 //                        for(PcapPacketPair pair: packetList) {
596 //                            System.out.println(PrintUtils.toCsv(pair, dnsMap));
597 //                            pwOn.println(PrintUtils.toCsv(pair, dnsMap));
598 //                        }
599 //                    }
600 //                }
601 //            }
602 //        }
603 //        pwOn.close();
604 //
605 //        System.out.println("==== OFF ====");
606 //        // Print out all the pairs into a file for ON events
607 //        File fileOffEvents = new File(offPairsPath);
608 //        PrintWriter pwOff = null;
609 //        try {
610 //            pwOff = new PrintWriter(fileOffEvents);
611 //        } catch(Exception ex) {
612 //            ex.printStackTrace();
613 //        }
614 //        for(Map.Entry<String, Map<String, List<Conversation>>> entry : offs.entrySet()) {
615 //            Map<String, List<Conversation>> seqsToConvs = entry.getValue();
616 //            for(Map.Entry<String, List<Conversation>> entryConv : seqsToConvs.entrySet()) {
617 //                List<Conversation> listConv = entryConv.getValue();
618 //                // Just get the first Conversation because all Conversations in this group
619 //                // should have the same pairs of Application Data.
620 //                for(Conversation conv : listConv) {
621 //                    // Process only if it is a TLS packet
622 //                    if (conv.isTls()) {
623 //                        List<PcapPacketPair> tlsAppDataList = TcpConversationUtils.extractTlsAppDataPacketPairs(conv);
624 //                        for(PcapPacketPair pair: tlsAppDataList) {
625 //                            System.out.println(PrintUtils.toCsv(pair, dnsMap));
626 //                            pwOff.println(PrintUtils.toCsv(pair, dnsMap));
627 //                        }
628 //                    } else { // Non-TLS conversations
629 //                        List<PcapPacketPair> packetList = TcpConversationUtils.extractPacketPairs(conv);
630 //                        for (PcapPacketPair pair : packetList) {
631 //                            System.out.println(PrintUtils.toCsv(pair, dnsMap));
632 //                            pwOff.println(PrintUtils.toCsv(pair, dnsMap));
633 //                        }
634 //                    }
635 //                }
636 //            }
637 //        }
638 //        pwOff.close();
639
640
641         // ================================================ CLUSTERING ================================================
642         // Note: no need to use the more convoluted on/off maps; can simply use the UserAction->List<Conversation> map
643         // when don't care about hostnames and sequences (see comment earlier).
644 //        List<Conversation> onConversations = userActionToConversations.entrySet().stream().
645 //                filter(e -> e.getKey().getType() == Type.TOGGLE_ON). // drop all OFF events from stream
646 //                map(e -> e.getValue()). // no longer interested in the UserActions
647 //                flatMap(List::stream). // flatten List<List<T>> to a List<T>
648 //                collect(Collectors.toList());
649 //        List<Conversation> offConversations = userActionToConversations.entrySet().stream().
650 //                filter(e -> e.getKey().getType() == Type.TOGGLE_OFF).
651 //                map(e -> e.getValue()).
652 //                flatMap(List::stream).
653 //                collect(Collectors.toList());
654 //        //Collections.sort(onConversations, (c1, c2) -> c1.getPackets().)
655 //
656 //        List<PcapPacketPair> onPairs = onConversations.stream().
657 //                map(c -> c.isTls() ? TcpConversationUtils.extractTlsAppDataPacketPairs(c) :
658 //                        TcpConversationUtils.extractPacketPairs(c)).
659 //                flatMap(List::stream). // flatten List<List<>> to List<>
660 //                collect(Collectors.toList());
661 //        List<PcapPacketPair> offPairs = offConversations.stream().
662 //                map(c -> c.isTls() ? TcpConversationUtils.extractTlsAppDataPacketPairs(c) :
663 //                        TcpConversationUtils.extractPacketPairs(c)).
664 //                flatMap(List::stream). // flatten List<List<>> to List<>
665 //                collect(Collectors.toList());
666 //        // Note: need to update the DnsMap of all PcapPacketPairs if we want to use the IP/hostname-sensitive distance.
667 //        Stream.concat(Stream.of(onPairs), Stream.of(offPairs)).flatMap(List::stream).forEach(p -> p.setDnsMap(dnsMap));
668 //        // Perform clustering on conversation logged as part of all ON events.
669 ////        DBSCANClusterer<PcapPacketPair> onClusterer = new DBSCANClusterer<>(10.0, 45);
670 //        DBSCANClusterer<PcapPacketPair> onClusterer = new DBSCANClusterer<>(2, 2);
671 //        //DBSCANClusterer<PcapPacketPair> onClusterer = new DBSCANClusterer<>(10.0, 10);
672 //        List<Cluster<PcapPacketPair>> onClusters = onClusterer.cluster(onPairs);
673 //        // Perform clustering on conversation logged as part of all OFF events.
674 ////        DBSCANClusterer<PcapPacketPair> offClusterer = new DBSCANClusterer<>(10.0, 45);
675 //        DBSCANClusterer<PcapPacketPair> offClusterer = new DBSCANClusterer<>(2, 2);
676 //        //DBSCANClusterer<PcapPacketPair> offClusterer = new DBSCANClusterer<>(10.0, 10);
677 //        List<Cluster<PcapPacketPair>> offClusters = offClusterer.cluster(offPairs);
678 //        // Sort the conversations as reference
679 //        List<Conversation> sortedAllConversation = TcpConversationUtils.sortConversationList(allConversations);
680 //        // Output clusters
681 //        System.out.println("========================================");
682 //        System.out.println("       Clustering results for ON        ");
683 //        System.out.println("       Number of clusters: " + onClusters.size());
684 //        int count = 0;
685 //        List<List<List<PcapPacket>>> ppListOfListReadOn = new ArrayList<>();
686 //        List<List<List<PcapPacket>>> ppListOfListListOn = new ArrayList<>();
687 //        for (Cluster<PcapPacketPair> c : onClusters) {
688 //            System.out.println(String.format("<<< Cluster #%02d (%03d points) >>>", ++count, c.getPoints().size()));
689 //            System.out.print(PrintUtils.toSummaryString(c));
690 //            if(c.getPoints().size() > 45 && c.getPoints().size() < 55) {
691 //            //if(c.getPoints().size() > 25) {
692 //                // Print to file
693 //                List<List<PcapPacket>> ppListOfList = PcapPacketUtils.clusterToListOfPcapPackets(c);
694 //                ppListOfListListOn.add(ppListOfList);
695 //            }
696 //        }
697 //        // TODO: Merging test
698 //        ppListOfListListOn = PcapPacketUtils.mergeSignatures(ppListOfListListOn, sortedAllConversation);
699 //        // TODO: Need to remove sequence 550 567 for Blossom phone side since it is not a good signature (overlap)!
700 ////        PcapPacketUtils.removeSequenceFromSignature(ppListOfListListOn, 1);
701 //        // TODO: Need to remove sequence 69 296 for Blossom device side since it is not a good signature (overlap)!
702 ////        PcapPacketUtils.removeSequenceFromSignature(ppListOfListListOn, 2);
703 //        // TODO: Need to remove sequence number 2 for ST plug since it is not a good signature!
704 //        //PcapPacketUtils.removeSequenceFromSignature(ppListOfListListOn, 2);
705 //        // TODO: Need to remove sequence number 0 for Arlo Camera since it is not a good signature!
706 //        //PcapPacketUtils.removeSequenceFromSignature(ppListOfListListOn, 0);
707 //        // TODO: Need to remove sequence number 0 for TP-Link plug since it is not a good signature!
708 //        // TODO: This sequence actually belongs to the local communication between the plug and the phone
709 //        //PcapPacketUtils.removeSequenceFromSignature(ppListOfListListOn, 0);
710 //        ppListOfListListOn = PcapPacketUtils.sortSignatures(ppListOfListListOn);
711 //        PcapPacketUtils.printSignatures(ppListOfListListOn);
712 //        //count = 0;
713 //        /*for (List<List<PcapPacket>> ll : ppListOfListListOn) {
714 //            PrintUtils.serializeClustersIntoFile("./onSignature" + ++count + ".sig", ll);
715 //            ppListOfListReadOn.add(PrintUtils.deserializeClustersFromFile("./onSignature" + count + ".sig"));
716 //        }*/
717 //        PrintUtils.serializeSignatureIntoFile("./onSignature.sig", ppListOfListListOn);
718 //        ppListOfListReadOn = PrintUtils.deserializeSignatureFromFile("./onSignature.sig");
719 //
720 //        System.out.println("========================================");
721 //        System.out.println("       Clustering results for OFF       ");
722 //        System.out.println("       Number of clusters: " + offClusters.size());
723 //        count = 0;
724 //        List<List<List<PcapPacket>>> ppListOfListReadOff = new ArrayList<>();
725 //        List<List<List<PcapPacket>>> ppListOfListListOff = new ArrayList<>();
726 //        for (Cluster<PcapPacketPair> c : offClusters) {
727 //            System.out.println(String.format("<<< Cluster #%03d (%06d points) >>>", ++count, c.getPoints().size()));
728 //            System.out.print(PrintUtils.toSummaryString(c));
729 //            if(c.getPoints().size() > 45 && c.getPoints().size() < 55) {
730 //            //if(c.getPoints().size() > 25) {
731 //                // Print to file
732 //                List<List<PcapPacket>> ppListOfList = PcapPacketUtils.clusterToListOfPcapPackets(c);
733 //                ppListOfListListOff.add(ppListOfList);
734 //            }
735 //        }
736 //        // TODO: Merging test
737 //        ppListOfListListOff = PcapPacketUtils.mergeSignatures(ppListOfListListOff, sortedAllConversation);
738 //        // TODO: Need to remove sequence 69 296 for Blossom device side since it is not a good signature (overlap)!
739 ////        PcapPacketUtils.removeSequenceFromSignature(ppListOfListListOff, 3);
740 //        // TODO: Need to remove sequence number 1 for Nest Thermostat since it is not a good signature!
741 //        //PcapPacketUtils.removeSequenceFromSignature(ppListOfListListOff, 1);
742 //        // TODO: Need to remove sequence number 0 for Arlo Camera since it is not a good signature!
743 ////        PcapPacketUtils.removeSequenceFromSignature(ppListOfListListOff, 1);
744 //        // TODO: Need to remove sequence number 2 for ST plug since it is not a good signature!
745 //        //PcapPacketUtils.removeSequenceFromSignature(ppListOfListListOff, 2);
746 //        // TODO: Need to remove sequence number 0 for TP-Link plug since it is not a good signature!
747 //        // TODO: This sequence actually belongs to the local communication between the plug and the phone
748 //        //PcapPacketUtils.removeSequenceFromSignature(ppListOfListListOff, 0);
749 //        ppListOfListListOff = PcapPacketUtils.sortSignatures(ppListOfListListOff);
750 //        PcapPacketUtils.printSignatures(ppListOfListListOff);
751 //        //count = 0;
752 //        /*for (List<List<PcapPacket>> ll : ppListOfListListOff) {
753 //            PrintUtils.serializeClustersIntoFile("./offSignature" + ++count + ".sig", ll);
754 //            ppListOfListReadOff.add(PrintUtils.deserializeClustersFromFile("./offSignature" + count + ".sig"));
755 //        }*/
756 //        PrintUtils.serializeSignatureIntoFile("./offSignature.sig", ppListOfListListOff);
757 //        ppListOfListReadOff = PrintUtils.deserializeSignatureFromFile("./offSignature.sig");
758 //        System.out.println("========================================");
759         // ============================================================================================================
760
761         // TODO: This part is just for DBSCAN sensitivity experiment
762         // TODO: This part is just for DBSCAN sensitivity experiment
763         // TODO: This part is just for DBSCAN sensitivity experiment
764         // TODO: This part is just for DBSCAN sensitivity experiment
765         // TODO: This part is just for DBSCAN sensitivity experiment
766         List<Conversation> onConversations = userActionToConversations.entrySet().stream().
767                 filter(e -> e.getKey().getType() == Type.TOGGLE_ON). // drop all OFF events from stream
768                 map(e -> e.getValue()). // no longer interested in the UserActions
769                 flatMap(List::stream). // flatten List<List<T>> to a List<T>
770                 collect(Collectors.toList());
771         List<Conversation> offConversations = userActionToConversations.entrySet().stream().
772                 filter(e -> e.getKey().getType() == Type.TOGGLE_OFF).
773                 map(e -> e.getValue()).
774                 flatMap(List::stream).
775                 collect(Collectors.toList());
776         //Collections.sort(onConversations, (c1, c2) -> c1.getPackets().)
777
778         List<PcapPacketPair> onPairs = onConversations.stream().
779                 map(c -> c.isTls() ? TcpConversationUtils.extractTlsAppDataPacketPairs(c) :
780                         TcpConversationUtils.extractPacketPairs(c)).
781                 flatMap(List::stream). // flatten List<List<>> to List<>
782                 collect(Collectors.toList());
783         List<PcapPacketPair> offPairs = offConversations.stream().
784                 map(c -> c.isTls() ? TcpConversationUtils.extractTlsAppDataPacketPairs(c) :
785                         TcpConversationUtils.extractPacketPairs(c)).
786                 flatMap(List::stream). // flatten List<List<>> to List<>
787                 collect(Collectors.toList());
788         // Note: need to update the DnsMap of all PcapPacketPairs if we want to use the IP/hostname-sensitive distance.
789         Stream.concat(Stream.of(onPairs), Stream.of(offPairs)).flatMap(List::stream).forEach(p -> p.setDnsMap(dnsMap));
790
791         double eps = 10; // loop from eps 1-10
792         int minPts = 50; // loop from minPts 30-50
793         for(int epsCount = 7; epsCount <= eps; epsCount++) {
794             for(int minPtsCount = 30; minPtsCount <= minPts; minPtsCount++) {
795                 System.out.println("Eps: " + epsCount + " --- minPts: " + minPtsCount);
796                 DBSCANClusterer<PcapPacketPair> onClusterer = new DBSCANClusterer<>(epsCount, minPtsCount);
797                 DBSCANClusterer<PcapPacketPair> offClusterer = new DBSCANClusterer<>(epsCount, minPtsCount);
798                 List<Cluster<PcapPacketPair>> onClusters = onClusterer.cluster(onPairs);
799                 List<Cluster<PcapPacketPair>> offClusters = offClusterer.cluster(offPairs);
800                 // Sort the conversations as reference
801                 List<Conversation> sortedAllConversation = TcpConversationUtils.sortConversationList(allConversations);
802                 // Output clusters
803                 System.out.println("========================================");
804                 System.out.println("       Clustering results for ON        ");
805                 System.out.println("       Number of clusters: " + onClusters.size());
806                 int count = 0;
807                 List<List<List<PcapPacket>>> ppListOfListListOn = new ArrayList<>();
808                 for (Cluster<PcapPacketPair> c : onClusters) {
809                     System.out.println(String.format("<<< Cluster #%02d (%03d points) >>>", ++count, c.getPoints().size()));
810 //                    System.out.print(PrintUtils.toSummaryString(c));
811                     if (c.getPoints().size() > 45 && c.getPoints().size() < 55) {
812 //                        if(c.getPoints().size() > 25) {
813                         // Print to file
814                         List<List<PcapPacket>> ppListOfList = PcapPacketUtils.clusterToListOfPcapPackets(c);
815                         ppListOfListListOn.add(ppListOfList);
816                     }
817                 }
818                 PcapPacketUtils.printSignatures(ppListOfListListOn);
819
820                 System.out.println("========================================");
821                 System.out.println("       Clustering results for OFF       ");
822                 System.out.println("       Number of clusters: " + offClusters.size());
823                 count = 0;
824                 List<List<List<PcapPacket>>> ppListOfListListOff = new ArrayList<>();
825                 for (Cluster<PcapPacketPair> c : offClusters) {
826                     System.out.println(String.format("<<< Cluster #%03d (%06d points) >>>", ++count, c.getPoints().size()));
827 //                    System.out.print(PrintUtils.toSummaryString(c));
828                     if (c.getPoints().size() > 45 && c.getPoints().size() < 55) {
829                         //if(c.getPoints().size() > 25) {
830                         // Print to file
831                         List<List<PcapPacket>> ppListOfList = PcapPacketUtils.clusterToListOfPcapPackets(c);
832                         ppListOfListListOff.add(ppListOfList);
833                     }
834                 }
835                 PcapPacketUtils.printSignatures(ppListOfListListOff);
836                 System.out.println();
837                 System.out.println();
838                 System.out.println();
839                 // ============================================================================================================
840             }
841         }
842
843
844 //        // ================================================================================================
845 //        // <<< Some work-in-progress/explorative code that extracts a "representative" sequence >>>
846 //        //
847 //        // Currently need to know relevant hostname in advance :(
848 //        String hostname = "events.tplinkra.com";
849 ////        String hostname = "rfe-us-west-1.dch.dlink.com";
850 //        // Conversations with 'hostname' for ON events.
851 //        List<Conversation> onsForHostname = new ArrayList<>();
852 //        // Conversations with 'hostname' for OFF events.
853 //        List<Conversation> offsForHostname = new ArrayList<>();
854 //        // "Unwrap" sequence groupings in ons/offs maps.
855 //        ons.get(hostname).forEach((k,v) -> onsForHostname.addAll(v));
856 //        offs.get(hostname).forEach((k,v) -> offsForHostname.addAll(v));
857 //
858 //
859 //        Map<String, List<Conversation>> onsForHostnameGroupedByTlsAppDataSequence = TcpConversationUtils.groupConversationsByTlsApplicationDataPacketSequence(onsForHostname);
860 //
861 //
862 //        // Extract representative sequence for ON and OFF by providing the list of conversations with
863 //        // 'hostname' observed for each event type (the training data).
864 //        SequenceExtraction seqExtraction = new SequenceExtraction();
865 ////        ExtractedSequence extractedSequenceForOn = seqExtraction.extract(onsForHostname);
866 ////        ExtractedSequence extractedSequenceForOff = seqExtraction.extract(offsForHostname);
867 //
868 //        ExtractedSequence extractedSequenceForOn = seqExtraction.extractByTlsAppData(onsForHostname);
869 //        ExtractedSequence extractedSequenceForOff = seqExtraction.extractByTlsAppData(offsForHostname);
870 //
871 //        // Let's check how many ONs align with OFFs and vice versa (that is, how many times an event is incorrectly
872 //        // labeled).
873 //        int onsLabeledAsOff = 0;
874 //        Integer[] representativeOnSeq = TcpConversationUtils.getPacketLengthSequence(extractedSequenceForOn.getRepresentativeSequence());
875 //        Integer[] representativeOffSeq = TcpConversationUtils.getPacketLengthSequence(extractedSequenceForOff.getRepresentativeSequence());
876 //        SequenceAlignment<Integer> seqAlg = seqExtraction.getAlignmentAlgorithm();
877 //        for (Conversation c : onsForHostname) {
878 //            Integer[] onSeq = TcpConversationUtils.getPacketLengthSequence(c);
879 //            if (seqAlg.calculateAlignment(representativeOffSeq, onSeq) <= extractedSequenceForOff.getMaxAlignmentCost()) {
880 //                onsLabeledAsOff++;
881 //            }
882 //        }
883 //        int offsLabeledAsOn = 0;
884 //        for (Conversation c : offsForHostname) {
885 //            Integer[] offSeq = TcpConversationUtils.getPacketLengthSequence(c);
886 //            if (seqAlg.calculateAlignment(representativeOnSeq, offSeq) <= extractedSequenceForOn.getMaxAlignmentCost()) {
887 //                offsLabeledAsOn++;
888 //            }
889 //        }
890 //        System.out.println("");
891 //        // ================================================================================================
892 //
893 //
894 //        // -------------------------------------------------------------------------------------------------------------
895 //        // -------------------------------------------------------------------------------------------------------------
896     }
897
898 }
899
900
901 // TP-Link MAC 50:c7:bf:33:1f:09 and usually IP 192.168.1.159 (remember to verify per file)
902 // frame.len >= 556 && frame.len <= 558 && ip.addr == 192.168.1.159