Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/test/jdk/java/net/Socket/HttpProxy.java
41149 views
1
/*
2
* Copyright (c) 2010, 2019, Oracle and/or its affiliates. All rights reserved.
3
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4
*
5
* This code is free software; you can redistribute it and/or modify it
6
* under the terms of the GNU General Public License version 2 only, as
7
* published by the Free Software Foundation.
8
*
9
* This code is distributed in the hope that it will be useful, but WITHOUT
10
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12
* version 2 for more details (a copy is included in the LICENSE file that
13
* accompanied this code).
14
*
15
* You should have received a copy of the GNU General Public License version
16
* 2 along with this work; if not, write to the Free Software Foundation,
17
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18
*
19
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20
* or visit www.oracle.com if you need additional information or have any
21
* questions.
22
*/
23
24
/*
25
* @test
26
* @bug 6370908 8220663
27
* @library /test/lib
28
* @summary Add support for HTTP_CONNECT proxy in Socket class.
29
* This test uses the wildcard address and is susceptible to fail intermittently.
30
* @key intermittent
31
* @modules java.base/sun.net.www
32
* @run main HttpProxy
33
* @run main/othervm -Djava.net.preferIPv4Stack=true HttpProxy
34
* @run main/othervm -Djava.net.preferIPv6Addresses=true HttpProxy
35
*/
36
37
import java.io.IOException;
38
import java.io.InputStream;
39
import java.io.OutputStream;
40
import java.io.PrintWriter;
41
import static java.lang.System.out;
42
import java.net.InetAddress;
43
import java.net.InetSocketAddress;
44
import java.net.Proxy;
45
import java.net.ServerSocket;
46
import java.net.Socket;
47
import java.net.SocketAddress;
48
import java.util.ArrayList;
49
import java.util.List;
50
import jdk.test.lib.net.IPSupport;
51
import sun.net.www.MessageHeader;
52
53
public class HttpProxy {
54
final String proxyHost;
55
final int proxyPort;
56
static final int SO_TIMEOUT = 15000;
57
58
public static void main(String[] args) throws Exception {
59
IPSupport.throwSkippedExceptionIfNonOperational();
60
61
String host;
62
int port;
63
ConnectProxyTunnelServer proxy = null;
64
if (args.length == 0) {
65
// Start internal proxy
66
proxy = new ConnectProxyTunnelServer();
67
proxy.start();
68
host = InetAddress.getLoopbackAddress().getHostAddress();
69
port = proxy.getLocalPort();
70
out.println("Running with internal proxy: " + host + ":" + port);
71
} else if (args.length == 2) {
72
host = args[0];
73
port = Integer.valueOf(args[1]);
74
out.println("Running against specified proxy server: " + host + ":" + port);
75
} else {
76
System.err.println("Usage: java HttpProxy [<proxy host> <proxy port>]");
77
return;
78
}
79
80
try {
81
HttpProxy p = new HttpProxy(host, port);
82
p.test();
83
} finally {
84
if (proxy != null)
85
proxy.close();
86
}
87
}
88
89
public HttpProxy(String proxyHost, int proxyPort) {
90
this.proxyHost = proxyHost;
91
this.proxyPort = proxyPort;
92
}
93
94
static boolean canUseIPv6() {
95
return IPSupport.hasIPv6() && !IPSupport.preferIPv4Stack();
96
}
97
98
void test() throws Exception {
99
InetSocketAddress proxyAddress = new InetSocketAddress(proxyHost, proxyPort);
100
Proxy httpProxy = new Proxy(Proxy.Type.HTTP, proxyAddress);
101
102
// Wildcard address is needed here
103
try (ServerSocket ss = new ServerSocket(0)) {
104
List<InetSocketAddress> externalAddresses = new ArrayList<>();
105
externalAddresses.add(
106
new InetSocketAddress(InetAddress.getLocalHost(), ss.getLocalPort()));
107
108
if (canUseIPv6()) {
109
byte[] bytes = new byte[] {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};
110
var address = InetAddress.getByAddress(bytes);
111
externalAddresses.add(
112
new InetSocketAddress(address, ss.getLocalPort()));
113
}
114
115
for (SocketAddress externalAddress : externalAddresses) {
116
try (Socket sock = new Socket(httpProxy)) {
117
sock.setSoTimeout(SO_TIMEOUT);
118
sock.setTcpNoDelay(false);
119
120
out.println("Trying to connect to server socket on " + externalAddress);
121
sock.connect(externalAddress);
122
try (Socket externalSock = ss.accept()) {
123
// perform some simple checks
124
check(sock.isBound(), "Socket is not bound");
125
check(sock.isConnected(), "Socket is not connected");
126
check(!sock.isClosed(), "Socket should not be closed");
127
check(sock.getSoTimeout() == SO_TIMEOUT,
128
"Socket should have a previously set timeout");
129
check(sock.getTcpNoDelay() == false, "NODELAY should be false");
130
131
simpleDataExchange(sock, externalSock);
132
}
133
}
134
}
135
}
136
}
137
138
static void check(boolean condition, String message) {
139
if (!condition) out.println(message);
140
}
141
142
static Exception unexpected(Exception e) {
143
out.println("Unexpected Exception: " + e);
144
e.printStackTrace();
145
return e;
146
}
147
148
// performs a simple exchange of data between the two sockets
149
// and throws an exception if there is any problem.
150
void simpleDataExchange(Socket s1, Socket s2) throws Exception {
151
try (final InputStream i1 = s1.getInputStream();
152
final InputStream i2 = s2.getInputStream();
153
final OutputStream o1 = s1.getOutputStream();
154
final OutputStream o2 = s2.getOutputStream()) {
155
startSimpleWriter("simpleWriter1", o1, 100);
156
startSimpleWriter("simpleWriter2", o2, 200);
157
simpleRead(i2, 100);
158
simpleRead(i1, 200);
159
}
160
}
161
162
void startSimpleWriter(String threadName, final OutputStream os, final int start) {
163
(new Thread(new Runnable() {
164
public void run() {
165
try { simpleWrite(os, start); }
166
catch (Exception e) {unexpected(e); }
167
finally { out.println(threadName + ": done"); }
168
}}, threadName)).start();
169
}
170
171
void simpleWrite(OutputStream os, int start) throws Exception {
172
byte b[] = new byte[2];
173
for (int i=start; i<start+100; i++) {
174
b[0] = (byte) (i / 256);
175
b[1] = (byte) (i % 256);
176
os.write(b);
177
}
178
out.println("Wrote " + start + " -> " + (start + 100));
179
}
180
181
void simpleRead(InputStream is, int start) throws Exception {
182
byte b[] = new byte [2];
183
for (int i=start; i<start+100; i++) {
184
int x = is.read(b);
185
if (x == 1)
186
x += is.read(b,1,1);
187
if (x!=2)
188
throw new Exception("read error");
189
int r = bytes(b[0], b[1]);
190
if (r != i)
191
throw new Exception("read " + r + " expected " +i);
192
}
193
out.println("Read " + start + " -> " + (start + 100));
194
}
195
196
int bytes(byte b1, byte b2) {
197
int i1 = (int)b1 & 0xFF;
198
int i2 = (int)b2 & 0xFF;
199
return i1 * 256 + i2;
200
}
201
202
static class ConnectProxyTunnelServer extends Thread implements AutoCloseable {
203
204
private final ServerSocket ss;
205
private volatile boolean closed;
206
207
public ConnectProxyTunnelServer() throws IOException {
208
ss = new ServerSocket(0, 0, InetAddress.getLoopbackAddress());
209
}
210
211
@Override
212
public void run() {
213
try {
214
while (!closed) {
215
try (Socket clientSocket = ss.accept()) {
216
processRequest(clientSocket);
217
}
218
}
219
} catch (Exception e) {
220
if (!closed) {
221
out.println("Proxy Failed: " + e);
222
e.printStackTrace();
223
}
224
} finally {
225
if (!closed)
226
try { ss.close(); } catch (IOException x) { unexpected(x); }
227
}
228
}
229
230
/**
231
* Returns the port on which the proxy is accepting connections.
232
*/
233
public int getLocalPort() {
234
return ss.getLocalPort();
235
}
236
237
@Override
238
public void close() throws Exception {
239
closed = true;
240
ss.close();
241
}
242
243
/*
244
* Processes the CONNECT request
245
*/
246
private void processRequest(Socket clientSocket) throws Exception {
247
MessageHeader mheader = new MessageHeader(clientSocket.getInputStream());
248
String statusLine = mheader.getValue(0);
249
250
if (!statusLine.startsWith("CONNECT")) {
251
out.println("proxy server: processes only "
252
+ "CONNECT method requests, received: "
253
+ statusLine);
254
return;
255
}
256
257
// retrieve the host and port info from the status-line
258
InetSocketAddress serverAddr = getConnectInfo(statusLine);
259
out.println("Proxy serving CONNECT request to " + serverAddr);
260
261
//open socket to the server
262
try (Socket serverSocket = new Socket(serverAddr.getAddress(),
263
serverAddr.getPort())) {
264
Forwarder clientFW = new Forwarder(clientSocket.getInputStream(),
265
serverSocket.getOutputStream());
266
Thread clientForwarderThread = new Thread(clientFW, "ClientForwarder");
267
clientForwarderThread.start();
268
send200(clientSocket);
269
Forwarder serverFW = new Forwarder(serverSocket.getInputStream(),
270
clientSocket.getOutputStream());
271
serverFW.run();
272
clientForwarderThread.join();
273
}
274
}
275
276
private void send200(Socket clientSocket) throws IOException {
277
OutputStream out = clientSocket.getOutputStream();
278
PrintWriter pout = new PrintWriter(out);
279
280
pout.println("HTTP/1.1 200 OK");
281
pout.println();
282
pout.flush();
283
}
284
285
/*
286
* This method retrieves the hostname and port of the tunnel destination
287
* from the request line.
288
* @param connectStr
289
* of the form: <i>CONNECT server-name:server-port HTTP/1.x</i>
290
*/
291
static InetSocketAddress getConnectInfo(String connectStr)
292
throws Exception
293
{
294
try {
295
int starti = connectStr.indexOf(' ');
296
int endi = connectStr.lastIndexOf(' ');
297
String connectInfo = connectStr.substring(starti+1, endi).trim();
298
// retrieve server name and port
299
endi = connectInfo.lastIndexOf(':');
300
String name = connectInfo.substring(0, endi);
301
302
if (name.contains(":")) {
303
if (!(name.startsWith("[") && name.endsWith("]"))) {
304
throw new IOException("Invalid host:" + name);
305
}
306
name = name.substring(1, name.length() - 1);
307
}
308
int port = Integer.parseInt(connectInfo.substring(endi+1));
309
return new InetSocketAddress(name, port);
310
} catch (Exception e) {
311
out.println("Proxy received a request: " + connectStr);
312
throw unexpected(e);
313
}
314
}
315
}
316
317
/* Reads from the given InputStream and writes to the given OutputStream */
318
static class Forwarder implements Runnable
319
{
320
private final InputStream in;
321
private final OutputStream os;
322
323
Forwarder(InputStream in, OutputStream os) {
324
this.in = in;
325
this.os = os;
326
}
327
328
@Override
329
public void run() {
330
try {
331
byte[] ba = new byte[1024];
332
int count;
333
while ((count = in.read(ba)) != -1) {
334
os.write(ba, 0, count);
335
}
336
} catch (IOException e) {
337
unexpected(e);
338
}
339
}
340
}
341
}
342
343