forked from Countly/countly-sdk-ios
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CountlyConnectionManager.m
369 lines (283 loc) · 12.3 KB
/
CountlyConnectionManager.m
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
368
369
// CountlyConnectionManager.m
//
// This code is provided under the MIT License.
//
// Please visit www.count.ly for more information.
#import "CountlyCommon.h"
NSString* const kCountlySDKVersion = @"16.06.4";
NSString* const kCountlySDKName = @"objc-native-ios";
@interface CountlyConnectionManager()
#if TARGET_OS_IOS
@property (nonatomic) UIBackgroundTaskIdentifier bgTask;
#endif
@end
@implementation CountlyConnectionManager : NSObject
+ (instancetype)sharedInstance
{
static CountlyConnectionManager *s_sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{s_sharedInstance = self.new;});
return s_sharedInstance;
}
- (void)tick
{
if (self.connection != nil)
return;
if (self.customHeaderFieldName && !self.customHeaderFieldValue)
{
COUNTLY_LOG(@"customHeaderFieldName specified on config, but customHeaderFieldValue not set! Requests are postponed!");
return;
}
NSString* firstItemInQueue = [CountlyPersistency.sharedInstance firstItemInQueue];
if (firstItemInQueue == nil)
return;
[self startBackgroundTask];
NSString* queryString = firstItemInQueue;
if(self.secretSalt)
{
NSString* checksum = [[queryString stringByAppendingString:self.secretSalt] SHA1];
queryString = [queryString stringByAppendingFormat:@"&checksum=%@", checksum];
}
//NOTE: For Limit Ad Tracking zero-IDFA problem
if([queryString rangeOfString:@"&device_id=00000000-0000-0000-0000-000000000000"].location != NSNotFound)
{
COUNTLY_LOG(@"Detected a request with device_id=[zero-IDFA] in queue and fixed.");
queryString = [queryString stringByReplacingOccurrencesOfString:@"&device_id=00000000-0000-0000-0000-000000000000" withString:[@"&device_id=" stringByAppendingString:CountlyDeviceInfo.sharedInstance.deviceID]];
}
if([queryString rangeOfString:@"&old_device_id=00000000-0000-0000-0000-000000000000"].location != NSNotFound)
{
COUNTLY_LOG(@"Detected a request with old_device_id=[zero-IDFA] in queue and fixed.");
[CountlyPersistency.sharedInstance removeFromQueue:firstItemInQueue];
[self tick];
}
NSString* countlyServerEndpoint = [self.appHost stringByAppendingString:@"/i"];
NSString* fullRequestURL = [countlyServerEndpoint stringByAppendingFormat:@"?%@", queryString];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:fullRequestURL]];
NSData* pictureUploadData = [CountlyUserDetails.sharedInstance pictureUploadDataForRequest:queryString];
if(pictureUploadData)
{
NSString *contentType = [@"multipart/form-data; boundary=" stringByAppendingString:self.boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
request.HTTPMethod = @"POST";
request.HTTPBody = pictureUploadData;
}
else if(queryString.length > 2048 || self.alwaysUsePOST)
{
request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:countlyServerEndpoint]];
request.HTTPMethod = @"POST";
request.HTTPBody = [queryString dataUTF8];
}
if(self.customHeaderFieldName && self.customHeaderFieldValue)
[request setValue:self.customHeaderFieldValue forHTTPHeaderField:self.customHeaderFieldName];
NSURLSession* session = NSURLSession.sharedSession;
if(self.pinnedCertificates)
{
COUNTLY_LOG(@"%i pinned certificate(s) specified in config.", self.pinnedCertificates.count);
NSURLSessionConfiguration *sc = [NSURLSessionConfiguration defaultSessionConfiguration];
session = [NSURLSession sessionWithConfiguration:sc delegate:self delegateQueue:nil];
}
self.connection = [session dataTaskWithRequest:request
completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error)
{
self.connection = nil;
if(!error)
{
if([self isRequestSuccessful:response])
{
COUNTLY_LOG(@"Request <%p> successfully completed.", request);
[CountlyPersistency.sharedInstance removeFromQueue:firstItemInQueue];
[CountlyPersistency.sharedInstance saveToFile];
[self tick];
}
else
{
COUNTLY_LOG(@"Request <%p> failed!\nServer reply: %@", request, [data stringUTF8]);
}
}
else
{
COUNTLY_LOG(@"Request <%p> failed!\nError: %@", request, error);
#if TARGET_OS_WATCH
[CountlyPersistency.sharedInstance saveToFile];
#endif
}
[self finishBackgroundTask];
}];
[self.connection resume];
COUNTLY_LOG(@"Request <%p> started:\n[%@] %@ \n%@", (id)request, request.HTTPMethod, request.URL.absoluteString, request.HTTPBody?([request.HTTPBody stringUTF8]?[request.HTTPBody stringUTF8]:@"Picture uploading..."):@"");
}
#pragma mark ---
- (void)beginSession
{
NSString* queryString = [[self queryEssentials] stringByAppendingFormat:@"&begin_session=1&metrics=%@", [CountlyDeviceInfo metrics]];
NSString* optionalParameters = [CountlyCommon.sharedInstance optionalParameters];
if(optionalParameters)
queryString = [queryString stringByAppendingString:optionalParameters];
[CountlyPersistency.sharedInstance addToQueue:queryString];
[self tick];
}
- (void)updateSessionWithDuration:(int)duration
{
NSString* queryString = [[self queryEssentials] stringByAppendingFormat:@"&session_duration=%d", duration];
[CountlyPersistency.sharedInstance addToQueue:queryString];
[self tick];
}
- (void)endSessionWithDuration:(int)duration
{
NSString* queryString = [[self queryEssentials] stringByAppendingFormat:@"&end_session=1&session_duration=%d", duration];
[CountlyPersistency.sharedInstance addToQueue:queryString];
[self tick];
}
- (void)sendEvents
{
NSString* events = [CountlyPersistency.sharedInstance serializedRecordedEvents];
if(!events)
return;
NSString* queryString = [[self queryEssentials] stringByAppendingFormat:@"&events=%@", events];
[CountlyPersistency.sharedInstance addToQueue:queryString];
[self tick];
}
#pragma mark ---
- (void)sendPushToken:(NSString *)token
{
// Test modes: 0 = Production build,
// 1 = Development build,
// 2 = AdHoc build (when isTestDevice flag on config object is set explicitly)
int testMode;
#ifndef __OPTIMIZE__
testMode = 1;
#else
testMode = self.isTestDevice ? 2 : 0;
#endif
NSString* queryString = [[self queryEssentials] stringByAppendingFormat:@"&token_session=1&ios_token=%@&test_mode=%d",
[token length] ? token : @"",
testMode];
// Not right now to prevent race with begin_session=1 when adding new user
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^
{
COUNTLY_LOG(@"Sending APNS token in mode %d", testMode);
[CountlyPersistency.sharedInstance addToQueue:queryString];
[self tick];
});
}
- (void)sendUserDetails:(NSString *)userDetails
{
NSString* queryString = [[self queryEssentials] stringByAppendingFormat:@"&user_details=%@", userDetails];
[CountlyPersistency.sharedInstance addToQueue:queryString];
[self tick];
}
- (void)sendCrashReportLater:(NSString *)report
{
NSString* queryString = [[self queryEssentials] stringByAppendingFormat:@"&crash=%@", report];
[CountlyPersistency.sharedInstance addToQueue:queryString];
[CountlyPersistency.sharedInstance saveToFileSync];
}
- (void)sendOldDeviceID:(NSString *)oldDeviceID
{
NSString* queryString = [[self queryEssentials] stringByAppendingFormat:@"&old_device_id=%@", oldDeviceID];
[CountlyPersistency.sharedInstance addToQueue:queryString];
[self tick];
}
- (void)sendParentDeviceID:(NSString *)parentDeviceID
{
NSString* queryString = [[self queryEssentials] stringByAppendingFormat:@"&parent_device_id=%@", parentDeviceID];
[CountlyPersistency.sharedInstance addToQueue:queryString];
[self tick];
}
- (void)sendLocation:(CLLocationCoordinate2D)coordinate
{
NSString* queryString = [[self queryEssentials] stringByAppendingFormat:@"&location=%f,%f", coordinate.latitude, coordinate.longitude];
[CountlyPersistency.sharedInstance addToQueue:queryString];
[self tick];
}
#pragma mark ---
- (void)startBackgroundTask
{
#if TARGET_OS_IOS
if (self.bgTask != UIBackgroundTaskInvalid)
return;
self.bgTask = [UIApplication.sharedApplication beginBackgroundTaskWithExpirationHandler:^
{
[UIApplication.sharedApplication endBackgroundTask:self.bgTask];
self.bgTask = UIBackgroundTaskInvalid;
}];
#endif
}
- (void)finishBackgroundTask
{
#if TARGET_OS_IOS
if (self.bgTask != UIBackgroundTaskInvalid && !self.connection)
{
[UIApplication.sharedApplication endBackgroundTask:self.bgTask];
self.bgTask = UIBackgroundTaskInvalid;
}
#endif
}
#pragma mark ---
- (NSString *)queryEssentials
{
return [NSString stringWithFormat:@"app_key=%@&device_id=%@×tamp=%ld&hour=%ld&dow=%ld&tz=%ld&sdk_version=%@&sdk_name=%@",
self.appKey,
CountlyDeviceInfo.sharedInstance.deviceID,
(long)(CountlyCommon.sharedInstance.uniqueTimestamp * 1000),
(long)CountlyCommon.sharedInstance.hourOfDay,
(long)CountlyCommon.sharedInstance.dayOfWeek,
(long)CountlyCommon.sharedInstance.timeZone,
kCountlySDKVersion,
kCountlySDKName];
}
- (NSString *)boundary
{
return @"0cae04a8b698d63ff6ea55d168993f21";
}
- (BOOL)isRequestSuccessful:(NSURLResponse *)response
{
if(!response)
return NO;
NSInteger code = ((NSHTTPURLResponse*)response).statusCode;
return (code >= 200 && code < 300);
}
#pragma mark ---
- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler
{
SecTrustRef serverTrust = challenge.protectionSpace.serverTrust;
SecKeyRef serverKey = SecTrustCopyPublicKey(serverTrust);
SecPolicyRef policy = SecPolicyCreateSSL(true, (__bridge CFStringRef)challenge.protectionSpace.host);
__block BOOL isLocalAndServerCertMatch = NO;
for (NSString* certificate in self.pinnedCertificates )
{
NSString* localCertPath = [NSBundle.mainBundle pathForResource:certificate ofType:nil];
NSAssert(localCertPath != nil, @"[CountlyAssert] Bundled certificate can not be found");
NSData* localCertData = [NSData dataWithContentsOfFile:localCertPath];
SecCertificateRef localCert = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)localCertData);
SecTrustRef localTrust = NULL;
SecTrustCreateWithCertificates(localCert, policy, &localTrust);
SecKeyRef localKey = SecTrustCopyPublicKey(localTrust);
CFRelease(localCert);
CFRelease(localTrust);
if (serverKey != NULL && localKey != NULL && [(__bridge id)serverKey isEqual:(__bridge id)localKey])
{
COUNTLY_LOG(@"Pinned certificate and server certificate match.");
isLocalAndServerCertMatch = YES;
CFRelease(localKey);
break;
}
if(localKey) CFRelease(localKey);
}
SecTrustResultType serverTrustResult;
SecTrustEvaluate(serverTrust, &serverTrustResult);
BOOL isServerCertValid = (serverTrustResult == kSecTrustResultUnspecified || serverTrustResult == kSecTrustResultProceed);
if (isLocalAndServerCertMatch && isServerCertValid)
{
COUNTLY_LOG(@"Pinned certificate check is successful. Proceeding with request.");
completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:serverTrust]);
}
else
{
COUNTLY_LOG(@"Pinned certificate check is failed! Cancelling request.");
completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, NULL);
}
if (serverKey) CFRelease(serverKey);
CFRelease(policy);
}
@end