GDTCORClock.m 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. /*
  2. * Copyright 2018 Google
  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. */
  16. #import "GoogleDataTransport/GDTCORLibrary/Public/GoogleDataTransport/GDTCORClock.h"
  17. #import <sys/sysctl.h>
  18. // Using a monotonic clock is necessary because CFAbsoluteTimeGetCurrent(), NSDate, and related all
  19. // are subject to drift. That it to say, multiple consecutive calls do not always result in a
  20. // time that is in the future. Clocks may be adjusted by the user, NTP, or any number of external
  21. // factors. This class attempts to determine the wall-clock time at the time of the event by
  22. // capturing the kernel start and time since boot to determine a wallclock time in UTC.
  23. //
  24. // Timezone offsets at the time of a snapshot are also captured in order to provide local-time
  25. // details. Other classes in this library depend on comparing times at some time in the future to
  26. // a time captured in the past, and this class needs to provide a mechanism to do that.
  27. //
  28. // TL;DR: This class attempts to accomplish two things: 1. Provide accurate event times. 2. Provide
  29. // a monotonic clock mechanism to accurately check if some clock snapshot was before or after
  30. // by using a shared reference point (kernel boot time).
  31. //
  32. // Note: Much of the mach time stuff doesn't work properly in the simulator. So this class can be
  33. // difficult to unit test.
  34. /** Returns the kernel boottime property from sysctl.
  35. *
  36. * Inspired by https://stackoverflow.com/a/40497811
  37. *
  38. * @return The KERN_BOOTTIME property from sysctl, in nanoseconds.
  39. */
  40. static int64_t KernelBootTimeInNanoseconds() {
  41. // Caching the result is not possible because clock drift would not be accounted for.
  42. struct timeval boottime;
  43. int mib[2] = {CTL_KERN, KERN_BOOTTIME};
  44. size_t size = sizeof(boottime);
  45. int rc = sysctl(mib, 2, &boottime, &size, NULL, 0);
  46. if (rc != 0) {
  47. return 0;
  48. }
  49. return (int64_t)boottime.tv_sec * NSEC_PER_SEC + (int64_t)boottime.tv_usec * NSEC_PER_USEC;
  50. }
  51. /** Returns value of gettimeofday, in nanoseconds.
  52. *
  53. * Inspired by https://stackoverflow.com/a/40497811
  54. *
  55. * @return The value of gettimeofday, in nanoseconds.
  56. */
  57. static int64_t UptimeInNanoseconds() {
  58. int64_t before_now_nsec;
  59. int64_t after_now_nsec;
  60. struct timeval now;
  61. before_now_nsec = KernelBootTimeInNanoseconds();
  62. // Addresses a race condition in which the system time has updated, but the boottime has not.
  63. do {
  64. gettimeofday(&now, NULL);
  65. after_now_nsec = KernelBootTimeInNanoseconds();
  66. } while (after_now_nsec != before_now_nsec);
  67. return (int64_t)now.tv_sec * NSEC_PER_SEC + (int64_t)now.tv_usec * NSEC_PER_USEC -
  68. before_now_nsec;
  69. }
  70. // TODO: Consider adding a 'trustedTime' property that can be populated by the response from a BE.
  71. @implementation GDTCORClock
  72. - (instancetype)init {
  73. self = [super init];
  74. if (self) {
  75. _kernelBootTimeNanoseconds = KernelBootTimeInNanoseconds();
  76. _uptimeNanoseconds = UptimeInNanoseconds();
  77. _timeMillis =
  78. (int64_t)((CFAbsoluteTimeGetCurrent() + kCFAbsoluteTimeIntervalSince1970) * NSEC_PER_USEC);
  79. _timezoneOffsetSeconds = [[NSTimeZone systemTimeZone] secondsFromGMT];
  80. }
  81. return self;
  82. }
  83. + (GDTCORClock *)snapshot {
  84. return [[GDTCORClock alloc] init];
  85. }
  86. + (instancetype)clockSnapshotInTheFuture:(uint64_t)millisInTheFuture {
  87. GDTCORClock *snapshot = [self snapshot];
  88. snapshot->_timeMillis += millisInTheFuture;
  89. return snapshot;
  90. }
  91. - (BOOL)isAfter:(GDTCORClock *)otherClock {
  92. // These clocks are trivially comparable when they share a kernel boot time.
  93. if (_kernelBootTimeNanoseconds == otherClock->_kernelBootTimeNanoseconds) {
  94. int64_t timeDiff = (_timeMillis + _timezoneOffsetSeconds) -
  95. (otherClock->_timeMillis + otherClock->_timezoneOffsetSeconds);
  96. return timeDiff > 0;
  97. } else {
  98. int64_t kernelBootTimeDiff =
  99. otherClock->_kernelBootTimeNanoseconds - _kernelBootTimeNanoseconds;
  100. // This isn't a great solution, but essentially, if the other clock's boot time is 'later', NO
  101. // is returned. This can be altered by changing the system time and rebooting.
  102. return kernelBootTimeDiff < 0 ? YES : NO;
  103. }
  104. }
  105. - (int64_t)uptimeMilliseconds {
  106. return self.uptimeNanoseconds / NSEC_PER_MSEC;
  107. }
  108. - (NSUInteger)hash {
  109. return [@(_kernelBootTimeNanoseconds) hash] ^ [@(_uptimeNanoseconds) hash] ^
  110. [@(_timeMillis) hash] ^ [@(_timezoneOffsetSeconds) hash];
  111. }
  112. - (BOOL)isEqual:(id)object {
  113. return [self hash] == [object hash];
  114. }
  115. #pragma mark - NSSecureCoding
  116. /** NSKeyedCoder key for timeMillis property. */
  117. static NSString *const kGDTCORClockTimeMillisKey = @"GDTCORClockTimeMillis";
  118. /** NSKeyedCoder key for timezoneOffsetMillis property. */
  119. static NSString *const kGDTCORClockTimezoneOffsetSeconds = @"GDTCORClockTimezoneOffsetSeconds";
  120. /** NSKeyedCoder key for _kernelBootTime ivar. */
  121. static NSString *const kGDTCORClockKernelBootTime = @"GDTCORClockKernelBootTime";
  122. /** NSKeyedCoder key for _uptimeNanoseconds ivar. */
  123. static NSString *const kGDTCORClockUptime = @"GDTCORClockUptime";
  124. + (BOOL)supportsSecureCoding {
  125. return YES;
  126. }
  127. - (instancetype)initWithCoder:(NSCoder *)aDecoder {
  128. self = [super init];
  129. if (self) {
  130. // TODO: If the kernelBootTimeNanoseconds is more recent, we need to change the kernel boot time
  131. // and uptimeMillis ivars
  132. _timeMillis = [aDecoder decodeInt64ForKey:kGDTCORClockTimeMillisKey];
  133. _timezoneOffsetSeconds = [aDecoder decodeInt64ForKey:kGDTCORClockTimezoneOffsetSeconds];
  134. _kernelBootTimeNanoseconds = [aDecoder decodeInt64ForKey:kGDTCORClockKernelBootTime];
  135. _uptimeNanoseconds = [aDecoder decodeInt64ForKey:kGDTCORClockUptime];
  136. }
  137. return self;
  138. }
  139. - (void)encodeWithCoder:(NSCoder *)aCoder {
  140. [aCoder encodeInt64:_timeMillis forKey:kGDTCORClockTimeMillisKey];
  141. [aCoder encodeInt64:_timezoneOffsetSeconds forKey:kGDTCORClockTimezoneOffsetSeconds];
  142. [aCoder encodeInt64:_kernelBootTimeNanoseconds forKey:kGDTCORClockKernelBootTime];
  143. [aCoder encodeInt64:_uptimeNanoseconds forKey:kGDTCORClockUptime];
  144. }
  145. #pragma mark - Deprecated properties
  146. - (int64_t)kernelBootTime {
  147. return self.kernelBootTimeNanoseconds;
  148. }
  149. - (int64_t)uptime {
  150. return self.uptimeNanoseconds;
  151. }
  152. @end