@capgo/capacitor-updater 9.0.2 → 9.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdaterPlugin.java +9 -1
- package/android/src/main/java/ee/forgr/capacitor_updater/CryptoCipher.java +10 -2
- package/android/src/main/java/ee/forgr/capacitor_updater/InternalUtils.java +5 -2
- package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin.swift +1 -1
- package/ios/Tests/CapacitorUpdaterPluginTests/CapacitorUpdaterPluginTests.swift +24 -11
- package/ios/Tests/CapacitorUpdaterPluginTests/NetworkTransportTests.swift +238 -112
- package/package.json +1 -1
|
@@ -159,7 +159,15 @@ public class CapacitorUpdaterPlugin extends Plugin {
|
|
|
159
159
|
static final int APPLICATION_EXIT_REASON_USER_REQUESTED = 10;
|
|
160
160
|
static final int APPLICATION_EXIT_REASON_DEPENDENCY_DIED = 12;
|
|
161
161
|
|
|
162
|
-
|
|
162
|
+
// The release bump (capacitor-plugin-standard-version) rewrites only a private final String field named
|
|
163
|
+
// pluginVersion that holds a string literal, so the version lives in that form below. PLUGIN_VERSION
|
|
164
|
+
// exposes it to code that runs without a plugin instance.
|
|
165
|
+
private static final class VersionHolder {
|
|
166
|
+
|
|
167
|
+
private final String pluginVersion = "9.0.4";
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
static final String PLUGIN_VERSION = new VersionHolder().pluginVersion;
|
|
163
171
|
// Set while a plugin instance (with its bridge) runs in this process. The headless update
|
|
164
172
|
// check then leaves installing to that instance instead of swapping bundles under it.
|
|
165
173
|
static final Object INSTANCE_LOADED_LOCK = new Object();
|
|
@@ -43,7 +43,14 @@ public class CryptoCipher {
|
|
|
43
43
|
}
|
|
44
44
|
|
|
45
45
|
public static byte[] decryptRSA(byte[] source, PublicKey publicKey)
|
|
46
|
-
throws
|
|
46
|
+
throws
|
|
47
|
+
NoSuchPaddingException,
|
|
48
|
+
NoSuchAlgorithmException,
|
|
49
|
+
InvalidAlgorithmParameterException,
|
|
50
|
+
InvalidKeyException,
|
|
51
|
+
IllegalBlockSizeException,
|
|
52
|
+
BadPaddingException
|
|
53
|
+
{
|
|
47
54
|
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
|
|
48
55
|
cipher.init(Cipher.DECRYPT_MODE, publicKey);
|
|
49
56
|
byte[] decryptedBytes = cipher.doFinal(source);
|
|
@@ -111,7 +118,8 @@ public class CryptoCipher {
|
|
|
111
118
|
};
|
|
112
119
|
|
|
113
120
|
private static PublicKey readPkcs1PublicKey(byte[] pkcs1Bytes)
|
|
114
|
-
throws NoSuchAlgorithmException, InvalidKeySpecException, GeneralSecurityException
|
|
121
|
+
throws NoSuchAlgorithmException, InvalidKeySpecException, GeneralSecurityException
|
|
122
|
+
{
|
|
115
123
|
// convert the pkcs1 public key to an x509 favorable format
|
|
116
124
|
byte[] keyBitString = createDEREncoding(BIT_STRING_TAG, joinPublic(NO_UNUSED_BITS, pkcs1Bytes));
|
|
117
125
|
byte[] keyInfoValue = joinPublic(RSA_ALGORITHM_IDENTIFIER_SEQUENCE, keyBitString);
|
|
@@ -72,8 +72,11 @@ public class InternalUtils {
|
|
|
72
72
|
}
|
|
73
73
|
|
|
74
74
|
@SuppressWarnings("deprecation")
|
|
75
|
-
private static PackageInfo getPackageInfoLegacy(
|
|
76
|
-
|
|
75
|
+
private static PackageInfo getPackageInfoLegacy(
|
|
76
|
+
PackageManager pm,
|
|
77
|
+
String packageName,
|
|
78
|
+
int flags
|
|
79
|
+
) throws PackageManager.NameNotFoundException {
|
|
77
80
|
return pm.getPackageInfo(packageName, flags);
|
|
78
81
|
}
|
|
79
82
|
}
|
|
@@ -95,7 +95,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
|
|
|
95
95
|
deinit {
|
|
96
96
|
implementation.shutdown()
|
|
97
97
|
}
|
|
98
|
-
private let pluginVersion: String = "9.0.
|
|
98
|
+
private let pluginVersion: String = "9.0.4"
|
|
99
99
|
private let launchStartedAtMs = Int64(Date().timeIntervalSince1970 * 1000)
|
|
100
100
|
static let updateUrlDefault = "https://plugin.capgo.app/updates"
|
|
101
101
|
static let statsUrlDefault = "https://plugin.capgo.app/stats"
|
|
@@ -3686,10 +3686,13 @@ class CapacitorUpdaterTests: XCTestCase {
|
|
|
3686
3686
|
_ = implementation.setNextBundle(next: BundleInfo.ID_BUILTIN)
|
|
3687
3687
|
var installed = false
|
|
3688
3688
|
let installDone = DispatchSemaphore(value: 0)
|
|
3689
|
-
|
|
3689
|
+
// A dedicated thread, not the shared global queue: earlier tests can leave its threads blocked in
|
|
3690
|
+
// app-ready waits, and on a loaded CI runner a queued job then may not start within the wait below.
|
|
3691
|
+
let installThread = Thread {
|
|
3690
3692
|
installed = testPlugin.installNextForTesting()
|
|
3691
3693
|
installDone.signal()
|
|
3692
3694
|
}
|
|
3695
|
+
installThread.start()
|
|
3693
3696
|
XCTAssertEqual(installDone.wait(timeout: .now() + 5), .success)
|
|
3694
3697
|
XCTAssertTrue(installed)
|
|
3695
3698
|
}
|
|
@@ -6331,29 +6334,39 @@ class CapacitorUpdaterTests: XCTestCase {
|
|
|
6331
6334
|
|
|
6332
6335
|
}
|
|
6333
6336
|
|
|
6337
|
+
/// A one-shot latch the test thread opens for download threads (or the reverse).
|
|
6338
|
+
/// Waiters poll a flag instead of blocking on a DispatchGroup, semaphore or condition. A blocking wait from a
|
|
6339
|
+
/// userInitiated download thread on a primitive created or entered by the Default-QoS test thread is a priority
|
|
6340
|
+
/// inversion for Xcode's Thread Performance Checker, which SwiftPM test runs inject. On CI, capturing and
|
|
6341
|
+
/// symbolicating each report stalled the process for 10-20s, so the coalescing tests' 5s waits timed out.
|
|
6334
6342
|
private final class OnceSignal {
|
|
6343
|
+
private static let pollInterval: TimeInterval = 0.001
|
|
6335
6344
|
private let lock = NSLock()
|
|
6336
|
-
private let group = DispatchGroup()
|
|
6337
6345
|
private var signaled = false
|
|
6338
6346
|
|
|
6339
|
-
|
|
6340
|
-
|
|
6347
|
+
private var isSignaled: Bool {
|
|
6348
|
+
lock.lock()
|
|
6349
|
+
defer { lock.unlock() }
|
|
6350
|
+
return signaled
|
|
6341
6351
|
}
|
|
6342
6352
|
|
|
6343
6353
|
@discardableResult
|
|
6344
6354
|
func signal() -> Bool {
|
|
6345
6355
|
lock.lock()
|
|
6346
|
-
|
|
6356
|
+
defer { lock.unlock() }
|
|
6357
|
+
let changed = !signaled
|
|
6347
6358
|
signaled = true
|
|
6348
|
-
|
|
6349
|
-
if shouldLeave {
|
|
6350
|
-
group.leave()
|
|
6351
|
-
}
|
|
6352
|
-
return shouldLeave
|
|
6359
|
+
return changed
|
|
6353
6360
|
}
|
|
6354
6361
|
|
|
6355
6362
|
func wait(timeout: DispatchTime) -> DispatchTimeoutResult {
|
|
6356
|
-
|
|
6363
|
+
while !isSignaled {
|
|
6364
|
+
if DispatchTime.now() >= timeout {
|
|
6365
|
+
return isSignaled ? .success : .timedOut
|
|
6366
|
+
}
|
|
6367
|
+
Thread.sleep(forTimeInterval: Self.pollInterval)
|
|
6368
|
+
}
|
|
6369
|
+
return .success
|
|
6357
6370
|
}
|
|
6358
6371
|
}
|
|
6359
6372
|
|
|
@@ -1,9 +1,13 @@
|
|
|
1
1
|
import Foundation
|
|
2
|
-
import Network
|
|
3
2
|
import XCTest
|
|
4
3
|
@testable import CapacitorUpdaterPlugin
|
|
5
4
|
|
|
6
5
|
/// Minimal loopback HTTP/1.1 server so the real URLSession transport can be exercised without the network.
|
|
6
|
+
///
|
|
7
|
+
/// It listens on a BSD socket that is bound and listening before `init` returns, so its port is known and the
|
|
8
|
+
/// kernel completes connections into the backlog even while this process is starved of CPU. An NWListener only
|
|
9
|
+
/// reports `.ready` asynchronously, and on loaded CI runners it was not ready within 5s, so a test could send its
|
|
10
|
+
/// request to port 0. `stop()` closes the socket synchronously, so later connections are refused at once.
|
|
7
11
|
private final class LoopbackHTTPServer {
|
|
8
12
|
struct Response {
|
|
9
13
|
var status: Int
|
|
@@ -28,32 +32,56 @@ private final class LoopbackHTTPServer {
|
|
|
28
32
|
var body: Data
|
|
29
33
|
}
|
|
30
34
|
|
|
31
|
-
|
|
32
|
-
|
|
35
|
+
enum SetupError: Error {
|
|
36
|
+
case socket(String, Int32)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
private let listenSocket: Int32
|
|
40
|
+
private let port: UInt16
|
|
41
|
+
private let acceptQueue = DispatchQueue(label: "capgo.loopback-http.accept")
|
|
42
|
+
private let acceptSource: DispatchSourceRead
|
|
33
43
|
private let lock = NSLock()
|
|
34
44
|
private var handler: (RecordedRequest) -> Response = { _ in Response(status: 200, body: Data()) }
|
|
35
45
|
private var recorded: [RecordedRequest] = []
|
|
36
46
|
private var activeConnections = 0
|
|
47
|
+
private var stopped = false
|
|
48
|
+
private let listenerClosed = DispatchSemaphore(value: 0)
|
|
37
49
|
|
|
38
50
|
init() throws {
|
|
39
|
-
let
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
51
|
+
let socketFD = socket(AF_INET, SOCK_STREAM, 0)
|
|
52
|
+
guard socketFD >= 0 else {
|
|
53
|
+
throw SetupError.socket("socket", errno)
|
|
54
|
+
}
|
|
55
|
+
var reuse: Int32 = 1
|
|
56
|
+
setsockopt(socketFD, SOL_SOCKET, SO_REUSEADDR, &reuse, socklen_t(MemoryLayout<Int32>.size))
|
|
57
|
+
do {
|
|
58
|
+
port = try Self.bindLoopback(socketFD)
|
|
59
|
+
guard listen(socketFD, 64) == 0 else {
|
|
60
|
+
throw SetupError.socket("listen", errno)
|
|
49
61
|
}
|
|
62
|
+
try Self.setNonBlocking(socketFD)
|
|
63
|
+
} catch {
|
|
64
|
+
close(socketFD)
|
|
65
|
+
throw error
|
|
66
|
+
}
|
|
67
|
+
listenSocket = socketFD
|
|
68
|
+
acceptSource = DispatchSource.makeReadSource(fileDescriptor: socketFD, queue: acceptQueue)
|
|
69
|
+
acceptSource.setEventHandler { [weak self] in
|
|
70
|
+
self?.acceptPendingConnections()
|
|
71
|
+
}
|
|
72
|
+
acceptSource.setCancelHandler { [listenerClosed] in
|
|
73
|
+
close(socketFD)
|
|
74
|
+
listenerClosed.signal()
|
|
50
75
|
}
|
|
51
|
-
|
|
52
|
-
|
|
76
|
+
acceptSource.resume()
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
deinit {
|
|
80
|
+
stop()
|
|
53
81
|
}
|
|
54
82
|
|
|
55
83
|
var baseURL: URL {
|
|
56
|
-
return URL(string: "http://127.0.0.1:\(
|
|
84
|
+
return URL(string: "http://127.0.0.1:\(port)") ?? URL(fileURLWithPath: "/")
|
|
57
85
|
}
|
|
58
86
|
|
|
59
87
|
var requests: [RecordedRequest] {
|
|
@@ -68,8 +96,20 @@ private final class LoopbackHTTPServer {
|
|
|
68
96
|
lock.unlock()
|
|
69
97
|
}
|
|
70
98
|
|
|
99
|
+
/// Stops accepting connections. The listening socket is closed before this returns, so a new connection to
|
|
100
|
+
/// the old port is refused instead of reaching a listener that is still shutting down.
|
|
71
101
|
func stop() {
|
|
72
|
-
|
|
102
|
+
lock.lock()
|
|
103
|
+
let wasStopped = stopped
|
|
104
|
+
stopped = true
|
|
105
|
+
lock.unlock()
|
|
106
|
+
guard !wasStopped else {
|
|
107
|
+
return
|
|
108
|
+
}
|
|
109
|
+
// The accept source's cancel handler closes the listening socket; wait for it so the port refuses
|
|
110
|
+
// new connections once stop() returns.
|
|
111
|
+
acceptSource.cancel()
|
|
112
|
+
listenerClosed.wait()
|
|
73
113
|
}
|
|
74
114
|
|
|
75
115
|
/// Waits until accepted connections finish or `timeout` elapses (stray URLSession tasks after invalidate).
|
|
@@ -86,55 +126,77 @@ private final class LoopbackHTTPServer {
|
|
|
86
126
|
}
|
|
87
127
|
}
|
|
88
128
|
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
129
|
+
/// A loopback port with nothing listening on it: bind a socket to an ephemeral port, then close it.
|
|
130
|
+
/// Connecting to it is refused at once.
|
|
131
|
+
static func closedLoopbackPort() throws -> UInt16 {
|
|
132
|
+
let socketFD = socket(AF_INET, SOCK_STREAM, 0)
|
|
133
|
+
guard socketFD >= 0 else {
|
|
134
|
+
throw SetupError.socket("socket", errno)
|
|
135
|
+
}
|
|
136
|
+
defer { close(socketFD) }
|
|
137
|
+
return try bindLoopback(socketFD)
|
|
93
138
|
}
|
|
94
139
|
|
|
95
|
-
private func
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
140
|
+
private static func bindLoopback(_ socketFD: Int32) throws -> UInt16 {
|
|
141
|
+
var address = sockaddr_in()
|
|
142
|
+
address.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
|
|
143
|
+
address.sin_family = sa_family_t(AF_INET)
|
|
144
|
+
address.sin_addr.s_addr = inet_addr("127.0.0.1")
|
|
145
|
+
address.sin_port = 0
|
|
146
|
+
var length = socklen_t(MemoryLayout<sockaddr_in>.size)
|
|
147
|
+
let bound = withUnsafeMutablePointer(to: &address) { pointer in
|
|
148
|
+
pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) { socketAddress in
|
|
149
|
+
bind(socketFD, socketAddress, length) == 0 && getsockname(socketFD, socketAddress, &length) == 0
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
guard bound else {
|
|
153
|
+
throw SetupError.socket("bind", errno)
|
|
154
|
+
}
|
|
155
|
+
return UInt16(bigEndian: address.sin_port)
|
|
99
156
|
}
|
|
100
157
|
|
|
101
|
-
private func
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
self?.connectionClosed()
|
|
106
|
-
}
|
|
158
|
+
private static func setNonBlocking(_ socketFD: Int32) throws {
|
|
159
|
+
let flags = fcntl(socketFD, F_GETFL)
|
|
160
|
+
guard flags >= 0, fcntl(socketFD, F_SETFL, flags | O_NONBLOCK) == 0 else {
|
|
161
|
+
throw SetupError.socket("fcntl", errno)
|
|
107
162
|
}
|
|
108
|
-
connection.start(queue: queue)
|
|
109
|
-
receive(on: connection, buffer: Data())
|
|
110
163
|
}
|
|
111
164
|
|
|
112
|
-
private func
|
|
113
|
-
|
|
114
|
-
|
|
165
|
+
private func acceptPendingConnections() {
|
|
166
|
+
while true {
|
|
167
|
+
let connectionFD = accept(listenSocket, nil, nil)
|
|
168
|
+
guard connectionFD >= 0 else {
|
|
115
169
|
return
|
|
116
170
|
}
|
|
117
|
-
var
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
if
|
|
122
|
-
|
|
123
|
-
self.recorded.append(request)
|
|
124
|
-
let handler = self.handler
|
|
125
|
-
self.lock.unlock()
|
|
126
|
-
self.send(handler(request), on: connection)
|
|
127
|
-
return
|
|
128
|
-
}
|
|
129
|
-
if isComplete || error != nil {
|
|
130
|
-
connection.cancel()
|
|
131
|
-
return
|
|
171
|
+
var noSigPipe: Int32 = 1
|
|
172
|
+
setsockopt(connectionFD, SOL_SOCKET, SO_NOSIGPIPE, &noSigPipe, socklen_t(MemoryLayout<Int32>.size))
|
|
173
|
+
// Accepted sockets inherit O_NONBLOCK from the listener on Darwin; the connection writes block.
|
|
174
|
+
let flags = fcntl(connectionFD, F_GETFL)
|
|
175
|
+
if flags >= 0 {
|
|
176
|
+
_ = fcntl(connectionFD, F_SETFL, flags & ~O_NONBLOCK)
|
|
132
177
|
}
|
|
133
|
-
|
|
178
|
+
lock.lock()
|
|
179
|
+
activeConnections += 1
|
|
180
|
+
lock.unlock()
|
|
181
|
+
LoopbackConnection(socketFD: connectionFD, server: self).start()
|
|
134
182
|
}
|
|
135
183
|
}
|
|
136
184
|
|
|
137
|
-
|
|
185
|
+
fileprivate func connectionClosed() {
|
|
186
|
+
lock.lock()
|
|
187
|
+
activeConnections = max(0, activeConnections - 1)
|
|
188
|
+
lock.unlock()
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
fileprivate func handle(_ request: RecordedRequest) -> Response {
|
|
192
|
+
lock.lock()
|
|
193
|
+
recorded.append(request)
|
|
194
|
+
let handler = self.handler
|
|
195
|
+
lock.unlock()
|
|
196
|
+
return handler(request)
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
fileprivate static func parse(_ buffer: Data) -> RecordedRequest? {
|
|
138
200
|
guard let headerEnd = buffer.range(of: Data("\r\n\r\n".utf8)),
|
|
139
201
|
let head = String(data: buffer[buffer.startIndex..<headerEnd.lowerBound], encoding: .utf8) else {
|
|
140
202
|
return nil
|
|
@@ -161,14 +223,60 @@ private final class LoopbackHTTPServer {
|
|
|
161
223
|
body: Data(body.prefix(contentLength))
|
|
162
224
|
)
|
|
163
225
|
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/// One accepted connection: reads a request, then writes the configured response on its own serial queue,
|
|
229
|
+
/// so a slow or paused response never delays another connection.
|
|
230
|
+
private final class LoopbackConnection {
|
|
231
|
+
private let socketFD: Int32
|
|
232
|
+
private let server: LoopbackHTTPServer
|
|
233
|
+
private let queue = DispatchQueue(label: "capgo.loopback-http.connection")
|
|
234
|
+
private var readSource: DispatchSourceRead?
|
|
235
|
+
private var buffer = Data()
|
|
236
|
+
private var answered = false
|
|
237
|
+
private var closed = false
|
|
238
|
+
|
|
239
|
+
init(socketFD: Int32, server: LoopbackHTTPServer) {
|
|
240
|
+
self.socketFD = socketFD
|
|
241
|
+
self.server = server
|
|
242
|
+
}
|
|
164
243
|
|
|
165
|
-
|
|
166
|
-
|
|
244
|
+
func start() {
|
|
245
|
+
let source = DispatchSource.makeReadSource(fileDescriptor: socketFD, queue: queue)
|
|
246
|
+
source.setEventHandler { [self] in
|
|
247
|
+
readAvailable()
|
|
248
|
+
}
|
|
249
|
+
readSource = source
|
|
250
|
+
source.resume()
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
private func readAvailable() {
|
|
254
|
+
var chunk = [UInt8](repeating: 0, count: 65536)
|
|
255
|
+
let count = read(socketFD, &chunk, chunk.count)
|
|
256
|
+
if count <= 0 {
|
|
257
|
+
// The peer closed the connection (or it failed); nothing more can be sent.
|
|
258
|
+
finish()
|
|
259
|
+
return
|
|
260
|
+
}
|
|
261
|
+
// One request per connection: bytes after it are ignored.
|
|
262
|
+
guard !answered else {
|
|
263
|
+
return
|
|
264
|
+
}
|
|
265
|
+
buffer.append(contentsOf: chunk[0..<count])
|
|
266
|
+
guard let request = LoopbackHTTPServer.parse(buffer) else {
|
|
267
|
+
return
|
|
268
|
+
}
|
|
269
|
+
answered = true
|
|
270
|
+
send(server.handle(request))
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
private func send(_ response: LoopbackHTTPServer.Response) {
|
|
167
274
|
if response.dropConnection {
|
|
168
|
-
|
|
275
|
+
finish()
|
|
169
276
|
return
|
|
170
277
|
}
|
|
171
|
-
var head = "HTTP/1.1 \(response.status) Status\r\
|
|
278
|
+
var head = "HTTP/1.1 \(response.status) Status\r\n"
|
|
279
|
+
head += "Content-Length: \(response.body.count)\r\nConnection: close\r\n"
|
|
172
280
|
for (name, value) in response.headers {
|
|
173
281
|
head += "\(name): \(value)\r\n"
|
|
174
282
|
}
|
|
@@ -176,73 +284,91 @@ private final class LoopbackHTTPServer {
|
|
|
176
284
|
let bodyData = response.truncateBodyAt.map { Data(response.body.prefix($0)) } ?? response.body
|
|
177
285
|
|
|
178
286
|
if let chunkSize = response.chunkSize, chunkSize > 0, bodyData.count > chunkSize {
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
)
|
|
185
|
-
})
|
|
287
|
+
guard write(Data(head.utf8)) else {
|
|
288
|
+
finish()
|
|
289
|
+
return
|
|
290
|
+
}
|
|
291
|
+
sendChunks(of: bodyData, offset: 0, chunkSize: chunkSize, response: response)
|
|
186
292
|
return
|
|
187
293
|
}
|
|
188
|
-
|
|
189
294
|
if response.truncateBodyAt != nil {
|
|
190
|
-
//
|
|
295
|
+
// Headers and body go out in separate writes so a truncated body is a real mid-stream drop,
|
|
191
296
|
// not one atomic read containing a short body with Content-Length still outstanding.
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
return
|
|
197
|
-
}
|
|
198
|
-
connection.send(content: bodyData, isComplete: true, completion: .contentProcessed { _ in
|
|
199
|
-
connection.cancel()
|
|
200
|
-
})
|
|
201
|
-
})
|
|
297
|
+
if write(Data(head.utf8)) {
|
|
298
|
+
_ = write(bodyData)
|
|
299
|
+
}
|
|
300
|
+
finish()
|
|
202
301
|
return
|
|
203
302
|
}
|
|
204
|
-
|
|
205
303
|
var payload = Data(head.utf8)
|
|
206
304
|
payload.append(bodyData)
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
})
|
|
305
|
+
_ = write(payload)
|
|
306
|
+
finish()
|
|
210
307
|
}
|
|
211
308
|
|
|
212
|
-
///
|
|
213
|
-
private func sendChunks(
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
guard offset < body.count else {
|
|
218
|
-
connection.cancel()
|
|
309
|
+
/// Writes slices of `body` separated by the response's chunk delay, then closes the connection.
|
|
310
|
+
private func sendChunks(of body: Data, offset: Int, chunkSize: Int, response: LoopbackHTTPServer.Response) {
|
|
311
|
+
let end = min(offset + chunkSize, body.count)
|
|
312
|
+
guard write(body.subdata(in: offset..<end)), end < body.count else {
|
|
313
|
+
finish()
|
|
219
314
|
return
|
|
220
315
|
}
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
316
|
+
queue.asyncAfter(deadline: .now() + response.chunkDelay) { [self] in
|
|
317
|
+
if let wait = response.waitBeforeContinuingBody {
|
|
318
|
+
let deadline = Date().addingTimeInterval(response.waitBeforeContinuingBodyTimeout)
|
|
319
|
+
while !wait() && Date() < deadline {
|
|
320
|
+
Thread.sleep(forTimeInterval: 0.005)
|
|
321
|
+
}
|
|
227
322
|
}
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
323
|
+
sendChunks(of: body, offset: end, chunkSize: chunkSize, response: response)
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/// Blocking write of all of `data`; false once the peer has gone away.
|
|
328
|
+
private func write(_ data: Data) -> Bool {
|
|
329
|
+
guard !closed else {
|
|
330
|
+
return false
|
|
331
|
+
}
|
|
332
|
+
return data.withUnsafeBytes { raw -> Bool in
|
|
333
|
+
guard var pointer = raw.baseAddress else {
|
|
334
|
+
return true
|
|
335
|
+
}
|
|
336
|
+
var remaining = raw.count
|
|
337
|
+
while remaining > 0 {
|
|
338
|
+
let written = Darwin.write(socketFD, pointer, remaining)
|
|
339
|
+
if written < 0 {
|
|
340
|
+
if errno == EINTR {
|
|
341
|
+
continue
|
|
235
342
|
}
|
|
236
|
-
|
|
237
|
-
of: body, offset: end, chunkSize: chunkSize, delay: delay,
|
|
238
|
-
waitBeforeContinuingBody: waitBeforeContinuingBody, waitTimeout: waitTimeout,
|
|
239
|
-
on: connection
|
|
240
|
-
)
|
|
343
|
+
return false
|
|
241
344
|
}
|
|
242
|
-
|
|
243
|
-
|
|
345
|
+
remaining -= written
|
|
346
|
+
pointer += written
|
|
244
347
|
}
|
|
245
|
-
|
|
348
|
+
return true
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
private func finish() {
|
|
353
|
+
guard !closed else {
|
|
354
|
+
return
|
|
355
|
+
}
|
|
356
|
+
closed = true
|
|
357
|
+
// Close the socket from the read source's cancel handler, so the source is gone before the descriptor
|
|
358
|
+
// number can be reused by another connection.
|
|
359
|
+
let socketFD = self.socketFD
|
|
360
|
+
let server = self.server
|
|
361
|
+
guard let source = readSource else {
|
|
362
|
+
close(socketFD)
|
|
363
|
+
server.connectionClosed()
|
|
364
|
+
return
|
|
365
|
+
}
|
|
366
|
+
readSource = nil
|
|
367
|
+
source.setCancelHandler {
|
|
368
|
+
close(socketFD)
|
|
369
|
+
server.connectionClosed()
|
|
370
|
+
}
|
|
371
|
+
source.cancel()
|
|
246
372
|
}
|
|
247
373
|
}
|
|
248
374
|
|
|
@@ -793,10 +919,10 @@ final class NetworkTransportTests: XCTestCase {
|
|
|
793
919
|
}
|
|
794
920
|
|
|
795
921
|
func testPerformRequestWrapsTransportErrors() throws {
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
var request = URLRequest(url: try XCTUnwrap(URL(string: "http://127.0.0.1:\(port
|
|
922
|
+
// A port that was never listening refuses the connection at once. Reusing the test server's port after
|
|
923
|
+
// stop() could still reach the listener while it shuts down, and that connection never gets a reply.
|
|
924
|
+
let port = try LoopbackHTTPServer.closedLoopbackPort()
|
|
925
|
+
var request = URLRequest(url: try XCTUnwrap(URL(string: "http://127.0.0.1:\(port)/closed")))
|
|
800
926
|
request.timeoutInterval = 5
|
|
801
927
|
|
|
802
928
|
let result = makeUpdater().performRequest(request, label: "test")
|