Repository: daltoniam/Starscream Branch: master Commit: c6bfd1af48ef Files: 72 Total size: 194.0 KB Directory structure: gitextract_a7i252zw/ ├── .github/ │ ├── ISSUE_TEMPLATE/ │ │ ├── bug_report.md │ │ ├── config.yml │ │ ├── feature_request.md │ │ └── general-question.md │ ├── pull_request_template.md │ └── workflows/ │ └── release.yml ├── .gitignore ├── .ruby-version ├── CHANGELOG.md ├── Gemfile ├── LICENSE ├── Package.swift ├── README.md ├── Sources/ │ ├── Compression/ │ │ ├── Compression.swift │ │ └── WSCompression.swift │ ├── DataBytes/ │ │ └── Data+Extensions.swift │ ├── Engine/ │ │ ├── Engine.swift │ │ ├── NativeEngine.swift │ │ └── WSEngine.swift │ ├── Framer/ │ │ ├── FoundationHTTPHandler.swift │ │ ├── FoundationHTTPServerHandler.swift │ │ ├── FrameCollector.swift │ │ ├── Framer.swift │ │ ├── HTTPHandler.swift │ │ └── StringHTTPHandler.swift │ ├── Info.plist │ ├── PrivacyInfo.xcprivacy │ ├── Security/ │ │ ├── FoundationSecurity.swift │ │ └── Security.swift │ ├── Server/ │ │ ├── Server.swift │ │ └── WebSocketServer.swift │ ├── Starscream/ │ │ └── WebSocket.swift │ ├── Starscream.h │ └── Transport/ │ ├── FoundationTransport.swift │ ├── TCPTransport.swift │ └── Transport.swift ├── Starscream.podspec ├── Tests/ │ ├── CompressionTests.swift │ ├── FuzzingTests.swift │ ├── Info.plist │ ├── MockServer.swift │ ├── MockTransport.swift │ └── StarscreamTests/ │ └── StarscreamTests.swift ├── examples/ │ ├── AutobahnTest/ │ │ ├── .gitignore │ │ └── Autobahn/ │ │ ├── AppDelegate.swift │ │ ├── Base.lproj/ │ │ │ ├── LaunchScreen.xib │ │ │ └── Main.storyboard │ │ ├── Images.xcassets/ │ │ │ └── AppIcon.appiconset/ │ │ │ └── Contents.json │ │ ├── Info.plist │ │ └── ViewController.swift │ ├── SimpleTest/ │ │ ├── .gitignore │ │ ├── README.md │ │ ├── SimpleTest/ │ │ │ ├── AppDelegate.swift │ │ │ ├── Base.lproj/ │ │ │ │ └── Main.storyboard │ │ │ ├── Images.xcassets/ │ │ │ │ ├── AppIcon.appiconset/ │ │ │ │ │ └── Contents.json │ │ │ │ └── LaunchImage.launchimage/ │ │ │ │ └── Contents.json │ │ │ ├── Info.plist │ │ │ └── ViewController.swift │ │ └── ws-server.rb │ └── WebSocketsOrgEcho/ │ ├── Podfile │ ├── WebSocketsOrgEcho/ │ │ ├── AppDelegate.swift │ │ ├── Assets.xcassets/ │ │ │ ├── AppIcon.appiconset/ │ │ │ │ └── Contents.json │ │ │ └── Contents.json │ │ ├── Base.lproj/ │ │ │ ├── LaunchScreen.storyboard │ │ │ └── Main.storyboard │ │ ├── Info.plist │ │ ├── URL+Extensions.swift │ │ └── ViewController.swift │ └── WebSocketsOrgEcho.xcworkspace/ │ ├── contents.xcworkspacedata │ └── xcshareddata/ │ └── IDEWorkspaceChecks.plist └── fastlane/ ├── Fastfile └── README.md ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/ISSUE_TEMPLATE/bug_report.md ================================================ --- name: Bug report about: Create a report about a bug title: '' labels: bug assignees: '' --- ### Describe the bug > A clear and concise description of what the bug is. ### Steps to Reproduce > Detailed steps to reproduce the problematic behavior: ### Expected behavior > A clear and concise description of what you expected to happen. ### Environment: - OS/Version: [e.g. iOS/13.3] - Starscream Version [e.g. 4.0.4] - Xcode version [e.g. 11.5] ### Additional context > Add any other context about the problem here. ================================================ FILE: .github/ISSUE_TEMPLATE/config.yml ================================================ blank_issues_enabled: false ================================================ FILE: .github/ISSUE_TEMPLATE/feature_request.md ================================================ --- name: Feature request about: Suggest an idea for this project title: '' labels: feature_request assignees: '' --- ### What do you want to happen? > Please replace this with the general overview of the feature that you'd like to have. ### What happens now? > Please replace this with of what is happening currently. ### Demo Code > Any demo code that may used to implement/use the desired feature. ### Describe alternatives you've considered > A clear and concise description of any alternative solutions or features you've considered. ### Additional context > Add any other context or screenshots about the feature request here. ================================================ FILE: .github/ISSUE_TEMPLATE/general-question.md ================================================ --- name: General Question about: 'Ask any question about the framework. ' title: '' labels: question assignees: '' --- ### Question > A description of what you want to know. ### Environment: - OS/Version: [e.g. iOS/13.3] - Starscream Version [e.g. 4.0.4] - Xcode version [e.g. 11.5] ================================================ FILE: .github/pull_request_template.md ================================================ ### Issue Link 🔗 > Please attach the link to an issue if it exists. ### Goals ⚽ > What you hope to address within this PR. ### Implementation Details 🚧 > Additional details about the PR. ================================================ FILE: .github/workflows/release.yml ================================================ name: Release on: push: tags: - "*.*.*" jobs: release: runs-on: macos-latest steps: - uses: actions/checkout@v4 - name: Set Latest Tag id: vars run: echo "tag=$(git describe --tags `git rev-list --tags --max-count=1`)" >> $GITHUB_OUTPUT - uses: ruby/setup-ruby@v1 with: bundler-cache: true # runs 'bundle install' and caches installed gems automatically - run: bundle exec fastlane test - run: bundle exec fastlane release env: GITHUB_TOKEN: ${{ secrets.BOT_GITHUB_TOKEN }} COCOAPODS_TRUNK_TOKEN: ${{ secrets.COCOAPODS_TRUNK_TOKEN }} TAG: ${{ steps.vars.outputs.tag }} ================================================ FILE: .gitignore ================================================ # CocoaPods # # We recommend against adding the Pods directory to your .gitignore. However # you should judge for yourself, the pros and cons are mentioned at: # http://guides.cocoapods.org/using/using-cocoapods.html#should-i-ignore-the-pods-directory-in-source-control? # Pods/ # Xcode .DS_Store build *.pbxuser !default.pbxuser *.mode1v3 !default.mode1v3 *.mode2v3 !default.mode2v3 *.perspectivev3 !default.perspectivev3 xcuserdata profile *.moved-aside DerivedData .idea/ *.hmap *.xccheckout *.xcodeproj/*.xcworkspace # Created by https://www.gitignore.io/api/swift,swiftpm ### Swift ### # Xcode # # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore ## Build generated build/ DerivedData/ ## Various settings *.pbxuser !default.pbxuser *.mode1v3 !default.mode1v3 *.mode2v3 !default.mode2v3 *.perspectivev3 !default.perspectivev3 xcuserdata/ ## Other *.moved-aside *.xccheckout *.xcscmblueprint ## Obj-C/Swift specific *.hmap *.ipa *.dSYM.zip *.dSYM ## Playgrounds timeline.xctimeline playground.xcworkspace # Swift Package Manager # # Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. # Packages/ # Package.pins # Package.resolved .build/ # CocoaPods # # We recommend against adding the Pods directory to your .gitignore. However # you should judge for yourself, the pros and cons are mentioned at: # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control # # Pods/ # # Add this line if you want to avoid checking in source code from the Xcode workspace # *.xcworkspace # Carthage # # Add this line if you want to avoid checking in source code from Carthage dependencies. # Carthage/Checkouts Carthage/Build # fastlane # # It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the # screenshots whenever they are needed. # For more information about the recommended setup visit: # https://docs.fastlane.tools/best-practices/source-control/#source-control fastlane/report.xml fastlane/Preview.html fastlane/screenshots/**/*.png fastlane/test_output # Code Injection # # After new code Injection tools there's a generated folder /iOSInjectionProject # https://github.com/johnno1962/injectionforxcode iOSInjectionProject/ ### SwiftPM ### Packages xcuserdata *.xcodeproj # End of https://www.gitignore.io/api/swift,swiftpm ================================================ FILE: .ruby-version ================================================ 3.2.2 ================================================ FILE: CHANGELOG.md ================================================ # Change Log All notable changes to this project will be documented in this file. `Starscream` adheres to [Semantic Versioning](http://semver.org/). ### [4.0.4](https://github.com/daltoniam/Starscream/tree/4.0.4) Bug fixes for 4.0.3. [#808](https://github.com/daltoniam/Starscream/pull/808) [#807](https://github.com/daltoniam/Starscream/pull/807) [#799](https://github.com/daltoniam/Starscream/pull/799) [#797](https://github.com/daltoniam/Starscream/pull/797) [#790](https://github.com/daltoniam/Starscream/pull/790) [#788](https://github.com/daltoniam/Starscream/pull/788) [#777](https://github.com/daltoniam/Starscream/pull/777) [#768](https://github.com/daltoniam/Starscream/pull/768) [#766](https://github.com/daltoniam/Starscream/pull/766) [#764](https://github.com/daltoniam/Starscream/pull/764) ### [4.0.3](https://github.com/daltoniam/Starscream/tree/4.0.3) Bug fixes for 4.0.2. [#760](https://github.com/daltoniam/Starscream/issues/760) ### [4.0.2](https://github.com/daltoniam/Starscream/tree/4.0.2) Bug fixes for 4.0.1. Fixed native engine is connected/disconnected. Native engine isn't the default since the API lacks features. [#697](https://github.com/daltoniam/Starscream/pull/697) ### [4.0.1](https://github.com/daltoniam/Starscream/tree/4.0.1) Bug fixes for 4.0.0. Enabled Native engine now that the API is out of beta and works properly. [#749](https://github.com/daltoniam/Starscream/pull/749) [#755](https://github.com/daltoniam/Starscream/pull/755) ### [4.0.0](https://github.com/daltoniam/Starscream/tree/4.0.0) Major API refactor. ### [3.1.1](https://github.com/daltoniam/Starscream/tree/3.1.1) Small version number fix for 3.1.0: [#703](https://github.com/daltoniam/Starscream/issues/703) ### [3.1.0](https://github.com/daltoniam/Starscream/tree/3.1.0) * Swift 5.0 and Xcode 10.2 support #### [3.0.6](https://github.com/daltoniam/Starscream/tree/3.0.6) * Swift 4.2 and Xcode 10 support * added pongDelegate * moved CommonCrypto and zlib dependencies * HTTP proxy support #### [3.0.5](https://github.com/daltoniam/Starscream/tree/3.0.5) Swift 4.1 support and bug fixes. Pull Requests: [#492](https://github.com/daltoniam/Starscream/pull/492) [#461](https://github.com/daltoniam/Starscream/pull/461) [#476](https://github.com/daltoniam/Starscream/pull/476) Issues: [#494](https://github.com/daltoniam/Starscream/issues/494) [#491](https://github.com/daltoniam/Starscream/issues/491) [#474](https://github.com/daltoniam/Starscream/issues/474) [#471](https://github.com/daltoniam/Starscream/issues/471) [#437](https://github.com/daltoniam/Starscream/issues/437) [#445](https://github.com/daltoniam/Starscream/issues/445) [#466](https://github.com/daltoniam/Starscream/issues/466) #### [3.0.4](https://github.com/daltoniam/Starscream/tree/3.0.4) Improved error handling. Timeout fix. Small assorted fixes. Pull Requests: [#452](https://github.com/daltoniam/Starscream/pull/452) [#448](https://github.com/daltoniam/Starscream/pull/448) [#444](https://github.com/daltoniam/Starscream/pull/444) [#443](https://github.com/daltoniam/Starscream/pull/443) Issues: [#415](https://github.com/daltoniam/Starscream/issues/415) [#422](https://github.com/daltoniam/Starscream/issues/422) [#429](https://github.com/daltoniam/Starscream/issues/429) [#433](https://github.com/daltoniam/Starscream/issues/433) [#439](https://github.com/daltoniam/Starscream/issues/439) #### [3.0.3](https://github.com/daltoniam/Starscream/tree/3.0.3) Assorted fixes. Pull Requests: [#438](https://github.com/daltoniam/Starscream/pull/438) [#423](https://github.com/daltoniam/Starscream/pull/423) [#420](https://github.com/daltoniam/Starscream/pull/420) [#418](https://github.com/daltoniam/Starscream/pull/418) [#410](https://github.com/daltoniam/Starscream/pull/410) [#405](https://github.com/daltoniam/Starscream/pull/405) [#404](https://github.com/daltoniam/Starscream/pull/404) [#400](https://github.com/daltoniam/Starscream/pull/400) Issues: [#435](https://github.com/daltoniam/Starscream/issues/435) [#431](https://github.com/daltoniam/Starscream/issues/431) [#426](https://github.com/daltoniam/Starscream/issues/426) [#409](https://github.com/daltoniam/Starscream/issues/409) [#408](https://github.com/daltoniam/Starscream/issues/408) [#401](https://github.com/daltoniam/Starscream/issues/401) [#399](https://github.com/daltoniam/Starscream/issues/399) [#378](https://github.com/daltoniam/Starscream/issues/378) #### [3.0.2](https://github.com/daltoniam/Starscream/tree/3.0.2) Small fixes for 3.0.1. [#394](https://github.com/daltoniam/Starscream/issues/394) [#392](https://github.com/daltoniam/Starscream/issues/392) [#391](https://github.com/daltoniam/Starscream/issues/391) #### [3.0.1](https://github.com/daltoniam/Starscream/tree/3.0.1) Small fixes for 3.0.0. [#389](https://github.com/daltoniam/Starscream/issues/389) [#354](https://github.com/daltoniam/Starscream/issues/354) [#386](https://github.com/daltoniam/Starscream/pull/386) [#388](https://github.com/daltoniam/Starscream/pull/388) [#390](https://github.com/daltoniam/Starscream/pull/390) #### [3.0.0](https://github.com/daltoniam/Starscream/tree/3.0.0) Major refactor and Swift 4 support. Additions include: - Watchos support. - Linux support. - New Stream class to allow custom socket implementations if desired. - Protocol added for mocking (dependency injection). - Single framework (no more platform suffixes! e.g. StarscreamOSX, StarscreamTVOS, etc). [#384](https://github.com/daltoniam/Starscream/issues/384) [#377](https://github.com/daltoniam/Starscream/pull/377) [#374](https://github.com/daltoniam/Starscream/issues/374) [#346](https://github.com/daltoniam/Starscream/issues/346) [#335](https://github.com/daltoniam/Starscream/issues/335) [#311](https://github.com/daltoniam/Starscream/pull/311) [#269](https://github.com/daltoniam/Starscream/issues/269) #### [2.1.1](https://github.com/daltoniam/Starscream/tree/2.1.1) Fixes race condition. Updated to avoid SPM dependencies. [#370](https://github.com/daltoniam/Starscream/issues/370) [#367](https://github.com/daltoniam/Starscream/issues/367) [#364](https://github.com/daltoniam/Starscream/pull/364) [#357](https://github.com/daltoniam/Starscream/pull/357) [#355](https://github.com/daltoniam/Starscream/pull/355) #### [2.1.0](https://github.com/daltoniam/Starscream/tree/2.1.0) Adds WebSocket compression. Also adds advance WebSocket delegate for extra control. Bug Fixes. [#349](https://github.com/daltoniam/Starscream/pull/349) [#344](https://github.com/daltoniam/Starscream/pull/344) [#339](https://github.com/daltoniam/Starscream/pull/339) [#337](https://github.com/daltoniam/Starscream/pull/337) [#334](https://github.com/daltoniam/Starscream/issues/334) [#333](https://github.com/daltoniam/Starscream/pull/333) [#319](https://github.com/daltoniam/Starscream/issues/319) [#309](https://github.com/daltoniam/Starscream/issues/309) [#329](https://github.com/daltoniam/Starscream/issues/329) #### [2.0.4](https://github.com/daltoniam/Starscream/tree/2.0.4) SSL Pinning fix by Giuliano Galea as reported by Lukas Futera of [Centralway](https://www.centralway.com/de/). Warning fixes for Swift 3.1 #### [2.0.3](https://github.com/daltoniam/Starscream/tree/2.0.3) [#302](https://github.com/daltoniam/Starscream/issues/302) [#301](https://github.com/daltoniam/Starscream/issues/301) [#300](https://github.com/daltoniam/Starscream/issues/300) [#296](https://github.com/daltoniam/Starscream/issues/296) [#294](https://github.com/daltoniam/Starscream/issues/294) [#292](https://github.com/daltoniam/Starscream/issues/292) [#289](https://github.com/daltoniam/Starscream/issues/289) [#288](https://github.com/daltoniam/Starscream/issues/288) #### [2.0.2](https://github.com/daltoniam/Starscream/tree/2.0.2) Fix for the Swift Package Manager. Fixed: [#277](https://github.com/daltoniam/Starscream/issues/277) #### [2.0.1](https://github.com/daltoniam/Starscream/tree/2.0.1) Bug fixes. Fixed: [#261](https://github.com/daltoniam/Starscream/issues/261) [#276](https://github.com/daltoniam/Starscream/issues/276) [#267](https://github.com/daltoniam/Starscream/issues/267) [#266](https://github.com/daltoniam/Starscream/issues/266) [#259](https://github.com/daltoniam/Starscream/issues/259) #### [2.0.0](https://github.com/daltoniam/Starscream/tree/2.0.0) Added Swift 3 support. Fixed: [#229](https://github.com/daltoniam/Starscream/issues/229) [#232](https://github.com/daltoniam/Starscream/issues/232) #### [1.1.4](https://github.com/daltoniam/Starscream/tree/1.1.4) Swift 2.3 support. #### [1.1.3](https://github.com/daltoniam/Starscream/tree/1.1.3) Changed: [#170](https://github.com/daltoniam/Starscream/issues/170) [#171](https://github.com/daltoniam/Starscream/issues/171) [#174](https://github.com/daltoniam/Starscream/issues/174) [#177](https://github.com/daltoniam/Starscream/issues/177) [#178](https://github.com/daltoniam/Starscream/issues/178) #### [1.1.2](https://github.com/daltoniam/Starscream/tree/1.1.2) Fixed: [#158](https://github.com/daltoniam/Starscream/issues/158) [#161](https://github.com/daltoniam/Starscream/issues/161) [#164](https://github.com/daltoniam/Starscream/issues/164) #### [1.1.1](https://github.com/daltoniam/Starscream/tree/1.1.1) Fixed: [#157](https://github.com/daltoniam/Starscream/issues/157) #### [1.1.0](https://github.com/daltoniam/Starscream/tree/1.1.0) Changed: Moved over to Runloop/default GCD queues to shared queue. Fixed: [#153](https://github.com/daltoniam/Starscream/issues/153) [#151](https://github.com/daltoniam/Starscream/issues/151) [#150](https://github.com/daltoniam/Starscream/issues/150) [#149](https://github.com/daltoniam/Starscream/issues/149) [#147](https://github.com/daltoniam/Starscream/issues/147) [#139](https://github.com/daltoniam/Starscream/issues/139) [#77](https://github.com/daltoniam/Starscream/issues/77) #### [1.0.2](https://github.com/daltoniam/Starscream/tree/1.0.2) Added TVOS support. #### [1.0.1](https://github.com/daltoniam/Starscream/tree/1.0.1) Fixes for #121, #123 #### [1.0.0](https://github.com/daltoniam/Starscream/tree/1.0.0) first release of Swift 2 support. ================================================ FILE: Gemfile ================================================ source "https://rubygems.org" gem "fastlane" gem "cocoapods" ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ Copyright (c) 2014-2023 Dalton Cherry. TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. ================================================ FILE: Package.swift ================================================ // swift-tools-version:5.3 // // Package.Swift // Starscream // // Created by Dalton Cherry on 5/16/15. // Copyright (c) 2014-2016 Dalton Cherry. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import PackageDescription let package = Package( name: "Starscream", products: [ .library(name: "Starscream", targets: ["Starscream"]) ], dependencies: [], targets: [ .target(name: "Starscream", path: "Sources", resources: [.copy("PrivacyInfo.xcprivacy")]) ] ) #if os(Linux) package.dependencies.append(.package(url: "https://github.com/apple/swift-nio-zlib-support.git", from: "1.0.0")) #endif ================================================ FILE: README.md ================================================ ![starscream](https://raw.githubusercontent.com/daltoniam/starscream/assets/starscream.jpg) Starscream is a conforming WebSocket ([RFC 6455](https://datatracker.ietf.org/doc/html/rfc6455)) library in Swift. ## Features - Conforms to all of the base [Autobahn test suite](https://crossbar.io/autobahn/). - Nonblocking. Everything happens in the background, thanks to GCD. - TLS/WSS support. - Compression Extensions support ([RFC 7692](https://tools.ietf.org/html/rfc7692)) ### Import the framework First thing is to import the framework. See the Installation instructions on how to add the framework to your project. ```swift import Starscream ``` ### Connect to the WebSocket Server Once imported, you can open a connection to your WebSocket server. Note that `socket` is probably best as a property, so it doesn't get deallocated right after being setup. ```swift var request = URLRequest(url: URL(string: "http://localhost:8080")!) request.timeoutInterval = 5 socket = WebSocket(request: request) socket.delegate = self socket.connect() ``` After you are connected, there is either a delegate or closure you can use for process WebSocket events. ### Receiving data from a WebSocket `didReceive` receives all the WebSocket events in a single easy to handle enum. ```swift func didReceive(event: WebSocketEvent, client: WebSocket) { switch event { case .connected(let headers): isConnected = true print("websocket is connected: \(headers)") case .disconnected(let reason, let code): isConnected = false print("websocket is disconnected: \(reason) with code: \(code)") case .text(let string): print("Received text: \(string)") case .binary(let data): print("Received data: \(data.count)") case .ping(_): break case .pong(_): break case .viabilityChanged(_): break case .reconnectSuggested(_): break case .cancelled: isConnected = false case .error(let error): isConnected = false handleError(error) case .peerClosed: break } } ``` The closure of this would be: ```swift socket.onEvent = { event in switch event { // handle events just like above... } } ``` ### Writing to a WebSocket ### write a binary frame The writeData method gives you a simple way to send `Data` (binary) data to the server. ```swift socket.write(data: data) //write some Data over the socket! ``` ### write a string frame The writeString method is the same as writeData, but sends text/string. ```swift socket.write(string: "Hi Server!") //example on how to write text over the socket! ``` ### write a ping frame The writePing method is the same as write, but sends a ping control frame. ```swift socket.write(ping: Data()) //example on how to write a ping control frame over the socket! ``` ### write a pong frame the writePong method is the same as writePing, but sends a pong control frame. ```swift socket.write(pong: Data()) //example on how to write a pong control frame over the socket! ``` Starscream will automatically respond to incoming `ping` control frames so you do not need to manually send `pong`s. However if for some reason you need to control this process you can turn off the automatic `ping` response by disabling `respondToPingWithPong`. ```swift socket.respondToPingWithPong = false //Do not automaticaly respond to incoming pings with pongs. ``` In most cases you will not need to do this. ### disconnect The disconnect method does what you would expect and closes the socket. ```swift socket.disconnect() ``` The disconnect method can also send a custom close code if desired. ```swift socket.disconnect(closeCode: CloseCode.normal.rawValue) ``` ### Custom Headers, Protocols and Timeout You can override the default websocket headers, add your own custom ones and set a timeout: ```swift var request = URLRequest(url: URL(string: "ws://localhost:8080/")!) request.timeoutInterval = 5 // Sets the timeout for the connection request.setValue("someother protocols", forHTTPHeaderField: "Sec-WebSocket-Protocol") request.setValue("14", forHTTPHeaderField: "Sec-WebSocket-Version") request.setValue("chat,superchat", forHTTPHeaderField: "Sec-WebSocket-Protocol") request.setValue("Everything is Awesome!", forHTTPHeaderField: "My-Awesome-Header") let socket = WebSocket(request: request) ``` ### SSL Pinning SSL Pinning is also supported in Starscream. Allow Self-signed certificates: ```swift var request = URLRequest(url: URL(string: "ws://localhost:8080/")!) let pinner = FoundationSecurity(allowSelfSigned: true) // don't validate SSL certificates let socket = WebSocket(request: request, certPinner: pinner) ``` TODO: Update docs on how to load certificates and public keys into an app bundle, use the builtin pinner and TrustKit. ### Compression Extensions Compression Extensions ([RFC 7692](https://tools.ietf.org/html/rfc7692)) is supported in Starscream. Compression is enabled by default, however compression will only be used if it is supported by the server as well. You may enable compression by adding a `compressionHandler`: ```swift var request = URLRequest(url: URL(string: "ws://localhost:8080/")!) let compression = WSCompression() let socket = WebSocket(request: request, compressionHandler: compression) ``` Compression should be disabled if your application is transmitting already-compressed, random, or other uncompressable data. ### Custom Queue A custom queue can be specified when delegate methods are called. By default `DispatchQueue.main` is used, thus making all delegate methods calls run on the main thread. It is important to note that all WebSocket processing is done on a background thread, only the delegate method calls are changed when modifying the queue. The actual processing is always on a background thread and will not pause your app. ```swift socket = WebSocket(url: URL(string: "ws://localhost:8080/")!, protocols: ["chat","superchat"]) //create a custom queue socket.callbackQueue = DispatchQueue(label: "com.vluxe.starscream.myapp") ``` ## Example Project Check out the SimpleTest project in the examples directory to see how to setup a simple connection to a WebSocket server. ## Requirements Starscream works with iOS 8/10.10 or above for CocoaPods/framework support. To use Starscream with a project targeting iOS 7, you must include all Swift files directly in your project. ## Installation ### Swift Package Manager The [Swift Package Manager](https://swift.org/package-manager/) is a tool for automating the distribution of Swift code and is integrated into the `swift` compiler. Once you have your Swift package set up, adding Starscream as a dependency is as easy as adding it to the `dependencies` value of your `Package.swift`. ```swift dependencies: [ .package(url: "https://github.com/daltoniam/Starscream.git", from: "4.0.6") ] ``` ### CocoaPods Check out [Get Started](http://cocoapods.org/) tab on [cocoapods.org](http://cocoapods.org/). To use Starscream in your project add the following 'Podfile' to your project source 'https://github.com/CocoaPods/Specs.git' platform :ios, '12.0' use_frameworks! pod 'Starscream', '~> 4.0.6' Then run: pod install ### Carthage Check out the [Carthage](https://github.com/Carthage/Carthage) docs on how to add a install. The `Starscream` framework is already setup with shared schemes. [Carthage Install](https://github.com/Carthage/Carthage#adding-frameworks-to-an-application) You can install Carthage with [Homebrew](http://brew.sh/) using the following command: ```bash $ brew update $ brew install carthage ``` To integrate Starscream into your Xcode project using Carthage, specify it in your `Cartfile`: ``` github "daltoniam/Starscream" >= 4.0.6 ``` ### Other Simply grab the framework (either via git submodule or another package manager). Add the `Starscream.xcodeproj` to your Xcode project. Once that is complete, in your "Build Phases" add the `Starscream.framework` to your "Link Binary with Libraries" phase. ### Add Copy Frameworks Phase If you are running this in an OSX app or on a physical iOS device you will need to make sure you add the `Starscream.framework` to be included in your app bundle. To do this, in Xcode, navigate to the target configuration window by clicking on the blue project icon, and selecting the application target under the "Targets" heading in the sidebar. In the tab bar at the top of that window, open the "Build Phases" panel. Expand the "Link Binary with Libraries" group, and add `Starscream.framework`. Click on the + button at the top left of the panel and select "New Copy Files Phase". Rename this new phase to "Copy Frameworks", set the "Destination" to "Frameworks", and add `Starscream.framework` respectively. ## TODOs - [ ] Proxy support - [ ] Thread safe implementation - [ ] Better testing/CI - [ ] SSL Pinning/client auth examples ## License Starscream is licensed under the Apache v2 License. ## Contact ### Dalton Cherry * https://github.com/daltoniam * http://twitter.com/daltoniam * http://daltoniam.com ### Austin Cherry ### * https://github.com/acmacalister * http://twitter.com/acmacalister * http://austincherry.me ================================================ FILE: Sources/Compression/Compression.swift ================================================ ////////////////////////////////////////////////////////////////////////////////////////////////// // // Compression.swift // Starscream // // Created by Dalton Cherry on 2/4/19. // Copyright © 2019 Vluxe. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ////////////////////////////////////////////////////////////////////////////////////////////////// import Foundation public protocol CompressionHandler { func load(headers: [String: String]) func decompress(data: Data, isFinal: Bool) -> Data? func compress(data: Data) -> Data? } ================================================ FILE: Sources/Compression/WSCompression.swift ================================================ ////////////////////////////////////////////////////////////////////////////////////////////////// // // WSCompression.swift // // Created by Joseph Ross on 7/16/14. // Copyright © 2017 Joseph Ross & Vluxe. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////// // // Compression implementation is implemented in conformance with RFC 7692 Compression Extensions // for WebSocket: https://tools.ietf.org/html/rfc7692 // ////////////////////////////////////////////////////////////////////////////////////////////////// import Foundation import zlib public class WSCompression: CompressionHandler { let headerWSExtensionName = "Sec-WebSocket-Extensions" var decompressor: Decompressor? var compressor: Compressor? var decompressorTakeOver = false var compressorTakeOver = false public init() { } public func load(headers: [String: String]) { guard let extensionHeader = headers[headerWSExtensionName] else { return } decompressorTakeOver = false compressorTakeOver = false // assume defaults unless the headers say otherwise compressor = Compressor(windowBits: 15) decompressor = Decompressor(windowBits: 15) let parts = extensionHeader.components(separatedBy: ";") for p in parts { let part = p.trimmingCharacters(in: .whitespaces) if part.hasPrefix("server_max_window_bits=") { let valString = part.components(separatedBy: "=")[1] if let val = Int(valString.trimmingCharacters(in: .whitespaces)) { decompressor = Decompressor(windowBits: val) } } else if part.hasPrefix("client_max_window_bits=") { let valString = part.components(separatedBy: "=")[1] if let val = Int(valString.trimmingCharacters(in: .whitespaces)) { compressor = Compressor(windowBits: val) } } else if part == "client_no_context_takeover" { compressorTakeOver = true } else if part == "server_no_context_takeover" { decompressorTakeOver = true } } } public func decompress(data: Data, isFinal: Bool) -> Data? { guard let decompressor = decompressor else { return nil } do { let decompressedData = try decompressor.decompress(data, finish: isFinal) if decompressorTakeOver { try decompressor.reset() } return decompressedData } catch { //do nothing with the error for now } return nil } public func compress(data: Data) -> Data? { guard let compressor = compressor else { return nil } do { let compressedData = try compressor.compress(data) if compressorTakeOver { try compressor.reset() } return compressedData } catch { //do nothing with the error for now } return nil } } class Decompressor { private var strm = z_stream() private var buffer = [UInt8](repeating: 0, count: 0x2000) private var inflateInitialized = false private let windowBits: Int init?(windowBits: Int) { self.windowBits = windowBits guard initInflate() else { return nil } } private func initInflate() -> Bool { if Z_OK == inflateInit2_(&strm, -CInt(windowBits), ZLIB_VERSION, CInt(MemoryLayout.size)) { inflateInitialized = true return true } return false } func reset() throws { teardownInflate() guard initInflate() else { throw WSError(type: .compressionError, message: "Error for decompressor on reset", code: 0) } } func decompress(_ data: Data, finish: Bool) throws -> Data { return try data.withUnsafeBytes { (bytes: UnsafePointer) -> Data in return try decompress(bytes: bytes, count: data.count, finish: finish) } } func decompress(bytes: UnsafePointer, count: Int, finish: Bool) throws -> Data { var decompressed = Data() try decompress(bytes: bytes, count: count, out: &decompressed) if finish { let tail:[UInt8] = [0x00, 0x00, 0xFF, 0xFF] try decompress(bytes: tail, count: tail.count, out: &decompressed) } return decompressed } private func decompress(bytes: UnsafePointer, count: Int, out: inout Data) throws { var res: CInt = 0 strm.next_in = UnsafeMutablePointer(mutating: bytes) strm.avail_in = CUnsignedInt(count) repeat { buffer.withUnsafeMutableBytes { (bufferPtr) in strm.next_out = bufferPtr.bindMemory(to: UInt8.self).baseAddress strm.avail_out = CUnsignedInt(bufferPtr.count) res = inflate(&strm, 0) } let byteCount = buffer.count - Int(strm.avail_out) out.append(buffer, count: byteCount) } while res == Z_OK && strm.avail_out == 0 guard (res == Z_OK && strm.avail_out > 0) || (res == Z_BUF_ERROR && Int(strm.avail_out) == buffer.count) else { throw WSError(type: .compressionError, message: "Error on decompressing", code: 0) } } private func teardownInflate() { if inflateInitialized, Z_OK == inflateEnd(&strm) { inflateInitialized = false } } deinit { teardownInflate() } } class Compressor { private var strm = z_stream() private var buffer = [UInt8](repeating: 0, count: 0x2000) private var deflateInitialized = false private let windowBits: Int init?(windowBits: Int) { self.windowBits = windowBits guard initDeflate() else { return nil } } private func initDeflate() -> Bool { if Z_OK == deflateInit2_(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, -CInt(windowBits), 8, Z_DEFAULT_STRATEGY, ZLIB_VERSION, CInt(MemoryLayout.size)) { deflateInitialized = true return true } return false } func reset() throws { teardownDeflate() guard initDeflate() else { throw WSError(type: .compressionError, message: "Error for compressor on reset", code: 0) } } func compress(_ data: Data) throws -> Data { guard !data.isEmpty else { // For example, PONG has no content return data } var compressed = Data() var res: CInt = 0 data.withUnsafeBytes { (ptr:UnsafePointer) -> Void in strm.next_in = UnsafeMutablePointer(mutating: ptr) strm.avail_in = CUnsignedInt(data.count) repeat { buffer.withUnsafeMutableBytes { (bufferPtr) in strm.next_out = bufferPtr.bindMemory(to: UInt8.self).baseAddress strm.avail_out = CUnsignedInt(bufferPtr.count) res = deflate(&strm, Z_SYNC_FLUSH) } let byteCount = buffer.count - Int(strm.avail_out) compressed.append(buffer, count: byteCount) } while res == Z_OK && strm.avail_out == 0 } guard res == Z_OK && strm.avail_out > 0 || (res == Z_BUF_ERROR && Int(strm.avail_out) == buffer.count) else { throw WSError(type: .compressionError, message: "Error on compressing", code: 0) } compressed.removeLast(4) return compressed } private func teardownDeflate() { if deflateInitialized, Z_OK == deflateEnd(&strm) { deflateInitialized = false } } deinit { teardownDeflate() } } ================================================ FILE: Sources/DataBytes/Data+Extensions.swift ================================================ ////////////////////////////////////////////////////////////////////////////////////////////////// // // Data+Extensions.swift // Starscream // // Created by Dalton Cherry on 3/27/19. // Copyright © 2019 Vluxe. All rights reserved. // // Fix for deprecation warnings // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ////////////////////////////////////////////////////////////////////////////////////////////////// import Foundation internal extension Data { struct ByteError: Swift.Error {} #if swift(>=5.0) func withUnsafeBytes(_ completion: (UnsafePointer) throws -> ResultType) rethrows -> ResultType { return try withUnsafeBytes { if let baseAddress = $0.baseAddress, $0.count > 0 { return try completion(baseAddress.assumingMemoryBound(to: ContentType.self)) } else { throw ByteError() } } } #endif #if swift(>=5.0) mutating func withUnsafeMutableBytes(_ completion: (UnsafeMutablePointer) throws -> ResultType) rethrows -> ResultType { return try withUnsafeMutableBytes { if let baseAddress = $0.baseAddress, $0.count > 0 { return try completion(baseAddress.assumingMemoryBound(to: ContentType.self)) } else { throw ByteError() } } } #endif } ================================================ FILE: Sources/Engine/Engine.swift ================================================ ////////////////////////////////////////////////////////////////////////////////////////////////// // // Engine.swift // Starscream // // Created by Dalton Cherry on 6/15/19 // Copyright © 2019 Vluxe. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ////////////////////////////////////////////////////////////////////////////////////////////////// import Foundation public protocol EngineDelegate: AnyObject { func didReceive(event: WebSocketEvent) } public protocol Engine { func register(delegate: EngineDelegate) func start(request: URLRequest) func stop(closeCode: UInt16) func forceStop() func write(data: Data, opcode: FrameOpCode, completion: (() -> ())?) func write(string: String, completion: (() -> ())?) } ================================================ FILE: Sources/Engine/NativeEngine.swift ================================================ ////////////////////////////////////////////////////////////////////////////////////////////////// // // NativeEngine.swift // Starscream // // Created by Dalton Cherry on 6/15/19 // Copyright © 2019 Vluxe. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ////////////////////////////////////////////////////////////////////////////////////////////////// import Foundation @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) public class NativeEngine: NSObject, Engine, URLSessionDataDelegate, URLSessionWebSocketDelegate { private var task: URLSessionWebSocketTask? weak var delegate: EngineDelegate? public func register(delegate: EngineDelegate) { self.delegate = delegate } public func start(request: URLRequest) { let session = URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: nil) task = session.webSocketTask(with: request) doRead() task?.resume() } public func stop(closeCode: UInt16) { let closeCode = URLSessionWebSocketTask.CloseCode(rawValue: Int(closeCode)) ?? .normalClosure task?.cancel(with: closeCode, reason: nil) } public func forceStop() { stop(closeCode: UInt16(URLSessionWebSocketTask.CloseCode.abnormalClosure.rawValue)) } public func write(string: String, completion: (() -> ())?) { task?.send(.string(string), completionHandler: { (error) in completion?() }) } public func write(data: Data, opcode: FrameOpCode, completion: (() -> ())?) { switch opcode { case .binaryFrame: task?.send(.data(data), completionHandler: { (error) in completion?() }) case .textFrame: let text = String(data: data, encoding: .utf8)! write(string: text, completion: completion) case .ping: task?.sendPing(pongReceiveHandler: { (error) in completion?() }) default: break //unsupported } } private func doRead() { task?.receive { [weak self] (result) in switch result { case .success(let message): switch message { case .string(let string): self?.broadcast(event: .text(string)) case .data(let data): self?.broadcast(event: .binary(data)) @unknown default: break } break case .failure(let error): self?.broadcast(event: .error(error)) return } self?.doRead() } } private func broadcast(event: WebSocketEvent) { delegate?.didReceive(event: event) } public func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didOpenWithProtocol protocol: String?) { let p = `protocol` ?? "" broadcast(event: .connected([HTTPWSHeader.protocolName: p])) } public func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didCloseWith closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?) { var r = "" if let d = reason { r = String(data: d, encoding: .utf8) ?? "" } broadcast(event: .disconnected(r, UInt16(closeCode.rawValue))) } public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { broadcast(event: .error(error)) } } ================================================ FILE: Sources/Engine/WSEngine.swift ================================================ ////////////////////////////////////////////////////////////////////////////////////////////////// // // WSEngine.swift // Starscream // // Created by Dalton Cherry on 6/15/19 // Copyright © 2019 Vluxe. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ////////////////////////////////////////////////////////////////////////////////////////////////// import Foundation public class WSEngine: Engine, TransportEventClient, FramerEventClient, FrameCollectorDelegate, HTTPHandlerDelegate { private let transport: Transport private let framer: Framer private let httpHandler: HTTPHandler private let compressionHandler: CompressionHandler? private let certPinner: CertificatePinning? private let headerChecker: HeaderValidator private var request: URLRequest! private let frameHandler = FrameCollector() private var didUpgrade = false private var secKeyValue = "" private let writeQueue = DispatchQueue(label: "com.vluxe.starscream.writequeue") private let mutex = DispatchSemaphore(value: 1) private var canSend = false private var isConnecting = false weak var delegate: EngineDelegate? public var respondToPingWithPong: Bool = true public init(transport: Transport, certPinner: CertificatePinning? = nil, headerValidator: HeaderValidator = FoundationSecurity(), httpHandler: HTTPHandler = FoundationHTTPHandler(), framer: Framer = WSFramer(), compressionHandler: CompressionHandler? = nil) { self.transport = transport self.framer = framer self.httpHandler = httpHandler self.certPinner = certPinner self.headerChecker = headerValidator self.compressionHandler = compressionHandler framer.updateCompression(supports: compressionHandler != nil) frameHandler.delegate = self } public func register(delegate: EngineDelegate) { self.delegate = delegate } public func start(request: URLRequest) { mutex.wait() let isConnecting = self.isConnecting let isConnected = canSend mutex.signal() if isConnecting || isConnected { return } self.request = request transport.register(delegate: self) framer.register(delegate: self) httpHandler.register(delegate: self) frameHandler.delegate = self guard let url = request.url else { return } mutex.wait() self.isConnecting = true mutex.signal() transport.connect(url: url, timeout: request.timeoutInterval, certificatePinning: certPinner) } public func stop(closeCode: UInt16 = CloseCode.normal.rawValue) { let capacity = MemoryLayout.size var pointer = [UInt8](repeating: 0, count: capacity) writeUint16(&pointer, offset: 0, value: closeCode) let payload = Data(bytes: pointer, count: MemoryLayout.size) write(data: payload, opcode: .connectionClose, completion: { [weak self] in self?.reset() self?.forceStop() }) } public func forceStop() { mutex.wait() isConnecting = false mutex.signal() transport.disconnect() } public func write(string: String, completion: (() -> ())?) { let data = string.data(using: .utf8)! write(data: data, opcode: .textFrame, completion: completion) } public func write(data: Data, opcode: FrameOpCode, completion: (() -> ())?) { writeQueue.async { [weak self] in guard let s = self else { return } s.mutex.wait() let canWrite = s.canSend s.mutex.signal() if !canWrite { return } var isCompressed = false var sendData = data if let compressedData = s.compressionHandler?.compress(data: data) { sendData = compressedData isCompressed = true } let frameData = s.framer.createWriteFrame(opcode: opcode, payload: sendData, isCompressed: isCompressed) s.transport.write(data: frameData, completion: {_ in completion?() }) } } // MARK: - TransportEventClient public func connectionChanged(state: ConnectionState) { switch state { case .connected: secKeyValue = HTTPWSHeader.generateWebSocketKey() let wsReq = HTTPWSHeader.createUpgrade(request: request, supportsCompression: framer.supportsCompression(), secKeyValue: secKeyValue) let data = httpHandler.convert(request: wsReq) transport.write(data: data, completion: {_ in }) case .waiting: break case .failed(let error): handleError(error) case .viability(let isViable): broadcast(event: .viabilityChanged(isViable)) case .shouldReconnect(let status): broadcast(event: .reconnectSuggested(status)) case .receive(let data): if didUpgrade { framer.add(data: data) } else { let offset = httpHandler.parse(data: data) if offset > 0 { let extraData = data.subdata(in: offset.. Data? { return compressionHandler?.decompress(data: data, isFinal: isFinal) } public func didForm(event: FrameCollector.Event) { switch event { case .text(let string): broadcast(event: .text(string)) case .binary(let data): broadcast(event: .binary(data)) case .pong(let data): broadcast(event: .pong(data)) case .ping(let data): broadcast(event: .ping(data)) if respondToPingWithPong { write(data: data ?? Data(), opcode: .pong, completion: nil) } case .closed(let reason, let code): broadcast(event: .disconnected(reason, code)) stop(closeCode: code) case .error(let error): handleError(error) } } private func broadcast(event: WebSocketEvent) { delegate?.didReceive(event: event) } //This call can be coming from a lot of different queues/threads. //be aware of that when modifying shared variables private func handleError(_ error: Error?) { if let wsError = error as? WSError { stop(closeCode: wsError.code) } else { stop() } delegate?.didReceive(event: .error(error)) } private func reset() { mutex.wait() isConnecting = false canSend = false didUpgrade = false mutex.signal() } } ================================================ FILE: Sources/Framer/FoundationHTTPHandler.swift ================================================ ////////////////////////////////////////////////////////////////////////////////////////////////// // // FoundationHTTPHandler.swift // Starscream // // Created by Dalton Cherry on 1/25/19. // Copyright © 2019 Vluxe. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ////////////////////////////////////////////////////////////////////////////////////////////////// import Foundation #if os(watchOS) public typealias FoundationHTTPHandler = StringHTTPHandler #else public class FoundationHTTPHandler: HTTPHandler { var buffer = Data() weak var delegate: HTTPHandlerDelegate? public init() { } public func convert(request: URLRequest) -> Data { let msg = CFHTTPMessageCreateRequest(kCFAllocatorDefault, request.httpMethod! as CFString, request.url! as CFURL, kCFHTTPVersion1_1).takeRetainedValue() if let headers = request.allHTTPHeaderFields { for (aKey, aValue) in headers { CFHTTPMessageSetHeaderFieldValue(msg, aKey as CFString, aValue as CFString) } } if let body = request.httpBody { CFHTTPMessageSetBody(msg, body as CFData) } guard let data = CFHTTPMessageCopySerializedMessage(msg) else { return Data() } return data.takeRetainedValue() as Data } public func parse(data: Data) -> Int { let offset = findEndOfHTTP(data: data) if offset > 0 { buffer.append(data.subdata(in: 0.. Bool { var pointer = [UInt8]() data.withUnsafeBytes { pointer.append(contentsOf: $0) } let response = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, false).takeRetainedValue() if !CFHTTPMessageAppendBytes(response, pointer, data.count) { return false //not enough data, wait for more } if !CFHTTPMessageIsHeaderComplete(response) { return false //not enough data, wait for more } if let cfHeaders = CFHTTPMessageCopyAllHeaderFields(response) { let nsHeaders = cfHeaders.takeRetainedValue() as NSDictionary var headers = [String: String]() for (key, value) in nsHeaders { if let key = key as? String, let value = value as? String { headers[key] = value } } let code = CFHTTPMessageGetResponseStatusCode(response) if code != HTTPWSHeader.switchProtocolCode { delegate?.didReceiveHTTP(event: .failure(HTTPUpgradeError.notAnUpgrade(code, headers))) return true } delegate?.didReceiveHTTP(event: .success(headers)) return true } delegate?.didReceiveHTTP(event: .failure(HTTPUpgradeError.invalidData)) return true } public func register(delegate: HTTPHandlerDelegate) { self.delegate = delegate } private func findEndOfHTTP(data: Data) -> Int { let endBytes = [UInt8(ascii: "\r"), UInt8(ascii: "\n"), UInt8(ascii: "\r"), UInt8(ascii: "\n")] var pointer = [UInt8]() data.withUnsafeBytes { pointer.append(contentsOf: $0) } var k = 0 for i in 0.. Data { #if os(watchOS) //TODO: build response header return Data() #else let response = CFHTTPMessageCreateResponse(kCFAllocatorDefault, HTTPWSHeader.switchProtocolCode, nil, kCFHTTPVersion1_1).takeRetainedValue() //TODO: add other values to make a proper response here... //TODO: also sec key thing (Sec-WebSocket-Key) for (key, value) in headers { CFHTTPMessageSetHeaderFieldValue(response, key as CFString, value as CFString) } guard let cfData = CFHTTPMessageCopySerializedMessage(response)?.takeRetainedValue() else { return Data() } return cfData as Data #endif } public func parse(data: Data) { buffer.append(data) if parseContent(data: buffer) { buffer = Data() } } //returns true when the buffer should be cleared func parseContent(data: Data) -> Bool { var pointer = [UInt8]() data.withUnsafeBytes { pointer.append(contentsOf: $0) } #if os(watchOS) //TODO: parse data return false #else let response = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, true).takeRetainedValue() if !CFHTTPMessageAppendBytes(response, pointer, data.count) { return false //not enough data, wait for more } if !CFHTTPMessageIsHeaderComplete(response) { return false //not enough data, wait for more } if let method = CFHTTPMessageCopyRequestMethod(response)?.takeRetainedValue() { if (method as NSString) != getVerb { delegate?.didReceive(event: .failure(HTTPUpgradeError.invalidData)) return true } } if let cfHeaders = CFHTTPMessageCopyAllHeaderFields(response) { let nsHeaders = cfHeaders.takeRetainedValue() as NSDictionary var headers = [String: String]() for (key, value) in nsHeaders { if let key = key as? String, let value = value as? String { headers[key] = value } } delegate?.didReceive(event: .success(headers)) return true } delegate?.didReceive(event: .failure(HTTPUpgradeError.invalidData)) return true #endif } } ================================================ FILE: Sources/Framer/FrameCollector.swift ================================================ ////////////////////////////////////////////////////////////////////////////////////////////////// // // FrameCollector.swift // Starscream // // Created by Dalton Cherry on 1/24/19. // Copyright © 2019 Vluxe. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ////////////////////////////////////////////////////////////////////////////////////////////////// import Foundation public protocol FrameCollectorDelegate: AnyObject { func didForm(event: FrameCollector.Event) func decompress(data: Data, isFinal: Bool) -> Data? } public class FrameCollector { public enum Event { case text(String) case binary(Data) case pong(Data?) case ping(Data?) case error(Error) case closed(String, UInt16) } weak var delegate: FrameCollectorDelegate? var buffer = Data() var frameCount = 0 var isText = false //was the first frame a text frame or a binary frame? var needsDecompression = false public func add(frame: Frame) { //check single frame action and out of order frames if frame.opcode == .connectionClose { var code = frame.closeCode var reason = "connection closed by server" if let customCloseReason = String(data: frame.payload, encoding: .utf8) { reason = customCloseReason } else { code = CloseCode.protocolError.rawValue } delegate?.didForm(event: .closed(reason, code)) return } else if frame.opcode == .pong { delegate?.didForm(event: .pong(frame.payload)) return } else if frame.opcode == .ping { delegate?.didForm(event: .ping(frame.payload)) return } else if frame.opcode == .continueFrame && frameCount == 0 { let errCode = CloseCode.protocolError.rawValue delegate?.didForm(event: .error(WSError(type: .protocolError, message: "first frame can't be a continue frame", code: errCode))) reset() return } else if frameCount > 0 && frame.opcode != .continueFrame { let errCode = CloseCode.protocolError.rawValue delegate?.didForm(event: .error(WSError(type: .protocolError, message: "second and beyond of fragment message must be a continue frame", code: errCode))) reset() return } if frameCount == 0 { isText = frame.opcode == .textFrame needsDecompression = frame.needsDecompression } let payload: Data if needsDecompression { payload = delegate?.decompress(data: frame.payload, isFinal: frame.isFin) ?? frame.payload } else { payload = frame.payload } buffer.append(payload) frameCount += 1 if frame.isFin { if isText { if let string = String(data: buffer, encoding: .utf8) { delegate?.didForm(event: .text(string)) } else { let errCode = CloseCode.protocolError.rawValue delegate?.didForm(event: .error(WSError(type: .protocolError, message: "not valid UTF-8 data", code: errCode))) } } else { delegate?.didForm(event: .binary(buffer)) } reset() } } func reset() { buffer = Data() frameCount = 0 } } ================================================ FILE: Sources/Framer/Framer.swift ================================================ ////////////////////////////////////////////////////////////////////////////////////////////////// // // Framer.swift // Starscream // // Created by Dalton Cherry on 1/23/19. // Copyright © 2019 Vluxe. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ////////////////////////////////////////////////////////////////////////////////////////////////// import Foundation let FinMask: UInt8 = 0x80 let OpCodeMask: UInt8 = 0x0F let RSVMask: UInt8 = 0x70 let RSV1Mask: UInt8 = 0x40 let MaskMask: UInt8 = 0x80 let PayloadLenMask: UInt8 = 0x7F let MaxFrameSize: Int = 32 // Standard WebSocket close codes public enum CloseCode: UInt16 { case normal = 1000 case goingAway = 1001 case protocolError = 1002 case protocolUnhandledType = 1003 // 1004 reserved. case noStatusReceived = 1005 //1006 reserved. case encoding = 1007 case policyViolated = 1008 case messageTooBig = 1009 } public enum FrameOpCode: UInt8 { case continueFrame = 0x0 case textFrame = 0x1 case binaryFrame = 0x2 // 3-7 are reserved. case connectionClose = 0x8 case ping = 0x9 case pong = 0xA // B-F reserved. case unknown = 100 } public struct Frame { let isFin: Bool let needsDecompression: Bool let isMasked: Bool let opcode: FrameOpCode let payloadLength: UInt64 let payload: Data let closeCode: UInt16 //only used by connectionClose opcode } public enum FrameEvent { case frame(Frame) case error(Error) } public protocol FramerEventClient: AnyObject { func frameProcessed(event: FrameEvent) } public protocol Framer { func add(data: Data) func register(delegate: FramerEventClient) func createWriteFrame(opcode: FrameOpCode, payload: Data, isCompressed: Bool) -> Data func updateCompression(supports: Bool) func supportsCompression() -> Bool } public class WSFramer: Framer { private let queue = DispatchQueue(label: "com.vluxe.starscream.wsframer", attributes: []) private weak var delegate: FramerEventClient? private var buffer = Data() public var compressionEnabled = false private let isServer: Bool public init(isServer: Bool = false) { self.isServer = isServer } public func updateCompression(supports: Bool) { compressionEnabled = supports } public func supportsCompression() -> Bool { return compressionEnabled } enum ProcessEvent { case needsMoreData case processedFrame(Frame, Int) case failed(Error) } public func add(data: Data) { queue.async { [weak self] in self?.buffer.append(data) while(true) { let event = self?.process() ?? .needsMoreData switch event { case .needsMoreData: return case .processedFrame(let frame, let split): guard let s = self else { return } s.delegate?.frameProcessed(event: .frame(frame)) if split >= s.buffer.count { s.buffer = Data() return } s.buffer = s.buffer.advanced(by: split) case .failed(let error): self?.delegate?.frameProcessed(event: .error(error)) self?.buffer = Data() return } } } } public func register(delegate: FramerEventClient) { self.delegate = delegate } private func process() -> ProcessEvent { if buffer.count < 2 { return .needsMoreData } var pointer = [UInt8]() buffer.withUnsafeBytes { pointer.append(contentsOf: $0) } let isFin = (FinMask & pointer[0]) let opcodeRawValue = (OpCodeMask & pointer[0]) let opcode = FrameOpCode(rawValue: opcodeRawValue) ?? .unknown let isMasked = (MaskMask & pointer[1]) let payloadLen = (PayloadLenMask & pointer[1]) let RSV1 = (RSVMask & pointer[0]) var needsDecompression = false if compressionEnabled && opcode != .continueFrame { needsDecompression = (RSV1Mask & pointer[0]) > 0 } if !isServer && (isMasked > 0 || RSV1 > 0) && opcode != .pong && !needsDecompression { let errCode = CloseCode.protocolError.rawValue return .failed(WSError(type: .protocolError, message: "masked and rsv data is not currently supported", code: errCode)) } let isControlFrame = (opcode == .connectionClose || opcode == .ping || opcode == .pong) if !isControlFrame && (opcode != .binaryFrame && opcode != .continueFrame && opcode != .textFrame && opcode != .pong) { let errCode = CloseCode.protocolError.rawValue return .failed(WSError(type: .protocolError, message: "unknown opcode: \(opcodeRawValue)", code: errCode)) } if isControlFrame && isFin == 0 { let errCode = CloseCode.protocolError.rawValue return .failed(WSError(type: .protocolError, message: "control frames can't be fragmented", code: errCode)) } var offset = 2 if isControlFrame && payloadLen > 125 { return .failed(WSError(type: .protocolError, message: "payload length is longer than allowed for a control frame", code: CloseCode.protocolError.rawValue)) } var dataLength = UInt64(payloadLen) var closeCode = CloseCode.normal.rawValue if opcode == .connectionClose { if payloadLen == 1 { closeCode = CloseCode.protocolError.rawValue dataLength = 0 } else if payloadLen > 1 { if pointer.count < 4 { return .needsMoreData } let size = MemoryLayout.size closeCode = pointer.readUint16(offset: offset) offset += size dataLength -= UInt64(size) if closeCode < 1000 || (closeCode > 1003 && closeCode < 1007) || (closeCode > 1013 && closeCode < 3000) { closeCode = CloseCode.protocolError.rawValue } } } if payloadLen == 127 { let size = MemoryLayout.size if size + offset > pointer.count { return .needsMoreData } dataLength = pointer.readUint64(offset: offset) offset += size } else if payloadLen == 126 { let size = MemoryLayout.size if size + offset > pointer.count { return .needsMoreData } dataLength = UInt64(pointer.readUint16(offset: offset)) offset += size } let maskStart = offset if isServer { offset += MemoryLayout.size } if dataLength > (pointer.count - offset) { return .needsMoreData } //I don't like this cast, but Data's count returns an Int. //Might be a problem with huge payloads. Need to revisit. let readDataLength = Int(dataLength) let payload: Data if readDataLength == 0 { payload = Data() } else { if isServer { payload = pointer.unmaskData(maskStart: maskStart, offset: offset, length: readDataLength) } else { let end = offset + readDataLength payload = Data(pointer[offset.. 0, needsDecompression: needsDecompression, isMasked: isMasked > 0, opcode: opcode, payloadLength: dataLength, payload: payload, closeCode: closeCode) return .processedFrame(frame, offset) } public func createWriteFrame(opcode: FrameOpCode, payload: Data, isCompressed: Bool) -> Data { let payloadLength = payload.count let capacity = payloadLength + MaxFrameSize var pointer = [UInt8](repeating: 0, count: capacity) //set the framing info pointer[0] = FinMask | opcode.rawValue if isCompressed { pointer[0] |= RSV1Mask } var offset = 2 //skip pass the framing info if payloadLength < 126 { pointer[1] = UInt8(payloadLength) } else if payloadLength <= Int(UInt16.max) { pointer[1] = 126 writeUint16(&pointer, offset: offset, value: UInt16(payloadLength)) offset += MemoryLayout.size } else { pointer[1] = 127 writeUint64(&pointer, offset: offset, value: UInt64(payloadLength)) offset += MemoryLayout.size } //clients are required to mask the payload data, but server don't according to the RFC if !isServer { pointer[1] |= MaskMask //write the random mask key in let maskKey: UInt32 = UInt32.random(in: 0...UInt32.max) writeUint32(&pointer, offset: offset, value: maskKey) let maskStart = offset offset += MemoryLayout.size //now write the payload data in for i in 0...size)] offset += 1 } } else { for i in 0.. UInt16 { return (UInt16(self[offset + 0]) << 8) | UInt16(self[offset + 1]) } /** Read a UInt64 from a buffer. - parameter offset: is the offset index to start the read from (e.g. buffer[0], buffer[1], etc). - returns: a UInt64 of the value from the buffer */ func readUint64(offset: Int) -> UInt64 { var value = UInt64(0) for i in 0...7 { value = (value << 8) | UInt64(self[offset + i]) } return value } func unmaskData(maskStart: Int, offset: Int, length: Int) -> Data { var unmaskedBytes = [UInt8](repeating: 0, count: length) let maskSize = MemoryLayout.size for i in 0..> 8) buffer[offset + 1] = UInt8(value & 0xff) } /** Write a UInt32 to the buffer. It fills the 4 array "slots" of the UInt8 array. - parameter buffer: is the UInt8 array (pointer) to write the value too. - parameter offset: is the offset index to start the write from (e.g. buffer[0], buffer[1], etc). */ public func writeUint32( _ buffer: inout [UInt8], offset: Int, value: UInt32) { for i in 0...3 { buffer[offset + i] = UInt8((value >> (8*UInt32(3 - i))) & 0xff) } } /** Write a UInt64 to the buffer. It fills the 8 array "slots" of the UInt8 array. - parameter buffer: is the UInt8 array (pointer) to write the value too. - parameter offset: is the offset index to start the write from (e.g. buffer[0], buffer[1], etc). */ public func writeUint64( _ buffer: inout [UInt8], offset: Int, value: UInt64) { for i in 0...7 { buffer[offset + i] = UInt8((value >> (8*UInt64(7 - i))) & 0xff) } } ================================================ FILE: Sources/Framer/HTTPHandler.swift ================================================ ////////////////////////////////////////////////////////////////////////////////////////////////// // // HTTPHandler.swift // Starscream // // Created by Dalton Cherry on 1/24/19. // Copyright © 2019 Vluxe. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ////////////////////////////////////////////////////////////////////////////////////////////////// import Foundation public enum HTTPUpgradeError: Error { case notAnUpgrade(Int, [String: String]) case invalidData } public struct HTTPWSHeader { static let upgradeName = "Upgrade" static let upgradeValue = "websocket" static let hostName = "Host" static let connectionName = "Connection" static let connectionValue = "Upgrade" static let protocolName = "Sec-WebSocket-Protocol" static let versionName = "Sec-WebSocket-Version" static let versionValue = "13" static let extensionName = "Sec-WebSocket-Extensions" static let keyName = "Sec-WebSocket-Key" static let originName = "Origin" static let acceptName = "Sec-WebSocket-Accept" static let switchProtocolCode = 101 static let defaultSSLSchemes = ["wss", "https"] /// Creates a new URLRequest based off the source URLRequest. /// - Parameter request: the request to "upgrade" the WebSocket request by adding headers. /// - Parameter supportsCompression: set if the client support text compression. /// - Parameter secKeyName: the security key to use in the WebSocket request. https://tools.ietf.org/html/rfc6455#section-1.3 /// - returns: A URLRequest request to be converted to data and sent to the server. public static func createUpgrade(request: URLRequest, supportsCompression: Bool, secKeyValue: String) -> URLRequest { guard let url = request.url, let parts = url.getParts() else { return request } var req = request if request.value(forHTTPHeaderField: HTTPWSHeader.originName) == nil { var origin = url.absoluteString if let hostUrl = URL (string: "/", relativeTo: url) { origin = hostUrl.absoluteString origin.remove(at: origin.index(before: origin.endIndex)) } req.setValue(origin, forHTTPHeaderField: HTTPWSHeader.originName) } req.setValue(HTTPWSHeader.upgradeValue, forHTTPHeaderField: HTTPWSHeader.upgradeName) req.setValue(HTTPWSHeader.connectionValue, forHTTPHeaderField: HTTPWSHeader.connectionName) req.setValue(HTTPWSHeader.versionValue, forHTTPHeaderField: HTTPWSHeader.versionName) req.setValue(secKeyValue, forHTTPHeaderField: HTTPWSHeader.keyName) if req.allHTTPHeaderFields?["Cookie"] == nil { if let cookies = HTTPCookieStorage.shared.cookies(for: url), !cookies.isEmpty { let headers = HTTPCookie.requestHeaderFields(with: cookies) for (key, val) in headers { req.setValue(val, forHTTPHeaderField: key) } } } if supportsCompression { let val = "permessage-deflate; client_max_window_bits; server_max_window_bits=15" req.setValue(val, forHTTPHeaderField: HTTPWSHeader.extensionName) } let hostValue = req.allHTTPHeaderFields?[HTTPWSHeader.hostName] ?? "\(parts.host):\(parts.port)" req.setValue(hostValue, forHTTPHeaderField: HTTPWSHeader.hostName) return req } // generateWebSocketKey 16 random characters between a-z and return them as a base64 string public static func generateWebSocketKey() -> String { return Data((0..<16).map{ _ in UInt8.random(in: 97...122) }).base64EncodedString() } } public enum HTTPEvent { case success([String: String]) case failure(Error) } public protocol HTTPHandlerDelegate: AnyObject { func didReceiveHTTP(event: HTTPEvent) } public protocol HTTPHandler { func register(delegate: HTTPHandlerDelegate) func convert(request: URLRequest) -> Data func parse(data: Data) -> Int } public protocol HTTPServerDelegate: AnyObject { func didReceive(event: HTTPEvent) } public protocol HTTPServerHandler { func register(delegate: HTTPServerDelegate) func parse(data: Data) func createResponse(headers: [String: String]) -> Data } public struct URLParts { let port: Int let host: String let isTLS: Bool } public extension URL { /// isTLSScheme returns true if the scheme is https or wss var isTLSScheme: Bool { guard let scheme = self.scheme else { return false } return HTTPWSHeader.defaultSSLSchemes.contains(scheme) } /// getParts pulls host and port from the url. func getParts() -> URLParts? { guard let host = self.host else { return nil // no host, this isn't a valid url } let isTLS = isTLSScheme var port = self.port ?? 0 if self.port == nil { if isTLS { port = 443 } else { port = 80 } } return URLParts(port: port, host: host, isTLS: isTLS) } } ================================================ FILE: Sources/Framer/StringHTTPHandler.swift ================================================ ////////////////////////////////////////////////////////////////////////////////////////////////// // // StringHTTPHandler.swift // Starscream // // Created by Dalton Cherry on 8/25/19. // Copyright © 2019 Vluxe. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ////////////////////////////////////////////////////////////////////////////////////////////////// import Foundation public class StringHTTPHandler: HTTPHandler { var buffer = Data() weak var delegate: HTTPHandlerDelegate? public init() { } public func convert(request: URLRequest) -> Data { guard let url = request.url else { return Data() } var path = url.absoluteString let offset = (url.scheme?.count ?? 2) + 3 path = String(path[path.index(path.startIndex, offsetBy: offset).. Int { let offset = findEndOfHTTP(data: data) if offset > 0 { buffer.append(data.subdata(in: 0.. Bool { guard let str = String(data: data, encoding: .utf8) else { delegate?.didReceiveHTTP(event: .failure(HTTPUpgradeError.invalidData)) return true } let splitArr = str.components(separatedBy: "\r\n") var code = -1 var i = 0 var headers = [String: String]() for str in splitArr { if i == 0 { let responseSplit = str.components(separatedBy: .whitespaces) guard responseSplit.count > 1 else { delegate?.didReceiveHTTP(event: .failure(HTTPUpgradeError.invalidData)) return true } if let c = Int(responseSplit[1]) { code = c } } else { guard let separatorIndex = str.firstIndex(of: ":") else { break } let key = str.prefix(upTo: separatorIndex).trimmingCharacters(in: .whitespaces) let val = str.suffix(from: str.index(after: separatorIndex)).trimmingCharacters(in: .whitespaces) headers[key.lowercased()] = val } i += 1 } if code != HTTPWSHeader.switchProtocolCode { delegate?.didReceiveHTTP(event: .failure(HTTPUpgradeError.notAnUpgrade(code, headers))) return true } delegate?.didReceiveHTTP(event: .success(headers)) return true } public func register(delegate: HTTPHandlerDelegate) { self.delegate = delegate } private func findEndOfHTTP(data: Data) -> Int { let endBytes = [UInt8(ascii: "\r"), UInt8(ascii: "\n"), UInt8(ascii: "\r"), UInt8(ascii: "\n")] var pointer = [UInt8]() data.withUnsafeBytes { pointer.append(contentsOf: $0) } var k = 0 for i in 0.. CFBundleDevelopmentRegion en CFBundleExecutable $(EXECUTABLE_NAME) CFBundleIdentifier $(PRODUCT_BUNDLE_IDENTIFIER) CFBundleInfoDictionaryVersion 6.0 CFBundleName $(PRODUCT_NAME) CFBundlePackageType FMWK CFBundleShortVersionString $(MARKETING_VERSION) CFBundleSignature ???? CFBundleVersion $(CURRENT_PROJECT_VERSION) NSPrincipalClass ================================================ FILE: Sources/PrivacyInfo.xcprivacy ================================================ NSPrivacyTracking NSPrivacyTrackingDomains NSPrivacyCollectedDataTypes NSPrivacyAccessedAPITypes ================================================ FILE: Sources/Security/FoundationSecurity.swift ================================================ ////////////////////////////////////////////////////////////////////////////////////////////////// // // FoundationSecurity.swift // Starscream // // Created by Dalton Cherry on 3/16/19. // Copyright © 2019 Vluxe. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ////////////////////////////////////////////////////////////////////////////////////////////////// import Foundation import CommonCrypto public enum FoundationSecurityError: Error { case invalidRequest } public class FoundationSecurity { var allowSelfSigned = false public init(allowSelfSigned: Bool = false) { self.allowSelfSigned = allowSelfSigned } } extension FoundationSecurity: CertificatePinning { public func evaluateTrust(trust: SecTrust, domain: String?, completion: ((PinningState) -> ())) { if allowSelfSigned { completion(.success) return } SecTrustSetPolicies(trust, SecPolicyCreateSSL(true, domain as NSString?)) handleSecurityTrust(trust: trust, completion: completion) } private func handleSecurityTrust(trust: SecTrust, completion: ((PinningState) -> ())) { if #available(iOS 12.0, OSX 10.14, watchOS 5.0, tvOS 12.0, *) { var error: CFError? if SecTrustEvaluateWithError(trust, &error) { completion(.success) } else { completion(.failed(error)) } } else { handleOldSecurityTrust(trust: trust, completion: completion) } } private func handleOldSecurityTrust(trust: SecTrust, completion: ((PinningState) -> ())) { var result: SecTrustResultType = .unspecified SecTrustEvaluate(trust, &result) if result == .unspecified || result == .proceed { completion(.success) } else { let e = CFErrorCreate(kCFAllocatorDefault, "FoundationSecurityError" as NSString?, Int(result.rawValue), nil) completion(.failed(e)) } } } extension FoundationSecurity: HeaderValidator { public func validate(headers: [String: String], key: String) -> Error? { if let acceptKey = headers[HTTPWSHeader.acceptName] { let sha = "\(key)258EAFA5-E914-47DA-95CA-C5AB0DC85B11".sha1Base64() if sha != acceptKey { return WSError(type: .securityError, message: "accept header doesn't match", code: SecurityErrorCode.acceptFailed.rawValue) } } return nil } } private extension String { func sha1Base64() -> String { let data = self.data(using: .utf8)! let pointer = data.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) -> [UInt8] in var digest = [UInt8](repeating: 0, count:Int(CC_SHA1_DIGEST_LENGTH)) CC_SHA1(bytes.baseAddress, CC_LONG(data.count), &digest) return digest } return Data(pointer).base64EncodedString() } } ================================================ FILE: Sources/Security/Security.swift ================================================ ////////////////////////////////////////////////////////////////////////////////////////////////// // // Security.swift // Starscream // // Created by Dalton Cherry on 3/16/19. // Copyright © 2019 Vluxe. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ////////////////////////////////////////////////////////////////////////////////////////////////// import Foundation public enum SecurityErrorCode: UInt16 { case acceptFailed = 1 case pinningFailed = 2 } public enum PinningState { case success case failed(CFError?) } // CertificatePinning protocol provides an interface for Transports to handle Certificate // or Public Key Pinning. public protocol CertificatePinning: AnyObject { func evaluateTrust(trust: SecTrust, domain: String?, completion: ((PinningState) -> ())) } // validates the "Sec-WebSocket-Accept" header as defined 1.3 of the RFC 6455 // https://tools.ietf.org/html/rfc6455#section-1.3 public protocol HeaderValidator: AnyObject { func validate(headers: [String: String], key: String) -> Error? } ================================================ FILE: Sources/Server/Server.swift ================================================ ////////////////////////////////////////////////////////////////////////////////////////////////// // // Server.swift // Starscream // // Created by Dalton Cherry on 4/2/19. // Copyright © 2019 Vluxe. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ////////////////////////////////////////////////////////////////////////////////////////////////// import Foundation public enum ConnectionEvent { case connected([String: String]) case disconnected(String, UInt16) case text(String) case binary(Data) case pong(Data?) case ping(Data?) case error(Error) } public protocol Connection { func write(data: Data, opcode: FrameOpCode) } public protocol ConnectionDelegate: AnyObject { func didReceive(event: ServerEvent) } public enum ServerEvent { case connected(Connection, [String: String]) case disconnected(Connection, String, UInt16) case text(Connection, String) case binary(Connection, Data) case pong(Connection, Data?) case ping(Connection, Data?) } public protocol Server { func start(address: String, port: UInt16) -> Error? } ================================================ FILE: Sources/Server/WebSocketServer.swift ================================================ ////////////////////////////////////////////////////////////////////////////////////////////////// // // WebSocketServer.swift // Starscream // // Created by Dalton Cherry on 4/5/19. // Copyright © 2019 Vluxe. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ////////////////////////////////////////////////////////////////////////////////////////////////// #if canImport(Network) import Foundation import Network /// WebSocketServer is a Network.framework implementation of a WebSocket server @available(watchOS, unavailable) @available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) public class WebSocketServer: Server, ConnectionDelegate { public var onEvent: ((ServerEvent) -> Void)? private var connections = [String: ServerConnection]() private var listener: NWListener? private let queue = DispatchQueue(label: "com.vluxe.starscream.server.networkstream", attributes: []) public init() { } public func start(address: String, port: UInt16) -> Error? { //TODO: support TLS cert adding/binding let parameters = NWParameters(tls: nil, tcp: NWProtocolTCP.Options()) let p = NWEndpoint.Port(rawValue: port)! parameters.requiredLocalEndpoint = NWEndpoint.hostPort(host: NWEndpoint.Host.name(address, nil), port: p) guard let listener = try? NWListener(using: parameters, on: p) else { return WSError(type: .serverError, message: "unable to start the listener at: \(address):\(port)", code: 0) } listener.newConnectionHandler = {[weak self] conn in let transport = TCPTransport(connection: conn) let c = ServerConnection(transport: transport) c.delegate = self self?.connections[c.uuid] = c } // listener.stateUpdateHandler = { state in // switch state { // case .ready: // print("ready to get sockets!") // case .setup: // print("setup to get sockets!") // case .cancelled: // print("server cancelled!") // case .waiting(let error): // print("waiting error: \(error)") // case .failed(let error): // print("server failed: \(error)") // @unknown default: // print("wat?") // } // } self.listener = listener listener.start(queue: queue) return nil } public func didReceive(event: ServerEvent) { onEvent?(event) switch event { case .disconnected(let conn, _, _): guard let conn = conn as? ServerConnection else { return } connections.removeValue(forKey: conn.uuid) default: break } } } @available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) public class ServerConnection: Connection, HTTPServerDelegate, FramerEventClient, FrameCollectorDelegate, TransportEventClient { let transport: TCPTransport private let httpHandler = FoundationHTTPServerHandler() private let framer = WSFramer(isServer: true) private let frameHandler = FrameCollector() private var didUpgrade = false public var onEvent: ((ConnectionEvent) -> Void)? public weak var delegate: ConnectionDelegate? private let id: String var uuid: String { return id } init(transport: TCPTransport) { self.id = UUID().uuidString self.transport = transport transport.register(delegate: self) httpHandler.register(delegate: self) framer.register(delegate: self) frameHandler.delegate = self } public func write(data: Data, opcode: FrameOpCode) { let wsData = framer.createWriteFrame(opcode: opcode, payload: data, isCompressed: false) transport.write(data: wsData, completion: {_ in }) } // MARK: - TransportEventClient public func connectionChanged(state: ConnectionState) { switch state { case .connected: break case .waiting: break case .failed(let error): print("server connection error: \(error ?? WSError(type: .protocolError, message: "default error, no extra data", code: 0))") //handleError(error) case .viability(_): break case .shouldReconnect(_): break case .receive(let data): if didUpgrade { framer.add(data: data) } else { httpHandler.parse(data: data) } case .cancelled: print("server connection cancelled!") //broadcast(event: .cancelled) case .peerClosed: delegate?.didReceive(event: .disconnected(self, "Connection closed by peer", UInt16(FrameOpCode.connectionClose.rawValue))) } } /// MARK: - HTTPServerDelegate public func didReceive(event: HTTPEvent) { switch event { case .success(let headers): didUpgrade = true let response = httpHandler.createResponse(headers: [:]) transport.write(data: response, completion: {_ in }) delegate?.didReceive(event: .connected(self, headers)) onEvent?(.connected(headers)) case .failure(let error): onEvent?(.error(error)) } } /// MARK: - FrameCollectorDelegate public func frameProcessed(event: FrameEvent) { switch event { case .frame(let frame): frameHandler.add(frame: frame) case .error(let error): onEvent?(.error(error)) } } public func didForm(event: FrameCollector.Event) { switch event { case .text(let string): delegate?.didReceive(event: .text(self, string)) onEvent?(.text(string)) case .binary(let data): delegate?.didReceive(event: .binary(self, data)) onEvent?(.binary(data)) case .pong(let data): delegate?.didReceive(event: .pong(self, data)) onEvent?(.pong(data)) case .ping(let data): delegate?.didReceive(event: .ping(self, data)) onEvent?(.ping(data)) case .closed(let reason, let code): delegate?.didReceive(event: .disconnected(self, reason, code)) onEvent?(.disconnected(reason, code)) case .error(let error): onEvent?(.error(error)) } } public func decompress(data: Data, isFinal: Bool) -> Data? { return nil } } #endif ================================================ FILE: Sources/Starscream/WebSocket.swift ================================================ ////////////////////////////////////////////////////////////////////////////////////////////////// // // Websocket.swift // Starscream // // Created by Dalton Cherry on 7/16/14. // Copyright (c) 2014-2019 Dalton Cherry. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ////////////////////////////////////////////////////////////////////////////////////////////////// import Foundation public enum ErrorType: Error { case compressionError case securityError case protocolError //There was an error parsing the WebSocket frames case serverError } public struct WSError: Error { public let type: ErrorType public let message: String public let code: UInt16 public init(type: ErrorType, message: String, code: UInt16) { self.type = type self.message = message self.code = code } } public protocol WebSocketClient: AnyObject { func connect() func disconnect(closeCode: UInt16) func write(string: String, completion: (() -> ())?) func write(stringData: Data, completion: (() -> ())?) func write(data: Data, completion: (() -> ())?) func write(ping: Data, completion: (() -> ())?) func write(pong: Data, completion: (() -> ())?) } //implements some of the base behaviors extension WebSocketClient { public func write(string: String) { write(string: string, completion: nil) } public func write(data: Data) { write(data: data, completion: nil) } public func write(ping: Data) { write(ping: ping, completion: nil) } public func write(pong: Data) { write(pong: pong, completion: nil) } public func disconnect() { disconnect(closeCode: CloseCode.normal.rawValue) } } public enum WebSocketEvent { case connected([String: String]) case disconnected(String, UInt16) case text(String) case binary(Data) case pong(Data?) case ping(Data?) case error(Error?) case viabilityChanged(Bool) case reconnectSuggested(Bool) case cancelled case peerClosed } public protocol WebSocketDelegate: AnyObject { func didReceive(event: WebSocketEvent, client: WebSocketClient) } open class WebSocket: WebSocketClient, EngineDelegate { private let engine: Engine public weak var delegate: WebSocketDelegate? public var onEvent: ((WebSocketEvent) -> Void)? public var request: URLRequest // Where the callback is executed. It defaults to the main UI thread queue. public var callbackQueue = DispatchQueue.main public var respondToPingWithPong: Bool { set { guard let e = engine as? WSEngine else { return } e.respondToPingWithPong = newValue } get { guard let e = engine as? WSEngine else { return true } return e.respondToPingWithPong } } public init(request: URLRequest, engine: Engine) { self.request = request self.engine = engine } public convenience init(request: URLRequest, certPinner: CertificatePinning? = FoundationSecurity(), compressionHandler: CompressionHandler? = nil, useCustomEngine: Bool = true) { if #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *), !useCustomEngine { self.init(request: request, engine: NativeEngine()) } else if #available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) { self.init(request: request, engine: WSEngine(transport: TCPTransport(), certPinner: certPinner, compressionHandler: compressionHandler)) } else { self.init(request: request, engine: WSEngine(transport: FoundationTransport(), certPinner: certPinner, compressionHandler: compressionHandler)) } } public func connect() { engine.register(delegate: self) engine.start(request: request) } public func disconnect(closeCode: UInt16 = CloseCode.normal.rawValue) { engine.stop(closeCode: closeCode) } public func forceDisconnect() { engine.forceStop() } public func write(data: Data, completion: (() -> ())?) { write(data: data, opcode: .binaryFrame, completion: completion) } public func write(string: String, completion: (() -> ())?) { engine.write(string: string, completion: completion) } public func write(stringData: Data, completion: (() -> ())?) { write(data: stringData, opcode: .textFrame, completion: completion) } public func write(ping: Data, completion: (() -> ())?) { write(data: ping, opcode: .ping, completion: completion) } public func write(pong: Data, completion: (() -> ())?) { write(data: pong, opcode: .pong, completion: completion) } private func write(data: Data, opcode: FrameOpCode, completion: (() -> ())?) { engine.write(data: data, opcode: opcode, completion: completion) } // MARK: - EngineDelegate public func didReceive(event: WebSocketEvent) { callbackQueue.async { [weak self] in guard let s = self else { return } s.delegate?.didReceive(event: event, client: s) s.onEvent?(event) } } } ================================================ FILE: Sources/Starscream.h ================================================ ////////////////////////////////////////////////////////////////////////////////////////////////// // // Starscream.h // Starscream // // Created by Austin Cherry on 9/25/14. // Copyright © 2014 Vluxe. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ////////////////////////////////////////////////////////////////////////////////////////////////// #import //! Project version number for Starscream. FOUNDATION_EXPORT double StarscreamVersionNumber; //! Project version string for Starscream. FOUNDATION_EXPORT const unsigned char StarscreamVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import ================================================ FILE: Sources/Transport/FoundationTransport.swift ================================================ ////////////////////////////////////////////////////////////////////////////////////////////////// // // FoundationTransport.swift // Starscream // // Created by Dalton Cherry on 1/23/19. // Copyright © 2019 Vluxe. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ////////////////////////////////////////////////////////////////////////////////////////////////// import Foundation public enum FoundationTransportError: Error { case invalidRequest case invalidOutputStream case timeout } public class FoundationTransport: NSObject, Transport, StreamDelegate { private weak var delegate: TransportEventClient? private let workQueue = DispatchQueue(label: "com.vluxe.starscream.websocket", attributes: []) private var inputStream: InputStream? private var outputStream: OutputStream? private var isOpen = false private var onConnect: ((InputStream, OutputStream) -> Void)? private var isTLS = false private var certPinner: CertificatePinning? public var usingTLS: Bool { return self.isTLS } public init(streamConfiguration: ((InputStream, OutputStream) -> Void)? = nil) { super.init() onConnect = streamConfiguration } deinit { inputStream?.delegate = nil outputStream?.delegate = nil } public func connect(url: URL, timeout: Double = 10, certificatePinning: CertificatePinning? = nil) { guard let parts = url.getParts() else { delegate?.connectionChanged(state: .failed(FoundationTransportError.invalidRequest)) return } self.certPinner = certificatePinning self.isTLS = parts.isTLS var readStream: Unmanaged? var writeStream: Unmanaged? let h = parts.host as NSString CFStreamCreatePairWithSocketToHost(nil, h, UInt32(parts.port), &readStream, &writeStream) inputStream = readStream!.takeRetainedValue() outputStream = writeStream!.takeRetainedValue() guard let inStream = inputStream, let outStream = outputStream else { return } inStream.delegate = self outStream.delegate = self if isTLS { let key = CFStreamPropertyKey(rawValue: kCFStreamPropertySocketSecurityLevel) CFReadStreamSetProperty(inStream, key, kCFStreamSocketSecurityLevelNegotiatedSSL) CFWriteStreamSetProperty(outStream, key, kCFStreamSocketSecurityLevelNegotiatedSSL) } onConnect?(inStream, outStream) isOpen = false CFReadStreamSetDispatchQueue(inStream, workQueue) CFWriteStreamSetDispatchQueue(outStream, workQueue) inStream.open() outStream.open() workQueue.asyncAfter(deadline: .now() + timeout, execute: { [weak self] in guard let s = self else { return } if !s.isOpen { s.delegate?.connectionChanged(state: .failed(FoundationTransportError.timeout)) } }) } public func disconnect() { if let stream = inputStream { stream.delegate = nil CFReadStreamSetDispatchQueue(stream, nil) stream.close() } if let stream = outputStream { stream.delegate = nil CFWriteStreamSetDispatchQueue(stream, nil) stream.close() } isOpen = false outputStream = nil inputStream = nil } public func register(delegate: TransportEventClient) { self.delegate = delegate } public func write(data: Data, completion: @escaping ((Error?) -> ())) { guard let outStream = outputStream else { completion(FoundationTransportError.invalidOutputStream) return } var total = 0 let buffer = UnsafeRawPointer((data as NSData).bytes).assumingMemoryBound(to: UInt8.self) //NOTE: this might need to be dispatched to the work queue instead of being written inline. TBD. while total < data.count { let written = outStream.write(buffer, maxLength: data.count) if written < 0 { completion(FoundationTransportError.invalidOutputStream) return } total += written } completion(nil) } private func getSecurityData() -> (SecTrust?, String?) { #if os(watchOS) return (nil, nil) #else guard let outputStream = outputStream else { return (nil, nil) } let trust = outputStream.property(forKey: kCFStreamPropertySSLPeerTrust as Stream.PropertyKey) as! SecTrust? var domain = outputStream.property(forKey: kCFStreamSSLPeerName as Stream.PropertyKey) as! String? if domain == nil, let sslContextOut = CFWriteStreamCopyProperty(outputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLContext)) as! SSLContext? { var peerNameLen: Int = 0 SSLGetPeerDomainNameLength(sslContextOut, &peerNameLen) var peerName = Data(count: peerNameLen) let _ = peerName.withUnsafeMutableBytes { (peerNamePtr: UnsafeMutablePointer) in SSLGetPeerDomainName(sslContextOut, peerNamePtr, &peerNameLen) } if let peerDomain = String(bytes: peerName, encoding: .utf8), peerDomain.count > 0 { domain = peerDomain } } return (trust, domain) #endif } private func read() { guard let stream = inputStream else { return } let maxBuffer = 4096 let buf = NSMutableData(capacity: maxBuffer) let buffer = UnsafeMutableRawPointer(mutating: buf!.bytes).assumingMemoryBound(to: UInt8.self) let length = stream.read(buffer, maxLength: maxBuffer) if length < 1 { return } let data = Data(bytes: buffer, count: length) delegate?.connectionChanged(state: .receive(data)) } // MARK: - StreamDelegate open func stream(_ aStream: Stream, handle eventCode: Stream.Event) { switch eventCode { case .hasBytesAvailable: if aStream == inputStream { read() } case .errorOccurred: delegate?.connectionChanged(state: .failed(aStream.streamError)) case .endEncountered: if aStream == inputStream { delegate?.connectionChanged(state: .cancelled) } case .openCompleted: if aStream == inputStream { let (trust, domain) = getSecurityData() if let pinner = certPinner, let trust = trust { pinner.evaluateTrust(trust: trust, domain: domain, completion: { [weak self] (state) in switch state { case .success: self?.isOpen = true self?.delegate?.connectionChanged(state: .connected) case .failed(let error): self?.delegate?.connectionChanged(state: .failed(error)) } }) } else { isOpen = true delegate?.connectionChanged(state: .connected) } } case .endEncountered: if aStream == inputStream { delegate?.connectionChanged(state: .cancelled) } default: break } } } ================================================ FILE: Sources/Transport/TCPTransport.swift ================================================ ////////////////////////////////////////////////////////////////////////////////////////////////// // // HTTPTransport.swift // Starscream // // Created by Dalton Cherry on 1/23/19. // Copyright © 2019 Vluxe. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ////////////////////////////////////////////////////////////////////////////////////////////////// #if canImport(Network) import Foundation import Network public enum TCPTransportError: Error { case invalidRequest } @available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) public class TCPTransport: Transport { private var connection: NWConnection? private let queue = DispatchQueue(label: "com.vluxe.starscream.networkstream", attributes: []) private weak var delegate: TransportEventClient? private var isRunning = false private var isTLS = false deinit { disconnect() } public var usingTLS: Bool { return self.isTLS } public init(connection: NWConnection) { self.connection = connection start() } public init() { //normal connection, will use the "connect" method below } public func connect(url: URL, timeout: Double = 10, certificatePinning: CertificatePinning? = nil) { guard let parts = url.getParts() else { delegate?.connectionChanged(state: .failed(TCPTransportError.invalidRequest)) return } self.isTLS = parts.isTLS let options = NWProtocolTCP.Options() options.connectionTimeout = Int(timeout.rounded(.up)) let tlsOptions = isTLS ? NWProtocolTLS.Options() : nil if let tlsOpts = tlsOptions { sec_protocol_options_set_verify_block(tlsOpts.securityProtocolOptions, { (sec_protocol_metadata, sec_trust, sec_protocol_verify_complete) in let trust = sec_trust_copy_ref(sec_trust).takeRetainedValue() guard let pinner = certificatePinning else { sec_protocol_verify_complete(true) return } pinner.evaluateTrust(trust: trust, domain: parts.host, completion: { (state) in switch state { case .success: sec_protocol_verify_complete(true) case .failed(_): sec_protocol_verify_complete(false) } }) }, queue) } let parameters = NWParameters(tls: tlsOptions, tcp: options) let conn = NWConnection(host: NWEndpoint.Host.name(parts.host, nil), port: NWEndpoint.Port(rawValue: UInt16(parts.port))!, using: parameters) connection = conn start() } public func disconnect() { isRunning = false connection?.cancel() connection = nil } public func register(delegate: TransportEventClient) { self.delegate = delegate } public func write(data: Data, completion: @escaping ((Error?) -> ())) { connection?.send(content: data, completion: .contentProcessed { (error) in completion(error) }) } private func start() { guard let conn = connection else { return } conn.stateUpdateHandler = { [weak self] (newState) in switch newState { case .ready: self?.delegate?.connectionChanged(state: .connected) case .waiting: self?.delegate?.connectionChanged(state: .waiting) case .cancelled: self?.delegate?.connectionChanged(state: .cancelled) case .failed(let error): self?.delegate?.connectionChanged(state: .failed(error)) case .setup, .preparing: break @unknown default: break } } conn.viabilityUpdateHandler = { [weak self] (isViable) in self?.delegate?.connectionChanged(state: .viability(isViable)) } conn.betterPathUpdateHandler = { [weak self] (isBetter) in self?.delegate?.connectionChanged(state: .shouldReconnect(isBetter)) } conn.start(queue: queue) isRunning = true readLoop() } //readLoop keeps reading from the connection to get the latest content private func readLoop() { if !isRunning { return } connection?.receive(minimumIncompleteLength: 2, maximumLength: 4096, completion: {[weak self] (data, context, isComplete, error) in guard let s = self else {return} if let data = data { s.delegate?.connectionChanged(state: .receive(data)) } // Refer to https://developer.apple.com/documentation/network/implementing_netcat_with_network_framework if let context = context, context.isFinal, isComplete { if let delegate = s.delegate { // Let the owner of this TCPTransport decide what to do next: disconnect or reconnect? delegate.connectionChanged(state: .peerClosed) } else { // No use to keep connection alive s.disconnect() } return } if error == nil { s.readLoop() } }) } } #else typealias TCPTransport = FoundationTransport #endif ================================================ FILE: Sources/Transport/Transport.swift ================================================ ////////////////////////////////////////////////////////////////////////////////////////////////// // // Transport.swift // Starscream // // Created by Dalton Cherry on 1/23/19. // Copyright © 2019 Vluxe. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ////////////////////////////////////////////////////////////////////////////////////////////////// import Foundation public enum ConnectionState { /// Ready connections can send and receive data case connected /// Waiting connections have not yet been started, or do not have a viable network case waiting /// Cancelled connections have been invalidated by the client and will send no more events case cancelled /// Failed connections are disconnected and can no longer send or receive data case failed(Error?) /// Viability (connection status) of the connection has updated /// e.g. connection is down, connection came back up, etc. case viability(Bool) /// Connection ca be upgraded to wifi from cellular. /// You should consider reconnecting to take advantage of this. case shouldReconnect(Bool) /// Received data case receive(Data) /// Remote peer has closed the network connection. case peerClosed } public protocol TransportEventClient: AnyObject { func connectionChanged(state: ConnectionState) } public protocol Transport: AnyObject { func register(delegate: TransportEventClient) func connect(url: URL, timeout: Double, certificatePinning: CertificatePinning?) func disconnect() func write(data: Data, completion: @escaping ((Error?) -> ())) var usingTLS: Bool { get } } ================================================ FILE: Starscream.podspec ================================================ Pod::Spec.new do |s| s.name = "Starscream" s.version = "4.0.4" s.summary = "A conforming WebSocket RFC 6455 client library in Swift." s.homepage = "https://github.com/daltoniam/Starscream" s.license = 'Apache License, Version 2.0' s.author = {'Dalton Cherry' => 'http://daltoniam.com', 'Austin Cherry' => 'http://austincherry.me'} s.source = { :git => 'https://github.com/daltoniam/Starscream.git', :tag => "#{s.version}"} s.social_media_url = 'http://twitter.com/daltoniam' s.ios.deployment_target = '12.0' s.osx.deployment_target = '10.13' s.tvos.deployment_target = '12.0' s.watchos.deployment_target = '2.0' s.source_files = 'Sources/**/*.swift' s.swift_version = '5.0' s.resource_bundles = { 'Starscream_Privacy' => ['Sources/PrivacyInfo.xcprivacy'], } end ================================================ FILE: Tests/CompressionTests.swift ================================================ ////////////////////////////////////////////////////////////////////////////////////////////////// // // CompressionTests.swift // // Created by Joseph Ross on 7/16/14. // Copyright © 2017 Joseph Ross. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ////////////////////////////////////////////////////////////////////////////////////////////////// import XCTest @testable import Starscream class CompressionTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testBasic() { let compressor = Compressor(windowBits: 15)! let decompressor = Decompressor(windowBits: 15)! let rawData = "Hello, World! Hello, World! Hello, World! Hello, World! Hello, World!".data(using: .utf8)! let compressed = try! compressor.compress(rawData) let uncompressed = try! decompressor.decompress(compressed, finish: true) XCTAssert(rawData == uncompressed) } func testHugeData() { let compressor = Compressor(windowBits: 15)! let decompressor = Decompressor(windowBits: 15)! // 2 Gigs! // var rawData = Data(repeating: 0, count: 0x80000000) var rawData = Data(repeating: 0, count: 0x80000) let rawDataLen = rawData.count rawData.withUnsafeMutableBytes { (ptr: UnsafeMutablePointer) -> Void in arc4random_buf(ptr, rawDataLen) } let compressed = try! compressor.compress(rawData) let uncompressed = try! decompressor.decompress(compressed, finish: true) XCTAssert(rawData == uncompressed) } } ================================================ FILE: Tests/FuzzingTests.swift ================================================ ////////////////////////////////////////////////////////////////////////////////////////////////// // // FuzzingTests.swift // Starscream // // Created by Dalton Cherry on 1/28/19. // Copyright © 2019 Vluxe. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ////////////////////////////////////////////////////////////////////////////////////////////////// import XCTest @testable import Starscream class FuzzingTests: XCTestCase { var websocket: WebSocket! var server: MockServer! var uuid = "" override func setUp() { super.setUp() let s = MockServer() let _ = s.start(address: "", port: 0) server = s let transport = MockTransport(server: s) uuid = transport.uuid let url = URL(string: "http://vluxe.io/ws")! //domain doesn't matter with the mock transport let request = URLRequest(url: url) websocket = WebSocket(request: request, engine: WSEngine(transport: transport)) } override func tearDown() { super.tearDown() } func runWebsocket(timeout: TimeInterval = 10, serverAction: @escaping ((ServerEvent) -> Bool)) { let e = expectation(description: "Websocket event timeout") server.onEvent = { event in let done = serverAction(event) if done { e.fulfill() } } websocket.onEvent = { event in switch event { case .text(let string): self.websocket.write(string: string) case .binary(let data): self.websocket.write(data: data) case .ping(_): break case .pong(_): break case .connected(_): break case .disconnected(let reason, let code): print("reason: \(reason) code: \(code)") case .error(_): break case .viabilityChanged(_): break case .reconnectSuggested(_): break case .cancelled: break case .peerClosed: break } } websocket.connect() waitForExpectations(timeout: timeout) { error in if let error = error { XCTFail("waitForExpectationsWithTimeout errored: \(error)") } } } func sendMessage(string: String, isBinary: Bool) { let payload = string.data(using: .utf8)! let code: FrameOpCode = isBinary ? .binaryFrame : .textFrame runWebsocket { event in switch event { case .connected(let conn, _): conn.write(data: payload, opcode: code) case .text(let conn, let text): if text == string && !isBinary { conn.write(data: Data(), opcode: .connectionClose) return true //success! } else { XCTFail("text does not match: source: [\(string)] response: [\(text)]") } case .binary(let conn, let data): if payload.count == data.count && isBinary { conn.write(data: Data(), opcode: .connectionClose) return true //success! } else { XCTFail("binary does not match: source: [\(payload.count)] response: [\(data.count)]") } case .disconnected(_, _, _): return false default: XCTFail("recieved unexpected server event: \(event)") } return false } } //These are the Autobahn test cases as unit tests /// MARK : - Framing cases // case 1.1.1 func testCase1() { sendMessage(string: "", isBinary: false) } // case 1.1.2 func testCase2() { sendMessage(string: String(repeating: "*", count: 125), isBinary: false) } // case 1.1.3 func testCase3() { sendMessage(string: String(repeating: "*", count: 126), isBinary: false) } // case 1.1.4 func testCase4() { sendMessage(string: String(repeating: "*", count: 127), isBinary: false) } // case 1.1.5 func testCase5() { sendMessage(string: String(repeating: "*", count: 128), isBinary: false) } // case 1.1.6 func testCase6() { sendMessage(string: String(repeating: "*", count: 65535), isBinary: false) } // case 1.1.7, 1.1.8 func testCase7() { sendMessage(string: String(repeating: "*", count: 65536), isBinary: false) } // case 1.2.1 func testCase9() { sendMessage(string: "", isBinary: true) } // case 1.2.2 func testCase10() { sendMessage(string: String(repeating: "*", count: 125), isBinary: true) } // case 1.2.3 func testCase11() { sendMessage(string: String(repeating: "*", count: 126), isBinary: true) } // case 1.2.4 func testCase12() { sendMessage(string: String(repeating: "*", count: 127), isBinary: true) } // case 1.2.5 func testCase13() { sendMessage(string: String(repeating: "*", count: 128), isBinary: true) } // case 1.2.6 func testCase14() { sendMessage(string: String(repeating: "*", count: 65535), isBinary: true) } // case 1.2.7, 1.2.8 func testCase15() { sendMessage(string: String(repeating: "*", count: 65536), isBinary: true) } //TODO: the rest of them. } ================================================ FILE: Tests/Info.plist ================================================ CFBundleDevelopmentRegion en CFBundleExecutable $(EXECUTABLE_NAME) CFBundleIdentifier $(PRODUCT_BUNDLE_IDENTIFIER) CFBundleInfoDictionaryVersion 6.0 CFBundleName $(PRODUCT_NAME) CFBundlePackageType BNDL CFBundleShortVersionString 1.0 CFBundleSignature ???? CFBundleVersion 1 ================================================ FILE: Tests/MockServer.swift ================================================ ////////////////////////////////////////////////////////////////////////////////////////////////// // // MockServer.swift // Starscream // // Created by Dalton Cherry on 1/29/19. // Copyright © 2019 Vluxe. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ////////////////////////////////////////////////////////////////////////////////////////////////// import Foundation @testable import Starscream public class MockConnection: Connection, HTTPServerDelegate, FramerEventClient, FrameCollectorDelegate { let transport: MockTransport private let httpHandler = FoundationHTTPServerHandler() private let framer = WSFramer(isServer: true) private let frameHandler = FrameCollector() private var didUpgrade = false public var onEvent: ((ConnectionEvent) -> Void)? fileprivate weak var delegate: ConnectionDelegate? init(transport: MockTransport) { self.transport = transport httpHandler.register(delegate: self) framer.register(delegate: self) frameHandler.delegate = self } func add(data: Data) { if !didUpgrade { httpHandler.parse(data: data) } else { framer.add(data: data) } } public func write(data: Data, opcode: FrameOpCode) { let wsData = framer.createWriteFrame(opcode: opcode, payload: data, isCompressed: false) transport.received(data: wsData) } /// MARK: - HTTPServerDelegate public func didReceive(event: HTTPEvent) { switch event { case .success(let headers): didUpgrade = true //TODO: add headers and key check? let response = httpHandler.createResponse(headers: [:]) transport.received(data: response) delegate?.didReceive(event: .connected(self, headers)) onEvent?(.connected(headers)) case .failure(let error): onEvent?(.error(error)) } } /// MARK: - FrameCollectorDelegate public func frameProcessed(event: FrameEvent) { switch event { case .frame(let frame): frameHandler.add(frame: frame) case .error(let error): onEvent?(.error(error)) } } public func didForm(event: FrameCollector.Event) { switch event { case .text(let string): delegate?.didReceive(event: .text(self, string)) onEvent?(.text(string)) case .binary(let data): delegate?.didReceive(event: .binary(self, data)) onEvent?(.binary(data)) case .pong(let data): delegate?.didReceive(event: .pong(self, data)) onEvent?(.pong(data)) case .ping(let data): delegate?.didReceive(event: .ping(self, data)) onEvent?(.ping(data)) case .closed(let reason, let code): delegate?.didReceive(event: .disconnected(self, reason, code)) onEvent?(.disconnected(reason, code)) case .error(let error): onEvent?(.error(error)) } } public func decompress(data: Data, isFinal: Bool) -> Data? { return nil } } public class MockServer: Server, ConnectionDelegate { fileprivate var connections = [String: MockConnection]() public var onEvent: ((ServerEvent) -> Void)? public func start(address: String, port: UInt16) -> Error? { return nil } public func connect(transport: MockTransport) { let conn = MockConnection(transport: transport) conn.delegate = self connections[transport.uuid] = conn } public func disconnect(uuid: String) { // guard let conn = connections[uuid] else { // return // } //TODO: force disconnect connections.removeValue(forKey: uuid) } public func write(data: Data, uuid: String) { guard let conn = connections[uuid] else { return } conn.add(data: data) } /// MARK: - MockConnectionDelegate public func didReceive(event: ServerEvent) { onEvent?(event) } } ================================================ FILE: Tests/MockTransport.swift ================================================ ////////////////////////////////////////////////////////////////////////////////////////////////// // // MockTransport.swift // Starscream // // Created by Dalton Cherry on 1/29/19. // Copyright © 2019 Vluxe. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ////////////////////////////////////////////////////////////////////////////////////////////////// import Foundation @testable import Starscream public class MockTransport: Transport { public var usingTLS: Bool { return false } private weak var delegate: TransportEventClient? private let id: String weak var server: MockServer? var uuid: String { return id } public init(server: MockServer) { self.server = server self.id = UUID().uuidString } public func register(delegate: TransportEventClient) { self.delegate = delegate } public func connect(url: URL, timeout: Double, certificatePinning: CertificatePinning?) { server?.connect(transport: self) delegate?.connectionChanged(state: .connected) } public func disconnect() { server?.disconnect(uuid: uuid) } public func write(data: Data, completion: @escaping ((Error?) -> ())) { server?.write(data: data, uuid: uuid) } public func received(data: Data) { delegate?.connectionChanged(state: .receive(data)) } public func getSecurityData() -> (SecTrust?, String?) { return (nil, nil) } } public class MockSecurity: CertificatePinning, HeaderValidator { public func evaluateTrust(trust: SecTrust, domain: String?, completion: ((PinningState) -> ())) { completion(.success) } public func validate(headers: [String: String], key: String) -> Error? { return nil } } ================================================ FILE: Tests/StarscreamTests/StarscreamTests.swift ================================================ ////////////////////////////////////////////////////////////////////////////////////////////////// // // StarscreamTests.swift // StarscreamTests // // Created by Austin Cherry on 9/25/14. // Copyright © 2014 Vluxe. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ////////////////////////////////////////////////////////////////////////////////////////////////// import XCTest class StarscreamTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measure() { // Put the code you want to measure the time of here. } } } ================================================ FILE: examples/AutobahnTest/.gitignore ================================================ # CocoaPods # # We recommend against adding the Pods directory to your .gitignore. However # you should judge for yourself, the pros and cons are mentioned at: # http://guides.cocoapods.org/using/using-cocoapods.html#should-i-ignore-the-pods-directory-in-source-control? # # Pods/ # Xcode .DS_Store build *.pbxuser !default.pbxuser *.mode1v3 !default.mode1v3 *.mode2v3 !default.mode2v3 *.perspectivev3 !default.perspectivev3 xcuserdata profile *.moved-aside DerivedData .idea/ *.hmap *.xccheckout *.xcodeproj/*.xcworkspace ================================================ FILE: examples/AutobahnTest/Autobahn/AppDelegate.swift ================================================ // // AppDelegate.swift // Autobahn // // Created by Dalton Cherry on 7/24/15. // Copyright (c) 2015 vluxe. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } } ================================================ FILE: examples/AutobahnTest/Autobahn/Base.lproj/LaunchScreen.xib ================================================ ================================================ FILE: examples/AutobahnTest/Autobahn/Base.lproj/Main.storyboard ================================================ ================================================ FILE: examples/AutobahnTest/Autobahn/Images.xcassets/AppIcon.appiconset/Contents.json ================================================ { "images" : [ { "idiom" : "iphone", "size" : "20x20", "scale" : "2x" }, { "idiom" : "iphone", "size" : "20x20", "scale" : "3x" }, { "idiom" : "iphone", "size" : "29x29", "scale" : "2x" }, { "idiom" : "iphone", "size" : "29x29", "scale" : "3x" }, { "idiom" : "iphone", "size" : "40x40", "scale" : "2x" }, { "idiom" : "iphone", "size" : "40x40", "scale" : "3x" }, { "idiom" : "iphone", "size" : "60x60", "scale" : "2x" }, { "idiom" : "iphone", "size" : "60x60", "scale" : "3x" }, { "idiom" : "ipad", "size" : "20x20", "scale" : "1x" }, { "idiom" : "ipad", "size" : "20x20", "scale" : "2x" }, { "idiom" : "ipad", "size" : "29x29", "scale" : "1x" }, { "idiom" : "ipad", "size" : "29x29", "scale" : "2x" }, { "idiom" : "ipad", "size" : "40x40", "scale" : "1x" }, { "idiom" : "ipad", "size" : "40x40", "scale" : "2x" }, { "idiom" : "ipad", "size" : "76x76", "scale" : "1x" }, { "idiom" : "ipad", "size" : "76x76", "scale" : "2x" }, { "idiom" : "ipad", "size" : "83.5x83.5", "scale" : "2x" }, { "idiom" : "ios-marketing", "size" : "1024x1024", "scale" : "1x" } ], "info" : { "version" : 1, "author" : "xcode" } } ================================================ FILE: examples/AutobahnTest/Autobahn/Info.plist ================================================ CFBundleDevelopmentRegion en CFBundleExecutable $(EXECUTABLE_NAME) CFBundleIdentifier $(PRODUCT_BUNDLE_IDENTIFIER) CFBundleInfoDictionaryVersion 6.0 CFBundleName $(PRODUCT_NAME) CFBundlePackageType APPL CFBundleShortVersionString 1.0 CFBundleSignature ???? CFBundleVersion 1 LSRequiresIPhoneOS UILaunchStoryboardName LaunchScreen UIMainStoryboardFile Main UIRequiredDeviceCapabilities armv7 UISupportedInterfaceOrientations UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight UISupportedInterfaceOrientations~ipad UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight ================================================ FILE: examples/AutobahnTest/Autobahn/ViewController.swift ================================================ // // ViewController.swift // Autobahn // // Created by Dalton Cherry on 7/24/15. // Copyright (c) 2015 vluxe. All rights reserved. // import UIKit import Starscream class ViewController: UIViewController { let host = "localhost:9001" var socketArray = [WebSocket]() var caseCount = 300 //starting cases override func viewDidLoad() { super.viewDidLoad() getCaseCount() //getTestInfo(1) //runTest(304) } func removeSocket(_ s: WebSocket?) { guard let s = s else {return} socketArray = socketArray.filter{$0 !== s} } func getCaseCount() { let req = URLRequest(url: URL(string: "ws://\(host)/getCaseCount")!) let s = WebSocket(request: req) socketArray.append(s) s.onEvent = { [weak self] event in switch event { case .text(let string): if let c = Int(string) { print("number of cases is: \(c)") self?.caseCount = c } case .disconnected(_, _): self?.runTest(1) self?.removeSocket(s) default: break } } s.connect() } func getTestInfo(_ caseNum: Int) { let s = createSocket("getCaseInfo",caseNum) socketArray.append(s) // s.onText = { (text: String) in // let data = text.dataUsingEncoding(NSUTF8StringEncoding) // do { // let resp: AnyObject? = try NSJSONSerialization.JSONObjectWithData(data!, // options: NSJSONReadingOptions()) // if let dict = resp as? Dictionary { // let num = dict["id"] // let summary = dict["description"] // if let n = num, let sum = summary { // print("running case:\(caseNum) id:\(n) summary: \(sum)") // } // } // } catch { // print("error parsing the json") // } // } var once = false s.onEvent = { [weak self] event in switch event { case .disconnected(_, _), .error(_): if !once { once = true self?.runTest(caseNum) } self?.removeSocket(s) default: break } } s.connect() } func runTest(_ caseNum: Int) { let s = createSocket("runCase",caseNum) self.socketArray.append(s) var once = false s.onEvent = { [weak self, weak s] event in switch event { case .disconnected(_, _), .error(_): if !once { once = true print("case:\(caseNum) finished") //self?.verifyTest(caseNum) //disabled since it slows down the tests let nextCase = caseNum+1 if nextCase <= (self?.caseCount)! { self?.runTest(nextCase) //self?.getTestInfo(nextCase) //disabled since it slows down the tests } else { self?.finishReports() } self?.removeSocket(s) } self?.removeSocket(s) case .text(let string): s?.write(string: string) case .binary(let data): s?.write(data: data) // case .error(let error): // print("got an error: \(error)") default: break } } s.connect() } // func verifyTest(_ caseNum: Int) { // let s = createSocket("getCaseStatus",caseNum) // self.socketArray.append(s) // s.onText = { (text: String) in // let data = text.data(using: String.Encoding.utf8) // do { // let resp: Any? = try JSONSerialization.jsonObject(with: data!, // options: JSONSerialization.ReadingOptions()) // if let dict = resp as? Dictionary { // if let status = dict["behavior"] { // if status == "OK" { // print("SUCCESS: \(caseNum)") // return // } // } // print("FAILURE: \(caseNum)") // } // } catch { // print("error parsing the json") // } // } // var once = false // s.onDisconnect = { [weak self, weak s] (error: Error?) in // if !once { // once = true // let nextCase = caseNum+1 // print("next test is: \(nextCase)") // if nextCase <= (self?.caseCount)! { // self?.getTestInfo(nextCase) // } else { // self?.finishReports() // } // } // self?.removeSocket(s) // } // s.connect() // } func finishReports() { let s = createSocket("updateReports",0) self.socketArray.append(s) s.onEvent = { [weak self, weak s] event in switch event { case .disconnected(_, _): print("finished all the tests!") self?.removeSocket(s) default: break } } s.connect() } func createSocket(_ cmd: String, _ caseNum: Int) -> WebSocket { let req = URLRequest(url: URL(string: "ws://\(host)\(buildPath(cmd,caseNum))")!) //return WebSocket(request: req, compressionHandler: WSCompression()) return WebSocket(request: req) } func buildPath(_ cmd: String, _ caseNum: Int) -> String { return "/\(cmd)?case=\(caseNum)&agent=Starscream" } } ================================================ FILE: examples/SimpleTest/.gitignore ================================================ # CocoaPods # # We recommend against adding the Pods directory to your .gitignore. However # you should judge for yourself, the pros and cons are mentioned at: # http://guides.cocoapods.org/using/using-cocoapods.html#should-i-ignore-the-pods-directory-in-source-control? # # Pods/ # Xcode .DS_Store build *.pbxuser !default.pbxuser *.mode1v3 !default.mode1v3 *.mode2v3 !default.mode2v3 *.perspectivev3 !default.perspectivev3 xcuserdata profile *.moved-aside DerivedData .idea/ *.hmap *.xccheckout *.xcodeproj/*.xcworkspace ================================================ FILE: examples/SimpleTest/README.md ================================================ # Simple Test This is a very simple example on how to use Starscream. # Usage First make sure you have the gem dependencies of websocket server. ``` gem install em-websocket gem install faker ``` Next simply run: ``` ruby ws-server.rb ``` After that, start and run the xCode project. Echo to your heart's desire. ================================================ FILE: examples/SimpleTest/SimpleTest/AppDelegate.swift ================================================ ////////////////////////////////////////////////////////////////////////////////////////////////// // // AppDelegate.swift // SimpleTest // // Created by Dalton Cherry on 8/12/14. // Copyright © 2014 Vluxe. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ////////////////////////////////////////////////////////////////////////////////////////////////// import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } } ================================================ FILE: examples/SimpleTest/SimpleTest/Base.lproj/Main.storyboard ================================================ ================================================ FILE: examples/SimpleTest/SimpleTest/Images.xcassets/AppIcon.appiconset/Contents.json ================================================ { "images" : [ { "idiom" : "iphone", "size" : "29x29", "scale" : "2x" }, { "idiom" : "iphone", "size" : "40x40", "scale" : "2x" }, { "idiom" : "iphone", "size" : "60x60", "scale" : "2x" }, { "idiom" : "iphone", "size" : "60x60", "scale" : "3x" }, { "idiom" : "ipad", "size" : "29x29", "scale" : "1x" }, { "idiom" : "ipad", "size" : "29x29", "scale" : "2x" }, { "idiom" : "ipad", "size" : "40x40", "scale" : "1x" }, { "idiom" : "ipad", "size" : "40x40", "scale" : "2x" }, { "idiom" : "ipad", "size" : "76x76", "scale" : "1x" }, { "idiom" : "ipad", "size" : "76x76", "scale" : "2x" } ], "info" : { "version" : 1, "author" : "xcode" } } ================================================ FILE: examples/SimpleTest/SimpleTest/Images.xcassets/LaunchImage.launchimage/Contents.json ================================================ { "images" : [ { "orientation" : "portrait", "idiom" : "iphone", "extent" : "full-screen", "minimum-system-version" : "7.0", "scale" : "2x" }, { "orientation" : "portrait", "idiom" : "iphone", "subtype" : "retina4", "extent" : "full-screen", "minimum-system-version" : "7.0", "scale" : "2x" }, { "orientation" : "portrait", "idiom" : "ipad", "extent" : "full-screen", "minimum-system-version" : "7.0", "scale" : "1x" }, { "orientation" : "landscape", "idiom" : "ipad", "extent" : "full-screen", "minimum-system-version" : "7.0", "scale" : "1x" }, { "orientation" : "portrait", "idiom" : "ipad", "extent" : "full-screen", "minimum-system-version" : "7.0", "scale" : "2x" }, { "orientation" : "landscape", "idiom" : "ipad", "extent" : "full-screen", "minimum-system-version" : "7.0", "scale" : "2x" } ], "info" : { "version" : 1, "author" : "xcode" } } ================================================ FILE: examples/SimpleTest/SimpleTest/Info.plist ================================================ CFBundleDevelopmentRegion en CFBundleExecutable $(EXECUTABLE_NAME) CFBundleIdentifier $(PRODUCT_BUNDLE_IDENTIFIER) CFBundleInfoDictionaryVersion 6.0 CFBundleName $(PRODUCT_NAME) CFBundlePackageType APPL CFBundleShortVersionString 1.0 CFBundleSignature ???? CFBundleVersion 1 LSRequiresIPhoneOS NSAppTransportSecurity NSAllowsArbitraryLoads UIMainStoryboardFile Main UIRequiredDeviceCapabilities armv7 UISupportedInterfaceOrientations UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight UISupportedInterfaceOrientations~ipad UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight ================================================ FILE: examples/SimpleTest/SimpleTest/ViewController.swift ================================================ ////////////////////////////////////////////////////////////////////////////////////////////////// // // ViewController.swift // SimpleTest // // Created by Dalton Cherry on 8/12/14. // Copyright © 2014 Vluxe. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ////////////////////////////////////////////////////////////////////////////////////////////////// import UIKit import Starscream class ViewController: UIViewController, WebSocketDelegate { var socket: WebSocket! var isConnected = false let server = WebSocketServer() override func viewDidLoad() { super.viewDidLoad() //https://echo.websocket.org var request = URLRequest(url: URL(string: "http://localhost:8080")!) //https://localhost:8080 request.timeoutInterval = 5 socket = WebSocket(request: request) socket.delegate = self socket.connect() } // MARK: - WebSocketDelegate func didReceive(event: Starscream.WebSocketEvent, client: Starscream.WebSocketClient) { switch event { case .connected(let headers): isConnected = true print("websocket is connected: \(headers)") case .disconnected(let reason, let code): isConnected = false print("websocket is disconnected: \(reason) with code: \(code)") case .text(let string): print("Received text: \(string)") case .binary(let data): print("Received data: \(data.count)") case .ping(_): break case .pong(_): break case .viabilityChanged(_): break case .reconnectSuggested(_): break case .cancelled: isConnected = false case .error(let error): isConnected = false handleError(error) case .peerClosed: break } } func handleError(_ error: Error?) { if let e = error as? WSError { print("websocket encountered an error: \(e.message)") } else if let e = error { print("websocket encountered an error: \(e.localizedDescription)") } else { print("websocket encountered an error") } } // MARK: Write Text Action @IBAction func writeText(_ sender: UIBarButtonItem) { socket.write(string: "hello there!") } // MARK: Disconnect Action @IBAction func disconnect(_ sender: UIBarButtonItem) { if isConnected { sender.title = "Connect" socket.disconnect() } else { sender.title = "Disconnect" socket.connect() } } } ================================================ FILE: examples/SimpleTest/ws-server.rb ================================================ require 'em-websocket' require 'faker' EM.run { EM::WebSocket.run(:host => "0.0.0.0", :port => 8080) do |ws| ws.onopen { |handshake| puts "WebSocket connection open" puts "origin: #{handshake.origin}" puts "headers: #{handshake.headers}" ws.send "Hello Client, you connected to #{handshake.path}" } ws.onerror do |error| puts "[error] #{error}" end ws.onclose { puts "Connection closed" } ws.onmessage { |msg| puts "message from client: #{msg}" ws.send +Faker::Hacker.say_something_smart } end } ================================================ FILE: examples/WebSocketsOrgEcho/Podfile ================================================ # Uncomment the next line to define a global platform for your project # platform :ios, '9.0' target 'WebSocketsOrgEcho' do # Comment the next line if you're not using Swift and don't want to use dynamic frameworks use_frameworks! # Pods for WebSocketsOrgEcho pod 'Starscream', :path => '../../' end ================================================ FILE: examples/WebSocketsOrgEcho/WebSocketsOrgEcho/AppDelegate.swift ================================================ // // AppDelegate.swift // WebSocketsOrgEcho // // Created by Kristaps Grinbergs on 08/10/2018. // Copyright © 2018 Starscream. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { return true } } ================================================ FILE: examples/WebSocketsOrgEcho/WebSocketsOrgEcho/Assets.xcassets/AppIcon.appiconset/Contents.json ================================================ { "images" : [ { "idiom" : "iphone", "size" : "20x20", "scale" : "2x" }, { "idiom" : "iphone", "size" : "20x20", "scale" : "3x" }, { "idiom" : "iphone", "size" : "29x29", "scale" : "2x" }, { "idiom" : "iphone", "size" : "29x29", "scale" : "3x" }, { "idiom" : "iphone", "size" : "40x40", "scale" : "2x" }, { "idiom" : "iphone", "size" : "40x40", "scale" : "3x" }, { "idiom" : "iphone", "size" : "60x60", "scale" : "2x" }, { "idiom" : "iphone", "size" : "60x60", "scale" : "3x" }, { "idiom" : "ipad", "size" : "20x20", "scale" : "1x" }, { "idiom" : "ipad", "size" : "20x20", "scale" : "2x" }, { "idiom" : "ipad", "size" : "29x29", "scale" : "1x" }, { "idiom" : "ipad", "size" : "29x29", "scale" : "2x" }, { "idiom" : "ipad", "size" : "40x40", "scale" : "1x" }, { "idiom" : "ipad", "size" : "40x40", "scale" : "2x" }, { "idiom" : "ipad", "size" : "76x76", "scale" : "1x" }, { "idiom" : "ipad", "size" : "76x76", "scale" : "2x" }, { "idiom" : "ipad", "size" : "83.5x83.5", "scale" : "2x" }, { "idiom" : "ios-marketing", "size" : "1024x1024", "scale" : "1x" } ], "info" : { "version" : 1, "author" : "xcode" } } ================================================ FILE: examples/WebSocketsOrgEcho/WebSocketsOrgEcho/Assets.xcassets/Contents.json ================================================ { "info" : { "version" : 1, "author" : "xcode" } } ================================================ FILE: examples/WebSocketsOrgEcho/WebSocketsOrgEcho/Base.lproj/LaunchScreen.storyboard ================================================ ================================================ FILE: examples/WebSocketsOrgEcho/WebSocketsOrgEcho/Base.lproj/Main.storyboard ================================================ ================================================ FILE: examples/WebSocketsOrgEcho/WebSocketsOrgEcho/Info.plist ================================================ CFBundleDevelopmentRegion $(DEVELOPMENT_LANGUAGE) CFBundleExecutable $(EXECUTABLE_NAME) CFBundleIdentifier $(PRODUCT_BUNDLE_IDENTIFIER) CFBundleInfoDictionaryVersion 6.0 CFBundleName $(PRODUCT_NAME) CFBundlePackageType APPL CFBundleShortVersionString 1.0 CFBundleVersion 1 LSRequiresIPhoneOS UILaunchStoryboardName LaunchScreen UIMainStoryboardFile Main UIRequiredDeviceCapabilities armv7 UISupportedInterfaceOrientations UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight UISupportedInterfaceOrientations~ipad UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight ================================================ FILE: examples/WebSocketsOrgEcho/WebSocketsOrgEcho/URL+Extensions.swift ================================================ // // URL+Extensions.swift // Example // // Created by Kristaps Grinbergs on 08/10/2018. // Copyright © 2018 Kristaps Grinbergs. All rights reserved. // import Foundation extension URL { init(staticString string: StaticString) { guard let url = URL(string: "\(string)") else { preconditionFailure("Invalid static URL string: \(string)") } self = url } } ================================================ FILE: examples/WebSocketsOrgEcho/WebSocketsOrgEcho/ViewController.swift ================================================ // // ViewController.swift // WebSocketsOrgEcho // // Created by Kristaps Grinbergs on 08/10/2018. // Copyright © 2018 Starscream. All rights reserved. // import UIKit import Starscream class ViewController: UIViewController, WebSocketDelegate { var socket: WebSocket = WebSocket(url: URL(staticString: "wss://echo.websocket.org")) func websocketDidConnect(socket: WebSocketClient) { print("websocketDidConnect") } func websocketDidDisconnect(socket: WebSocketClient, error: Error?) { print("websocketDidDisconnect", error ?? "") } func websocketDidReceiveMessage(socket: WebSocketClient, text: String) { print("websocketDidReceiveMessage", text) } func websocketDidReceiveData(socket: WebSocketClient, data: Data) { print("websocketDidReceiveData", data) } override func viewDidLoad() { super.viewDidLoad() socket.delegate = self } @IBAction func connect(_ sender: Any) { socket.connect() } } ================================================ FILE: examples/WebSocketsOrgEcho/WebSocketsOrgEcho.xcworkspace/contents.xcworkspacedata ================================================ ================================================ FILE: examples/WebSocketsOrgEcho/WebSocketsOrgEcho.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist ================================================ IDEDidComputeMac32BitWarning ================================================ FILE: fastlane/Fastfile ================================================ default_platform(:ios) update_fastlane desc "Run tests" lane :test do run_tests( devices: ["iPhone 14 Pro", "iPad Pro (11-inch) (4th generation)"], ) end platform :ios do desc "Deploy new version" lane :release do version = version_bump_podspec(path: "Starscream.podspec", version_number: ENV["TAG"]) changelog = changelog_from_git_commits(merge_commit_filtering: "exclude_merges") github_release = set_github_release( repository_name: "daltoniam/starscream", api_token: ENV["GITHUB_TOKEN"], name: version, tag_name: version, description: changelog, commitish: "master" ) pod_push(allow_warnings: false, verbose: true) end end ================================================ FILE: fastlane/README.md ================================================ fastlane documentation ---- # Installation Make sure you have the latest version of the Xcode command line tools installed: ```sh xcode-select --install ``` For _fastlane_ installation instructions, see [Installing _fastlane_](https://docs.fastlane.tools/#installing-fastlane) # Available Actions ### test ```sh [bundle exec] fastlane test ``` Run tests ---- ## iOS ### ios release ```sh [bundle exec] fastlane ios release ``` Deploy new version ---- This README.md is auto-generated and will be re-generated every time [_fastlane_](https://fastlane.tools) is run. More information about _fastlane_ can be found on [fastlane.tools](https://fastlane.tools). The documentation of _fastlane_ can be found on [docs.fastlane.tools](https://docs.fastlane.tools).