-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathiOSSSLSocketFactory.swift
More file actions
367 lines (307 loc) · 11.4 KB
/
iOSSSLSocketFactory.swift
File metadata and controls
367 lines (307 loc) · 11.4 KB
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
///
/// iOSSSLSocketFactory.swift
///
/// An SSLSocketFactory for j2objc that uses the native iOS SecureTransport API
///
/// - Author: Florian Draschbacher
/// - Copyright: © 2018 Florian Draschbacher. All rights reserved.
///
/// 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.
import Foundation
import Security
private func throwIOException(description: String, status: OSStatus){
var statusDescription = "Error \(status)"
if #available(iOS 11.3, *) {
statusDescription = SecCopyErrorMessageString(status, nil)! as String
}
ObjC.throwException(JavaIoIOException(nsString: description + String(status) +
" - " + statusDescription))
}
func synchronize<T>(on object: Any, block: () throws -> T) rethrows -> T {
objc_sync_enter(object)
defer {
objc_sync_exit(object)
}
return try block()
}
class iOSSSLInputStream : JavaIoInputStream {
unowned let sslSocket : iOSSSLSocket
init(sslSocket: iOSSSLSocket) {
self.sslSocket = sslSocket
super.init()
}
override func read(with b: IOSByteArray!, with off: jint, with len: jint) -> jint {
let bufferPointer = UnsafeMutableRawPointer(b.byteRef(at: UInt(off)))
var actuallyRead : Int = 0
var status = noErr
synchronize(on: self.sslSocket) {
repeat {
status = SSLRead(sslSocket.getSSLContext()!, bufferPointer!, Int(len), &actuallyRead)
} while (status == errSSLWouldBlock && actuallyRead == 0)
}
if (status == errSecSuccess || status == errSSLWouldBlock){
return jint(actuallyRead)
} else {
if let exception = sslSocket.underlyingException {
ObjC.throwException(exception)
}
throwIOException(description: "Error reading from SSL: ", status: status)
}
return jint(actuallyRead)
}
override func read(with b: IOSByteArray!) -> jint {
return read(with: b, with: 0, with: b.length())
}
override func read() -> jint {
let buffer = IOSByteArray.newArray(withLength: 1)
let actuallyRead = read(with: buffer)
if (actuallyRead == 1) {
let resultByte: jbyte = (buffer?.byte(at: 0))!
return jint(resultByte)
} else {
return actuallyRead
}
}
override func close() {
sslSocket.close()
}
override func available() -> jint {
// Not supported
ObjC.throwException(JavaIoIOException(nsString: "Available is not supported"))
return -1;
}
override func mark(with readlimit: jint) {
// Not supported
}
override func markSupported() -> jboolean {
return false
}
override func reset() {
// Not supported
}
override func skip(withLong n: jlong) -> jlong {
// Not supported
return 0
}
}
class iOSSSLOutputStream : JavaIoOutputStream {
unowned let sslSocket: iOSSSLSocket
init(sslSocket: iOSSSLSocket) {
self.sslSocket = sslSocket
super.init()
}
override func write(with b: IOSByteArray!, with off: jint, with len: jint) {
var bufferPointer = UnsafeMutableRawPointer(b.byteRef(at: UInt(off)))
var actuallyWritten: Int = 0
var remaining: Int = Int(len);
while (remaining > 0) {
var status = noErr
synchronize(on: self.sslSocket) {
status = SSLWrite(self.sslSocket.getSSLContext()!, bufferPointer, remaining,
&actuallyWritten)
}
if (status == noErr || status == errSSLWouldBlock){
bufferPointer = bufferPointer?.advanced(by: actuallyWritten)
remaining -= actuallyWritten
} else {
if let exception = sslSocket.underlyingException {
ObjC.throwException(exception)
}
throwIOException(description: "Error writing to SSL: ", status: status)
}
}
}
override func write(with b: IOSByteArray!) {
write(with: b, with: 0, with: b.length())
}
override func write(with b: jint) {
let buffer = IOSByteArray.newArray(withLength: 1)
buffer?.replaceByte(at: 0, withByte: jbyte(b))
write(with: buffer)
}
override func close() {
sslSocket.close()
}
override func flush() {
// The framework keeps SSL caches for reading and writing.
// Whenever a call to SSLWrite returns errSSLWouldBlock, the data has been
// copied to the cache, but not yet (completely) sent. In order to flush
// this cache, we have to call SSLWrite on an empty buffer.
var status: OSStatus = noErr
var actuallyWritten: Int = 0
synchronize(on: self.sslSocket) {
repeat {
status = SSLWrite(sslSocket.getSSLContext()!, nil, 0, &actuallyWritten)
} while (status == errSSLWouldBlock)
}
sslSocket.getUnderlyingSocket().getOutputStream().flush()
}
}
class iOSSSLSocket: UVDWrappedSSLSocket{
var sslContext: SSLContext?
var inputStream: iOSSSLInputStream?
var outputStream: iOSSSLOutputStream?
var underlyingSocket: JavaNetSocket?
var underlyingException: JavaLangException?
init(underlyingSocket: JavaNetSocket, hostName: String) {
self.underlyingSocket = underlyingSocket
self.sslContext = SSLCreateContext(nil, SSLProtocolSide.clientSide,
SSLConnectionType.streamType)
super.init(javaNetSocket: underlyingSocket)
self.inputStream = iOSSSLInputStream(sslSocket: self)
self.outputStream = iOSSSLOutputStream(sslSocket: self)
var status = noErr
status = SSLSetIOFuncs(sslContext!, sslReadCallback, sslWriteCallback)
if (status != noErr) {
throwIOException(description: "Error setting IO functions: ", status: status)
}
let connectionRef: SSLConnectionRef = UnsafeRawPointer(
Unmanaged.passUnretained(self).toOpaque())
status = SSLSetConnection(sslContext!, connectionRef)
if (status != noErr) {
throwIOException(description: "Error setting connection data: ", status: status)
}
status = SSLSetPeerDomainName(sslContext!, hostName,
hostName.lengthOfBytes(using: String.Encoding.utf8))
if (status != noErr) {
throwIOException(description: "Error setting domain name: ", status: status)
}
}
override func startHandshake() {
var status = noErr
synchronize(on: self) {
repeat {
status = SSLHandshake(sslContext!)
} while (status == errSSLWouldBlock)
}
if (status != noErr) {
throwIOException(description: "Handshake error: ", status: status)
}
}
func getSSLContext() -> SSLContext?{
return sslContext
}
override func close() {
if (isClosed()) {
ObjC.throwException(JavaIoIOException(nsString: "Already closed"))
}
var status = noErr
synchronize(on: self) {
status = SSLClose(sslContext!)
}
if (status != noErr) {
throwIOException(description: "Closing error: ", status: status)
}
underlyingSocket?.close()
}
override func getInputStream() -> JavaIoInputStream! {
return inputStream
}
override func getOutputStream() -> JavaIoOutputStream! {
return outputStream
}
}
private func sslReadCallback(connection: SSLConnectionRef, data: UnsafeMutableRawPointer,
dataLength: UnsafeMutablePointer<Int>) -> OSStatus {
let socket = Unmanaged<iOSSSLSocket>.fromOpaque(connection).takeUnretainedValue()
var status = noErr
do {
// The SecureTransport API sometimes requests data from the
// callback even if it still has application data in its buffer. If we would
// blindly read from the underlying (blocking) socket in that case, the
// application layer would only get the data from the SecureTransport buffer
// after the blocking read on the underlying socket returns, which in some
// cases means we'd have to wait for the timeout to kick in.
// By letting the SecureTransport API know we don't have any more data
// at this point, we can force it to deplete its internal buffer of application
// data.
var available: jint = -1
do {
try ObjC.catchException {
available = socket.getUnderlyingSocket().getInputStream().available()
}
} catch {}
if (available == 0) {
// The underlying socket supports available() and reported that no data is
// available.
dataLength.pointee = 0
status = errSSLWouldBlock
} else {
try ObjC.catchException {
let askedToRead = dataLength.pointee
let javaByteBuffer = IOSByteArray.newArray(withLength: UInt(dataLength.pointee))
let actuallyRead = socket.getUnderlyingSocket().getInputStream().read(with: javaByteBuffer)
if (actuallyRead == 0) {
// This case shouldn't actually happen
dataLength.pointee = 0
status = errSSLWouldBlock
} else if (actuallyRead > 0) {
let jbytePointer = data.bindMemory(to: jbyte.self, capacity: dataLength.pointee)
javaByteBuffer?.getBytes(jbytePointer, length:UInt(actuallyRead))
dataLength.pointee = Int(actuallyRead)
// Important: Return errSSLWouldBlock if we didn't read exactly as much as requested
status = actuallyRead < askedToRead ? errSSLWouldBlock : noErr
} else {
status = errSSLClosedAbort
}
}
}
} catch let error as NSError {
if let exception = error.userInfo["exception"] {
socket.underlyingException = exception as? JavaLangException
}
status = errSSLInternal
}
return status
}
private func sslWriteCallback(connection: SSLConnectionRef, data: UnsafeRawPointer,
dataLength: UnsafeMutablePointer<Int>) -> OSStatus {
let socket = Unmanaged<iOSSSLSocket>.fromOpaque(connection).takeUnretainedValue()
let jbytePointer = data.bindMemory(to: jbyte.self, capacity: dataLength.pointee)
let javaByteBuffer = IOSByteArray.newArray(withBytes:jbytePointer,
count: UInt(dataLength.pointee))
do {
try ObjC.catchException {
socket.getUnderlyingSocket().getOutputStream().write(with: javaByteBuffer)
socket.getUnderlyingSocket().getOutputStream().flush()
}
} catch let error as NSError {
if let exception = error.userInfo["exception"] {
socket.underlyingException = exception as? JavaLangException
}
return errSSLInternal
}
return noErr
}
class iOSSSLSocketFactory : JavaxNetSslSSLSocketFactory{
override func createSocket(with s: JavaNetSocket!, with host: String!,
with port: jint, withBoolean autoClose: jboolean) -> JavaNetSocket! {
return iOSSSLSocket(underlyingSocket: s, hostName: host)
}
override func createSocket() -> JavaNetSocket! {
// Not implemented
return nil
}
override func createSocket(with host: String!, with port: jint) -> JavaNetSocket! {
// Not implemented
return nil
}
override func getSupportedCipherSuites() -> IOSObjectArray! {
// Not implemented
return nil
}
override func getDefaultCipherSuites() -> IOSObjectArray! {
// Not implemented
return nil
}
}