This repository has been archived by the owner on Sep 20, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathChromeSocketsTcp.java
1147 lines (949 loc) · 33.1 KB
/
ChromeSocketsTcp.java
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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package org.chromium;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.channels.UnresolvedAddressException;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLException;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaArgs;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.apache.cordova.PluginResult.Status;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.net.Uri;
import android.util.Log;
public class ChromeSocketsTcp extends CordovaPlugin {
private static final String LOG_TAG = "ChromeSocketsTcp";
private Map<Integer, TcpSocket> sockets = new ConcurrentHashMap<Integer, TcpSocket>();
private BlockingQueue<SelectorMessage> selectorMessages =
new LinkedBlockingQueue<SelectorMessage>();
private int nextSocket = 1;
private CallbackContext recvContext;
private Selector selector;
private SelectorThread selectorThread;
private boolean isReadyToRead;
@Override
public boolean execute(String action, CordovaArgs args, final CallbackContext callbackContext)
throws JSONException {
if ("create".equals(action)) {
create(args, callbackContext);
} else if ("update".equals(action)) {
update(args, callbackContext);
} else if ("setPaused".equals(action)) {
setPaused(args, callbackContext);
} else if ("setKeepAlive".equals(action)) {
setKeepAlive(args, callbackContext);
} else if ("setNoDelay".equals(action)) {
setNoDelay(args, callbackContext);
} else if ("connect".equals(action)) {
connect(args, callbackContext);
} else if ("disconnect".equals(action)) {
disconnect(args, callbackContext);
} else if ("secure".equals(action)) {
secure(args, callbackContext);
} else if ("send".equals(action)) {
send(args, callbackContext);
} else if ("close".equals(action)) {
close(args, callbackContext);
} else if ("getInfo".equals(action)) {
getInfo(args, callbackContext);
} else if ("getSockets".equals(action)) {
getSockets(args, callbackContext);
} else if ("pipeToFile".equals(action)) {
pipeToFile(args, callbackContext);
} else if ("registerReceiveEvents".equals(action)) {
registerReceiveEvents(args, callbackContext);
} else if ("readyToRead".equals(action)) {
readyToRead();
} else {
return false;
}
return true;
}
@Override
public void onDestroy() {
super.onDestroy();
closeAllSockets();
stopSelectorThread();
}
@Override
public void onReset() {
super.onReset();
closeAllSockets();
stopSelectorThread();
}
private JSONObject buildErrorInfo(int code, String message) {
JSONObject error = new JSONObject();
try {
error.put("message", message);
error.put("resultCode", code);
} catch (JSONException e) {
}
return error;
}
private void sendReceiveEvent(PluginResult result) {
if (recvContext != null) {
result.setKeepCallback(true);
recvContext.sendPluginResult(result);
}
}
public int registerAcceptedSocketChannel(SocketChannel socketChannel)
throws IOException {
TcpSocket socket = new TcpSocket(nextSocket++, socketChannel);
sockets.put(Integer.valueOf(socket.getSocketId()), socket);
addSelectorMessage(socket, SelectorMessageType.SO_ACCEPTED, null);
return socket.getSocketId();
}
private void create(CordovaArgs args, final CallbackContext callbackContext)
throws JSONException {
JSONObject properties = args.getJSONObject(0);
try {
TcpSocket socket = new TcpSocket(nextSocket++, properties);
sockets.put(Integer.valueOf(socket.getSocketId()), socket);
callbackContext.success(socket.getSocketId());
} catch (IOException e) {
}
}
private void update(CordovaArgs args, final CallbackContext callbackContext)
throws JSONException {
int socketId = args.getInt(0);
JSONObject properties = args.getJSONObject(1);
TcpSocket socket = sockets.get(Integer.valueOf(socketId));
if (socket == null) {
Log.e(LOG_TAG, "No socket with socketId " + socketId);
return;
}
try {
socket.setProperties(properties);
callbackContext.success();
} catch (SocketException e) {
}
}
private void setPaused(CordovaArgs args, final CallbackContext callbackContext)
throws JSONException {
int socketId = args.getInt(0);
boolean paused = args.getBoolean(1);
TcpSocket socket = sockets.get(Integer.valueOf(socketId));
if (socket == null) {
Log.e(LOG_TAG, "No socket with socketId " + socketId);
return;
}
socket.setPaused(paused);
if (paused) {
// Read interest will be removed when socket is readable on selector thread.
callbackContext.success();
} else {
// All interests need to be modified in selector thread.
addSelectorMessage(socket, SelectorMessageType.SO_ADD_READ_INTEREST, callbackContext);
}
}
private void setKeepAlive(CordovaArgs args, final CallbackContext callbackContext)
throws JSONException {
int socketId = args.getInt(0);
boolean enable = args.getBoolean(1);
TcpSocket socket = sockets.get(Integer.valueOf(socketId));
if (socket == null) {
Log.e(LOG_TAG, "No socket with socketId " + socketId);
callbackContext.error(buildErrorInfo(-4, "Invalid Argument"));
return;
}
try {
socket.setKeepAlive(enable);
callbackContext.success();
} catch (SocketException e) {
callbackContext.error(buildErrorInfo(-2, e.getMessage()));
}
}
private void setNoDelay(CordovaArgs args, final CallbackContext callbackContext)
throws JSONException {
int socketId = args.getInt(0);
boolean noDelay = args.getBoolean(1);
TcpSocket socket = sockets.get(Integer.valueOf(socketId));
if (socket == null) {
Log.e(LOG_TAG, "No socket with socketId " + socketId);
callbackContext.error(buildErrorInfo(-4, "Invalid Argument"));
return;
}
try {
socket.setNoDelay(noDelay);
callbackContext.success();
} catch (SocketException e) {
callbackContext.error(buildErrorInfo(-2, e.getMessage()));
}
}
private void connect(CordovaArgs args, final CallbackContext callbackContext)
throws JSONException {
int socketId = args.getInt(0);
String peerAddress = args.getString(1);
int peerPort = args.getInt(2);
TcpSocket socket = sockets.get(Integer.valueOf(socketId));
if (socket == null) {
Log.e(LOG_TAG, "No socket with socketId " + socketId);
callbackContext.error(buildErrorInfo(-4, "Invalid Argument"));
return;
}
try {
if (socket.connect(peerAddress, peerPort, callbackContext)) {
addSelectorMessage(socket, SelectorMessageType.SO_CONNECTED, null);
} else {
addSelectorMessage(socket, SelectorMessageType.SO_CONNECT, null);
}
} catch (IOException e) {
callbackContext.error(buildErrorInfo(-104, e.getMessage()));
}
}
private void disconnect(CordovaArgs args, final CallbackContext callbackContext)
throws JSONException {
int socketId = args.getInt(0);
TcpSocket socket = sockets.get(Integer.valueOf(socketId));
if (socket == null) {
Log.e(LOG_TAG, "No socket with socketId " + socketId);
return;
}
addSelectorMessage(socket, SelectorMessageType.SO_DISCONNECTED, callbackContext);
}
private void secure(CordovaArgs args, final CallbackContext callbackContext)
throws JSONException {
int socketId = args.getInt(0);
JSONObject options = args.getJSONObject(1);
TcpSocket socket = sockets.get(Integer.valueOf(socketId));
if (socket == null) {
Log.e(LOG_TAG, "No socket with socketId " + socketId);
callbackContext.error(buildErrorInfo(-4, "Invalid Argument"));
return;
}
if (!socket.isConnected()) {
Log.e(LOG_TAG, "Socket is not connected with host " + socketId);
callbackContext.error(buildErrorInfo(-15, "Socket not connected"));
return;
}
String minVersion = "";
String maxVersion = "";
if (options != null && !options.isNull("tlsVersion")) {
JSONObject tlsVersion = options.getJSONObject("tlsVersion");
if (!tlsVersion.isNull("min")) {
minVersion = tlsVersion.getString("min");
}
if (!tlsVersion.isNull("max")) {
maxVersion = tlsVersion.getString("max");
}
}
socket.setSecureCallbackAndOptions(minVersion, maxVersion, callbackContext);
addSelectorMessage(socket, SelectorMessageType.SSL_INIT_HANDSHAKE, null);
}
private void send(CordovaArgs args, final CallbackContext callbackContext)
throws JSONException {
int socketId = args.getInt(0);
byte[] data = args.getArrayBuffer(1);
TcpSocket socket = sockets.get(Integer.valueOf(socketId));
if (socket == null) {
Log.e(LOG_TAG, "No socket with socketId " + socketId);
callbackContext.error(buildErrorInfo(-4, "Invalid Argument"));
return;
}
if (!socket.isConnected()) {
Log.e(LOG_TAG, "Socket is not connected with host " + socketId);
callbackContext.error(buildErrorInfo(-15, "Socket not connected"));
return;
}
socket.addSendPacket(data, callbackContext);
// All interests need to be modified in selector thread.
addSelectorMessage(socket, SelectorMessageType.SO_ADD_WRITE_INTEREST, null);
}
private void closeAllSockets() {
for (TcpSocket socket: sockets.values()) {
addSelectorMessage(socket, SelectorMessageType.SO_CLOSE, null);
}
}
private void close(CordovaArgs args, final CallbackContext callbackContext)
throws JSONException {
int socketId = args.getInt(0);
TcpSocket socket = sockets.get(Integer.valueOf(socketId));
if (socket == null) {
Log.e(LOG_TAG, "No socket with socketId " + socketId);
return;
}
addSelectorMessage(socket, SelectorMessageType.SO_CLOSE, callbackContext);
}
private void getInfo(CordovaArgs args, final CallbackContext callbackContext)
throws JSONException {
int socketId = args.getInt(0);
TcpSocket socket = sockets.get(Integer.valueOf(socketId));
if (socket == null) {
Log.e(LOG_TAG, "No socket with socketId " + socketId);
return;
}
callbackContext.success(socket.getInfo());
}
private void getSockets(CordovaArgs args, final CallbackContext callbackContext)
throws JSONException {
JSONArray results = new JSONArray();
for (TcpSocket socket: sockets.values()) {
results.put(socket.getInfo());
}
callbackContext.success(results);
}
private void pipeToFile(CordovaArgs args, final CallbackContext callbackContext)
throws JSONException {
final int socketId = args.getInt(0);
final JSONObject options = args.getJSONObject(1);
final TcpSocket socket = sockets.get(Integer.valueOf(socketId));
// Use a background thread because setProperties may perform IO operations.
cordova.getThreadPool().execute(new Runnable() {
public void run() {
String errMessage = null;
try {
if(!socket.setPipeToFileProperties(options, callbackContext)) {
errMessage = "Failed to start pipeToFile";
}
} catch (IOException e) {
errMessage = e.getMessage();
}
if (errMessage != null) {
try {
JSONObject info = buildErrorInfo(-1000, errMessage);
info.put("socketId", socketId);
sendReceiveEvent(new PluginResult(Status.ERROR, info));
} catch (JSONException e) {
}
}
}
});
}
private void registerReceiveEvents(CordovaArgs args, final CallbackContext callbackContext) {
recvContext = callbackContext;
startSelectorThread();
readyToRead();
}
private void readyToRead() {
isReadyToRead = true;
}
private void startSelectorThread() {
if (selectorThread != null) return;
selectorThread = new SelectorThread(selectorMessages, sockets);
selectorThread.start();
}
private void stopSelectorThread() {
if (selectorThread == null) return;
addSelectorMessage(null, SelectorMessageType.T_STOP, null);
try {
selectorThread.join();
selectorThread = null;
} catch (InterruptedException e) {
}
}
private void addSelectorMessage(
TcpSocket socket, SelectorMessageType type, CallbackContext callbackContext) {
try {
selectorMessages.put(new SelectorMessage(
socket, type, callbackContext));
if (selector != null)
selector.wakeup();
} catch (InterruptedException e) {
}
}
private enum SelectorMessageType {
SO_CONNECT,
SO_CONNECTED,
SO_ACCEPTED,
SO_DISCONNECTED,
SO_CLOSE,
SSL_INIT_HANDSHAKE,
SO_ADD_READ_INTEREST,
SO_ADD_WRITE_INTEREST,
T_STOP;
}
private class SelectorMessage {
final TcpSocket socket;
final SelectorMessageType type;
final CallbackContext callbackContext;
SelectorMessage(
TcpSocket socket, SelectorMessageType type, CallbackContext callbackContext) {
this.socket = socket;
this.type = type;
this.callbackContext = callbackContext;
}
}
private class SelectorThread extends Thread {
private BlockingQueue<SelectorMessage> selectorMessages;
private Map<Integer, TcpSocket> sockets;
private boolean running = true;
SelectorThread(
BlockingQueue<SelectorMessage> selectorMessages,
Map<Integer, TcpSocket> sockets) {
this.selectorMessages = selectorMessages;
this.sockets = sockets;
}
private void processPendingMessages() {
while (selectorMessages.peek() != null) {
SelectorMessage msg = null;
try {
msg = selectorMessages.take();
switch (msg.type) {
case SO_CONNECT:
msg.socket.register(selector, SelectionKey.OP_CONNECT);
break;
case SO_CONNECTED:
msg.socket.register(selector, SelectionKey.OP_READ);
break;
case SO_ACCEPTED:
msg.socket.register(selector, 0);
break;
case SO_DISCONNECTED:
msg.socket.disconnect();
break;
case SO_CLOSE:
msg.socket.disconnect();
sockets.remove(Integer.valueOf(msg.socket.getSocketId()));
break;
case SSL_INIT_HANDSHAKE:
msg.socket.setUpSSLEngine();
boolean hasWork = true;
while(hasWork) {
hasWork = msg.socket.performNextHandshakeStep();
}
msg.socket.handshakeSuccess();
break;
case SO_ADD_READ_INTEREST:
msg.socket.addInterestSet(SelectionKey.OP_READ);
break;
case SO_ADD_WRITE_INTEREST:
msg.socket.addInterestSet(SelectionKey.OP_WRITE);
break;
case T_STOP:
running = false;
break;
}
if (msg.callbackContext != null)
msg.callbackContext.success();
} catch (InterruptedException e) {
} catch (IOException e) {
if (msg.callbackContext != null)
msg.callbackContext.error(buildErrorInfo(-2, e.getMessage()));
} catch (JSONException e) {
}
}
}
public void run() {
try {
selector = Selector.open();
} catch (IOException e) {
throw new RuntimeException(e);
}
// process possible messages that send during openning the selector
// before select.
processPendingMessages();
Iterator<SelectionKey> it;
while (running) {
try {
selector.select();
} catch (IOException e) {
continue;
}
it = selector.selectedKeys().iterator();
while (it.hasNext()) {
SelectionKey key = it.next();
it.remove();
if (!key.isValid()) {
continue;
}
TcpSocket socket = (TcpSocket)key.attachment();
if (key.isReadable()) {
try {
if (socket.read() < 0) {
addSelectorMessage(socket, SelectorMessageType.SO_DISCONNECTED, null);
}
} catch (JSONException e) {
}
}
if (key.isWritable()) {
socket.dequeueSend();
}
if (key.isConnectable()) {
if (socket.finishConnect()) {
addSelectorMessage(socket, SelectorMessageType.SO_CONNECTED, null);
}
}
} // while next
processPendingMessages();
}
}
}
private class TcpSocket {
private final static long PIPE_TO_FILE_PROGRESS_INTERVAL = 100000000; // nano seconds
private final int socketId;
private SocketChannel channel;
private ByteBuffer receiveDataBuffer;
private SSLEngine sslEngine;
private String sslMinVersion;
private String sslMaxVersion;
// Buffer used to decrypt SSL data, we have no control on its size
private ByteBuffer sslPeerAppBuffer;
private ByteBuffer sslNetBuffer;
private BlockingQueue<TcpSendPacket> sendPackets = new LinkedBlockingQueue<TcpSendPacket>();
private SelectionKey key;
private boolean paused;
private boolean persistent;
private String name;
private int bufferSize;
// pipeToFile properties
private Uri uri;
private OutputStream uriOutputStream;
private boolean append;
private int numBytes;
private CallbackContext pipeToFileCallback;
private long bytesReadNotSend;
private long lastProgressTimestamp;
private CallbackContext connectCallback;
private CallbackContext secureCallback;
TcpSocket(int socketId, JSONObject properties)
throws JSONException, IOException {
this.socketId = socketId;
channel = SocketChannel.open();
channel.configureBlocking(false);
sslEngine = null;
sslMinVersion = "";
sslMaxVersion = "";
setDefaultProperties();
setProperties(properties);
setBufferSize();
}
TcpSocket(int socketId, SocketChannel acceptedSocket)
throws IOException {
this.socketId = socketId;
channel = acceptedSocket;
channel.configureBlocking(false);
sslEngine = null;
setDefaultProperties();
setBufferSize();
// accepted socket paused by default
paused = true;
}
void resetPipeToFileProperties() throws IOException {
if (uriOutputStream != null) {
uriOutputStream.close();
uriOutputStream = null;
uri = null;
}
pipeToFileCallback = null;
append = false;
numBytes = 0;
bytesReadNotSend = 0;
}
void setDefaultProperties() throws IOException {
paused = false;
persistent = false;
bufferSize = 4096;
name = "";
resetPipeToFileProperties();
}
// Only call this method on selector thread
void addInterestSet(int interestSet) {
if (key != null && key.isValid()) {
key.interestOps(key.interestOps() | interestSet);
}
}
// Only call this method on selector thread
void removeInterestSet(int interestSet) {
if (key != null && key.isValid()) {
key.interestOps(key.interestOps() & ~interestSet);
}
}
int getSocketId() {
return socketId;
}
boolean isConnected() {
return channel.isOpen() && channel.isConnected();
}
void register(Selector selector, int interestSets) throws IOException {
key = channel.register(selector, interestSets, this);
}
void setProperties(JSONObject properties) throws JSONException, SocketException {
if (!properties.isNull("persistent"))
persistent = properties.getBoolean("persistent");
if (!properties.isNull("name"))
name = properties.getString("name");
if (!properties.isNull("bufferSize")) {
bufferSize = properties.getInt("bufferSize");
setBufferSize();
}
}
boolean setPipeToFileProperties(JSONObject properties, CallbackContext callbackContext)
throws IOException {
resetPipeToFileProperties();
append = properties.optBoolean("append");
numBytes = properties.optInt("numBytes");
if (numBytes <= 0)
return false;
pipeToFileCallback = callbackContext;
String uriString = properties.optString("uri");
if (uriString.length() > 0) {
Uri outputUri = Uri.parse(uriString);
uriOutputStream = webView.getResourceApi().openOutputStream(outputUri, append);
// Only update the uri if the output uri is valid for openOutputStream()
uri = outputUri;
} else {
return false;
}
lastProgressTimestamp = System.nanoTime();
return true;
}
void setBufferSize() throws SocketException {
channel.socket().setSendBufferSize(bufferSize);
channel.socket().setReceiveBufferSize(bufferSize);
receiveDataBuffer = ByteBuffer.allocate(bufferSize);
}
void setPaused(boolean paused) {
this.paused = paused;
}
void setKeepAlive(boolean enable) throws SocketException {
channel.socket().setKeepAlive(enable);
}
void setNoDelay(boolean noDelay) throws SocketException {
channel.socket().setTcpNoDelay(noDelay);
}
boolean connect(String address, int port, CallbackContext connectCallback) throws IOException {
if (!channel.isOpen()) {
channel = SocketChannel.open();
channel.configureBlocking(false);
setBufferSize();
}
boolean connected = false;
try {
connected = channel.connect(new InetSocketAddress(address, port));
} catch (UnresolvedAddressException e) {
connectCallback.error(e.getMessage());
}
if (connected) {
connectCallback.success();
} else {
this.connectCallback = connectCallback;
}
return connected;
}
boolean finishConnect() {
if (channel.isConnectionPending() && connectCallback != null) {
try {
boolean connected = channel.finishConnect();
if (connected) {
connectCallback.success();
connectCallback = null;
}
return connected;
} catch (IOException e) {
connectCallback.error(buildErrorInfo(-104, e.getMessage()));
connectCallback = null;
}
}
return false;
}
void disconnect() throws IOException {
if (key != null && channel.isRegistered())
key.cancel();
resetPipeToFileProperties();
channel.close();
}
/**
* @return whether further handshake need to be performed.
*/
boolean performNextHandshakeStep() throws IOException, JSONException {
switch(sslEngine.getHandshakeStatus()) {
case FINISHED:
return false;
case NEED_TASK:
Runnable task;
while((task = sslEngine.getDelegatedTask()) != null) {
task.run();
}
return true;
case NEED_UNWRAP:
int bytesRead = channel.read(receiveDataBuffer);
if (bytesRead == -1) {
handshakeFailed();
return false;
}
tryUnwrapReceiveData();
return true;
case NEED_WRAP:
ByteBuffer wrapData = ByteBuffer.allocate(sslEngine.getSession().getPacketBufferSize());
sslEngine.wrap(ByteBuffer.allocate(0), wrapData);
wrapData.flip();
channel.write(wrapData);
return true;
default:
return false;
}
}
void handshakeFailed() {
if (secureCallback != null) {
secureCallback.error(buildErrorInfo(-148, "SSL handshake not completed"));
secureCallback = null;
}
tearDownSSLEngine();
}
void handshakeSuccess() {
if (secureCallback != null) {
secureCallback.success();
secureCallback = null;
}
}
SSLEngineResult tryUnwrapReceiveData() throws SSLException {
receiveDataBuffer.flip();
sslPeerAppBuffer.clear();
SSLEngineResult res;
do {
res = sslEngine.unwrap(receiveDataBuffer, sslPeerAppBuffer);
} while (maybeGrowBuffersForUnwrap(res));
sslPeerAppBuffer.flip();
receiveDataBuffer.compact();
return res;
}
boolean maybeGrowBuffersForUnwrap(SSLEngineResult res) {
switch (res.getStatus()) {
case BUFFER_OVERFLOW:
increaseSSLPeerAppBuffer();
return true;
case BUFFER_UNDERFLOW:
increaseReceiveDataBuffer();
// Need another read to get enough data to unwrap.
case OK:
default:
return false;
}
}
boolean maybeGrowBuffersForWrap(SSLEngineResult res) {
switch (res.getStatus()) {
case BUFFER_OVERFLOW:
increaseSSLNetBuffer();
return true;
default:
return false;
}
}
void increaseSSLPeerAppBuffer() {
// Increase the capacity of sslPeerAppBuffer to the size needed to decrypt
// inbound data.
ByteBuffer newBuffer = ByteBuffer.allocate(
sslEngine.getSession().getApplicationBufferSize() +
sslPeerAppBuffer.position());
sslPeerAppBuffer.flip();
newBuffer.put(sslPeerAppBuffer);
sslPeerAppBuffer = newBuffer;
}
void increaseReceiveDataBuffer() {
// Increase the capacity of the receiveDataBuffer for next receive if
// needed.
if (receiveDataBuffer.capacity() < sslEngine.getSession().getPacketBufferSize()) {
ByteBuffer newBuffer = ByteBuffer.allocate(
sslEngine.getSession().getPacketBufferSize() +
receiveDataBuffer.position());
receiveDataBuffer.flip();
newBuffer.put(receiveDataBuffer);
receiveDataBuffer = newBuffer;
}
}
void increaseSSLNetBuffer() {
// Increase the capacity of sslNetBuffer to the size needed to encrypt
// outbound data.
ByteBuffer newBuffer = ByteBuffer.allocate(
sslEngine.getSession().getPacketBufferSize() +
sslNetBuffer.position());
sslNetBuffer.flip();
newBuffer.put(sslNetBuffer);
sslNetBuffer = newBuffer;
}
void setUpSSLEngine() throws JSONException {
try {
sslEngine = SSLContext.getDefault().createSSLEngine();
sslEngine.setUseClientMode(true);
receiveDataBuffer = ByteBuffer.allocate(sslEngine.getSession().getPacketBufferSize());
sslNetBuffer = ByteBuffer.allocate(sslEngine.getSession().getPacketBufferSize());
sslPeerAppBuffer = ByteBuffer.allocate(sslEngine.getSession().getApplicationBufferSize());
// TODO: TLS1.1 and TLS1.2 is supported and enabled by default for API 20+.
if (sslMinVersion.startsWith("tls")) {
sslEngine.setEnabledProtocols(new String[] {"TLSv1"});
}
if (sslMaxVersion.startsWith("ssl")) {
sslEngine.setEnabledProtocols(new String[] {"SSLv3"});
}
sslEngine.beginHandshake();
} catch (SSLException e) {
handshakeFailed();
} catch (NoSuchAlgorithmException e) {
handshakeFailed();
}
}
void tearDownSSLEngine() {
sslEngine = null;
}
void setSecureCallbackAndOptions(
String minVersion, String maxVersion, CallbackContext callbackContext) {
if (sslEngine != null)
return;
sslMinVersion = minVersion;
sslMaxVersion = maxVersion;
secureCallback = callbackContext;
}
void addSendPacket(byte[] data, CallbackContext callbackContext) {
ByteBuffer appData = ByteBuffer.wrap(data);
TcpSendPacket sendPacket = new TcpSendPacket(appData, callbackContext);
try {
sendPackets.put(sendPacket);
} catch (InterruptedException e) {
}
}
// This method can be only called by selector thread.
void dequeueSend() {
if (sendPackets.peek() == null) {
removeInterestSet(SelectionKey.OP_WRITE);
return;
}
TcpSendPacket sendPacket = null;
try {
int bytesSent = 0;
sendPacket = sendPackets.take();
if (sslEngine != null) {
SSLEngineResult res;
do {
res = sslEngine.wrap(sendPacket.data, sslNetBuffer);
} while (maybeGrowBuffersForWrap(res));
sslNetBuffer.flip();
bytesSent = res.bytesConsumed();