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
|
/**
* Copyright (c) 2013, The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.proxyhandler;
import android.os.RemoteException;
import android.util.Log;
import com.android.net.IProxyPortListener;
import com.google.android.collect.Lists;
import com.google.android.collect.Sets;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @hide
*/
public class ProxyServer extends Thread {
private static final String CONNECT = "CONNECT";
private static final String HTTP_OK = "HTTP/1.1 200 OK\n";
private static final String TAG = "ProxyServer";
// HTTP Headers
private static final String HEADER_CONNECTION = "connection";
private static final String HEADER_PROXY_CONNECTION = "proxy-connection";
private ExecutorService threadExecutor;
public boolean mIsRunning = false;
private ServerSocket serverSocket;
private int mPort;
private IProxyPortListener mCallback;
private class ProxyConnection implements Runnable {
private Socket connection;
private ProxyConnection(Socket connection) {
this.connection = connection;
}
@Override
public void run() {
try {
String requestLine = getLine(connection.getInputStream());
String[] splitLine = requestLine.split(" ");
if (splitLine.length < 3) {
connection.close();
return;
}
String requestType = splitLine[0];
String urlString = splitLine[1];
String httpVersion = splitLine[2];
URI url = null;
String host;
int port;
if (requestType.equals(CONNECT)) {
String[] hostPortSplit = urlString.split(":");
host = hostPortSplit[0];
// Use default SSL port if not specified. Parse it otherwise
if (hostPortSplit.length < 2) {
port = 443;
} else {
try {
port = Integer.parseInt(hostPortSplit[1]);
} catch (NumberFormatException nfe) {
connection.close();
return;
}
}
urlString = "Https://" + host + ":" + port;
} else {
try {
url = new URI(urlString);
host = url.getHost();
port = url.getPort();
if (port < 0) {
port = 80;
}
} catch (URISyntaxException e) {
connection.close();
return;
}
}
List<Proxy> list = Lists.newArrayList();
try {
list = ProxySelector.getDefault().select(new URI(urlString));
} catch (URISyntaxException e) {
e.printStackTrace();
}
Socket server = null;
for (Proxy proxy : list) {
try {
if (!proxy.equals(Proxy.NO_PROXY)) {
// Only Inets created by PacProxySelector.
InetSocketAddress inetSocketAddress =
(InetSocketAddress)proxy.address();
server = new Socket(inetSocketAddress.getHostName(),
inetSocketAddress.getPort());
sendLine(server, requestLine);
} else {
server = new Socket(host, port);
if (requestType.equals(CONNECT)) {
skipToRequestBody(connection);
// No proxy to respond so we must.
sendLine(connection, HTTP_OK);
} else {
// Proxying the request directly to the origin server.
sendAugmentedRequestToHost(connection, server,
requestType, url, httpVersion);
}
}
} catch (IOException ioe) {
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.v(TAG, "Unable to connect to proxy " + proxy, ioe);
}
}
if (server != null) {
break;
}
}
if (list.isEmpty()) {
server = new Socket(host, port);
if (requestType.equals(CONNECT)) {
skipToRequestBody(connection);
// No proxy to respond so we must.
sendLine(connection, HTTP_OK);
} else {
// Proxying the request directly to the origin server.
sendAugmentedRequestToHost(connection, server,
requestType, url, httpVersion);
}
}
// Pass data back and forth until complete.
if (server != null) {
SocketConnect.connect(connection, server);
}
} catch (Exception e) {
Log.d(TAG, "Problem Proxying", e);
}
try {
connection.close();
} catch (IOException ioe) {
// Do nothing
}
}
/**
* Sends HTTP request-line (i.e. the first line in the request)
* that contains absolute path of a given absolute URI.
*
* @param server server to send the request to.
* @param requestType type of the request, a.k.a. HTTP method.
* @param absoluteUri absolute URI which absolute path should be extracted.
* @param httpVersion version of HTTP, e.g. HTTP/1.1.
* @throws IOException if the request-line cannot be sent.
*/
private void sendRequestLineWithPath(Socket server, String requestType,
URI absoluteUri, String httpVersion) throws IOException {
String absolutePath = getAbsolutePathFromAbsoluteURI(absoluteUri);
String outgoingRequestLine = String.format("%s %s %s",
requestType, absolutePath, httpVersion);
sendLine(server, outgoingRequestLine);
}
/**
* Extracts absolute path form a given URI. E.g., passing
* <code>http://google.com:80/execute?query=cat#top</code>
* will result in <code>/execute?query=cat#top</code>.
*
* @param uri URI which absolute path has to be extracted,
* @return the absolute path of the URI,
*/
private String getAbsolutePathFromAbsoluteURI(URI uri) {
String rawPath = uri.getRawPath();
String rawQuery = uri.getRawQuery();
String rawFragment = uri.getRawFragment();
StringBuilder absolutePath = new StringBuilder();
if (rawPath != null) {
absolutePath.append(rawPath);
} else {
absolutePath.append("/");
}
if (rawQuery != null) {
absolutePath.append("?").append(rawQuery);
}
if (rawFragment != null) {
absolutePath.append("#").append(rawFragment);
}
return absolutePath.toString();
}
private String getLine(InputStream inputStream) throws IOException {
StringBuilder buffer = new StringBuilder();
int byteBuffer = inputStream.read();
if (byteBuffer < 0) return "";
do {
if (byteBuffer != '\r') {
buffer.append((char)byteBuffer);
}
byteBuffer = inputStream.read();
} while ((byteBuffer != '\n') && (byteBuffer >= 0));
return buffer.toString();
}
private void sendLine(Socket socket, String line) throws IOException {
OutputStream os = socket.getOutputStream();
os.write(line.getBytes());
os.write('\r');
os.write('\n');
os.flush();
}
/**
* Reads from socket until an empty line is read which indicates the end of HTTP headers.
*
* @param socket socket to read from.
* @throws IOException if an exception took place during the socket read.
*/
private void skipToRequestBody(Socket socket) throws IOException {
while (getLine(socket.getInputStream()).length() != 0);
}
/**
* Sends an augmented request to the final host (DIRECT connection).
*
* @param src socket to read HTTP headers from.The socket current position should point
* to the beginning of the HTTP header section.
* @param dst socket to write the augmented request to.
* @param httpMethod original request http method.
* @param uri original request absolute URI.
* @param httpVersion original request http version.
* @throws IOException if an exception took place during socket reads or writes.
*/
private void sendAugmentedRequestToHost(Socket src, Socket dst,
String httpMethod, URI uri, String httpVersion) throws IOException {
sendRequestLineWithPath(dst, httpMethod, uri, httpVersion);
filterAndForwardRequestHeaders(src, dst);
// Currently the proxy does not support keep-alive connections; therefore,
// the proxy has to request the destination server to close the connection
// after the destination server sent the response.
sendLine(dst, "Connection: close");
// Sends and empty line that indicates termination of the header section.
sendLine(dst, "");
}
/**
* Forwards original request headers filtering out the ones that have to be removed.
*
* @param src source socket that contains original request headers.
* @param dst destination socket to send the filtered headers to.
* @throws IOException if the data cannot be read from or written to the sockets.
*/
private void filterAndForwardRequestHeaders(Socket src, Socket dst) throws IOException {
String line;
do {
line = getLine(src.getInputStream());
if (line.length() > 0 && !shouldRemoveHeaderLine(line)) {
sendLine(dst, line);
}
} while (line.length() > 0);
}
/**
* Returns true if a given header line has to be removed from the original request.
*
* @param line header line that should be analysed.
* @return true if the header line should be removed and not forwarded to the destination.
*/
private boolean shouldRemoveHeaderLine(String line) {
int colIndex = line.indexOf(":");
if (colIndex != -1) {
String headerName = line.substring(0, colIndex).trim();
if (headerName.regionMatches(true, 0, HEADER_CONNECTION, 0,
HEADER_CONNECTION.length())
|| headerName.regionMatches(true, 0, HEADER_PROXY_CONNECTION,
0, HEADER_PROXY_CONNECTION.length())) {
return true;
}
}
return false;
}
}
public ProxyServer() {
threadExecutor = Executors.newCachedThreadPool();
mPort = -1;
mCallback = null;
}
@Override
public void run() {
try {
serverSocket = new ServerSocket(0);
setPort(serverSocket.getLocalPort());
while (mIsRunning) {
try {
Socket socket = serverSocket.accept();
// Only receive local connections.
if (socket.getInetAddress().isLoopbackAddress()) {
ProxyConnection parser = new ProxyConnection(socket);
threadExecutor.execute(parser);
} else {
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (SocketException e) {
Log.e(TAG, "Failed to start proxy server", e);
} catch (IOException e1) {
Log.e(TAG, "Failed to start proxy server", e1);
}
mIsRunning = false;
}
public synchronized void setPort(int port) {
if (mCallback != null) {
try {
mCallback.setProxyPort(port);
} catch (RemoteException e) {
Log.w(TAG, "Proxy failed to report port to PacManager", e);
}
}
mPort = port;
}
public synchronized void setCallback(IProxyPortListener callback) {
if (mPort != -1) {
try {
callback.setProxyPort(mPort);
} catch (RemoteException e) {
Log.w(TAG, "Proxy failed to report port to PacManager", e);
}
}
mCallback = callback;
}
public synchronized void startServer() {
mIsRunning = true;
start();
}
public synchronized void stopServer() {
mIsRunning = false;
if (serverSocket != null) {
try {
serverSocket.close();
serverSocket = null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
public boolean isBound() {
return (mPort != -1);
}
public int getPort() {
return mPort;
}
}
|