-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
Proxy.java
77 lines (65 loc) · 2.44 KB
/
Proxy.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
package io.vertx.example.core.http.proxyconnect;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Launcher;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.net.NetClient;
import io.vertx.core.net.NetClientOptions;
import io.vertx.core.net.NetSocket;
/*
* @author <a href="http://tfox.org">Tim Fox</a>
*/
public class Proxy extends AbstractVerticle {
public static void main(String[] args) {
Launcher.executeCommand("run", Proxy.class.getName());
}
@Override
public void start() throws Exception {
NetClient client = vertx.createNetClient(new NetClientOptions());
vertx.createHttpServer().requestHandler(req -> {
if (req.method() == HttpMethod.CONNECT) {
// Determine proxied server address
String proxyAddress = req.uri();
int idx = proxyAddress.indexOf(':');
String host = proxyAddress.substring(0, idx);
int port = Integer.parseInt(proxyAddress.substring(idx + 1));
System.out.println("Connecting to proxy " + proxyAddress);
client.connect(port, host, ar -> {
if (ar.succeeded()) {
System.out.println("Connected to proxy");
NetSocket serverSocket = ar.result();
serverSocket.pause();
req.toNetSocket().onComplete(ar2 -> {
if (ar2.succeeded()) {
NetSocket clientSocket = ar2.result();
serverSocket.handler(buff -> {
System.out.println("Forwarding server packet to the client");
clientSocket.write(buff);
});
serverSocket.closeHandler(v -> {
System.out.println("Server socket closed");
clientSocket.close();
});
clientSocket.handler(buff -> {
System.out.println("Forwarding client packet to the server");
serverSocket.write(buff);
});
clientSocket.closeHandler(v -> {
System.out.println("Client socket closed");
serverSocket.close();
});
serverSocket.resume();
} else {
serverSocket.close();
}
});
} else {
System.out.println("Fail proxy connection");
req.response().setStatusCode(403).end();
}
});
} else {
req.response().setStatusCode(405).end();
}
}).listen(8080);
}
}