-
Notifications
You must be signed in to change notification settings - Fork 137
Expand file tree
/
Copy pathNETCommunications.java
More file actions
406 lines (344 loc) · 14.2 KB
/
Copy pathNETCommunications.java
File metadata and controls
406 lines (344 loc) · 14.2 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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
/*
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.CancellableRunnable;
import nsusbloader.ModelControllers.ILogPrinter;
import nsusbloader.NSLDataTypes.EFileStatus;
import nsusbloader.ModelControllers.Log;
import nsusbloader.NSLDataTypes.EModule;
import nsusbloader.NSLDataTypes.EMsgType;
import nsusbloader.com.helpers.NSSplitReader;
import java.io.*;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.*;
public class NETCommunications extends CancellableRunnable {
private final ILogPrinter logPrinter;
private final String switchIP;
private final static int SWITCH_PORT = 2000;
private final String hostIP;
private final int hostPort;
private final String extras;
private final boolean doNotServe;
private final HashMap<String, UniFile> files;
private final ServerSocket serverSocket;
private Socket clientSocket;
private final boolean isValid;
private OutputStream currSockOS;
private PrintWriter currSockPW;
private boolean jobInProgress = true;
/**
* Simple constructor that everybody uses
* */
public NETCommunications(List<File> filesList,
String switchIP,
boolean doNotServe,
String hostIP,
String hostPortNum,
String extras)
{
this.doNotServe = doNotServe;
if (doNotServe)
this.extras = extras;
else
this.extras = "";
this.switchIP = switchIP;
this.logPrinter = Log.getPrinter(EModule.USB_NET_TRANSFERS);
NetworkSetupValidator validator =
new NetworkSetupValidator(filesList, doNotServe, hostIP, hostPortNum, switchIP, logPrinter);
this.hostIP = validator.getHostIP();
this.hostPort = validator.getHostPort();
this.files = validator.getFiles();
this.serverSocket = validator.getServerSocket();
this.isValid = validator.isValid();
if (! isValid)
close(EFileStatus.FAILED);
}
@Override
public void run() {
if (! isValid || isCancelled() )
return;
print("\tStart chain", EMsgType.INFO);
final String handshakeContent = buildHandshakeContent();
byte[] handshakeCommand = handshakeContent.getBytes(StandardCharsets.UTF_8);
byte[] handshakeCommandSize = ByteBuffer.allocate(Integer.BYTES).putInt(handshakeCommand.length).array();
if (sendHandshake(handshakeCommandSize, handshakeCommand))
return;
// Check if we should serve requests
if (this.doNotServe){
print("List of files transferred. Replies won't be served.", EMsgType.PASS);
close(EFileStatus.UNKNOWN);
return;
}
print("Initiation files list has been sent to NS.", EMsgType.PASS);
// Go transfer
serveRequestsLoop();
}
/**
* Create string that we'll send to TF/AW and which initiates chain
* */
private String buildHandshakeContent(){
StringBuilder builder = new StringBuilder();
for (String fileNameEncoded : files.keySet()) {
builder.append(hostIP);
builder.append(':');
builder.append(hostPort);
builder.append('/');
builder.append(extras);
builder.append(fileNameEncoded);
builder.append('\n');
}
return builder.toString();
}
private boolean sendHandshake(byte[] handshakeCommandSize, byte[] handshakeCommand){
try {
Socket handshakeSocket = new Socket(InetAddress.getByName(switchIP), SWITCH_PORT);
OutputStream os = handshakeSocket.getOutputStream();
os.write(handshakeCommandSize);
os.write(handshakeCommand);
os.flush();
handshakeSocket.close();
}
catch (IOException uhe){
print("Unable to connect to NS and send files list:\n "
+ uhe.getMessage(), EMsgType.FAIL);
close(EFileStatus.UNKNOWN);
return true;
}
return false;
}
private void serveRequestsLoop(){
try {
while (jobInProgress){
clientSocket = serverSocket.accept();
BufferedReader br = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream())
);
currSockOS = clientSocket.getOutputStream();
currSockPW = new PrintWriter(new OutputStreamWriter(currSockOS));
String line;
LinkedList<String> tcpPacket = new LinkedList<>();
while ((line = br.readLine()) != null) {
if (line.trim().isEmpty()) { // If TCP packet is ended
handleRequest(tcpPacket); // Proceed required things
tcpPacket.clear(); // Clear data and wait for next TCP packet
}
else
tcpPacket.add(line); // Otherwise collect data
}
clientSocket.close();
}
}
catch (Exception e){
if (isCancelled())
print("Interrupted by user.", EMsgType.INFO);
else
print(e.getMessage(), EMsgType.INFO);
close(EFileStatus.UNKNOWN);
return;
}
print("All transfers complete", EMsgType.PASS);
close(EFileStatus.UPLOADED);
}
/**
* Handle requests
* @return true if failed
* */
private void handleRequest(LinkedList<String> packet) throws Exception{
if (packet.get(0).startsWith("DROP")){
jobInProgress = false;
return;
}
File requestedFile;
String reqFileName = packet.get(0).replaceAll("(^[A-z\\s]+/)|(\\s+?.*$)", "");
if (! files.containsKey(reqFileName)){
writeToSocket(NETPacket.getCode404());
print("File "+reqFileName+" doesn't exists or have 0 size. Returning 404", EMsgType.FAIL);
return;
}
long reqFileSize = files.get(reqFileName).getSize();
requestedFile = files.get(reqFileName).getFile();
if (! requestedFile.exists() || reqFileSize == 0){ // well.. tell 404 if file exists with 0 length is against standard, but saves time
writeToSocket(NETPacket.getCode404());
print("File "+requestedFile.getName()+" doesn't exists or have 0 size. Returning 404", EMsgType.FAIL);
logPrinter.update(requestedFile, EFileStatus.FAILED);
return;
}
if (packet.get(0).startsWith("HEAD")){
writeToSocket(NETPacket.getCode200(reqFileSize));
print("Replying for requested file: "+requestedFile.getName(), EMsgType.INFO);
return;
}
if (packet.get(0).startsWith("GET")) {
for (String line: packet) {
if (line.toLowerCase().startsWith("range")){
parseGETrange(requestedFile, reqFileName, reqFileSize, line);
return;
}
}
}
}
private void parseGETrange(File file, String fileName, long fileSize, String rangeDirective) throws Exception{
try {
String[] rangeStr = rangeDirective.toLowerCase().replaceAll("^range:\\s+?bytes=", "").split("-", 2);
if (! rangeStr[0].isEmpty() && ! rangeStr[1].isEmpty()) { // If both ranges defined: Read requested
long fromRange = Long.parseLong(rangeStr[0]);
long toRange = Long.parseLong(rangeStr[1]);
if (fromRange > toRange){ // If start bytes greater then end bytes
writeToSocket(NETPacket.getCode400());
print("Requested range for "
+ file.getName()
+ " is incorrect. Returning 400", EMsgType.FAIL);
logPrinter.update(file, EFileStatus.FAILED);
return;
}
writeToSocket(fileName, fromRange, toRange);
return;
}
if (! rangeStr[0].isEmpty()) { // If only START defined: Read all
writeToSocket(fileName, Long.parseLong(rangeStr[0]), fileSize);
return;
}
if (rangeStr[1].isEmpty()) { // If Range not defined: like "Range: bytes=-"
writeToSocket(NETPacket.getCode400());
print("Requested range for "
+ file.getName()
+ " is incorrect (empty start & end). Returning 400", EMsgType.FAIL);
logPrinter.update(file, EFileStatus.FAILED);
return;
}
if (fileSize > 500){
writeToSocket(fileName, fileSize - 500, fileSize);
return;
}
// If file smaller than 500 bytes
writeToSocket(NETPacket.getCode416());
print("File size requested for "
+ file.getName()
+ " while actual size of it: "
+ fileSize+". Returning 416", EMsgType.FAIL);
logPrinter.update(file, EFileStatus.FAILED);
}
catch (NumberFormatException nfe){
writeToSocket(NETPacket.getCode400());
print("Requested range for "
+ file.getName()
+ " has incorrect format. Returning 400\n\t"
+ nfe.getMessage(), EMsgType.FAIL);
logPrinter.update(file, EFileStatus.FAILED);
}
}
private void writeToSocket(String string) {
currSockPW.write(string);
currSockPW.flush();
}
/**
* Send files.
* */
private void writeToSocket(String fileName, long start, long end) throws Exception{
File file = files.get(fileName).getFile();
print("Reply to range: "+start+"-"+end, EMsgType.INFO);
writeToSocket(NETPacket.getCode206(files.get(fileName).getSize(), start, end));
try{
if (file.isDirectory())
handleSplitFile(file, start, end);
else
handleRegularFile(file, start, end);
logPrinter.updateProgress(1.0);
}
catch (Exception e){
logPrinter.update(file, EFileStatus.FAILED);
throw new Exception("File transmission failed:\n "+e.getMessage());
}
}
private void handleSplitFile(File file, long start, long end) throws Exception{
long count = end - start + 1;
int readPice = 1024;// NOTE: keep it small for better speed
byte[] byteBuf;
long currentOffset = 0;
NSSplitReader nsr = new NSSplitReader(file, start);
while (currentOffset < count){
if ((currentOffset + readPice) >= count){
readPice = Math.toIntExact(count - currentOffset);
}
byteBuf = new byte[readPice];
if (nsr.read(byteBuf) != readPice)
throw new IOException("File stream suddenly ended.");
currSockOS.write(byteBuf);
logPrinter.updateProgress((currentOffset+readPice)/(count/100.0) / 100.0);
currentOffset += readPice;
}
currSockOS.flush(); // TODO: check if this really needed.
nsr.close();
}
private void handleRegularFile(File file, long start, long end) throws Exception{
long count = end - start + 1;
int readPice = 1024; // NOTE: keep it small for better speed
byte[] byteBuf;
long currentOffset = 0;
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
if (bis.skip(start) != start)
throw new IOException("Unable to skip requested range.");
while (currentOffset < count){
if ((currentOffset + readPice) >= count){
readPice = Math.toIntExact(count - currentOffset);
}
byteBuf = new byte[readPice];
if (bis.read(byteBuf) != readPice){
throw new IOException("File stream suddenly ended.");
}
currSockOS.write(byteBuf);
logPrinter.updateProgress((currentOffset+readPice)/(count/100.0) / 100.0);
currentOffset += readPice;
}
currSockOS.flush(); // TODO: check if this really needed.
bis.close();
}
public ServerSocket getServerSocket(){
return serverSocket;
}
public Socket getClientSocket(){
return clientSocket;
}
/**
* Close when done
* */
private void close(EFileStatus status){
try {
if (serverSocket != null && ! serverSocket.isClosed()) {
serverSocket.close();
print("Closing server socket.", EMsgType.PASS);
}
}
catch (IOException ioe){
print("Closing server socket failed. Sometimes it's not an issue.", EMsgType.WARNING);
}
HashMap<String, File> tempMap = new HashMap<>();
for (UniFile sf : files.values())
tempMap.put(sf.getFile().getName(), sf.getFile());
logPrinter.update(tempMap, status);
print("\tEnd chain", EMsgType.INFO);
logPrinter.close();
}
private void print(String message, EMsgType type){
try {
logPrinter.print(message, type);
}
catch (InterruptedException ie){
ie.printStackTrace();
}
}
}