-
Notifications
You must be signed in to change notification settings - Fork 137
Expand file tree
/
Copy pathNetworkSetupValidator.java
More file actions
272 lines (232 loc) · 9.92 KB
/
Copy pathNetworkSetupValidator.java
File metadata and controls
272 lines (232 loc) · 9.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
/*
Copyright 2019-2020 Dmitry Isaenko
This file is part of NS-USBloader.
NS-USBloader is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
NS-USBloader is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with NS-USBloader. If not, see <https://www.gnu.org/licenses/>.
*/
package nsusbloader.com.net;
import nsusbloader.ModelControllers.ILogPrinter;
import nsusbloader.NSLDataTypes.EMsgType;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.*;
import java.util.*;
public class NetworkSetupValidator {
private String hostIP;
private int hostPort;
private final HashMap<String, UniFile> files;
private ServerSocket serverSocket;
private final boolean valid;
private final ILogPrinter logPrinter;
private final boolean doNotServe;
NetworkSetupValidator(List<File> filesList,
boolean doNotServe,
String hostIP,
String hostPortNum,
String remoteIP,
ILogPrinter logPrinter) {
this.files = new HashMap<>();
this.logPrinter = logPrinter;
this.doNotServe = doNotServe;
try {
validateFiles(filesList);
encodeAndAddFilesToMap(filesList);
resolveIp(hostIP, remoteIP);
resolvePort(hostPortNum);
}
catch (Exception e){
try {
logPrinter.print(e.getMessage(), EMsgType.FAIL);
}
catch (InterruptedException ignore){}
valid = false;
return;
}
valid = true;
}
private void validateFiles(List<File> filesList){
filesList.removeIf(this::validator);
}
private boolean validator(File f){
try {
if (f.isFile())
return false;
File[] subFiles = f.listFiles((file, name) -> name.matches("[0-9]{2}"));
if (subFiles == null || subFiles.length == 0) {
logPrinter.print("NET: Exclude folder: " + f.getName(), EMsgType.WARNING);
return true;
}
Arrays.sort(subFiles, Comparator.comparingInt(file -> Integer.parseInt(file.getName())));
for (int i = subFiles.length - 2; i > 0; i--) {
if (subFiles[i].length() != subFiles[i - 1].length()) {
logPrinter.print("NET: Exclude split file: " + f.getName() +
"\n Chunk sizes of the split file are not the same, but has to be.", EMsgType.WARNING);
return true;
}
}
long firstFileLength = subFiles[0].length();
long lastFileLength = subFiles[subFiles.length - 1].length();
if (lastFileLength > firstFileLength) {
logPrinter.print("NET: Exclude split file: " + f.getName() +
"\n Chunk sizes of the split file are not the same, but has to be.", EMsgType.WARNING);
return true;
}
return false;
}
catch (InterruptedException ie){
return false;
}
}
private void encodeAndAddFilesToMap(List<File> filesList) throws UnsupportedEncodingException, FileNotFoundException {
for (File file : filesList){
String encodedName = URLEncoder.encode(file.getName(), "UTF-8").replaceAll("\\+", "%20"); // replace '+' to '%20'
UniFile uniFile = new UniFile(file);
files.put(encodedName, uniFile);
}
if (files.size() == 0) {
throw new FileNotFoundException("NET: No files to send.");
}
}
private void resolveIp(String hostIPaddr, String remoteIP) throws IOException, InterruptedException{
if (! hostIPaddr.isEmpty()){
this.hostIP = hostIPaddr;
logPrinter.print("NET: Host IP defined as: " + hostIP, EMsgType.PASS);
return;
}
if (findIpLocally(remoteIP))
return;
if (findIpUsingHost("google.com"))
return;
if (findIpUsingHost("people.com.cn"))
return;
throw new IOException("Try using 'Expert mode' and set IP manually. " + getAvaliableIpExamples());
}
private boolean findIpUsingHost(String host) throws InterruptedException{
try {
Socket scoketK;
scoketK = new Socket();
scoketK.connect(new InetSocketAddress(host, 80));
hostIP = scoketK.getLocalAddress().getHostAddress();
scoketK.close();
logPrinter.print("NET: Host IP detected as: " + hostIP, EMsgType.PASS);
return true;
}
catch (IOException e){
logPrinter.print("NET: Can't get your computer IP using "
+ host
+ " server (InetSocketAddress). Returned:\n\t"+e.getMessage(), EMsgType.INFO);
return false;
}
}
private boolean findIpLocally(String remoteIP) throws InterruptedException{
try {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface iface = interfaces.nextElement();
if (iface.isLoopback() || !iface.isUp()) continue;
Enumeration<InetAddress> addresses = iface.getInetAddresses();
while (addresses.hasMoreElements()) {
InetAddress addr = addresses.nextElement();
if (addr instanceof Inet4Address && !addr.isLoopbackAddress()) {
// Test if this interface can reach the remote IP
if (isAddressReachable(iface, remoteIP)) {
hostIP = addr.getHostAddress();
logPrinter.print("NET: Host IP verified as: " + hostIP +
" (can reach " + remoteIP + ")", EMsgType.PASS);
return true;
}
}
}
}
}
catch (SocketException e){
logPrinter.print("NET: Error scanning local adapters: " + e.getMessage(), EMsgType.INFO);
}
return false;
}
private boolean isAddressReachable(NetworkInterface iface, String remoteIP)
{
try {
InetAddress remoteAddr = InetAddress.getByName(remoteIP);
// Test if remoteIP is reachable via this specific network interface
boolean reachable = remoteAddr.isReachable(iface, 64, 5000);
return reachable;
}
catch (Exception e) {
return false;
}
}
private String getAvaliableIpExamples(){
try {
StringBuilder builder = new StringBuilder("Check for:\n");
Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
while (enumeration.hasMoreElements()) {
NetworkInterface n = enumeration.nextElement();
Enumeration<InetAddress> enumeration1 = n.getInetAddresses();
while (enumeration1.hasMoreElements()){
builder.append("- ");
builder.append(enumeration1.nextElement().getHostAddress());
builder.append("\n");
}
}
return builder.toString();
}
catch (SocketException socketException) {
return "";
}
}
private void resolvePort(String hostPortNum) throws Exception{
if (! hostPortNum.isEmpty()) {
parsePort(hostPortNum);
return;
}
if (doNotServe)
throw new Exception("NET: Port must be defined if 'Don't serve requests' option selected!");
findPort();
}
private void findPort() throws Exception{
Random portRandomizer = new Random();
for (int i = 0; i < 5; i++) {
try {
this.hostPort = portRandomizer.nextInt(999) + 6000;
serverSocket = new ServerSocket(hostPort); //System.out.println(serverSocket.getInetAddress()); 0.0.0.0
logPrinter.print("NET: Your port detected as: " + hostPort, EMsgType.PASS);
break;
}
catch (IOException ioe) {
if (i == 4) {
throw new Exception("NET: Can't find good port\n"
+ "Set port by in settings ('Expert mode').");
}
logPrinter.print("NET: Can't use port " + hostPort + "\nLooking for another one.", EMsgType.WARNING);
}
}
}
private void parsePort(String hostPortNum) throws Exception{
try {
this.hostPort = Integer.parseInt(hostPortNum);
if (doNotServe)
return;
serverSocket = new ServerSocket(hostPort);
logPrinter.print("NET: Using defined port number: " + hostPort, EMsgType.PASS);
}
catch (IllegalArgumentException | IOException eee){
throw new Exception("NET: Can't use port defined in settings: " + hostPortNum + "\n\t"+eee.getMessage());
}
}
String getHostIP() { return hostIP; }
int getHostPort() { return hostPort; }
HashMap<String, UniFile> getFiles() { return files; }
ServerSocket getServerSocket() { return serverSocket; }
boolean isValid() { return valid; }
}