]> git.saurik.com Git - apple/security.git/blob - keychain/analytics/SecMetrics.m
Security-59306.11.20.tar.gz
[apple/security.git] / keychain / analytics / SecMetrics.m
1 /*
2 * Copyright (c) 2018 Apple Inc. All Rights Reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
11 * file.
12 *
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23
24 #import <os/transaction_private.h>
25 #import <Foundation/Foundation.h>
26 #import <CFNetwork/CFURLConnection.h>
27 #import <Accounts/Accounts.h>
28 #import <Accounts/Accounts_Private.h>
29 #import <AppleAccount/ACAccount+AppleAccount.h>
30 #import <AppleAccount/ACAccountStore+AppleAccount.h>
31 #import <zlib.h>
32
33 #import "keychain/analytics/SecMetrics.h"
34 #import "keychain/analytics/SecEventMetric.h"
35 #import "keychain/analytics/SecEventMetric_private.h"
36 #import "keychain/analytics/SecC2DeviceInfo.h"
37
38 #import "keychain/analytics/C2Metric/SECC2MPMetric.h"
39 #import "keychain/analytics/C2Metric/SECC2MPGenericEvent.h"
40 #import "keychain/analytics/C2Metric/SECC2MPGenericEventMetric.h"
41 #import "keychain/analytics/C2Metric/SECC2MPGenericEventMetricValue.h"
42 #import "keychain/analytics/C2Metric/SECC2MPDeviceInfo.h"
43 #import <utilities/SecCoreAnalytics.h>
44
45
46
47 @interface SecMetrics () <NSURLSessionDelegate>
48 @property (strong) NSMutableDictionary<NSNumber *, SecEventMetric *> *taskMap;
49 @property (strong) NSURLSession *URLSession;
50 @property (strong) os_transaction_t transaction;
51 @property (assign) long lostEvents;
52 @end
53
54
55 static NSString *securtitydPushTopic = @"com.apple.private.alloy.keychain.metrics";
56
57 @implementation SecMetrics
58
59 + (NSURL *)c2MetricsEndpoint {
60 ACAccountStore *store = [[ACAccountStore alloc] init];
61 ACAccount* primaryAccount = [store aa_primaryAppleAccount];
62 if(!primaryAccount) {
63 return nil;
64 }
65 NSString *urlString = [primaryAccount propertiesForDataclass:ACAccountDataclassCKMetricsService][@"url"];
66 if (urlString == NULL) {
67 return nil;
68 }
69
70 NSURL *url = [[[NSURL alloc] initWithString:urlString] URLByAppendingPathComponent:@"c2"];
71
72 if (url) {
73 static dispatch_once_t onceToken;
74 dispatch_once(&onceToken, ^{
75 os_log(OS_LOG_DEFAULT, "metrics URL is: %@", url);
76 });
77 }
78
79 return url;
80 }
81
82 + (SecMetrics *)managerObject {
83 static SecMetrics *manager;
84 static dispatch_once_t onceToken;
85 dispatch_once(&onceToken, ^{
86 manager = [[SecMetrics alloc] init];
87 });
88 return manager;
89 }
90
91 - (instancetype)init
92 {
93 if ((self = [super init]) == NULL) {
94 return self;
95 }
96
97 NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration];
98
99 self.URLSession = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:NULL];
100 self.taskMap = [NSMutableDictionary dictionary];
101 return self;
102 }
103
104 - (void)submitEvent:(SecEventMetric *)metric
105 {
106 [self sendEvent:metric pushTopic:securtitydPushTopic];
107 }
108
109
110 - (void)sendEvent:(SecEventMetric *)event pushTopic:(NSString *)pushTopic
111 {
112 bool tooMany = false;
113
114 @synchronized(self) {
115 if ([self.taskMap count] > 5) {
116 self.lostEvents++;
117 tooMany = true;
118 }
119 }
120 if (tooMany) {
121 os_log(OS_LOG_DEFAULT, "metrics %@ dropped on floor since too many are pending", event.eventName);
122 return;
123 }
124
125 SECC2MPGenericEvent *genericEvent = [event genericEvent];
126 if (genericEvent == NULL) {
127 return;
128 }
129
130 NSMutableURLRequest *request = [self requestForGenericEvent:genericEvent];
131 if (request == NULL) {
132 return;
133 }
134
135 NSURLSessionDataTask *task = [self.URLSession dataTaskWithRequest:request];
136 if (pushTopic) {
137 #if !TARGET_OS_BRIDGE
138 task._APSRelayTopic = pushTopic;
139 #endif
140 }
141
142 @synchronized(self) {
143 if ([self.taskMap count] == 0) {
144 self.transaction = os_transaction_create("com.apple.security.c2metric.upload");
145 }
146 self.taskMap[@(task.taskIdentifier)] = event;
147 }
148
149 [task resume];
150 }
151
152 - (SecEventMetric *)getEvent:(NSURLSessionTask *)task
153 {
154 @synchronized(self) {
155 return self.taskMap[@(task.taskIdentifier)];
156 }
157 }
158
159 //MARK: - URLSession Callbacks
160
161 - (void) URLSession:(NSURLSession *)session
162 task:(NSURLSessionTask *)task
163 didCompleteWithError:(nullable NSError *)error
164 {
165 SecEventMetric *event = [self getEvent:task];
166
167 os_log(OS_LOG_DEFAULT, "metrics %@ transfer %@ completed with: %@",
168 event.eventName, task.originalRequest.URL, error ? [error description] : @"success");
169
170 @synchronized(self) {
171 [self.taskMap removeObjectForKey:@(task.taskIdentifier)];
172 if (self.lostEvents || error) {
173 NSMutableDictionary *event = [NSMutableDictionary dictionary];
174
175 if (self.lostEvents) {
176 event[@"counter"] = @(self.lostEvents);
177 }
178 if (error) {
179 event[@"error_code"] = @(error.code);
180 event[@"error_domain"] = error.domain;
181 }
182 [SecCoreAnalytics sendEvent:@"com.apple.security.push.channel.dropped" event:event];
183 self.lostEvents = 0;
184 }
185
186 if (self.taskMap.count == 0) {
187 self.transaction = NULL;
188 }
189 }
190 }
191
192 //MARK: - FOO
193
194
195 - (NSMutableURLRequest*)requestForGenericEvent:(SECC2MPGenericEvent*)genericEvent
196 {
197 NSURL* metricURL = [[self class] c2MetricsEndpoint];
198 if (!metricURL) {
199 return nil;
200 }
201
202 NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:metricURL];
203 if (!request) {
204 return nil;
205 }
206
207 SECC2MPMetric* metrics = [[SECC2MPMetric alloc] init];
208 if (!metrics) {
209 return nil;
210 }
211 metrics.deviceInfo = [self generateDeviceInfo];
212 metrics.reportFrequency = 0;
213 metrics.reportFrequencyBase = 0;
214
215 metrics.metricType = SECC2MPMetric_Type_generic_event_type;
216 metrics.genericEvent = genericEvent;
217
218 PBDataWriter* protobufWriter = [[PBDataWriter alloc] init];
219 if (!protobufWriter) {
220 return nil;
221 }
222 [metrics writeTo:protobufWriter];
223 NSData* metricData = [protobufWriter immutableData];
224 if (!metricData) {
225 return nil;
226 }
227 NSData* compressedData = [self gzipEncode:metricData];
228 if (!compressedData) {
229 return nil;
230 }
231 [request setHTTPMethod:@"POST"];
232 [request setHTTPBody:compressedData];
233 [request setValue:@"application/protobuf" forHTTPHeaderField:@"Content-Type"];
234 [request setValue:@"gzip" forHTTPHeaderField:@"Content-Encoding"];
235
236 return request;
237 }
238
239 #define CHUNK 1024
240
241 - (NSData*) gzipEncode:(NSData*)bodyData {
242 unsigned have;
243 unsigned char outBytes[CHUNK] = {0};
244 NSMutableData *compressedData = [NSMutableData data];
245
246 /* allocate deflate state */
247 z_stream _zlibStream;
248 _zlibStream.zalloc = Z_NULL;
249 _zlibStream.zfree = Z_NULL;
250 _zlibStream.opaque = Z_NULL;
251
252 // generate gzip header/trailer, use defaults for all other values
253 int ret = deflateInit2(&_zlibStream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 15 + 16, 8, Z_DEFAULT_STRATEGY);
254 if (ret != Z_OK) {
255 return NULL;
256 }
257
258 NS_VALID_UNTIL_END_OF_SCOPE NSData *arcSafeBodyData = bodyData;
259 _zlibStream.next_in = (Bytef *)[arcSafeBodyData bytes];
260 _zlibStream.avail_in = (unsigned int)[arcSafeBodyData length];
261 do {
262 _zlibStream.avail_out = CHUNK;
263 _zlibStream.next_out = outBytes;
264 ret = deflate(&_zlibStream, Z_FINISH);
265 assert(ret != Z_STREAM_ERROR);
266 have = CHUNK - _zlibStream.avail_out;
267 [compressedData appendBytes:outBytes length:have];
268 } while (_zlibStream.avail_out == 0);
269 assert(_zlibStream.avail_in == 0);
270 deflateEnd(&_zlibStream);
271
272 return compressedData;
273 }
274
275
276 - (SECC2MPDeviceInfo*) generateDeviceInfo {
277 SECC2MPDeviceInfo* deviceInfo = [[SECC2MPDeviceInfo alloc] init];
278 deviceInfo.productName = [SecC2DeviceInfo productName];
279 deviceInfo.productType = [SecC2DeviceInfo productType];
280 deviceInfo.productVersion = [SecC2DeviceInfo productVersion];
281 deviceInfo.productBuild = [SecC2DeviceInfo buildVersion];
282 deviceInfo.processName = [SecC2DeviceInfo processName];
283 deviceInfo.processVersion = [SecC2DeviceInfo processVersion];
284 deviceInfo.processUuid = [SecC2DeviceInfo processUUID];
285 return deviceInfo;
286 }
287
288 @end