FPRNetworkTrace.m 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. // Copyright 2020 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #import "FirebasePerformance/Sources/Instrumentation/FPRNetworkTrace.h"
  15. #import "FirebasePerformance/Sources/Instrumentation/FPRNetworkTrace+Private.h"
  16. #import "FirebasePerformance/Sources/AppActivity/FPRSessionManager.h"
  17. #import "FirebasePerformance/Sources/Common/FPRConstants.h"
  18. #import "FirebasePerformance/Sources/Common/FPRDiagnostics.h"
  19. #import "FirebasePerformance/Sources/Configurations/FPRConfigurations.h"
  20. #import "FirebasePerformance/Sources/FPRClient.h"
  21. #import "FirebasePerformance/Sources/FPRConsoleLogger.h"
  22. #import "FirebasePerformance/Sources/FPRDataUtils.h"
  23. #import "FirebasePerformance/Sources/FPRURLFilter.h"
  24. #import "FirebasePerformance/Sources/Gauges/FPRGaugeManager.h"
  25. #import "FirebasePerformance/Sources/ISASwizzler/FPRObjectSwizzler.h"
  26. NSString *const kFPRNetworkTracePropertyName = @"fpr_networkTrace";
  27. @interface FPRNetworkTrace ()
  28. @property(nonatomic, readwrite) NSURLRequest *URLRequest;
  29. @property(nonatomic, readwrite, nullable) NSError *responseError;
  30. /** State to know if the trace has started. */
  31. @property(nonatomic) BOOL traceStarted;
  32. /** State to know if the trace has completed. */
  33. @property(nonatomic) BOOL traceCompleted;
  34. /** Background activity tracker to know the background state of the trace. */
  35. @property(nonatomic) FPRTraceBackgroundActivityTracker *backgroundActivityTracker;
  36. /** Custom attribute managed internally. */
  37. @property(nonatomic) NSMutableDictionary<NSString *, NSString *> *customAttributes;
  38. /** @brief Serial queue to manage the updation of session Ids. */
  39. @property(nonatomic, readwrite) dispatch_queue_t sessionIdSerialQueue;
  40. /**
  41. * Updates the current trace with the current session details.
  42. * @param sessionDetails Updated session details of the currently active session.
  43. */
  44. - (void)updateTraceWithCurrentSession:(FPRSessionDetails *)sessionDetails;
  45. @end
  46. @implementation FPRNetworkTrace {
  47. /**
  48. * @brief Object containing different states of the network request. Stores the information about
  49. * the state of a network request (defined in FPRNetworkTraceCheckpointState) and the time at
  50. * which the event happened.
  51. */
  52. NSMutableDictionary<NSString *, NSNumber *> *_states;
  53. }
  54. - (nullable instancetype)initWithURLRequest:(NSURLRequest *)URLRequest {
  55. if (URLRequest.URL == nil) {
  56. FPRLogError(kFPRNetworkTraceInvalidInputs, @"Invalid URL. URL is nil.");
  57. return nil;
  58. }
  59. // Fail early instead of creating a trace here.
  60. // IMPORTANT: Order is important here. This check needs to be done before looking up on remote
  61. // config. Reference bug: b/141861005.
  62. if (![[FPRURLFilter sharedInstance] shouldInstrumentURL:URLRequest.URL.absoluteString]) {
  63. return nil;
  64. }
  65. BOOL tracingEnabled = [FPRConfigurations sharedInstance].isDataCollectionEnabled;
  66. if (!tracingEnabled) {
  67. FPRLogInfo(kFPRTraceDisabled, @"Trace feature is disabled.");
  68. return nil;
  69. }
  70. BOOL sdkEnabled = [[FPRConfigurations sharedInstance] sdkEnabled];
  71. if (!sdkEnabled) {
  72. FPRLogInfo(kFPRTraceDisabled, @"Dropping event since Performance SDK is disabled.");
  73. return nil;
  74. }
  75. NSString *trimmedURLString = [FPRNetworkTrace stringByTrimmingURLString:URLRequest];
  76. if (!trimmedURLString || trimmedURLString.length <= 0) {
  77. FPRLogWarning(kFPRNetworkTraceURLLengthExceeds, @"URL length outside limits, returning nil.");
  78. return nil;
  79. }
  80. if (![URLRequest.URL.absoluteString isEqualToString:trimmedURLString]) {
  81. FPRLogInfo(kFPRNetworkTraceURLLengthTruncation,
  82. @"URL length exceeds limits, truncating recorded URL - %@.", trimmedURLString);
  83. }
  84. self = [super init];
  85. if (self) {
  86. _URLRequest = URLRequest;
  87. _trimmedURLString = trimmedURLString;
  88. _states = [[NSMutableDictionary<NSString *, NSNumber *> alloc] init];
  89. _hasValidResponseCode = NO;
  90. _customAttributes = [[NSMutableDictionary<NSString *, NSString *> alloc] init];
  91. _syncQueue =
  92. dispatch_queue_create("com.google.perf.networkTrace.metric", DISPATCH_QUEUE_SERIAL);
  93. _sessionIdSerialQueue =
  94. dispatch_queue_create("com.google.perf.sessionIds.networkTrace", DISPATCH_QUEUE_SERIAL);
  95. _activeSessions = [[NSMutableArray<FPRSessionDetails *> alloc] init];
  96. if (![FPRNetworkTrace isCompleteAndValidTrimmedURLString:_trimmedURLString
  97. URLRequest:_URLRequest]) {
  98. return nil;
  99. };
  100. }
  101. return self;
  102. }
  103. - (instancetype)init {
  104. FPRAssert(NO, @"Not a designated initializer.");
  105. return nil;
  106. }
  107. - (void)dealloc {
  108. // Safety net to ensure the notifications are not received anymore.
  109. FPRSessionManager *sessionManager = [FPRSessionManager sharedInstance];
  110. [sessionManager.sessionNotificationCenter removeObserver:self
  111. name:kFPRSessionIdUpdatedNotification
  112. object:sessionManager];
  113. }
  114. - (NSString *)description {
  115. return [NSString stringWithFormat:@"Request: %@", _URLRequest];
  116. }
  117. - (void)sessionChanged:(NSNotification *)notification {
  118. if (self.traceStarted && !self.traceCompleted) {
  119. NSDictionary<NSString *, FPRSessionDetails *> *userInfo = notification.userInfo;
  120. FPRSessionDetails *sessionDetails = [userInfo valueForKey:kFPRSessionIdNotificationKey];
  121. if (sessionDetails) {
  122. [self updateTraceWithCurrentSession:sessionDetails];
  123. }
  124. }
  125. }
  126. - (void)updateTraceWithCurrentSession:(FPRSessionDetails *)sessionDetails {
  127. if (sessionDetails != nil) {
  128. dispatch_sync(self.sessionIdSerialQueue, ^{
  129. [self.activeSessions addObject:sessionDetails];
  130. });
  131. }
  132. }
  133. - (NSArray<FPRSessionDetails *> *)sessions {
  134. __block NSArray<FPRSessionDetails *> *sessionInfos = nil;
  135. dispatch_sync(self.sessionIdSerialQueue, ^{
  136. sessionInfos = [self.activeSessions copy];
  137. });
  138. return sessionInfos;
  139. }
  140. - (NSDictionary<NSString *, NSNumber *> *)checkpointStates {
  141. __block NSDictionary<NSString *, NSNumber *> *copiedStates;
  142. dispatch_sync(self.syncQueue, ^{
  143. copiedStates = [_states copy];
  144. });
  145. return copiedStates;
  146. }
  147. - (void)checkpointState:(FPRNetworkTraceCheckpointState)state {
  148. if (!self.traceCompleted && self.traceStarted) {
  149. NSString *stateKey = @(state).stringValue;
  150. if (stateKey) {
  151. dispatch_sync(self.syncQueue, ^{
  152. NSNumber *existingState = _states[stateKey];
  153. if (existingState == nil) {
  154. double intervalSinceEpoch = [[NSDate date] timeIntervalSince1970];
  155. [_states setObject:@(intervalSinceEpoch) forKey:stateKey];
  156. }
  157. });
  158. } else {
  159. FPRAssert(NO, @"stateKey wasn't created for checkpoint state %ld", (long)state);
  160. }
  161. }
  162. }
  163. - (void)start {
  164. if (!self.traceCompleted) {
  165. [[FPRSessionManager sharedInstance] collectAllGaugesOnce];
  166. self.traceStarted = YES;
  167. self.backgroundActivityTracker = [[FPRTraceBackgroundActivityTracker alloc] init];
  168. [self checkpointState:FPRNetworkTraceCheckpointStateInitiated];
  169. if ([self.URLRequest.HTTPMethod isEqualToString:@"POST"] ||
  170. [self.URLRequest.HTTPMethod isEqualToString:@"PUT"]) {
  171. self.requestSize = self.URLRequest.HTTPBody.length;
  172. }
  173. FPRSessionManager *sessionManager = [FPRSessionManager sharedInstance];
  174. [self updateTraceWithCurrentSession:[sessionManager.sessionDetails copy]];
  175. [sessionManager.sessionNotificationCenter addObserver:self
  176. selector:@selector(sessionChanged:)
  177. name:kFPRSessionIdUpdatedNotification
  178. object:sessionManager];
  179. }
  180. }
  181. - (FPRTraceState)backgroundTraceState {
  182. FPRTraceBackgroundActivityTracker *backgroundActivityTracker = self.backgroundActivityTracker;
  183. if (backgroundActivityTracker) {
  184. return backgroundActivityTracker.traceBackgroundState;
  185. }
  186. return FPRTraceStateUnknown;
  187. }
  188. - (NSTimeInterval)startTimeSinceEpoch {
  189. NSString *stateKey =
  190. [NSString stringWithFormat:@"%lu", (unsigned long)FPRNetworkTraceCheckpointStateInitiated];
  191. __block NSTimeInterval timeSinceEpoch;
  192. dispatch_sync(self.syncQueue, ^{
  193. timeSinceEpoch = [[_states objectForKey:stateKey] doubleValue];
  194. });
  195. return timeSinceEpoch;
  196. }
  197. #pragma mark - Overrides
  198. - (void)setResponseCode:(int32_t)responseCode {
  199. dispatch_sync(self.syncQueue, ^{
  200. _responseCode = responseCode;
  201. });
  202. if (responseCode != 0) {
  203. _hasValidResponseCode = YES;
  204. }
  205. }
  206. #pragma mark - FPRNetworkResponseHandler methods
  207. - (void)didCompleteRequestWithResponse:(NSURLResponse *)response error:(NSError *)error {
  208. if (!self.traceCompleted && self.traceStarted) {
  209. // Extract needed fields for the trace object.
  210. if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
  211. NSHTTPURLResponse *HTTPResponse = (NSHTTPURLResponse *)response;
  212. self.responseCode = (int32_t)HTTPResponse.statusCode;
  213. }
  214. self.responseError = error;
  215. // Safely copy MIMEType to prevent use after free
  216. NSString *mime = [response.MIMEType copy];
  217. self.responseContentType = (mime.length ? mime : nil);
  218. [self checkpointState:FPRNetworkTraceCheckpointStateResponseCompleted];
  219. // Send the network trace for logging.
  220. [[FPRSessionManager sharedInstance] collectAllGaugesOnce];
  221. [[FPRClient sharedInstance] logNetworkTrace:self];
  222. self.traceCompleted = YES;
  223. }
  224. FPRSessionManager *sessionManager = [FPRSessionManager sharedInstance];
  225. [sessionManager.sessionNotificationCenter removeObserver:self
  226. name:kFPRSessionIdUpdatedNotification
  227. object:sessionManager];
  228. }
  229. - (void)didUploadFileWithURL:(NSURL *)URL {
  230. NSNumber *value = nil;
  231. NSError *error = nil;
  232. if ([URL getResourceValue:&value forKey:NSURLFileSizeKey error:&error]) {
  233. if (error) {
  234. FPRLogNotice(kFPRNetworkTraceFileError, @"Unable to determine the size of file.");
  235. } else {
  236. self.requestSize = value.unsignedIntegerValue;
  237. }
  238. }
  239. }
  240. - (void)didReceiveData:(NSData *)data {
  241. dispatch_sync(self.syncQueue, ^{
  242. self.responseSize = data.length;
  243. });
  244. }
  245. - (void)didReceiveFileURL:(NSURL *)URL {
  246. NSNumber *value = nil;
  247. NSError *error = nil;
  248. if ([URL getResourceValue:&value forKey:NSURLFileSizeKey error:&error]) {
  249. if (error) {
  250. FPRLogNotice(kFPRNetworkTraceFileError, @"Unable to determine the size of file.");
  251. } else {
  252. dispatch_sync(self.syncQueue, ^{
  253. self.responseSize = value.unsignedIntegerValue;
  254. });
  255. }
  256. }
  257. }
  258. - (NSTimeInterval)timeIntervalBetweenCheckpointState:(FPRNetworkTraceCheckpointState)startState
  259. andState:(FPRNetworkTraceCheckpointState)endState {
  260. __block NSNumber *startStateTime;
  261. __block NSNumber *endStateTime;
  262. dispatch_sync(self.syncQueue, ^{
  263. startStateTime = [_states objectForKey:[@(startState) stringValue]];
  264. endStateTime = [_states objectForKey:[@(endState) stringValue]];
  265. });
  266. // Fail fast. If any of the times do not exist, return 0.
  267. if (startStateTime == nil || endStateTime == nil) {
  268. return 0;
  269. }
  270. NSTimeInterval timeDiff = (endStateTime.doubleValue - startStateTime.doubleValue);
  271. return timeDiff;
  272. }
  273. /** Trims and validates the URL string of a given NSURLRequest.
  274. *
  275. * @param URLRequest The NSURLRequest containing the URL string to trim.
  276. * @return The trimmed string.
  277. */
  278. + (NSString *)stringByTrimmingURLString:(NSURLRequest *)URLRequest {
  279. NSURLComponents *components = [NSURLComponents componentsWithURL:URLRequest.URL
  280. resolvingAgainstBaseURL:NO];
  281. components.query = nil;
  282. components.fragment = nil;
  283. components.user = nil;
  284. components.password = nil;
  285. NSURL *trimmedURL = [components URL];
  286. NSString *truncatedURLString = FPRTruncatedURLString(trimmedURL.absoluteString);
  287. NSURL *truncatedURL = [NSURL URLWithString:truncatedURLString];
  288. if (!truncatedURL || truncatedURL.host == nil) {
  289. return nil;
  290. }
  291. return truncatedURLString;
  292. }
  293. /** Validates the trace object by checking that it's http or https, and not a denied URL.
  294. *
  295. * @param trimmedURLString A trimmed URL string from the URLRequest.
  296. * @param URLRequest The NSURLRequest that this trace will operate on.
  297. * @return YES if the trace object is valid, NO otherwise.
  298. */
  299. + (BOOL)isCompleteAndValidTrimmedURLString:(NSString *)trimmedURLString
  300. URLRequest:(NSURLRequest *)URLRequest {
  301. if (![[FPRURLFilter sharedInstance] shouldInstrumentURL:trimmedURLString]) {
  302. return NO;
  303. }
  304. // Check the URL begins with http or https.
  305. NSURLComponents *components = [NSURLComponents componentsWithURL:URLRequest.URL
  306. resolvingAgainstBaseURL:NO];
  307. NSString *scheme = components.scheme;
  308. if (!scheme || !([scheme caseInsensitiveCompare:@"HTTP"] == NSOrderedSame ||
  309. [scheme caseInsensitiveCompare:@"HTTPS"] == NSOrderedSame)) {
  310. FPRLogError(kFPRNetworkTraceInvalidInputs, @"Invalid URL - %@, returning nil.", URLRequest.URL);
  311. return NO;
  312. }
  313. return YES;
  314. }
  315. #pragma mark - Custom attributes related methods
  316. - (NSDictionary<NSString *, NSString *> *)attributes {
  317. return [self.customAttributes copy];
  318. }
  319. - (void)setValue:(NSString *)value forAttribute:(nonnull NSString *)attribute {
  320. BOOL canAddAttribute = YES;
  321. if (self.traceCompleted) {
  322. FPRLogError(kFPRTraceAlreadyStopped,
  323. @"Failed to set attribute %@ because network request %@ has already stopped.",
  324. attribute, self.URLRequest.URL);
  325. canAddAttribute = NO;
  326. }
  327. NSString *validatedName = FPRReservableAttributeName(attribute);
  328. NSString *validatedValue = FPRValidatedAttributeValue(value);
  329. if (validatedName == nil) {
  330. FPRLogError(kFPRAttributeNoName,
  331. @"Failed to initialize because of a nil or zero length attribute name.");
  332. canAddAttribute = NO;
  333. }
  334. if (validatedValue == nil) {
  335. FPRLogError(kFPRAttributeNoValue,
  336. @"Failed to initialize because of a nil or zero length attribute value.");
  337. canAddAttribute = NO;
  338. }
  339. if (self.customAttributes.allKeys.count >= kFPRMaxGlobalCustomAttributesCount) {
  340. FPRLogError(kFPRMaxAttributesReached,
  341. @"Only %d attributes allowed. Already reached maximum attribute count.",
  342. kFPRMaxGlobalCustomAttributesCount);
  343. canAddAttribute = NO;
  344. }
  345. if (canAddAttribute) {
  346. // Ensure concurrency during update of attributes.
  347. dispatch_sync(self.syncQueue, ^{
  348. self.customAttributes[validatedName] = validatedValue;
  349. FPRLogDebug(kFPRClientMetricLogged, @"Setting attribute %@ to %@ on network request %@",
  350. validatedName, validatedValue, self.URLRequest.URL);
  351. });
  352. }
  353. }
  354. - (NSString *)valueForAttribute:(NSString *)attribute {
  355. // TODO(b/175053654): Should this be happening on the serial queue for thread safety?
  356. return self.customAttributes[attribute];
  357. }
  358. - (void)removeAttribute:(NSString *)attribute {
  359. if (self.traceCompleted) {
  360. FPRLogError(kFPRTraceAlreadyStopped,
  361. @"Failed to remove attribute %@ because network request %@ has already stopped.",
  362. attribute, self.URLRequest.URL);
  363. return;
  364. }
  365. [self.customAttributes removeObjectForKey:attribute];
  366. }
  367. #pragma mark - Class methods related to object association.
  368. + (void)addNetworkTrace:(FPRNetworkTrace *)networkTrace toObject:(id)object {
  369. if (object != nil && networkTrace != nil) {
  370. [FPRObjectSwizzler
  371. setAssociatedObject:object
  372. key:(__bridge const void *_Nonnull)kFPRNetworkTracePropertyName
  373. value:networkTrace
  374. association:GUL_ASSOCIATION_RETAIN_NONATOMIC];
  375. }
  376. }
  377. + (FPRNetworkTrace *)networkTraceFromObject:(id)object {
  378. FPRNetworkTrace *networkTrace = nil;
  379. if (object != nil) {
  380. id traceObject = [FPRObjectSwizzler
  381. getAssociatedObject:object
  382. key:(__bridge const void *_Nonnull)kFPRNetworkTracePropertyName];
  383. if ([traceObject isKindOfClass:[FPRNetworkTrace class]]) {
  384. networkTrace = (FPRNetworkTrace *)traceObject;
  385. }
  386. }
  387. return networkTrace;
  388. }
  389. + (void)removeNetworkTraceFromObject:(id)object {
  390. if (object != nil) {
  391. [FPRObjectSwizzler
  392. setAssociatedObject:object
  393. key:(__bridge const void *_Nonnull)kFPRNetworkTracePropertyName
  394. value:nil
  395. association:GUL_ASSOCIATION_RETAIN_NONATOMIC];
  396. }
  397. }
  398. - (BOOL)isValid {
  399. return _hasValidResponseCode;
  400. }
  401. @end