1/*
2 * Copyright (c) 2021 Apple Inc. All rights reserved.
3 *
4 * @APPLE_OSREFERENCE_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. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
14 *
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
25 *
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27 */
28
29#define IOKIT_ENABLE_SHARED_PTR
30#include <kern/debug.h>
31#include <libkern/coreanalytics/coreanalytics.h>
32#include <libkern/coreanalytics/coreanalytics_shim.h>
33#include <libkern/c++/OSBoolean.h>
34#include <libkern/c++/OSDictionary.h>
35#include <libkern/c++/OSNumber.h>
36#include <libkern/c++/OSMetaClass.h>
37#include <libkern/c++/OSString.h>
38#include <os/atomic.h>
39#include <os/log.h>
40#include <sys/errno.h>
41
42/* Pulled from CoreAnalyticsHub.h in CoreAnalytics project */
43static const char *kCoreAnalyticsMatchingClassName = "CoreAnalyticsHub";
44
45core_analytics_hub_functions_t *core_analytics_hub_functions = NULL;
46
47core_analytics_family_service_t *
48core_analytics_family_match()
49{
50 OSSharedPtr<OSDictionary> dict = IOService::serviceMatching(className: kCoreAnalyticsMatchingClassName);
51 OSSharedPtr<IOService> service = nullptr;
52 if (dict) {
53 service = IOService::waitForMatchingService(matching: dict.get());
54 } else {
55 os_log_with_startup_serial(OS_LOG_DEFAULT, "No service matching %s", kCoreAnalyticsMatchingClassName);
56 }
57 if (service) {
58 return service.detach();
59 } else {
60 os_log_with_startup_serial(OS_LOG_DEFAULT, "Unable to match CoreAnalyticsHub");
61 return nullptr;
62 }
63}
64
65void
66core_analytics_family_release(core_analytics_family_service_t *service)
67{
68 service->release();
69}
70
71typedef struct core_analytics_serialized_event_s {
72 OSSharedPtr<OSString> case_event_name;
73 OSSharedPtr<OSDictionary> case_event;
74} core_analytics_serialized_event_t;
75
76/*
77 * Stringifying CA_BOOL is different in C vs. C++ b/c the underlying
78 * bool typename is different (_Bool vs bool).
79 * We want to support both since the event may have been defined in C or C++ code.
80 */
81extern const char *core_analytics_ca_bool_c_stringified;
82const char *core_analytics_ca_bool_cpp_stringified = _CA_STRINGIFY_EXPAND(CA_BOOL);
83
84static OSSharedPtr<OSObject>
85serialize_event_field(const char **field_spec, ptrdiff_t *event, OSSharedPtr<const OSSymbol> *key)
86{
87 OSSharedPtr<OSObject> field = nullptr;
88 ptrdiff_t field_value = (ptrdiff_t) *event;
89 uint64_t number_value;
90 const char *str_value;
91 size_t str_len = 0;
92 bool bool_value;
93
94 if (strcmp(s1: *field_spec, _CA_STRINGIFY_EXPAND(CA_INT)) == 0) {
95 number_value = *(const uint64_t *)field_value;
96 field = OSNumber::withNumber(value: number_value, numberOfBits: sizeof(uint64_t) * 8);
97 *event += sizeof(const uint64_t);
98 } else if (strcmp(s1: *field_spec, s2: core_analytics_ca_bool_cpp_stringified) == 0 ||
99 strcmp(s1: *field_spec, s2: core_analytics_ca_bool_c_stringified) == 0) {
100 bool_value = *(const bool *)field_value;
101 field = OSBoolean::withBoolean(value: bool_value);
102 *event += sizeof(const bool);
103 } else if ((str_len = core_analytics_field_is_string(field_spec: *field_spec)) != 0) {
104 str_value = (const char *) field_value;
105 assert(strlen(str_value) < str_len);
106 if (strlen(s: str_value) < str_len) {
107 field = OSString::withCString(cString: str_value);
108 } else {
109 field = nullptr;
110 }
111 *event += str_len;
112 } else {
113 panic("Unknown CoreAnalytics event type: %s.", *field_spec);
114 }
115 *field_spec += strlen(s: *field_spec) + 1;
116
117 *key = OSSymbol::withCString(cString: *field_spec);
118 assert(*key != nullptr);
119 if (!*key) {
120 return nullptr;
121 }
122 *field_spec += strlen(s: *field_spec) + 1;
123 return field;
124}
125
126static int
127core_analytics_serialize_event(const char *event_spec,
128 const ca_event_t event,
129 core_analytics_serialized_event_t *serialized_event)
130{
131 serialized_event->case_event_name = nullptr;
132 serialized_event->case_event = nullptr;
133 OSSharedPtr<OSDictionary> dict = nullptr;
134 bool success;
135 OSSharedPtr<OSString> name = OSString::withCStringNoCopy(cString: event_spec);
136 if (!name) {
137 return ENOMEM;
138 }
139 dict = OSDictionary::withCapacity(capacity: 1);
140 if (!dict) {
141 return ENOMEM;
142 }
143 const char *spec_curr = event_spec + strlen(s: event_spec) + 1;
144 ptrdiff_t event_curr = (ptrdiff_t) event->data;
145 while (strlen(s: spec_curr) != 0) {
146 OSSharedPtr<const OSSymbol> key = NULL;
147 OSSharedPtr<OSObject> object = serialize_event_field(field_spec: &spec_curr, event: &event_curr, key: &key);
148 if (!object) {
149 return ENOMEM;
150 }
151 success = dict->setObject(aKey: key, anObject: object);
152 if (!success) {
153 return ENOMEM;
154 }
155 }
156
157 serialized_event->case_event_name = name;
158 serialized_event->case_event = dict;
159 return 0;
160}
161
162int
163core_analytics_send_event_lazy(
164 core_analytics_family_service_t *core_analytics_hub,
165 const char *event_spec, const ca_event_t event)
166{
167 int ret = 0;
168 bool success;
169 static constexpr size_t kMaxRetries = 5;
170 static constexpr uint64_t kDelayBetweenRetries = 1000; // microseconds
171 core_analytics_serialized_event_t serialized;
172 if (!core_analytics_hub_functions) {
173 os_log_with_startup_serial(OS_LOG_DEFAULT, "Dropping attempt to send a CoreAnalytics event before CoreAnalyticsHub has registered.");
174 return EAGAIN;
175 }
176
177 ret = core_analytics_serialize_event(event_spec, event, serialized_event: &serialized);
178 if (ret != 0) {
179 os_log_with_startup_serial(OS_LOG_DEFAULT, "Unable to serialize CoreAnalytics event: %d", ret);
180 return ret;
181 }
182 for (size_t i = 0; i < kMaxRetries; i++) {
183 success = core_analytics_hub_functions->analytics_send_event_lazy(core_analytics_hub, serialized.case_event_name.get(), serialized.case_event.get());
184 if (success) {
185 break;
186 } else {
187 if (i != kMaxRetries - 1) {
188 os_log_with_startup_serial(OS_LOG_DEFAULT, "Unable to send CoreAnalytics event. Delaying for %llu u.s. to see if the queue drains.", kDelayBetweenRetries);
189 delay(usec: kDelayBetweenRetries);
190 } else {
191 os_log_with_startup_serial(OS_LOG_DEFAULT, "Unable to send CoreAnalytics event. Giving up.");
192 ret = EAGAIN;
193 break;
194 }
195 }
196 }
197 return ret;
198}
199
200void
201core_analytics_hub_register(core_analytics_hub_functions_t *fns)
202{
203 if (fns->version != CORE_ANALYTICS_FUNCTIONS_TABLE_VERSION) {
204 panic("CoreAnalyticsHub is out of sync with xnu. CoreAnalyticsHub table version: %d. xnu table version: %d", fns->version, CORE_ANALYTICS_FUNCTIONS_TABLE_VERSION);
205 }
206 core_analytics_hub_functions = fns;
207 os_log_with_startup_serial(OS_LOG_DEFAULT, "Registered CoreAnalyticsHub functions with xnu.");
208}
209