Compare commits
No commits in common. "master" and "gh-pages" have entirely different histories.
26
.gitignore
vendored
26
.gitignore
vendored
@ -1,26 +0,0 @@
|
||||
.idea/
|
||||
.env/
|
||||
*.egg-info
|
||||
reports/
|
||||
build/
|
||||
nohup.out
|
||||
.DS_Store
|
||||
xcuserdata/
|
||||
*.pbxuser
|
||||
!default.pbxuser
|
||||
*.mode1v3
|
||||
!default.mode1v3
|
||||
*.mode2v3
|
||||
!default.mode2v3
|
||||
*.perspectivev3
|
||||
!default.perspectivev3
|
||||
*.xcworkspace
|
||||
!default.xcworkspace
|
||||
*xcuserdata
|
||||
*.xccheckout
|
||||
profile
|
||||
*.moved-aside
|
||||
DerivedData
|
||||
extern/
|
||||
|
||||
*.pyc
|
||||
3
.gitmodules
vendored
3
.gitmodules
vendored
@ -1,3 +0,0 @@
|
||||
[submodule "Vendor/xctoolchain"]
|
||||
path = Vendor/xctoolchain
|
||||
url = https://github.com/ParsePlatform/xctoolchain.git
|
||||
@ -1 +0,0 @@
|
||||
2.3.1
|
||||
43
.travis.yml
43
.travis.yml
@ -1,43 +0,0 @@
|
||||
branches:
|
||||
only:
|
||||
- master
|
||||
language: objective-c
|
||||
os: osx
|
||||
osx_image: xcode7.3
|
||||
env:
|
||||
matrix:
|
||||
- TEST_TYPE=iOS
|
||||
- TEST_TYPE=OSX
|
||||
- TEST_TYPE=tvOS
|
||||
- TEST_TYPE=CocoaPods
|
||||
- TEST_TYPE=Carthage
|
||||
before_install:
|
||||
- |
|
||||
if [ "$TEST_TYPE" = iOS ] || [ "$TEST_TYPE" = OSX ] || [ "$TEST_TYPE" = tvOS ]; then
|
||||
bundle install
|
||||
elif [ "$TEST_TYPE" = Carthage ]; then
|
||||
brew update
|
||||
brew install carthage || brew upgrade carthage
|
||||
fi
|
||||
install:
|
||||
- |
|
||||
if [ "$TEST_TYPE" = iOS ]; then
|
||||
./TestSupport/setup_env.sh .env
|
||||
fi
|
||||
script:
|
||||
- |
|
||||
if [ "$TEST_TYPE" = iOS ]; then
|
||||
set -o pipefail
|
||||
xcodebuild -project SocketRocket.xcodeproj -scheme "SocketRocket-iOS" -sdk iphonesimulator build test
|
||||
elif [ "$TEST_TYPE" = OSX ]; then
|
||||
set -o pipefail
|
||||
xcodebuild -project SocketRocket.xcodeproj -scheme "SocketRocket-macOS" -sdk macosx build | xcpretty -c
|
||||
elif [ "$TEST_TYPE" = tvOS ]; then
|
||||
set -o pipefail
|
||||
xcodebuild -project SocketRocket.xcodeproj -scheme "SocketRocket-tvOS" -sdk appletvsimulator build | xcpretty -c
|
||||
elif [ "$TEST_TYPE" = CocoaPods ]; then
|
||||
pod lib lint SocketRocket.podspec
|
||||
pod lib lint --use-libraries SocketRocket.podspec
|
||||
elif [ "$TEST_TYPE" = Carthage ]; then
|
||||
carthage build --no-skip-current
|
||||
fi
|
||||
@ -1,33 +0,0 @@
|
||||
# Contributing to SocketRocket
|
||||
We want to make contributing to this project as easy and transparent as possible.
|
||||
|
||||
## Pull Requests
|
||||
We actively welcome your pull requests.
|
||||
|
||||
1. Fork the repo and create your branch from `master`.
|
||||
2. If you've added code that should be tested, add tests.
|
||||
3. If you've changed APIs, update the documentation.
|
||||
4. Ensure the test suite passes.
|
||||
5. Make sure your code lints.
|
||||
6. If you haven't already, complete the Contributor License Agreement ("CLA").
|
||||
|
||||
## Contributor License Agreement ("CLA")
|
||||
In order to accept your pull request, we need you to submit a CLA.
|
||||
You only need to do this once to work on any of Facebook's open source projects.
|
||||
|
||||
Complete your CLA here: <https://code.facebook.com/cla>
|
||||
|
||||
## Issues
|
||||
We use GitHub issues to track public bugs. Please ensure your description is
|
||||
clear and has sufficient instructions to be able to reproduce the issue.
|
||||
|
||||
Facebook has a [bounty program](https://www.facebook.com/whitehat/) for the safe
|
||||
disclosure of security bugs. In those cases, please go through the process
|
||||
outlined on that page and do not file a public issue.
|
||||
|
||||
## Coding Style
|
||||
* Most importantly, match the existing code style as much as possible.
|
||||
* Try to keep lines under 140 characters, if possible.
|
||||
|
||||
## License
|
||||
By contributing to SocketRocket, you agree that your contributions will be licensed under its BSD license.
|
||||
@ -1 +0,0 @@
|
||||
../Vendor/xctoolchain/Configurations/
|
||||
@ -1,17 +0,0 @@
|
||||
//
|
||||
// Copyright (c) 2016-present, Facebook, Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the BSD-style license found in the
|
||||
// LICENSE file in the root directory of this source tree. An additional grant
|
||||
// of patent rights can be found in the PATENTS file in the same directory.
|
||||
//
|
||||
|
||||
#include "Shared/Platform/iOS.xcconfig"
|
||||
#include "Shared/Product/DynamicFramework.xcconfig"
|
||||
|
||||
PRODUCT_NAME = SocketRocket
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.facebook.socketrocket.ios
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 8.0
|
||||
|
||||
INFOPLIST_FILE = $(SRCROOT)/SocketRocket/Resources/Info.plist
|
||||
@ -1,20 +0,0 @@
|
||||
//
|
||||
// Copyright (c) 2016-present, Facebook, Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the BSD-style license found in the
|
||||
// LICENSE file in the root directory of this source tree. An additional grant
|
||||
// of patent rights can be found in the PATENTS file in the same directory.
|
||||
//
|
||||
|
||||
#include "Shared/Platform/iOS.xcconfig"
|
||||
#include "Shared/Product/StaticFramework.xcconfig"
|
||||
|
||||
PRODUCT_NAME = SocketRocket
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.facebook.socketrocket.ios
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 6.0
|
||||
|
||||
INFOPLIST_FILE = $(SRCROOT)/SocketRocket/Resources/Info.plist
|
||||
|
||||
OTHER_CFLAGS[sdk=iphoneos9.*] = $(inherited) -fembed-bitcode
|
||||
OTHER_LDFLAGS = $(inherited) -Licucore
|
||||
@ -1,17 +0,0 @@
|
||||
//
|
||||
// Copyright (c) 2016-present, Facebook, Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the BSD-style license found in the
|
||||
// LICENSE file in the root directory of this source tree. An additional grant
|
||||
// of patent rights can be found in the PATENTS file in the same directory.
|
||||
//
|
||||
|
||||
#include "Shared/Platform/macOS.xcconfig"
|
||||
#include "Shared/Product/DynamicFramework.xcconfig"
|
||||
|
||||
PRODUCT_NAME = SocketRocket
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.facebook.socketrocket.macos
|
||||
MACOSX_DEPLOYMENT_TARGET = 10.8
|
||||
|
||||
INFOPLIST_FILE = $(SRCROOT)/SocketRocket/Resources/Info.plist
|
||||
@ -1,16 +0,0 @@
|
||||
//
|
||||
// Copyright (c) 2016-present, Facebook, Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the BSD-style license found in the
|
||||
// LICENSE file in the root directory of this source tree. An additional grant
|
||||
// of patent rights can be found in the PATENTS file in the same directory.
|
||||
//
|
||||
|
||||
#include "Shared/Platform/tvOS.xcconfig"
|
||||
#include "Shared/Product/DynamicFramework.xcconfig"
|
||||
|
||||
PRODUCT_NAME = SocketRocket
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.facebook.socketrocket.tvos
|
||||
|
||||
INFOPLIST_FILE = $(SRCROOT)/SocketRocket/Resources/Info.plist
|
||||
@ -1,19 +0,0 @@
|
||||
//
|
||||
// Copyright (c) 2016-present, Facebook, Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the BSD-style license found in the
|
||||
// LICENSE file in the root directory of this source tree. An additional grant
|
||||
// of patent rights can be found in the PATENTS file in the same directory.
|
||||
//
|
||||
|
||||
#include "Shared/Platform/iOS.xcconfig"
|
||||
#include "Shared/Product/LogicTests.xcconfig"
|
||||
|
||||
PRODUCT_NAME = SocketRocketTests-iOS
|
||||
PRODUCT_MODULE_NAME = SocketRocketTests
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.facebook.socketrocket.tests.ios
|
||||
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 7.0
|
||||
|
||||
INFOPLIST_FILE = $(SRCROOT)/Tests/Resources/Info.plist
|
||||
@ -1,19 +0,0 @@
|
||||
//
|
||||
// Copyright (c) 2016-present, Facebook, Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the BSD-style license found in the
|
||||
// LICENSE file in the root directory of this source tree. An additional grant
|
||||
// of patent rights can be found in the PATENTS file in the same directory.
|
||||
//
|
||||
|
||||
#include "Shared/Platform/iOS.xcconfig"
|
||||
#include "Shared/Product/Application.xcconfig"
|
||||
|
||||
PRODUCT_NAME = TestChat
|
||||
PRODUCT_MODULE_NAME = TestChat
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.facebook.socketrocket.testchat
|
||||
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 8.0
|
||||
|
||||
INFOPLIST_FILE = $(SRCROOT)/TestChat/TestChat-Info.plist
|
||||
30
LICENSE
30
LICENSE
@ -1,30 +0,0 @@
|
||||
BSD License
|
||||
|
||||
For SocketRocket software
|
||||
|
||||
Copyright (c) 2016-present, Facebook, Inc. All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification,
|
||||
are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
|
||||
* Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
* Neither the name Facebook nor the names of its contributors may be used to
|
||||
endorse or promote products derived from this software without specific
|
||||
prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
||||
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
@ -1,11 +0,0 @@
|
||||
Copyright (c) 2016-present, Facebook, Inc. All rights reserved.
|
||||
|
||||
The examples provided by Facebook are for non-commercial testing and evaluation
|
||||
purposes only. Facebook reserves all rights not expressly granted.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
|
||||
FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
|
||||
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
30
Makefile
30
Makefile
@ -1,30 +0,0 @@
|
||||
TEST_SCENARIOS="[1-8]*"
|
||||
TEST_URL='ws://localhost:9001/'
|
||||
|
||||
all:
|
||||
$(MAKE) -C SocketRocket
|
||||
|
||||
clean:
|
||||
$(MAKE) -C SocketRocket clean
|
||||
|
||||
.env:
|
||||
|
||||
./TestSupport/setup_env.sh .env
|
||||
|
||||
test: .env
|
||||
|
||||
mkdir -p pages/results
|
||||
bash ./TestSupport/run_test_server.sh $(TEST_SCENARIOS) $(TEST_URL) Debug || open pages/results/index.html && false
|
||||
open pages/results/index.html
|
||||
|
||||
test_all: .env
|
||||
|
||||
mkdir -p pages/results
|
||||
bash ./TestSupport/run_test_server.sh '*' $(TEST_URL) Debug || open pages/results/index.html && false
|
||||
open pages/results/index.html
|
||||
|
||||
test_perf: .env
|
||||
|
||||
mkdir -p pages/results
|
||||
bash ./TestSupport/run_test_server.sh '9.*' $(TEST_URL) Release || open pages/results/index.html && false
|
||||
open pages/results/index.html
|
||||
33
PATENTS
33
PATENTS
@ -1,33 +0,0 @@
|
||||
Additional Grant of Patent Rights Version 2
|
||||
|
||||
"Software" means the SocketRocket software distributed by Facebook, Inc.
|
||||
|
||||
Facebook, Inc. ("Facebook") hereby grants to each recipient of the Software
|
||||
("you") a perpetual, worldwide, royalty-free, non-exclusive, irrevocable
|
||||
(subject to the termination provision below) license under any Necessary
|
||||
Claims, to make, have made, use, sell, offer to sell, import, and otherwise
|
||||
transfer the Software. For avoidance of doubt, no license is granted under
|
||||
Facebook’s rights in any patent claims that are infringed by (i) modifications
|
||||
to the Software made by you or any third party or (ii) the Software in
|
||||
combination with any software or other technology.
|
||||
|
||||
The license granted hereunder will terminate, automatically and without notice,
|
||||
if you (or any of your subsidiaries, corporate affiliates or agents) initiate
|
||||
directly or indirectly, or take a direct financial interest in, any Patent
|
||||
Assertion: (i) against Facebook or any of its subsidiaries or corporate
|
||||
affiliates, (ii) against any party if such Patent Assertion arises in whole or
|
||||
in part from any software, technology, product or service of Facebook or any of
|
||||
its subsidiaries or corporate affiliates, or (iii) against any party relating
|
||||
to the Software. Notwithstanding the foregoing, if Facebook or any of its
|
||||
subsidiaries or corporate affiliates files a lawsuit alleging patent
|
||||
infringement against you in the first instance, and you respond by filing a
|
||||
patent infringement counterclaim in that lawsuit against that party that is
|
||||
unrelated to the Software, the license granted hereunder will not terminate
|
||||
under section (i) of this paragraph due to such counterclaim.
|
||||
|
||||
A "Necessary Claim" is a claim of a patent owned by Facebook that is
|
||||
necessarily infringed by the Software standing alone.
|
||||
|
||||
A "Patent Assertion" is any lawsuit or other action alleging direct, indirect,
|
||||
or contributory infringement or inducement to infringe any patent, including a
|
||||
cross-claim or counterclaim.
|
||||
213
README.md
213
README.md
@ -1,213 +0,0 @@
|
||||
# SocketRocket
|
||||
|
||||
![Platforms][platforms-svg]
|
||||
[![License][license-svg]][license-link]
|
||||
|
||||
[![Podspec][podspec-svg]][podspec-link]
|
||||
[![Carthage Compatible][carthage-svg]](carthage-link)
|
||||
|
||||
[![Build Status][build-status-svg]][build-status-link]
|
||||
|
||||
A conforming WebSocket ([RFC 6455](https://tools.ietf.org/html/rfc6455>)) client library for iOS, macOS and tvOS.
|
||||
|
||||
Test results for SocketRocket [here](http://facebook.github.io/SocketRocket/results/).
|
||||
You can compare to what modern browsers look like [here](http://autobahn.ws/testsuite/reports/clients/index.html).
|
||||
|
||||
SocketRocket currently conforms to all core ~300 of [Autobahn](http://autobahn.ws/testsuite/>)'s fuzzing tests
|
||||
(aside from two UTF-8 ones where it is merely *non-strict* tests 6.4.2 and 6.4.4).
|
||||
|
||||
## Features/Design
|
||||
|
||||
- TLS (wss) support, including self-signed certificates.
|
||||
- Seems to perform quite well.
|
||||
- Supports HTTP Proxies.
|
||||
- Supports IPv4/IPv6.
|
||||
- Supports SSL certificate pinning.
|
||||
- Sends `ping` and can process `pong` events.
|
||||
- Asynchronous and non-blocking. Most of the work is done on a background thread.
|
||||
- Supports iOS, macOS, tvOS.
|
||||
|
||||
## Installing
|
||||
|
||||
There are a few options. Choose one, or just figure it out:
|
||||
|
||||
- **[CocoaPods](https://cocoapods.org)**
|
||||
|
||||
Add the following line to your Podfile:
|
||||
```ruby
|
||||
pod 'SocketRocket'
|
||||
```
|
||||
Run `pod install`, and you are all set.
|
||||
|
||||
- **[Carthage](https://github.com/carthage/carthage)**
|
||||
|
||||
Add the following line to your Cartfile:
|
||||
```
|
||||
github "facebook/SocketRocket"
|
||||
```
|
||||
Run `carthage update`, and you should now have the latest version of `SocketRocket` in your `Carthage` folder.
|
||||
|
||||
- **Using SocketRocket as a sub-project**
|
||||
|
||||
You can also include `SocketRocket` as a subproject inside of your application if you'd prefer, although we do not recommend this, as it will increase your indexing time significantly. To do so, just drag and drop the `SocketRocket.xcodeproj` file into your workspace.
|
||||
|
||||
## API
|
||||
|
||||
### `SRWebSocket`
|
||||
|
||||
The Web Socket.
|
||||
|
||||
#### Note:
|
||||
|
||||
`SRWebSocket` will retain itself between `-(void)open` and when it closes, errors, or fails.
|
||||
This is similar to how `NSURLConnection` behaves (unlike `NSURLConnection`, `SRWebSocket` won't retain the delegate).
|
||||
|
||||
#### Interface
|
||||
|
||||
```objective-c
|
||||
@interface SRWebSocket : NSObject
|
||||
|
||||
// Make it with this
|
||||
- (instancetype)initWithURLRequest:(NSURLRequest *)request;
|
||||
|
||||
// Set this before opening
|
||||
@property (nonatomic, weak) id <SRWebSocketDelegate> delegate;
|
||||
|
||||
// Open with this
|
||||
- (void)open;
|
||||
|
||||
// Close it with this
|
||||
- (void)close;
|
||||
|
||||
// Send a Data
|
||||
- (void)sendData:(nullable NSData *)data error:(NSError **)error;
|
||||
|
||||
// Send a UTF8 String
|
||||
- (void)sendString:(NSString *)string error:(NSError **)error;
|
||||
|
||||
@end
|
||||
```
|
||||
|
||||
### `SRWebSocketDelegate`
|
||||
|
||||
You implement this
|
||||
|
||||
```objective-c
|
||||
@protocol SRWebSocketDelegate <NSObject>
|
||||
|
||||
@optional
|
||||
|
||||
- (void)webSocketDidOpen:(SRWebSocket *)webSocket;
|
||||
|
||||
- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessageWithString:(NSString *)string;
|
||||
- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessageWithData:(NSData *)data;
|
||||
|
||||
- (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error;
|
||||
- (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(nullable NSString *)reason wasClean:(BOOL)wasClean;
|
||||
|
||||
@end
|
||||
```
|
||||
|
||||
## Testing
|
||||
|
||||
Included are setup scripts for the python testing environment.
|
||||
It comes packaged with vitualenv so all the dependencies are installed in userland.
|
||||
|
||||
To run the short test from the command line, run:
|
||||
```bash
|
||||
make test
|
||||
```
|
||||
|
||||
To run all the tests, run:
|
||||
```bash
|
||||
make test_all
|
||||
```
|
||||
|
||||
The short tests don't include the performance tests
|
||||
(the test harness is actually the bottleneck, not SocketRocket).
|
||||
|
||||
The first time this is run, it may take a while to install the dependencies. It will be smooth sailing after that.
|
||||
|
||||
You can also run tests inside Xcode, which runs the same thing, but makes it easier to debug.
|
||||
|
||||
- Choose the `SocketRocket` target
|
||||
- Run the test action (`⌘+U`)
|
||||
|
||||
### TestChat Demo Application
|
||||
|
||||
SocketRocket includes a demo app, TestChat.
|
||||
It will "chat" with a listening websocket on port 9900.
|
||||
|
||||
#### TestChat Server
|
||||
|
||||
The sever takes a message and broadcasts it to all other connected clients.
|
||||
|
||||
It requires some dependencies though to run.
|
||||
We also want to reuse the virtualenv we made when we ran the tests.
|
||||
If you haven't run the tests yet, go into the SocketRocket root directory and type:
|
||||
|
||||
```bash
|
||||
make test
|
||||
```
|
||||
|
||||
This will set up your [virtualenv](https://pypi.python.org/pypi/virtualenv).
|
||||
|
||||
Now, in your terminal:
|
||||
|
||||
```bash
|
||||
source .env/bin/activate
|
||||
pip install git+https://github.com/tornadoweb/tornado.git
|
||||
```
|
||||
|
||||
In the same terminal session, start the chatroom server:
|
||||
|
||||
```bash
|
||||
python TestChatServer/py/chatroom.py
|
||||
```
|
||||
|
||||
There's also a Go implementation (with the latest weekly) where you can:
|
||||
|
||||
```bash
|
||||
cd TestChatServer/go
|
||||
go run chatroom.go
|
||||
```
|
||||
|
||||
#### Chatting
|
||||
|
||||
Now, start TestChat.app (just run the target in the Xcode project).
|
||||
If you had it started already you can hit the refresh button to reconnect.
|
||||
It should say "Connected!" on top.
|
||||
|
||||
To talk with the app, open up your browser to [http://localhost:9000](http://localhost:9000) and start chatting.
|
||||
|
||||
|
||||
## WebSocket Server Implementation Recommendations
|
||||
|
||||
SocketRocket has been used with the following libraries:
|
||||
|
||||
- [Tornado](https://github.com/tornadoweb/tornado)
|
||||
- Go's [WebSocket package](https://godoc.org/golang.org/x/net/websocket) or Gorilla's [version](http://www.gorillatoolkit.org/pkg/websocket).
|
||||
- [Autobahn](http://autobahn.ws/testsuite/) (using its fuzzing client).
|
||||
|
||||
The Tornado one is dirt simple and works like a charm.
|
||||
([IPython notebook](http://ipython.org/ipython-doc/dev/interactive/htmlnotebook.html) uses it too).
|
||||
It's much easier to configure handlers and routes than in Autobahn/twisted.
|
||||
|
||||
## Contributing
|
||||
|
||||
We’re glad you’re interested in SocketRocket, and we’d love to see where you take it.
|
||||
Please read our [contributing guidelines](https://github.com/facebook/SocketRocket/blob/master/CONTRIBUTING.md) prior to submitting a Pull Request.
|
||||
|
||||
[build-status-svg]: https://img.shields.io/travis/facebook/SocketRocket/master.svg
|
||||
[build-status-link]: https://travis-ci.org/facebook/SocketRocket/branches
|
||||
|
||||
[license-svg]: https://img.shields.io/badge/license-BSD-lightgrey.svg
|
||||
[license-link]: https://github.com/facebook/SocketRocket/blob/master/LICENSE
|
||||
|
||||
[podspec-svg]: https://img.shields.io/cocoapods/v/SocketRocket.svg
|
||||
[podspec-link]: https://cocoapods.org/pods/SocketRocket
|
||||
|
||||
[carthage-svg]: https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat
|
||||
[carthage-link]: https://github.com/carthage/carthage
|
||||
|
||||
[platforms-svg]: http://img.shields.io/cocoapods/p/SocketRocket.svg?style=flat
|
||||
@ -1,22 +0,0 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'SocketRocket'
|
||||
s.version = '0.5.1'
|
||||
s.summary = 'A conforming WebSocket (RFC 6455) client library for iOS, macOS and tvOS.'
|
||||
s.homepage = 'https://github.com/facebook/SocketRocket'
|
||||
s.authors = { 'Nikita Lutsenko' => 'nlutsenko@me.com', 'Dan Federman' => 'federman@squareup.com', 'Mike Lewis' => 'mikelikespie@gmail.com' }
|
||||
s.license = 'BSD'
|
||||
s.source = { :git => 'https://github.com/facebook/SocketRocket.git', :tag => s.version.to_s }
|
||||
s.requires_arc = true
|
||||
|
||||
s.source_files = 'SocketRocket/**/*.{h,m}'
|
||||
s.public_header_files = 'SocketRocket/*.h'
|
||||
|
||||
s.ios.deployment_target = '6.0'
|
||||
s.osx.deployment_target = '10.8'
|
||||
s.tvos.deployment_target = '9.0'
|
||||
|
||||
s.ios.frameworks = 'CFNetwork', 'Security'
|
||||
s.osx.frameworks = 'CoreServices', 'Security'
|
||||
s.tvos.frameworks = 'CFNetwork', 'Security'
|
||||
s.libraries = 'icucore'
|
||||
end
|
||||
File diff suppressed because it is too large
Load Diff
@ -1,7 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Workspace
|
||||
version = "1.0">
|
||||
<FileRef
|
||||
location = "self:SocketRocket.xcodeproj">
|
||||
</FileRef>
|
||||
</Workspace>
|
||||
@ -1,8 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>IDEWorkspaceSharedSettings_AutocreateContextsIfNeeded</key>
|
||||
<false/>
|
||||
</dict>
|
||||
</plist>
|
||||
@ -1,80 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0730"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "2D4227611BB4358C000C1A6C"
|
||||
BuildableName = "SocketRocket.framework"
|
||||
BlueprintName = "SocketRocket-iOS-Dynamic"
|
||||
ReferencedContainer = "container:SocketRocket.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
</Testables>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "2D4227611BB4358C000C1A6C"
|
||||
BuildableName = "SocketRocket.framework"
|
||||
BlueprintName = "SocketRocket-iOS-Dynamic"
|
||||
ReferencedContainer = "container:SocketRocket.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "2D4227611BB4358C000C1A6C"
|
||||
BuildableName = "SocketRocket.framework"
|
||||
BlueprintName = "SocketRocket-iOS-Dynamic"
|
||||
ReferencedContainer = "container:SocketRocket.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
@ -1,149 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0730"
|
||||
version = "1.7">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "81D6475F1D2CA78800690609"
|
||||
BuildableName = "SocketRocket.framework"
|
||||
BlueprintName = "SocketRocket-iOS"
|
||||
ReferencedContainer = "container:SocketRocket.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "NO"
|
||||
buildForProfiling = "NO"
|
||||
buildForArchiving = "NO"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "F6BDA801145900D200FE3253"
|
||||
BuildableName = "SocketRocketTests-iOS.xctest"
|
||||
BlueprintName = "SocketRocketTests-iOS"
|
||||
ReferencedContainer = "container:SocketRocket.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<PreActions>
|
||||
<ExecutionAction
|
||||
ActionType = "Xcode.IDEStandardExecutionActionsCore.ExecutionActionType.ShellScriptAction">
|
||||
<ActionContent
|
||||
title = "Run Script"
|
||||
scriptText = "PIDFILE=$TMPDIR/sr_test_server.pid if [ -r $PIDFILE ]; then EXISTING_PID=`cat $PIDFILE` echo "Killing Dangling Autobahn Server PID:" $EXISTING_PID kill $EXISTING_PID || true rm $PIDFILE fi pushd $PROJECT_DIR source .env/bin/activate nohup ./TestSupport/run_test_server.sh & echo $! > $PIDFILE popd ">
|
||||
<EnvironmentBuildable>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "F6BDA801145900D200FE3253"
|
||||
BuildableName = "SocketRocketTests-iOS.xctest"
|
||||
BlueprintName = "SocketRocketTests-iOS"
|
||||
ReferencedContainer = "container:SocketRocket.xcodeproj">
|
||||
</BuildableReference>
|
||||
</EnvironmentBuildable>
|
||||
</ActionContent>
|
||||
</ExecutionAction>
|
||||
</PreActions>
|
||||
<PostActions>
|
||||
<ExecutionAction
|
||||
ActionType = "Xcode.IDEStandardExecutionActionsCore.ExecutionActionType.ShellScriptAction">
|
||||
<ActionContent
|
||||
title = "Run Script"
|
||||
scriptText = "PIDFILE=$TMPDIR/sr_test_server.pid if [ -r $PIDFILE ]; then EXISTING_PID=`cat $PIDFILE` echo "Killing SR TestServer PID:" $EXISTING_PID kill $EXISTING_PID rm $PIDFILE fi ">
|
||||
<EnvironmentBuildable>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "F6BDA801145900D200FE3253"
|
||||
BuildableName = "SocketRocketTests-iOS.xctest"
|
||||
BlueprintName = "SocketRocketTests-iOS"
|
||||
ReferencedContainer = "container:SocketRocket.xcodeproj">
|
||||
</BuildableReference>
|
||||
</EnvironmentBuildable>
|
||||
</ActionContent>
|
||||
</ExecutionAction>
|
||||
</PostActions>
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "F6BDA801145900D200FE3253"
|
||||
BuildableName = "SocketRocketTests-iOS.xctest"
|
||||
BlueprintName = "SocketRocketTests-iOS"
|
||||
ReferencedContainer = "container:SocketRocket.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "81D6475F1D2CA78800690609"
|
||||
BuildableName = "SocketRocket.framework"
|
||||
BlueprintName = "SocketRocket-iOS"
|
||||
ReferencedContainer = "container:SocketRocket.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "81D6475F1D2CA78800690609"
|
||||
BuildableName = "SocketRocket.framework"
|
||||
BlueprintName = "SocketRocket-iOS"
|
||||
ReferencedContainer = "container:SocketRocket.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "81D6475F1D2CA78800690609"
|
||||
BuildableName = "SocketRocket.framework"
|
||||
BlueprintName = "SocketRocket-iOS"
|
||||
ReferencedContainer = "container:SocketRocket.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
@ -1,80 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0730"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "F668C87F153E91210044DBAC"
|
||||
BuildableName = "SocketRocket.framework"
|
||||
BlueprintName = "SocketRocket-macOS"
|
||||
ReferencedContainer = "container:SocketRocket.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
</Testables>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "F668C87F153E91210044DBAC"
|
||||
BuildableName = "SocketRocket.framework"
|
||||
BlueprintName = "SocketRocket-macOS"
|
||||
ReferencedContainer = "container:SocketRocket.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "F668C87F153E91210044DBAC"
|
||||
BuildableName = "SocketRocket.framework"
|
||||
BlueprintName = "SocketRocket-macOS"
|
||||
ReferencedContainer = "container:SocketRocket.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
@ -1,80 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0730"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "3345DC821C52ACD70083CCB8"
|
||||
BuildableName = "SocketRocket.framework"
|
||||
BlueprintName = "SocketRocket-tvOS"
|
||||
ReferencedContainer = "container:SocketRocket.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
</Testables>
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "2D4227611BB4358C000C1A6C"
|
||||
BuildableName = "SocketRocket.framework"
|
||||
BlueprintName = "SocketRocket-iOS-Dynamic"
|
||||
ReferencedContainer = "container:SocketRocket.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "3345DC821C52ACD70083CCB8"
|
||||
BuildableName = "SocketRocket.framework"
|
||||
BlueprintName = "SocketRocket-tvOS"
|
||||
ReferencedContainer = "container:SocketRocket.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
@ -1,101 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0730"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "NO"
|
||||
buildForArchiving = "NO"
|
||||
buildForAnalyzing = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "F6BDA801145900D200FE3253"
|
||||
BuildableName = "SocketRocketTests-iOS.xctest"
|
||||
BlueprintName = "SocketRocketTests-iOS"
|
||||
ReferencedContainer = "container:SocketRocket.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "NO">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "F6BDA801145900D200FE3253"
|
||||
BuildableName = "SocketRocketTests-iOS.xctest"
|
||||
BlueprintName = "SocketRocketTests-iOS"
|
||||
ReferencedContainer = "container:SocketRocket.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "F6BDA801145900D200FE3253"
|
||||
BuildableName = "SocketRocketTests-iOS.xctest"
|
||||
BlueprintName = "SocketRocketTests-iOS"
|
||||
ReferencedContainer = "container:SocketRocket.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
<AdditionalOption
|
||||
key = "NSZombieEnabled"
|
||||
value = "YES"
|
||||
isEnabled = "YES">
|
||||
</AdditionalOption>
|
||||
<AdditionalOption
|
||||
key = "OBJC_PRINT_EXCEPTIONS"
|
||||
value = "YES"
|
||||
isEnabled = "YES">
|
||||
</AdditionalOption>
|
||||
<AdditionalOption
|
||||
key = "MallocGuardEdges"
|
||||
value = ""
|
||||
isEnabled = "YES">
|
||||
</AdditionalOption>
|
||||
<AdditionalOption
|
||||
key = "MallocScribble"
|
||||
value = ""
|
||||
isEnabled = "YES">
|
||||
</AdditionalOption>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
@ -1,111 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0730"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "F62417E214D52F3C003CE997"
|
||||
BuildableName = "TestChat.app"
|
||||
BlueprintName = "TestChat"
|
||||
ReferencedContainer = "container:SocketRocket.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.GDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
</Testables>
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "F62417E214D52F3C003CE997"
|
||||
BuildableName = "TestChat.app"
|
||||
BlueprintName = "TestChat"
|
||||
ReferencedContainer = "container:SocketRocket.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<BuildableProductRunnable
|
||||
runnableDebuggingMode = "0">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "F62417E214D52F3C003CE997"
|
||||
BuildableName = "TestChat.app"
|
||||
BlueprintName = "TestChat"
|
||||
ReferencedContainer = "container:SocketRocket.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
<AdditionalOptions>
|
||||
<AdditionalOption
|
||||
key = "NSZombieEnabled"
|
||||
value = "YES"
|
||||
isEnabled = "YES">
|
||||
</AdditionalOption>
|
||||
<AdditionalOption
|
||||
key = "OBJC_PRINT_EXCEPTIONS"
|
||||
value = "YES"
|
||||
isEnabled = "YES">
|
||||
</AdditionalOption>
|
||||
<AdditionalOption
|
||||
key = "MallocGuardEdges"
|
||||
value = ""
|
||||
isEnabled = "YES">
|
||||
</AdditionalOption>
|
||||
<AdditionalOption
|
||||
key = "MallocScribble"
|
||||
value = ""
|
||||
isEnabled = "YES">
|
||||
</AdditionalOption>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<BuildableProductRunnable
|
||||
runnableDebuggingMode = "0">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "F62417E214D52F3C003CE997"
|
||||
BuildableName = "TestChat.app"
|
||||
BlueprintName = "TestChat"
|
||||
ReferencedContainer = "container:SocketRocket.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
@ -1,67 +0,0 @@
|
||||
//
|
||||
// Copyright (c) 2016-present, Facebook, Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the BSD-style license found in the
|
||||
// LICENSE file in the root directory of this source tree. An additional grant
|
||||
// of patent rights can be found in the PATENTS file in the same directory.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
#import <SocketRocket/SRWebSocket.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
#if OBJC_BOOL_IS_BOOL
|
||||
|
||||
struct SRDelegateAvailableMethods {
|
||||
BOOL didReceiveMessage : 1;
|
||||
BOOL didReceiveMessageWithString : 1;
|
||||
BOOL didReceiveMessageWithData : 1;
|
||||
BOOL didOpen : 1;
|
||||
BOOL didFailWithError : 1;
|
||||
BOOL didCloseWithCode : 1;
|
||||
BOOL didReceivePing : 1;
|
||||
BOOL didReceivePong : 1;
|
||||
BOOL shouldConvertTextFrameToString : 1;
|
||||
};
|
||||
|
||||
#else
|
||||
|
||||
struct SRDelegateAvailableMethods {
|
||||
BOOL didReceiveMessage;
|
||||
BOOL didReceiveMessageWithString;
|
||||
BOOL didReceiveMessageWithData;
|
||||
BOOL didOpen;
|
||||
BOOL didFailWithError;
|
||||
BOOL didCloseWithCode;
|
||||
BOOL didReceivePing;
|
||||
BOOL didReceivePong;
|
||||
BOOL shouldConvertTextFrameToString;
|
||||
};
|
||||
|
||||
#endif
|
||||
|
||||
typedef struct SRDelegateAvailableMethods SRDelegateAvailableMethods;
|
||||
|
||||
typedef void(^SRDelegateBlock)(id<SRWebSocketDelegate> _Nullable delegate, SRDelegateAvailableMethods availableMethods);
|
||||
|
||||
@interface SRDelegateController : NSObject
|
||||
|
||||
@property (nonatomic, weak) id<SRWebSocketDelegate> delegate;
|
||||
@property (atomic, readonly) SRDelegateAvailableMethods availableDelegateMethods;
|
||||
|
||||
@property (nullable, nonatomic, strong) dispatch_queue_t dispatchQueue;
|
||||
@property (nullable, nonatomic, strong) NSOperationQueue *operationQueue;
|
||||
|
||||
///--------------------------------------
|
||||
#pragma mark - Perform
|
||||
///--------------------------------------
|
||||
|
||||
- (void)performDelegateBlock:(SRDelegateBlock)block;
|
||||
- (void)performDelegateQueueBlock:(dispatch_block_t)block;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
@ -1,138 +0,0 @@
|
||||
//
|
||||
// Copyright (c) 2016-present, Facebook, Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the BSD-style license found in the
|
||||
// LICENSE file in the root directory of this source tree. An additional grant
|
||||
// of patent rights can be found in the PATENTS file in the same directory.
|
||||
//
|
||||
|
||||
#import "SRDelegateController.h"
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@interface SRDelegateController ()
|
||||
|
||||
@property (nonatomic, strong, readonly) dispatch_queue_t accessQueue;
|
||||
|
||||
@property (atomic, assign, readwrite) SRDelegateAvailableMethods availableDelegateMethods;
|
||||
|
||||
@end
|
||||
|
||||
@implementation SRDelegateController
|
||||
|
||||
@synthesize delegate = _delegate;
|
||||
@synthesize dispatchQueue = _dispatchQueue;
|
||||
@synthesize operationQueue = _operationQueue;
|
||||
|
||||
///--------------------------------------
|
||||
#pragma mark - Init
|
||||
///--------------------------------------
|
||||
|
||||
- (instancetype)init
|
||||
{
|
||||
self = [super init];
|
||||
if (!self) return self;
|
||||
|
||||
_accessQueue = dispatch_queue_create("com.facebook.socketrocket.delegate.access", DISPATCH_QUEUE_CONCURRENT);
|
||||
_dispatchQueue = dispatch_get_main_queue();
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
///--------------------------------------
|
||||
#pragma mark - Accessors
|
||||
///--------------------------------------
|
||||
|
||||
- (void)setDelegate:(id<SRWebSocketDelegate> _Nullable)delegate
|
||||
{
|
||||
dispatch_barrier_async(self.accessQueue, ^{
|
||||
_delegate = delegate;
|
||||
|
||||
self.availableDelegateMethods = (SRDelegateAvailableMethods){
|
||||
.didReceiveMessage = [delegate respondsToSelector:@selector(webSocket:didReceiveMessage:)],
|
||||
.didReceiveMessageWithString = [delegate respondsToSelector:@selector(webSocket:didReceiveMessageWithString:)],
|
||||
.didReceiveMessageWithData = [delegate respondsToSelector:@selector(webSocket:didReceiveMessageWithData:)],
|
||||
.didOpen = [delegate respondsToSelector:@selector(webSocketDidOpen:)],
|
||||
.didFailWithError = [delegate respondsToSelector:@selector(webSocket:didFailWithError:)],
|
||||
.didCloseWithCode = [delegate respondsToSelector:@selector(webSocket:didCloseWithCode:reason:wasClean:)],
|
||||
.didReceivePing = [delegate respondsToSelector:@selector(webSocket:didReceivePingWithData:)],
|
||||
.didReceivePong = [delegate respondsToSelector:@selector(webSocket:didReceivePong:)],
|
||||
.shouldConvertTextFrameToString = [delegate respondsToSelector:@selector(webSocketShouldConvertTextFrameToString:)]
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
- (id<SRWebSocketDelegate> _Nullable)delegate
|
||||
{
|
||||
__block id<SRWebSocketDelegate> delegate = nil;
|
||||
dispatch_sync(self.accessQueue, ^{
|
||||
delegate = _delegate;
|
||||
});
|
||||
return delegate;
|
||||
}
|
||||
|
||||
- (void)setDispatchQueue:(dispatch_queue_t _Nullable)queue
|
||||
{
|
||||
dispatch_barrier_async(self.accessQueue, ^{
|
||||
_dispatchQueue = queue ?: dispatch_get_main_queue();
|
||||
_operationQueue = nil;
|
||||
});
|
||||
}
|
||||
|
||||
- (dispatch_queue_t _Nullable)dispatchQueue
|
||||
{
|
||||
__block dispatch_queue_t queue = nil;
|
||||
dispatch_sync(self.accessQueue, ^{
|
||||
queue = _dispatchQueue;
|
||||
});
|
||||
return queue;
|
||||
}
|
||||
|
||||
- (void)setOperationQueue:(NSOperationQueue *_Nullable)queue
|
||||
{
|
||||
dispatch_barrier_async(self.accessQueue, ^{
|
||||
_dispatchQueue = queue ? nil : dispatch_get_main_queue();
|
||||
_operationQueue = queue;
|
||||
});
|
||||
}
|
||||
|
||||
- (NSOperationQueue *_Nullable)operationQueue
|
||||
{
|
||||
__block NSOperationQueue *queue = nil;
|
||||
dispatch_sync(self.accessQueue, ^{
|
||||
queue = _operationQueue;
|
||||
});
|
||||
return queue;
|
||||
}
|
||||
|
||||
///--------------------------------------
|
||||
#pragma mark - Perform
|
||||
///--------------------------------------
|
||||
|
||||
- (void)performDelegateBlock:(SRDelegateBlock)block
|
||||
{
|
||||
__block __strong id<SRWebSocketDelegate> delegate = nil;
|
||||
__block SRDelegateAvailableMethods availableMethods = {};
|
||||
dispatch_sync(self.accessQueue, ^{
|
||||
delegate = _delegate; // Not `OK` to go through `self`, since queue sync.
|
||||
availableMethods = self.availableDelegateMethods; // `OK` to call through `self`, since no queue sync.
|
||||
});
|
||||
[self performDelegateQueueBlock:^{
|
||||
block(delegate, availableMethods);
|
||||
}];
|
||||
}
|
||||
|
||||
- (void)performDelegateQueueBlock:(dispatch_block_t)block
|
||||
{
|
||||
dispatch_queue_t dispatchQueue = self.dispatchQueue;
|
||||
if (dispatchQueue) {
|
||||
dispatch_async(dispatchQueue, block);
|
||||
} else {
|
||||
[self.operationQueue addOperationWithBlock:block];
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
@ -1,40 +0,0 @@
|
||||
//
|
||||
// Copyright 2012 Square Inc.
|
||||
// Portions Copyright (c) 2016-present, Facebook, Inc.
|
||||
//
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the BSD-style license found in the
|
||||
// LICENSE file in the root directory of this source tree. An additional grant
|
||||
// of patent rights can be found in the PATENTS file in the same directory.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
@class SRWebSocket; // TODO: (nlutsenko) Remove dependency on SRWebSocket here.
|
||||
|
||||
// Returns number of bytes consumed. Returning 0 means you didn't match.
|
||||
// Sends bytes to callback handler;
|
||||
typedef size_t (^stream_scanner)(NSData *collected_data);
|
||||
typedef void (^data_callback)(SRWebSocket *webSocket, NSData *data);
|
||||
|
||||
@interface SRIOConsumer : NSObject {
|
||||
stream_scanner _scanner;
|
||||
data_callback _handler;
|
||||
size_t _bytesNeeded;
|
||||
BOOL _readToCurrentFrame;
|
||||
BOOL _unmaskBytes;
|
||||
}
|
||||
@property (nonatomic, copy, readonly) stream_scanner consumer;
|
||||
@property (nonatomic, copy, readonly) data_callback handler;
|
||||
@property (nonatomic, assign) size_t bytesNeeded;
|
||||
@property (nonatomic, assign, readonly) BOOL readToCurrentFrame;
|
||||
@property (nonatomic, assign, readonly) BOOL unmaskBytes;
|
||||
|
||||
- (void)resetWithScanner:(stream_scanner)scanner
|
||||
handler:(data_callback)handler
|
||||
bytesNeeded:(size_t)bytesNeeded
|
||||
readToCurrentFrame:(BOOL)readToCurrentFrame
|
||||
unmaskBytes:(BOOL)unmaskBytes;
|
||||
|
||||
@end
|
||||
@ -1,36 +0,0 @@
|
||||
//
|
||||
// Copyright 2012 Square Inc.
|
||||
// Portions Copyright (c) 2016-present, Facebook, Inc.
|
||||
//
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the BSD-style license found in the
|
||||
// LICENSE file in the root directory of this source tree. An additional grant
|
||||
// of patent rights can be found in the PATENTS file in the same directory.
|
||||
//
|
||||
|
||||
#import "SRIOConsumer.h"
|
||||
|
||||
@implementation SRIOConsumer
|
||||
|
||||
@synthesize bytesNeeded = _bytesNeeded;
|
||||
@synthesize consumer = _scanner;
|
||||
@synthesize handler = _handler;
|
||||
@synthesize readToCurrentFrame = _readToCurrentFrame;
|
||||
@synthesize unmaskBytes = _unmaskBytes;
|
||||
|
||||
- (void)resetWithScanner:(stream_scanner)scanner
|
||||
handler:(data_callback)handler
|
||||
bytesNeeded:(size_t)bytesNeeded
|
||||
readToCurrentFrame:(BOOL)readToCurrentFrame
|
||||
unmaskBytes:(BOOL)unmaskBytes
|
||||
{
|
||||
_scanner = [scanner copy];
|
||||
_handler = [handler copy];
|
||||
_bytesNeeded = bytesNeeded;
|
||||
_readToCurrentFrame = readToCurrentFrame;
|
||||
_unmaskBytes = unmaskBytes;
|
||||
assert(_scanner || _bytesNeeded);
|
||||
}
|
||||
|
||||
@end
|
||||
@ -1,28 +0,0 @@
|
||||
//
|
||||
// Copyright 2012 Square Inc.
|
||||
// Portions Copyright (c) 2016-present, Facebook, Inc.
|
||||
//
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the BSD-style license found in the
|
||||
// LICENSE file in the root directory of this source tree. An additional grant
|
||||
// of patent rights can be found in the PATENTS file in the same directory.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
#import "SRIOConsumer.h" // TODO: (nlutsenko) Convert to @class and constants file for block types
|
||||
|
||||
// This class is not thread-safe, and is expected to always be run on the same queue.
|
||||
@interface SRIOConsumerPool : NSObject
|
||||
|
||||
- (instancetype)initWithBufferCapacity:(NSUInteger)poolSize;
|
||||
|
||||
- (SRIOConsumer *)consumerWithScanner:(stream_scanner)scanner
|
||||
handler:(data_callback)handler
|
||||
bytesNeeded:(size_t)bytesNeeded
|
||||
readToCurrentFrame:(BOOL)readToCurrentFrame
|
||||
unmaskBytes:(BOOL)unmaskBytes;
|
||||
- (void)returnConsumer:(SRIOConsumer *)consumer;
|
||||
|
||||
@end
|
||||
@ -1,64 +0,0 @@
|
||||
//
|
||||
// Copyright 2012 Square Inc.
|
||||
// Portions Copyright (c) 2016-present, Facebook, Inc.
|
||||
//
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the BSD-style license found in the
|
||||
// LICENSE file in the root directory of this source tree. An additional grant
|
||||
// of patent rights can be found in the PATENTS file in the same directory.
|
||||
//
|
||||
|
||||
#import "SRIOConsumerPool.h"
|
||||
|
||||
@implementation SRIOConsumerPool {
|
||||
NSUInteger _poolSize;
|
||||
NSMutableArray<SRIOConsumer *> *_bufferedConsumers;
|
||||
}
|
||||
|
||||
- (instancetype)initWithBufferCapacity:(NSUInteger)poolSize;
|
||||
{
|
||||
self = [super init];
|
||||
if (self) {
|
||||
_poolSize = poolSize;
|
||||
_bufferedConsumers = [NSMutableArray arrayWithCapacity:poolSize];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (instancetype)init
|
||||
{
|
||||
return [self initWithBufferCapacity:8];
|
||||
}
|
||||
|
||||
- (SRIOConsumer *)consumerWithScanner:(stream_scanner)scanner
|
||||
handler:(data_callback)handler
|
||||
bytesNeeded:(size_t)bytesNeeded
|
||||
readToCurrentFrame:(BOOL)readToCurrentFrame
|
||||
unmaskBytes:(BOOL)unmaskBytes
|
||||
{
|
||||
SRIOConsumer *consumer = nil;
|
||||
if (_bufferedConsumers.count) {
|
||||
consumer = [_bufferedConsumers lastObject];
|
||||
[_bufferedConsumers removeLastObject];
|
||||
} else {
|
||||
consumer = [[SRIOConsumer alloc] init];
|
||||
}
|
||||
|
||||
[consumer resetWithScanner:scanner
|
||||
handler:handler
|
||||
bytesNeeded:bytesNeeded
|
||||
readToCurrentFrame:readToCurrentFrame
|
||||
unmaskBytes:unmaskBytes];
|
||||
|
||||
return consumer;
|
||||
}
|
||||
|
||||
- (void)returnConsumer:(SRIOConsumer *)consumer;
|
||||
{
|
||||
if (_bufferedConsumers.count < _poolSize) {
|
||||
[_bufferedConsumers addObject:consumer];
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
||||
@ -1,13 +0,0 @@
|
||||
//
|
||||
// Copyright (c) 2016-present, Facebook, Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the BSD-style license found in the
|
||||
// LICENSE file in the root directory of this source tree. An additional grant
|
||||
// of patent rights can be found in the PATENTS file in the same directory.
|
||||
//
|
||||
|
||||
#import <SocketRocket/NSRunLoop+SRWebSocket.h>
|
||||
|
||||
// Empty function that force links the object file for the category.
|
||||
extern void import_NSRunLoop_SRWebSocket(void);
|
||||
@ -1,13 +0,0 @@
|
||||
//
|
||||
// Copyright (c) 2016-present, Facebook, Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the BSD-style license found in the
|
||||
// LICENSE file in the root directory of this source tree. An additional grant
|
||||
// of patent rights can be found in the PATENTS file in the same directory.
|
||||
//
|
||||
|
||||
#import <SocketRocket/NSURLRequest+SRWebSocket.h>
|
||||
|
||||
// Empty function that force links the object file for the category.
|
||||
extern void import_NSURLRequest_SRWebSocket(void);
|
||||
@ -1,26 +0,0 @@
|
||||
//
|
||||
// Copyright (c) 2016-present, Facebook, Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the BSD-style license found in the
|
||||
// LICENSE file in the root directory of this source tree. An additional grant
|
||||
// of patent rights can be found in the PATENTS file in the same directory.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
typedef void(^SRProxyConnectCompletion)(NSError *_Nullable error,
|
||||
NSInputStream *_Nullable readStream,
|
||||
NSOutputStream *_Nullable writeStream);
|
||||
|
||||
@interface SRProxyConnect : NSObject
|
||||
|
||||
- (instancetype)initWithURL:(NSURL *)url;
|
||||
|
||||
- (void)openNetworkStreamWithCompletion:(SRProxyConnectCompletion)completion;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
@ -1,481 +0,0 @@
|
||||
//
|
||||
// Copyright (c) 2016-present, Facebook, Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the BSD-style license found in the
|
||||
// LICENSE file in the root directory of this source tree. An additional grant
|
||||
// of patent rights can be found in the PATENTS file in the same directory.
|
||||
//
|
||||
|
||||
#import "SRProxyConnect.h"
|
||||
|
||||
#import "NSRunLoop+SRWebSocket.h"
|
||||
#import "SRConstants.h"
|
||||
#import "SRError.h"
|
||||
#import "SRLog.h"
|
||||
#import "SRURLUtilities.h"
|
||||
|
||||
@interface SRProxyConnect() <NSStreamDelegate>
|
||||
|
||||
@property (nonatomic, strong) NSURL *url;
|
||||
@property (nonatomic, strong) NSInputStream *inputStream;
|
||||
@property (nonatomic, strong) NSOutputStream *outputStream;
|
||||
|
||||
@end
|
||||
|
||||
@implementation SRProxyConnect
|
||||
{
|
||||
SRProxyConnectCompletion _completion;
|
||||
|
||||
NSString *_httpProxyHost;
|
||||
uint32_t _httpProxyPort;
|
||||
|
||||
CFHTTPMessageRef _receivedHTTPHeaders;
|
||||
|
||||
NSString *_socksProxyHost;
|
||||
uint32_t _socksProxyPort;
|
||||
NSString *_socksProxyUsername;
|
||||
NSString *_socksProxyPassword;
|
||||
|
||||
BOOL _connectionRequiresSSL;
|
||||
|
||||
NSMutableArray<NSData *> *_inputQueue;
|
||||
dispatch_queue_t _writeQueue;
|
||||
}
|
||||
|
||||
///--------------------------------------
|
||||
#pragma mark - Init
|
||||
///--------------------------------------
|
||||
|
||||
-(instancetype)initWithURL:(NSURL *)url
|
||||
{
|
||||
self = [super init];
|
||||
if (!self) return self;
|
||||
|
||||
_url = url;
|
||||
_connectionRequiresSSL = SRURLRequiresSSL(url);
|
||||
|
||||
_writeQueue = dispatch_queue_create("com.facebook.socketrocket.proxyconnect.write", DISPATCH_QUEUE_SERIAL);
|
||||
_inputQueue = [NSMutableArray arrayWithCapacity:2];
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)dealloc
|
||||
{
|
||||
// If we get deallocated before the socket open finishes - we need to cleanup everything.
|
||||
|
||||
[self.inputStream removeFromRunLoop:[NSRunLoop SR_networkRunLoop] forMode:NSDefaultRunLoopMode];
|
||||
self.inputStream.delegate = nil;
|
||||
[self.inputStream close];
|
||||
self.inputStream = nil;
|
||||
|
||||
self.outputStream.delegate = nil;
|
||||
[self.outputStream close];
|
||||
self.outputStream = nil;
|
||||
}
|
||||
|
||||
///--------------------------------------
|
||||
#pragma mark - Open
|
||||
///--------------------------------------
|
||||
|
||||
- (void)openNetworkStreamWithCompletion:(SRProxyConnectCompletion)completion
|
||||
{
|
||||
_completion = completion;
|
||||
[self _configureProxy];
|
||||
}
|
||||
|
||||
///--------------------------------------
|
||||
#pragma mark - Flow
|
||||
///--------------------------------------
|
||||
|
||||
- (void)_didConnect
|
||||
{
|
||||
SRDebugLog(@"_didConnect, return streams");
|
||||
if (_connectionRequiresSSL) {
|
||||
if (_httpProxyHost) {
|
||||
// Must set the real peer name before turning on SSL
|
||||
SRDebugLog(@"proxy set peer name to real host %@", self.url.host);
|
||||
[self.outputStream setProperty:self.url.host forKey:@"_kCFStreamPropertySocketPeerName"];
|
||||
}
|
||||
}
|
||||
if (_receivedHTTPHeaders) {
|
||||
CFRelease(_receivedHTTPHeaders);
|
||||
_receivedHTTPHeaders = NULL;
|
||||
}
|
||||
|
||||
NSInputStream *inputStream = self.inputStream;
|
||||
NSOutputStream *outputStream = self.outputStream;
|
||||
|
||||
self.inputStream = nil;
|
||||
self.outputStream = nil;
|
||||
|
||||
[inputStream removeFromRunLoop:[NSRunLoop SR_networkRunLoop] forMode:NSDefaultRunLoopMode];
|
||||
inputStream.delegate = nil;
|
||||
outputStream.delegate = nil;
|
||||
|
||||
_completion(nil, inputStream, outputStream);
|
||||
}
|
||||
|
||||
- (void)_failWithError:(NSError *)error
|
||||
{
|
||||
SRDebugLog(@"_failWithError, return error");
|
||||
if (!error) {
|
||||
error = SRHTTPErrorWithCodeDescription(500, 2132,@"Proxy Error");
|
||||
}
|
||||
|
||||
if (_receivedHTTPHeaders) {
|
||||
CFRelease(_receivedHTTPHeaders);
|
||||
_receivedHTTPHeaders = NULL;
|
||||
}
|
||||
|
||||
self.inputStream.delegate = nil;
|
||||
self.outputStream.delegate = nil;
|
||||
|
||||
[self.inputStream removeFromRunLoop:[NSRunLoop SR_networkRunLoop]
|
||||
forMode:NSDefaultRunLoopMode];
|
||||
[self.inputStream close];
|
||||
[self.outputStream close];
|
||||
self.inputStream = nil;
|
||||
self.outputStream = nil;
|
||||
_completion(error, nil, nil);
|
||||
}
|
||||
|
||||
// get proxy setting from device setting
|
||||
- (void)_configureProxy
|
||||
{
|
||||
SRDebugLog(@"configureProxy");
|
||||
NSDictionary *proxySettings = CFBridgingRelease(CFNetworkCopySystemProxySettings());
|
||||
|
||||
// CFNetworkCopyProxiesForURL doesn't understand ws:// or wss://
|
||||
NSURL *httpURL;
|
||||
if (_connectionRequiresSSL) {
|
||||
httpURL = [NSURL URLWithString:[NSString stringWithFormat:@"https://%@", _url.host]];
|
||||
} else {
|
||||
httpURL = [NSURL URLWithString:[NSString stringWithFormat:@"http://%@", _url.host]];
|
||||
}
|
||||
|
||||
NSArray *proxies = CFBridgingRelease(CFNetworkCopyProxiesForURL((__bridge CFURLRef)httpURL, (__bridge CFDictionaryRef)proxySettings));
|
||||
if (proxies.count == 0) {
|
||||
SRDebugLog(@"configureProxy no proxies");
|
||||
[self _openConnection];
|
||||
return; // no proxy
|
||||
}
|
||||
NSDictionary *settings = [proxies objectAtIndex:0];
|
||||
NSString *proxyType = settings[(NSString *)kCFProxyTypeKey];
|
||||
if ([proxyType isEqualToString:(NSString *)kCFProxyTypeAutoConfigurationURL]) {
|
||||
NSURL *pacURL = settings[(NSString *)kCFProxyAutoConfigurationURLKey];
|
||||
if (pacURL) {
|
||||
[self _fetchPAC:pacURL withProxySettings:proxySettings];
|
||||
return;
|
||||
}
|
||||
}
|
||||
if ([proxyType isEqualToString:(__bridge NSString *)kCFProxyTypeAutoConfigurationJavaScript]) {
|
||||
NSString *script = settings[(__bridge NSString *)kCFProxyAutoConfigurationJavaScriptKey];
|
||||
if (script) {
|
||||
[self _runPACScript:script withProxySettings:proxySettings];
|
||||
return;
|
||||
}
|
||||
}
|
||||
[self _readProxySettingWithType:proxyType settings:settings];
|
||||
|
||||
[self _openConnection];
|
||||
}
|
||||
|
||||
- (void)_readProxySettingWithType:(NSString *)proxyType settings:(NSDictionary *)settings
|
||||
{
|
||||
if ([proxyType isEqualToString:(NSString *)kCFProxyTypeHTTP] ||
|
||||
[proxyType isEqualToString:(NSString *)kCFProxyTypeHTTPS]) {
|
||||
_httpProxyHost = settings[(NSString *)kCFProxyHostNameKey];
|
||||
NSNumber *portValue = settings[(NSString *)kCFProxyPortNumberKey];
|
||||
if (portValue) {
|
||||
_httpProxyPort = [portValue intValue];
|
||||
}
|
||||
}
|
||||
if ([proxyType isEqualToString:(NSString *)kCFProxyTypeSOCKS]) {
|
||||
_socksProxyHost = settings[(NSString *)kCFProxyHostNameKey];
|
||||
NSNumber *portValue = settings[(NSString *)kCFProxyPortNumberKey];
|
||||
if (portValue)
|
||||
_socksProxyPort = [portValue intValue];
|
||||
_socksProxyUsername = settings[(NSString *)kCFProxyUsernameKey];
|
||||
_socksProxyPassword = settings[(NSString *)kCFProxyPasswordKey];
|
||||
}
|
||||
if (_httpProxyHost) {
|
||||
SRDebugLog(@"Using http proxy %@:%u", _httpProxyHost, _httpProxyPort);
|
||||
} else if (_socksProxyHost) {
|
||||
SRDebugLog(@"Using socks proxy %@:%u", _socksProxyHost, _socksProxyPort);
|
||||
} else {
|
||||
SRDebugLog(@"configureProxy no proxies");
|
||||
}
|
||||
}
|
||||
|
||||
- (void)_fetchPAC:(NSURL *)PACurl withProxySettings:(NSDictionary *)proxySettings
|
||||
{
|
||||
SRDebugLog(@"SRWebSocket fetchPAC:%@", PACurl);
|
||||
|
||||
if ([PACurl isFileURL]) {
|
||||
NSError *error = nil;
|
||||
NSString *script = [NSString stringWithContentsOfURL:PACurl
|
||||
usedEncoding:NULL
|
||||
error:&error];
|
||||
|
||||
if (error) {
|
||||
[self _openConnection];
|
||||
} else {
|
||||
[self _runPACScript:script withProxySettings:proxySettings];
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
NSString *scheme = [PACurl.scheme lowercaseString];
|
||||
if (![scheme isEqualToString:@"http"] && ![scheme isEqualToString:@"https"]) {
|
||||
// Don't know how to read data from this URL, we'll have to give up
|
||||
// We'll simply assume no proxies, and start the request as normal
|
||||
[self _openConnection];
|
||||
return;
|
||||
}
|
||||
__weak typeof(self) wself = self;
|
||||
NSURLRequest *request = [NSURLRequest requestWithURL:PACurl];
|
||||
NSURLSession *session = [NSURLSession sharedSession];
|
||||
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
|
||||
__strong typeof(wself) sself = wself;
|
||||
if (!error) {
|
||||
NSString *script = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
|
||||
[sself _runPACScript:script withProxySettings:proxySettings];
|
||||
} else {
|
||||
[sself _openConnection];
|
||||
}
|
||||
}] resume];
|
||||
}
|
||||
|
||||
- (void)_runPACScript:(NSString *)script withProxySettings:(NSDictionary *)proxySettings
|
||||
{
|
||||
if (!script) {
|
||||
[self _openConnection];
|
||||
return;
|
||||
}
|
||||
SRDebugLog(@"runPACScript");
|
||||
// From: http://developer.apple.com/samplecode/CFProxySupportTool/listing1.html
|
||||
// Work around <rdar://problem/5530166>. This dummy call to
|
||||
// CFNetworkCopyProxiesForURL initialise some state within CFNetwork
|
||||
// that is required by CFNetworkCopyProxiesForAutoConfigurationScript.
|
||||
CFBridgingRelease(CFNetworkCopyProxiesForURL((__bridge CFURLRef)_url, (__bridge CFDictionaryRef)proxySettings));
|
||||
|
||||
// Obtain the list of proxies by running the autoconfiguration script
|
||||
CFErrorRef err = NULL;
|
||||
|
||||
// CFNetworkCopyProxiesForAutoConfigurationScript doesn't understand ws:// or wss://
|
||||
NSURL *httpURL;
|
||||
if (_connectionRequiresSSL)
|
||||
httpURL = [NSURL URLWithString:[NSString stringWithFormat:@"https://%@", _url.host]];
|
||||
else
|
||||
httpURL = [NSURL URLWithString:[NSString stringWithFormat:@"http://%@", _url.host]];
|
||||
|
||||
NSArray *proxies = CFBridgingRelease(CFNetworkCopyProxiesForAutoConfigurationScript((__bridge CFStringRef)script,(__bridge CFURLRef)httpURL, &err));
|
||||
if (!err && [proxies count] > 0) {
|
||||
NSDictionary *settings = [proxies objectAtIndex:0];
|
||||
NSString *proxyType = settings[(NSString *)kCFProxyTypeKey];
|
||||
[self _readProxySettingWithType:proxyType settings:settings];
|
||||
}
|
||||
[self _openConnection];
|
||||
}
|
||||
|
||||
- (void)_openConnection
|
||||
{
|
||||
[self _initializeStreams];
|
||||
|
||||
[self.inputStream scheduleInRunLoop:[NSRunLoop SR_networkRunLoop]
|
||||
forMode:NSDefaultRunLoopMode];
|
||||
//[self.outputStream scheduleInRunLoop:[NSRunLoop SR_networkRunLoop]
|
||||
// forMode:NSDefaultRunLoopMode];
|
||||
[self.outputStream open];
|
||||
[self.inputStream open];
|
||||
}
|
||||
|
||||
- (void)_initializeStreams
|
||||
{
|
||||
assert(_url.port.unsignedIntValue <= UINT32_MAX);
|
||||
uint32_t port = _url.port.unsignedIntValue;
|
||||
if (port == 0) {
|
||||
port = (_connectionRequiresSSL ? 443 : 80);
|
||||
}
|
||||
NSString *host = _url.host;
|
||||
|
||||
if (_httpProxyHost) {
|
||||
host = _httpProxyHost;
|
||||
port = (_httpProxyPort ?: 80);
|
||||
}
|
||||
|
||||
CFReadStreamRef readStream = NULL;
|
||||
CFWriteStreamRef writeStream = NULL;
|
||||
|
||||
SRDebugLog(@"ProxyConnect connect stream to %@:%u", host, port);
|
||||
CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)host, port, &readStream, &writeStream);
|
||||
|
||||
self.outputStream = CFBridgingRelease(writeStream);
|
||||
self.inputStream = CFBridgingRelease(readStream);
|
||||
|
||||
if (_socksProxyHost) {
|
||||
SRDebugLog(@"ProxyConnect set sock property stream to %@:%u user %@ password %@", _socksProxyHost, _socksProxyPort, _socksProxyUsername, _socksProxyPassword);
|
||||
NSMutableDictionary *settings = [NSMutableDictionary dictionaryWithCapacity:4];
|
||||
settings[NSStreamSOCKSProxyHostKey] = _socksProxyHost;
|
||||
if (_socksProxyPort) {
|
||||
settings[NSStreamSOCKSProxyPortKey] = @(_socksProxyPort);
|
||||
}
|
||||
if (_socksProxyUsername) {
|
||||
settings[NSStreamSOCKSProxyUserKey] = _socksProxyUsername;
|
||||
}
|
||||
if (_socksProxyPassword) {
|
||||
settings[NSStreamSOCKSProxyPasswordKey] = _socksProxyPassword;
|
||||
}
|
||||
[self.inputStream setProperty:settings forKey:NSStreamSOCKSProxyConfigurationKey];
|
||||
[self.outputStream setProperty:settings forKey:NSStreamSOCKSProxyConfigurationKey];
|
||||
}
|
||||
self.inputStream.delegate = self;
|
||||
self.outputStream.delegate = self;
|
||||
}
|
||||
|
||||
- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode;
|
||||
{
|
||||
SRDebugLog(@"stream handleEvent %u", eventCode);
|
||||
switch (eventCode) {
|
||||
case NSStreamEventOpenCompleted: {
|
||||
if (aStream == self.inputStream) {
|
||||
if (_httpProxyHost) {
|
||||
[self _proxyDidConnect];
|
||||
} else {
|
||||
[self _didConnect];
|
||||
}
|
||||
}
|
||||
} break;
|
||||
case NSStreamEventErrorOccurred: {
|
||||
[self _failWithError:aStream.streamError];
|
||||
} break;
|
||||
case NSStreamEventEndEncountered: {
|
||||
[self _failWithError:aStream.streamError];
|
||||
} break;
|
||||
case NSStreamEventHasBytesAvailable: {
|
||||
if (aStream == _inputStream) {
|
||||
[self _processInputStream];
|
||||
}
|
||||
} break;
|
||||
case NSStreamEventHasSpaceAvailable:
|
||||
case NSStreamEventNone:
|
||||
SRDebugLog(@"(default) %@", aStream);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
- (void)_proxyDidConnect
|
||||
{
|
||||
SRDebugLog(@"Proxy Connected");
|
||||
uint32_t port = _url.port.unsignedIntValue;
|
||||
if (port == 0) {
|
||||
port = (_connectionRequiresSSL ? 443 : 80);
|
||||
}
|
||||
// Send HTTP CONNECT Request
|
||||
NSString *connectRequestStr = [NSString stringWithFormat:@"CONNECT %@:%u HTTP/1.1\r\nHost: %@\r\nConnection: keep-alive\r\nProxy-Connection: keep-alive\r\n\r\n", _url.host, port, _url.host];
|
||||
|
||||
NSData *message = [connectRequestStr dataUsingEncoding:NSUTF8StringEncoding];
|
||||
SRDebugLog(@"Proxy sending %@", connectRequestStr);
|
||||
|
||||
[self _writeData:message];
|
||||
}
|
||||
|
||||
///handles the incoming bytes and sending them to the proper processing method
|
||||
- (void)_processInputStream
|
||||
{
|
||||
NSMutableData *buf = [NSMutableData dataWithCapacity:SRDefaultBufferSize()];
|
||||
uint8_t *buffer = buf.mutableBytes;
|
||||
NSInteger length = [_inputStream read:buffer maxLength:SRDefaultBufferSize()];
|
||||
|
||||
if (length <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
BOOL process = (_inputQueue.count == 0);
|
||||
[_inputQueue addObject:[NSData dataWithBytes:buffer length:length]];
|
||||
|
||||
if (process) {
|
||||
[self _dequeueInput];
|
||||
}
|
||||
}
|
||||
|
||||
// dequeue the incoming input so it is processed in order
|
||||
|
||||
- (void)_dequeueInput
|
||||
{
|
||||
while (_inputQueue.count > 0) {
|
||||
NSData *data = _inputQueue.firstObject;
|
||||
[_inputQueue removeObjectAtIndex:0];
|
||||
|
||||
// No need to process any data further, we got the full header data.
|
||||
if ([self _proxyProcessHTTPResponseWithData:data]) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
//handle checking the proxy connection status
|
||||
- (BOOL)_proxyProcessHTTPResponseWithData:(NSData *)data
|
||||
{
|
||||
if (_receivedHTTPHeaders == NULL) {
|
||||
_receivedHTTPHeaders = CFHTTPMessageCreateEmpty(NULL, NO);
|
||||
}
|
||||
|
||||
CFHTTPMessageAppendBytes(_receivedHTTPHeaders, (const UInt8 *)data.bytes, data.length);
|
||||
if (CFHTTPMessageIsHeaderComplete(_receivedHTTPHeaders)) {
|
||||
SRDebugLog(@"Finished reading headers %@", CFBridgingRelease(CFHTTPMessageCopyAllHeaderFields(_receivedHTTPHeaders)));
|
||||
[self _proxyHTTPHeadersDidFinish];
|
||||
return YES;
|
||||
}
|
||||
|
||||
return NO;
|
||||
}
|
||||
|
||||
- (void)_proxyHTTPHeadersDidFinish
|
||||
{
|
||||
NSInteger responseCode = CFHTTPMessageGetResponseStatusCode(_receivedHTTPHeaders);
|
||||
|
||||
if (responseCode >= 299) {
|
||||
SRDebugLog(@"Connect to Proxy Request failed with response code %d", responseCode);
|
||||
NSError *error = SRHTTPErrorWithCodeDescription(responseCode, 2132,
|
||||
[NSString stringWithFormat:@"Received bad response code from proxy server: %d.",
|
||||
(int)responseCode]);
|
||||
[self _failWithError:error];
|
||||
return;
|
||||
}
|
||||
SRDebugLog(@"proxy connect return %d, call socket connect", responseCode);
|
||||
[self _didConnect];
|
||||
}
|
||||
|
||||
static NSTimeInterval const SRProxyConnectWriteTimeout = 5.0;
|
||||
|
||||
- (void)_writeData:(NSData *)data
|
||||
{
|
||||
const uint8_t * bytes = data.bytes;
|
||||
__block NSInteger timeout = (NSInteger)(SRProxyConnectWriteTimeout * 1000000); // wait timeout before giving up
|
||||
__weak typeof(self) wself = self;
|
||||
dispatch_async(_writeQueue, ^{
|
||||
__strong typeof(wself) sself = self;
|
||||
if (!sself) {
|
||||
return;
|
||||
}
|
||||
NSOutputStream *outStream = sself.outputStream;
|
||||
if (!outStream) {
|
||||
return;
|
||||
}
|
||||
while (![outStream hasSpaceAvailable]) {
|
||||
usleep(100); //wait until the socket is ready
|
||||
timeout -= 100;
|
||||
if (timeout < 0) {
|
||||
NSError *error = SRHTTPErrorWithCodeDescription(408, 2132, @"Proxy timeout");
|
||||
[sself _failWithError:error];
|
||||
} else if (outStream.streamError != nil) {
|
||||
[sself _failWithError:outStream.streamError];
|
||||
}
|
||||
}
|
||||
[outStream write:bytes maxLength:data.length];
|
||||
});
|
||||
}
|
||||
|
||||
@end
|
||||
@ -1,24 +0,0 @@
|
||||
//
|
||||
// Copyright 2012 Square Inc.
|
||||
// Portions Copyright (c) 2016-present, Facebook, Inc.
|
||||
//
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the BSD-style license found in the
|
||||
// LICENSE file in the root directory of this source tree. An additional grant
|
||||
// of patent rights can be found in the PATENTS file in the same directory.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@interface SRRunLoopThread : NSThread
|
||||
|
||||
@property (nonatomic, strong, readonly) NSRunLoop *runLoop;
|
||||
|
||||
+ (instancetype)sharedThread;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
@ -1,83 +0,0 @@
|
||||
//
|
||||
// Copyright 2012 Square Inc.
|
||||
// Portions Copyright (c) 2016-present, Facebook, Inc.
|
||||
//
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the BSD-style license found in the
|
||||
// LICENSE file in the root directory of this source tree. An additional grant
|
||||
// of patent rights can be found in the PATENTS file in the same directory.
|
||||
//
|
||||
|
||||
#import "SRRunLoopThread.h"
|
||||
|
||||
@interface SRRunLoopThread ()
|
||||
{
|
||||
dispatch_group_t _waitGroup;
|
||||
}
|
||||
|
||||
@property (nonatomic, strong, readwrite) NSRunLoop *runLoop;
|
||||
|
||||
@end
|
||||
|
||||
@implementation SRRunLoopThread
|
||||
|
||||
+ (instancetype)sharedThread
|
||||
{
|
||||
static SRRunLoopThread *thread;
|
||||
static dispatch_once_t onceToken;
|
||||
dispatch_once(&onceToken, ^{
|
||||
thread = [[SRRunLoopThread alloc] init];
|
||||
thread.name = @"com.facebook.SocketRocket.NetworkThread";
|
||||
[thread start];
|
||||
});
|
||||
return thread;
|
||||
}
|
||||
|
||||
- (instancetype)init
|
||||
{
|
||||
self = [super init];
|
||||
if (self) {
|
||||
_waitGroup = dispatch_group_create();
|
||||
dispatch_group_enter(_waitGroup);
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)main
|
||||
{
|
||||
@autoreleasepool {
|
||||
_runLoop = [NSRunLoop currentRunLoop];
|
||||
dispatch_group_leave(_waitGroup);
|
||||
|
||||
// Add an empty run loop source to prevent runloop from spinning.
|
||||
CFRunLoopSourceContext sourceCtx = {
|
||||
.version = 0,
|
||||
.info = NULL,
|
||||
.retain = NULL,
|
||||
.release = NULL,
|
||||
.copyDescription = NULL,
|
||||
.equal = NULL,
|
||||
.hash = NULL,
|
||||
.schedule = NULL,
|
||||
.cancel = NULL,
|
||||
.perform = NULL
|
||||
};
|
||||
CFRunLoopSourceRef source = CFRunLoopSourceCreate(NULL, 0, &sourceCtx);
|
||||
CFRunLoopAddSource(CFRunLoopGetCurrent(), source, kCFRunLoopDefaultMode);
|
||||
CFRelease(source);
|
||||
|
||||
while ([_runLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]) {
|
||||
|
||||
}
|
||||
assert(NO);
|
||||
}
|
||||
}
|
||||
|
||||
- (NSRunLoop *)runLoop;
|
||||
{
|
||||
dispatch_group_wait(_waitGroup, DISPATCH_TIME_FOREVER);
|
||||
return _runLoop;
|
||||
}
|
||||
|
||||
@end
|
||||
@ -1,26 +0,0 @@
|
||||
//
|
||||
// Copyright (c) 2016-present, Facebook, Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the BSD-style license found in the
|
||||
// LICENSE file in the root directory of this source tree. An additional grant
|
||||
// of patent rights can be found in the PATENTS file in the same directory.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
typedef NS_ENUM(NSInteger, SROpCode)
|
||||
{
|
||||
SROpCodeTextFrame = 0x1,
|
||||
SROpCodeBinaryFrame = 0x2,
|
||||
// 3-7 reserved.
|
||||
SROpCodeConnectionClose = 0x8,
|
||||
SROpCodePing = 0x9,
|
||||
SROpCodePong = 0xA,
|
||||
// B-F reserved.
|
||||
};
|
||||
|
||||
/**
|
||||
Default buffer size that is used for reading/writing to streams.
|
||||
*/
|
||||
extern size_t SRDefaultBufferSize(void);
|
||||
@ -1,19 +0,0 @@
|
||||
//
|
||||
// Copyright (c) 2016-present, Facebook, Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the BSD-style license found in the
|
||||
// LICENSE file in the root directory of this source tree. An additional grant
|
||||
// of patent rights can be found in the PATENTS file in the same directory.
|
||||
//
|
||||
|
||||
#import "SRConstants.h"
|
||||
|
||||
size_t SRDefaultBufferSize(void) {
|
||||
static size_t size;
|
||||
static dispatch_once_t onceToken;
|
||||
dispatch_once(&onceToken, ^{
|
||||
size = getpagesize();
|
||||
});
|
||||
return size;
|
||||
}
|
||||
@ -1,27 +0,0 @@
|
||||
//
|
||||
// Copyright (c) 2016-present, Facebook, Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the BSD-style license found in the
|
||||
// LICENSE file in the root directory of this source tree. An additional grant
|
||||
// of patent rights can be found in the PATENTS file in the same directory.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
#import <SocketRocket/SRSecurityPolicy.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
/**
|
||||
* NOTE: While publicly, SocketRocket does not support configuring the security policy with pinned certificates,
|
||||
* it is still possible to manually construct a security policy of this class. If you do this, note that you may
|
||||
* be open to MitM attacks, and we will not support any issues you may have. Dive at your own risk.
|
||||
*/
|
||||
@interface SRPinningSecurityPolicy : SRSecurityPolicy
|
||||
|
||||
- (instancetype)initWithCertificates:(NSArray *)pinnedCertificates;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
@ -1,73 +0,0 @@
|
||||
//
|
||||
// Copyright (c) 2016-present, Facebook, Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the BSD-style license found in the
|
||||
// LICENSE file in the root directory of this source tree. An additional grant
|
||||
// of patent rights can be found in the PATENTS file in the same directory.
|
||||
//
|
||||
|
||||
#import "SRPinningSecurityPolicy.h"
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
#import "SRLog.h"
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@interface SRPinningSecurityPolicy ()
|
||||
|
||||
@property (nonatomic, copy, readonly) NSArray *pinnedCertificates;
|
||||
|
||||
@end
|
||||
|
||||
@implementation SRPinningSecurityPolicy
|
||||
|
||||
- (instancetype)initWithCertificates:(NSArray *)pinnedCertificates
|
||||
{
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wdeprecated"
|
||||
|
||||
// Do not validate certificate chain since we're pinning to specific certificates.
|
||||
self = [super initWithCertificateChainValidationEnabled:NO];
|
||||
|
||||
#pragma clang diagnostic pop
|
||||
|
||||
if (!self) { return self; }
|
||||
|
||||
if (pinnedCertificates.count == 0) {
|
||||
@throw [NSException exceptionWithName:@"Creating security policy failed."
|
||||
reason:@"Must specify at least one certificate when creating a pinning policy."
|
||||
userInfo:nil];
|
||||
}
|
||||
_pinnedCertificates = [pinnedCertificates copy];
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust forDomain:(NSString *)domain
|
||||
{
|
||||
SRDebugLog(@"Pinned cert count: %d", self.pinnedCertificates.count);
|
||||
NSUInteger requiredCertCount = self.pinnedCertificates.count;
|
||||
|
||||
NSUInteger validatedCertCount = 0;
|
||||
CFIndex serverCertCount = SecTrustGetCertificateCount(serverTrust);
|
||||
for (CFIndex i = 0; i < serverCertCount; i++) {
|
||||
SecCertificateRef cert = SecTrustGetCertificateAtIndex(serverTrust, i);
|
||||
NSData *data = CFBridgingRelease(SecCertificateCopyData(cert));
|
||||
for (id ref in self.pinnedCertificates) {
|
||||
SecCertificateRef trustedCert = (__bridge SecCertificateRef)ref;
|
||||
// TODO: (nlutsenko) Add caching, so we don't copy the data for every pinned cert all the time.
|
||||
NSData *trustedCertData = CFBridgingRelease(SecCertificateCopyData(trustedCert));
|
||||
if ([trustedCertData isEqualToData:data]) {
|
||||
validatedCertCount++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return (requiredCertCount == validatedCertCount);
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
@ -1,20 +0,0 @@
|
||||
//
|
||||
// Copyright (c) 2016-present, Facebook, Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the BSD-style license found in the
|
||||
// LICENSE file in the root directory of this source tree. An additional grant
|
||||
// of patent rights can be found in the PATENTS file in the same directory.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
extern NSError *SRErrorWithDomainCodeDescription(NSString *domain, NSInteger code, NSString *description);
|
||||
extern NSError *SRErrorWithCodeDescription(NSInteger code, NSString *description);
|
||||
extern NSError *SRErrorWithCodeDescriptionUnderlyingError(NSInteger code, NSString *description, NSError *underlyingError);
|
||||
|
||||
extern NSError *SRHTTPErrorWithCodeDescription(NSInteger httpCode, NSInteger errorCode, NSString *description);
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
@ -1,42 +0,0 @@
|
||||
//
|
||||
// Copyright (c) 2016-present, Facebook, Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the BSD-style license found in the
|
||||
// LICENSE file in the root directory of this source tree. An additional grant
|
||||
// of patent rights can be found in the PATENTS file in the same directory.
|
||||
//
|
||||
|
||||
#import "SRError.h"
|
||||
|
||||
#import "SRWebSocket.h"
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
NSError *SRErrorWithDomainCodeDescription(NSString *domain, NSInteger code, NSString *description)
|
||||
{
|
||||
return [NSError errorWithDomain:domain code:code userInfo:@{ NSLocalizedDescriptionKey: description }];
|
||||
}
|
||||
|
||||
NSError *SRErrorWithCodeDescription(NSInteger code, NSString *description)
|
||||
{
|
||||
return SRErrorWithDomainCodeDescription(SRWebSocketErrorDomain, code, description);
|
||||
}
|
||||
|
||||
NSError *SRErrorWithCodeDescriptionUnderlyingError(NSInteger code, NSString *description, NSError *underlyingError)
|
||||
{
|
||||
return [NSError errorWithDomain:SRWebSocketErrorDomain
|
||||
code:code
|
||||
userInfo:@{ NSLocalizedDescriptionKey: description,
|
||||
NSUnderlyingErrorKey: underlyingError }];
|
||||
}
|
||||
|
||||
NSError *SRHTTPErrorWithCodeDescription(NSInteger httpCode, NSInteger errorCode, NSString *description)
|
||||
{
|
||||
return [NSError errorWithDomain:SRWebSocketErrorDomain
|
||||
code:errorCode
|
||||
userInfo:@{ NSLocalizedDescriptionKey: description,
|
||||
SRHTTPResponseErrorKey: @(httpCode) }];
|
||||
}
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
@ -1,20 +0,0 @@
|
||||
//
|
||||
// Copyright (c) 2016-present, Facebook, Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the BSD-style license found in the
|
||||
// LICENSE file in the root directory of this source tree. An additional grant
|
||||
// of patent rights can be found in the PATENTS file in the same directory.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
extern CFHTTPMessageRef SRHTTPConnectMessageCreate(NSURLRequest *request,
|
||||
NSString *securityKey,
|
||||
uint8_t webSocketProtocolVersion,
|
||||
NSArray<NSHTTPCookie *> *_Nullable cookies,
|
||||
NSArray<NSString *> *_Nullable requestedProtocols);
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
@ -1,79 +0,0 @@
|
||||
//
|
||||
// Copyright (c) 2016-present, Facebook, Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the BSD-style license found in the
|
||||
// LICENSE file in the root directory of this source tree. An additional grant
|
||||
// of patent rights can be found in the PATENTS file in the same directory.
|
||||
//
|
||||
|
||||
#import "SRHTTPConnectMessage.h"
|
||||
|
||||
#import "SRURLUtilities.h"
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
static NSString *_SRHTTPConnectMessageHost(NSURL *url)
|
||||
{
|
||||
NSString *host = url.host;
|
||||
if (url.port) {
|
||||
host = [host stringByAppendingFormat:@":%@", url.port];
|
||||
}
|
||||
return host;
|
||||
}
|
||||
|
||||
CFHTTPMessageRef SRHTTPConnectMessageCreate(NSURLRequest *request,
|
||||
NSString *securityKey,
|
||||
uint8_t webSocketProtocolVersion,
|
||||
NSArray<NSHTTPCookie *> *_Nullable cookies,
|
||||
NSArray<NSString *> *_Nullable requestedProtocols)
|
||||
{
|
||||
NSURL *url = request.URL;
|
||||
|
||||
CFHTTPMessageRef message = CFHTTPMessageCreateRequest(NULL, CFSTR("GET"), (__bridge CFURLRef)url, kCFHTTPVersion1_1);
|
||||
|
||||
// Set host first so it defaults
|
||||
CFHTTPMessageSetHeaderFieldValue(message, CFSTR("Host"), (__bridge CFStringRef)_SRHTTPConnectMessageHost(url));
|
||||
|
||||
NSMutableData *keyBytes = [[NSMutableData alloc] initWithLength:16];
|
||||
int result = SecRandomCopyBytes(kSecRandomDefault, keyBytes.length, keyBytes.mutableBytes);
|
||||
if (result != 0) {
|
||||
//TODO: (nlutsenko) Check if there was an error.
|
||||
}
|
||||
|
||||
// Apply cookies if any have been provided
|
||||
if (cookies) {
|
||||
NSDictionary<NSString *, NSString *> *messageCookies = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
|
||||
[messageCookies enumerateKeysAndObjectsUsingBlock:^(NSString * _Nonnull key, NSString * _Nonnull obj, BOOL * _Nonnull stop) {
|
||||
if (key.length && obj.length) {
|
||||
CFHTTPMessageSetHeaderFieldValue(message, (__bridge CFStringRef)key, (__bridge CFStringRef)obj);
|
||||
}
|
||||
}];
|
||||
}
|
||||
|
||||
// set header for http basic auth
|
||||
NSString *basicAuthorizationString = SRBasicAuthorizationHeaderFromURL(url);
|
||||
if (basicAuthorizationString) {
|
||||
CFHTTPMessageSetHeaderFieldValue(message, CFSTR("Authorization"), (__bridge CFStringRef)basicAuthorizationString);
|
||||
}
|
||||
|
||||
CFHTTPMessageSetHeaderFieldValue(message, CFSTR("Upgrade"), CFSTR("websocket"));
|
||||
CFHTTPMessageSetHeaderFieldValue(message, CFSTR("Connection"), CFSTR("Upgrade"));
|
||||
CFHTTPMessageSetHeaderFieldValue(message, CFSTR("Sec-WebSocket-Key"), (__bridge CFStringRef)securityKey);
|
||||
CFHTTPMessageSetHeaderFieldValue(message, CFSTR("Sec-WebSocket-Version"), (__bridge CFStringRef)@(webSocketProtocolVersion).stringValue);
|
||||
|
||||
CFHTTPMessageSetHeaderFieldValue(message, CFSTR("Origin"), (__bridge CFStringRef)SRURLOrigin(url));
|
||||
|
||||
if (requestedProtocols.count) {
|
||||
CFHTTPMessageSetHeaderFieldValue(message, CFSTR("Sec-WebSocket-Protocol"),
|
||||
(__bridge CFStringRef)[requestedProtocols componentsJoinedByString:@", "]);
|
||||
}
|
||||
|
||||
[request.allHTTPHeaderFields enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
|
||||
CFHTTPMessageSetHeaderFieldValue(message, (__bridge CFStringRef)key, (__bridge CFStringRef)obj);
|
||||
}];
|
||||
|
||||
return message;
|
||||
}
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
@ -1,19 +0,0 @@
|
||||
//
|
||||
// Copyright (c) 2016-present, Facebook, Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the BSD-style license found in the
|
||||
// LICENSE file in the root directory of this source tree. An additional grant
|
||||
// of patent rights can be found in the PATENTS file in the same directory.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
extern NSData *SRSHA1HashFromString(NSString *string);
|
||||
extern NSData *SRSHA1HashFromBytes(const char *bytes, size_t length);
|
||||
|
||||
extern NSString *SRBase64EncodedStringFromData(NSData *data);
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
@ -1,43 +0,0 @@
|
||||
//
|
||||
// Copyright (c) 2016-present, Facebook, Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the BSD-style license found in the
|
||||
// LICENSE file in the root directory of this source tree. An additional grant
|
||||
// of patent rights can be found in the PATENTS file in the same directory.
|
||||
//
|
||||
|
||||
#import "SRHash.h"
|
||||
|
||||
#import <CommonCrypto/CommonDigest.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
NSData *SRSHA1HashFromString(NSString *string)
|
||||
{
|
||||
size_t length = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
|
||||
return SRSHA1HashFromBytes(string.UTF8String, length);
|
||||
}
|
||||
|
||||
NSData *SRSHA1HashFromBytes(const char *bytes, size_t length)
|
||||
{
|
||||
uint8_t outputLength = CC_SHA1_DIGEST_LENGTH;
|
||||
unsigned char output[outputLength];
|
||||
CC_SHA1(bytes, (CC_LONG)length, output);
|
||||
|
||||
return [NSData dataWithBytes:output length:outputLength];
|
||||
}
|
||||
|
||||
NSString *SRBase64EncodedStringFromData(NSData *data)
|
||||
{
|
||||
if ([data respondsToSelector:@selector(base64EncodedStringWithOptions:)]) {
|
||||
return [data base64EncodedStringWithOptions:0];
|
||||
}
|
||||
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
|
||||
return [data base64Encoding];
|
||||
#pragma clang diagnostic pop
|
||||
}
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
@ -1,20 +0,0 @@
|
||||
//
|
||||
// Copyright (c) 2016-present, Facebook, Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the BSD-style license found in the
|
||||
// LICENSE file in the root directory of this source tree. An additional grant
|
||||
// of patent rights can be found in the PATENTS file in the same directory.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
// Uncomment this line to enable debug logging
|
||||
//#define SR_DEBUG_LOG_ENABLED
|
||||
|
||||
extern void SRErrorLog(NSString *format, ...);
|
||||
extern void SRDebugLog(NSString *format, ...);
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
@ -1,33 +0,0 @@
|
||||
//
|
||||
// Copyright (c) 2016-present, Facebook, Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the BSD-style license found in the
|
||||
// LICENSE file in the root directory of this source tree. An additional grant
|
||||
// of patent rights can be found in the PATENTS file in the same directory.
|
||||
//
|
||||
|
||||
#import "SRLog.h"
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
extern void SRErrorLog(NSString *format, ...)
|
||||
{
|
||||
__block va_list arg_list;
|
||||
va_start (arg_list, format);
|
||||
|
||||
NSString *formattedString = [[NSString alloc] initWithFormat:format arguments:arg_list];
|
||||
|
||||
va_end(arg_list);
|
||||
|
||||
NSLog(@"[SocketRocket] %@", formattedString);
|
||||
}
|
||||
|
||||
extern void SRDebugLog(NSString *format, ...)
|
||||
{
|
||||
#ifdef SR_DEBUG_LOG_ENABLED
|
||||
SRErrorLog(tag, format);
|
||||
#endif
|
||||
}
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
@ -1,22 +0,0 @@
|
||||
//
|
||||
// Copyright (c) 2016-present, Facebook, Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the BSD-style license found in the
|
||||
// LICENSE file in the root directory of this source tree. An additional grant
|
||||
// of patent rights can be found in the PATENTS file in the same directory.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
typedef __attribute__((capability("mutex"))) pthread_mutex_t *SRMutex;
|
||||
|
||||
extern SRMutex SRMutexInitRecursive(void);
|
||||
extern void SRMutexDestroy(SRMutex mutex);
|
||||
|
||||
extern void SRMutexLock(SRMutex mutex) __attribute__((acquire_capability(mutex)));
|
||||
extern void SRMutexUnlock(SRMutex mutex) __attribute__((release_capability(mutex)));
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
@ -1,47 +0,0 @@
|
||||
//
|
||||
// Copyright (c) 2016-present, Facebook, Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the BSD-style license found in the
|
||||
// LICENSE file in the root directory of this source tree. An additional grant
|
||||
// of patent rights can be found in the PATENTS file in the same directory.
|
||||
//
|
||||
|
||||
#import "SRMutex.h"
|
||||
|
||||
#import <pthread/pthread.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
SRMutex SRMutexInitRecursive(void)
|
||||
{
|
||||
pthread_mutex_t *mutex = malloc(sizeof(pthread_mutex_t));
|
||||
pthread_mutexattr_t attributes;
|
||||
|
||||
pthread_mutexattr_init(&attributes);
|
||||
pthread_mutexattr_settype(&attributes, PTHREAD_MUTEX_RECURSIVE);
|
||||
pthread_mutex_init(mutex, &attributes);
|
||||
pthread_mutexattr_destroy(&attributes);
|
||||
|
||||
return mutex;
|
||||
}
|
||||
|
||||
void SRMutexDestroy(SRMutex mutex)
|
||||
{
|
||||
pthread_mutex_destroy(mutex);
|
||||
free(mutex);
|
||||
}
|
||||
|
||||
__attribute__((no_thread_safety_analysis))
|
||||
void SRMutexLock(SRMutex mutex)
|
||||
{
|
||||
pthread_mutex_lock(mutex);
|
||||
}
|
||||
|
||||
__attribute__((no_thread_safety_analysis))
|
||||
void SRMutexUnlock(SRMutex mutex)
|
||||
{
|
||||
pthread_mutex_unlock(mutex);
|
||||
}
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
@ -1,16 +0,0 @@
|
||||
//
|
||||
// Copyright (c) 2016-present, Facebook, Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the BSD-style license found in the
|
||||
// LICENSE file in the root directory of this source tree. An additional grant
|
||||
// of patent rights can be found in the PATENTS file in the same directory.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
extern NSData *SRRandomData(NSUInteger length);
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
@ -1,26 +0,0 @@
|
||||
//
|
||||
// Copyright (c) 2016-present, Facebook, Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the BSD-style license found in the
|
||||
// LICENSE file in the root directory of this source tree. An additional grant
|
||||
// of patent rights can be found in the PATENTS file in the same directory.
|
||||
//
|
||||
|
||||
#import "SRRandom.h"
|
||||
|
||||
#import <Security/SecRandom.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
NSData *SRRandomData(NSUInteger length)
|
||||
{
|
||||
NSMutableData *data = [NSMutableData dataWithLength:length];
|
||||
int result = SecRandomCopyBytes(kSecRandomDefault, data.length, data.mutableBytes);
|
||||
if (result != 0) {
|
||||
[NSException raise:NSInternalInconsistencyException format:@"Failed to generate random bytes with OSStatus: %d", result];
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
@ -1,19 +0,0 @@
|
||||
//
|
||||
// Copyright (c) 2016-present, Facebook, Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the BSD-style license found in the
|
||||
// LICENSE file in the root directory of this source tree. An additional grant
|
||||
// of patent rights can be found in the PATENTS file in the same directory.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
/**
|
||||
Unmask bytes using XOR via SIMD.
|
||||
|
||||
@param bytes The bytes to unmask.
|
||||
@param length The number of bytes to unmask.
|
||||
@param maskKey The mask to XOR with MUST be of length sizeof(uint32_t).
|
||||
*/
|
||||
void SRMaskBytesSIMD(uint8_t *bytes, size_t length, uint8_t *maskKey);
|
||||
@ -1,73 +0,0 @@
|
||||
//
|
||||
// Copyright (c) 2016-present, Facebook, Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the BSD-style license found in the
|
||||
// LICENSE file in the root directory of this source tree. An additional grant
|
||||
// of patent rights can be found in the PATENTS file in the same directory.
|
||||
//
|
||||
|
||||
#import "SRSIMDHelpers.h"
|
||||
|
||||
typedef uint8_t uint8x32_t __attribute__((vector_size(32)));
|
||||
|
||||
static void SRMaskBytesManual(uint8_t *bytes, size_t length, uint8_t *maskKey) {
|
||||
for (size_t i = 0; i < length; i++) {
|
||||
bytes[i] = bytes[i] ^ maskKey[i % sizeof(uint32_t)];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Right-shift the elements of a vector, circularly.
|
||||
|
||||
@param vector The vector to circular shift.
|
||||
@param by The number of elements to shift by.
|
||||
|
||||
@return A shifted vector.
|
||||
*/
|
||||
static uint8x32_t SRShiftVector(uint8x32_t vector, size_t by) {
|
||||
uint8x32_t vectorCopy = vector;
|
||||
by = by % _Alignof(uint8x32_t);
|
||||
|
||||
uint8_t *vectorPointer = (uint8_t *)&vector;
|
||||
uint8_t *vectorCopyPointer = (uint8_t *)&vectorCopy;
|
||||
|
||||
memmove(vectorPointer + by, vectorPointer, sizeof(vector) - by);
|
||||
memcpy(vectorPointer, vectorCopyPointer + (sizeof(vector) - by), by);
|
||||
|
||||
return vector;
|
||||
}
|
||||
|
||||
void SRMaskBytesSIMD(uint8_t *bytes, size_t length, uint8_t *maskKey) {
|
||||
size_t alignmentBytes = _Alignof(uint8x32_t) - ((uintptr_t)bytes % _Alignof(uint8x32_t));
|
||||
if (alignmentBytes == _Alignof(uint8x32_t)) {
|
||||
alignmentBytes = 0;
|
||||
}
|
||||
|
||||
// If the number of bytes that can be processed after aligning is
|
||||
// less than the number of bytes we can put into a vector,
|
||||
// then there's no work to do with SIMD, just call the manual version.
|
||||
if (alignmentBytes > length || (length - alignmentBytes) < sizeof(uint8x32_t)) {
|
||||
SRMaskBytesManual(bytes, length, maskKey);
|
||||
return;
|
||||
}
|
||||
|
||||
size_t vectorLength = (length - alignmentBytes) / sizeof(uint8x32_t);
|
||||
size_t manualStartOffset = alignmentBytes + (vectorLength * sizeof(uint8x32_t));
|
||||
size_t manualLength = length - manualStartOffset;
|
||||
|
||||
uint8x32_t *vector = (uint8x32_t *)(bytes + alignmentBytes);
|
||||
uint8x32_t maskVector = { };
|
||||
|
||||
memset_pattern4(&maskVector, maskKey, sizeof(uint8x32_t));
|
||||
maskVector = SRShiftVector(maskVector, alignmentBytes);
|
||||
|
||||
SRMaskBytesManual(bytes, alignmentBytes, maskKey);
|
||||
|
||||
for (size_t vectorIndex = 0; vectorIndex < vectorLength; vectorIndex++) {
|
||||
vector[vectorIndex] = vector[vectorIndex] ^ maskVector;
|
||||
}
|
||||
|
||||
// Use the shifted mask for the final manual part.
|
||||
SRMaskBytesManual(bytes + manualStartOffset, manualLength, (uint8_t *) &maskVector);
|
||||
}
|
||||
@ -1,26 +0,0 @@
|
||||
//
|
||||
// Copyright (c) 2016-present, Facebook, Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the BSD-style license found in the
|
||||
// LICENSE file in the root directory of this source tree. An additional grant
|
||||
// of patent rights can be found in the PATENTS file in the same directory.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
// The origin isn't really applicable for a native application.
|
||||
// So instead, just map ws -> http and wss -> https.
|
||||
extern NSString *SRURLOrigin(NSURL *url);
|
||||
|
||||
extern BOOL SRURLRequiresSSL(NSURL *url);
|
||||
|
||||
// Extracts `user` and `password` from url (if available) into `Basic base64(user:password)`.
|
||||
extern NSString *_Nullable SRBasicAuthorizationHeaderFromURL(NSURL *url);
|
||||
|
||||
// Returns a valid value for `NSStreamNetworkServiceType` or `nil`.
|
||||
extern NSString *_Nullable SRStreamNetworkServiceTypeFromURLRequest(NSURLRequest *request);
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
@ -1,77 +0,0 @@
|
||||
//
|
||||
// Copyright (c) 2016-present, Facebook, Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the BSD-style license found in the
|
||||
// LICENSE file in the root directory of this source tree. An additional grant
|
||||
// of patent rights can be found in the PATENTS file in the same directory.
|
||||
//
|
||||
|
||||
#import "SRURLUtilities.h"
|
||||
|
||||
#import "SRHash.h"
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
NSString *SRURLOrigin(NSURL *url)
|
||||
{
|
||||
NSMutableString *origin = [NSMutableString string];
|
||||
|
||||
NSString *scheme = url.scheme.lowercaseString;
|
||||
if ([scheme isEqualToString:@"wss"]) {
|
||||
scheme = @"https";
|
||||
} else if ([scheme isEqualToString:@"ws"]) {
|
||||
scheme = @"http";
|
||||
}
|
||||
[origin appendFormat:@"%@://%@", scheme, url.host];
|
||||
|
||||
NSNumber *port = url.port;
|
||||
BOOL portIsDefault = (!port ||
|
||||
([scheme isEqualToString:@"http"] && port.integerValue == 80) ||
|
||||
([scheme isEqualToString:@"https"] && port.integerValue == 443));
|
||||
if (!portIsDefault) {
|
||||
[origin appendFormat:@":%@", port.stringValue];
|
||||
}
|
||||
return origin;
|
||||
}
|
||||
|
||||
extern BOOL SRURLRequiresSSL(NSURL *url)
|
||||
{
|
||||
NSString *scheme = url.scheme.lowercaseString;
|
||||
return ([scheme isEqualToString:@"wss"] || [scheme isEqualToString:@"https"]);
|
||||
}
|
||||
|
||||
extern NSString *_Nullable SRBasicAuthorizationHeaderFromURL(NSURL *url)
|
||||
{
|
||||
NSData *data = [[NSString stringWithFormat:@"%@:%@", url.user, url.password] dataUsingEncoding:NSUTF8StringEncoding];
|
||||
return [NSString stringWithFormat:@"Basic %@", SRBase64EncodedStringFromData(data)];
|
||||
}
|
||||
|
||||
extern NSString *_Nullable SRStreamNetworkServiceTypeFromURLRequest(NSURLRequest *request)
|
||||
{
|
||||
NSString *networkServiceType = nil;
|
||||
switch (request.networkServiceType) {
|
||||
case NSURLNetworkServiceTypeDefault:
|
||||
break;
|
||||
case NSURLNetworkServiceTypeVoIP:
|
||||
networkServiceType = NSStreamNetworkServiceTypeVoIP;
|
||||
break;
|
||||
case NSURLNetworkServiceTypeVideo:
|
||||
networkServiceType = NSStreamNetworkServiceTypeVideo;
|
||||
break;
|
||||
case NSURLNetworkServiceTypeBackground:
|
||||
networkServiceType = NSStreamNetworkServiceTypeBackground;
|
||||
break;
|
||||
case NSURLNetworkServiceTypeVoice:
|
||||
networkServiceType = NSStreamNetworkServiceTypeVoice;
|
||||
break;
|
||||
#if (__MAC_OS_X_VERSION_MAX_ALLOWED >= 101200 || __IPHONE_OS_VERSION_MAX_ALLOWED >= 100000 || __TV_OS_VERSION_MAX_ALLOWED >= 100000 || __WATCH_OS_VERSION_MAX_ALLOWED >= 30000)
|
||||
case NSURLNetworkServiceTypeCallSignaling:
|
||||
networkServiceType = NSStreamNetworkServiceTypeCallSignaling;
|
||||
break;
|
||||
#endif
|
||||
}
|
||||
return networkServiceType;
|
||||
}
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
@ -1,27 +0,0 @@
|
||||
//
|
||||
// Copyright 2012 Square Inc.
|
||||
// Portions Copyright (c) 2016-present, Facebook, Inc.
|
||||
//
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the BSD-style license found in the
|
||||
// LICENSE file in the root directory of this source tree. An additional grant
|
||||
// of patent rights can be found in the PATENTS file in the same directory.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@interface NSRunLoop (SRWebSocket)
|
||||
|
||||
/**
|
||||
Default run loop that will be used to schedule all instances of `SRWebSocket`.
|
||||
|
||||
@return An instance of `NSRunLoop`.
|
||||
*/
|
||||
+ (NSRunLoop *)SR_networkRunLoop;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
@ -1,27 +0,0 @@
|
||||
//
|
||||
// Copyright 2012 Square Inc.
|
||||
// Portions Copyright (c) 2016-present, Facebook, Inc.
|
||||
//
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the BSD-style license found in the
|
||||
// LICENSE file in the root directory of this source tree. An additional grant
|
||||
// of patent rights can be found in the PATENTS file in the same directory.
|
||||
//
|
||||
|
||||
#import "NSRunLoop+SRWebSocket.h"
|
||||
#import "NSRunLoop+SRWebSocketPrivate.h"
|
||||
|
||||
#import "SRRunLoopThread.h"
|
||||
|
||||
// Required for object file to always be linked.
|
||||
void import_NSRunLoop_SRWebSocket() { }
|
||||
|
||||
@implementation NSRunLoop (SRWebSocket)
|
||||
|
||||
+ (NSRunLoop *)SR_networkRunLoop
|
||||
{
|
||||
return [SRRunLoopThread sharedThread].runLoop;
|
||||
}
|
||||
|
||||
@end
|
||||
@ -1,38 +0,0 @@
|
||||
//
|
||||
// Copyright 2012 Square Inc.
|
||||
// Portions Copyright (c) 2016-present, Facebook, Inc.
|
||||
//
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the BSD-style license found in the
|
||||
// LICENSE file in the root directory of this source tree. An additional grant
|
||||
// of patent rights can be found in the PATENTS file in the same directory.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@interface NSURLRequest (SRWebSocket)
|
||||
|
||||
/**
|
||||
An array of pinned `SecCertificateRef` SSL certificates that `SRWebSocket` will use for validation.
|
||||
*/
|
||||
@property (nullable, nonatomic, copy, readonly) NSArray *SR_SSLPinnedCertificates
|
||||
DEPRECATED_MSG_ATTRIBUTE("Using pinned certificates is neither secure nor supported in SocketRocket, "
|
||||
"and leads to security issues. Please use a proper, trust chain validated certificate.");
|
||||
|
||||
@end
|
||||
|
||||
@interface NSMutableURLRequest (SRWebSocket)
|
||||
|
||||
/**
|
||||
An array of pinned `SecCertificateRef` SSL certificates that `SRWebSocket` will use for validation.
|
||||
*/
|
||||
@property (nullable, nonatomic, copy) NSArray *SR_SSLPinnedCertificates
|
||||
DEPRECATED_MSG_ATTRIBUTE("Using pinned certificates is neither secure nor supported in SocketRocket, "
|
||||
"and leads to security issues. Please use a proper, trust chain validated certificate.");
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
@ -1,42 +0,0 @@
|
||||
//
|
||||
// Copyright 2012 Square Inc.
|
||||
// Portions Copyright (c) 2016-present, Facebook, Inc.
|
||||
//
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the BSD-style license found in the
|
||||
// LICENSE file in the root directory of this source tree. An additional grant
|
||||
// of patent rights can be found in the PATENTS file in the same directory.
|
||||
//
|
||||
|
||||
#import "NSURLRequest+SRWebSocket.h"
|
||||
#import "NSURLRequest+SRWebSocketPrivate.h"
|
||||
|
||||
// Required for object file to always be linked.
|
||||
void import_NSURLRequest_SRWebSocket() { }
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
static NSString *const SRSSLPinnnedCertificatesKey = @"SocketRocket_SSLPinnedCertificates";
|
||||
|
||||
@implementation NSURLRequest (SRWebSocket)
|
||||
|
||||
- (nullable NSArray *)SR_SSLPinnedCertificates
|
||||
{
|
||||
return nil;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation NSMutableURLRequest (SRWebSocket)
|
||||
|
||||
- (void)setSR_SSLPinnedCertificates:(nullable NSArray *)SR_SSLPinnedCertificates
|
||||
{
|
||||
[NSException raise:NSInvalidArgumentException
|
||||
format:@"Using pinned certificates is neither secure nor supported in SocketRocket, "
|
||||
"and leads to security issues. Please use a proper, trust chain validated certificate."];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
@ -1,26 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleDevelopmentRegion</key>
|
||||
<string>en</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>$(EXECUTABLE_NAME)</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>$(PRODUCT_NAME)</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>FMWK</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>1.0</string>
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>$(CURRENT_PROJECT_VERSION)</string>
|
||||
<key>NSPrincipalClass</key>
|
||||
<string></string>
|
||||
</dict>
|
||||
</plist>
|
||||
@ -1,72 +0,0 @@
|
||||
//
|
||||
// Copyright (c) 2016-present, Facebook, Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the BSD-style license found in the
|
||||
// LICENSE file in the root directory of this source tree. An additional grant
|
||||
// of patent rights can be found in the PATENTS file in the same directory.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import <Security/Security.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@interface SRSecurityPolicy : NSObject
|
||||
|
||||
/**
|
||||
A default `SRSecurityPolicy` implementation specifies socket security and
|
||||
validates the certificate chain.
|
||||
|
||||
Use a subclass of `SRSecurityPolicy` for more fine grained customization.
|
||||
*/
|
||||
+ (instancetype)defaultPolicy;
|
||||
|
||||
/**
|
||||
Specifies socket security and provider certificate pinning, disregarding certificate
|
||||
chain validation.
|
||||
|
||||
@param pinnedCertificates Array of `SecCertificateRef` SSL certificates to use for validation.
|
||||
*/
|
||||
+ (instancetype)pinnningPolicyWithCertificates:(NSArray *)pinnedCertificates
|
||||
DEPRECATED_MSG_ATTRIBUTE("Using pinned certificates is neither secure nor supported in SocketRocket, "
|
||||
"and leads to security issues. Please use a proper, trust chain validated certificate.");
|
||||
|
||||
/**
|
||||
Specifies socket security and optional certificate chain validation.
|
||||
|
||||
@param enabled Whether or not to validate the SSL certificate chain. If you
|
||||
are considering using this method because your certificate was not issued by a
|
||||
recognized certificate authority, consider using `pinningPolicyWithCertificates` instead.
|
||||
*/
|
||||
- (instancetype)initWithCertificateChainValidationEnabled:(BOOL)enabled
|
||||
DEPRECATED_MSG_ATTRIBUTE("Disabling certificate chain validation is unsafe. "
|
||||
"Please use a proper Certificate Authority to issue your TLS certificates.")
|
||||
NS_DESIGNATED_INITIALIZER;
|
||||
|
||||
/**
|
||||
Updates all the security options for input and output streams, for example you
|
||||
can set your socket security level here.
|
||||
|
||||
@param stream Stream to update the options in.
|
||||
*/
|
||||
- (void)updateSecurityOptionsInStream:(NSStream *)stream;
|
||||
|
||||
/**
|
||||
Whether or not the specified server trust should be accepted, based on the security policy.
|
||||
|
||||
This method should be used when responding to an authentication challenge from
|
||||
a server. In the default implemenation, no further validation is done here, but
|
||||
you're free to override it in a subclass. See `SRPinningSecurityPolicy.h` for
|
||||
an example.
|
||||
|
||||
@param serverTrust The X.509 certificate trust of the server.
|
||||
@param domain The domain of serverTrust.
|
||||
|
||||
@return Whether or not to trust the server.
|
||||
*/
|
||||
- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust forDomain:(NSString *)domain;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
@ -1,75 +0,0 @@
|
||||
//
|
||||
// Copyright (c) 2016-present, Facebook, Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the BSD-style license found in the
|
||||
// LICENSE file in the root directory of this source tree. An additional grant
|
||||
// of patent rights can be found in the PATENTS file in the same directory.
|
||||
//
|
||||
|
||||
#import "SRSecurityPolicy.h"
|
||||
#import "SRPinningSecurityPolicy.h"
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@interface SRSecurityPolicy ()
|
||||
|
||||
@property (nonatomic, assign, readonly) BOOL certificateChainValidationEnabled;
|
||||
|
||||
@end
|
||||
|
||||
@implementation SRSecurityPolicy
|
||||
|
||||
+ (instancetype)defaultPolicy
|
||||
{
|
||||
return [self new];
|
||||
}
|
||||
|
||||
+ (instancetype)pinnningPolicyWithCertificates:(NSArray *)pinnedCertificates
|
||||
{
|
||||
[NSException raise:NSInvalidArgumentException
|
||||
format:@"Using pinned certificates is neither secure nor supported in SocketRocket, "
|
||||
"and leads to security issues. Please use a proper, trust chain validated certificate."];
|
||||
|
||||
return nil;
|
||||
}
|
||||
|
||||
- (instancetype)initWithCertificateChainValidationEnabled:(BOOL)enabled
|
||||
{
|
||||
self = [super init];
|
||||
if (!self) { return self; }
|
||||
|
||||
_certificateChainValidationEnabled = enabled;
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (instancetype)init
|
||||
{
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wdeprecated"
|
||||
|
||||
return [self initWithCertificateChainValidationEnabled:YES];
|
||||
|
||||
#pragma clang diagnostic pop
|
||||
}
|
||||
|
||||
- (void)updateSecurityOptionsInStream:(NSStream *)stream
|
||||
{
|
||||
// Enforce TLS 1.2
|
||||
[stream setProperty:(__bridge id)CFSTR("kCFStreamSocketSecurityLevelTLSv1_2") forKey:(__bridge id)kCFStreamPropertySocketSecurityLevel];
|
||||
|
||||
// Validate certificate chain for this stream if enabled.
|
||||
NSDictionary<NSString *, id> *sslOptions = @{ (__bridge NSString *)kCFStreamSSLValidatesCertificateChain : @(self.certificateChainValidationEnabled) };
|
||||
[stream setProperty:sslOptions forKey:(__bridge NSString *)kCFStreamPropertySSLSettings];
|
||||
}
|
||||
|
||||
- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust forDomain:(NSString *)domain
|
||||
{
|
||||
// No further evaluation happens in the default policy.
|
||||
return YES;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
@ -1,417 +0,0 @@
|
||||
//
|
||||
// Copyright 2012 Square Inc.
|
||||
// Portions Copyright (c) 2016-present, Facebook, Inc.
|
||||
//
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the BSD-style license found in the
|
||||
// LICENSE file in the root directory of this source tree. An additional grant
|
||||
// of patent rights can be found in the PATENTS file in the same directory.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
typedef NS_ENUM(NSInteger, SRReadyState) {
|
||||
SR_CONNECTING = 0,
|
||||
SR_OPEN = 1,
|
||||
SR_CLOSING = 2,
|
||||
SR_CLOSED = 3,
|
||||
};
|
||||
|
||||
typedef NS_ENUM(NSInteger, SRStatusCode) {
|
||||
// 0-999: Reserved and not used.
|
||||
SRStatusCodeNormal = 1000,
|
||||
SRStatusCodeGoingAway = 1001,
|
||||
SRStatusCodeProtocolError = 1002,
|
||||
SRStatusCodeUnhandledType = 1003,
|
||||
// 1004 reserved.
|
||||
SRStatusNoStatusReceived = 1005,
|
||||
SRStatusCodeAbnormal = 1006,
|
||||
SRStatusCodeInvalidUTF8 = 1007,
|
||||
SRStatusCodePolicyViolated = 1008,
|
||||
SRStatusCodeMessageTooBig = 1009,
|
||||
SRStatusCodeMissingExtension = 1010,
|
||||
SRStatusCodeInternalError = 1011,
|
||||
SRStatusCodeServiceRestart = 1012,
|
||||
SRStatusCodeTryAgainLater = 1013,
|
||||
// 1014: Reserved for future use by the WebSocket standard.
|
||||
SRStatusCodeTLSHandshake = 1015,
|
||||
// 1016-1999: Reserved for future use by the WebSocket standard.
|
||||
// 2000-2999: Reserved for use by WebSocket extensions.
|
||||
// 3000-3999: Available for use by libraries and frameworks. May not be used by applications. Available for registration at the IANA via first-come, first-serve.
|
||||
// 4000-4999: Available for use by applications.
|
||||
};
|
||||
|
||||
@class SRWebSocket;
|
||||
@class SRSecurityPolicy;
|
||||
|
||||
/**
|
||||
Error domain used for errors reported by SRWebSocket.
|
||||
*/
|
||||
extern NSString *const SRWebSocketErrorDomain;
|
||||
|
||||
/**
|
||||
Key used for HTTP status code if bad response was received from the server.
|
||||
*/
|
||||
extern NSString *const SRHTTPResponseErrorKey;
|
||||
|
||||
@protocol SRWebSocketDelegate;
|
||||
|
||||
///--------------------------------------
|
||||
#pragma mark - SRWebSocket
|
||||
///--------------------------------------
|
||||
|
||||
/**
|
||||
A `SRWebSocket` object lets you connect, send and receive data to a remote Web Socket.
|
||||
*/
|
||||
@interface SRWebSocket : NSObject <NSStreamDelegate>
|
||||
|
||||
/**
|
||||
The delegate of the web socket.
|
||||
|
||||
The web socket delegate is notified on all state changes that happen to the web socket.
|
||||
*/
|
||||
@property (nonatomic, weak) id <SRWebSocketDelegate> delegate;
|
||||
|
||||
/**
|
||||
A dispatch queue for scheduling the delegate calls. The queue doesn't need be a serial queue.
|
||||
|
||||
If `nil` and `delegateOperationQueue` is `nil`, the socket uses main queue for performing all delegate method calls.
|
||||
*/
|
||||
@property (nullable, nonatomic, strong) dispatch_queue_t delegateDispatchQueue;
|
||||
|
||||
/**
|
||||
An operation queue for scheduling the delegate calls.
|
||||
|
||||
If `nil` and `delegateOperationQueue` is `nil`, the socket uses main queue for performing all delegate method calls.
|
||||
*/
|
||||
@property (nullable, nonatomic, strong) NSOperationQueue *delegateOperationQueue;
|
||||
|
||||
/**
|
||||
Current ready state of the socket. Default: `SR_CONNECTING`.
|
||||
|
||||
This property is Key-Value Observable and fully thread-safe.
|
||||
*/
|
||||
@property (atomic, assign, readonly) SRReadyState readyState;
|
||||
|
||||
/**
|
||||
An instance of `NSURL` that this socket connects to.
|
||||
*/
|
||||
@property (nullable, nonatomic, strong, readonly) NSURL *url;
|
||||
|
||||
/**
|
||||
All HTTP headers that were received by socket or `nil` if none were received so far.
|
||||
*/
|
||||
@property (nullable, nonatomic, assign, readonly) CFHTTPMessageRef receivedHTTPHeaders;
|
||||
|
||||
/**
|
||||
Array of `NSHTTPCookie` cookies to apply to the connection.
|
||||
*/
|
||||
@property (nullable, nonatomic, copy) NSArray<NSHTTPCookie *> *requestCookies;
|
||||
|
||||
/**
|
||||
The negotiated web socket protocol or `nil` if handshake did not yet complete.
|
||||
*/
|
||||
@property (nullable, nonatomic, copy, readonly) NSString *protocol;
|
||||
|
||||
/**
|
||||
A boolean value indicating whether this socket will allow connection without SSL trust chain evaluation.
|
||||
For DEBUG builds this flag is ignored, and SSL connections are allowed regardless of the certificate trust configuration
|
||||
*/
|
||||
@property (nonatomic, assign, readonly) BOOL allowsUntrustedSSLCertificates;
|
||||
|
||||
///--------------------------------------
|
||||
#pragma mark - Constructors
|
||||
///--------------------------------------
|
||||
|
||||
/**
|
||||
Initializes a web socket with a given `NSURLRequest`.
|
||||
|
||||
@param request Request to initialize with.
|
||||
*/
|
||||
- (instancetype)initWithURLRequest:(NSURLRequest *)request;
|
||||
|
||||
/**
|
||||
Initializes a web socket with a given `NSURLRequest`, specifying a transport security policy (e.g. SSL configuration).
|
||||
|
||||
@param request Request to initialize with.
|
||||
@param securityPolicy Policy object describing transport security behavior.
|
||||
*/
|
||||
- (instancetype)initWithURLRequest:(NSURLRequest *)request securityPolicy:(SRSecurityPolicy *)securityPolicy;
|
||||
|
||||
/**
|
||||
Initializes a web socket with a given `NSURLRequest` and list of sub-protocols.
|
||||
|
||||
@param request Request to initialize with.
|
||||
@param protocols An array of strings that turn into `Sec-WebSocket-Protocol`. Default: `nil`.
|
||||
*/
|
||||
- (instancetype)initWithURLRequest:(NSURLRequest *)request protocols:(nullable NSArray<NSString *> *)protocols;
|
||||
|
||||
/**
|
||||
Initializes a web socket with a given `NSURLRequest`, list of sub-protocols and whether untrusted SSL certificates are allowed.
|
||||
|
||||
@param request Request to initialize with.
|
||||
@param protocols An array of strings that turn into `Sec-WebSocket-Protocol`. Default: `nil`.
|
||||
@param allowsUntrustedSSLCertificates Boolean value indicating whether untrusted SSL certificates are allowed. Default: `false`.
|
||||
*/
|
||||
- (instancetype)initWithURLRequest:(NSURLRequest *)request protocols:(nullable NSArray<NSString *> *)protocols allowsUntrustedSSLCertificates:(BOOL)allowsUntrustedSSLCertificates
|
||||
DEPRECATED_MSG_ATTRIBUTE("Disabling certificate chain validation is unsafe. "
|
||||
"Please use a proper Certificate Authority to issue your TLS certificates.");
|
||||
|
||||
/**
|
||||
Initializes a web socket with a given `NSURLRequest`, list of sub-protocols and whether untrusted SSL certificates are allowed.
|
||||
|
||||
@param request Request to initialize with.
|
||||
@param protocols An array of strings that turn into `Sec-WebSocket-Protocol`. Default: `nil`.
|
||||
@param securityPolicy Policy object describing transport security behavior.
|
||||
*/
|
||||
- (instancetype)initWithURLRequest:(NSURLRequest *)request protocols:(nullable NSArray<NSString *> *)protocols securityPolicy:(SRSecurityPolicy *)securityPolicy NS_DESIGNATED_INITIALIZER;
|
||||
|
||||
/**
|
||||
Initializes a web socket with a given `NSURL`.
|
||||
|
||||
@param url URL to initialize with.
|
||||
*/
|
||||
- (instancetype)initWithURL:(NSURL *)url;
|
||||
|
||||
/**
|
||||
Initializes a web socket with a given `NSURL` and list of sub-protocols.
|
||||
|
||||
@param url URL to initialize with.
|
||||
@param protocols An array of strings that turn into `Sec-WebSocket-Protocol`. Default: `nil`.
|
||||
*/
|
||||
- (instancetype)initWithURL:(NSURL *)url protocols:(nullable NSArray<NSString *> *)protocols;
|
||||
|
||||
/**
|
||||
Initializes a web socket with a given `NSURL`, specifying a transport security policy (e.g. SSL configuration).
|
||||
|
||||
@param url URL to initialize with.
|
||||
@param securityPolicy Policy object describing transport security behavior.
|
||||
*/
|
||||
- (instancetype)initWithURL:(NSURL *)url securityPolicy:(SRSecurityPolicy *)securityPolicy;
|
||||
|
||||
/**
|
||||
Initializes a web socket with a given `NSURL`, list of sub-protocols and whether untrusted SSL certificates are allowed.
|
||||
|
||||
@param url URL to initialize with.
|
||||
@param protocols An array of strings that turn into `Sec-WebSocket-Protocol`. Default: `nil`.
|
||||
@param allowsUntrustedSSLCertificates Boolean value indicating whether untrusted SSL certificates are allowed. Default: `false`.
|
||||
*/
|
||||
- (instancetype)initWithURL:(NSURL *)url protocols:(nullable NSArray<NSString *> *)protocols allowsUntrustedSSLCertificates:(BOOL)allowsUntrustedSSLCertificates
|
||||
DEPRECATED_MSG_ATTRIBUTE("Disabling certificate chain validation is unsafe. "
|
||||
"Please use a proper Certificate Authority to issue your TLS certificates.");
|
||||
|
||||
/**
|
||||
Unavailable initializer. Please use any other initializer.
|
||||
*/
|
||||
- (instancetype)init NS_UNAVAILABLE;
|
||||
|
||||
/**
|
||||
Unavailable constructor. Please use any other initializer.
|
||||
*/
|
||||
+ (instancetype)new NS_UNAVAILABLE;
|
||||
|
||||
///--------------------------------------
|
||||
#pragma mark - Schedule
|
||||
///--------------------------------------
|
||||
|
||||
/**
|
||||
Schedules a received on a given run loop in a given mode.
|
||||
By default, a web socket will schedule itself on `+[NSRunLoop SR_networkRunLoop]` using `NSDefaultRunLoopMode`.
|
||||
|
||||
@param runLoop The run loop on which to schedule the receiver.
|
||||
@param mode The mode for the run loop.
|
||||
*/
|
||||
- (void)scheduleInRunLoop:(NSRunLoop *)runLoop forMode:(NSString *)mode NS_SWIFT_NAME(schedule(in:forMode:));
|
||||
|
||||
/**
|
||||
Removes the receiver from a given run loop running in a given mode.
|
||||
|
||||
@param runLoop The run loop on which the receiver was scheduled.
|
||||
@param mode The mode for the run loop.
|
||||
*/
|
||||
- (void)unscheduleFromRunLoop:(NSRunLoop *)runLoop forMode:(NSString *)mode NS_SWIFT_NAME(unschedule(from:forMode:));
|
||||
|
||||
///--------------------------------------
|
||||
#pragma mark - Open / Close
|
||||
///--------------------------------------
|
||||
|
||||
/**
|
||||
Opens web socket, which will trigger connection, authentication and start receiving/sending events.
|
||||
An instance of `SRWebSocket` is intended for one-time-use only. This method should be called once and only once.
|
||||
*/
|
||||
- (void)open;
|
||||
|
||||
/**
|
||||
Closes a web socket using `SRStatusCodeNormal` code and no reason.
|
||||
*/
|
||||
- (void)close;
|
||||
|
||||
/**
|
||||
Closes a web socket using a given code and reason.
|
||||
|
||||
@param code Code to close the socket with.
|
||||
@param reason Reason to send to the server or `nil`.
|
||||
*/
|
||||
- (void)closeWithCode:(NSInteger)code reason:(nullable NSString *)reason;
|
||||
|
||||
///--------------------------------------
|
||||
#pragma mark Send
|
||||
///--------------------------------------
|
||||
|
||||
/**
|
||||
Send a UTF-8 string or binary data to the server.
|
||||
|
||||
@param message UTF-8 String or Data to send.
|
||||
|
||||
@deprecated Please use `sendString:` or `sendData` instead.
|
||||
*/
|
||||
- (void)send:(nullable id)message __attribute__((deprecated("Please use `sendString:error:` or `sendData:error:` instead.")));
|
||||
|
||||
/**
|
||||
Send a UTF-8 String to the server.
|
||||
|
||||
@param string String to send.
|
||||
@param error On input, a pointer to variable for an `NSError` object.
|
||||
If an error occurs, this pointer is set to an `NSError` object containing information about the error.
|
||||
You may specify `nil` to ignore the error information.
|
||||
|
||||
@return `YES` if the string was scheduled to send, otherwise - `NO`.
|
||||
*/
|
||||
- (BOOL)sendString:(NSString *)string error:(NSError **)error NS_SWIFT_NAME(send(string:));
|
||||
|
||||
/**
|
||||
Send binary data to the server.
|
||||
|
||||
@param data Data to send.
|
||||
@param error On input, a pointer to variable for an `NSError` object.
|
||||
If an error occurs, this pointer is set to an `NSError` object containing information about the error.
|
||||
You may specify `nil` to ignore the error information.
|
||||
|
||||
@return `YES` if the string was scheduled to send, otherwise - `NO`.
|
||||
*/
|
||||
- (BOOL)sendData:(nullable NSData *)data error:(NSError **)error NS_SWIFT_NAME(send(data:));
|
||||
|
||||
/**
|
||||
Send binary data to the server, without making a defensive copy of it first.
|
||||
|
||||
@param data Data to send.
|
||||
@param error On input, a pointer to variable for an `NSError` object.
|
||||
If an error occurs, this pointer is set to an `NSError` object containing information about the error.
|
||||
You may specify `nil` to ignore the error information.
|
||||
|
||||
@return `YES` if the string was scheduled to send, otherwise - `NO`.
|
||||
*/
|
||||
- (BOOL)sendDataNoCopy:(nullable NSData *)data error:(NSError **)error NS_SWIFT_NAME(send(dataNoCopy:));
|
||||
|
||||
/**
|
||||
Send Ping message to the server with optional data.
|
||||
|
||||
@param data Instance of `NSData` or `nil`.
|
||||
@param error On input, a pointer to variable for an `NSError` object.
|
||||
If an error occurs, this pointer is set to an `NSError` object containing information about the error.
|
||||
You may specify `nil` to ignore the error information.
|
||||
|
||||
@return `YES` if the string was scheduled to send, otherwise - `NO`.
|
||||
*/
|
||||
- (BOOL)sendPing:(nullable NSData *)data error:(NSError **)error NS_SWIFT_NAME(sendPing(_:));
|
||||
|
||||
@end
|
||||
|
||||
///--------------------------------------
|
||||
#pragma mark - SRWebSocketDelegate
|
||||
///--------------------------------------
|
||||
|
||||
/**
|
||||
The `SRWebSocketDelegate` protocol describes the methods that `SRWebSocket` objects
|
||||
call on their delegates to handle status and messsage events.
|
||||
*/
|
||||
@protocol SRWebSocketDelegate <NSObject>
|
||||
|
||||
@optional
|
||||
|
||||
#pragma mark Receive Messages
|
||||
|
||||
/**
|
||||
Called when any message was received from a web socket.
|
||||
This method is suboptimal and might be deprecated in a future release.
|
||||
|
||||
@param webSocket An instance of `SRWebSocket` that received a message.
|
||||
@param message Received message. Either a `String` or `NSData`.
|
||||
*/
|
||||
- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message;
|
||||
|
||||
/**
|
||||
Called when a frame was received from a web socket.
|
||||
|
||||
@param webSocket An instance of `SRWebSocket` that received a message.
|
||||
@param string Received text in a form of UTF-8 `String`.
|
||||
*/
|
||||
- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessageWithString:(NSString *)string;
|
||||
|
||||
/**
|
||||
Called when a frame was received from a web socket.
|
||||
|
||||
@param webSocket An instance of `SRWebSocket` that received a message.
|
||||
@param data Received data in a form of `NSData`.
|
||||
*/
|
||||
- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessageWithData:(NSData *)data;
|
||||
|
||||
#pragma mark Status & Connection
|
||||
|
||||
/**
|
||||
Called when a given web socket was open and authenticated.
|
||||
|
||||
@param webSocket An instance of `SRWebSocket` that was open.
|
||||
*/
|
||||
- (void)webSocketDidOpen:(SRWebSocket *)webSocket;
|
||||
|
||||
/**
|
||||
Called when a given web socket encountered an error.
|
||||
|
||||
@param webSocket An instance of `SRWebSocket` that failed with an error.
|
||||
@param error An instance of `NSError`.
|
||||
*/
|
||||
- (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error;
|
||||
|
||||
/**
|
||||
Called when a given web socket was closed.
|
||||
|
||||
@param webSocket An instance of `SRWebSocket` that was closed.
|
||||
@param code Code reported by the server.
|
||||
@param reason Reason in a form of a String that was reported by the server or `nil`.
|
||||
@param wasClean Boolean value indicating whether a socket was closed in a clean state.
|
||||
*/
|
||||
- (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(nullable NSString *)reason wasClean:(BOOL)wasClean;
|
||||
|
||||
/**
|
||||
Called on receive of a ping message from the server.
|
||||
|
||||
@param webSocket An instance of `SRWebSocket` that received a ping frame.
|
||||
@param data Payload that was received or `nil` if there was no payload.
|
||||
*/
|
||||
- (void)webSocket:(SRWebSocket *)webSocket didReceivePingWithData:(nullable NSData *)data;
|
||||
|
||||
/**
|
||||
Called when a pong data was received in response to ping.
|
||||
|
||||
@param webSocket An instance of `SRWebSocket` that received a pong frame.
|
||||
@param pongData Payload that was received or `nil` if there was no payload.
|
||||
*/
|
||||
- (void)webSocket:(SRWebSocket *)webSocket didReceivePong:(nullable NSData *)pongData;
|
||||
|
||||
/**
|
||||
Sent before reporting a text frame to be able to configure if it shuold be convert to a UTF-8 String or passed as `NSData`.
|
||||
If the method is not implemented - it will always convert text frames to String.
|
||||
|
||||
@param webSocket An instance of `SRWebSocket` that received a text frame.
|
||||
|
||||
@return `YES` if text frame should be converted to UTF-8 String, otherwise - `NO`. Default: `YES`.
|
||||
*/
|
||||
- (BOOL)webSocketShouldConvertTextFrameToString:(SRWebSocket *)webSocket NS_SWIFT_NAME(webSocketShouldConvertTextFrameToString(_:));
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
File diff suppressed because it is too large
Load Diff
@ -1,15 +0,0 @@
|
||||
//
|
||||
// Copyright 2012 Square Inc.
|
||||
// Portions Copyright (c) 2016-present, Facebook, Inc.
|
||||
//
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the BSD-style license found in the
|
||||
// LICENSE file in the root directory of this source tree. An additional grant
|
||||
// of patent rights can be found in the PATENTS file in the same directory.
|
||||
//
|
||||
|
||||
#import <SocketRocket/NSRunLoop+SRWebSocket.h>
|
||||
#import <SocketRocket/NSURLRequest+SRWebSocket.h>
|
||||
#import <SocketRocket/SRSecurityPolicy.h>
|
||||
#import <SocketRocket/SRWebSocket.h>
|
||||
@ -1,16 +0,0 @@
|
||||
//
|
||||
// Copyright 2012 Square Inc.
|
||||
// Portions Copyright (c) 2016-present, Facebook, Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the license found in the
|
||||
// LICENSE-examples file in the root directory of this source tree.
|
||||
//
|
||||
|
||||
#import <UIKit/UIKit.h>
|
||||
|
||||
@interface TCAppDelegate : UIResponder <UIApplicationDelegate>
|
||||
|
||||
@property (nonatomic, strong) UIWindow *window;
|
||||
|
||||
@end
|
||||
@ -1,19 +0,0 @@
|
||||
//
|
||||
// Copyright 2012 Square Inc.
|
||||
// Portions Copyright (c) 2016-present, Facebook, Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the license found in the
|
||||
// LICENSE-examples file in the root directory of this source tree.
|
||||
//
|
||||
|
||||
#import "TCAppDelegate.h"
|
||||
|
||||
@implementation TCAppDelegate
|
||||
|
||||
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
|
||||
{
|
||||
return YES;
|
||||
}
|
||||
|
||||
@end
|
||||
@ -1,17 +0,0 @@
|
||||
//
|
||||
// Copyright 2012 Square Inc.
|
||||
// Portions Copyright (c) 2016-present, Facebook, Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the license found in the
|
||||
// LICENSE-examples file in the root directory of this source tree.
|
||||
//
|
||||
|
||||
#import <UIKit/UIKit.h>
|
||||
|
||||
@interface TCChatCell : UITableViewCell
|
||||
|
||||
@property (nonatomic, retain) IBOutlet UITextView *textView;
|
||||
@property (nonatomic, retain) IBOutlet UILabel *nameLabel;
|
||||
|
||||
@end
|
||||
@ -1,40 +0,0 @@
|
||||
//
|
||||
// Copyright 2012 Square Inc.
|
||||
// Portions Copyright (c) 2016-present, Facebook, Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the license found in the
|
||||
// LICENSE-examples file in the root directory of this source tree.
|
||||
//
|
||||
|
||||
#import "TCChatCell.h"
|
||||
|
||||
@implementation TCChatCell
|
||||
|
||||
@synthesize nameLabel = _nameLabel;
|
||||
@synthesize textView = _textView;
|
||||
|
||||
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
|
||||
{
|
||||
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
|
||||
if (self) {
|
||||
// Initialization code
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (CGSize)sizeThatFits:(CGSize)size;
|
||||
{
|
||||
CGSize textViewSize = _textView.bounds.size;
|
||||
CGSize fitTextViewSize = CGSizeMake(textViewSize.width, size.height);
|
||||
CGSize sizeThatFitsSize = [self.textView sizeThatFits:fitTextViewSize];
|
||||
|
||||
CGSize superSize = [super sizeThatFits:size];
|
||||
|
||||
sizeThatFitsSize.height = MAX(superSize.height, sizeThatFitsSize.height);
|
||||
sizeThatFitsSize.width = superSize.width;
|
||||
|
||||
return sizeThatFitsSize;
|
||||
}
|
||||
|
||||
@end
|
||||
@ -1,19 +0,0 @@
|
||||
//
|
||||
// Copyright 2012 Square Inc.
|
||||
// Portions Copyright (c) 2016-present, Facebook, Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the license found in the
|
||||
// LICENSE-examples file in the root directory of this source tree.
|
||||
//
|
||||
|
||||
#import <UIKit/UIKit.h>
|
||||
|
||||
@interface TCViewController : UITableViewController
|
||||
|
||||
@property (nonatomic, strong) IBOutlet UITextView *inputView;
|
||||
|
||||
- (IBAction)reconnect:(id)sender;
|
||||
- (IBAction)sendPing:(id)sender;
|
||||
|
||||
@end
|
||||
@ -1,195 +0,0 @@
|
||||
//
|
||||
// Copyright 2012 Square Inc.
|
||||
// Portions Copyright (c) 2016-present, Facebook, Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the license found in the
|
||||
// LICENSE-examples file in the root directory of this source tree.
|
||||
//
|
||||
|
||||
#import "TCViewController.h"
|
||||
|
||||
#import <SocketRocket/SocketRocket.h>
|
||||
|
||||
#import "TCChatCell.h"
|
||||
|
||||
@interface TCMessage : NSObject
|
||||
|
||||
- (instancetype)initWithMessage:(NSString *)message incoming:(BOOL)incoming;
|
||||
|
||||
@property (nonatomic, copy, readonly) NSString *message;
|
||||
@property (nonatomic, assign, readonly, getter=isIncoming) BOOL incoming;
|
||||
|
||||
@end
|
||||
|
||||
@implementation TCMessage
|
||||
|
||||
- (instancetype)initWithMessage:(NSString *)message incoming:(BOOL)incoming
|
||||
{
|
||||
self = [super init];
|
||||
if (!self) return self;
|
||||
|
||||
_incoming = incoming;
|
||||
_message = message;
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
|
||||
@interface TCViewController () <SRWebSocketDelegate, UITextViewDelegate>
|
||||
{
|
||||
SRWebSocket *_webSocket;
|
||||
NSMutableArray<TCMessage *> *_messages;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation TCViewController
|
||||
|
||||
///--------------------------------------
|
||||
#pragma mark - View
|
||||
///--------------------------------------
|
||||
|
||||
- (void)viewDidLoad;
|
||||
{
|
||||
[super viewDidLoad];
|
||||
|
||||
_messages = [[NSMutableArray alloc] init];
|
||||
}
|
||||
|
||||
- (void)viewWillAppear:(BOOL)animated
|
||||
{
|
||||
[super viewWillAppear:animated];
|
||||
|
||||
[self reconnect:nil];
|
||||
}
|
||||
|
||||
- (void)viewDidAppear:(BOOL)animated
|
||||
{
|
||||
[super viewDidAppear:animated];
|
||||
|
||||
[_inputView becomeFirstResponder];
|
||||
}
|
||||
|
||||
- (void)viewDidDisappear:(BOOL)animated
|
||||
{
|
||||
[super viewDidDisappear:animated];
|
||||
|
||||
[_webSocket close];
|
||||
_webSocket = nil;
|
||||
}
|
||||
|
||||
///--------------------------------------
|
||||
#pragma mark - Actions
|
||||
///--------------------------------------
|
||||
|
||||
- (IBAction)reconnect:(id)sender
|
||||
{
|
||||
_webSocket.delegate = nil;
|
||||
[_webSocket close];
|
||||
|
||||
_webSocket = [[SRWebSocket alloc] initWithURL:[NSURL URLWithString:@"wss://echo.websocket.org"]];
|
||||
_webSocket.delegate = self;
|
||||
|
||||
self.title = @"Opening Connection...";
|
||||
[_webSocket open];
|
||||
}
|
||||
|
||||
- (void)sendPing:(id)sender;
|
||||
{
|
||||
[_webSocket sendPing:nil error:NULL];
|
||||
}
|
||||
|
||||
///--------------------------------------
|
||||
#pragma mark - Messages
|
||||
///--------------------------------------
|
||||
|
||||
- (void)_addMessage:(TCMessage *)message
|
||||
{
|
||||
[_messages addObject:message];
|
||||
[self.tableView insertRowsAtIndexPaths:@[ [NSIndexPath indexPathForRow:_messages.count - 1 inSection:0] ]
|
||||
withRowAnimation:UITableViewRowAnimationNone];
|
||||
[self.tableView scrollRectToVisible:self.tableView.tableFooterView.frame animated:YES];
|
||||
}
|
||||
|
||||
///--------------------------------------
|
||||
#pragma mark - UITableViewController
|
||||
///--------------------------------------
|
||||
|
||||
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
|
||||
{
|
||||
return _messages.count;
|
||||
}
|
||||
|
||||
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
|
||||
{
|
||||
TCMessage *message = _messages[indexPath.row];
|
||||
|
||||
TCChatCell *cell = [self.tableView dequeueReusableCellWithIdentifier:message.incoming ? @"ReceivedCell" : @"SentCell"
|
||||
forIndexPath:indexPath];
|
||||
|
||||
cell.textView.text = message.message;
|
||||
cell.nameLabel.text = message.incoming ? @"Other" : @"Me";
|
||||
|
||||
return cell;
|
||||
}
|
||||
|
||||
///--------------------------------------
|
||||
#pragma mark - SRWebSocketDelegate
|
||||
///--------------------------------------
|
||||
|
||||
- (void)webSocketDidOpen:(SRWebSocket *)webSocket;
|
||||
{
|
||||
NSLog(@"Websocket Connected");
|
||||
self.title = @"Connected!";
|
||||
}
|
||||
|
||||
- (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error;
|
||||
{
|
||||
NSLog(@":( Websocket Failed With Error %@", error);
|
||||
|
||||
self.title = @"Connection Failed! (see logs)";
|
||||
_webSocket = nil;
|
||||
}
|
||||
|
||||
- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessageWithString:(nonnull NSString *)string
|
||||
{
|
||||
NSLog(@"Received \"%@\"", string);
|
||||
[self _addMessage:[[TCMessage alloc] initWithMessage:string incoming:YES]];
|
||||
}
|
||||
|
||||
- (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean;
|
||||
{
|
||||
NSLog(@"WebSocket closed");
|
||||
self.title = @"Connection Closed! (see logs)";
|
||||
_webSocket = nil;
|
||||
}
|
||||
|
||||
- (void)webSocket:(SRWebSocket *)webSocket didReceivePong:(NSData *)pongPayload;
|
||||
{
|
||||
NSLog(@"WebSocket received pong");
|
||||
}
|
||||
|
||||
///--------------------------------------
|
||||
#pragma mark - UITextViewDelegate
|
||||
///--------------------------------------
|
||||
|
||||
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
|
||||
{
|
||||
if ([text rangeOfString:@"\n"].location != NSNotFound) {
|
||||
NSString *message = [textView.text stringByReplacingCharactersInRange:range withString:text];
|
||||
message = [message stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
|
||||
|
||||
[_webSocket sendString:message error:NULL];
|
||||
|
||||
[self _addMessage:[[TCMessage alloc] initWithMessage:message incoming:NO]];
|
||||
|
||||
textView.text = nil;
|
||||
return NO;
|
||||
}
|
||||
return YES;
|
||||
}
|
||||
|
||||
@end
|
||||
@ -1,42 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleDevelopmentRegion</key>
|
||||
<string>en</string>
|
||||
<key>CFBundleDisplayName</key>
|
||||
<string>${PRODUCT_NAME}</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>${EXECUTABLE_NAME}</string>
|
||||
<key>CFBundleIconFiles</key>
|
||||
<array/>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>${PRODUCT_NAME}</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>APPL</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>1.0</string>
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>1.0</string>
|
||||
<key>LSRequiresIPhoneOS</key>
|
||||
<true/>
|
||||
<key>UIMainStoryboardFile</key>
|
||||
<string>MainStoryboard</string>
|
||||
<key>UIRequiredDeviceCapabilities</key>
|
||||
<array>
|
||||
<string>armv7</string>
|
||||
</array>
|
||||
<key>UISupportedInterfaceOrientations</key>
|
||||
<array>
|
||||
<string>UIInterfaceOrientationPortrait</string>
|
||||
<string>UIInterfaceOrientationLandscapeLeft</string>
|
||||
<string>UIInterfaceOrientationLandscapeRight</string>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 18 KiB |
@ -1,2 +0,0 @@
|
||||
/* Localized versions of Info.plist keys */
|
||||
|
||||
@ -1,128 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="10117" systemVersion="15F34" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" initialViewController="J5d-9g-n8O">
|
||||
<dependencies>
|
||||
<deployment identifier="iOS"/>
|
||||
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="10085"/>
|
||||
</dependencies>
|
||||
<scenes>
|
||||
<!--View Controller-->
|
||||
<scene sceneID="6me-oX-IDw">
|
||||
<objects>
|
||||
<tableViewController id="X5f-jW-I9m" customClass="TCViewController" sceneMemberID="viewController">
|
||||
<tableView key="view" opaque="NO" clipsSubviews="YES" clearsContextBeforeDrawing="NO" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="prototypes" style="plain" separatorStyle="default" allowsSelection="NO" rowHeight="44" sectionHeaderHeight="22" sectionFooterHeight="22" id="RXu-lL-Fvu">
|
||||
<rect key="frame" x="0.0" y="0.0" width="320" height="480"/>
|
||||
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
|
||||
<color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
|
||||
<textView key="tableFooterView" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" scrollEnabled="NO" id="rfU-78-BK7">
|
||||
<rect key="frame" x="0.0" y="174" width="320" height="48"/>
|
||||
<autoresizingMask key="autoresizingMask" widthSizable="YES"/>
|
||||
<color key="backgroundColor" red="0.90196079015731812" green="0.90196079015731812" blue="0.90196079015731812" alpha="1" colorSpace="calibratedRGB"/>
|
||||
<color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
|
||||
<fontDescription key="fontDescription" type="boldSystem" pointSize="14"/>
|
||||
<textInputTraits key="textInputTraits" autocapitalizationType="sentences"/>
|
||||
<connections>
|
||||
<outlet property="delegate" destination="X5f-jW-I9m" id="wFD-6X-WBc"/>
|
||||
</connections>
|
||||
</textView>
|
||||
<prototypes>
|
||||
<tableViewCell contentMode="scaleToFill" selectionStyle="blue" hidesAccessoryWhenEditing="NO" indentationLevel="1" indentationWidth="0.0" reuseIdentifier="SentCell" id="bz8-oG-fQA" customClass="TCChatCell">
|
||||
<rect key="frame" x="0.0" y="86" width="320" height="44"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="bz8-oG-fQA" id="ZUj-kZ-dtZ">
|
||||
<rect key="frame" x="0.0" y="0.0" width="320" height="43"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<subviews>
|
||||
<textView clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" scrollEnabled="NO" editable="NO" text="blah" id="5Mf-2x-lct">
|
||||
<rect key="frame" x="0.0" y="0.0" width="340" height="43"/>
|
||||
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
|
||||
<color key="backgroundColor" red="1" green="0.80000001192092896" blue="0.40000000596046448" alpha="1" colorSpace="calibratedRGB"/>
|
||||
<fontDescription key="fontDescription" type="system" pointSize="14"/>
|
||||
<textInputTraits key="textInputTraits" autocapitalizationType="sentences"/>
|
||||
<dataDetectorType key="dataDetectorTypes" phoneNumber="YES" link="YES" address="YES"/>
|
||||
<connections>
|
||||
<outlet property="delegate" destination="RXu-lL-Fvu" id="gq9-g4-aL4"/>
|
||||
</connections>
|
||||
</textView>
|
||||
</subviews>
|
||||
</tableViewCellContentView>
|
||||
<color key="backgroundColor" red="0.40000000596046448" green="0.80000001192092896" blue="1" alpha="1" colorSpace="calibratedRGB"/>
|
||||
<connections>
|
||||
<outlet property="textView" destination="5Mf-2x-lct" id="9XD-07-EiF"/>
|
||||
</connections>
|
||||
</tableViewCell>
|
||||
<tableViewCell contentMode="scaleToFill" selectionStyle="blue" hidesAccessoryWhenEditing="NO" indentationLevel="1" indentationWidth="0.0" reuseIdentifier="ReceivedCell" id="RDH-ix-a2K" customClass="TCChatCell">
|
||||
<rect key="frame" x="0.0" y="130" width="320" height="44"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="RDH-ix-a2K" id="HND-fP-cKl">
|
||||
<rect key="frame" x="0.0" y="0.0" width="320" height="43"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<subviews>
|
||||
<textView clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" scrollEnabled="NO" editable="NO" text="blah" id="D4G-dV-Fxa">
|
||||
<rect key="frame" x="0.0" y="0.0" width="340" height="43"/>
|
||||
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
|
||||
<color key="backgroundColor" red="0.80000001192092896" green="1" blue="0.40000000596046448" alpha="1" colorSpace="calibratedRGB"/>
|
||||
<fontDescription key="fontDescription" type="system" pointSize="14"/>
|
||||
<textInputTraits key="textInputTraits" autocapitalizationType="sentences"/>
|
||||
<dataDetectorType key="dataDetectorTypes" phoneNumber="YES" link="YES" address="YES"/>
|
||||
<connections>
|
||||
<outlet property="delegate" destination="RXu-lL-Fvu" id="R8T-eM-Gx7"/>
|
||||
</connections>
|
||||
</textView>
|
||||
</subviews>
|
||||
</tableViewCellContentView>
|
||||
<color key="backgroundColor" red="0.40000000600000002" green="0.80000001190000003" blue="1" alpha="1" colorSpace="calibratedRGB"/>
|
||||
<connections>
|
||||
<outlet property="textView" destination="D4G-dV-Fxa" id="uY3-zG-DIh"/>
|
||||
</connections>
|
||||
</tableViewCell>
|
||||
</prototypes>
|
||||
<connections>
|
||||
<outlet property="dataSource" destination="X5f-jW-I9m" id="L9s-pB-HYL"/>
|
||||
<outlet property="delegate" destination="X5f-jW-I9m" id="ikq-4l-mw5"/>
|
||||
</connections>
|
||||
</tableView>
|
||||
<navigationItem key="navigationItem" id="hu8-ml-uHB">
|
||||
<barButtonItem key="leftBarButtonItem" title="Ping" id="zLH-d1-wAa">
|
||||
<connections>
|
||||
<action selector="sendPing:" destination="X5f-jW-I9m" id="y6C-K5-50Q"/>
|
||||
</connections>
|
||||
</barButtonItem>
|
||||
<barButtonItem key="rightBarButtonItem" systemItem="refresh" id="cNK-1A-b66">
|
||||
<connections>
|
||||
<action selector="reconnect:" destination="X5f-jW-I9m" id="yjV-1U-Tjn"/>
|
||||
</connections>
|
||||
</barButtonItem>
|
||||
</navigationItem>
|
||||
<connections>
|
||||
<outlet property="inputView" destination="rfU-78-BK7" id="emF-S6-iR0"/>
|
||||
</connections>
|
||||
</tableViewController>
|
||||
<placeholder placeholderIdentifier="IBFirstResponder" id="KsG-hH-48N" userLabel="First Responder" sceneMemberID="firstResponder"/>
|
||||
</objects>
|
||||
<point key="canvasLocation" x="676" y="93"/>
|
||||
</scene>
|
||||
<!--Navigation Controller-->
|
||||
<scene sceneID="nGX-KT-vxI">
|
||||
<objects>
|
||||
<navigationController id="J5d-9g-n8O" sceneMemberID="viewController">
|
||||
<toolbarItems/>
|
||||
<navigationBar key="navigationBar" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" id="8yP-KL-gkV">
|
||||
<rect key="frame" x="0.0" y="0.0" width="320" height="44"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
</navigationBar>
|
||||
<nil name="viewControllers"/>
|
||||
<connections>
|
||||
<segue destination="X5f-jW-I9m" kind="relationship" relationship="rootViewController" id="3EC-DA-AY5"/>
|
||||
</connections>
|
||||
</navigationController>
|
||||
<placeholder placeholderIdentifier="IBFirstResponder" id="DyG-Ww-kME" userLabel="First Responder" sceneMemberID="firstResponder"/>
|
||||
</objects>
|
||||
<point key="canvasLocation" x="227" y="65"/>
|
||||
</scene>
|
||||
</scenes>
|
||||
<simulatedMetricsContainer key="defaultSimulatedMetrics">
|
||||
<simulatedStatusBarMetrics key="statusBar"/>
|
||||
<simulatedOrientationMetrics key="orientation"/>
|
||||
<simulatedScreenMetrics key="destination"/>
|
||||
</simulatedMetricsContainer>
|
||||
</document>
|
||||
@ -1,19 +0,0 @@
|
||||
//
|
||||
// Copyright 2012 Square Inc.
|
||||
// Portions Copyright (c) 2016-present, Facebook, Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the license found in the
|
||||
// LICENSE-examples file in the root directory of this source tree.
|
||||
//
|
||||
|
||||
#import <UIKit/UIKit.h>
|
||||
|
||||
#import "TCAppDelegate.h"
|
||||
|
||||
int main(int argc, char *argv[])
|
||||
{
|
||||
@autoreleasepool {
|
||||
return UIApplicationMain(argc, argv, nil, NSStringFromClass([TCAppDelegate class]));
|
||||
}
|
||||
}
|
||||
@ -1,3 +0,0 @@
|
||||
With the latest weekly go:
|
||||
|
||||
go run chatroom.go
|
||||
@ -1,70 +0,0 @@
|
||||
//
|
||||
// Copyright 2012 Square Inc.
|
||||
// Portions Copyright (c) 2016-present, Facebook, Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the license found in the
|
||||
// LICENSE-examples file in the root directory of this source tree.
|
||||
//
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"code.google.com/p/go.net/websocket"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// Msg stores both the message and the connection
|
||||
type Msg struct {
|
||||
sender *websocket.Conn
|
||||
msg string
|
||||
}
|
||||
|
||||
func run(reg chan *websocket.Conn, unreg chan *websocket.Conn, msg chan Msg) {
|
||||
conns := make(map[*websocket.Conn]int)
|
||||
for {
|
||||
select {
|
||||
case c := <-reg:
|
||||
conns[c] = 1
|
||||
case c := <-unreg:
|
||||
delete(conns, c)
|
||||
case msg := <-msg:
|
||||
for c := range conns {
|
||||
if c != msg.sender {
|
||||
websocket.Message.Send(c, msg.msg)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func newChatServer(reg chan *websocket.Conn, unreg chan *websocket.Conn, msg chan Msg) websocket.Handler {
|
||||
return func(ws *websocket.Conn) {
|
||||
reg <- ws
|
||||
for {
|
||||
var message string
|
||||
err := websocket.Message.Receive(ws, &message)
|
||||
if err != nil {
|
||||
unreg <- ws
|
||||
break
|
||||
}
|
||||
msg <- Msg{ws, message}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
reg := make(chan *websocket.Conn)
|
||||
unreg := make(chan *websocket.Conn)
|
||||
msg := make(chan Msg)
|
||||
|
||||
http.Handle("/chat", websocket.Handler(newChatServer(reg, unreg, msg)))
|
||||
http.Handle("/", http.FileServer(http.Dir("../static")))
|
||||
|
||||
go run(reg, unreg, msg)
|
||||
|
||||
err := http.ListenAndServe(":9000", nil)
|
||||
if err != nil {
|
||||
panic("ListenAndServe: " + err.Error())
|
||||
}
|
||||
}
|
||||
@ -1,86 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# Copyright 2012 Square Inc.
|
||||
# Portions Copyright (c) 2016-present, Facebook, Inc.
|
||||
# All rights reserved.
|
||||
#
|
||||
# This source code is licensed under the license found in the
|
||||
# LICENSE-examples file in the root directory of this source tree.
|
||||
#
|
||||
|
||||
import tornado
|
||||
import tornado.web
|
||||
import tornado.websocket
|
||||
import tornado.options
|
||||
|
||||
import os
|
||||
|
||||
import json
|
||||
import uuid
|
||||
|
||||
import argparse
|
||||
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger('gateway')
|
||||
|
||||
args = None
|
||||
|
||||
def parse_args():
|
||||
global args
|
||||
static_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'static'))
|
||||
parser = argparse.ArgumentParser(description='Gateway server')
|
||||
|
||||
parser.add_argument('-v', '--verbose', help='verbose logging', action='store_true')
|
||||
|
||||
parser.add_argument('-s', '--static-path', help='path for static files [default: %(default)s]', default=static_path)
|
||||
|
||||
parser.add_argument('-p', '--listen-port', help='port to listen on [default: %(default)s]', default=9000, type=int, metavar='PORT')
|
||||
parser.add_argument('-i', '--listen-interface', help='interface to listen on. [default: %(default)s]', default='0.0.0.0', metavar='IFACE')
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
|
||||
connections = set()
|
||||
|
||||
class ChatHandler(tornado.websocket.WebSocketHandler):
|
||||
def open(self):
|
||||
connections.add(self)
|
||||
return None
|
||||
|
||||
def on_message(self, msg):
|
||||
for c in connections:
|
||||
if c is self:
|
||||
continue
|
||||
c.write_message(msg)
|
||||
|
||||
def on_close(self):
|
||||
connections.remove(self)
|
||||
|
||||
|
||||
def main():
|
||||
global logger
|
||||
#tornado.options.parse_command_line()
|
||||
|
||||
parse_args()
|
||||
|
||||
if args.verbose:
|
||||
tornado.options.enable_pretty_logging()
|
||||
logger = logging.getLogger()
|
||||
logger.setLevel(logging.INFO)
|
||||
|
||||
|
||||
application = tornado.web.Application([
|
||||
(r"/chat", ChatHandler),
|
||||
(r"/(.*)", tornado.web.StaticFileHandler, {"path": args.static_path, "default_filename":'index.html'}),
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
print "Listening on %s:%s" % (args.listen_interface, args.listen_port)
|
||||
application.listen(args.listen_port, args.listen_interface)
|
||||
tornado.ioloop.IOLoop.instance().start()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
1
TestChatServer/static/.gitignore
vendored
1
TestChatServer/static/.gitignore
vendored
@ -1 +0,0 @@
|
||||
devtools/
|
||||
@ -1,38 +0,0 @@
|
||||
<!DOCTYPE HTML>
|
||||
<html>
|
||||
<head>
|
||||
<script src='proxy.js'>
|
||||
</script>
|
||||
<style type='text/css'>
|
||||
html {
|
||||
background-color: rgb(48,48, 48);
|
||||
color: rgb(221, 190, 120);
|
||||
font-family: "HelveticaNeue", Helvetica, Arial;
|
||||
}
|
||||
|
||||
a {
|
||||
color: rgb(193, 127, 128);
|
||||
}
|
||||
#info_div {
|
||||
font-size:small;
|
||||
color: rgb(108, 144, 100);
|
||||
}
|
||||
|
||||
.device_details {
|
||||
font-size:small;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h3>Chat History</h3>
|
||||
<ul id='history'>
|
||||
</ul>
|
||||
<form id="msg_form">
|
||||
<input type='text' name='message' id='msg_field'/>
|
||||
<input type='submit'/>
|
||||
</form>
|
||||
|
||||
<ul id='client_list'></ul>
|
||||
<div id='info_div'></div>
|
||||
</body>
|
||||
</html>
|
||||
@ -1,81 +0,0 @@
|
||||
//
|
||||
// Copyright 2012 Square Inc.
|
||||
// Portions Copyright (c) 2016-present, Facebook, Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the license found in the
|
||||
// LICENSE-examples file in the root directory of this source tree.
|
||||
//
|
||||
|
||||
function SocketClient () {
|
||||
this.list_elem = document.getElementById('client_list');
|
||||
this.info_div = document.getElementById('info_div');
|
||||
var self = this;
|
||||
}
|
||||
|
||||
SocketClient.prototype.connect = function () {
|
||||
var self = this;
|
||||
|
||||
this.list_elem.innerHTML = '';
|
||||
this.info_div.innerHTML = 'status: connecting...';
|
||||
this.socket = new WebSocket("ws://" + document.location.host + "/chat");
|
||||
|
||||
this.socket.onopen = function () {self.onopen.apply(self, arguments);};
|
||||
this.socket.onmessage = function () {self.onmessage.apply(self, arguments);};
|
||||
this.socket.onclose = function () {self.onclose.apply(self, arguments);};
|
||||
};
|
||||
|
||||
SocketClient.prototype.deviceAdded = function (params) {
|
||||
var el = document.createElement('li');
|
||||
el.innerHTML = '<a href="devtools/devtools.html?host=' + document.location.host + '&page=' + params.page + '">' + params.device_name + '</a>' + ' <span class="device_details">(' + params.app_id + ', ' + params.device_model + ', ' + params.device_id + ')</span>';
|
||||
this.list_elem.appendChild(el);
|
||||
this.visibleElems[params.connection_id] = el;
|
||||
};
|
||||
|
||||
SocketClient.prototype.deviceRemoved = function (params) {
|
||||
var li = this.visibleElems[params.connection_id];
|
||||
li.parentNode.removeChild(li);
|
||||
};
|
||||
|
||||
SocketClient.prototype.onopen = function () {
|
||||
this.info_div.innerHTML = 'status: connected to gateway';
|
||||
this.list_elem.innerHTML = '';
|
||||
this.visibleElems = {};
|
||||
console.log('connection to gateway opened');
|
||||
};
|
||||
|
||||
SocketClient.prototype.onmessage = function (message) {
|
||||
var el = document.createElement('li');
|
||||
el.innerHTML = message.data;
|
||||
window.document.getElementById('history').appendChild(el);
|
||||
};
|
||||
|
||||
SocketClient.prototype.onclose = function () {
|
||||
var retryInterval = 1000.0;
|
||||
console.log('connection closed, retrying in ' + (retryInterval/1000.0) + ' seconds');
|
||||
var self = this;
|
||||
window.setTimeout(function () {self.connect();}, retryInterval);
|
||||
};
|
||||
|
||||
|
||||
window.addEventListener('load', function () {
|
||||
var form = window.document.getElementById('msg_form');
|
||||
var msg_field = window.document.getElementById('msg_field');
|
||||
|
||||
var socketClient = new SocketClient();
|
||||
socketClient.connect()
|
||||
|
||||
form.onsubmit = function () {
|
||||
msg = msg_field.value;
|
||||
msg_field.value = '';
|
||||
|
||||
socketClient.socket.send(msg);
|
||||
|
||||
var el = document.createElement('li');
|
||||
el.innerHTML = msg;
|
||||
window.document.getElementById('history').appendChild(el);
|
||||
|
||||
return false;
|
||||
};
|
||||
}
|
||||
);
|
||||
@ -1,7 +0,0 @@
|
||||
{
|
||||
"url": "ws://127.0.0.1:9001",
|
||||
"outdir": "./pages/results",
|
||||
"cases": ["*"],
|
||||
"exclude-cases": [],
|
||||
"exclude-agent-cases": {}
|
||||
}
|
||||
@ -1,18 +0,0 @@
|
||||
#
|
||||
# Copyright (c) 2016-present, Facebook, Inc.
|
||||
# All rights reserved.
|
||||
#
|
||||
# This source code is licensed under the license found in the
|
||||
# LICENSE-examples file in the root directory of this source tree.
|
||||
#
|
||||
|
||||
PYENV_PATH=$(pwd)/.env
|
||||
|
||||
echo $PYENV_PATH
|
||||
if [ -d "$PYENV_PATH" ]; then
|
||||
source $PYENV_PATH/bin/activate
|
||||
$PYENV_PATH/bin/wstest -m fuzzingserver -s TestSupport/autobahn_fuzzingserver.json
|
||||
else
|
||||
echo "Python Virtualenv not set up. Please run './TestSupport/setup_env.sh .env' first."
|
||||
fi
|
||||
|
||||
@ -1,36 +0,0 @@
|
||||
#
|
||||
# Copyright (c) 2016-present, Facebook, Inc.
|
||||
# All rights reserved.
|
||||
#
|
||||
# This source code is licensed under the license found in the
|
||||
# LICENSE-examples file in the root directory of this source tree.
|
||||
#
|
||||
|
||||
VIRTUALENV_PATH=$1
|
||||
VIRTUALENV_VERSION=15.0.1
|
||||
|
||||
if [ -d "$VIRTUALENV_PATH" ]; then
|
||||
echo "Virtual Env already installed"
|
||||
elif [ -z "$VIRTUALENV_PATH" ]; then
|
||||
echo "Usage: ./setup_env.sh <folder path>"
|
||||
else
|
||||
mkdir $VIRTUALENV_PATH
|
||||
|
||||
pushd $VIRTUALENV_PATH
|
||||
|
||||
curl -L -o virtualenv.tar.gz https://pypi.python.org/packages/source/v/virtualenv/virtualenv-$VIRTUALENV_VERSION.tar.gz
|
||||
tar xvfz virtualenv.tar.gz
|
||||
|
||||
pushd virtualenv-$VIRTUALENV_VERSION
|
||||
python setup.py install --user
|
||||
popd
|
||||
|
||||
popd
|
||||
|
||||
python $VIRTUALENV_PATH/virtualenv-$VIRTUALENV_VERSION/virtualenv.py $VIRTUALENV_PATH
|
||||
|
||||
source $VIRTUALENV_PATH/bin/activate
|
||||
pip install autobahntestsuite
|
||||
|
||||
echo "Environment succesfully set up in $VIRTUALENV_PATH."
|
||||
fi
|
||||
@ -1,41 +0,0 @@
|
||||
//
|
||||
// Copyright (c) 2016-present, Facebook, Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the BSD-style license found in the
|
||||
// LICENSE file in the root directory of this source tree. An additional grant
|
||||
// of patent rights can be found in the PATENTS file in the same directory.
|
||||
//
|
||||
|
||||
#import "SRTWebSocketOperation.h"
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
typedef void(^SRAutobahnSocketTextMessageHandler)(SRWebSocket *socket, NSString * _Nullable message);
|
||||
typedef void(^SRAutobahnSocketDataMessageHandler)(SRWebSocket *socket, NSData * _Nullable message);
|
||||
|
||||
@interface SRAutobahnOperation : SRTWebSocketOperation
|
||||
|
||||
- (instancetype)initWithServerURL:(NSURL *)url
|
||||
testCommandPath:(NSString *)path
|
||||
caseNumber:(nullable NSNumber *)caseNumber
|
||||
agent:(nullable NSString *)agent
|
||||
textMessageHandler:(nullable SRAutobahnSocketTextMessageHandler)textMessageHandler
|
||||
dataMessageHandler:(nullable SRAutobahnSocketDataMessageHandler)dataMessageHandler;
|
||||
|
||||
@end
|
||||
|
||||
extern SRAutobahnOperation *SRAutobahnTestOperation(NSURL *serverURL, NSInteger caseNumber, NSString *agent);
|
||||
|
||||
typedef void(^SRAutobahnTestResultHandler)(NSDictionary *_Nullable result);
|
||||
extern SRAutobahnOperation *SRAutobahnTestResultOperation(NSURL *serverURL, NSInteger caseNumber, NSString *agent, SRAutobahnTestResultHandler handler);
|
||||
|
||||
typedef void(^SRAutobahnTestCaseInfoHandler)(NSDictionary *_Nullable caseInfo);
|
||||
extern SRAutobahnOperation *SRAutobahnTestCaseInfoOperation(NSURL *serverURL, NSInteger caseNumber, SRAutobahnTestCaseInfoHandler handler);
|
||||
|
||||
typedef void(^SRAutobahnTestCaseCountHandler)(NSInteger caseCount);
|
||||
extern SRAutobahnOperation *SRAutobahnTestCaseCountOperation(NSURL *serverURL, NSString *agent, SRAutobahnTestCaseCountHandler handler);
|
||||
|
||||
extern SRAutobahnOperation *SRAutobahnTestUpdateReportsOperation(NSURL *serverURL, NSString *agent);
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
@ -1,131 +0,0 @@
|
||||
//
|
||||
// Copyright (c) 2016-present, Facebook, Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the BSD-style license found in the
|
||||
// LICENSE file in the root directory of this source tree. An additional grant
|
||||
// of patent rights can be found in the PATENTS file in the same directory.
|
||||
//
|
||||
|
||||
#import "SRAutobahnOperation.h"
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@interface SRAutobahnOperation ()
|
||||
|
||||
@property (nullable, nonatomic, copy, readonly) SRAutobahnSocketTextMessageHandler textMessageHandler;
|
||||
@property (nullable, nonatomic, copy, readonly) SRAutobahnSocketDataMessageHandler dataMessageHandler;
|
||||
|
||||
@end
|
||||
|
||||
@implementation SRAutobahnOperation
|
||||
|
||||
- (instancetype)initWithServerURL:(NSURL *)url
|
||||
testCommandPath:(NSString *)path
|
||||
caseNumber:(nullable NSNumber *)caseNumber
|
||||
agent:(nullable NSString *)agent
|
||||
textMessageHandler:(nullable SRAutobahnSocketTextMessageHandler)textMessageHandler
|
||||
dataMessageHandler:(nullable SRAutobahnSocketDataMessageHandler)dataMessageHandler
|
||||
{
|
||||
NSURLComponents *components = [NSURLComponents componentsWithURL:url resolvingAgainstBaseURL:NO];
|
||||
components.path = (components.path ? [components.path stringByAppendingPathComponent:path] : path);
|
||||
|
||||
NSMutableArray<NSURLQueryItem *> *queryItems = [NSMutableArray arrayWithCapacity:2];
|
||||
if (caseNumber) {
|
||||
[queryItems addObject:[NSURLQueryItem queryItemWithName:@"case" value:caseNumber.stringValue]];
|
||||
}
|
||||
if (agent) {
|
||||
[queryItems addObject:[NSURLQueryItem queryItemWithName:@"agent" value:agent]];
|
||||
}
|
||||
components.queryItems = queryItems;
|
||||
self = [self initWithURL:components.URL];
|
||||
if (!self) return self;
|
||||
|
||||
_textMessageHandler = [textMessageHandler copy];
|
||||
_dataMessageHandler = [dataMessageHandler copy];
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessageWithString:(NSString *)string
|
||||
{
|
||||
if (self.textMessageHandler) {
|
||||
self.textMessageHandler(webSocket, string);
|
||||
}
|
||||
}
|
||||
|
||||
- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessageWithData:(NSData *)data
|
||||
{
|
||||
if (self.dataMessageHandler) {
|
||||
self.dataMessageHandler(webSocket, data);
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
SRAutobahnOperation *SRAutobahnTestOperation(NSURL *serverURL, NSInteger caseNumber, NSString *agent)
|
||||
{
|
||||
return [[SRAutobahnOperation alloc] initWithServerURL:serverURL
|
||||
testCommandPath:@"/runCase"
|
||||
caseNumber:@(caseNumber)
|
||||
agent:agent
|
||||
textMessageHandler:^(SRWebSocket * _Nonnull socket, NSString * _Nullable message) {
|
||||
[socket sendString:message error:nil];
|
||||
}
|
||||
dataMessageHandler:^(SRWebSocket * _Nonnull socket, NSData * _Nullable message) {
|
||||
[socket sendData:message error:nil];
|
||||
}];
|
||||
}
|
||||
|
||||
extern SRAutobahnOperation *SRAutobahnTestResultOperation(NSURL *serverURL, NSInteger caseNumber, NSString *agent, SRAutobahnTestResultHandler handler)
|
||||
{
|
||||
return [[SRAutobahnOperation alloc] initWithServerURL:serverURL
|
||||
testCommandPath:@"/getCaseStatus"
|
||||
caseNumber:@(caseNumber)
|
||||
agent:agent
|
||||
textMessageHandler:^(SRWebSocket * _Nonnull socket, NSString * _Nullable message) {
|
||||
NSData *messageData = [message dataUsingEncoding:NSUTF8StringEncoding];
|
||||
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:messageData options:0 error:NULL];
|
||||
handler(result);
|
||||
}
|
||||
dataMessageHandler:nil];
|
||||
}
|
||||
|
||||
extern SRAutobahnOperation *SRAutobahnTestCaseInfoOperation(NSURL *serverURL, NSInteger caseNumber, SRAutobahnTestCaseInfoHandler handler)
|
||||
{
|
||||
return [[SRAutobahnOperation alloc] initWithServerURL:serverURL
|
||||
testCommandPath:@"/getCaseInfo"
|
||||
caseNumber:@(caseNumber)
|
||||
agent:nil
|
||||
textMessageHandler:^(SRWebSocket * _Nonnull socket, NSString * _Nullable message) {
|
||||
NSData *messageData = [message dataUsingEncoding:NSUTF8StringEncoding];
|
||||
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:messageData options:0 error:NULL];
|
||||
handler(result);
|
||||
}
|
||||
dataMessageHandler:nil];
|
||||
}
|
||||
|
||||
extern SRAutobahnOperation *SRAutobahnTestCaseCountOperation(NSURL *serverURL, NSString *agent, SRAutobahnTestCaseCountHandler handler)
|
||||
{
|
||||
return [[SRAutobahnOperation alloc] initWithServerURL:serverURL
|
||||
testCommandPath:@"/getCaseCount"
|
||||
caseNumber:nil
|
||||
agent:agent
|
||||
textMessageHandler:^(SRWebSocket * _Nonnull socket, NSString * _Nullable message) {
|
||||
NSInteger count = [message integerValue];
|
||||
handler(count);
|
||||
}
|
||||
dataMessageHandler:nil];
|
||||
}
|
||||
|
||||
extern SRAutobahnOperation *SRAutobahnTestUpdateReportsOperation(NSURL *serverURL, NSString *agent)
|
||||
{
|
||||
return [[SRAutobahnOperation alloc] initWithServerURL:serverURL
|
||||
testCommandPath:@"/updateReports"
|
||||
caseNumber:nil
|
||||
agent:agent
|
||||
textMessageHandler:nil
|
||||
dataMessageHandler:nil];
|
||||
}
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
@ -1,29 +0,0 @@
|
||||
//
|
||||
// Copyright 2012 Square Inc.
|
||||
// Portions Copyright (c) 2016-present, Facebook, Inc.
|
||||
//
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the BSD-style license found in the
|
||||
// LICENSE file in the root directory of this source tree. An additional grant
|
||||
// of patent rights can be found in the PATENTS file in the same directory.
|
||||
//
|
||||
|
||||
#import <SocketRocket/SRWebSocket.h>
|
||||
|
||||
@interface SRTWebSocketOperation : NSOperation <SRWebSocketDelegate>
|
||||
|
||||
@property (nonatomic) BOOL isFinished;
|
||||
@property (nonatomic) BOOL isExecuting;
|
||||
|
||||
@property (nonatomic, strong, readonly) NSError *error;
|
||||
|
||||
- (instancetype)initWithURL:(NSURL *)URL;
|
||||
|
||||
// We override these methods. Please call super
|
||||
- (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean NS_REQUIRES_SUPER;
|
||||
- (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error NS_REQUIRES_SUPER;
|
||||
|
||||
- (BOOL)waitUntilFinishedWithTimeout:(NSTimeInterval)timeout;
|
||||
|
||||
@end
|
||||
@ -1,91 +0,0 @@
|
||||
//
|
||||
// Copyright 2012 Square Inc.
|
||||
// Portions Copyright (c) 2016-present, Facebook, Inc.
|
||||
//
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the BSD-style license found in the
|
||||
// LICENSE file in the root directory of this source tree. An additional grant
|
||||
// of patent rights can be found in the PATENTS file in the same directory.
|
||||
//
|
||||
|
||||
#import "SRTWebSocketOperation.h"
|
||||
|
||||
#import "SRAutobahnUtilities.h"
|
||||
|
||||
@interface SRTWebSocketOperation ()
|
||||
|
||||
@end
|
||||
|
||||
@implementation SRTWebSocketOperation {
|
||||
NSInteger _testNumber;
|
||||
SRWebSocket *_webSocket;
|
||||
NSURL *_url;
|
||||
}
|
||||
|
||||
@synthesize isFinished = _isFinished;
|
||||
@synthesize isExecuting = _isExecuting;
|
||||
@synthesize error = _error;
|
||||
|
||||
- (instancetype)initWithURL:(NSURL *)URL;
|
||||
{
|
||||
self = [super init];
|
||||
if (self) {
|
||||
_url = URL;
|
||||
_isExecuting = NO;
|
||||
_isFinished = NO;
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (BOOL)isConcurrent;
|
||||
{
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (void)start;
|
||||
{
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
_webSocket = [[SRWebSocket alloc] initWithURLRequest:[NSURLRequest requestWithURL:_url]];
|
||||
_webSocket.delegate = self;
|
||||
[_webSocket open];
|
||||
});
|
||||
self.isExecuting = YES;
|
||||
}
|
||||
|
||||
- (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean;
|
||||
{
|
||||
[self willChangeValueForKey:@"isExecuting"];
|
||||
[self willChangeValueForKey:@"isFinished"];
|
||||
_isFinished = YES;
|
||||
_isExecuting = NO;
|
||||
[self didChangeValueForKey:@"isExecuting"];
|
||||
[self didChangeValueForKey:@"isFinished"];
|
||||
_webSocket.delegate = nil;
|
||||
_webSocket = nil;
|
||||
}
|
||||
|
||||
- (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error;
|
||||
{
|
||||
_error = error;
|
||||
[self willChangeValueForKey:@"isExecuting"];
|
||||
[self willChangeValueForKey:@"isFinished"];
|
||||
_isFinished = YES;
|
||||
_isExecuting = NO;
|
||||
[self didChangeValueForKey:@"isExecuting"];
|
||||
[self didChangeValueForKey:@"isFinished"];
|
||||
_webSocket.delegate = nil;
|
||||
_webSocket = nil;
|
||||
}
|
||||
|
||||
- (BOOL)waitUntilFinishedWithTimeout:(NSTimeInterval)timeout
|
||||
{
|
||||
if (self.isFinished) {
|
||||
return YES;
|
||||
}
|
||||
return SRRunLoopRunUntil(^BOOL{
|
||||
return self.isFinished;
|
||||
}, timeout);
|
||||
}
|
||||
|
||||
@end
|
||||
@ -1,22 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleDevelopmentRegion</key>
|
||||
<string>en</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>${EXECUTABLE_NAME}</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>BNDL</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>1.0</string>
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>1</string>
|
||||
</dict>
|
||||
</plist>
|
||||
@ -1,15 +0,0 @@
|
||||
{
|
||||
"UNIMPLEMENTED": [
|
||||
"12",
|
||||
"13"
|
||||
],
|
||||
"NON-STRICT": [
|
||||
"6.4.2",
|
||||
"6.4.4",
|
||||
],
|
||||
"INFORMATIONAL": [
|
||||
"7.1.6",
|
||||
"7.13.1",
|
||||
"7.13.2"
|
||||
]
|
||||
}
|
||||
@ -1,146 +0,0 @@
|
||||
//
|
||||
// Copyright 2012 Square Inc.
|
||||
// Portions Copyright (c) 2016-present, Facebook, Inc.
|
||||
//
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the BSD-style license found in the
|
||||
// LICENSE file in the root directory of this source tree. An additional grant
|
||||
// of patent rights can be found in the PATENTS file in the same directory.
|
||||
//
|
||||
|
||||
@import XCTest;
|
||||
@import ObjectiveC;
|
||||
|
||||
#import <SocketRocket/SRWebSocket.h>
|
||||
|
||||
#import "SRTWebSocketOperation.h"
|
||||
#import "SRAutobahnOperation.h"
|
||||
#import "SRAutobahnUtilities.h"
|
||||
|
||||
@interface SRAutobahnTests : XCTestCase
|
||||
@end
|
||||
|
||||
@implementation SRAutobahnTests
|
||||
|
||||
///--------------------------------------
|
||||
#pragma mark - Init
|
||||
///--------------------------------------
|
||||
|
||||
/**
|
||||
This method is called if Xcode is targeting a specific test or a set of them.
|
||||
If you change this method - please make sure you test this behavior in Xcode by running all tests, then running 1+ test.
|
||||
*/
|
||||
+ (instancetype)testCaseWithSelector:(SEL)selector
|
||||
{
|
||||
NSArray<NSInvocation *> *invocations = [self testInvocations];
|
||||
for (NSInvocation *invocation in invocations) {
|
||||
if (invocation.selector == selector) {
|
||||
return [super testCaseWithSelector:selector];
|
||||
}
|
||||
}
|
||||
return nil;
|
||||
}
|
||||
|
||||
///--------------------------------------
|
||||
#pragma mark - Setup
|
||||
///--------------------------------------
|
||||
|
||||
/**
|
||||
This method is called by xctest to figure out all the tests that are available.
|
||||
All the selector names are also reported back to Xcode and displayed in Test Navigator/Console.
|
||||
*/
|
||||
+ (NSArray<NSInvocation *> *)testInvocations
|
||||
{
|
||||
__block NSArray<NSInvocation *> *array = nil;
|
||||
static dispatch_once_t onceToken;
|
||||
dispatch_once(&onceToken, ^{
|
||||
NSMutableArray<NSInvocation *> *invocations = [NSMutableArray array];
|
||||
for (NSUInteger i = 1; i <= SRAutobahnTestCaseCount(); i++) {
|
||||
NSDictionary *caseInfo = SRAutobahnTestCaseInfo(i);
|
||||
NSString *identifier = caseInfo[@"id"];
|
||||
|
||||
NSInvocation *invocation = [self invocationWithCaseNumber:i identifier:identifier];
|
||||
[invocations addObject:invocation];
|
||||
}
|
||||
|
||||
array = [invocations sortedArrayUsingComparator:^NSComparisonResult(NSInvocation *_Nonnull obj1, NSInvocation *_Nonnull obj2) {
|
||||
return [NSStringFromSelector(obj1.selector) compare:NSStringFromSelector(obj2.selector) options:NSNumericSearch];
|
||||
}];
|
||||
});
|
||||
return array;
|
||||
}
|
||||
|
||||
+ (NSInvocation *)invocationWithCaseNumber:(NSUInteger)caseNumber identifier:(NSString *)identifier
|
||||
{
|
||||
SEL selector = [self addInstanceMethodForTestCaseNumber:caseNumber identifier:identifier];
|
||||
NSMethodSignature *signature = [self instanceMethodSignatureForSelector:selector];
|
||||
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
|
||||
invocation.selector = selector;
|
||||
return invocation;
|
||||
}
|
||||
|
||||
+ (SEL)addInstanceMethodForTestCaseNumber:(NSInteger)caseNumber identifier:(NSString *)identifier
|
||||
{
|
||||
NSString *selectorName = [NSString stringWithFormat:@"Case #%@", identifier];
|
||||
SEL selector = NSSelectorFromString(selectorName);
|
||||
|
||||
IMP implementation = imp_implementationWithBlock(^(SRAutobahnTests *sself) {
|
||||
[sself performTestWithCaseNumber:caseNumber identifier:identifier];
|
||||
});
|
||||
NSString *typeString = [NSString stringWithFormat:@"%s%s%s", @encode(id), @encode(id), @encode(SEL)];
|
||||
class_addMethod(self, selector, implementation, typeString.UTF8String);
|
||||
|
||||
return selector;
|
||||
}
|
||||
|
||||
///--------------------------------------
|
||||
#pragma mark - Teardown
|
||||
///--------------------------------------
|
||||
|
||||
+ (void)tearDown
|
||||
{
|
||||
[self updateReports];
|
||||
[super tearDown];
|
||||
}
|
||||
|
||||
+ (void)updateReports
|
||||
{
|
||||
SRAutobahnOperation *operation = SRAutobahnTestUpdateReportsOperation(SRAutobahnTestServerURL(), SRAutobahnTestAgentName());
|
||||
[operation start];
|
||||
|
||||
NSAssert([operation waitUntilFinishedWithTimeout:60], @"Timed out on updating reports.");
|
||||
NSAssert(!operation.error, @"Updating the report should not have errored %@", operation.error);
|
||||
}
|
||||
|
||||
///--------------------------------------
|
||||
#pragma mark - Test
|
||||
///--------------------------------------
|
||||
|
||||
- (void)performTestWithCaseNumber:(NSInteger)caseNumber identifier:(NSString *)identifier
|
||||
{
|
||||
NSURL *serverURL = SRAutobahnTestServerURL();
|
||||
NSString *agent = SRAutobahnTestAgentName();
|
||||
|
||||
NSOperationQueue *testQueue = [[NSOperationQueue alloc] init];
|
||||
testQueue.maxConcurrentOperationCount = 1;
|
||||
|
||||
SRAutobahnOperation *testOp = SRAutobahnTestOperation(serverURL, caseNumber, agent);
|
||||
[testQueue addOperation:testOp];
|
||||
|
||||
__block NSDictionary *resultInfo = nil;
|
||||
SRAutobahnOperation *resultOp = SRAutobahnTestResultOperation(serverURL, caseNumber, agent, ^(NSDictionary * _Nullable result) {
|
||||
resultInfo = result;
|
||||
});
|
||||
[resultOp addDependency:testOp];
|
||||
[testQueue addOperation:resultOp];
|
||||
|
||||
|
||||
XCTAssertTrue([resultOp waitUntilFinishedWithTimeout:60 * 5], @"Test operation timed out.");
|
||||
XCTAssertTrue(!testOp.error, @"Test operation should not have failed");
|
||||
if (!SRAutobahnIsValidResultBehavior(identifier, resultInfo[@"behavior"])) {
|
||||
XCTFail(@"Invalid test behavior %@ for %@.", resultInfo[@"behavior"], identifier);
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
||||
@ -1,41 +0,0 @@
|
||||
//
|
||||
// Copyright (c) 2016-present, Facebook, Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the BSD-style license found in the
|
||||
// LICENSE file in the root directory of this source tree. An additional grant
|
||||
// of patent rights can be found in the PATENTS file in the same directory.
|
||||
//
|
||||
|
||||
@import Foundation;
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
///--------------------------------------
|
||||
#pragma mark - Test Configuration
|
||||
///--------------------------------------
|
||||
|
||||
extern NSString *SRAutobahnTestAgentName(void);
|
||||
extern NSURL *SRAutobahnTestServerURL(void);
|
||||
|
||||
///--------------------------------------
|
||||
#pragma mark - Validation
|
||||
///--------------------------------------
|
||||
|
||||
extern NSDictionary<NSString *, id> *SRAutobahnTestConfiguration(void);
|
||||
extern BOOL SRAutobahnIsValidResultBehavior(NSString *caseIdentifier, NSString *behavior);
|
||||
|
||||
///--------------------------------------
|
||||
#pragma mark - Utilities
|
||||
///--------------------------------------
|
||||
|
||||
extern BOOL SRRunLoopRunUntil(BOOL (^predicate)(), NSTimeInterval timeout);
|
||||
|
||||
///--------------------------------------
|
||||
#pragma mark - Setup
|
||||
///--------------------------------------
|
||||
|
||||
extern NSUInteger SRAutobahnTestCaseCount(void);
|
||||
extern NSDictionary<NSString *, id> *SRAutobahnTestCaseInfo(NSInteger caseNumber);
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
@ -1,120 +0,0 @@
|
||||
//
|
||||
// Copyright (c) 2016-present, Facebook, Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the BSD-style license found in the
|
||||
// LICENSE file in the root directory of this source tree. An additional grant
|
||||
// of patent rights can be found in the PATENTS file in the same directory.
|
||||
//
|
||||
|
||||
#import "SRAutobahnUtilities.h"
|
||||
|
||||
#import "SRAutobahnOperation.h"
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@interface SRAutobahnUtilities : NSObject @end
|
||||
@implementation SRAutobahnUtilities @end
|
||||
|
||||
///--------------------------------------
|
||||
#pragma mark - Test Configuration
|
||||
///--------------------------------------
|
||||
|
||||
NSString *SRAutobahnTestAgentName(void)
|
||||
{
|
||||
return [NSBundle bundleForClass:[SRAutobahnUtilities class]].bundleIdentifier;
|
||||
}
|
||||
|
||||
NSURL *SRAutobahnTestServerURL(void)
|
||||
{
|
||||
return [NSURL URLWithString:@"ws://localhost:9001"];
|
||||
}
|
||||
|
||||
///--------------------------------------
|
||||
#pragma mark - Validation
|
||||
///--------------------------------------
|
||||
|
||||
NSDictionary<NSString *, id> *SRAutobahnTestConfiguration(void)
|
||||
{
|
||||
static NSDictionary *configuration;
|
||||
static dispatch_once_t onceToken;
|
||||
dispatch_once(&onceToken, ^{
|
||||
NSURL *configurationURL = [[NSBundle bundleForClass:[SRAutobahnUtilities class]] URLForResource:@"autobahn_configuration"
|
||||
withExtension:@"json"];
|
||||
NSInputStream *readStream = [NSInputStream inputStreamWithURL:configurationURL];
|
||||
[readStream open];
|
||||
configuration = [NSJSONSerialization JSONObjectWithStream:readStream options:0 error:nil];
|
||||
[readStream close];
|
||||
});
|
||||
return configuration;
|
||||
}
|
||||
|
||||
BOOL SRAutobahnIsValidResultBehavior(NSString *caseIdentifier, NSString *behavior)
|
||||
{
|
||||
if ([behavior isEqualToString:@"OK"]) {
|
||||
return YES;
|
||||
}
|
||||
|
||||
NSArray *cases = SRAutobahnTestConfiguration()[behavior];
|
||||
for (NSString *caseId in cases) {
|
||||
if ([caseIdentifier hasPrefix:caseId]) {
|
||||
return YES;
|
||||
}
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
///--------------------------------------
|
||||
#pragma mark - Utilities
|
||||
///--------------------------------------
|
||||
|
||||
BOOL SRRunLoopRunUntil(BOOL (^predicate)(), NSTimeInterval timeout)
|
||||
{
|
||||
NSDate *timeoutDate = [NSDate dateWithTimeIntervalSinceNow:timeout];
|
||||
|
||||
NSTimeInterval timeoutTime = [timeoutDate timeIntervalSinceReferenceDate];
|
||||
NSTimeInterval currentTime = [NSDate timeIntervalSinceReferenceDate];
|
||||
|
||||
while (!predicate() && currentTime < timeoutTime) {
|
||||
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
|
||||
currentTime = [NSDate timeIntervalSinceReferenceDate];
|
||||
}
|
||||
return (currentTime <= timeoutTime);
|
||||
}
|
||||
|
||||
///--------------------------------------
|
||||
#pragma mark - Setup
|
||||
///--------------------------------------
|
||||
|
||||
NSUInteger SRAutobahnTestCaseCount(void)
|
||||
{
|
||||
static NSUInteger count;
|
||||
static dispatch_once_t onceToken;
|
||||
dispatch_once(&onceToken, ^{
|
||||
SRAutobahnOperation *operation = SRAutobahnTestCaseCountOperation(SRAutobahnTestServerURL(),
|
||||
SRAutobahnTestAgentName(),
|
||||
^(NSInteger caseCount) {
|
||||
count = caseCount;
|
||||
});
|
||||
[operation start];
|
||||
|
||||
NSCAssert([operation waitUntilFinishedWithTimeout:10], @"Timed out fetching test case count.");
|
||||
NSCAssert(!operation.error, @"CaseGetter should have successfully returned the number of testCases. Instead got error %@", operation.error);
|
||||
});
|
||||
return count;
|
||||
}
|
||||
|
||||
NSDictionary<NSString *, id> *SRAutobahnTestCaseInfo(NSInteger caseNumber)
|
||||
{
|
||||
__block NSDictionary *caseInfo = nil;
|
||||
SRAutobahnOperation *operation = SRAutobahnTestCaseInfoOperation(SRAutobahnTestServerURL(), caseNumber, ^(NSDictionary * _Nullable info) {
|
||||
caseInfo = info;
|
||||
});
|
||||
[operation start];
|
||||
|
||||
NSCAssert([operation waitUntilFinishedWithTimeout:10], @"Timed out fetching test case info %ld.", (long)caseNumber);
|
||||
NSCAssert(!operation.error, @"Updating the report should not have errored");
|
||||
return caseInfo;
|
||||
}
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
1
Vendor/xctoolchain
vendored
1
Vendor/xctoolchain
vendored
@ -1 +0,0 @@
|
||||
Subproject commit a66c63fe948cf8b4d77a51b69f35459fe0c68973
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user