-
-
Notifications
You must be signed in to change notification settings - Fork 144
Expand file tree
/
Copy pathNativeScriptSyncServiceSocketImpl.java
More file actions
462 lines (389 loc) · 18.6 KB
/
Copy pathNativeScriptSyncServiceSocketImpl.java
File metadata and controls
462 lines (389 loc) · 18.6 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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
package com.tns;
import android.content.Context;
import android.net.LocalServerSocket;
import android.net.LocalSocket;
import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.io.OutputStream;
import java.util.Arrays;
public class NativeScriptSyncServiceSocketImpl {
private static String DEVICE_APP_DIR;
private final Runtime runtime;
private static Logger logger;
private final Context context;
private LocalServerSocketThread localServerThread;
private Thread localServerJavaThread;
public NativeScriptSyncServiceSocketImpl(Runtime runtime, Logger logger, Context context) {
this.runtime = runtime;
NativeScriptSyncServiceSocketImpl.logger = logger;
this.context = context;
DEVICE_APP_DIR = this.context.getFilesDir().getAbsolutePath() + "/app";
}
private class LocalServerSocketThread implements Runnable {
private volatile boolean running;
private final String name;
private LiveSyncWorker livesyncWorker;
private LocalServerSocket deviceSystemSocket;
public LocalServerSocketThread(String name) {
this.name = name;
this.running = false;
}
public void stop() {
this.running = false;
try {
deviceSystemSocket.close();
} catch (IOException e) {
if (com.tns.Runtime.isDebuggable()) {
e.printStackTrace();
}
}
}
public void run() {
running = true;
try {
deviceSystemSocket = new LocalServerSocket(this.name);
while (running) {
LocalSocket systemSocket = deviceSystemSocket.accept();
livesyncWorker = new LiveSyncWorker(systemSocket);
Thread liveSyncThread = setUpLivesyncThread();
liveSyncThread.start();
}
} catch (IOException e) {
if (com.tns.Runtime.isDebuggable()) {
e.printStackTrace();
}
}
catch (java.security.NoSuchAlgorithmException e) {
if (com.tns.Runtime.isDebuggable()) {
e.printStackTrace();
}
}
}
private Thread setUpLivesyncThread() {
Thread livesyncThread = new Thread(livesyncWorker);
livesyncThread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
logger.write(String.format("%s(%s): %s", t.getName(), t.getId(), e.toString()));
}
});
livesyncThread.setName("Livesync Thread");
return livesyncThread;
}
@Override
protected void finalize() throws Throwable {
deviceSystemSocket.close();
}
}
public void startServer() {
localServerThread = new LocalServerSocketThread(context.getPackageName() + "-livesync");
localServerJavaThread = new Thread(localServerThread);
localServerJavaThread.setName("Livesync Server Thread");
localServerJavaThread.start();
}
private class LiveSyncWorker implements Runnable {
public static final int OPERATION_BYTE_SIZE = 1;
public static final int HASH_BYTE_SIZE = 16;
public static final int LENGTH_BYTE_SIZE = 1;
public static final int OPERATION_ID_BYTE_SIZE = 32;
public static final int DELETE_FILE_OPERATION = 7;
public static final int CREATE_FILE_OPERATION = 8;
public static final int DO_SYNC_OPERATION = 9;
public static final int ERROR_REPORT_CODE = 1;
public static final int OPERATION_END_NO_REFRESH_REPORT_CODE = 3;
public static final int OPERATION_END_REPORT_CODE = 2;
public static final int REPORT_CODE_SIZE = 1;
public static final int DO_REFRESH_LENGTH = 1;
public static final int DO_REFRESH_VALUE = 1;
public static final String FILE_NAME = "fileName";
public static final String FILE_NAME_LENGTH = FILE_NAME + "Length";
public static final String OPERATION = "operation";
public static final String FILE_CONTENT = "fileContent";
public static final String FILE_CONTENT_LENGTH = FILE_CONTENT + "Length";
public static final int DEFAULT_OPERATION = -1;
private static final String PROTOCOL_VERSION = "0.2.0";
private byte[] handshakeMessage;
private final DigestInputStream input;
private Closeable livesyncSocket;
private OutputStream output;
public LiveSyncWorker(LocalSocket systemSocket) throws IOException, java.security.NoSuchAlgorithmException {
this.livesyncSocket = systemSocket;
MessageDigest md = MessageDigest.getInstance("MD5");
input = new DigestInputStream(systemSocket.getInputStream(), md);
output = systemSocket.getOutputStream();
handshakeMessage = getHandshakeMessage();
}
public void run() {
try {
output.write(handshakeMessage);
output.flush();
} catch (IOException e) {
logger.write(String.format("Error while LiveSyncing: Client socket might be closed!", e.toString()));
if (com.tns.Runtime.isDebuggable()) {
e.printStackTrace();
}
}
try {
do {
int operation = getOperation();
if (operation == DELETE_FILE_OPERATION) {
String fileName = getFileName();
validateData();
deleteRecursive(new File(DEVICE_APP_DIR, fileName));
} else if (operation == CREATE_FILE_OPERATION) {
String fileName = getFileName();
int contentLength = getFileContentLength(fileName);
validateData();
byte[] content = getFileContent(fileName, contentLength);
validateData();
createOrOverrideFile(fileName, content);
} else if (operation == DO_SYNC_OPERATION) {
byte[] operationUid = readNextBytes(OPERATION_ID_BYTE_SIZE);
byte doRefresh = readNextBytes(DO_REFRESH_LENGTH)[0];
int doRefreshInt = (int)doRefresh;
int operationReportCode;
validateData();
if(runtime != null && doRefreshInt == DO_REFRESH_VALUE) {
runtime.runScript(new File(NativeScriptSyncServiceSocketImpl.this.context.getFilesDir(), "internal/livesync.js"), false);
operationReportCode = OPERATION_END_REPORT_CODE;
} else {
operationReportCode = OPERATION_END_NO_REFRESH_REPORT_CODE;
}
output.write(getReportMessageBytes(operationReportCode, operationUid));
output.flush();
} else if (operation == DEFAULT_OPERATION) {
logger.write("LiveSync: input stream is empty!");
break;
} else {
throw new IllegalArgumentException(String.format("\nLiveSync: Operation not recognised. Received operation is %s.", operation));
}
} while (true);
} catch (Exception e) {
String message = String.format("Error while LiveSyncing: %s", e.toString());
this.closeWithError(message);
} catch (Throwable e) {
String message = String.format("%s(%s): Error while LiveSyncing.\nOriginal Exception: %s", Thread.currentThread().getName(), Thread.currentThread().getId(), e.toString());
this.closeWithError(message);
}
}
private byte[] getErrorMessageBytes(String message) {
return this.getReportMessageBytes(ERROR_REPORT_CODE, message.getBytes());
}
private byte[] getReportMessageBytes(int reportType, byte[] messageBytes) {
byte[] reportBytes = new byte[]{(byte)reportType};
byte[] combined = new byte[messageBytes.length + REPORT_CODE_SIZE];
System.arraycopy(reportBytes,0,combined, 0, REPORT_CODE_SIZE);
System.arraycopy(messageBytes,0,combined, REPORT_CODE_SIZE, messageBytes.length);
return combined;
}
private byte[] getHandshakeMessage() {
byte[] protocolVersionBytes = PROTOCOL_VERSION.getBytes();
byte[] versionLength = new byte[]{(byte)protocolVersionBytes.length};
byte[] packageNameBytes = context.getPackageName().getBytes();
byte[] combined = new byte[protocolVersionBytes.length + packageNameBytes.length + versionLength.length];
System.arraycopy(versionLength,0,combined, 0, versionLength.length);
System.arraycopy(protocolVersionBytes,0,combined, versionLength.length, protocolVersionBytes.length);
System.arraycopy(packageNameBytes,0,combined,protocolVersionBytes.length + versionLength.length,packageNameBytes.length);
return combined;
}
private void validateData() throws IOException {
MessageDigest messageDigest = input.getMessageDigest();
byte[] digest = messageDigest.digest();
input.on(false);
byte[] inputMD5 = readNextBytes(HASH_BYTE_SIZE);
input.on(true);
if(!Arrays.equals(digest, inputMD5)){
throw new IllegalStateException(String.format("\nLiveSync: Validation of data failed.\nComputed hash: %s\nOriginal hash: %s ", Arrays.toString(digest), Arrays.toString(inputMD5)));
}
}
/*
* Tries to read operation input stream
* If the stream is empty, method returns -1
* */
private int getOperation() {
Integer operation;
byte[] operationBuff = null;
try {
operationBuff = readNextBytes(OPERATION_BYTE_SIZE);
if (operationBuff == null) {
return DEFAULT_OPERATION;
}
operation = Integer.parseInt(new String(operationBuff));
} catch (Exception e) {
if(operationBuff == null){
operationBuff = new byte[]{};
}
throw new IllegalStateException(String.format("\nLiveSync: failed to parse %s. Bytes read: $s %s\nOriginal Exception: %s", OPERATION, Arrays.toString(operationBuff), e.toString()));
}
return operation;
}
private String getFileName() {
byte[] fileNameBuffer;
int fileNameLength = -1;
try {
fileNameLength = getLength();
} catch (Exception e) {
throw new IllegalStateException(String.format("\nLiveSync: failed to parse %s. \nOriginal Exception: %s", FILE_NAME_LENGTH, e.toString()));
}
if(fileNameLength <= 0) {
throw new IllegalStateException(String.format("\nLiveSync: File name length must be positive number or zero. Provided length: %s.", fileNameLength));
}
try {
fileNameBuffer = readNextBytes(fileNameLength);
} catch (Exception e) {
throw new IllegalStateException(String.format("\nLiveSync: failed to parse %s.\nOriginal Exception: %s", FILE_NAME, e.toString()));
}
if (fileNameBuffer == null) {
throw new IllegalStateException(String.format("\nLiveSync: Missing %s bytes.", FILE_NAME));
}
String fileName = new String(fileNameBuffer);
if (fileName.trim().length() < fileNameLength) {
logger.write(String.format("WARNING: %s parsed length is less than %s. We read less information than you specified!", FILE_NAME, FILE_NAME_LENGTH));
}
return fileName.trim();
}
private int getFileContentLength(String fileName) throws IllegalStateException {
int contentLength;
try {
contentLength = getLength();
} catch (Exception e) {
throw new IllegalStateException(String.format("\nLiveSync: failed to read %s for %s.\nOriginal Exception: %s", FILE_CONTENT_LENGTH, fileName, e.toString()));
}
if(contentLength < 0){
throw new IllegalStateException(String.format("\nLiveSync: Content length must be positive number or zero. Provided content length: %s.", contentLength));
}
return contentLength;
}
private byte[] getFileContent(String fileName, int contentLength) throws IllegalStateException {
byte[] contentBuff = null;
try {
if(contentLength > 0) {
contentBuff = readNextBytes(contentLength);
} else if(contentLength == 0){
contentBuff = new byte[]{};
}
} catch (Exception e) {
throw new IllegalStateException(String.format("\nLiveSync: failed to parse content of file: %s.\nOriginal Exception: %s", fileName, e.toString()));
}
if (contentLength != 0 && contentBuff == null) {
throw new IllegalStateException(String.format("\nLiveSync: Missing %s bytes for file: %s. Did you send %s bytes?", FILE_CONTENT, fileName, contentLength));
}
return contentBuff;
}
private int getLength() {
byte[] lengthBuffer;
int lengthInt;
try {
byte lengthSize = readNextBytes(LENGTH_BYTE_SIZE)[0];
//Cast signed byte to unsigned int
int lengthSizeInt = ((int) lengthSize) & 0xFF;
lengthBuffer = readNextBytes(lengthSizeInt);
if (lengthBuffer == null) {
throw new IllegalStateException(String.format("\nLiveSync: Missing size length bytes."));
}
} catch (Exception e) {
throw new IllegalStateException(String.format("\nLiveSync: Failed to read size length. \nOriginal Exception: %s", e.toString()));
}
try {
lengthInt = Integer.valueOf(new String(lengthBuffer));
} catch (Exception e) {
throw new IllegalStateException(String.format("\nLiveSync: Failed to parse size length. \nOriginal Exception: %s", e.toString()));
}
return lengthInt;
}
/*
* Written through a sibling temp file renamed over the target, because
* the app keeps running JS while files stream in: rename(2) within a
* directory is atomic, so a runtime thread that requires this path
* mid-sync gets either the whole previous file or the whole new one.
* Writing in place cannot be made safe from the reader side -- the
* truncate lands before any lock a reader could share, and each runtime
* (main, every worker) reads on its own thread.
*/
private void createOrOverrideFile(String fileName, byte[] content) throws IOException {
File fileToCreate = new File(DEVICE_APP_DIR, fileName);
File parentDir = fileToCreate.getParentFile();
if (parentDir != null) {
parentDir.mkdirs();
}
File temp = null;
try {
// Same directory as the target: rename is only atomic within one
// filesystem, and a sibling is the one placement that guarantees it.
temp = File.createTempFile("livesync", ".tmp", parentDir);
FileOutputStream fos = new FileOutputStream(temp);
try {
fos.write(content);
} finally {
fos.close();
}
if (!temp.renameTo(fileToCreate)) {
throw new IOException(String.format("failed to rename %s onto the target", temp.getAbsolutePath()));
}
temp = null;
} catch (Exception e) {
throw new IOException(String.format("\nLiveSync: failed to write file: %s\nOriginal Exception: %s", fileName, e.toString()));
} finally {
if (temp != null) {
temp.delete();
}
}
}
void deleteRecursive(File fileOrDirectory) {
if (fileOrDirectory.isDirectory())
for (File child : fileOrDirectory.listFiles()) {
deleteRecursive(child);
}
fileOrDirectory.delete();
}
/*
* Reads next bites from input stream. Bytes read depend on passed parameter.
* */
private byte[] readNextBytes(int size) throws IOException {
byte[] buffer = new byte[size];
int bytesRead = 0;
int bufferWriteOffset = bytesRead;
try {
do {
bytesRead = this.input.read(buffer, bufferWriteOffset, size);
if (bytesRead == -1) {
if (bufferWriteOffset == 0) {
return null;
}
break;
}
size -= bytesRead;
bufferWriteOffset += bytesRead;
} while (size > 0);
} catch (IOException e) {
String message = e.getMessage();
if (message != null && message.equals("Try again")) {
throw new IllegalStateException("Error while LiveSyncing: Read operation timed out.");
} else {
throw e;
}
}
return buffer;
}
private void closeWithError(String message) {
try {
output.write(getErrorMessageBytes(message));
output.flush();
logger.write(message);
this.livesyncSocket.close();
} catch (IOException e) {
if (com.tns.Runtime.isDebuggable()) {
e.printStackTrace();
}
}
}
@Override
protected void finalize() throws Throwable {
this.livesyncSocket.close();
}
}
}