Files
firebase-ios-sdk/FirebaseDatabase/Sources/Realtime/FWebSocketConnection.m
T

456 lines
16 KiB
Objective-C
Raw Normal View History

2017-05-15 12:27:07 -07:00
/*
* Copyright 2017 Google
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Targeted compilation is ONLY for testing. UIKit is weak-linked in actual
2019-08-05 13:27:47 -07:00
// release build.
2017-05-15 12:27:07 -07:00
#import <Foundation/Foundation.h>
#import "FirebaseCore/Extension/FirebaseCoreInternal.h"
2020-06-22 07:58:52 -07:00
#import "FirebaseDatabase/Sources/Api/Private/FIRDatabase_Private.h"
#import "FirebaseDatabase/Sources/Constants/FConstants.h"
2020-07-31 07:22:02 -07:00
#import "FirebaseDatabase/Sources/Public/FirebaseDatabase/FIRDatabaseReference.h"
2020-06-22 07:58:52 -07:00
#import "FirebaseDatabase/Sources/Realtime/FWebSocketConnection.h"
#import "FirebaseDatabase/Sources/Utilities/FStringUtilities.h"
2017-05-15 12:27:07 -07:00
#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_VISION
2017-05-15 12:27:07 -07:00
#import <UIKit/UIKit.h>
2021-03-12 14:19:16 -05:00
#elif TARGET_OS_WATCH
2021-03-12 14:19:16 -05:00
#import <WatchKit/WatchKit.h>
#elif TARGET_OS_OSX
#import <AppKit/NSApplication.h>
#endif
#import <Network/Network.h>
2017-05-15 12:27:07 -07:00
static NSString *const kAppCheckTokenHeader = @"X-Firebase-AppCheck";
static NSString *const kUserAgentHeader = @"User-Agent";
static NSString *const kGoogleAppIDHeader = @"X-Firebase-GMPID";
2017-05-15 12:27:07 -07:00
@interface FWebSocketConnection () {
2019-08-05 13:27:47 -07:00
NSMutableString *frame;
2017-05-15 12:27:07 -07:00
BOOL everConnected;
BOOL isClosed;
2019-08-05 13:27:47 -07:00
NSTimer *keepAlive;
2017-05-15 12:27:07 -07:00
}
2019-08-05 13:27:47 -07:00
- (void)shutdown;
- (void)onClosed;
- (void)closeIfNeverConnected;
2017-05-15 12:27:07 -07:00
@property(nonatomic, strong)
NSURLSessionWebSocketTask *webSocketTask API_AVAILABLE(
macos(10.15), ios(13.0), watchos(6.0), tvos(13.0));
2019-08-05 13:27:47 -07:00
@property(nonatomic, strong) NSNumber *connectionId;
@property(nonatomic, readwrite) int totalFrames;
@property(nonatomic, readonly) BOOL buffering;
@property(nonatomic, readonly) NSString *userAgent;
@property(nonatomic) dispatch_queue_t dispatchQueue;
2017-05-15 12:27:07 -07:00
- (void)nop:(NSTimer *)timer;
@end
@implementation FWebSocketConnection
@synthesize delegate;
@synthesize connectionId;
- (instancetype)initWith:(FRepoInfo *)repoInfo
andQueue:(dispatch_queue_t)queue
googleAppID:(NSString *)googleAppID
lastSessionID:(NSString *)lastSessionID
appCheckToken:(nullable NSString *)appCheckToken {
2017-05-15 12:27:07 -07:00
self = [super init];
if (self) {
everConnected = NO;
isClosed = NO;
self.connectionId = [FUtilities LUIDGenerator];
self.totalFrames = 0;
self.dispatchQueue = queue;
frame = nil;
2017-06-30 10:47:37 -07:00
NSString *userAgent = [self userAgent];
NSString *connectionURL =
2019-08-05 13:27:47 -07:00
[repoInfo connectionURLWithLastSessionID:lastSessionID];
2017-06-30 10:47:37 -07:00
FFLog(@"I-RDB083001", @"(wsc:%@) Connecting to: %@ as %@",
self.connectionId, connectionURL, userAgent);
NSURLRequest *req = [[self class] createRequestWithURL:connectionURL
userAgent:userAgent
googleAppID:googleAppID
appCheckToken:appCheckToken];
2021-03-12 14:19:16 -05:00
if (@available(iOS 13.0, macOS 10.15, macCatalyst 13.1, tvOS 13.0,
watchOS 6.0, *)) {
// Regular NSURLSession websocket.
NSOperationQueue *opQueue = [[NSOperationQueue alloc] init];
opQueue.underlyingQueue = queue;
NSURLSession *session = [NSURLSession
sessionWithConfiguration:[NSURLSessionConfiguration
defaultSessionConfiguration]
delegate:self
delegateQueue:opQueue];
NSURLSessionWebSocketTask *task =
[session webSocketTaskWithRequest:req];
self.webSocketTask = task;
}
2017-05-15 12:27:07 -07:00
}
return self;
}
2019-08-05 13:27:47 -07:00
- (NSString *)userAgent {
NSString *systemVersion;
NSString *deviceName;
2017-05-15 12:27:07 -07:00
BOOL hasUiDeviceClass = NO;
2017-06-30 10:47:37 -07:00
// Targeted compilation is ONLY for testing. UIKit is weak-linked in actual
2019-08-05 13:27:47 -07:00
// release build.
#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_VISION
2017-05-15 12:27:07 -07:00
Class uiDeviceClass = NSClassFromString(@"UIDevice");
if (uiDeviceClass) {
systemVersion = [uiDeviceClass currentDevice].systemVersion;
deviceName = [uiDeviceClass currentDevice].model;
hasUiDeviceClass = YES;
}
#endif // TARGET_OS_IOS || TARGET_OS_TV || (defined(TARGET_OS_VISION) &&
// TARGET_OS_VISION)
2017-06-30 10:47:37 -07:00
2017-05-15 12:27:07 -07:00
if (!hasUiDeviceClass) {
2019-08-05 13:27:47 -07:00
NSDictionary *systemVersionDictionary = [NSDictionary
dictionaryWithContentsOfFile:
@"/System/Library/CoreServices/SystemVersion.plist"];
systemVersion =
[systemVersionDictionary objectForKey:@"ProductVersion"];
2017-05-15 12:27:07 -07:00
deviceName = [systemVersionDictionary objectForKey:@"ProductName"];
}
2019-08-05 13:27:47 -07:00
NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
2017-05-15 12:27:07 -07:00
// Sanitize '/'s in deviceName and bundleIdentifier for stats
deviceName = [FStringUtilities sanitizedForUserAgent:deviceName];
2019-08-05 13:27:47 -07:00
bundleIdentifier =
[FStringUtilities sanitizedForUserAgent:bundleIdentifier];
2017-05-15 12:27:07 -07:00
2019-08-05 13:27:47 -07:00
// Firebase/5/<semver>_<build date>_<git hash>/<os version>/{device model /
// os (Mac OS X, iPhone, etc.}_<bundle id>
NSString *ua = [NSString
stringWithFormat:@"Firebase/%@/%@/%@/%@_%@", kWebsocketProtocolVersion,
[FIRDatabase buildVersion], systemVersion, deviceName,
bundleIdentifier];
2017-05-15 12:27:07 -07:00
return ua;
}
2019-08-05 13:27:47 -07:00
- (BOOL)buffering {
2017-05-15 12:27:07 -07:00
return frame != nil;
}
#pragma mark -
#pragma mark Public FWebSocketConnection methods
2019-08-05 13:27:47 -07:00
- (void)open {
FFLog(@"I-RDB083002", @"(wsc:%@) FWebSocketConnection open.",
self.connectionId);
2017-05-15 12:27:07 -07:00
assert(delegate);
everConnected = NO;
// TODO Assert url
if (@available(iOS 13.0, macOS 10.15, macCatalyst 13.1, tvOS 13.0,
watchOS 6.0, *)) {
[self.webSocketTask resume];
// We need to request data from the web socket in order for it to start
// sending data.
[self receiveWebSocketData];
}
2019-08-05 13:27:47 -07:00
dispatch_time_t when = dispatch_time(
DISPATCH_TIME_NOW, kWebsocketConnectTimeout * NSEC_PER_SEC);
2017-05-15 12:27:07 -07:00
dispatch_after(when, self.dispatchQueue, ^{
2019-08-05 13:27:47 -07:00
[self closeIfNeverConnected];
2017-05-15 12:27:07 -07:00
});
}
2019-08-05 13:27:47 -07:00
- (void)close {
FFLog(@"I-RDB083003", @"(wsc:%@) FWebSocketConnection is being closed.",
self.connectionId);
2017-05-15 12:27:07 -07:00
isClosed = YES;
if (@available(iOS 13.0, macOS 10.15, macCatalyst 13.1, tvOS 13.0,
watchOS 6.0, *)) {
[self.webSocketTask
cancelWithCloseCode:NSURLSessionWebSocketCloseCodeNormalClosure
reason:nil];
}
2017-05-15 12:27:07 -07:00
}
2019-08-05 13:27:47 -07:00
- (void)start {
2017-05-15 12:27:07 -07:00
// Start is a no-op for websockets.
}
2019-08-05 13:27:47 -07:00
- (void)send:(NSDictionary *)dictionary {
2017-05-15 12:27:07 -07:00
[self resetKeepAlive];
2019-08-05 13:27:47 -07:00
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary
options:kNilOptions
error:nil];
2017-06-30 10:47:37 -07:00
2019-08-05 13:27:47 -07:00
NSString *data = [[NSString alloc] initWithData:jsonData
2017-05-15 12:27:07 -07:00
encoding:NSUTF8StringEncoding];
2017-06-30 10:47:37 -07:00
2019-08-05 13:27:47 -07:00
NSArray *dataSegs = [FUtilities splitString:data
intoMaxSize:kWebsocketMaxFrameSize];
2017-05-15 12:27:07 -07:00
2019-08-05 13:27:47 -07:00
// First send the header so the server knows how many segments are
// forthcoming
2017-05-15 12:27:07 -07:00
if (dataSegs.count > 1) {
2021-03-12 14:19:16 -05:00
NSString *formattedData =
[NSString stringWithFormat:@"%u", (unsigned int)dataSegs.count];
[self sendStringToWebSocket:formattedData];
2017-05-15 12:27:07 -07:00
}
2017-06-30 10:47:37 -07:00
2017-05-15 12:27:07 -07:00
// Then, actually send the segments.
2019-08-05 13:27:47 -07:00
for (NSString *segment in dataSegs) {
2021-03-12 14:19:16 -05:00
[self sendStringToWebSocket:segment];
2017-05-15 12:27:07 -07:00
}
}
2019-08-05 13:27:47 -07:00
- (void)nop:(NSTimer *)timer {
if (!isClosed) {
2017-05-15 12:27:07 -07:00
FFLog(@"I-RDB083004", @"(wsc:%@) nop", self.connectionId);
2021-03-12 14:19:16 -05:00
// Note: the backend is expecting a string "0" here, not any special
// ping/pong from build in websocket APIs.
[self sendStringToWebSocket:@"0"];
2019-08-05 13:27:47 -07:00
} else {
FFLog(@"I-RDB083005",
@"(wsc:%@) No more websocket; invalidating nop timer.",
self.connectionId);
2017-05-15 12:27:07 -07:00
[timer invalidate];
}
}
2019-08-05 13:27:47 -07:00
- (void)handleNewFrameCount:(int)numFrames {
2017-05-15 12:27:07 -07:00
self.totalFrames = numFrames;
frame = [[NSMutableString alloc] initWithString:@""];
2019-08-05 13:27:47 -07:00
FFLog(@"I-RDB083006", @"(wsc:%@) handleNewFrameCount: %d",
self.connectionId, self.totalFrames);
2017-05-15 12:27:07 -07:00
}
2019-08-05 13:27:47 -07:00
- (NSString *)extractFrameCount:(NSString *)message {
2017-05-15 12:27:07 -07:00
if ([message length] <= 4) {
int frameCount = [message intValue];
if (frameCount > 0) {
[self handleNewFrameCount:frameCount];
return nil;
}
}
[self handleNewFrameCount:1];
return message;
}
2019-08-05 13:27:47 -07:00
- (void)appendFrame:(NSString *)message {
2017-05-15 12:27:07 -07:00
[frame appendString:message];
self.totalFrames = self.totalFrames - 1;
if (self.totalFrames == 0) {
// Call delegate and pass an immutable version of the frame
2019-08-05 13:27:47 -07:00
NSDictionary *json = [NSJSONSerialization
JSONObjectWithData:[frame dataUsingEncoding:NSUTF8StringEncoding]
options:kNilOptions
error:nil];
2017-05-15 12:27:07 -07:00
frame = nil;
2019-08-05 13:27:47 -07:00
FFLog(@"I-RDB083007",
@"(wsc:%@) handleIncomingFrame sending complete frame: %d",
self.connectionId, self.totalFrames);
2017-06-30 10:47:37 -07:00
2017-05-15 12:27:07 -07:00
@autoreleasepool {
[self.delegate onMessage:self withMessage:json];
}
}
}
2019-08-05 13:27:47 -07:00
- (void)handleIncomingFrame:(NSString *)message {
2017-05-15 12:27:07 -07:00
[self resetKeepAlive];
if (self.buffering) {
[self appendFrame:message];
} else {
NSString *remaining = [self extractFrameCount:message];
if (remaining) {
[self appendFrame:remaining];
}
}
}
#pragma mark -
#pragma mark URLSessionWebSocketDelegate implementation
2021-03-12 14:19:16 -05:00
- (void)URLSession:(NSURLSession *)session
webSocketTask:(NSURLSessionWebSocketTask *)webSocketTask
didOpenWithProtocol:(NSString *)protocol
API_AVAILABLE(macos(10.15), ios(13.0), watchos(6.0), tvos(13.0)) {
2021-03-12 14:19:16 -05:00
[self webSocketDidOpen];
2017-05-15 12:27:07 -07:00
}
2021-03-12 14:19:16 -05:00
- (void)URLSession:(NSURLSession *)session
webSocketTask:(NSURLSessionWebSocketTask *)webSocketTask
didCloseWithCode:(NSURLSessionWebSocketCloseCode)closeCode
reason:(NSData *)reason
API_AVAILABLE(macos(10.15), ios(13.0), watchos(6.0), tvos(13.0)) {
2021-03-12 14:19:16 -05:00
FFLog(@"I-RDB083011", @"(wsc:%@) didCloseWithCode: %ld %@",
self.connectionId, (long)closeCode, reason);
[self onClosed];
}
2017-06-30 10:47:37 -07:00
- (void)receiveWebSocketData API_AVAILABLE(macos(10.15), ios(13.0),
watchos(6.0), tvos(13.0)) {
__weak __auto_type weakSelf = self;
2021-03-12 14:19:16 -05:00
[self.webSocketTask receiveMessageWithCompletionHandler:^(
NSURLSessionWebSocketMessage *_Nullable message,
NSError *_Nullable error) {
__auto_type strongSelf = weakSelf;
if (strongSelf == nil) {
2021-03-12 14:19:16 -05:00
return;
}
2017-06-30 10:47:37 -07:00
if (message) {
[strongSelf handleIncomingFrame:message.string];
} else if (error && !strongSelf->isClosed) {
FFWarn(@"I-RDB083020",
@"Error received from web socket, closing the connection. %@",
error);
[strongSelf shutdown];
return;
}
[strongSelf receiveWebSocketData];
2021-03-12 14:19:16 -05:00
}];
}
// Common to both SRWebSocketDelegate and URLSessionWebSocketDelegate.
- (void)webSocketDidOpen {
FFLog(@"I-RDB083008", @"(wsc:%@) webSocketDidOpen", self.connectionId);
everConnected = YES;
dispatch_async(dispatch_get_main_queue(), ^{
self->keepAlive =
[NSTimer scheduledTimerWithTimeInterval:kWebsocketKeepaliveInterval
target:self
selector:@selector(nop:)
userInfo:nil
repeats:YES];
FFLog(@"I-RDB083009", @"(wsc:%@) nop timer kicked off",
self.connectionId);
});
}
2017-05-15 12:27:07 -07:00
#pragma mark -
#pragma mark Private methods
2021-03-12 14:19:16 -05:00
/** Sends a string through the open web socket. */
- (void)sendStringToWebSocket:(NSString *)string {
if (@available(iOS 13.0, macOS 10.15, macCatalyst 13.1, tvOS 13.0,
watchOS 6.0, *)) {
// Use built-in URLSessionWebSocket functionality.
[self.webSocketTask
sendMessage:[[NSURLSessionWebSocketMessage alloc]
initWithString:string]
completionHandler:^(NSError *_Nullable error) {
if (error) {
FFWarn(@"I-RDB083016", @"Error sending web socket data: %@.",
error);
return;
}
}];
}
2021-03-12 14:19:16 -05:00
}
2017-05-15 12:27:07 -07:00
/**
2019-08-05 13:27:47 -07:00
* Note that the close / onClosed / shutdown cycle here is a little different
* from the javascript client. In order to properly handle deallocation, no
* close-related action is taken at a higher level until we have received
* notification from the websocket itself that it is closed. Otherwise, we end
* up deallocating this class and the FConnection class before the websocket has
* a change to call some of its delegate methods. So, since close is the
* external close handler, we just set a flag saying not to call our own
* delegate method and close the websocket. That will trigger a callback into
* this class that can then do things like clean up the keepalive timer.
2017-05-15 12:27:07 -07:00
*/
2019-08-05 13:27:47 -07:00
- (void)closeIfNeverConnected {
2017-05-15 12:27:07 -07:00
if (!everConnected) {
2019-08-05 13:27:47 -07:00
FFLog(@"I-RDB083012", @"(wsc:%@) Websocket timed out on connect",
self.connectionId);
if (@available(iOS 13.0, macOS 10.15, macCatalyst 13.1, tvOS 13.0,
watchOS 6.0, *)) {
[self.webSocketTask
cancelWithCloseCode:
NSURLSessionWebSocketCloseCodeNoStatusReceived
reason:nil];
}
2017-05-15 12:27:07 -07:00
}
}
2019-08-05 13:27:47 -07:00
- (void)shutdown {
2017-05-15 12:27:07 -07:00
isClosed = YES;
2017-06-30 10:47:37 -07:00
2017-05-15 12:27:07 -07:00
// Call delegate methods
[self.delegate onDisconnect:self wasEverConnected:everConnected];
}
2019-08-05 13:27:47 -07:00
- (void)onClosed {
2017-05-15 12:27:07 -07:00
if (!isClosed) {
FFLog(@"I-RDB083013", @"Websocket is closing itself");
[self shutdown];
}
if (@available(iOS 13.0, macOS 10.15, macCatalyst 13.1, tvOS 13.0,
watchOS 6.0, *)) {
self.webSocketTask = nil;
}
2017-05-15 12:27:07 -07:00
if (keepAlive.isValid) {
[keepAlive invalidate];
}
}
2019-08-05 13:27:47 -07:00
- (void)resetKeepAlive {
NSDate *newTime =
[NSDate dateWithTimeIntervalSinceNow:kWebsocketKeepaliveInterval];
// Calling setFireDate is actually kinda' expensive, so wait at least 5
// seconds before updating it.
2017-05-15 12:27:07 -07:00
if ([newTime timeIntervalSinceDate:keepAlive.fireDate] > 5) {
2019-08-05 13:27:47 -07:00
FFLog(@"I-RDB083014", @"(wsc:%@) resetting keepalive, to %@ ; old: %@",
self.connectionId, newTime, [keepAlive fireDate]);
2017-05-15 12:27:07 -07:00
[keepAlive setFireDate:newTime];
}
}
+ (NSURLRequest *)createRequestWithURL:(NSString *)connectionURL
userAgent:(NSString *)userAgent
googleAppID:(NSString *)googleAppID
appCheckToken:(nullable NSString *)appCheckToken {
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]
initWithURL:[[NSURL alloc] initWithString:connectionURL]];
[request setValue:appCheckToken forHTTPHeaderField:kAppCheckTokenHeader];
[request setValue:userAgent forHTTPHeaderField:kUserAgentHeader];
[request setValue:googleAppID forHTTPHeaderField:kGoogleAppIDHeader];
return [request copy];
}
2017-05-15 12:27:07 -07:00
@end