FIRMessagingFakeSocket.m 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /*
  2. * Copyright 2017 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 "FIRMessagingFakeSocket.h"
  17. #import "FIRMessagingConstants.h"
  18. #import "FIRMessagingDefines.h"
  19. #import <GoogleToolboxForMac/GTMDefines.h>
  20. @interface FIRMessagingSecureSocket() <NSStreamDelegate>
  21. @property(nonatomic, readwrite, assign) FIRMessagingSecureSocketState state;
  22. @property(nonatomic, readwrite, strong) NSInputStream *inStream;
  23. @property(nonatomic, readwrite, strong) NSOutputStream *outStream;
  24. @property(nonatomic, readwrite, assign) BOOL isInStreamOpen;
  25. @property(nonatomic, readwrite, assign) BOOL isOutStreamOpen;
  26. @property(nonatomic, readwrite, strong) NSRunLoop *runLoop;
  27. @end
  28. @interface FIRMessagingFakeSocket ()
  29. @property(nonatomic, readwrite, assign) int8_t bufferSize;
  30. @end
  31. @implementation FIRMessagingFakeSocket
  32. - (instancetype)initWithBufferSize:(uint8_t)bufferSize {
  33. self = [super init];
  34. if (self) {
  35. _bufferSize = bufferSize;
  36. }
  37. return self;
  38. }
  39. - (void)connectToHost:(NSString *)host
  40. port:(NSUInteger)port
  41. onRunLoop:(NSRunLoop *)runLoop {
  42. self.state = kFIRMessagingSecureSocketOpening;
  43. self.runLoop = runLoop;
  44. CFReadStreamRef inputStreamRef = nil;
  45. CFWriteStreamRef outputStreamRef = nil;
  46. CFStreamCreateBoundPair(NULL,
  47. &inputStreamRef,
  48. &outputStreamRef,
  49. self.bufferSize);
  50. self.inStream = CFBridgingRelease(inputStreamRef);
  51. self.outStream = CFBridgingRelease(outputStreamRef);
  52. if (!self.inStream || !self.outStream) {
  53. NSAssert(NO, @"Cannot create a fake socket");
  54. return;
  55. }
  56. self.isInStreamOpen = NO;
  57. self.isOutStreamOpen = NO;
  58. [self openStream:self.outStream];
  59. [self openStream:self.inStream];
  60. }
  61. - (void)openStream:(NSStream *)stream {
  62. _GTMDevAssert(stream, @"Cannot open nil stream");
  63. if (stream) {
  64. stream.delegate = self;
  65. [stream scheduleInRunLoop:self.runLoop forMode:NSDefaultRunLoopMode];
  66. [stream open];
  67. }
  68. }
  69. @end