Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/test/jdk/sun/net/www/protocol/https/HttpsURLConnection/ProxyTunnelServer.java
41161 views
1
/*
2
* Copyright (c) 2001, 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
*
26
* This class includes a proxy server that processes HTTP CONNECT requests,
27
* and tunnels the data from the client to the server, once the CONNECT
28
* request is accepted.
29
* The proxy server processes only one transaction, i.e a CONNECT request
30
* followed by the corresponding tunnel data.
31
*/
32
33
import java.io.*;
34
import java.net.*;
35
import javax.net.ServerSocketFactory;
36
import sun.net.www.*;
37
import java.util.Base64;
38
39
public class ProxyTunnelServer extends Thread {
40
41
private static final int TIMEOUT = 30000;
42
43
private static ServerSocket ss = null;
44
/*
45
* holds the registered user's username and password
46
* only one such entry is maintained
47
*/
48
private String userPlusPass;
49
50
// client requesting for a tunnel
51
private Socket clientSocket = null;
52
53
/*
54
* Origin server's address and port that the client
55
* wants to establish the tunnel for communication.
56
*/
57
private InetAddress serverInetAddr;
58
private int serverPort;
59
60
/*
61
* denote whether the proxy needs to authorize
62
* CONNECT requests.
63
*/
64
static boolean needAuth = false;
65
66
volatile long connectCount;
67
68
public ProxyTunnelServer() throws IOException {
69
if (ss == null) {
70
ss = (ServerSocket) ServerSocketFactory.getDefault()
71
.createServerSocket(0);
72
ss.setSoTimeout(TIMEOUT);
73
System.out.println("Proxy server created: " + ss);
74
}
75
}
76
77
public ProxyTunnelServer(InetAddress address) throws IOException {
78
if (ss == null) {
79
ss = (ServerSocket) ServerSocketFactory.getDefault()
80
.createServerSocket(0, 0, address);
81
ss.setSoTimeout(TIMEOUT);
82
System.out.println("Proxy server created: " + ss);
83
}
84
}
85
86
public void needUserAuth(boolean auth) {
87
needAuth = auth;
88
}
89
90
/*
91
* register users with the proxy, by providing username and
92
* password. The username and password are used for authorizing the
93
* user when a CONNECT request is made and needAuth is set to true.
94
*/
95
public void setUserAuth(String uname, String passwd) {
96
userPlusPass = uname + ":" + passwd;
97
}
98
99
public void run() {
100
try {
101
System.out.println("Proxy server listening at: " + ss);
102
clientSocket = ss.accept();
103
System.out.println("Proxy server accepted connection: " + clientSocket);
104
processRequests();
105
} catch (SocketTimeoutException e) {
106
System.out.println(
107
"Proxy can not get response in time: " + e.getMessage());
108
} catch (Exception e) {
109
System.out.println("Proxy Failed: " + e);
110
e.printStackTrace();
111
try {
112
ss.close();
113
}
114
catch (IOException excep) {
115
System.out.println("ProxyServer close error: " + excep);
116
excep.printStackTrace();
117
}
118
} finally {
119
System.out.println("Proxy server: request served");
120
}
121
}
122
123
/*
124
* Processes the CONNECT requests, if needAuth is set to true, then
125
* the name and password are extracted from the Proxy-Authorization header
126
* of the request. They are checked against the one that is registered,
127
* if there is a match, connection is set in tunneling mode. If
128
* needAuth is set to false, Proxy-Authorization checks are not made
129
*/
130
private void processRequests() throws Exception {
131
132
InputStream in = clientSocket.getInputStream();
133
MessageHeader mheader = new MessageHeader(in);
134
String statusLine = mheader.getValue(0);
135
136
if (statusLine.startsWith("CONNECT")) {
137
synchronized(this) { connectCount++; }
138
// retrieve the host and port info from the status-line
139
retrieveConnectInfo(statusLine);
140
if (needAuth) {
141
String authInfo;
142
if ((authInfo = mheader.findValue("Proxy-Authorization"))
143
!= null) {
144
if (authenticate(authInfo)) {
145
needAuth = false;
146
System.out.println(
147
"Proxy: client authentication successful");
148
}
149
}
150
}
151
respondForConnect(needAuth);
152
153
// connection set to the tunneling mode
154
if (!needAuth) {
155
doTunnel();
156
/*
157
* done with tunneling, we process only one successful
158
* tunneling request
159
*/
160
ss.close();
161
} else {
162
// we may get another request with Proxy-Authorization set
163
in.close();
164
clientSocket.close();
165
restart();
166
}
167
} else {
168
System.out.println("proxy server: processes only "
169
+ "CONNECT method requests, recieved: "
170
+ statusLine);
171
}
172
}
173
174
public long getConnectCount() {
175
return connectCount;
176
}
177
178
private void respondForConnect(boolean needAuth) throws Exception {
179
180
OutputStream out = clientSocket.getOutputStream();
181
PrintWriter pout = new PrintWriter(out);
182
183
if (needAuth) {
184
pout.println("HTTP/1.1 407 Proxy Auth Required");
185
pout.println("Proxy-Authenticate: Basic realm=\"WallyWorld\"");
186
pout.println();
187
pout.flush();
188
out.close();
189
} else {
190
pout.println("HTTP/1.1 200 OK");
191
pout.println();
192
pout.flush();
193
}
194
}
195
196
private void restart() throws IOException {
197
(new Thread(this)).start();
198
}
199
200
/*
201
* note: Tunneling has to be provided in both directions, i.e
202
* from client->server and server->client, even if the application
203
* data may be unidirectional, SSL handshaking data flows in either
204
* direction.
205
*/
206
private void doTunnel() throws Exception {
207
208
Socket serverSocket = new Socket(serverInetAddr, serverPort);
209
ProxyTunnel clientToServer = new ProxyTunnel(
210
clientSocket, serverSocket);
211
ProxyTunnel serverToClient = new ProxyTunnel(
212
serverSocket, clientSocket);
213
clientToServer.start();
214
serverToClient.start();
215
System.out.println("Proxy: Started tunneling.......");
216
217
clientToServer.join(TIMEOUT);
218
serverToClient.join(TIMEOUT);
219
System.out.println("Proxy: Finished tunneling........");
220
221
clientToServer.close();
222
serverToClient.close();
223
}
224
225
/*
226
* This inner class provides unidirectional data flow through the sockets
227
* by continuously copying bytes from the input socket onto the output
228
* socket, until both sockets are open and EOF has not been received.
229
*/
230
class ProxyTunnel extends Thread {
231
Socket sockIn;
232
Socket sockOut;
233
InputStream input;
234
OutputStream output;
235
236
public ProxyTunnel(Socket sockIn, Socket sockOut)
237
throws Exception {
238
this.sockIn = sockIn;
239
this.sockOut = sockOut;
240
input = sockIn.getInputStream();
241
output = sockOut.getOutputStream();
242
}
243
244
public void run() {
245
int BUFFER_SIZE = 400;
246
byte[] buf = new byte[BUFFER_SIZE];
247
int bytesRead = 0;
248
249
try {
250
while ((bytesRead = input.read(buf)) >= 0) {
251
output.write(buf, 0, bytesRead);
252
output.flush();
253
}
254
} catch (IOException e) {
255
/*
256
* The peer end has closed the connection
257
* we will close the tunnel
258
*/
259
close();
260
}
261
}
262
263
private void close() {
264
try {
265
if (!sockIn.isClosed())
266
sockIn.close();
267
if (!sockOut.isClosed())
268
sockOut.close();
269
} catch (IOException ignored) { }
270
}
271
}
272
273
/*
274
***************************************************************
275
* helper methods follow
276
***************************************************************
277
*/
278
279
/*
280
* This method retrieves the hostname and port of the destination
281
* that the connect request wants to establish a tunnel for
282
* communication.
283
* The input, connectStr is of the form:
284
* CONNECT server-name:server-port HTTP/1.x
285
*/
286
private void retrieveConnectInfo(String connectStr) throws Exception {
287
288
int starti;
289
int endi;
290
String connectInfo;
291
String serverName = null;
292
try {
293
starti = connectStr.indexOf(' ');
294
endi = connectStr.lastIndexOf(' ');
295
connectInfo = connectStr.substring(starti+1, endi).trim();
296
// retrieve server name and port
297
if (connectInfo.charAt(0) == '[') {
298
endi = connectInfo.indexOf(']');
299
serverName = connectInfo.substring(1, endi++);
300
assert connectInfo.charAt(endi) == ':' : "Expected [IPv6]:port";
301
} else {
302
endi = connectInfo.indexOf(':');
303
serverName = connectInfo.substring(0, endi);
304
}
305
serverPort = Integer.parseInt(connectInfo.substring(endi+1));
306
} catch (Exception e) {
307
throw new IOException("Proxy recieved a request: "
308
+ connectStr, e);
309
}
310
serverInetAddr = InetAddress.getByName(serverName);
311
}
312
313
public int getPort() {
314
return ss.getLocalPort();
315
}
316
317
/*
318
* do "basic" authentication, authInfo is of the form:
319
* Basic <encoded username":"password>
320
* reference RFC 2617
321
*/
322
private boolean authenticate(String authInfo) throws IOException {
323
boolean matched = false;
324
try {
325
authInfo.trim();
326
int ind = authInfo.indexOf(' ');
327
String recvdUserPlusPass = authInfo.substring(ind + 1).trim();
328
// extract encoded (username:passwd
329
if (userPlusPass.equals(
330
new String( Base64.getMimeDecoder()
331
.decode(recvdUserPlusPass))))
332
{
333
matched = true;
334
}
335
} catch (Exception e) {
336
throw new IOException(
337
"Proxy received invalid Proxy-Authorization value: "
338
+ authInfo);
339
}
340
return matched;
341
}
342
}
343
344