2 * Copyright (c) 2017 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@
26 #import "SFAnalytics+Internal.h"
27 #import "SFAnalyticsDefines.h"
28 #import "SFAnalyticsActivityTracker+Internal.h"
29 #import "SFAnalyticsSampler+Internal.h"
30 #import "SFAnalyticsMultiSampler+Internal.h"
31 #import "SFAnalyticsSQLiteStore.h"
32 #import "utilities/debugging.h"
33 #import <objc/runtime.h>
34 #import <CoreFoundation/CFPriv.h>
36 // SFAnalyticsDefines constants
37 NSString* const SFAnalyticsTableSuccessCount = @"success_count";
38 NSString* const SFAnalyticsTableHardFailures = @"hard_failures";
39 NSString* const SFAnalyticsTableSoftFailures = @"soft_failures";
40 NSString* const SFAnalyticsTableSamples = @"samples";
41 NSString* const SFAnalyticsTableAllEvents = @"all_events";
43 NSString* const SFAnalyticsColumnSuccessCount = @"success_count";
44 NSString* const SFAnalyticsColumnHardFailureCount = @"hard_failure_count";
45 NSString* const SFAnalyticsColumnSoftFailureCount = @"soft_failure_count";
46 NSString* const SFAnalyticsColumnSampleValue = @"value";
47 NSString* const SFAnalyticsColumnSampleName = @"name";
49 NSString* const SFAnalyticsEventTime = @"eventTime";
50 NSString* const SFAnalyticsEventType = @"eventType";
51 NSString* const SFAnalyticsEventClassKey = @"eventClass";
53 NSString* const SFAnalyticsAttributeErrorUnderlyingChain = @"errorChain";
54 NSString* const SFAnalyticsAttributeErrorDomain = @"errorDomain";
55 NSString* const SFAnalyticsAttributeErrorCode = @"errorCode";
57 NSString* const SFAnalyticsUserDefaultsSuite = @"com.apple.security.analytics";
59 char* const SFAnalyticsFireSamplersNotification = "com.apple.security.sfanalytics.samplers";
61 NSString* const SFAnalyticsTopicKeySync = @"KeySyncTopic";
62 NSString* const SFAnaltyicsTopicTrust = @"TrustTopic";
64 NSString* const SFAnalyticsTableSchema = @"CREATE TABLE IF NOT EXISTS hard_failures (\n"
65 @"id INTEGER PRIMARY KEY AUTOINCREMENT,\n"
69 @"CREATE TRIGGER IF NOT EXISTS maintain_ring_buffer_hard_failures AFTER INSERT ON hard_failures\n"
71 @"DELETE FROM hard_failures WHERE id != NEW.id AND id % 1000 = NEW.id % 1000;\n"
73 @"CREATE TABLE IF NOT EXISTS soft_failures (\n"
74 @"id INTEGER PRIMARY KEY AUTOINCREMENT,\n"
78 @"CREATE TRIGGER IF NOT EXISTS maintain_ring_buffer_soft_failures AFTER INSERT ON soft_failures\n"
80 @"DELETE FROM soft_failures WHERE id != NEW.id AND id % 1000 = NEW.id % 1000;\n"
82 @"CREATE TABLE IF NOT EXISTS all_events (\n"
83 @"id INTEGER PRIMARY KEY AUTOINCREMENT,\n"
87 @"CREATE TRIGGER IF NOT EXISTS maintain_ring_buffer_all_events AFTER INSERT ON all_events\n"
89 @"DELETE FROM all_events WHERE id != NEW.id AND id % 10000 = NEW.id % 10000;\n"
91 @"CREATE TABLE IF NOT EXISTS samples (\n"
92 @"id INTEGER PRIMARY KEY AUTOINCREMENT,\n"
97 @"CREATE TRIGGER IF NOT EXISTS maintain_ring_buffer_samples AFTER INSERT ON samples\n"
99 @"DELETE FROM samples WHERE id != NEW.id AND id % 1000 = NEW.id % 1000;\n"
101 @"CREATE TABLE IF NOT EXISTS success_count (\n"
102 @"event_type STRING PRIMARY KEY,\n"
103 @"success_count INTEGER,\n"
104 @"hard_failure_count INTEGER,\n"
105 @"soft_failure_count INTEGER\n"
108 NSUInteger const SFAnalyticsMaxEventsToReport = 1000;
111 NSString* const SFAnalyticsEventBuild = @"build";
112 NSString* const SFAnalyticsEventProduct = @"product";
113 const NSTimeInterval SFAnalyticsSamplerIntervalOncePerReport = -1.0;
115 @interface SFAnalytics ()
116 @property (nonatomic) SFAnalyticsSQLiteStore* database;
119 @implementation SFAnalytics {
120 SFAnalyticsSQLiteStore* _database;
121 dispatch_queue_t _queue;
122 NSMutableDictionary<NSString*, SFAnalyticsSampler*>* _samplers;
123 NSMutableDictionary<NSString*, SFAnalyticsMultiSampler*>* _multisamplers;
124 unsigned int _disableLogging:1;
127 + (instancetype)logger
129 #if TARGET_OS_SIMULATOR
133 if (self == [SFAnalytics class]) {
134 secerror("attempt to instatiate abstract class SFAnalytics");
138 SFAnalytics* logger = nil;
139 @synchronized(self) {
140 logger = objc_getAssociatedObject(self, "SFAnalyticsInstance");
142 logger = [[self alloc] init];
143 objc_setAssociatedObject(self, "SFAnalyticsInstance", logger, OBJC_ASSOCIATION_RETAIN);
147 [logger database]; // For unit testing so there's always a database. DB shouldn't be nilled in production though
152 + (NSString*)databasePath
157 + (NSInteger)fuzzyDaysSinceDate:(NSDate*)date
159 // Sentinel: it didn't happen at all
164 // Sentinel: it happened but we don't know when because the date doesn't make sense
165 // Magic number represents January 1, 2017.
166 if ([date compare:[NSDate dateWithTimeIntervalSince1970:1483228800]] == NSOrderedAscending) {
170 NSInteger secondsPerDay = 60 * 60 * 24;
172 NSTimeInterval timeIntervalSinceDate = [[NSDate date] timeIntervalSinceDate:date];
173 if (timeIntervalSinceDate < secondsPerDay) {
176 else if (timeIntervalSinceDate < (secondsPerDay * 7)) {
179 else if (timeIntervalSinceDate < (secondsPerDay * 30)) {
182 else if (timeIntervalSinceDate < (secondsPerDay * 365)) {
190 // Instantiate lazily so unit tests can have clean databases each
191 - (SFAnalyticsSQLiteStore*)database
194 _database = [SFAnalyticsSQLiteStore storeWithPath:self.class.databasePath schema:SFAnalyticsTableSchema];
201 [_samplers removeAllObjects];
202 [_multisamplers removeAllObjects];
204 __weak __typeof(self) weakSelf = self;
205 dispatch_sync(_queue, ^{
206 __strong __typeof(self) strongSelf = weakSelf;
208 [strongSelf.database close];
209 strongSelf->_database = nil;
214 - (void)setDateProperty:(NSDate*)date forKey:(NSString*)key
216 __weak __typeof(self) weakSelf = self;
217 dispatch_sync(_queue, ^{
218 __strong __typeof(self) strongSelf = weakSelf;
220 [strongSelf.database setDateProperty:date forKey:key];
225 - (NSDate*)datePropertyForKey:(NSString*)key
227 __block NSDate* result = nil;
228 __weak __typeof(self) weakSelf = self;
229 dispatch_sync(_queue, ^{
230 __strong __typeof(self) strongSelf = weakSelf;
232 result = [strongSelf.database datePropertyForKey:key];
238 + (void)addOSVersionToEvent:(NSMutableDictionary*)eventDict {
239 static dispatch_once_t onceToken;
240 static NSString *build = NULL;
241 static NSString *product = NULL;
242 dispatch_once(&onceToken, ^{
243 NSDictionary *version = CFBridgingRelease(_CFCopySystemVersionDictionary());
246 build = version[(__bridge NSString *)_kCFSystemVersionBuildVersionKey];
247 product = version[(__bridge NSString *)_kCFSystemVersionProductNameKey];
250 eventDict[SFAnalyticsEventBuild] = build;
253 eventDict[SFAnalyticsEventProduct] = product;
259 if (self = [super init]) {
260 _queue = dispatch_queue_create("SFAnalytics data access queue", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL);
261 _samplers = [NSMutableDictionary<NSString*, SFAnalyticsSampler*> new];
262 _multisamplers = [NSMutableDictionary<NSString*, SFAnalyticsMultiSampler*> new];
263 [self database]; // for side effect of instantiating DB object. Used for testing.
269 // MARK: Event logging
271 - (void)logSuccessForEventNamed:(NSString*)eventName
273 [self logEventNamed:eventName class:SFAnalyticsEventClassSuccess attributes:nil];
276 - (void)logHardFailureForEventNamed:(NSString*)eventName withAttributes:(NSDictionary*)attributes
278 [self logEventNamed:eventName class:SFAnalyticsEventClassHardFailure attributes:attributes];
281 - (void)logSoftFailureForEventNamed:(NSString*)eventName withAttributes:(NSDictionary*)attributes
283 [self logEventNamed:eventName class:SFAnalyticsEventClassSoftFailure attributes:attributes];
286 - (void)logResultForEvent:(NSString*)eventName hardFailure:(bool)hardFailure result:(NSError*)eventResultError
288 if(!eventResultError) {
289 [self logSuccessForEventNamed:eventName];
291 // Make an Attributes dictionary
292 NSMutableDictionary* eventAttributes = [NSMutableDictionary dictionary];
294 /* if we have underlying errors, capture the chain below the top-most error */
295 NSError *underlyingError = eventResultError.userInfo[NSUnderlyingErrorKey];
296 if ([underlyingError isKindOfClass:[NSError class]]) {
297 NSMutableString *chain = [NSMutableString string];
300 [chain appendFormat:@"%@-%ld:", underlyingError.domain, (long)underlyingError.code];
301 underlyingError = underlyingError.userInfo[NSUnderlyingErrorKey];
302 } while (count++ < 5 && [underlyingError isKindOfClass:[NSError class]]);
304 eventAttributes[SFAnalyticsAttributeErrorUnderlyingChain] = chain;
307 eventAttributes[SFAnalyticsAttributeErrorDomain] = eventResultError.domain;
308 eventAttributes[SFAnalyticsAttributeErrorCode] = @(eventResultError.code);
311 [self logHardFailureForEventNamed:eventName withAttributes:eventAttributes];
313 [self logSoftFailureForEventNamed:eventName withAttributes:eventAttributes];
318 - (void)noteEventNamed:(NSString*)eventName
320 [self logEventNamed:eventName class:SFAnalyticsEventClassNote attributes:nil];
323 - (void)logEventNamed:(NSString*)eventName class:(SFAnalyticsEventClass)class attributes:(NSDictionary*)attributes
326 secerror("SFAnalytics: attempt to log an event with no name");
330 __weak __typeof(self) weakSelf = self;
331 dispatch_sync(_queue, ^{
332 __strong __typeof(self) strongSelf = weakSelf;
333 if (!strongSelf || strongSelf->_disableLogging) {
337 NSDictionary* eventDict = [self eventDictForEventName:eventName withAttributes:attributes eventClass:class];
338 [strongSelf.database addEventDict:eventDict toTable:SFAnalyticsTableAllEvents];
340 if (class == SFAnalyticsEventClassHardFailure) {
341 [strongSelf.database addEventDict:eventDict toTable:SFAnalyticsTableHardFailures];
342 [strongSelf.database incrementHardFailureCountForEventType:eventName];
344 else if (class == SFAnalyticsEventClassSoftFailure) {
345 [strongSelf.database addEventDict:eventDict toTable:SFAnalyticsTableSoftFailures];
346 [strongSelf.database incrementSoftFailureCountForEventType:eventName];
348 else if (class == SFAnalyticsEventClassSuccess || class == SFAnalyticsEventClassNote) {
349 [strongSelf.database incrementSuccessCountForEventType:eventName];
354 - (NSDictionary*)eventDictForEventName:(NSString*)eventName withAttributes:(NSDictionary*)attributes eventClass:(SFAnalyticsEventClass)eventClass
356 NSMutableDictionary* eventDict = attributes ? attributes.mutableCopy : [NSMutableDictionary dictionary];
357 eventDict[SFAnalyticsEventType] = eventName;
358 // our backend wants timestamps in milliseconds
359 eventDict[SFAnalyticsEventTime] = @([[NSDate date] timeIntervalSince1970] * 1000);
360 eventDict[SFAnalyticsEventClassKey] = @(eventClass);
361 [SFAnalytics addOSVersionToEvent:eventDict];
368 - (SFAnalyticsSampler*)addMetricSamplerForName:(NSString *)samplerName withTimeInterval:(NSTimeInterval)timeInterval block:(NSNumber *(^)(void))block
371 secerror("SFAnalytics: cannot add sampler without name");
374 if (timeInterval < 1.0f && timeInterval != SFAnalyticsSamplerIntervalOncePerReport) {
375 secerror("SFAnalytics: cannot add sampler with interval %f", timeInterval);
379 secerror("SFAnalytics: cannot add sampler without block");
383 __block SFAnalyticsSampler* sampler = nil;
385 __weak __typeof(self) weakSelf = self;
386 dispatch_sync(_queue, ^{
387 __strong __typeof(self) strongSelf = weakSelf;
388 if (strongSelf->_samplers[samplerName]) {
389 secerror("SFAnalytics: sampler \"%@\" already exists", samplerName);
391 sampler = [[SFAnalyticsSampler alloc] initWithName:samplerName interval:timeInterval block:block clientClass:[self class]];
392 strongSelf->_samplers[samplerName] = sampler; // If sampler did not init because of bad data this 'removes' it from the dict, so a noop
399 - (SFAnalyticsMultiSampler*)AddMultiSamplerForName:(NSString *)samplerName withTimeInterval:(NSTimeInterval)timeInterval block:(NSDictionary<NSString *,NSNumber *> *(^)(void))block
402 secerror("SFAnalytics: cannot add sampler without name");
405 if (timeInterval < 1.0f && timeInterval != SFAnalyticsSamplerIntervalOncePerReport) {
406 secerror("SFAnalytics: cannot add sampler with interval %f", timeInterval);
410 secerror("SFAnalytics: cannot add sampler without block");
414 __block SFAnalyticsMultiSampler* sampler = nil;
415 __weak __typeof(self) weakSelf = self;
416 dispatch_sync(_queue, ^{
417 __strong __typeof(self) strongSelf = weakSelf;
418 if (strongSelf->_multisamplers[samplerName]) {
419 secerror("SFAnalytics: multisampler \"%@\" already exists", samplerName);
421 sampler = [[SFAnalyticsMultiSampler alloc] initWithName:samplerName interval:timeInterval block:block clientClass:[self class]];
422 strongSelf->_multisamplers[samplerName] = sampler;
430 - (SFAnalyticsSampler*)existingMetricSamplerForName:(NSString *)samplerName
432 __block SFAnalyticsSampler* sampler = nil;
434 __weak __typeof(self) weakSelf = self;
435 dispatch_sync(_queue, ^{
436 __strong __typeof(self) strongSelf = weakSelf;
438 sampler = strongSelf->_samplers[samplerName];
444 - (SFAnalyticsMultiSampler*)existingMultiSamplerForName:(NSString *)samplerName
446 __block SFAnalyticsMultiSampler* sampler = nil;
448 __weak __typeof(self) weakSelf = self;
449 dispatch_sync(_queue, ^{
450 __strong __typeof(self) strongSelf = weakSelf;
452 sampler = strongSelf->_multisamplers[samplerName];
458 - (void)removeMetricSamplerForName:(NSString *)samplerName
461 secerror("Attempt to remove sampler without specifying samplerName");
465 __weak __typeof(self) weakSelf = self;
466 dispatch_sync(_queue, ^{
467 __strong __typeof(self) strongSelf = weakSelf;
469 [strongSelf->_samplers[samplerName] pauseSampling]; // when dealloced it would also stop, but we're not sure when that is so let's stop it right away
470 [strongSelf->_samplers removeObjectForKey:samplerName];
475 - (void)removeMultiSamplerForName:(NSString *)samplerName
478 secerror("Attempt to remove multisampler without specifying samplerName");
482 __weak __typeof(self) weakSelf = self;
483 dispatch_sync(_queue, ^{
484 __strong __typeof(self) strongSelf = weakSelf;
486 [strongSelf->_multisamplers[samplerName] pauseSampling]; // when dealloced it would also stop, but we're not sure when that is so let's stop it right away
487 [strongSelf->_multisamplers removeObjectForKey:samplerName];
492 - (SFAnalyticsActivityTracker*)logSystemMetricsForActivityNamed:(NSString *)eventName withAction:(void (^)(void))action
494 if (![eventName isKindOfClass:[NSString class]]) {
495 secerror("Cannot log system metrics without name");
498 SFAnalyticsActivityTracker* tracker = [[SFAnalyticsActivityTracker alloc] initWithName:eventName clientClass:[self class]];
500 [tracker performAction:action];
504 - (void)logMetric:(NSNumber *)metric withName:(NSString *)metricName
506 [self logMetric:metric withName:metricName oncePerReport:NO];
509 - (void)logMetric:(NSNumber*)metric withName:(NSString*)metricName oncePerReport:(BOOL)once
511 if (![metric isKindOfClass:[NSNumber class]] || ![metricName isKindOfClass:[NSString class]]) {
512 secerror("SFAnalytics: Need a valid result and name to log result");
516 __weak __typeof(self) weakSelf = self;
517 dispatch_sync(_queue, ^{
518 __strong __typeof(self) strongSelf = weakSelf;
519 if (strongSelf && !strongSelf->_disableLogging) {
521 [strongSelf.database removeAllSamplesForName:metricName];
523 [strongSelf.database addSample:metric forName:metricName];