UnityWebRequest.mm
12.9 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
const CFIndex streamSize = 1024;
static NSOperationQueue* webOperationQueue;
static NSURLSession* unityWebRequestSession;
@interface UnityURLRequest : NSMutableURLRequest
@property (readonly, nonatomic) void* udata;
@property (readwrite, nonatomic) NSUInteger taskIdentifier;
@property (readonly, nonatomic) long long estimatedContentLength;
@property (readonly, nonatomic) long long receivedBytes;
@property (readwrite, nonatomic) bool wantCertificateCallback;
@property (readwrite, nonatomic) bool redirecting;
@property (readwrite) bool isDone;
- (id)init:(void*)udata;
@end
static NSMutableArray<UnityURLRequest*>* currentRequests;
static NSLock* currentRequestsLock;
@implementation UnityURLRequest
{
void* _udata;
NSUInteger _taskIdentifier;
long long _estimatedContentLength;
long long _receivedBytes;
bool _wantCertificateCallback;
bool _redirecting;
bool _isDone;
}
@synthesize udata = _udata;
@synthesize taskIdentifier = _taskIdentifier;
@synthesize estimatedContentLength = _estimatedContentLength;
@synthesize receivedBytes = _receivedBytes;
@synthesize wantCertificateCallback = _wantCertificateCallback;
@synthesize redirecting = _redirecting;
@synthesize isDone = _isDone;
+ (void)storeRequest:(UnityURLRequest *)request taskID:(NSUInteger)taskId
{
request.taskIdentifier = taskId;
[currentRequestsLock lock];
[currentRequests addObject: request];
[currentRequestsLock unlock];
}
+ (UnityURLRequest*)requestForTask:(NSURLSessionTask*)task
{
UnityURLRequest* request = nil;
[currentRequestsLock lock];
for (unsigned i = 0; i < currentRequests.count; ++i)
if (currentRequests[i].taskIdentifier == task.taskIdentifier)
{
request = currentRequests[i];
break;
}
[currentRequestsLock unlock];
return request;
}
+ (void)removeRequest:(UnityURLRequest*)request
{
// removeObject would remove all identical request, taskIdentifier is unique
[currentRequestsLock lock];
for (unsigned i = 0; i < currentRequests.count; ++i)
if (currentRequests[i].taskIdentifier == request.taskIdentifier)
{
[currentRequests removeObjectAtIndex: i];
break;
}
[currentRequestsLock unlock];
}
+ (void)writeBody:(NSOutputStream*)outputStream task:(NSURLSessionTask*)task udata:(void*)udata
{
unsigned dataSize = streamSize;
BOOL uploadComplete = FALSE;
while (!uploadComplete)
{
dataSize = streamSize;
const UInt8* data = (const UInt8*)UnityWebRequestGetUploadData(udata, &dataSize);
if (dataSize == 0)
break;
NSInteger transmitted = [outputStream write: data maxLength: dataSize];
if (transmitted > 0)
UnityWebRequestConsumeUploadData(udata, (unsigned)transmitted);
switch (task.state)
{
case NSURLSessionTaskStateCanceling:
case NSURLSessionTaskStateCompleted:
uploadComplete = TRUE;
break;
default:
uploadComplete = FALSE;
}
}
[outputStream close];
}
- (id)init:(void*)udata
{
self = [super init];
_udata = udata;
_taskIdentifier = 0;
_estimatedContentLength = 0;
_receivedBytes = 0;
_wantCertificateCallback = false;
_redirecting = false;
_isDone = false;
return self;
}
- (void)updateEstimatedContentLength:(long long)contentLength
{
if (contentLength > _estimatedContentLength)
_estimatedContentLength = contentLength;
}
- (void)updateReceivedBytes:(long long)receivedBytes
{
_receivedBytes += receivedBytes;
if (_receivedBytes > _estimatedContentLength)
_estimatedContentLength = _receivedBytes;
}
@end
@interface UnityWebRequestDelegate : NSObject<NSURLSessionDataDelegate, NSURLSessionTaskDelegate>
@end
@implementation UnityWebRequestDelegate
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(nonnull NSURLResponse *)response completionHandler:(nonnull void (^)(NSURLSessionResponseDisposition))completionHandler
{
[self handleResponse: response task: dataTask];
completionHandler(NSURLSessionResponseAllow);
}
- (void)handleResponse:(NSURLResponse*)response task:(NSURLSessionTask*)task
{
UnityURLRequest* urequest = [UnityURLRequest requestForTask: task];
if (urequest == nil)
return;
if ([response isKindOfClass: [NSHTTPURLResponse class]])
[self handleHTTPResponse: (NSHTTPURLResponse*)response urequest: urequest];
else
[self handleResponse: response urequest: urequest];
}
- (void)handleHTTPResponse:(NSHTTPURLResponse*)response task:(NSURLSessionTask*)task
{
UnityURLRequest* urequest = [UnityURLRequest requestForTask: task];
if (urequest == nil)
return;
[self handleHTTPResponse: response urequest: urequest];
}
- (void)handleHTTPResponse:(NSHTTPURLResponse*)response urequest:(UnityURLRequest*)urequest
{
UnityReportWebRequestStatus(urequest.udata, (int)[response statusCode]);
NSDictionary* respHeader = [response allHeaderFields];
NSEnumerator* headerEnum = [respHeader keyEnumerator];
for (id headerKey = [headerEnum nextObject]; headerKey; headerKey = [headerEnum nextObject])
UnityReportWebRequestResponseHeader(urequest.udata, [headerKey UTF8String], [[respHeader objectForKey: headerKey] UTF8String]);
[self handleResponse: response urequest: urequest];
}
- (void)handleResponse:(NSURLResponse*)response urequest:(UnityURLRequest*)urequest
{
[urequest updateEstimatedContentLength: response.expectedContentLength];
UnityReportWebRequestReceivedResponse(urequest.udata, (unsigned int)urequest.estimatedContentLength);
}
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
UnityURLRequest* urequest = [UnityURLRequest requestForTask: dataTask];
if (urequest == nil)
return;
[urequest updateEstimatedContentLength: [dataTask countOfBytesExpectedToReceive]];
[data enumerateByteRangesUsingBlock:^(const void* bytes, NSRange range, BOOL* stop) {
UnityReportWebRequestReceivedData(urequest.udata, bytes, (unsigned int)range.length, (unsigned int)urequest.estimatedContentLength);
}];
}
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest * _Nullable))completionHandler
{
UnityURLRequest* urequest = [UnityURLRequest requestForTask: task];
if (urequest == nil)
return;
urequest.redirecting = true;
[self handleHTTPResponse: response task: task];
completionHandler(nil);
[task cancel];
}
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential* credential))completionHandler
{
if ([[challenge protectionSpace] authenticationMethod] == NSURLAuthenticationMethodServerTrust)
{
UnityURLRequest* urequest = [UnityURLRequest requestForTask: task];
if (urequest == nil || !urequest.wantCertificateCallback)
{
completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
return;
}
#if !defined(DISABLE_WEBREQUEST_CERTIFICATE_CALLBACK)
SecTrustResultType systemResult;
SecTrustRef serverTrust = [[challenge protectionSpace] serverTrust];
if (serverTrust == nil || errSecSuccess != SecTrustEvaluate(serverTrust, &systemResult))
{
systemResult = kSecTrustResultOtherError;
}
switch (systemResult)
{
case kSecTrustResultUnspecified:
case kSecTrustResultProceed:
case kSecTrustResultRecoverableTrustFailure:
break;
default:
completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
return;
}
SecCertificateRef serverCertificate = SecTrustGetCertificateAtIndex(serverTrust, 0);
if (serverCertificate != nil)
{
CFDataRef serverCertificateData = SecCertificateCopyData(serverCertificate);
const UInt8* const data = CFDataGetBytePtr(serverCertificateData);
const CFIndex size = CFDataGetLength(serverCertificateData);
bool trust = UnityReportWebRequestValidateCertificate(urequest.udata, (const char*)data, (unsigned)size);
CFRelease(serverCertificateData);
if (trust)
{
NSURLCredential *credential = [NSURLCredential credentialForTrust: challenge.protectionSpace.serverTrust];
completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
return;
}
}
#endif
completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
return;
}
else
completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
}
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
UnityURLRequest* urequest = [UnityURLRequest requestForTask: task];
if (urequest == nil)
return;
urequest.isDone = true;
if (urequest.redirecting)
return;
if (error != nil)
UnityReportWebRequestNetworkError(urequest.udata, (int)[error code]);
UnityReportWebRequestFinishedLoadingData(urequest.udata);
}
@end
extern "C" void* UnityCreateWebRequestBackend(void* udata, const char* methodString, const void* headerDict, const char* url)
{
@autoreleasepool
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
@autoreleasepool
{
webOperationQueue = [[NSOperationQueue alloc] init];
webOperationQueue.name = @"com.unity3d.WebOperationQueue";
currentRequests = [[NSMutableArray<UnityURLRequest*> alloc] init];
currentRequestsLock = [[NSLock alloc] init];
NSURLSessionConfiguration* config = [NSURLSessionConfiguration defaultSessionConfiguration];
UnityWebRequestDelegate* delegate = [[UnityWebRequestDelegate alloc] init];
unityWebRequestSession = [NSURLSession sessionWithConfiguration: config delegate: delegate delegateQueue: webOperationQueue];
}
});
UnityURLRequest* request = [[UnityURLRequest alloc] init: udata];
request.URL = [NSURL URLWithString: [NSString stringWithUTF8String: url]];
request.HTTPMethod = [NSString stringWithUTF8String: methodString];
request.allHTTPHeaderFields = (__bridge NSMutableDictionary*)headerDict;
[request setCachePolicy: NSURLRequestReloadIgnoringLocalCacheData];
return (__bridge_retained void*)request;
}
}
extern "C" void UnitySendWebRequest(void* connection, unsigned length, unsigned long timeoutSec, bool wantCertificateCallback)
{
@autoreleasepool
{
UnityURLRequest* request = (__bridge UnityURLRequest*)connection;
request.wantCertificateCallback = wantCertificateCallback;
request.timeoutInterval = timeoutSec;
NSOutputStream* outputStream = nil;
if (length > 0)
{
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreateBoundPair(kCFAllocatorDefault, &readStream, &writeStream, streamSize);
CFWriteStreamOpen(writeStream);
outputStream = (__bridge_transfer NSOutputStream*)writeStream;
request.HTTPBodyStream = (__bridge_transfer NSInputStream*)readStream;
}
NSURLSessionTask* task = [unityWebRequestSession dataTaskWithRequest: request];
[UnityURLRequest storeRequest: request taskID: task.taskIdentifier];
[task resume];
if (length > 0)
[webOperationQueue addOperationWithBlock:^{
[UnityURLRequest writeBody: outputStream task: task udata: request.udata];
}];
}
}
extern "C" bool UnityWebRequestIsDone(void* connection)
{
@autoreleasepool
{
UnityURLRequest* request = (__bridge UnityURLRequest*)connection;
return request.isDone;
}
}
extern "C" void UnityDestroyWebRequestBackend(void* connection)
{
@autoreleasepool
{
UnityURLRequest* request = (__bridge_transfer UnityURLRequest*)connection;
[UnityURLRequest removeRequest: request];
}
}
extern "C" void UnityCancelWebRequest(void* connection)
{
@autoreleasepool
{
UnityURLRequest* request = (__bridge UnityURLRequest*)connection;
[unityWebRequestSession getAllTasksWithCompletionHandler:^(NSArray<NSURLSessionTask*>* _Nonnull tasks) {
for (unsigned i = 0; i < tasks.count; ++i)
if (tasks[i].taskIdentifier == request.taskIdentifier)
{
[tasks[i] cancel];
break;
}
}];
}
}