-
Notifications
You must be signed in to change notification settings - Fork 0
/
AppHTTPProxyProvider.swift
166 lines (129 loc) · 5.51 KB
/
AppHTTPProxyProvider.swift
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
import NetworkExtension
import CocoaAsyncSocket
struct HTTPProxySet {
var host: String
var port: UInt16
}
var proxy = HTTPProxySet(host: "127.0.0.1", port: 1080)
class AppProxyProvider: NEAppProxyProvider {
override func startProxy(options: [String : Any]? = nil, completionHandler: @escaping (Error?) -> Void) {
// Add code here to start the process of connecting the tunnel.
print("start")
completionHandler(nil)
}
override func stopProxy(with reason: NEProviderStopReason, completionHandler: @escaping () -> Void) {
// Add code here to start the process of stopping the tunnel.
print("stop")
completionHandler()
}
override func handleAppMessage(_ messageData: Data, completionHandler: ((Data?) -> Void)?) {
// Add code here to handle the message.
print("")
if let handler = completionHandler {
handler(messageData)
}
}
override func sleep(completionHandler: @escaping() -> Void) {
// Add code here to get ready to sleep.
completionHandler()
}
override func wake() {
// Add code here to wake up.
}
override func handleNewFlow(_ flow: NEAppProxyFlow) -> Bool {
// Add code here to handle the incoming flow.
if let TCPFlow = flow as? NEAppProxyTCPFlow {
let conn = ClientAppHTTPProxyConnection(flow: TCPFlow)
conn.open()
}
return false
}
}
/// An object representing the client side of a logical flow of network data in the SimpleTunnel tunneling protocol.
class ClientAppHTTPProxyConnection : NSObject, GCDAsyncSocketDelegate {
// MARK: Constants
let bufferSize: UInt = 4096
let timeout = 30.0
let pattern = "\n\n".data(using: .utf8)
// MARK: Properties
/// The NEAppProxyFlow object corresponding to this connection.
let TCPFlow: NEAppProxyTCPFlow
// MARK: Initializers
var sock: GCDAsyncSocket!
init(flow: NEAppProxyTCPFlow) {
TCPFlow = flow
}
func open() {
sock = GCDAsyncSocket(delegate: self, delegateQueue: DispatchQueue.main)
do {
try sock.connect(toHost: proxy.host, onPort: proxy.port, withTimeout: 3.0)
} catch {
TCPFlow.closeReadWithError(
NSError(domain: NEAppProxyErrorDomain,
code: NEAppProxyFlowError.notConnected.rawValue,
userInfo: nil
)
)
return
}
}
func socket(_ sock: GCDAsyncSocket, didConnectToHost host:String, port p:UInt16) {
print("Connected to \(host) on port \(p).")
let remoteHost = (TCPFlow.remoteEndpoint as! NWHostEndpoint).hostname
let remotePort = (TCPFlow.remoteEndpoint as! NWHostEndpoint).port
// 1. send CONNECT
// CONNECT www.google.com:80 HTTP/1.1
sock.write(
"CONNECT \(remoteHost):\(remotePort) HTTP/1.1\n\n".data(using: .utf8),
withTimeout: timeout,
tag: 1)
}
func didReadFlow(data: Data?, error: Error?) -> Void {
// 7. did read from flow
// 8. write flow data to proxy
sock.write(data, withTimeout: timeout, tag: 0)
// 9. keep reading from flow
TCPFlow.readData(completionHandler: self.didReadFlow)
}
func socket(_ sock: GCDAsyncSocket, didWriteDataWithTag tag: Int) {
if tag == 1 {
// 2. CONNECT header sent
// 3. begin to read from proxy server
sock.readData(toLength: bufferSize, withTimeout: timeout, tag: 1)
}
}
func socket(_ sock: GCDAsyncSocket, didRead data: Data, withTag tag: Int) {
if tag == 1 {
// 4. read 1st proxy server response of CONNECT
let range = data.range(of:pattern!,
options: NSData.SearchOptions(rawValue: 0),
in: 0..<data.count)
if range != nil {
let ret = data.range(of: "\r\n\r\n".data(using: .utf8)!,
options: NSData.SearchOptions(rawValue: 0),
in: 0..<range!.lowerBound)
if ret != nil {
let loc = range?.upperBound
if data.count > loc! {
// 5. write to flow if there is data already
let left_data = data[loc! ..< data.count]
TCPFlow.write(left_data, withCompletionHandler: { error in })
}
// 6. begin to read from Flow
TCPFlow.readData(completionHandler: self.didReadFlow)
// 6.5 keep reading from proxy server
sock.readData(toLength: bufferSize, withTimeout: timeout, tag: 0)
return
}
}
// Error: CONNECT failed
TCPFlow.closeReadWithError(NSError(domain: NEAppProxyErrorDomain, code: NEAppProxyFlowError.notConnected.rawValue, userInfo: nil))
sock.disconnect()
return
}
// 10. writing any data followed to flow
TCPFlow.write(data, withCompletionHandler: { error in })
// 11. keep reading from proxy server
sock.readData(toLength: bufferSize, withTimeout: timeout, tag: 0)
}
}