-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSuo5Server.java
More file actions
1236 lines (1114 loc) · 46.3 KB
/
Copy pathSuo5Server.java
File metadata and controls
1236 lines (1114 loc) · 46.3 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
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
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
public final class Suo5Server {
private Suo5Server() {
}
public static void main(String[] args) throws Exception {
Config config = Config.parse(args);
InetSocketAddress address = new InetSocketAddress(config.host, config.port);
HttpServer server = HttpServer.create(address, 128);
server.createContext(config.path, new Suo5Handler(config));
server.setExecutor(Executors.newCachedThreadPool());
server.start();
}
private static final class Config {
private String host = "0.0.0.0";
private int port = 1098;
private String path = "/s5";
private String header = "X-Authorization";
private String token = "";
private static Config parse(String[] args) {
Config config = new Config();
for (int i = 0; i < args.length; i++) {
String arg = args[i];
if ("-l".equals(arg) && i + 1 < args.length) {
config.host = args[++i];
} else if ("-p".equals(arg) && i + 1 < args.length) {
config.port = Integer.parseInt(args[++i]);
} else if ("-P".equals(arg) && i + 1 < args.length) {
config.path = normalizePath(args[++i]);
} else if ("-t".equals(arg) && i + 1 < args.length) {
config.token = args[++i];
} else if ("-k".equals(arg) && i + 1 < args.length) {
config.header = args[++i];
} else {
throw new IllegalArgumentException("unknown or incomplete argument: " + arg);
}
}
return config;
}
private static String normalizePath(String path) {
if (path == null || path.length() == 0) {
return "/s5";
}
return path.startsWith("/") ? path : "/" + path;
}
}
private static final class Suo5Handler implements HttpHandler {
private final Config config;
private Suo5Handler(Config config) {
this.config = config;
}
public void handle(HttpExchange exchange) throws IOException {
if (!isAuthorized(exchange)) {
byte[] body = "unauthorized".getBytes("UTF-8");
exchange.getResponseHeaders().set("Content-Type", "text/plain; charset=utf-8");
exchange.sendResponseHeaders(401, body.length);
OutputStream out = exchange.getResponseBody();
out.write(body);
out.close();
return;
}
SimpleRequest request = new SimpleRequest(exchange);
SimpleResponse response = new SimpleResponse(exchange);
try {
new Suo5().process(request, response);
} finally {
try {
response.closeIfNeeded();
} catch (IOException ignored) {
}
}
}
private boolean isAuthorized(HttpExchange exchange) {
if (config.token == null || config.token.length() == 0) {
return true;
}
String headerToken = exchange.getRequestHeaders().getFirst(config.header);
if (config.token.equals(headerToken)) {
return true;
}
String query = exchange.getRequestURI().getRawQuery();
if (query == null || query.length() == 0) {
return false;
}
String[] pairs = query.split("&");
for (int i = 0; i < pairs.length; i++) {
String pair = pairs[i];
int idx = pair.indexOf('=');
if (idx > 0 && "token".equals(pair.substring(0, idx)) && config.token.equals(pair.substring(idx + 1))) {
return true;
}
}
return false;
}
}
private static final class SimpleRequest {
private final HttpExchange exchange;
private SimpleRequest(HttpExchange exchange) {
this.exchange = exchange;
}
private InputStream getInputStream() {
return exchange.getRequestBody();
}
private String getMethod() {
return exchange.getRequestMethod();
}
private int getLocalPort() {
return exchange.getLocalAddress().getPort();
}
private int getServerPort() {
return getLocalPort();
}
private Enumeration<String> getHeaderNames() {
List<String> names = new ArrayList<String>(exchange.getRequestHeaders().keySet());
return java.util.Collections.enumeration(names);
}
private String getHeader(String name) {
return exchange.getRequestHeaders().getFirst(name);
}
}
private static final class SimpleResponse {
private final HttpExchange exchange;
private final OutputStream body;
private int status = 200;
private long contentLength = Long.MIN_VALUE;
private boolean headersSent;
private SimpleResponse(HttpExchange exchange) {
this.exchange = exchange;
this.body = new FilterOutputStream(exchange.getResponseBody()) {
public void write(int b) throws IOException {
ensureHeadersSent();
out.write(b);
}
public void write(byte[] b, int off, int len) throws IOException {
ensureHeadersSent();
out.write(b, off, len);
}
public void flush() throws IOException {
ensureHeadersSent();
out.flush();
}
public void close() throws IOException {
ensureHeadersSent();
out.close();
}
};
}
private void setBufferSize(int size) {
}
private void setHeader(String name, String value) {
if (!headersSent) {
exchange.getResponseHeaders().set(name, value);
}
}
private void setStatus(int status) {
if (!headersSent) {
this.status = status;
}
}
private void setContentLength(int length) {
if (!headersSent) {
this.contentLength = length;
exchange.getResponseHeaders().set("Content-Length", String.valueOf(length));
}
}
private OutputStream getOutputStream() {
return body;
}
private void flushBuffer() throws IOException {
ensureHeadersSent();
body.flush();
}
private void closeIfNeeded() throws IOException {
body.close();
}
private void ensureHeadersSent() throws IOException {
if (headersSent) {
return;
}
headersSent = true;
long length = contentLength == Long.MIN_VALUE ? 0 : contentLength;
exchange.sendResponseHeaders(status, length);
}
}
public static class Suo5 implements Runnable, HostnameVerifier, X509TrustManager {
private static HashMap addrs = collectAddr();
private static Hashtable ctx = new Hashtable();
private final String CHARACTERS = "abcdefghijklmnopqrstuvwxyz0123456789";
private final int CHARACTERS_LENGTH = CHARACTERS.length();
private final int BUF_SIZE = 1024 * 16;
private InputStream gInStream;
private OutputStream gOutStream;
private String gtunId;
private int mode = 0;
public Suo5() {
}
public Suo5(InputStream in, OutputStream out, String tunId) {
this.gInStream = in;
this.gOutStream = out;
this.gtunId = tunId;
}
public Suo5(String tunId, int mode) {
this.gtunId = tunId;
this.mode = mode;
}
private void process(SimpleRequest req, SimpleResponse resp) {
String sid = null;
byte[] bodyPrefix = new byte[0];
try {
InputStream reqInputStream = req.getInputStream();
HashMap dataMap = unmarshalBase64(reqInputStream);
byte[] modeData = (byte[]) dataMap.get("m");
byte[] actionData = (byte[]) dataMap.get("ac");
byte[] tunIdData = (byte[]) dataMap.get("id");
byte[] sidData = (byte[]) dataMap.get("sid");
if (actionData == null || actionData.length != 1 || tunIdData == null || tunIdData.length == 0 || modeData == null || modeData.length == 0) {
return;
}
if (sidData != null && sidData.length > 0) {
sid = new String(sidData);
}
String tunId = new String(tunIdData);
byte mode = modeData[0];
switch (mode) {
case 0x00:
sid = randomString(16);
processHandshake(req, resp, dataMap, tunId, sid);
break;
case 0x01:
setBypassHeader(resp);
processFullStream(req, resp, dataMap, tunId);
break;
case 0x02:
setBypassHeader(resp);
case 0x03:
byte[] bodyContent = toByteArray(reqInputStream);
if (processRedirect(req, resp, dataMap, bodyPrefix, bodyContent)) {
break;
}
if (sidData == null || sidData.length == 0 || getKey(new String(sidData)) == null) {
resp.setStatus(403);
return;
}
InputStream bodyStream = new ByteArrayInputStream(bodyContent);
int dirySize = getDirtySize(sid);
if (mode == 0x02) {
writeAndFlush(resp, processTemplateStart(resp, new String(sidData)), dirySize);
do {
processHalfStream(req, resp, dataMap, tunId, dirySize);
try {
dataMap = unmarshalBase64(bodyStream);
if (dataMap.isEmpty()) {
break;
}
tunId = new String((byte[]) dataMap.get("id"));
} catch (Exception e) {
break;
}
} while (true);
writeAndFlush(resp, processTemplateEnd(sid), dirySize);
} else {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write(processTemplateStart(resp, new String(sidData)));
do {
processClassic(req, baos, dataMap, tunId);
try {
dataMap = unmarshalBase64(bodyStream);
if (dataMap.isEmpty()) {
break;
}
tunId = new String((byte[]) dataMap.get("id"));
} catch (Exception e) {
break;
}
} while (true);
baos.write(processTemplateEnd(sid));
resp.setContentLength(baos.size());
writeAndFlush(resp, baos.toByteArray(), 0);
}
break;
default:
}
} catch (Throwable e) {
} finally {
try {
OutputStream out = resp.getOutputStream();
out.flush();
out.close();
} catch (Throwable ignored) {
}
}
}
private void setBypassHeader(SimpleResponse resp) {
resp.setBufferSize(BUF_SIZE);
resp.setHeader("X-Accel-Buffering", "no");
}
private byte[] processTemplateStart(SimpleResponse resp, String sid) throws Exception {
byte[] data = new byte[0];
Object o = getKey(sid);
if (o == null) {
return data;
}
String[] tplParts = (String[]) o;
if (tplParts.length != 3) {
return data;
}
resp.setHeader("Content-Type", tplParts[0]);
return tplParts[1].getBytes();
}
private byte[] processTemplateEnd(String sid) {
byte[] data = new byte[0];
Object o = getKey(sid);
if (o == null) {
return data;
}
String[] tplParts = (String[]) o;
if (tplParts.length != 3) {
return data;
}
return tplParts[2].getBytes();
}
private int getDirtySize(String sid) {
Object o = getKey(sid + "_jk");
if (o == null) {
return 0;
}
return (Integer) o;
}
private boolean processRedirect(SimpleRequest req, SimpleResponse resp, HashMap dataMap, byte[] bodyPrefix, byte[] bodyContent) throws Exception {
byte[] redirectData = (byte[]) dataMap.get("r");
dataMap.remove("r");
boolean needRedirect = redirectData != null && redirectData.length > 0;
if (needRedirect && !isLocalAddr(new String(redirectData))) {
HttpURLConnection conn = null;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write(bodyPrefix);
baos.write(marshalBase64(dataMap));
baos.write(bodyContent);
byte[] newBody = baos.toByteArray();
conn = redirect(req, new String(redirectData), newBody);
resp.setStatus(conn.getResponseCode());
pipeStream(conn.getInputStream(), resp.getOutputStream(), resp, false);
} finally {
if (conn != null) {
conn.disconnect();
}
}
return true;
}
return false;
}
private void processHandshake(SimpleRequest req, SimpleResponse resp, HashMap dataMap, String tunId, String sid) throws Exception {
byte[] redirectData = (byte[]) dataMap.get("r");
boolean needRedirect = redirectData != null && redirectData.length > 0;
if (needRedirect && !isLocalAddr(new String(redirectData))) {
resp.setStatus(403);
return;
}
byte[] tplData = (byte[]) dataMap.get("tpl");
byte[] contentTypeData = (byte[]) dataMap.get("ct");
if (tplData != null && tplData.length > 0 && contentTypeData != null && contentTypeData.length > 0) {
String tpl = new String(tplData);
String[] parts = tpl.split("#data#", 2);
putKey(sid, new String[]{new String(contentTypeData), parts[0], parts[1]});
} else {
putKey(sid, new String[0]);
}
byte[] dirtySizeData = (byte[]) dataMap.get("jk");
if (dirtySizeData != null && dirtySizeData.length > 0) {
int dirtySize = 0;
try {
dirtySize = Integer.parseInt(new String(dirtySizeData));
} catch (NumberFormatException e) {
}
if (dirtySize < 0) {
dirtySize = 0;
}
putKey(sid + "_jk", dirtySize);
}
byte[] isAutoData = (byte[]) dataMap.get("a");
boolean isAuto = isAutoData != null && isAutoData.length > 0 && isAutoData[0] == 0x01;
if (isAuto) {
setBypassHeader(resp);
writeAndFlush(resp, processTemplateStart(resp, sid), 0);
writeAndFlush(resp, marshalBase64(newData(tunId, (byte[]) dataMap.get("dt"))), 0);
Thread.sleep(2000);
writeAndFlush(resp, marshalBase64(newData(tunId, sid.getBytes())), 0);
writeAndFlush(resp, processTemplateEnd(sid), 0);
} else {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write(processTemplateStart(resp, sid));
baos.write(marshalBase64(newData(tunId, (byte[]) dataMap.get("dt"))));
baos.write(marshalBase64(newData(tunId, sid.getBytes())));
baos.write(processTemplateEnd(sid));
resp.setContentLength(baos.size());
writeAndFlush(resp, baos.toByteArray(), 0);
}
}
private void processFullStream(SimpleRequest req, SimpleResponse resp, HashMap dataMap, String tunId) throws Exception {
InputStream reqInputStream = req.getInputStream();
String host = new String((byte[]) dataMap.get("h"));
int port = Integer.parseInt(new String((byte[]) dataMap.get("p")));
if (port == 0) {
port = getServerPort(req);
}
Socket socket = null;
try {
socket = new Socket();
socket.setTcpNoDelay(true);
socket.setReceiveBufferSize(128 * 1024);
socket.setSendBufferSize(128 * 1024);
socket.connect(new InetSocketAddress(host, port), 5000);
writeAndFlush(resp, marshalBase64(newStatus(tunId, (byte) 0x00)), 0);
} catch (Exception e) {
if (socket != null) {
socket.close();
}
writeAndFlush(resp, marshalBase64(newStatus(tunId, (byte) 0x01)), 0);
return;
}
Thread t = null;
boolean sendClose = true;
final OutputStream scOutStream = socket.getOutputStream();
final InputStream scInStream = socket.getInputStream();
final OutputStream respOutputStream = resp.getOutputStream();
try {
Suo5 p = new Suo5(scInStream, respOutputStream, tunId);
t = new Thread(p);
t.start();
while (true) {
HashMap newData = unmarshalBase64(reqInputStream);
if (newData.isEmpty()) {
break;
}
byte action = ((byte[]) newData.get("ac"))[0];
switch (action) {
case 0x00:
case 0x02:
sendClose = false;
break;
case 0x01:
byte[] data = (byte[]) newData.get("dt");
if (data.length != 0) {
scOutStream.write(data);
scOutStream.flush();
}
break;
case 0x10:
writeAndFlush(resp, marshalBase64(newHeartbeat(tunId)), 0);
break;
default:
}
}
} catch (Exception ignored) {
} finally {
try {
socket.close();
} catch (Exception ignored) {
}
if (sendClose) {
writeAndFlush(resp, marshalBase64(newDel(tunId)), 0);
}
if (t != null) {
t.join();
}
}
}
private void processHalfStream(SimpleRequest req, SimpleResponse resp, HashMap dataMap, String tunId, int dirtySize) throws Exception {
boolean newThread = false;
boolean sendClose = true;
try {
byte action = ((byte[]) dataMap.get("ac"))[0];
switch (action) {
case 0x00:
byte[] createData = performCreate(req, dataMap, tunId, newThread);
writeAndFlush(resp, createData, dirtySize);
Object[] objs = (Object[]) getKey(tunId);
if (objs == null) {
throw new IOException("tunnel not found");
}
SocketChannel sc = (SocketChannel) objs[0];
ByteBuffer buffer = ByteBuffer.allocate(BUF_SIZE);
while (true) {
try {
byte[] data = readSocketChannel(sc, buffer);
if (data.length == 0) {
break;
}
writeAndFlush(resp, marshalBase64(newData(tunId, data)), dirtySize);
} catch (Exception e) {
break;
}
}
break;
case 0x01:
performWrite(dataMap, tunId, newThread);
break;
case 0x02:
sendClose = false;
performDelete(tunId);
break;
case 0x10:
writeAndFlush(resp, marshalBase64(newHeartbeat(tunId)), dirtySize);
break;
default:
}
} catch (Exception e) {
performDelete(tunId);
if (sendClose) {
writeAndFlush(resp, marshalBase64(newDel(tunId)), dirtySize);
}
}
}
private void processClassic(SimpleRequest req, ByteArrayOutputStream respBodyStream, HashMap dataMap, String tunId) throws Exception {
boolean sendClose = true;
boolean newThread = true;
try {
byte action = ((byte[]) dataMap.get("ac"))[0];
switch (action) {
case 0x00:
byte[] createData = performCreate(req, dataMap, tunId, newThread);
respBodyStream.write(createData);
break;
case 0x01:
performWrite(dataMap, tunId, newThread);
byte[] readData = performRead(tunId);
respBodyStream.write(readData);
break;
case 0x02:
sendClose = false;
performDelete(tunId);
break;
default:
}
} catch (Exception e) {
performDelete(tunId);
if (sendClose) {
respBodyStream.write(marshalBase64(newDel(tunId)));
}
}
}
private void writeAndFlush(SimpleResponse resp, byte[] data, int dirtySize) throws Exception {
if (data == null || data.length == 0) {
return;
}
OutputStream out = resp.getOutputStream();
out.write(data);
if (dirtySize != 0) {
out.write(marshalBase64(newDirtyChunk(dirtySize)));
}
out.flush();
resp.flushBuffer();
}
private byte[] performCreate(SimpleRequest request, HashMap dataMap, String tunId, boolean newThread) throws Exception {
String host = new String((byte[]) dataMap.get("h"));
int port = Integer.parseInt(new String((byte[]) dataMap.get("p")));
if (port == 0) {
port = getServerPort(request);
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
SocketChannel socketChannel = null;
HashMap resultData;
try {
socketChannel = SocketChannel.open();
socketChannel.socket().setTcpNoDelay(true);
socketChannel.socket().setReceiveBufferSize(128 * 1024);
socketChannel.socket().setSendBufferSize(128 * 1024);
socketChannel.socket().connect(new InetSocketAddress(host, port), 3000);
socketChannel.configureBlocking(true);
resultData = newStatus(tunId, (byte) 0x00);
BlockingQueue<byte[]> readQueue = new LinkedBlockingQueue<byte[]>(100);
BlockingQueue<byte[]> writeQueue = new LinkedBlockingQueue<byte[]>();
putKey(tunId, new Object[]{socketChannel, readQueue, writeQueue});
if (newThread) {
new Thread(new Suo5(tunId, 1)).start();
new Thread(new Suo5(tunId, 2)).start();
}
} catch (Exception e) {
if (socketChannel != null) {
try {
socketChannel.close();
} catch (Exception ignore) {
}
}
resultData = newStatus(tunId, (byte) 0x01);
}
baos.write(marshalBase64(resultData));
return baos.toByteArray();
}
private void performWrite(HashMap dataMap, String tunId, boolean newThread) throws Exception {
Object[] objs = (Object[]) getKey(tunId);
if (objs == null) {
throw new IOException("tunnel not found");
}
SocketChannel sc = (SocketChannel) objs[0];
if (!sc.isOpen()) {
return;
}
byte[] data = (byte[]) dataMap.get("dt");
if (data.length != 0) {
if (newThread) {
BlockingQueue<byte[]> writeQueue = (BlockingQueue<byte[]>) objs[2];
writeQueue.put(data);
} else {
ByteBuffer buf = ByteBuffer.wrap(data);
while (buf.hasRemaining()) {
sc.write(buf);
}
}
}
}
private byte[] performRead(String tunId) throws Exception {
Object[] objs = (Object[]) getKey(tunId);
if (objs == null) {
throw new IOException("tunnel not found");
}
SocketChannel sc = (SocketChannel) objs[0];
BlockingQueue<byte[]> readQueue = (BlockingQueue<byte[]>) objs[1];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int maxSize = 512 * 1024;
int written = 0;
while (true) {
byte[] data = readQueue.poll();
if (data != null) {
written += data.length;
baos.write(marshalBase64(newData(tunId, data)));
if (written >= maxSize) {
break;
}
} else {
break;
}
}
if (!sc.isOpen() && readQueue.isEmpty()) {
performDelete(tunId);
baos.write(marshalBase64(newDel(tunId)));
}
return baos.toByteArray();
}
private void performDelete(String tunId) {
Object[] objs = (Object[]) getKey(tunId);
if (objs != null) {
removeKey(tunId);
SocketChannel sc = (SocketChannel) objs[0];
BlockingQueue<byte[]> writeQueue = (BlockingQueue<byte[]>) objs[2];
try {
writeQueue.put(new byte[0]);
sc.close();
} catch (Exception ignore) {
}
}
}
private int getServerPort(SimpleRequest request) {
return request.getLocalPort();
}
private void pipeStream(InputStream inputStream, OutputStream outputStream, SimpleResponse resp, boolean needMarshal) throws Exception {
try {
byte[] readBuf = new byte[1024 * 8];
while (true) {
int n = inputStream.read(readBuf);
if (n <= 0) {
break;
}
byte[] dataTmp = copyOfRange(readBuf, 0, n);
if (needMarshal) {
dataTmp = marshalBase64(newData(this.gtunId, dataTmp));
}
outputStream.write(dataTmp);
outputStream.flush();
if (resp != null) {
resp.flushBuffer();
}
}
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (Exception ignore) {
}
}
}
}
private byte[] readSocketChannel(SocketChannel socketChannel, ByteBuffer buffer) throws IOException {
buffer.clear();
int bytesRead = socketChannel.read(buffer);
if (bytesRead <= 0) {
return new byte[0];
}
buffer.flip();
byte[] data = new byte[buffer.remaining()];
buffer.get(data);
return data;
}
private static HashMap collectAddr() {
HashMap addrs = new HashMap();
try {
Enumeration nifs = NetworkInterface.getNetworkInterfaces();
while (nifs.hasMoreElements()) {
NetworkInterface nif = (NetworkInterface) nifs.nextElement();
Enumeration addresses = nif.getInetAddresses();
while (addresses.hasMoreElements()) {
InetAddress addr = (InetAddress) addresses.nextElement();
String s = addr.getHostAddress();
if (s != null) {
int ifaceIndex = s.indexOf('%');
if (ifaceIndex != -1) {
s = s.substring(0, ifaceIndex);
}
addrs.put(s, Boolean.TRUE);
}
}
}
} catch (Exception e) {
}
return addrs;
}
private boolean isLocalAddr(String url) throws Exception {
String ip = (new URL(url)).getHost();
return addrs.containsKey(ip);
}
private HttpURLConnection redirect(SimpleRequest request, String rUrl, byte[] body) throws Exception {
String method = request.getMethod();
URL u = new URL(rUrl);
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
conn.setRequestMethod(method);
conn.setConnectTimeout(3000);
conn.setReadTimeout(0);
conn.setDoOutput(true);
conn.setDoInput(true);
if (HttpsURLConnection.class.isInstance(conn)) {
((HttpsURLConnection) conn).setHostnameVerifier(this);
SSLContext sslCtx = SSLContext.getInstance("SSL");
sslCtx.init(null, new TrustManager[]{this}, null);
((HttpsURLConnection) conn).setSSLSocketFactory(sslCtx.getSocketFactory());
}
Enumeration headers = request.getHeaderNames();
while (headers.hasMoreElements()) {
String k = (String) headers.nextElement();
if (k.equalsIgnoreCase("Content-Length")) {
conn.setRequestProperty(k, String.valueOf(body.length));
} else if (k.equalsIgnoreCase("Host")) {
conn.setRequestProperty(k, u.getHost());
} else if (k.equalsIgnoreCase("Connection")) {
conn.setRequestProperty(k, "close");
} else if (k.equalsIgnoreCase("Content-Encoding") || k.equalsIgnoreCase("Transfer-Encoding")) {
continue;
} else {
conn.setRequestProperty(k, request.getHeader(k));
}
}
OutputStream rout = conn.getOutputStream();
rout.write(body);
rout.flush();
rout.close();
conn.getResponseCode();
return conn;
}
private byte[] toByteArray(InputStream in) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int len;
while ((len = in.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
return baos.toByteArray();
} catch (IOException var5) {
return new byte[0];
}
}
private void readFull(InputStream is, byte[] b) throws IOException {
int bufferOffset = 0;
while (bufferOffset < b.length) {
int readLength = b.length - bufferOffset;
int readResult = is.read(b, bufferOffset, readLength);
if (readResult == -1) {
throw new IOException("stream EOF");
}
bufferOffset += readResult;
}
}
public HashMap newDirtyChunk(int size) {
HashMap m = new HashMap();
m.put("ac", new byte[]{0x11});
if (size > 0) {
byte[] data = new byte[size];
new Random().nextBytes(data);
m.put("d", data);
}
return m;
}
private HashMap newData(String tunId, byte[] data) {
HashMap m = new HashMap();
m.put("ac", new byte[]{0x01});
m.put("dt", data);
m.put("id", tunId.getBytes());
return m;
}
private HashMap newDel(String tunId) {
HashMap m = new HashMap();
m.put("ac", new byte[]{0x02});
m.put("id", tunId.getBytes());
return m;
}
private HashMap newStatus(String tunId, byte b) {
HashMap m = new HashMap();
m.put("ac", new byte[]{0x03});
m.put("s", new byte[]{b});
m.put("id", tunId.getBytes());
return m;
}
private HashMap newHeartbeat(String tunId) {
HashMap m = new HashMap();
m.put("ac", new byte[]{0x10});
m.put("id", tunId.getBytes());
return m;
}
private byte[] u32toBytes(int i) {
byte[] result = new byte[4];
result[0] = (byte) (i >> 24);
result[1] = (byte) (i >> 16);
result[2] = (byte) (i >> 8);
result[3] = (byte) i;
return result;
}
private int bytesToU32(byte[] bytes) {
return ((bytes[0] & 0xFF) << 24)
| ((bytes[1] & 0xFF) << 16)
| ((bytes[2] & 0xFF) << 8)
| (bytes[3] & 0xFF);
}
private void putKey(String k, Object v) {
ctx.put(k, v);
}
private Object getKey(String k) {
return ctx.get(k);
}
private void removeKey(String k) {
ctx.remove(k);
}
private byte[] copyOfRange(byte[] original, int from, int to) {
int newLength = to - from;
if (newLength < 0) {
throw new IllegalArgumentException(from + " > " + to);
}
byte[] copy = new byte[newLength];
int copyLength = Math.min(original.length - from, newLength);
for (int i = 0; i < copyLength; i++) {
copy[i] = original[from + i];
}
return copy;
}
private String base64UrlEncode(byte[] bs) throws Exception {
Class base64;
String value = null;
try {
base64 = Class.forName("java.util.Base64");
Object encoder = base64.getMethod("getEncoder", new Class[0]).invoke(base64, new Object[0]);
value = (String) encoder.getClass().getMethod("encodeToString", new Class[]{byte[].class}).invoke(encoder, new Object[]{bs});
} catch (Exception e) {
try {
base64 = Class.forName("sun.misc.BASE64Encoder");
Object encoder = base64.newInstance();