-
Notifications
You must be signed in to change notification settings - Fork 129
/
URLSessionSwizzler.swift
285 lines (240 loc) · 12.6 KB
/
URLSessionSwizzler.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
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
/*
* Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
* This product includes software developed at Datadog (https://www.datadoghq.com/).
* Copyright 2019-Present Datadog, Inc.
*/
import Foundation
internal class URLSessionSwizzler {
/// Counts of bindings of the URL swizzler.
///
/// This value will increment for each call to the `bind()` method.
/// Calling `unbind()` will decrement the count, when reaching zero, the swizzler is disabled.
internal private(set) static var bindingsCount: UInt = 0
/// The binding lock.
private static var lock = NSLock()
/// `URLSession.dataTask(with:completionHandler:)` (for `URLRequest`) swizzling.
internal private(set) static var dataTaskWithURLRequestAndCompletion: DataTaskWithURLRequestAndCompletion?
/// `URLSession.dataTask(with:)` (for `URLRequest`) swizzling.
internal private(set) static var dataTaskWithURLRequest: DataTaskWithURLRequest?
/// `URLSession.dataTask(with:completionHandler:)` (for `URL`) swizzling. Only applied on iOS 13 and above.
internal private(set) static var dataTaskWithURLAndCompletion: DataTaskWithURLAndCompletion?
/// `URLSession.dataTask(with:)` (for `URL`) swizzling. Only applied on iOS 13 and above.
internal private(set) static var dataTaskWithURL: DataTaskWithURL?
static func bind() throws {
lock.lock()
defer { lock.unlock() }
guard bindingsCount == 0 else {
return bindingsCount += 1
}
if #available(iOS 13.0, *) {
// Prior to iOS 13.0 we do not apply following swizzlings, as those methods call
// the `URLSession.dataTask(with:completionHandler:)` internally which is managed
// by the `DataTaskWithURLRequestAndCompletion` swizzling.
dataTaskWithURLAndCompletion = try DataTaskWithURLAndCompletion.build()
dataTaskWithURL = try DataTaskWithURL.build()
}
dataTaskWithURLRequestAndCompletion = try DataTaskWithURLRequestAndCompletion.build()
dataTaskWithURLRequest = try DataTaskWithURLRequest.build()
dataTaskWithURLRequestAndCompletion?.swizzle()
dataTaskWithURLAndCompletion?.swizzle()
dataTaskWithURLRequest?.swizzle()
dataTaskWithURL?.swizzle()
bindingsCount += 1
}
static func unbind() {
lock.lock()
defer { lock.unlock() }
if bindingsCount == 0 {
return
}
if bindingsCount > 1 {
return bindingsCount -= 1
}
dataTaskWithURLRequestAndCompletion?.unswizzle()
dataTaskWithURLRequest?.unswizzle()
dataTaskWithURLAndCompletion?.unswizzle()
dataTaskWithURL?.unswizzle()
dataTaskWithURLRequestAndCompletion = nil
dataTaskWithURLRequest = nil
dataTaskWithURLAndCompletion = nil
dataTaskWithURL = nil
bindingsCount -= 1
}
// MARK: - Swizzlings
typealias CompletionHandler = (Data?, URLResponse?, Error?) -> Void
/// Swizzles the `URLSession.dataTask(with:completionHandler:)` for `URLRequest`.
class DataTaskWithURLRequestAndCompletion: MethodSwizzler<
@convention(c) (URLSession, Selector, URLRequest, CompletionHandler?) -> URLSessionDataTask,
@convention(block) (URLSession, URLRequest, CompletionHandler?) -> URLSessionDataTask
> {
private static let selector = #selector(
URLSession.dataTask(with:completionHandler:) as (URLSession) -> (URLRequest, @escaping CompletionHandler) -> URLSessionDataTask
)
private let method: FoundMethod
static func build() throws -> DataTaskWithURLRequestAndCompletion {
return try DataTaskWithURLRequestAndCompletion(
selector: self.selector,
klass: URLSession.self
)
}
private init(selector: Selector, klass: AnyClass) throws {
self.method = try Self.findMethod(with: selector, in: klass)
super.init()
}
func swizzle() {
typealias Signature = @convention(block) (URLSession, URLRequest, CompletionHandler?) -> URLSessionDataTask
swizzle(method) { previousImplementation -> Signature in
return { session, request, completionHandler -> URLSessionDataTask in
guard
let delegate = (session.delegate as? __URLSessionDelegateProviding)?.ddURLSessionDelegate,
let interceptor = delegate.interceptor
else {
return previousImplementation(session, Self.selector, request, completionHandler)
}
guard let completionHandler = completionHandler else {
// The `completionHandler` can be `nil` in two cases:
// - on iOS 11 or 12, where `dataTask(with:)` (for `URL` and `URLRequest`) calls
// the `dataTask(with:completionHandler:)` (for `URLRequest`) internally by nullifying the completion block.
// - when `[session dataTaskWithURL:completionHandler:]` is called in Objective-C with explicitly passing
// `nil` as the `completionHandler` (it produces a warning, but compiles).
let task = previousImplementation(session, Self.selector, request, completionHandler)
interceptor.intercept(task: task, additionalFirstPartyHosts: delegate.firstPartyHosts)
return task
}
var _task: URLSessionDataTask?
let request = interceptor.intercept(request: request, additionalFirstPartyHosts: delegate.firstPartyHosts)
let task = previousImplementation(session, Self.selector, request) { data, response, error in
completionHandler(data, response, error)
if let task = _task { // sanity check, should always succeed
data.map { interceptor.task(task, didReceive: $0) }
interceptor.task(task, didCompleteWithError: error)
}
}
_task = task
interceptor.intercept(task: task, additionalFirstPartyHosts: delegate.firstPartyHosts)
return task
}
}
}
}
/// Swizzles the `URLSession.dataTask(with:completionHandler:)` for `URL`.
class DataTaskWithURLAndCompletion: MethodSwizzler<
@convention(c) (URLSession, Selector, URL, CompletionHandler?) -> URLSessionDataTask,
@convention(block) (URLSession, URL, CompletionHandler?) -> URLSessionDataTask
> {
private static let selector = #selector(
URLSession.dataTask(with:completionHandler:) as (URLSession) -> (URL, @escaping CompletionHandler) -> URLSessionDataTask
)
private let method: FoundMethod
static func build() throws -> DataTaskWithURLAndCompletion {
return try DataTaskWithURLAndCompletion(
selector: self.selector,
klass: URLSession.self
)
}
private init(selector: Selector, klass: AnyClass) throws {
self.method = try Self.findMethod(with: selector, in: klass)
super.init()
}
func swizzle() {
typealias Signature = @convention(block) (URLSession, URL, CompletionHandler?) -> URLSessionDataTask
swizzle(method) { previousImplementation -> Signature in
return { session, url, completionHandler -> URLSessionDataTask in
guard
let delegate = (session.delegate as? __URLSessionDelegateProviding)?.ddURLSessionDelegate,
let interceptor = delegate.interceptor
else {
return previousImplementation(session, Self.selector, url, completionHandler)
}
guard let completionHandler = completionHandler else {
let task = previousImplementation(session, Self.selector, url, completionHandler)
interceptor.intercept(task: task, additionalFirstPartyHosts: delegate.firstPartyHosts)
return task
}
var _task: URLSessionDataTask?
let task = previousImplementation(session, Self.selector, url) { data, response, error in
completionHandler(data, response, error)
if let task = _task { // sanity check, should always succeed
data.map { interceptor.task(task, didReceive: $0) }
interceptor.task(task, didCompleteWithError: error)
}
}
_task = task
interceptor.intercept(task: task, additionalFirstPartyHosts: delegate.firstPartyHosts)
return task
}
}
}
}
/// Swizzles the `URLSession.dataTask(with:)` for `URLRequest`.
class DataTaskWithURLRequest: MethodSwizzler<
@convention(c) (URLSession, Selector, URLRequest) -> URLSessionDataTask,
@convention(block) (URLSession, URLRequest) -> URLSessionDataTask
> {
private static let selector = #selector(
URLSession.dataTask(with:) as (URLSession) -> (URLRequest) -> URLSessionDataTask
)
private let method: FoundMethod
static func build() throws -> DataTaskWithURLRequest {
return try DataTaskWithURLRequest(
selector: self.selector,
klass: URLSession.self
)
}
private init(selector: Selector, klass: AnyClass) throws {
self.method = try Self.findMethod(with: selector, in: klass)
super.init()
}
func swizzle() {
typealias Signature = @convention(block) (URLSession, URLRequest) -> URLSessionDataTask
swizzle(method) { previousImplementation -> Signature in
return { session, request -> URLSessionDataTask in
guard let delegate = (session.delegate as? __URLSessionDelegateProviding)?.ddURLSessionDelegate else {
return previousImplementation(session, Self.selector, request)
}
let request = delegate.interceptor?.intercept(request: request, additionalFirstPartyHosts: delegate.firstPartyHosts) ?? request
let task = previousImplementation(session, Self.selector, request)
if #available(iOS 13.0, *) {
// Prior to iOS 13.0, `dataTask(with:)` (for `URLRequest`) calls the
// the `dataTask(with:completionHandler:)` (for `URLRequest`) internally,
// so the task creation will be notified from `dataTaskWithURLRequestAndCompletion` swizzling.
delegate.interceptor?.intercept(task: task, additionalFirstPartyHosts: delegate.firstPartyHosts)
}
return task
}
}
}
}
/// Swizzles the `URLSession.dataTask(with:)` for `URL`.
class DataTaskWithURL: MethodSwizzler<
@convention(c) (URLSession, Selector, URL) -> URLSessionDataTask,
@convention(block) (URLSession, URL) -> URLSessionDataTask
> {
private static let selector = #selector(
URLSession.dataTask(with:) as (URLSession) -> (URL) -> URLSessionDataTask
)
private let method: FoundMethod
static func build() throws -> DataTaskWithURL {
return try DataTaskWithURL(
selector: self.selector,
klass: URLSession.self
)
}
private init(selector: Selector, klass: AnyClass) throws {
self.method = try Self.findMethod(with: selector, in: klass)
super.init()
}
func swizzle() {
typealias Signature = @convention(block) (URLSession, URL) -> URLSessionDataTask
swizzle(method) { previousImplementation -> Signature in
return { session, url -> URLSessionDataTask in
let task = previousImplementation(session, Self.selector, url)
if let delegate = (session.delegate as? __URLSessionDelegateProviding)?.ddURLSessionDelegate {
delegate.interceptor?.intercept(task: task, additionalFirstPartyHosts: delegate.firstPartyHosts)
}
return task
}
}
}
}
}