2 * Copyright (c) 2018 Apple Inc. All Rights Reserved.
4 * @APPLE_LICENSE_HEADER_START@
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
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.
21 * @APPLE_LICENSE_HEADER_END@
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>
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"
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>
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;
55 static NSString *securtitydPushTopic = @"com.apple.private.alloy.keychain.metrics";
57 @implementation SecMetrics
59 + (NSURL *)c2MetricsEndpoint {
60 ACAccountStore *store = [[ACAccountStore alloc] init];
61 ACAccount* primaryAccount = [store aa_primaryAppleAccount];
65 NSString *urlString = [primaryAccount propertiesForDataclass:ACAccountDataclassCKMetricsService][@"url"];
66 if (urlString == NULL) {
70 NSURL *url = [[[NSURL alloc] initWithString:urlString] URLByAppendingPathComponent:@"c2"];
73 static dispatch_once_t onceToken;
74 dispatch_once(&onceToken, ^{
75 os_log(OS_LOG_DEFAULT, "metrics URL is: %@", url);
82 + (SecMetrics *)managerObject {
83 static SecMetrics *manager;
84 static dispatch_once_t onceToken;
85 dispatch_once(&onceToken, ^{
86 manager = [[SecMetrics alloc] init];
93 if ((self = [super init]) == NULL) {
97 NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration];
99 self.URLSession = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:NULL];
100 self.taskMap = [NSMutableDictionary dictionary];
104 - (void)submitEvent:(SecEventMetric *)metric
106 [self sendEvent:metric pushTopic:securtitydPushTopic];
110 - (void)sendEvent:(SecEventMetric *)event pushTopic:(NSString *)pushTopic
112 bool tooMany = false;
114 @synchronized(self) {
115 if ([self.taskMap count] > 5) {
121 os_log(OS_LOG_DEFAULT, "metrics %@ dropped on floor since too many are pending", event.eventName);
125 SECC2MPGenericEvent *genericEvent = [event genericEvent];
126 if (genericEvent == NULL) {
130 NSMutableURLRequest *request = [self requestForGenericEvent:genericEvent];
131 if (request == NULL) {
135 NSURLSessionDataTask *task = [self.URLSession dataTaskWithRequest:request];
137 #if !TARGET_OS_BRIDGE
138 task._APSRelayTopic = pushTopic;
142 @synchronized(self) {
143 if ([self.taskMap count] == 0) {
144 self.transaction = os_transaction_create("com.apple.security.c2metric.upload");
146 self.taskMap[@(task.taskIdentifier)] = event;
152 - (SecEventMetric *)getEvent:(NSURLSessionTask *)task
154 @synchronized(self) {
155 return self.taskMap[@(task.taskIdentifier)];
159 //MARK: - URLSession Callbacks
161 - (void) URLSession:(NSURLSession *)session
162 task:(NSURLSessionTask *)task
163 didCompleteWithError:(nullable NSError *)error
165 SecEventMetric *event = [self getEvent:task];
167 os_log(OS_LOG_DEFAULT, "metrics %@ transfer %@ completed with: %@",
168 event.eventName, task.originalRequest.URL, error ? [error description] : @"success");
170 @synchronized(self) {
171 [self.taskMap removeObjectForKey:@(task.taskIdentifier)];
172 if (self.lostEvents || error) {
173 NSMutableDictionary *event = [NSMutableDictionary dictionary];
175 if (self.lostEvents) {
176 event[@"counter"] = @(self.lostEvents);
179 event[@"error_code"] = @(error.code);
180 event[@"error_domain"] = error.domain;
182 [SecCoreAnalytics sendEvent:@"com.apple.security.push.channel.dropped" event:event];
186 if (self.taskMap.count == 0) {
187 self.transaction = NULL;
195 - (NSMutableURLRequest*)requestForGenericEvent:(SECC2MPGenericEvent*)genericEvent
197 NSURL* metricURL = [[self class] c2MetricsEndpoint];
202 NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:metricURL];
207 SECC2MPMetric* metrics = [[SECC2MPMetric alloc] init];
211 metrics.deviceInfo = [self generateDeviceInfo];
212 metrics.reportFrequency = 0;
213 metrics.reportFrequencyBase = 0;
215 metrics.metricType = SECC2MPMetric_Type_generic_event_type;
216 metrics.genericEvent = genericEvent;
218 PBDataWriter* protobufWriter = [[PBDataWriter alloc] init];
219 if (!protobufWriter) {
222 [metrics writeTo:protobufWriter];
223 NSData* metricData = [protobufWriter immutableData];
227 NSData* compressedData = [self gzipEncode:metricData];
228 if (!compressedData) {
231 [request setHTTPMethod:@"POST"];
232 [request setHTTPBody:compressedData];
233 [request setValue:@"application/protobuf" forHTTPHeaderField:@"Content-Type"];
234 [request setValue:@"gzip" forHTTPHeaderField:@"Content-Encoding"];
241 - (NSData*) gzipEncode:(NSData*)bodyData {
243 unsigned char outBytes[CHUNK] = {0};
244 NSMutableData *compressedData = [NSMutableData data];
246 /* allocate deflate state */
247 z_stream _zlibStream;
248 _zlibStream.zalloc = Z_NULL;
249 _zlibStream.zfree = Z_NULL;
250 _zlibStream.opaque = Z_NULL;
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);
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];
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);
272 return compressedData;
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];