FIRSESNanoPBHelpers.m 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. //
  2. // Copyright 2022 Google LLC
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. #import <Foundation/Foundation.h>
  16. #import <GoogleUtilities/GULNetworkInfo.h>
  17. #import "FirebaseSessions/SourcesObjC/NanoPB/FIRSESNanoPBHelpers.h"
  18. #import "FirebaseSessions/SourcesObjC/Protogen/nanopb/sessions.nanopb.h"
  19. @import FirebaseCoreExtension;
  20. #import <nanopb/pb.h>
  21. #import <nanopb/pb_decode.h>
  22. #import <nanopb/pb_encode.h>
  23. #import <sys/sysctl.h>
  24. NS_ASSUME_NONNULL_BEGIN
  25. void nanopb_free(void *_Nullable ptr) {
  26. pb_free(ptr);
  27. }
  28. NSError *FIRSESMakeEncodeError(NSString *description) {
  29. return [NSError errorWithDomain:@"FIRSESEncodeError"
  30. code:-1
  31. userInfo:@{@"NSLocalizedDescriptionKey" : description}];
  32. }
  33. NSString *FIRSESPBGetError(pb_istream_t istream) {
  34. return [NSString stringWithCString:PB_GET_ERROR(&istream) encoding:NSASCIIStringEncoding];
  35. }
  36. // It seems impossible to specify the nullability of the `fields` parameter below,
  37. // yet the compiler complains that it's missing a nullability specifier. Google
  38. // yields no results at this time.
  39. //
  40. // Note 4/17/2023: The warning seems to be spurious (pb_field_t is a non-pointer
  41. // type) and is not present on Xcode 14+. This pragma can be removed after the
  42. // minimum supported Xcode version is above 14.
  43. #pragma clang diagnostic push
  44. #pragma clang diagnostic ignored "-Wnullability-completeness"
  45. NSData *_Nullable FIRSESEncodeProto(const pb_field_t fields[],
  46. const void *_Nonnull proto,
  47. NSError **error) {
  48. pb_ostream_t sizestream = PB_OSTREAM_SIZING;
  49. // Encode 1 time to determine the size.
  50. if (!pb_encode(&sizestream, fields, proto)) {
  51. NSString *errorString = [NSString
  52. stringWithFormat:@"Error in nanopb encoding to get size: %s", PB_GET_ERROR(&sizestream)];
  53. if (error != NULL) {
  54. *error = FIRSESMakeEncodeError(errorString);
  55. }
  56. return nil;
  57. }
  58. // Encode a 2nd time to actually get the bytes from it.
  59. size_t bufferSize = sizestream.bytes_written;
  60. CFMutableDataRef dataRef = CFDataCreateMutable(CFAllocatorGetDefault(), bufferSize);
  61. CFDataSetLength(dataRef, bufferSize);
  62. pb_ostream_t ostream = pb_ostream_from_buffer((void *)CFDataGetBytePtr(dataRef), bufferSize);
  63. if (!pb_encode(&ostream, fields, proto)) {
  64. NSString *errorString =
  65. [NSString stringWithFormat:@"Error in nanopb encoding: %s", PB_GET_ERROR(&sizestream)];
  66. if (error != NULL) {
  67. *error = FIRSESMakeEncodeError(errorString);
  68. }
  69. CFBridgingRelease(dataRef);
  70. return nil;
  71. }
  72. return CFBridgingRelease(dataRef);
  73. }
  74. #pragma clang diagnostic pop
  75. /** Mallocs a pb_bytes_array and copies the given NSData bytes into the bytes array.
  76. * @note Memory needs to be free manually, through pb_free or pb_release.
  77. * @param data The data to copy into the new bytes array.
  78. */
  79. pb_bytes_array_t *_Nullable FIRSESEncodeData(NSData *_Nullable data) {
  80. pb_bytes_array_t *pbBytes = malloc(PB_BYTES_ARRAY_T_ALLOCSIZE(data.length));
  81. if (pbBytes == NULL) {
  82. return NULL;
  83. }
  84. [data getBytes:pbBytes->bytes length:data.length];
  85. pbBytes->size = (pb_size_t)data.length;
  86. return pbBytes;
  87. }
  88. /** Mallocs a pb_bytes_array and copies the given NSString's bytes into the bytes array.
  89. * @note Memory needs to be freed manually, through pb_free or pb_release.
  90. * @param string The string to encode as pb_bytes.
  91. */
  92. pb_bytes_array_t *_Nullable FIRSESEncodeString(NSString *_Nullable string) {
  93. if ([string isMemberOfClass:[NSNull class]]) {
  94. string = nil;
  95. }
  96. NSString *stringToEncode = string ? string : @"";
  97. NSData *stringBytes = [stringToEncode dataUsingEncoding:NSUTF8StringEncoding];
  98. return FIRSESEncodeData(stringBytes);
  99. }
  100. NSData *FIRSESDecodeData(pb_bytes_array_t *pbData) {
  101. NSData *data = [NSData dataWithBytes:&(pbData->bytes) length:pbData->size];
  102. return data;
  103. }
  104. NSString *FIRSESDecodeString(pb_bytes_array_t *pbData) {
  105. if (pbData->size == 0) {
  106. return @"";
  107. }
  108. NSData *data = FIRSESDecodeData(pbData);
  109. // There was a bug where length 32 strings were sometimes null after encoding
  110. // and decoding. We found that this was due to the null terminator sometimes not
  111. // being included in the decoded code. Using stringWithCString assumes the string
  112. // is null terminated, so we switched to initWithBytes because it takes a length.
  113. return [[NSString alloc] initWithBytes:data.bytes
  114. length:data.length
  115. encoding:NSUTF8StringEncoding];
  116. }
  117. BOOL FIRSESIsPBArrayEqual(pb_bytes_array_t *_Nullable array, pb_bytes_array_t *_Nullable expected) {
  118. // Treat the empty string as the same as a missing field
  119. if (array == nil) {
  120. return expected->size == 0;
  121. }
  122. if (array->size != expected->size) {
  123. return false;
  124. }
  125. for (int i = 0; i < array->size; i++) {
  126. if (expected->bytes[i] != array->bytes[i]) {
  127. return false;
  128. }
  129. }
  130. return true;
  131. }
  132. BOOL FIRSESIsPBStringEqual(pb_bytes_array_t *_Nullable pbString, NSString *_Nullable str) {
  133. pb_bytes_array_t *expected = FIRSESEncodeString(str);
  134. return FIRSESIsPBArrayEqual(pbString, expected);
  135. }
  136. BOOL FIRSESIsPBDataEqual(pb_bytes_array_t *_Nullable pbArray, NSData *_Nullable data) {
  137. pb_bytes_array_t *expected = FIRSESEncodeData(data);
  138. BOOL equal = FIRSESIsPBArrayEqual(pbArray, expected);
  139. free(expected);
  140. return equal;
  141. }
  142. pb_size_t FIRSESGetAppleApplicationInfoTag(void) {
  143. return firebase_appquality_sessions_ApplicationInfo_apple_app_info_tag;
  144. }
  145. /// Copied from a private method in GULAppEnvironmentUtil.
  146. NSString *_Nullable FIRSESGetSysctlEntry(const char *sysctlKey) {
  147. static NSString *entryValue;
  148. size_t size;
  149. sysctlbyname(sysctlKey, NULL, &size, NULL, 0);
  150. if (size > 0) {
  151. char *entryValueCStr = malloc(size);
  152. sysctlbyname(sysctlKey, entryValueCStr, &size, NULL, 0);
  153. entryValue = [NSString stringWithCString:entryValueCStr encoding:NSUTF8StringEncoding];
  154. free(entryValueCStr);
  155. return entryValue;
  156. } else {
  157. return nil;
  158. }
  159. }
  160. NSData *FIRSESTransportBytes(const void *_Nonnull proto) {
  161. const pb_field_t *fields = firebase_appquality_sessions_SessionEvent_fields;
  162. NSError *error;
  163. NSData *data = FIRSESEncodeProto(fields, proto, &error);
  164. if (error != nil) {
  165. FIRLogError(
  166. @"FirebaseSessions", @"I-SES000001", @"%@",
  167. [NSString stringWithFormat:@"Session Event failed to encode as proto with error: %@",
  168. error.debugDescription]);
  169. }
  170. if (data == nil) {
  171. data = [NSData data];
  172. FIRLogError(@"FirebaseSessions", @"I-SES000002",
  173. @"Session Event generated nil transportBytes. Returning empty data.");
  174. }
  175. return data;
  176. }
  177. NS_ASSUME_NONNULL_END