Compare commits

..

480 Commits

Author SHA1 Message Date
Austin Cherry c6bfd1af48 chore: update release tooling 2024-03-07 12:57:12 -06:00
Austin Cherry 82d8a0119e fix: update build setting to recommended 2024-03-07 12:10:16 -06:00
Dylan 11c401f408 fix: crash as NWEndpoint requires a min target of 12.0 (#998) 2024-03-07 12:05:33 -06:00
Jonathan Ellis b32c9ab481 Add privacy manifest (#1008) 2024-03-07 12:03:19 -06:00
Rüdiger Busche b12442f29c chore: Update install instructions (#984)
Remove Accio instructions, since the project is deprecated. Remove Rouge instructions,
since the repo was not updated since 2014. Move SwiftPM instructions up, since it should be the
default for new projects.
2024-02-20 12:47:38 -06:00
dependabot[bot] d3a0b10732 Bump activesupport from 7.0.7 to 7.0.7.2 (#976)
Bumps [activesupport](https://github.com/rails/rails) from 7.0.7 to 7.0.7.2.
- [Release notes](https://github.com/rails/rails/releases)
- [Changelog](https://github.com/rails/rails/blob/v7.0.7.2/activesupport/CHANGELOG.md)
- [Commits](https://github.com/rails/rails/compare/v7.0.7...v7.0.7.2)

---
updated-dependencies:
- dependency-name: activesupport
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-08-29 12:08:38 -05:00
Austin Cherry 7723d1ec4f Update README.md 2023-08-22 16:32:08 -05:00
Austin Cherry ac6c0fc9da fix: update README 2023-08-19 16:19:25 -05:00
Mikhail Akopov ca9b1225b7 Update SwiftPM section in Readme (#824) 2023-08-19 16:12:23 -05:00
yohei yoshimuta 86998dd144 Fix connection race when using WSEngine (#930) 2023-08-19 16:11:05 -05:00
Zac West d67812c561 Fix compression when headers don't include window bits (#937) 2023-08-19 16:09:52 -05:00
paul-verkada d2a9549ea4 Fix a leak with the TCPTransport (#923)
Co-authored-by: Andreas Binnewies <andreas.binnewies@verkada.com>
2023-08-19 16:09:19 -05:00
Austin Cherry 7b1e5bb60d fix: update secret 2023-08-19 15:30:29 -05:00
Austin Cherry 4c7b8817a1 fix: release workflow 2023-08-19 15:24:17 -05:00
Austin Cherry f8ac424b8e chore: update bundler 2023-08-19 13:16:38 -05:00
Austin Cherry dcfffe1114 chore: change ruby version 2023-08-19 13:13:57 -05:00
Austin Cherry 76fa39ec30 chore: add ruby version 2023-08-19 13:09:12 -05:00
Austin Cherry ea9a6ff27e feat: cleanup, update for latest xcode/swift, add release workflow 2023-08-19 13:03:25 -05:00
Muhammad Adil 66a441a917 rfc6455 link fixed (#952) 2023-08-16 17:29:37 -05:00
Mustapha Qadri 04acf17f4c Added support for connection error (#912) 2023-08-16 17:25:49 -05:00
dependabot[bot] 826008daab Bump cocoapods-downloader from 1.3.0 to 1.6.3 (#948)
Bumps [cocoapods-downloader](https://github.com/CocoaPods/cocoapods-downloader) from 1.3.0 to 1.6.3.
- [Release notes](https://github.com/CocoaPods/cocoapods-downloader/releases)
- [Changelog](https://github.com/CocoaPods/cocoapods-downloader/blob/master/CHANGELOG.md)
- [Commits](https://github.com/CocoaPods/cocoapods-downloader/compare/1.3.0...1.6.3)

---
updated-dependencies:
- dependency-name: cocoapods-downloader
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-08-16 17:24:08 -05:00
newloran2 cdb61a3624 Fix for start websocket with cookies in initial request (#942) 2023-08-16 17:22:28 -05:00
Jenea Vranceanu f900d67759 fix: added peerClosed case for WebSocketEvent enum (#946) 2023-08-16 17:21:37 -05:00
Hugin cb131f8ea3 Update README.md (#950)
Modify the version reference to prevent user copy errors
2023-08-16 17:20:26 -05:00
dependabot[bot] 3c5a484049 Bump tzinfo from 1.2.6 to 1.2.10 (#955)
Bumps [tzinfo](https://github.com/tzinfo/tzinfo) from 1.2.6 to 1.2.10.
- [Release notes](https://github.com/tzinfo/tzinfo/releases)
- [Changelog](https://github.com/tzinfo/tzinfo/blob/master/CHANGES.md)
- [Commits](https://github.com/tzinfo/tzinfo/compare/v1.2.6...v1.2.10)

---
updated-dependencies:
- dependency-name: tzinfo
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-08-16 17:19:45 -05:00
dependabot[bot] 5ab0d5a541 Bump addressable from 2.7.0 to 2.8.1 (#963)
Bumps [addressable](https://github.com/sporkmonger/addressable) from 2.7.0 to 2.8.1.
- [Release notes](https://github.com/sporkmonger/addressable/releases)
- [Changelog](https://github.com/sporkmonger/addressable/blob/main/CHANGELOG.md)
- [Commits](https://github.com/sporkmonger/addressable/compare/addressable-2.7.0...addressable-2.8.1)

---
updated-dependencies:
- dependency-name: addressable
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-08-16 17:19:37 -05:00
Ste Prescott 060600f343 Conditionally include 'swift-nio-zlib-support' dependency to avoid warning on macOS (#964)
Co-authored-by: Mykola Varahash <varagash.kolya@gmail.com>
2023-08-16 17:19:18 -05:00
NachoSoto f354881550 Added support for xrOS (#973) 2023-08-16 17:18:19 -05:00
Kristaps Grinbergs c68359159d Merge pull request #894 from Emadgnia/Remove-warnings-on-Xcode-12.5 2021-09-30 22:28:57 +03:00
Emad Ghorbaninia 2c476c7582 Replace all the class with AnyObject due to the deprication. 2021-06-08 10:52:05 +02:00
Dalton 6f18c4938a Merge pull request #812 from JonathanDowning/feature/WebSocketDelegate-change
Allow WebSocketDelegate 'didReceive' method's 'client' parameter to work with `WebSocketClient` mock objects
2021-05-31 14:58:13 -05:00
Dalton 1435d726ae Merge pull request #823 from mininny/feature/mininny/fix-control-frame
Add .pong to be counted as control frame.
2021-05-31 14:01:55 -05:00
Dalton 95eab636fb Merge pull request #845 from XueshiQiao/master
Remove three unused properties
2021-05-31 13:58:22 -05:00
Dalton f567b33704 Merge pull request #839 from moogle19/fix_native_engine_loop
Fix native engine loop
2021-05-31 13:56:22 -05:00
Dalton 62626d875a Merge pull request #863 from hishnash/addHeadersToError
Add Headers to `notAnUpgrade` error.
2021-05-31 13:53:10 -05:00
Dalton 7e7d8a42ef Merge pull request #830 from mininny/feature/mininny/add-templates
Add Issue templates and PR templates.
2021-05-31 13:50:42 -05:00
Eric Rowe a0ba26b7de Explicitly set domain to the passed value (#890) 2021-05-28 20:08:53 -05:00
Jonas Schmid b7f15e63c3 Fixed documentation on compression (#883) 2021-05-28 20:08:37 -05:00
Matthaus Woolard cebca639ee Add Headers to notAnUpgrade error. 2021-01-26 09:24:30 +13:00
Joey e73800e668 Remove three unused properties 2020-10-21 17:40:28 +08:00
Minhyuk Kim 4ae4531e7a Add Issue templates and PR templates. 2020-09-12 22:25:43 +09:00
Minhyuk Kim a55720bd9a Add .pong to be counted as control frame. 2020-08-22 23:43:24 +09:00
Jonathan Downing e95db8ff29 Tweak WebSocketDelegate method signature 2020-08-07 12:57:25 -07:00
moogle 9447264238 Merge branch 'master' of https://github.com/daltoniam/Starscream into fix_native_engine_loop 2020-08-03 15:32:49 +02:00
daltoniam df8d82047f 4.0.4 release 2020-08-01 15:04:10 -05:00
Dalton 85c8412646 Merge pull request #807 from varahash/conditional-zlib-dependency
Conditionally include 'swift-nio-zlib-support' dependency to avoid warning on macOS
2020-07-18 19:48:29 -05:00
Dalton 4820831260 Merge pull request #799 from amayers/xcode12
Fix compile error on Xcode 12
2020-07-18 19:47:50 -05:00
Dalton 024a27711e Merge pull request #808 from dvshelley/deployTarget9
move deployment target to iOS 9 to fix compile for archive with Xcode 12
2020-07-18 19:47:10 -05:00
Daniel Shelley 5987db1605 move deployment target to iOS 9 to fix compile for archive with Xcode 12 2020-07-16 16:50:35 -06:00
Mykola Varahash fe5769f2ae Conditionally include 'swift-nio-zlib-support' dependency to avoid warning on macOS 2020-07-13 01:35:26 +03:00
Andrew Mayers 263b9419bb Fix compile error on Xcode 12
Now you can build on both Xcode 11.5 & 12.0 b1.

On 12, the unit tests would fail to compile because it wasn't finding the `Starscream` framework. So I added `Starscream` as a dependency of the test target.

In `FoundationHTTPServerHandler` the `method` is of type `CFString`, while `getVerb` is `NSString`. Looks like Xcode 12 doesn't like equality comparison between those types without a cast as `NSString`.
2020-06-22 17:23:47 -04:00
Dalton 5fbeab4c12 Merge pull request #777 from jaltreuter/crash_after_disconnect
In FoundationTransport deinit, remove self as a delegate to InputStream and OutputStream to prevent EXC_BAD_ACCESS
2020-06-20 19:20:04 -05:00
Dalton 07bccd9c16 Merge pull request #790 from sdidla/fix_readLoop
Improve conditions for calling readLoop() and prevent infinite looping
2020-06-20 19:18:12 -05:00
Dalton 51b6c789bd Merge pull request #788 from SemyonBaryshev/master
Fix error when trying to convert text message partial payload to UTF-8
2020-06-20 19:15:56 -05:00
Dalton 0c7e7abfd7 Merge pull request #764 from ameyjain/fix/data-extension-swift-version-check
Fix the deadlock issue on iOS 11
2020-06-20 19:13:26 -05:00
Dalton d2f22783b6 Merge pull request #768 from michalsrutek/patch-1
Update README.md
2020-06-20 19:12:03 -05:00
Dalton e6236acc00 Merge pull request #797 from amayers/swift52
Switch SPM to use Swift 5.2
2020-06-20 19:11:18 -05:00
Dalton d003b62b54 Merge pull request #766 from urbanairship/fixUnsafeMutablePointerDeprecation
Fix deprecation warning in WSCompression
2020-06-20 19:07:41 -05:00
Andrew Mayers 70d9e6ec5c Switch SPM to use Swift 5.2 2020-06-17 09:52:36 -04:00
Shammi Didla c0e7d40284 improve conditions for calling readLoop() 2020-06-06 15:27:27 +02:00
Semyon Baryshev 06945ada8b Fix error when trying to convert text message partial payload to UTF-8 2020-06-05 18:39:16 +03:00
moogle fedd77ba8e Stop reading when error is encountered 2020-05-14 15:56:57 +02:00
Jamie Altreuter 7e5a96341c In FoundationTransport deinit, remove self as a delegate to InputStream and OutputStream to prevent EXC_BAD_ACCESS 2020-05-12 18:14:25 -07:00
Michal Šrůtek ce4fcdc967 Update README.md
Update Autobahn link
2020-04-26 10:00:02 +02:00
Nick Ratelle da1d9c69a7 Fix deprecation warning in WSCompression
Apple recommends using the withUnsafeMutableBytes method on the buffer
to bind an unsafe pointer.
2020-04-21 17:54:17 -04:00
Amey Jain b6630118fe Fix the deadlock issue on iOS 11 2020-04-16 11:47:42 -04:00
daltoniam cfc7b7b8dc version bump 2020-04-08 19:59:30 -05:00
daltoniam 311b6dd9c7 fixes #760 2020-04-08 19:58:07 -05:00
daltoniam 339ca39461 improved native engine and a few bug fixes 2020-04-06 14:29:55 -05:00
Dalton 4e8973e3fc Merge pull request #697 from mikaryyn/feature/v4-refactor
Fix for a buffer overflow when close code has not been received from the socket
2020-04-06 14:16:00 -05:00
daltoniam 990a4c858e enabled native engine. Updated Changelog and README 2020-04-04 14:28:42 -05:00
Dalton 3b4c81547a Merge pull request #755 from dylanmaryk/patch-1
Fix "viabilityChanged" typos
2020-04-04 13:57:40 -05:00
Dalton 9e8fcba42e Merge pull request #749 from YellEngineering/feature/fix-foundation-transport-tls
Enable SSL in FoundationTransport for secure hosts
2020-04-04 13:57:16 -05:00
Dylan Maryk d84552f944 Fix typo 2020-03-27 17:54:35 +01:00
Dylan Maryk c3ac0a9df7 Fix typo 2020-03-27 17:50:56 +01:00
Nick Dowell 97538bc11d Enable SSL in FoundationTransport for secure hosts
This fixes connection to secure hosts such as
wss://echo.websocket.org
2020-03-11 16:03:14 +00:00
Patrick Maltagliati 4e8dca654d Use the host for evaluating trust, not the entire URL (#721)
* Use the host for evaluating trust, not the entire URL

* Get host from URLParts
2020-01-13 14:46:07 -06:00
Kristaps Grinbergs 547cb80ef6 Update Travis CI build (#723)
Update Travis CI build
2020-01-06 11:03:23 +02:00
Kristaps Grinbergs 12946fc610 Update Travis CI build 2020-01-06 10:43:29 +02:00
daltoniam 850f620441 resolved conflicts 2020-01-02 16:38:34 -06:00
daltoniam ced0725e4b update gem file to remove warnings 2020-01-02 16:37:50 -06:00
Dalton 9d1bac8ede Merge pull request #716 from TomasLinhart/macCatalystSupport
Add macCatalyst support
2020-01-02 16:09:54 -06:00
Dalton eb29f2a1f9 Merge pull request #713 from daltoniam/dependabot/bundler/rubyzip-1.3.0
Bump rubyzip from 1.2.2 to 1.3.0
2020-01-02 16:09:00 -06:00
Dalton 9cf7b4dfcb Merge pull request #718 from daltoniam/dependabot/bundler/excon-0.71.0
Bump excon from 0.64.0 to 0.71.0
2020-01-02 16:08:38 -06:00
Dalton 6b2742542c Merge pull request #653 from daltoniam/feature/v4-refactor
v4 Refactor Notice (WIP)
2020-01-02 15:57:37 -06:00
daltoniam e14338dd1d resolved conflicts 2020-01-02 15:47:03 -06:00
daltoniam 0cea1194d2 resolved conflicts 2020-01-02 15:39:22 -06:00
dependabot[bot] a986e38e56 Bump excon from 0.64.0 to 0.71.0
Bumps [excon](https://github.com/excon/excon) from 0.64.0 to 0.71.0.
- [Release notes](https://github.com/excon/excon/releases)
- [Changelog](https://github.com/excon/excon/blob/master/changelog.txt)
- [Commits](https://github.com/excon/excon/compare/v0.64.0...v0.71.0)

Signed-off-by: dependabot[bot] <support@github.com>
2019-12-16 22:06:19 +00:00
Tomas Linhart 692f3cb14a Allow running tests with macCatalyst 2019-11-25 16:53:23 +11:00
Tomas Linhart e8c0e894aa Add macCatalyst support 2019-11-25 16:44:01 +11:00
dependabot[bot] b7e98e147f Bump rubyzip from 1.2.2 to 1.3.0
Bumps [rubyzip](https://github.com/rubyzip/rubyzip) from 1.2.2 to 1.3.0.
- [Release notes](https://github.com/rubyzip/rubyzip/releases)
- [Changelog](https://github.com/rubyzip/rubyzip/blob/master/Changelog.md)
- [Commits](https://github.com/rubyzip/rubyzip/compare/v1.2.2...v1.3.0)

Signed-off-by: dependabot[bot] <support@github.com>
2019-11-14 12:24:24 +00:00
Kristaps Grinbergs e6b65c6d90 Merge pull request #704 from dessmith/bugfix/plist-version-number-correction
Fix version number
2019-10-14 07:36:10 +03:00
Desmond Smith 7ce91f71ca Fix version number
Version number in Info.plist was not incremented in version 3.1.0
2019-10-10 16:06:53 +01:00
daltoniam 83ae006b5c fixed the unit tests 2019-10-01 20:02:10 -05:00
daltoniam 394afb99a9 README update and travis to xcode 11 2019-09-24 20:08:58 -05:00
Mika Ryynänen 281a49edd8 Fix for a buffer overflow when close code has not been received from the socket. 2019-09-24 13:13:36 +03:00
daltoniam 109dd033fc fixed the build 2019-09-22 16:30:55 -05:00
daltoniam 136274da76 WatchOS ifdef checks 2019-08-27 22:21:58 -05:00
daltoniam 6e3b96ace5 CI fixes by readding watchOS support of raw string parsing for HTTP header 2019-08-25 19:22:07 -05:00
daltoniam b8c4183d68 fixed conflicts 2019-08-10 12:36:50 -05:00
daltoniam 839bf25f59 disabled native websocket until offical release 2019-08-10 12:32:21 -05:00
daltoniam c946f5c68b laid the ground work for supporting both the native API and backwards compatibility with old versions 2019-06-15 18:40:22 -05:00
Kristaps Grinbergs a2ed45c0b2 Update gems and allow warnings for now 2019-05-05 17:42:46 +03:00
Kristaps Grinbergs ccb32575e5 Bump Xcode version 2019-05-04 20:10:55 +03:00
Austin Cherry 9164a09cf5 Merge pull request #644 from AccioSupport/master
[README] Document installation via Accio
2019-04-27 18:55:05 -05:00
Austin Cherry b386d1ea5a Cleaned up docs, example project, licensing, etc 2019-04-27 18:42:30 -05:00
Austin Cherry c0d564fcc1 Added Certificate Pinning Support 2019-04-27 16:48:37 -05:00
Kristaps Grinbergs a9625bf474 Merge pull request #650 from pducks32/patch-1
Fix typo in Fastfile
2019-04-25 10:54:12 +03:00
Patrick Metcalfe e68b2f7427 Fix typo in Fastfile 2019-04-24 10:07:29 -07:00
Kristaps Grinbergs 1d81b781e9 Adding support for zlib in linux 2019-04-22 12:42:31 +03:00
daltoniam ebcc04315d added Network framework server 2019-04-05 12:17:26 -05:00
Cihat Gündüz 692d55c76a [README] Document installation via Accio 2019-04-05 17:31:18 +02:00
daltoniam 520e510c2c basic server support for unit tests 2019-04-04 16:20:22 -05:00
daltoniam 4993e492d7 disabled pod lint for now 2019-03-30 22:13:52 -05:00
daltoniam d944b0df20 package manager fix 2019-03-30 22:08:46 -05:00
daltoniam 522b7e74ee updated travis for swift 5 build 2019-03-30 21:41:17 -05:00
daltoniam a664af674e updated travis for swift 5 2019-03-30 21:26:03 -05:00
daltoniam ec0953ee73 tests are building again 2019-03-30 21:20:04 -05:00
Dalton Cherry 21c38d3c1f changed simple test back 2019-03-27 14:26:25 -05:00
Dalton Cherry 1cbfd8126c swift 5 update 2019-03-27 14:19:57 -05:00
Kristaps Grinbergs 9c03ef715d Merge pull request #636 from daltoniam/swift_5
Swift 5 support
2019-03-26 11:11:18 +07:00
Kristaps Grinbergs 7860785cf3 Added version for Swift 4.2 2019-03-26 11:10:59 +07:00
Kristaps Grinbergs b1312f8af1 Fix warnings about project file 2019-03-26 11:04:18 +07:00
Dalton Cherry 0e6bdc81e1 start of security. SSL pinning next 2019-03-22 11:12:49 -05:00
Kristaps Grinbergs 514eb3ddb9 Merge pull request #628 from yamoridon/ws-server-frozen-string
Fix FrozenError in ws-server.rb
2019-03-01 08:33:43 +07:00
Kazuki Ohara 4c48638295 Fix FrozenError in ws-server.rb 2019-03-01 00:28:36 +09:00
Kristaps Grinbergs 429bd1a0b7 Swift 5 support 2019-02-22 16:09:03 +02:00
Kristaps Grinbergs 5ecb5fd499 Merge pull request #618 from c0diq/fix-archs-2
Better way to fix archs
2019-02-11 10:16:25 +02:00
daltoniam 63b76e1fd9 finished up some of the TODOs 2019-02-09 12:04:04 -06:00
daltoniam db7685cf93 off by one 2019-02-09 10:54:36 -06:00
daltoniam 5abcb7f11b updated simple test 2019-02-09 10:50:21 -06:00
Sylvain Rebaud fbd80c2367 Better way to fix archs 2019-02-09 03:10:52 -08:00
Dalton Cherry 75236d6cc7 fixed conflicts 2019-02-08 11:05:54 -06:00
Dalton Cherry 5f467266fc got compression hooked up 2019-02-08 11:04:46 -06:00
daltoniam 12e668f84b foundation HTTP request creation 2019-02-07 18:01:23 -06:00
Kristaps Grinbergs 40cda44e40 Merge pull request #616 from c0diq/fix-archs
Fix Xcode 10.1 valid archs warnings
2019-02-06 17:55:17 +02:00
Sylvain Rebaud 51ee77cf6c Fix Xcode 10.1 valid archs warnings 2019-02-05 21:36:45 -08:00
daltoniam c639b64972 HTTP connetion work 2019-02-05 07:06:29 -06:00
Dalton Cherry 7bb64ba35c writing queue added. Compression stubbed out. Framing refactor is done 2019-02-04 13:54:47 -06:00
Kristaps Grinbergs de293c4b26 Merge pull request #614 from c0diq/fix-code-signing
Fix code signing
2019-02-02 20:19:17 +02:00
Sylvain Rebaud 688bd32df8 Fix Tests 2019-01-25 14:20:41 -08:00
Sylvain Rebaud ee00c1dfdd Fix incorrect code signing
There’s no need to define code signing for frameworks. If hardcoding iOS Developer, this would prevent a framework from getting signed for Enterprise.
2019-01-25 14:20:41 -08:00
Dalton Cherry f8238c495d proper offset 2019-01-25 09:48:32 -06:00
Dalton Cherry 2d059501d1 start and layout of refactored code base 2019-01-24 14:35:14 -06:00
Kristaps Grinbergs 07e09a8ab3 Merge pull request #603 from turingvideo/master
Static queue can cause unexpected timeout when there are multiple ws connections.
2019-01-17 18:32:05 +02:00
Sen Liu d58f0a4436 fix 2018-12-21 10:59:36 -08:00
Sen Liu 36254e8945 fix static queue issues 2018-12-14 16:34:15 -08:00
Kristaps Grinbergs 9b942131d5 Merge pull request #590 from sirlantis/patch-1
Don't add empty Sec-WebSocket-Protocol header
2018-10-29 15:04:45 +02:00
Marcel Jackwerth 108aa5e4c8 Don't add empty Sec-WebSocket-Protocol header
> The request MAY include a header field with the name
> |Sec-WebSocket-Protocol|.  If present, this value indicates one
> or more comma-separated subprotocol the client wishes to speak,
> ordered by preference.
> 
> -- The WebSocket Protocol (https://tools.ietf.org/html/rfc6455)

Passing an empty / neutral array should be the same as passing `nil` here.
The WebSocket API (in Browsers) also seems to treat `null` and `[]` the same.

Preferably the initializer signature should be `protocols: [String] = []`,
but that would make this a breaking change.
2018-10-29 13:13:25 +01:00
Kristaps Grinbergs c72659bd32 Added 3.0.6 to changelog 2018-10-10 15:08:57 +03:00
Kristaps Grinbergs ebdc260ea6 Merge pull request #572 from daltoniam/self_swift_4.2
Using s = self in Swift 4.2 way
2018-10-09 11:42:07 +03:00
Kristaps Grinbergs 361a905d30 Using s = self in Swift 4.2 way 2018-10-08 20:19:36 +03:00
Kristaps Grinbergs 0f18ae5959 Merge pull request #570 from vonox7/patch-1
Add onHttpResponseHeaders callback. Fixes #567
2018-10-08 19:42:58 +03:00
Kristaps Grinbergs 82a01218cc Merge pull request #569 from daltoniam/release_action
Release action with fastlane
2018-10-08 19:36:51 +03:00
Valentin Slawicek 46d8cacb2e Add onHttpResponseHeaders callback. Fixes #567 2018-10-08 17:54:04 +02:00
Kristaps Grinbergs 2280423c21 Release action with fastlane 2018-10-08 18:42:48 +03:00
Kristaps Grinbergs 2022e6f553 Merge pull request #568 from daltoniam/swift_4.2
Swift 4.2 and example project
2018-10-08 18:12:31 +03:00
Kristaps Grinbergs b0729b1181 Added build.sh file 2018-10-08 18:10:25 +03:00
Kristaps Grinbergs fd8a3fc3fa Clean up example project 2018-10-08 17:59:34 +03:00
Kristaps Grinbergs f58389b4ff Remove test project as submodule 2018-10-08 17:55:36 +03:00
Kristaps Grinbergs 4b28929ae5 Swift 4.2 and example project
* Swift 4.2 support
* version bump in podspec
* example version with websockets.org echo example
* remove deprecated .swift-version
2018-10-08 17:36:51 +03:00
Kristaps Grinbergs 384b8039ef Merge pull request #559 from turbulem/pr_520
Move CommonCrypto and zlib dependencies mapping to custom module map
2018-10-08 16:57:58 +03:00
Kristaps Grinbergs c70d18f03d Merge pull request #564 from fb55/patch-1
Add pongDelegate to WebSocketClient protocol
2018-10-04 21:57:27 +03:00
Felix Böhm 813d92d917 Add pongDelegate to WebSocketClient protocol
currently blocking https://github.com/RxSwiftCommunity/RxStarscream/pull/23
2018-10-04 12:53:54 +01:00
Sergey Lem c6dfbf1ccb Update podspec, return old code for sha1, update project settings 2018-10-02 11:28:24 +01:00
Sergey Lem e22724f5cf Remove no longer needed dependencies from SPM config 2018-10-01 11:52:33 +01:00
Sergey Lem dceb95c4ea Remove custom module maps for CC and zlib, use system-provided ones 2018-10-01 11:44:36 +01:00
Sergey Lem c3b05cde30 Squashed commit of the following:
commit 467334e818
Author: Sergey Lem <lemsergey@gmail.com>
Date:   Fri Sep 28 10:47:53 2018 +0100

    Remove old file

commit 631c25645a
Author: Sergey Lem <lemsergey@gmail.com>
Date:   Fri Sep 28 09:51:15 2018 +0100

    Fix project settings

commit d629a65c20
Merge: 6371914 7f12731
Author: Sergey Lem <lemsergey@gmail.com>
Date:   Wed Sep 26 14:58:20 2018 +0100

    Merge branch 'master' of github.com:turbulem/Starscream

    # Conflicts:
    #	Starscream.xcodeproj/project.pbxproj

commit 637191444a
Author: Sergey Lem <lemsergey@gmail.com>
Date:   Mon Sep 10 09:45:21 2018 +0100

    Add NSString+SHA1 to test target

commit 33846d16f5
Author: Sergey Lem <lemsergey@gmail.com>
Date:   Mon Sep 10 09:40:09 2018 +0100

    Fix project inclusion and add missing linker flag

commit 74e3c637e5
Author: Sergey Lem <lemsergey@gmail.com>
Date:   Wed Jul 25 10:47:16 2018 +0100

    Pull master branch from daltoniam/Starscream

commit 912e7da6a1
Author: Sergey Lem <lemsergey@gmail.com>
Date:   Thu Jun 28 11:30:51 2018 +0100

    Fix return type for SHA1 digest and cast warning

commit 70234bc6bb
Author: Sergey Lem <lemsergey@gmail.com>
Date:   Mon Jun 25 13:18:18 2018 +0100

    Add custom wrapper for SHA1 and custom modulemap for framework including module maps for CommonCrypto and zlib

commit 94f8d58d0b
Author: Sergey Lem <lemsergey@gmail.com>
Date:   Thu Jun 14 18:52:14 2018 +0100

    Move CommonCrypto and zlib dependencies mapping to private module map

commit 7f12731d14
Author: Sergey Lem <lemsergey@gmail.com>
Date:   Mon Sep 10 09:45:21 2018 +0100

    Add NSString+SHA1 to test target

commit 8df9d1ebf9
Author: Sergey Lem <lemsergey@gmail.com>
Date:   Mon Sep 10 09:40:09 2018 +0100

    Fix project inclusion and add missing linker flag

commit bd0732e53b
Merge: 138cfa7 70fd033
Author: Sergey Lem <lemsergey@gmail.com>
Date:   Wed Jul 25 10:48:22 2018 +0100

    Merge branch 'master'

    # Conflicts:
    #	Starscream.xcodeproj/project.pbxproj

commit 138cfa76a3
Author: Sergey Lem <lemsergey@gmail.com>
Date:   Wed Jul 25 10:47:16 2018 +0100

    Pull master branch from daltoniam/Starscream

commit ca783dbcae
Author: Sergey Lem <lemsergey@gmail.com>
Date:   Thu Jun 28 11:30:51 2018 +0100

    Fix return type for SHA1 digest and cast warning

commit 8ca8df0edc
Author: Sergey Lem <lemsergey@gmail.com>
Date:   Mon Jun 25 13:18:18 2018 +0100

    Add custom wrapper for SHA1 and custom modulemap for framework including module maps for CommonCrypto and zlib

commit 98e1d6207c
Author: Sergey Lem <lemsergey@gmail.com>
Date:   Thu Jun 14 18:52:14 2018 +0100

    Move CommonCrypto and zlib dependencies mapping to private module map
2018-09-28 13:20:22 +01:00
Dalton 79cd8a2a89 Merge pull request #556 from nuclearace/spm-4
update to swift 4 manifest
2018-09-25 10:58:35 -05:00
Erik Little a403aea07e update to swift 4 manifest 2018-09-23 09:41:41 -04:00
Dalton 70fd033db6 Merge pull request #527 from brian-dlee/master
Documents `disconnect` behavior in README
2018-07-20 16:50:59 -05:00
Dalton d2bf71599a Merge pull request #522 from MaherKSantina/master
Fixed typo in Readme
2018-07-20 16:49:59 -05:00
Dalton 09297799cc Merge pull request #507 from eliburke/master
added open keyword to SSLSecurity.isValid, added public to other methods
2018-07-20 16:48:48 -05:00
Dalton b111e1a8f0 Merge pull request #481 from MuniekMg/master
Client Side Authentication Added
2018-07-20 16:44:26 -05:00
Dalton 451480d86f Merge pull request #524 from adamkaplan/fix-crash-nil-outstream
Fix crash nil outstream
2018-07-20 16:41:39 -05:00
Brian Lee 9811225d21 Documents disconnect behavior in README 2018-06-25 15:41:34 -07:00
Adam Kaplan cfd37a6f08 Fix Xcode 10 error on unsafe access in test 2018-06-21 11:49:13 -04:00
Adam Kaplan c89a127289 Prevent a crash if Websocket output stream is gone 2018-06-21 11:45:29 -04:00
Maher Santina 6a2a3a7c36 Fixed typo 2018-06-21 18:32:03 +10:00
Maher Santina 8266c80b85 Fixed typo 2018-06-21 18:30:37 +10:00
Eli Burke d8278d951a added keyword public to SSLSecurity.certificateChain, publicKeyChain, extractPublicKey 2018-04-24 10:18:30 -04:00
Eli Burke 0f2ee9f68e change SSLSecurity.isValid from public to open 2018-04-24 09:58:53 -04:00
Tomasz Trela 8b9c52eec3 cosmetic changes to match original code 2018-04-07 19:43:02 +02:00
Tomasz Trela 073aa863cd prints changes to throw error 2018-04-07 19:39:42 +02:00
Tomasz Trela cd185b6fe9 Removed conflicts and unnecessary useSSLClientAuthentication varialbe 2018-04-07 18:50:35 +02:00
daltoniam 114e5df9b6 Merge branch 'master' of https://github.com/daltoniam/Starscream 2018-04-04 13:16:29 -05:00
daltoniam 430bfc32c3 a few small bug fixes and swift 4.1 support 2018-04-04 13:16:20 -05:00
MuniekMg 1edb4c0b65 Documantations fixed 2018-03-10 11:54:24 +01:00
MuniekMg 157291cb5e Client Side Authentication Added 2018-03-09 18:45:32 +01:00
Austin Cherry 31f522155a Merge pull request #461 from rastersize/remove-cartfile
Remove Cartfile as the checkout is unused
2018-02-19 17:22:33 -06:00
Aron Cedercrantz 327a7d8e9e Remove Cartfile as the checkout is unused 2018-01-30 18:04:11 -05:00
daltoniam 6e10c04c83 bumped spec. Updated CHANGELOG 2018-01-13 19:14:22 -06:00
daltoniam 97401e04bc Merge branch 'master' of https://github.com/daltoniam/Starscream 2018-01-13 18:56:36 -06:00
Dalton 6ba3563148 Merge pull request #452 from victorg1991/master
Enable editing Host header value
2018-01-13 18:56:27 -06:00
daltoniam 146368c71a new error handling. Timeout fix. Assorted fixes 2018-01-13 18:53:59 -06:00
Victor Galan 4ea6f4be3a Enable editing Host header value 2018-01-11 17:20:04 +01:00
daltoniam 6cb1c474e0 watchos, forgot about that one 2017-12-08 13:56:15 -06:00
daltoniam 7102d31afb watchos, forgot about that one 2017-12-08 13:53:31 -06:00
daltoniam 0f94bb3d95 spec 2017-12-08 13:46:43 -06:00
daltoniam 28070bf2a4 bumped spec 2017-12-08 13:40:21 -06:00
daltoniam ee0c7f9213 Merge branch 'master' of https://github.com/daltoniam/Starscream 2017-12-08 13:06:52 -06:00
daltoniam a49c7e2119 bug fixes 2017-12-08 13:06:50 -06:00
Dalton 7fad6b3a82 Merge pull request #438 from BlakeBarrett/patch-1
Update README.md
2017-12-08 13:04:32 -06:00
Dalton 06baac0fe7 Merge pull request #423 from neoneye/master
enableSOCKSProxy - See websocket traffic in Charles proxy
2017-12-08 13:04:16 -06:00
Blake Barrett 5866676617 Update README.md
Fix a typo in one of the code samples.
2017-12-07 16:44:04 -08:00
Simon Strandgaard b074c6c833 I was unable to see any websocket traffic in Charles proxy. In order to enable websocket inspection I applied the snippet by https://github.com/kevinmlong that is mentioned here: https://github.com/daltoniam/Starscream/issues/240 2017-11-15 15:58:36 +01:00
Dalton 8f2af31bd3 Merge pull request #418 from frederik-jacques/master
Fix warning for Swift 4 on the use of `character` property
2017-11-08 12:51:17 -06:00
Dalton d3fb769f93 Merge pull request #420 from fjcaetano/fix/deployment_target
Fix: tvOS framework deployment target
2017-11-08 12:47:36 -06:00
Flávio Caetano f58eb4ccad Fix: tvOS framework deployment target
fix #419
2017-11-07 17:35:35 -02:00
Frederik Jacques 880b5b4c9e Fix warning for Swift 4 on the use of character property 2017-11-07 09:37:00 +01:00
Dalton 97e378d94a Merge pull request #405 from hishnash/sendPong
Expose Pong Control frames
2017-11-06 12:58:32 -06:00
Dalton ca20b02ca2 Merge pull request #410 from qiuncheng/master
Fixed #409 When url contains query, server cannot get query parameters.
2017-11-06 12:57:18 -06:00
Dalton a1f133d737 Merge pull request #412 from eliburke/master
improved handling for self-signed certificate validation
2017-11-06 12:56:56 -06:00
Eli Burke 13f685f464 add flag to SSLSecurity implementation to turn off full cert chain checks. The
existing code would not work in cases where a CA cert was trusted, and the web
site used a signed leaf certificate. default behavior is unchanged
2017-10-31 11:41:41 -04:00
Eli Burke fae7ef2817 preserve original behavior when desiredTrustHostname is set to nil or "" 2017-10-23 09:45:19 -04:00
Eli Burke b24eaba135 separate self-signed from cert name override
add a 2nd method of getting the remote host domain name
2017-10-20 16:29:25 -04:00
qiuncheng e8182190b7 Fixed #409 When url contains query, server cannot get query parameters. 2017-10-17 14:22:22 +08:00
Dalton bf24825167 Merge pull request #400 from fassko/ISSUE_399
Fixes #399 String.characters.count deprecation warning in Xcode 9.1
2017-10-16 12:50:57 -05:00
Dalton 9ee57e089d Merge pull request #404 from rastersize/patch-1
Fix version number in changelog
2017-10-16 12:49:39 -05:00
Matthaus Woolard f057a8b33d Expose Pong Control frames
* Let users send Pong frames
* let users turn off automatic Ping responds with Pong. (only needed are edge cases)
2017-10-16 08:43:15 +03:00
Aron Cedercrantz b8fe0f64e3 Fix version number in changelog 2017-10-13 15:02:06 -04:00
Kristaps Grinbergs 94e54af61c Fixes #399
String.characters.count deprecation warnings
2017-10-09 16:40:15 +03:00
daltoniam 44ce58956f handle trailing slash better. bumped version 2017-10-04 21:54:22 -05:00
daltoniam c7cc1db0e3 fix for servers disliking not having a trailing slash. #394, #392 2017-10-02 13:08:10 -05:00
daltoniam a438ea1977 added armv7k 2017-09-27 15:12:41 -05:00
daltoniam b5991eda48 version update 2017-09-27 13:42:09 -05:00
Dalton 0a6f6d2a79 Merge pull request #388 from nuclearace/fix-http-headers
HTTP headers are case insensitive
2017-09-27 13:37:51 -05:00
Dalton 3fdf33a078 Merge pull request #390 from xjbeta/Fix-Deployment
Add macOS Deployment Target.
2017-09-27 13:36:04 -05:00
xjbeta 9f5f0f44f9 Add macOS Deployment Target. 2017-09-27 14:12:42 +08:00
Erik Little da7949d2da HTTP headers are case insensitive 2017-09-26 13:12:43 -04:00
Dalton dc48916804 Merge pull request #386 from lukkas/missing-arm64
add missing arm64
2017-09-26 11:51:03 -05:00
Lukasz Kasperek e0e8271725 add missing armv7 2017-09-26 15:57:04 +02:00
Lukasz Kasperek 411820d836 add missing arm64 2017-09-26 14:56:33 +02:00
daltoniam d326d448b0 pod spec update for new folder name 2017-09-25 16:29:15 -05:00
daltoniam 7dd90900dc merged the swift 4 branch 2017-09-25 16:22:33 -05:00
daltoniam f506be54ae refactor and swift4 2017-09-25 16:00:28 -05:00
Dalton 143ab16c1a Merge pull request #377 from hamchapman/two-targets-one-scheme
Reduce to two targets and a single scheme
2017-09-22 13:17:03 -05:00
Hamilton Chapman 4d281416c2 Reduce to two targets and a single scheme 2017-09-05 10:30:55 +01:00
Dalton e9d10000ec Merge pull request #372 from jcesarmobile/patch-1
Use Swift 4
2017-09-02 14:33:58 -05:00
Austin Cherry 789264eeff Merge pull request #375 from nremond/patch-1
Typo in README.md
2017-08-31 11:29:00 -05:00
Nicolas Rémond 644e8f92c0 Typo in README.md 2017-08-31 10:49:34 +02:00
jcesarmobile 68b64ede4e Use Swift 4
update .swift-version file to use Swift 4
2017-08-23 11:06:25 +02:00
daltoniam 31277a418c swift4 project file update 2017-08-19 17:23:58 -05:00
daltoniam 21678c9426 syntax fail 2017-08-19 17:03:45 -05:00
daltoniam acbf665b3d syntax fail 2017-08-19 17:01:00 -05:00
daltoniam e99deb9af8 changelog 2017-08-19 16:59:41 -05:00
daltoniam 6dc9cdffbc bumped spec 2017-08-19 16:50:40 -05:00
daltoniam ef4ed1b2f9 Merge branch 'master' of https://github.com/daltoniam/Starscream 2017-08-14 21:53:03 -05:00
daltoniam 3401fb25f4 fix for possible race condition 2017-08-14 21:53:00 -05:00
Dalton daa97005e6 Merge pull request #364 from nuclearace/master
Namespace zlib and common crypto
2017-08-14 21:52:14 -05:00
Erik Little 008302326b Namespace zlib and common crypto 2017-07-28 17:00:49 -04:00
Dalton d7c41e513f Merge pull request #357 from slk333/patch-2
typo
2017-07-28 14:15:47 -05:00
Dalton 92816513c3 Merge pull request #355 from danielrhammond/fix-segfault
Fix race on connected
2017-07-28 14:15:31 -05:00
slk333 6c9f76e7ea typo 2017-07-13 01:56:33 +02:00
Daniel Hammond 4d6dce3d64 Fix race on connected
doDisconnect(_:) gets called from a background thread as part of the operation queued in dequeueWrite(_,code:completion:) when a connection failure triggers this code it produces a race between all the reads of isConnected and that write on a different queue.
2017-07-10 13:23:06 -07:00
Dalton b0ed1decce Merge pull request #331 from winsmith/master
Added docs and error message for SSL Cipher Suites
2017-07-07 15:29:11 -05:00
daltoniam 86310e7bbc updated podspec 2017-07-07 15:18:08 -05:00
daltoniam 7edfb2ad85 the joys of getting all the package manager to play nice 2017-07-07 14:38:47 -05:00
Daniel Jilg 1efe3ce798 Merge branch 'master' into master 2017-07-05 09:44:12 +02:00
Daniel Jilg 624a5cc6c3 Removed Else Clause that would sometimes give a wrong error message
This reverts parts of commit 87dbce07ea.
2017-07-05 09:42:27 +02:00
daltoniam 09b9136ef0 updated changelog 2017-06-29 17:48:36 -05:00
daltoniam 5434be279c updated pod spec for compression changes 2017-06-29 17:46:31 -05:00
Dalton 08edd54a40 Merge pull request #349 from giullo/Fix-SSL-Pinning-Crash
SecTrust object now is conditionally unwrapped
2017-06-29 17:44:18 -05:00
Giuliano Galea 8623fe8b9e SecTrust object now is conditionally unwrapped 2017-06-27 10:29:29 +02:00
daltoniam fa85b9c61c spm fix 2017-06-24 19:09:03 -05:00
daltoniam 6e9a33a854 spm fix 2017-06-24 18:55:53 -05:00
daltoniam b5e68fceae package manager update 2017-06-24 18:13:24 -05:00
daltoniam 601ef74ca4 fixes #309, #319, #334 2017-06-24 18:09:48 -05:00
Dalton 7e517c246b Merge pull request #337 from hishnash/AdvancedDelegate
Add Advanced Delegate and Custom HTTP methods
2017-06-24 14:54:36 -05:00
Dalton bb11123729 Merge pull request #344 from wittedhaddock/patch-1
Update README with (trite) grammar changes
2017-06-24 14:46:35 -05:00
Dalton 7bf478ce94 Merge pull request #339 from junelife/compression
Support websocket compression
2017-06-24 14:45:25 -05:00
Matthaus Woolard bce64dabfa make WSResponse values public 2017-06-18 14:02:12 +03:00
Matthaus Woolard 3104c289e9 Add Advanced Delegate and Custom HTTP methods
Added the `WebSocketAdvancedDelegate` protocol that optionaly replaces the `WebSocketDelegate` adding support for:

* More detail when getting data (exposes the WSFrame object to the delegate)
* More detail about the HTTP request and response so that the user can extract needed information.

Also added support for custom HTTP methods for the http request.
2017-06-18 12:08:07 +03:00
James Graham f35266534a Update README with (trite) grammar changes 2017-06-06 10:46:07 -04:00
Joseph Ross 44fdfa3791 Include zlib as a module, rather than using @_silgen_name and redefinition. This is less verbose and less error-prone. 2017-05-25 14:23:07 -07:00
Joseph Ross 35fc161193 Add information about compression support to README. Other changes based on PR feedback. 2017-05-25 10:24:51 -07:00
Joseph Ross 45546818fb Avoid unnecessary copying. Confirm Autobahn fuzzing test results are comparable with the autobahn library itself. 2017-05-24 17:17:12 -07:00
Joseph Ross 19793796bb Fix capture memory leaks in Autobahn tester. 2017-05-24 13:39:06 -07:00
Joseph Ross 4ba077ee4b Fixes to handle different windowsBits and noContextTakeover. 2017-05-24 13:06:37 -07:00
Joseph Ross ca85642c21 Integrate compression classes. 2017-05-24 12:01:43 -07:00
Joseph Ross ccc9c4ea43 Add compression classes and unit tests. 2017-05-24 07:38:03 -07:00
Dalton 02718e7a45 Merge pull request #333 from nuclearace/master
Remove void parameter from onConnect, Swift4 would require passi…
2017-05-23 13:39:55 -05:00
Erik 961fd34f3d Remove void parameter from onConnect, Swift4 would require passing () into it 2017-05-20 21:40:38 -04:00
Daniel Jilg 87dbce07ea Add docs for SSL Cipher Suites 2017-05-04 15:44:26 +02:00
Dalton ee993322c1 Merge pull request #320 from RaghavMangrola/master
Swift Package Manager Installation Instructions
2017-03-28 20:15:52 -05:00
daltoniam 85070aab91 few warning fixes 2017-03-28 20:09:07 -05:00
Raghav Mangrola 07351dcb77 Swift Package Manager Installation Instructions 2017-03-19 16:11:13 -07:00
daltoniam dbeb1190b8 some cleanup and SSL pinning fix 2017-03-14 13:12:39 -05:00
daltoniam 13859364e3 updated changelog 2017-02-03 14:25:31 -06:00
daltoniam 41c0c5e08b version bump 2017-02-03 14:20:21 -06:00
daltoniam 60b27a4388 possible fix for #301 2017-01-11 22:55:39 -06:00
daltoniam a68bf7c35b connect delegate before firing message delegates. Fixed disconnect getting called before connect 2017-01-11 12:10:33 -06:00
Dalton 33a4551f3b Merge pull request #302 from Elethier/operation-cancellation
Fixed issues with not cancelling block operations properly
2017-01-10 22:25:12 -06:00
Dalton b22fae407e Merge pull request #300 from Elethier/multiple-disconnects
Added guard against multiple disconnects
2017-01-10 21:41:02 -06:00
Dalton e9160df255 Merge pull request #296 from nuclearace/fix-disconnect
Fix #295
2017-01-06 21:32:13 -06:00
Praneet Sahgal c63e173021 Fixed issues with not cancelling block operations properly 2017-01-04 09:15:56 -06:00
Praneet Sahgal ddcc30d200 Added guard against multiple disconnects 2017-01-04 09:03:42 -06:00
Erik 6bacb6f972 Fix #295
This sets didDisconnect to false if we receive a connect.
2016-12-31 18:05:11 -05:00
Dalton aca2ad5332 Merge pull request #292 from euskadi31/master
Change public to open
2016-12-30 16:32:51 -06:00
Dalton 3ba1963c65 Merge pull request #294 from wordpress-mobile/prevent-reconnection-crash
Prevent reconnection crash
2016-12-30 15:56:12 -06:00
Dalton 3cc4a60e05 Merge pull request #289 from robinmj/master
Fix for excessive memory use caused by the receipt of an unusually large message
2016-12-30 15:54:37 -06:00
Jorge Bernal 14313df360 Disconnect and clean up streams before connecting.
Since `disconnect` without a timeout only sends a close message to the server,
if we tried to `connect` the socket again before the connection was closed it
would not clean up the streams properly, which could result in a crash.

See #272
2016-12-27 16:23:39 +01:00
Jorge Bernal 162c1d53b8 Keep isConnecting true while connecting.
The existing code only prevented a second connection to be created while
createHTTPRequest was being called (setting up the HTTP request and the
streams). However, between the time when the socket opens the streams until the
TCP handshake ends, it would be both `!conneted` and `!isConnecting`, which
wouldn't prevent a second `connect`.
2016-12-27 15:56:01 +01:00
Axel Etcheverry b404f98244 Change public to open 2016-12-19 15:31:10 +01:00
daltoniam 8d0c0c1afa simple test update 2016-12-12 13:26:41 -06:00
Dalton 816fe413a4 Merge pull request #288 from dancasimiro/host-only-origin
Remove the path components from the URL sent as origin
2016-12-12 13:22:27 -06:00
Daniel C. Casimiro 5cc0d860ba Add path components to the test server URL
This demonstrates the path stripping from the origin URL.
2016-11-22 08:53:45 -05:00
Daniel C. Casimiro 4d2f8dbfee Remove the path components from the URL sent as origin
This fixes issue #287. The origin is a URI indicating the server from
which the request initiated. It does not include any path information,
but only the server name.
2016-11-22 08:53:45 -05:00
Robin Johnson 126c021e61 fixed malloc failure by draining autorelease pool with every dequeuing operation 2016-11-21 19:14:20 -07:00
daltoniam c13584b99c bumped spec 2016-11-14 22:29:34 -06:00
Dalton 178c3e8a49 Merge pull request #277 from nuclearace/master
Fix Swift package manager
2016-11-01 18:57:49 -05:00
Erik ccc1b703dd Fix Swift package manager 2016-10-30 19:47:58 -04:00
daltoniam 1b64f78542 version bump 2016-10-26 20:41:30 -05:00
Dalton 549500a503 Merge pull request #253 from noremac/master
Only disable SSL cert validation if we are using a secure scheme.
2016-10-26 20:26:58 -05:00
Dalton 22d57dca07 Merge pull request #276 from profer/master
Enable custom trust validation
2016-10-26 20:26:30 -05:00
daltoniam dd5119cfce fix for #261 2016-10-26 20:25:39 -05:00
Wolfgang Profer a6b2e4329b Enable custom trust validation
Change WebSocket to use a protocol for trust validation instead of SSLSecurity directly. This allows users of Starscream to supply their own validation logic.
2016-10-24 13:43:44 +02:00
Dalton 931e3ba8ae Merge pull request #266 from fjcaetano/master
'Open'ing classes
2016-10-11 23:23:09 -05:00
Dalton 7476f5196e Merge pull request #267 from Dipak99041012/2.0.0HotFixes
[Fixup] crash for SSL Pinning Strange crash
2016-10-11 23:20:28 -05:00
Dipak Kasabwala 20285cce97 [Fixup] crash for SSL Pinning Strange crash 2016-10-10 18:14:01 -04:00
Flávio Caetano 8e1de1d475 'Open'ing classes 2016-10-10 17:47:13 -03:00
Cameron Pulsford acf64adc24 Only disable SSL cert validation if we are using a secure scheme. 2016-09-30 14:49:26 -04:00
Dalton b0fa08cde4 Merge pull request #259 from robinkunde/master
Improve clarity of asyncAfter code and other timeout
2016-09-30 13:34:49 -05:00
Dalton 9d32864ab4 Merge pull request #260 from ujell/master
Fixed parameter names in documentation
2016-09-30 13:02:28 -05:00
Yücel Uzun 7ef2bc41e0 Fixed parameter names in documentation 2016-09-29 18:50:22 +02:00
Robin Kunde 24e32a78e3 improve clarity of asyncAfter code and other timeout 2016-09-28 12:27:48 -04:00
daltoniam d831901ff4 more things to get cocoapods working 2016-09-18 16:35:32 -05:00
daltoniam 26b03ddaef swift 3 support 2016-09-18 16:28:53 -05:00
daltoniam d94c3ff3b4 cocoapods... 2016-09-18 16:18:21 -05:00
daltoniam 60d853742c cocoapods... 2016-09-18 16:16:37 -05:00
daltoniam 8563f6b85e osx podspec update 2016-09-18 16:13:23 -05:00
daltoniam c889a6c977 available for osx 2016-09-18 16:07:39 -05:00
daltoniam 8f3761215b conflict fixes 2016-09-18 15:46:05 -05:00
daltoniam cdf8caeb1a swift 2.3 update 2016-09-18 15:43:12 -05:00
daltoniam 00d8fae6cd swift3 updates 2016-09-18 15:37:55 -05:00
Dalton 46db9a75f0 Merge pull request #243 from cpinski/writeQueueQOS
Added initializer to set the QOS of the write queue
2016-09-13 21:21:48 -05:00
Christopher Pinski 5a3adc7756 Added initializer to set the QOS of the write queue 2016-08-29 15:44:05 -05:00
Austin Cherry b1472f2a99 Merge pull request #242 from pvzig/xcode8b6
Xcode8b6
2016-08-28 13:15:57 -07:00
Peter Zignego 34ed785564 Update example test syntax 2016-08-28 11:26:03 -04:00
Peter Zignego 08d2da1221 Set SWIFT_VERSION for all targets 2016-08-28 11:25:52 -04:00
Dalton 5c607a80ce Merge pull request #235 from nuclearace/swift3-nuclearace
Beta6 update
2016-08-22 13:30:48 -07:00
Erik 3aac891e83 Merge dalton/master and update for swift3 2016-08-21 17:07:07 -04:00
Dalton 32fb0aa87e Merge pull request #230 from cpinski/swift2.3
Adding full support for swift 2.3
2016-08-14 15:21:25 -07:00
Dalton 473a1382ac Merge pull request #227 from tractus/swift3
Updated for Xcode 8 Beta 4
2016-08-08 17:41:39 -07:00
Christopher Pinski 9c210e006e Adding full support for swift 2.3 2016-08-05 10:47:12 -05:00
Dalton c767cb2a54 Merge pull request #225 from ThinkChaos/master
Fix typo that prevents SSL detection
2016-08-03 14:57:31 -07:00
Trey Richards cdd1224a71 Updated for Xcode 8 Beta 4 2016-08-02 15:30:56 -07:00
ThinkChaos 7c09aa08b4 Fix typo that prevents SSL detection 2016-07-31 10:18:00 +02:00
Dalton c2782b5452 Merge pull request #222 from Danappelxx/swift3
Fix typo in `dequeueInput`
2016-07-21 14:42:02 -07:00
Dan Appel 14bc9ad90f Fix typo in dequeueInput
This was breaking messages that were sent in chunks, since only the first chunk would be processed.
2016-07-20 18:51:58 -07:00
Dalton bdab51f4af Merge pull request #219 from nathanborror/master
Fixing 'queue' naming error
2016-07-12 18:39:42 -07:00
Nathan Borror 26297ed3c1 Fixing 'queue' naming error 2016-07-12 15:57:03 -07:00
Dalton 600815b240 Merge pull request #211 from Abeansits/master
Fixed formatting on a a few places to be more consistent.
2016-07-08 23:00:32 -07:00
Sebastian Nystorm 5fba5b83b4 Fixed formatting on a a few places to be more consistent.
Renamed a few vars to be more descriptive.
Added some MARKS to divide the code inte clearer chunks.
Also fixed a few spelling mistakes.
2016-07-03 22:19:08 -07:00
Dalton c39043cc29 Merge pull request #209 from Abeansits/master
Returned custom close reason from server according to RFC 6455
2016-06-24 19:35:44 -07:00
Sebastian Nystorm dd6bfa24b7 Returned custom close reason from server according to RFC 6455 2016-06-23 12:26:07 -07:00
daltoniam 64661bc6ce Merge branch 'master' of https://github.com/daltoniam/Starscream 2016-06-18 19:23:02 -07:00
daltoniam 0f03fab95d swift 3 branch README note 2016-06-18 19:22:45 -07:00
daltoniam c7b52b4485 swift 3 changes to build with xCode 8. More cleanup staged 2016-06-18 19:20:26 -07:00
Dalton fc35de78a5 Merge pull request #199 from dreymonde/notifications
Posting NSNotification about websocket connection and disconnection
2016-06-02 20:41:52 -07:00
Oleg Dreyman d911dc1adf README update to include information about NSNotifications 2016-05-29 20:19:55 +03:00
Oleg Dreyman f5f777c507 Posting errors with userInfo on WebsocketDidDisconnectNotification 2016-05-28 01:37:26 +03:00
Oleg Dreyman cca4af6112 Posting NSNotification about websocket connection and disconnection 2016-05-28 01:16:03 +03:00
daltoniam afad19ca84 changes for swift 3 2016-05-21 21:16:59 -07:00
daltoniam b159d03640 fixes #185 2016-05-16 22:27:51 -07:00
daltoniam d5aeefd853 switch from recusion to loop 2016-05-16 22:01:20 -07:00
Dalton f0f2ceee20 Merge pull request #189 from mayoff/upstream
process buffered messages non-recursively
2016-05-16 18:51:47 -07:00
Rob Mayoff 10cfb16197 process buffered messages non-recursively 2016-05-11 15:37:14 -05:00
daltoniam bf0146db26 1.1.3 release 2016-03-31 12:25:30 -07:00
Austin Cherry cf6def9453 Merge pull request #178 from noremac/dev/cameron.pulsford/write-complete
Adds an optional `writeCompletion` callback
2016-03-01 10:59:39 -08:00
Cameron Pulsford 8db1a45c6c Adds an optional "write did complete" callback 2016-03-01 09:24:16 -05:00
Austin Cherry 592da86d06 Merge pull request #177 from noremac/dev/cameron.pulsford/var-let
Replaces a force-unwrapped var with a let
2016-02-29 23:07:41 -08:00
Cameron Pulsford 43ade49abe Replaces a force-unwrapped NSData var with a let 2016-02-29 00:18:35 -05:00
Dalton e32674a1ea Merge pull request #175 from impossibleventures/master
Set "Require Only App-Extension-Safe API" to YES
2016-02-25 12:56:44 -08:00
Ryan Peck 7e49eb2458 Set APPLICATION_EXTENSION_API_ONLY = YES 2016-02-24 18:27:11 -06:00
Dalton 53c19d2388 Merge pull request #174 from nicolasbigot/master
Remove `var` parameters to conform to Swift 3
2016-02-24 11:42:36 -08:00
Nicolas Bigot ab02d55700 Fix comments spaces 2016-02-24 09:58:09 +01:00
Nicolas Bigot fa0865fcac Remove var parameters to conform to Swift 3 2016-02-24 09:55:23 +01:00
Dalton 5d185b41cb Merge pull request #171 from ReadmeCritic/master
Correct the spelling of CocoaPods in README
2016-02-12 18:19:34 -08:00
ReadmeCritic ba1d7db873 Correct the spelling of CocoaPods in README 2016-02-12 15:47:14 -08:00
Dalton e2eea95ea5 Merge pull request #170 from mayoff/master
change all use of ++ to += 1
2016-02-11 10:43:14 -08:00
Rob Mayoff 363e331a84 change all use of ++ to += 1
Swift 2.2 deprecates ++ and --, and Swift 3 will remove them.
2016-02-11 11:59:27 -06:00
daltoniam 75721192c9 Merge branch 'master' of https://github.com/daltoniam/Starscream 2016-02-08 19:04:10 -08:00
daltoniam 0c4a99588f bumped version 2016-02-08 19:03:41 -08:00
Dalton 4387f497c9 Merge pull request #167 from ayking/master
fix : connect to a shutdown server will not get error call back
2016-02-08 18:57:00 -08:00
Dalton d87b422950 Merge pull request #168 from onevcat/master
Fix crashing when reconnecting repeatedly
2016-02-08 18:55:26 -08:00
onevcat c5569dff12 Fix crashing when reconnecting repeatedly 2016-02-08 22:40:11 +08:00
Alan YU 6b303eafec fix : connect to a shutdown server will not get error call back 2016-02-05 17:12:33 +08:00
daltoniam 0f8dd95f70 proper fix for #164 2016-01-29 10:52:18 -08:00
daltoniam ede7c9aa89 Merge branch 'master' of https://github.com/daltoniam/Starscream 2016-01-27 21:39:38 -08:00
daltoniam afefdff061 fixes for #158, #159, #161, #164 2016-01-27 21:39:13 -08:00
Dalton 3a59333bac Merge pull request #160 from kylebshr/master
Simple update to examples for Swift 2 (println() to print())
2016-01-22 13:19:41 -08:00
Kyle Bashour 1951d74516 Simple update to examples for Swift 2 (println() to print()) 2016-01-22 13:00:04 -05:00
daltoniam 6c34076224 another possible fix for #158 2016-01-21 15:44:51 -08:00
daltoniam f189e7c51f possible fix for #158 2016-01-21 13:46:52 -08:00
daltoniam 95c91f9dbf changelog update 2016-01-18 12:34:43 -08:00
daltoniam 398d9c15bf bumped spec 2016-01-18 12:26:32 -08:00
Dalton 5a85e4e524 Merge pull request #157 from dsato80/fragBuffer-fix
set fragBuffer data if processHTTP returns -1
2016-01-18 12:15:57 -08:00
Daisuke Sato d6f2c2c409 set fragBuffer data if processHTTP returns -1 2016-01-18 18:10:30 +09:00
daltoniam ad91b8f1f3 shared queue and bug fixes 2016-01-17 22:39:41 -08:00
daltoniam c59125f34a fixes #139 2016-01-13 18:20:41 -08:00
daltoniam ce9062ab81 fixes #149 2016-01-13 18:16:37 -08:00
Dalton ff64f0b349 Merge pull request #152 from steven851007/master
Fix #151
2016-01-11 15:27:09 -08:00
Istvan Balogh 65dbee5c94 Add default value to origin to keep backward compatibility 2016-01-09 10:53:14 +01:00
Istvan Balogh 7927195b05 Fix #151 2015-12-25 11:19:09 +01:00
Dalton d32dcb2aaa Merge pull request #144 from JamesPrudente/master
call websocketDidConnect delegate after connected is set to prevent race condition
2015-12-23 15:03:49 -08:00
Dalton aeae316209 Merge pull request #146 from mstorsjo/avoid-unaligned
Avoid doing unaligned reads/writes via UnsafePointer
2015-12-12 20:22:57 +02:00
Martin Storsjö 4f2201d6b7 Avoid doing unaligned reads/writes via UnsafePointer
Instead read/write individual bytes via UnsafePointer<UInt8>.

This fixes crashes that only happen when optimization is turned on,
on 32 bit arm builds.

Not all processors support unaligned reads/writes of 64 bit values.
Without optimizations, the reads/writes probably end up handling one
byte at a time (like this commit makes it do), while higher
optimization levels convert it to single reads/writes of the full
size, which may require that the pointer is properly aligned.
2015-12-11 20:39:03 +02:00
James Prudente ec313a376e call websocketDidConnect delegate after connected is set to prevent race condition 2015-12-10 16:05:07 -08:00
Dalton d5f690123f Merge pull request #141 from delba/syntax
Syntax
2015-12-07 11:37:30 -08:00
delba b00a84716c Use implicit casting 2015-12-07 18:41:19 +01:00
delba aa11fd3bbe Use guard 2015-12-07 18:39:58 +01:00
delba b6dddff56c Use if-let optional unwrapping 2015-12-07 18:29:22 +01:00
delba ac4f5ced1e Use contains 2015-12-07 18:24:32 +01:00
delba 947601b673 Initialize OpCode from rawValue 2015-12-07 18:15:11 +01:00
delba cea6ce13c8 Remove unneccessary parentheses around conditions 2015-12-07 18:15:11 +01:00
delba 09c032a138 Use reduce 2015-12-07 18:15:11 +01:00
delba 3fe7363ee9 Use an optional parameter 2015-12-07 18:15:11 +01:00
delba 32925e3847 Use the optional method call syntax 2015-12-07 18:15:11 +01:00
delba 6ad98fb458 Use the for-i-in-range syntax 2015-12-07 18:15:11 +01:00
delba f02840355d Use the trailing closure syntax 2015-12-07 18:15:11 +01:00
delba 4bece17d89 Use the shorthand notation for Array and Dictionary 2015-12-07 18:15:11 +01:00
Dalton 3582bab0b8 Merge pull request #140 from markus-k/master
Unwrap header safely when validating response.
2015-11-24 09:58:22 -08:00
Dalton 737fca6e73 Merge pull request #138 from Abizern/error-codes
Make CloseCode enum public
2015-11-24 09:52:38 -08:00
Markus Kasten e9446a57cd Unwrap header safely when validating response.
App will crash otherwise, when the header is missing.
2015-11-24 11:53:02 +01:00
Abizer Nasir b6054567ee Create a WebSocket error domain
Saves using strings, and also the domain of the error can be switched against.
2015-11-22 00:14:52 +00:00
Abizer Nasir 2b8d6214e2 Make CloseCode enum public
Since they get passed to the websocketDidDisconnect delegate method,
making them public means that the codes can be switched against without
needing magic numbers.
2015-11-21 23:59:45 +00:00
Dalton c56e0104c3 Merge pull request #135 from simonbs/master
Sets UIRequiredDeviceCapabilities in tvOS target
2015-11-16 11:10:31 -08:00
Dalton 2bbc0895d6 Merge pull request #133 from mayoff/maintenance-1.0.2
clean up WebSocket.disconnect parameter
2015-11-16 11:10:05 -08:00
Simon Støvring f1acef9a5f Sets UIRequiredDeviceCapabilities in tvOS target 2015-11-16 18:51:41 +01:00
Rob Mayoff b29059a937 clean up WebSocket.disconnect parameter
Now the parameter is properly an Optional<NSTimeInterval>, nil means no timeout, and zero means close immediately and forcibly.
2015-11-12 21:02:02 -06:00
Dalton e1bbc7612e added license to source files 2015-11-12 11:40:48 -08:00
Dalton e10942bc23 bumped spec 2015-11-05 10:09:45 -08:00
Dalton 9cf2c1f787 framework and package managers 2015-11-05 10:03:19 -08:00
Dalton bc48e654ca fixed tvOS build settings 2015-11-04 15:02:51 -08:00
Dalton 5e2768c048 possible fix for #132 2015-11-04 13:18:00 -08:00
Dalton 756a42756a Merge branch 'master' of https://github.com/daltoniam/Starscream 2015-10-20 18:51:17 -07:00
Dalton 4442aed401 added force timeout option for #127 2015-10-20 18:51:10 -07:00
Dalton 5f4db02f99 Merge pull request #129 from OlivierBoucher/master
Added tvOS target and podspec modifications
2015-10-20 18:46:09 -07:00
Olivier Boucher 679d858bbb Added tvOS target and podspec modifications 2015-10-20 09:16:21 -04:00
Dalton ec32edfb4e README update 2015-10-13 19:20:01 -07:00
Dalton df98a6e363 changelog and README update 2015-10-12 12:06:54 -07:00
Dalton 47bcdfbe57 bumped spec 2015-09-29 12:59:38 -07:00
Austin Cherry d69b169970 Merge pull request #125 from victorluft/master
When using cert pinning with public keys, only require one match.
2015-09-29 11:57:43 -07:00
Victor Luft aa2cb1b8fb When using cert pinning with public keys, only require one match. 2015-09-29 10:34:26 -07:00
Dalton fe2c26b760 fix for #121. Possible fix for upgrade issue 2015-09-28 10:29:36 -07:00
Dalton 357cd532dc example updates and fix #119 2015-09-28 10:14:36 -07:00
Dalton e0e4b379e7 Merge pull request #110 from TeletronicsDotAe/master
Property for enabling only certain cipher suites for the WSS connection
2015-09-22 10:28:03 -07:00
Pelle Stenild Coltau 4c66b22b43 Changes made regarding CipherSuites with respect to pull request review comments: Removed NSLog and doDisconnect() and added return statements in failure scenarios. 2015-09-21 11:27:14 +04:00
Pelle Stenild Coltau e848f186a5 Merge remote-tracking branch 'upstream/master' 2015-09-20 12:32:39 +04:00
Dalton c8201ec71c README update 2015-09-18 10:40:21 -07:00
Dalton f990c68c53 fixed conflicts 2015-09-14 09:56:30 -07:00
Dalton 9d37723c4d ready to become the master 2015-09-14 09:49:33 -07:00
Dalton b32048b229 ready to become the master 2015-09-14 09:47:31 -07:00
Dalton a40f448a16 quick README update 2015-09-14 09:32:49 -07:00
Dalton dcb046a46c bumped podspec 2015-09-14 09:26:01 -07:00
Dalton 357a178a64 last quick fix for #113 2015-09-14 09:24:45 -07:00
Dalton 7a15d7d7e6 fix for #113 2015-09-11 10:52:07 -07:00
Dalton 13f7502163 cleanup for Swift 2 2015-09-10 17:17:42 -07:00
Dalton 2e5cb03ac3 fix for #115 2015-09-10 15:59:29 -07:00
Dalton b26ffa28cd fix for #115 2015-09-10 15:57:34 -07:00
Dalton b962e3e532 fixed conflicts 2015-09-04 13:30:52 -07:00
Dalton 5dfe1fc117 added master fixes 2015-09-03 20:05:33 -07:00
Pelle Stenild Coltau 4d072de18d Added optional unwrapping to cipher suites in case there is no ssl context 2015-08-30 11:22:39 +04:00
Leif Bredgaard Honore f0b188606f Revert "Better error handling of missing SSLContext"
This reverts commit fac69339ba.
2015-08-30 09:10:40 +04:00
Leif Bredgaard Honore fac69339ba Better error handling of missing SSLContext 2015-08-27 14:38:25 +04:00
Leif Bredgaard Honore e2c3e38a23 Bug fixed 2015-08-27 11:12:56 +04:00
Leif Bredgaard Honore 5f46a9097e Improved cipher suite error handling
We check the error code from SSLSetEnabledCiphers() and fail if it does
not succeed.
2015-08-26 14:06:43 +04:00
Leif Bredgaard Honore 8376a9c70b Cypher suite property renamed 2015-08-26 11:14:08 +04:00
Dalton 02f8eac43b Merge pull request #108 from FanVox/xcode7_b6
Make compatible with Xcode7 b5
2015-08-25 10:49:25 -07:00
Abizer Nasir 6a318b29d2 Make compatible with Xcode7 b5 2015-08-25 17:30:35 +01:00
Leif Bredgaard Honore df88d97511 It is now possible to set which SSL Cipher Suites are enabled for a connection 2015-08-24 14:21:05 +04:00
Austin ca478d26b2 fixed conflicts 2015-08-12 19:12:29 -07:00
Dalton 4b65324a8d Merge pull request #102 from Ewg777/Swift-2.0
xcode 7 beta 5 compatibility
2015-08-07 13:31:16 -07:00
Ewg 9663215089 xcode 7 beta 5 compatibility 2015-08-07 13:13:35 +03:00
Ewg 5d272a80ef xcode 7 beta 5 compatibility 2015-08-07 13:12:48 +03:00
Dalton e39ddeecf5 Merge pull request #101 from col/Swift-2.0
Xcode 7 / iOS 9 beta 4 compatibility
2015-07-22 10:38:22 -07:00
Colin Harris 36d4426888 Modified the Security class to make it compatible with Xcode 7 / iOS9 beta 4 2015-07-23 01:15:24 +08:00
Dalton a69929fbc1 Merge pull request #95 from ricardopereira/Swift-2.0
Swift 2.0 update
2015-06-10 13:36:29 -07:00
Ricardo Pereira 3178fb1705 #93 Converted to latest swift syntax 2015-06-10 11:58:10 +01:00
98 changed files with 6156 additions and 2221 deletions
+25
View File
@@ -0,0 +1,25 @@
---
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.
+1
View File
@@ -0,0 +1 @@
blank_issues_enabled: false
+23
View File
@@ -0,0 +1,23 @@
---
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.
@@ -0,0 +1,16 @@
---
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]
+8
View File
@@ -0,0 +1,8 @@
### 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.
+24
View File
@@ -0,0 +1,24 @@
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 }}
+93 -2
View File
@@ -4,7 +4,7 @@
# 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/
Pods/
# Xcode
.DS_Store
@@ -24,4 +24,95 @@ DerivedData
.idea/
*.hmap
*.xccheckout
*.xcodeproj/*.xcworkspace
*.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
+1
View File
@@ -0,0 +1 @@
3.2.2
+269
View File
@@ -0,0 +1,269 @@
# 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.
+4
View File
@@ -0,0 +1,4 @@
source "https://rubygems.org"
gem "fastlane"
gem "cocoapods"
+290
View File
@@ -0,0 +1,290 @@
GEM
remote: https://rubygems.org/
specs:
CFPropertyList (3.0.7)
base64
nkf
rexml
activesupport (6.1.7.7)
concurrent-ruby (~> 1.0, >= 1.0.2)
i18n (>= 1.6, < 2)
minitest (>= 5.1)
tzinfo (~> 2.0)
zeitwerk (~> 2.3)
addressable (2.8.6)
public_suffix (>= 2.0.2, < 6.0)
algoliasearch (1.27.5)
httpclient (~> 2.8, >= 2.8.3)
json (>= 1.5.1)
artifactory (3.0.17)
atomos (0.1.3)
aws-eventstream (1.3.0)
aws-partitions (1.895.0)
aws-sdk-core (3.191.3)
aws-eventstream (~> 1, >= 1.3.0)
aws-partitions (~> 1, >= 1.651.0)
aws-sigv4 (~> 1.8)
jmespath (~> 1, >= 1.6.1)
aws-sdk-kms (1.77.0)
aws-sdk-core (~> 3, >= 3.191.0)
aws-sigv4 (~> 1.1)
aws-sdk-s3 (1.143.0)
aws-sdk-core (~> 3, >= 3.191.0)
aws-sdk-kms (~> 1)
aws-sigv4 (~> 1.8)
aws-sigv4 (1.8.0)
aws-eventstream (~> 1, >= 1.0.2)
babosa (1.0.4)
base64 (0.2.0)
claide (1.1.0)
cocoapods (1.15.2)
addressable (~> 2.8)
claide (>= 1.0.2, < 2.0)
cocoapods-core (= 1.15.2)
cocoapods-deintegrate (>= 1.0.3, < 2.0)
cocoapods-downloader (>= 2.1, < 3.0)
cocoapods-plugins (>= 1.0.0, < 2.0)
cocoapods-search (>= 1.0.0, < 2.0)
cocoapods-trunk (>= 1.6.0, < 2.0)
cocoapods-try (>= 1.1.0, < 2.0)
colored2 (~> 3.1)
escape (~> 0.0.4)
fourflusher (>= 2.3.0, < 3.0)
gh_inspector (~> 1.0)
molinillo (~> 0.8.0)
nap (~> 1.0)
ruby-macho (>= 2.3.0, < 3.0)
xcodeproj (>= 1.23.0, < 2.0)
cocoapods-core (1.15.2)
activesupport (>= 5.0, < 8)
addressable (~> 2.8)
algoliasearch (~> 1.0)
concurrent-ruby (~> 1.1)
fuzzy_match (~> 2.0.4)
nap (~> 1.0)
netrc (~> 0.11)
public_suffix (~> 4.0)
typhoeus (~> 1.0)
cocoapods-deintegrate (1.0.5)
cocoapods-downloader (2.1)
cocoapods-plugins (1.0.0)
nap
cocoapods-search (1.0.1)
cocoapods-trunk (1.6.0)
nap (>= 0.8, < 2.0)
netrc (~> 0.11)
cocoapods-try (1.2.0)
colored (1.2)
colored2 (3.1.2)
commander (4.6.0)
highline (~> 2.0.0)
concurrent-ruby (1.2.3)
declarative (0.0.20)
digest-crc (0.6.5)
rake (>= 12.0.0, < 14.0.0)
domain_name (0.5.20190701)
unf (>= 0.0.5, < 1.0.0)
dotenv (2.8.1)
emoji_regex (3.2.3)
escape (0.0.4)
ethon (0.16.0)
ffi (>= 1.15.0)
excon (0.109.0)
faraday (1.10.3)
faraday-em_http (~> 1.0)
faraday-em_synchrony (~> 1.0)
faraday-excon (~> 1.1)
faraday-httpclient (~> 1.0)
faraday-multipart (~> 1.0)
faraday-net_http (~> 1.0)
faraday-net_http_persistent (~> 1.0)
faraday-patron (~> 1.0)
faraday-rack (~> 1.0)
faraday-retry (~> 1.0)
ruby2_keywords (>= 0.0.4)
faraday-cookie_jar (0.0.7)
faraday (>= 0.8.0)
http-cookie (~> 1.0.0)
faraday-em_http (1.0.0)
faraday-em_synchrony (1.0.0)
faraday-excon (1.1.0)
faraday-httpclient (1.0.1)
faraday-multipart (1.0.4)
multipart-post (~> 2)
faraday-net_http (1.0.1)
faraday-net_http_persistent (1.2.0)
faraday-patron (1.0.0)
faraday-rack (1.0.0)
faraday-retry (1.0.3)
faraday_middleware (1.2.0)
faraday (~> 1.0)
fastimage (2.3.0)
fastlane (2.219.0)
CFPropertyList (>= 2.3, < 4.0.0)
addressable (>= 2.8, < 3.0.0)
artifactory (~> 3.0)
aws-sdk-s3 (~> 1.0)
babosa (>= 1.0.3, < 2.0.0)
bundler (>= 1.12.0, < 3.0.0)
colored
commander (~> 4.6)
dotenv (>= 2.1.1, < 3.0.0)
emoji_regex (>= 0.1, < 4.0)
excon (>= 0.71.0, < 1.0.0)
faraday (~> 1.0)
faraday-cookie_jar (~> 0.0.6)
faraday_middleware (~> 1.0)
fastimage (>= 2.1.0, < 3.0.0)
gh_inspector (>= 1.1.2, < 2.0.0)
google-apis-androidpublisher_v3 (~> 0.3)
google-apis-playcustomapp_v1 (~> 0.1)
google-cloud-env (>= 1.6.0, < 2.0.0)
google-cloud-storage (~> 1.31)
highline (~> 2.0)
http-cookie (~> 1.0.5)
json (< 3.0.0)
jwt (>= 2.1.0, < 3)
mini_magick (>= 4.9.4, < 5.0.0)
multipart-post (>= 2.0.0, < 3.0.0)
naturally (~> 2.2)
optparse (>= 0.1.1)
plist (>= 3.1.0, < 4.0.0)
rubyzip (>= 2.0.0, < 3.0.0)
security (= 0.1.3)
simctl (~> 1.6.3)
terminal-notifier (>= 2.0.0, < 3.0.0)
terminal-table (~> 3)
tty-screen (>= 0.6.3, < 1.0.0)
tty-spinner (>= 0.8.0, < 1.0.0)
word_wrap (~> 1.0.0)
xcodeproj (>= 1.13.0, < 2.0.0)
xcpretty (~> 0.3.0)
xcpretty-travis-formatter (>= 0.0.3)
ffi (1.16.3)
fourflusher (2.3.1)
fuzzy_match (2.0.4)
gh_inspector (1.1.3)
google-apis-androidpublisher_v3 (0.54.0)
google-apis-core (>= 0.11.0, < 2.a)
google-apis-core (0.11.3)
addressable (~> 2.5, >= 2.5.1)
googleauth (>= 0.16.2, < 2.a)
httpclient (>= 2.8.1, < 3.a)
mini_mime (~> 1.0)
representable (~> 3.0)
retriable (>= 2.0, < 4.a)
rexml
google-apis-iamcredentials_v1 (0.17.0)
google-apis-core (>= 0.11.0, < 2.a)
google-apis-playcustomapp_v1 (0.13.0)
google-apis-core (>= 0.11.0, < 2.a)
google-apis-storage_v1 (0.29.0)
google-apis-core (>= 0.11.0, < 2.a)
google-cloud-core (1.6.1)
google-cloud-env (>= 1.0, < 3.a)
google-cloud-errors (~> 1.0)
google-cloud-env (1.6.0)
faraday (>= 0.17.3, < 3.0)
google-cloud-errors (1.3.1)
google-cloud-storage (1.45.0)
addressable (~> 2.8)
digest-crc (~> 0.4)
google-apis-iamcredentials_v1 (~> 0.1)
google-apis-storage_v1 (~> 0.29.0)
google-cloud-core (~> 1.6)
googleauth (>= 0.16.2, < 2.a)
mini_mime (~> 1.0)
googleauth (1.8.1)
faraday (>= 0.17.3, < 3.a)
jwt (>= 1.4, < 3.0)
multi_json (~> 1.11)
os (>= 0.9, < 2.0)
signet (>= 0.16, < 2.a)
highline (2.0.3)
http-cookie (1.0.5)
domain_name (~> 0.5)
httpclient (2.8.3)
i18n (1.14.4)
concurrent-ruby (~> 1.0)
jmespath (1.6.2)
json (2.7.1)
jwt (2.8.1)
base64
mini_magick (4.12.0)
mini_mime (1.1.5)
minitest (5.22.2)
molinillo (0.8.0)
multi_json (1.15.0)
multipart-post (2.4.0)
nanaimo (0.3.0)
nap (1.1.0)
naturally (2.2.1)
netrc (0.11.0)
nkf (0.2.0)
optparse (0.4.0)
os (1.1.4)
plist (3.7.1)
public_suffix (4.0.7)
rake (13.1.0)
representable (3.2.0)
declarative (< 0.1.0)
trailblazer-option (>= 0.1.1, < 0.2.0)
uber (< 0.2.0)
retriable (3.1.2)
rexml (3.2.6)
rouge (2.0.7)
ruby-macho (2.5.1)
ruby2_keywords (0.0.5)
rubyzip (2.3.2)
security (0.1.3)
signet (0.18.0)
addressable (~> 2.8)
faraday (>= 0.17.5, < 3.a)
jwt (>= 1.5, < 3.0)
multi_json (~> 1.10)
simctl (1.6.10)
CFPropertyList
naturally
terminal-notifier (2.0.0)
terminal-table (3.0.2)
unicode-display_width (>= 1.1.1, < 3)
trailblazer-option (0.1.2)
tty-cursor (0.7.1)
tty-screen (0.8.2)
tty-spinner (0.9.3)
tty-cursor (~> 0.7)
typhoeus (1.4.1)
ethon (>= 0.9.0)
tzinfo (2.0.6)
concurrent-ruby (~> 1.0)
uber (0.1.0)
unf (0.1.4)
unf_ext
unf_ext (0.0.9.1)
unicode-display_width (2.5.0)
word_wrap (1.0.0)
xcodeproj (1.24.0)
CFPropertyList (>= 2.3.3, < 4.0)
atomos (~> 0.1.3)
claide (>= 1.0.2, < 2.0)
colored2 (~> 3.1)
nanaimo (~> 0.3.0)
rexml (~> 3.2.4)
xcpretty (0.3.0)
rouge (~> 2.0.7)
xcpretty-travis-formatter (1.0.1)
xcpretty (~> 0.2, >= 0.0.7)
zeitwerk (2.6.13)
PLATFORMS
arm64-darwin-22
arm64-darwin-23
x86_64-darwin-20
x86_64-linux
DEPENDENCIES
cocoapods
fastlane
BUNDLED WITH
2.4.19
+4 -29
View File
@@ -1,7 +1,9 @@
Apache 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.
@@ -171,31 +173,4 @@ Apache License
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.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
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.
of your accepting any such warranty or additional liability.
+40
View File
@@ -0,0 +1,40 @@
// 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
+139 -145
View File
@@ -1,19 +1,15 @@
![starscream](https://raw.githubusercontent.com/daltoniam/starscream/assets/starscream.jpg)
Starscream is a conforming WebSocket ([RFC 6455](http://tools.ietf.org/html/rfc6455)) client library in Swift for iOS and OSX.
It's Objective-C counter part can be found here: [Jetfire](https://github.com/acmacalister/jetfire)
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](http://autobahn.ws/testsuite/).
- Conforms to all of the base [Autobahn test suite](https://crossbar.io/autobahn/).
- Nonblocking. Everything happens in the background, thanks to GCD.
- Simple delegate pattern design.
- TLS/WSS support.
- Simple concise codebase at just a few hundred LOC.
- Compression Extensions support ([RFC 7692](https://tools.ietf.org/html/rfc7692))
## Example
### Import the framework
First thing is to import the framework. See the Installation instructions on how to add the framework to your project.
@@ -21,190 +17,173 @@ First thing is to import the framework. See the Installation instructions on how
import Starscream
```
Once imported, you can open a connection to your WebSocket server. Note that `socket` is probably best as a property, so your delegate can stick around.
### 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 socket = WebSocket(url: NSURL(scheme: "ws", host: "localhost:8080", path: "/")!)
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 are some delegate methods that we need to implement.
After you are connected, there is either a delegate or closure you can use for process WebSocket events.
### websocketDidConnect
### Receiving data from a WebSocket
websocketDidConnect is called as soon as the client connects to the server.
`didReceive` receives all the WebSocket events in a single easy to handle enum.
```swift
func websocketDidConnect(socket: WebSocket) {
println("websocket is connected")
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
}
}
```
### websocketDidDisconnect
websocketDidDisconnect is called as soon as the client is disconnected from the server.
The closure of this would be:
```swift
func websocketDidDisconnect(socket: WebSocket, error: NSError?) {
println("websocket is disconnected: \(error?.localizedDescription)")
socket.onEvent = { event in
switch event {
// handle events just like above...
}
}
```
### websocketDidReceiveMessage
### Writing to a WebSocket
websocketDidReceiveMessage is called when the client gets a text frame from the connection.
### write a binary frame
The writeData method gives you a simple way to send `Data` (binary) data to the server.
```swift
func websocketDidReceiveMessage(socket: WebSocket, text: String) {
println("got some text: \(text)")
}
socket.write(data: data) //write some Data over the socket!
```
### websocketDidReceiveData
websocketDidReceiveData is called when the client gets a binary frame from the connection.
```swift
func websocketDidReceiveData(socket: WebSocket, data: NSData) {
println("got some data: \(data.length)")
}
```
### Optional: websocketDidReceivePong *(required protocol: WebSocketPongDelegate)*
websocketDidReceivePong is called when the client gets a pong response from the connection. You need to implement the WebSocketPongDelegate protocol and set an additional delegate, eg: ` socket.pongDelegate = self`
```swift
func websocketDidReceivePong(socket: WebSocket) {
println("Got pong!")
}
```
Or you can use closures.
```swift
var socket = WebSocket(url: NSURL(scheme: "ws", host: "localhost:8080", path: "/")!)
//websocketDidConnect
socket.onConnect = {
println("websocket is connected")
}
//websocketDidDisconnect
socket.onDisconnect = { (error: NSError?) in
println("websocket is disconnected: \(error?.localizedDescription)")
}
//websocketDidReceiveMessage
socket.onText = { (text: String) in
println("got some text: \(text)")
}
//websocketDidReceiveData
socket.onData = { (data: NSData) in
println("got some data: \(data.length)")
}
//you could do onPong as well.
socket.connect()
```
## The delegate methods give you a simple way to handle data from the server, but how do you send data?
### writeData
The writeData method gives you a simple way to send `NSData` (binary) data to the server.
```swift
self.socket.writeData(data) //write some NSData over the socket!
```
### writeString
### write a string frame
The writeString method is the same as writeData, but sends text/string.
```swift
self.socket.writeString("Hi Server!") //example on how to write text over the socket!
socket.write(string: "Hi Server!") //example on how to write text over the socket!
```
### writePing
### write a ping frame
The writePing method is the same as writeData, but sends a ping control frame.
The writePing method is the same as write, but sends a ping control frame.
```swift
self.socket.writePing(NSData()) //example on how to write a ping control frame over the socket!
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
self.socket.disconnect()
socket.disconnect()
```
### isConnected
Returns if the socket is connected or not.
The disconnect method can also send a custom close code if desired.
```swift
if self.socket.isConnected {
// do cool stuff.
}
socket.disconnect(closeCode: CloseCode.normal.rawValue)
```
### Custom Headers
### Custom Headers, Protocols and Timeout
You can also override the default websocket headers with your own custom ones like so:
You can override the default websocket headers, add your own custom ones and set a timeout:
```swift
socket.headers["Sec-WebSocket-Protocol"] = "someother protocols"
socket.headers["Sec-WebSocket-Version"] = "14"
socket.headers["My-Awesome-Header"] = "Everything is Awesome!"
```
### Protocols
If you need to specify a protocol, simple add it to the init:
```swift
//chat and superchat are the example protocols here
var socket = WebSocket(url: NSURL(scheme: "ws", host: "localhost:8080", path: "/")!, protocols: ["chat","superchat"])
socket.delegate = self
socket.connect()
```
### Self Signed SSL and VOIP
There are a couple of other properties that modify the stream:
```swift
var socket = WebSocket(url: NSURL(scheme: "ws", host: "localhost:8080", path: "/")!, protocols: ["chat","superchat"])
//set this if you are planning on using the socket in a VOIP background setting (using the background VOIP service).
socket.voipEnabled = true
//set this you want to ignore SSL cert validation, so a self signed SSL certificate can be used.
socket.selfSignedSSL = true
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.
SSL Pinning is also supported in Starscream.
Allow Self-signed certificates:
```swift
var socket = WebSocket(url: NSURL(scheme: "ws", host: "localhost:8080", path: "/")!, protocols: ["chat","superchat"])
let data = ... //load your certificate from disk
socket.security = Security(certs: [SSLCert(data: data)], usePublicKeys: true)
//socket.security = Security() //uses the .cer files in your app's bundle
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)
```
You load either a `NSData` blob of your certificate or you can use a `SecKeyRef` if you have a public key you want to use. The `usePublicKeys` bool is whether to use the certificates for validation or the public keys. The public keys will be extracted from the certificates automatically if `usePublicKeys` is choosen.
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 `dispatch_get_main_queue` 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.
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
var socket = WebSocket(url: NSURL(scheme: "ws", host: "localhost:8080", path: "/")!, protocols: ["chat","superchat"])
socket = WebSocket(url: URL(string: "ws://localhost:8080/")!, protocols: ["chat","superchat"])
//create a custom queue
socket.queue = dispatch_queue_create("com.vluxe.starscream.myapp", nil)
socket.callbackQueue = DispatchQueue(label: "com.vluxe.starscream.myapp")
```
## Example Project
@@ -213,21 +192,33 @@ Check out the SimpleTest project in the examples directory to see how to setup a
## Requirements
Starscream works with iOS 7/OSX 10.9 or above. It is recommended to use iOS 8/10.10 or above for Cocoapods/framework support.
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
### Cocoapods
### 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, '8.0'
platform :ios, '12.0'
use_frameworks!
pod 'Starscream', '~> 0.9.4'
pod 'Starscream', '~> 4.0.6'
Then run:
@@ -239,17 +230,18 @@ Check out the [Carthage](https://github.com/Carthage/Carthage) docs on how to ad
[Carthage Install](https://github.com/Carthage/Carthage#adding-frameworks-to-an-application)
### Rogue
You can install Carthage with [Homebrew](http://brew.sh/) using the following command:
First see the [installation docs](https://github.com/acmacalister/Rogue) for how to install Rogue.
To install Starscream run the command below in the directory you created the rogue file.
```
rogue add https://github.com/daltoniam/starscream
```bash
$ brew update
$ brew install carthage
```
Next open the `libs` folder and 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. Make sure to add the `libs` folder to your `.gitignore` file.
To integrate Starscream into your Xcode project using Carthage, specify it in your `Cartfile`:
```
github "daltoniam/Starscream" >= 4.0.6
```
### Other
@@ -263,8 +255,10 @@ If you are running this in an OSX app or on a physical iOS device you will need
## TODOs
- [ ] Complete Docs
- [ ] Add Unit Tests
- [ ] Proxy support
- [ ] Thread safe implementation
- [ ] Better testing/CI
- [ ] SSL Pinning/client auth examples
## License
-244
View File
@@ -1,244 +0,0 @@
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// Security.swift
// Starscream
//
// Created by Dalton Cherry on 5/16/15.
// Copyright (c) 2015 Vluxe. All rights reserved.
//
//////////////////////////////////////////////////////////////////////////////////////////////////
import Foundation
import Security
public class SSLCert {
var certData: NSData?
var key: SecKeyRef?
/**
Designated init for certificates
:param: data is the binary data of the certificate
:returns: a representation security object to be used with
*/
public init(data: NSData) {
self.certData = data
}
/**
Designated init for public keys
:param: key is the public key to be used
:returns: a representation security object to be used with
*/
public init(key: SecKeyRef) {
self.key = key
}
}
public class Security {
public var validatedDN = true //should the domain name be validated?
var isReady = false //is the key processing done?
var certificates: [NSData]? //the certificates
var pubKeys: [SecKeyRef]? //the public keys
var usePublicKeys = false //use public keys or certificate validation?
/**
Use certs from main app bundle
:param: usePublicKeys is to specific if the publicKeys or certificates should be used for SSL pinning validation
:returns: a representation security object to be used with
*/
public convenience init(usePublicKeys: Bool = false) {
let paths = NSBundle.mainBundle().pathsForResourcesOfType("cer", inDirectory: ".")
var collect = Array<SSLCert>()
for path in paths {
if let d = NSData(contentsOfFile: path as! String) {
collect.append(SSLCert(data: d))
}
}
self.init(certs:collect, usePublicKeys: usePublicKeys)
}
/**
Designated init
:param: keys is the certificates or public keys to use
:param: usePublicKeys is to specific if the publicKeys or certificates should be used for SSL pinning validation
:returns: a representation security object to be used with
*/
public init(certs: [SSLCert], usePublicKeys: Bool) {
self.usePublicKeys = usePublicKeys
if self.usePublicKeys {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), {
var collect = Array<SecKeyRef>()
for cert in certs {
if let data = cert.certData where cert.key == nil {
cert.key = self.extractPublicKey(data)
}
if let k = cert.key {
collect.append(k)
}
}
self.pubKeys = collect
self.isReady = true
})
} else {
var collect = Array<NSData>()
for cert in certs {
if let d = cert.certData {
collect.append(d)
}
}
self.certificates = collect
self.isReady = true
}
}
/**
Valid the trust and domain name.
:param: trust is the serverTrust to validate
:param: domain is the CN domain to validate
:returns: if the key was successfully validated
*/
public func isValid(trust: SecTrustRef, domain: String?) -> Bool {
var tries = 0
while(!self.isReady) {
usleep(1000)
tries += 1
if tries > 5 {
return false //doesn't appear it is going to ever be ready...
}
}
var policy: SecPolicyRef
if self.validatedDN {
policy = SecPolicyCreateSSL(1, domain).takeRetainedValue()
} else {
policy = SecPolicyCreateBasicX509().takeRetainedValue()
}
SecTrustSetPolicies(trust,policy)
if self.usePublicKeys {
if let keys = self.pubKeys {
var trustedCount = 0
let serverPubKeys = publicKeyChainForTrust(trust)
for serverKey in serverPubKeys as [AnyObject] {
for key in keys as [AnyObject] {
if serverKey.isEqual(key) {
trustedCount++
break
}
}
}
if trustedCount == serverPubKeys.count {
return true
}
}
} else if let certs = self.certificates {
let serverCerts = certificateChainForTrust(trust)
var collect = Array<SecCertificate>()
for cert in certs {
collect.append(SecCertificateCreateWithData(nil,cert).takeRetainedValue())
}
SecTrustSetAnchorCertificates(trust,collect)
var result: SecTrustResultType = 0
SecTrustEvaluate(trust,&result)
let r = Int(result)
if r == kSecTrustResultUnspecified || r == kSecTrustResultProceed {
var trustedCount = 0
for serverCert in serverCerts {
for cert in certs {
if cert == serverCert {
trustedCount++
break
}
}
}
if trustedCount == serverCerts.count {
return true
}
}
}
return false
}
/**
Get the public key from a certificate data
:param: data is the certificate to pull the public key from
:returns: a public key
*/
func extractPublicKey(data: NSData) -> SecKeyRef? {
var publicKey: NSData?
let possibleCert = SecCertificateCreateWithData(nil,data)
if let cert = possibleCert {
return extractPublicKeyFromCert(cert.takeRetainedValue(),policy: SecPolicyCreateBasicX509().takeRetainedValue())
}
return nil
}
/**
Get the public key from a certificate
:param: data is the certificate to pull the public key from
:returns: a public key
*/
func extractPublicKeyFromCert(cert: SecCertificate, policy: SecPolicy) -> SecKeyRef? {
var possibleTrust: Unmanaged<SecTrust>?
SecTrustCreateWithCertificates(cert,policy, &possibleTrust)
if let trust = possibleTrust {
let t = trust.takeRetainedValue()
var result: SecTrustResultType = 0
SecTrustEvaluate(t,&result)
return SecTrustCopyPublicKey(t).takeRetainedValue()
}
return nil
}
/**
Get the certificate chain for the trust
:param: trust is the trust to lookup the certificate chain for
:returns: the certificate chain for the trust
*/
func certificateChainForTrust(trust: SecTrustRef) -> Array<NSData> {
var collect = Array<NSData>()
for var i = 0; i < SecTrustGetCertificateCount(trust); i++ {
let cert = SecTrustGetCertificateAtIndex(trust,i)
collect.append(SecCertificateCopyData(cert.takeRetainedValue()).takeRetainedValue())
}
return collect
}
/**
Get the public key chain for the trust
:param: trust is the trust to lookup the certificate chain and extract the public keys
:returns: the public keys from the certifcate chain for the trust
*/
func publicKeyChainForTrust(trust: SecTrustRef) -> Array<SecKeyRef> {
var collect = Array<SecKeyRef>()
let policy = SecPolicyCreateBasicX509().takeRetainedValue()
for var i = 0; i < SecTrustGetCertificateCount(trust); i++ {
let cert = SecTrustGetCertificateAtIndex(trust,i)
if let key = extractPublicKeyFromCert(cert.takeRetainedValue(), policy: policy) {
collect.append(key)
}
}
return collect
}
}
+29
View File
@@ -0,0 +1,29 @@
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// 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?
}
+256
View File
@@ -0,0 +1,256 @@
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// 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<z_stream>.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<UInt8>) -> Data in
return try decompress(bytes: bytes, count: data.count, finish: finish)
}
}
func decompress(bytes: UnsafePointer<UInt8>, 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<UInt8>, count: Int, out: inout Data) throws {
var res: CInt = 0
strm.next_in = UnsafeMutablePointer<UInt8>(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<z_stream>.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<UInt8>) -> Void in
strm.next_in = UnsafeMutablePointer<UInt8>(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()
}
}
+53
View File
@@ -0,0 +1,53 @@
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// 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<ResultType, ContentType>(_ completion: (UnsafePointer<ContentType>) 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<ResultType, ContentType>(_ completion: (UnsafeMutablePointer<ContentType>) 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
}
+36
View File
@@ -0,0 +1,36 @@
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// 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: (() -> ())?)
}
+115
View File
@@ -0,0 +1,115 @@
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// 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))
}
}
+265
View File
@@ -0,0 +1,265 @@
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// 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<UInt16>.size
var pointer = [UInt8](repeating: 0, count: capacity)
writeUint16(&pointer, offset: 0, value: closeCode)
let payload = Data(bytes: pointer, count: MemoryLayout<UInt16>.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.endIndex)
framer.add(data: extraData)
}
}
case .cancelled:
mutex.wait()
isConnecting = false
mutex.signal()
broadcast(event: .cancelled)
case .peerClosed:
broadcast(event: .peerClosed)
}
}
// MARK: - HTTPHandlerDelegate
public func didReceiveHTTP(event: HTTPEvent) {
switch event {
case .success(let headers):
if let error = headerChecker.validate(headers: headers, key: secKeyValue) {
handleError(error)
return
}
mutex.wait()
isConnecting = false
didUpgrade = true
canSend = true
mutex.signal()
compressionHandler?.load(headers: headers)
if let url = request.url {
HTTPCookie.cookies(withResponseHeaderFields: headers, for: url).forEach {
HTTPCookieStorage.shared.setCookie($0)
}
}
broadcast(event: .connected(headers))
case .failure(let error):
handleError(error)
}
}
// MARK: - FramerEventClient
public func frameProcessed(event: FrameEvent) {
switch event {
case .frame(let frame):
frameHandler.add(frame: frame)
case .error(let error):
handleError(error)
}
}
// MARK: - FrameCollectorDelegate
public func decompress(data: Data, isFinal: Bool) -> 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()
}
}
+124
View File
@@ -0,0 +1,124 @@
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// 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..<offset))
} else {
buffer.append(data)
}
if parseContent(data: buffer) {
buffer = Data()
}
return offset
}
//returns true when the buffer should be cleared
func parseContent(data: Data) -> 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.count {
if pointer[i] == endBytes[k] {
k += 1
if k == 4 {
return i + 1
}
} else {
k = 0
}
}
return -1
}
}
#endif
@@ -0,0 +1,99 @@
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// FoundationHTTPHandler.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 class FoundationHTTPServerHandler: HTTPServerHandler {
var buffer = Data()
weak var delegate: HTTPServerDelegate?
let getVerb: NSString = "GET"
public func register(delegate: HTTPServerDelegate) {
self.delegate = delegate
}
public func createResponse(headers: [String: String]) -> 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
}
}
+107
View File
@@ -0,0 +1,107 @@
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// 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
}
}
+365
View File
@@ -0,0 +1,365 @@
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// 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<UInt16>.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<UInt64>.size
if size + offset > pointer.count {
return .needsMoreData
}
dataLength = pointer.readUint64(offset: offset)
offset += size
} else if payloadLen == 126 {
let size = MemoryLayout<UInt16>.size
if size + offset > pointer.count {
return .needsMoreData
}
dataLength = UInt64(pointer.readUint16(offset: offset))
offset += size
}
let maskStart = offset
if isServer {
offset += MemoryLayout<UInt32>.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..<end])
}
}
offset += readDataLength
let frame = Frame(isFin: isFin > 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<UInt16>.size
} else {
pointer[1] = 127
writeUint64(&pointer, offset: offset, value: UInt64(payloadLength))
offset += MemoryLayout<UInt64>.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<UInt32>.size
//now write the payload data in
for i in 0..<payloadLength {
pointer[offset] = payload[i] ^ pointer[maskStart + (i % MemoryLayout<UInt32>.size)]
offset += 1
}
} else {
for i in 0..<payloadLength {
pointer[offset] = payload[i]
offset += 1
}
}
return Data(pointer[0..<offset])
}
}
/// MARK: - functions for simpler array buffer reading and writing
public protocol MyWSArrayType {}
extension UInt8: MyWSArrayType {}
public extension Array where Element: MyWSArrayType & UnsignedInteger {
/**
Read a UInt16 from a buffer.
- parameter offset: is the offset index to start the read from (e.g. buffer[0], buffer[1], etc).
- returns: a UInt16 of the value from the buffer
*/
func readUint16(offset: Int) -> 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<UInt32>.size
for i in 0..<length {
unmaskedBytes[i] = UInt8(self[offset + i] ^ self[maskStart + (i % maskSize)])
}
return Data(unmaskedBytes)
}
}
/**
Write a UInt16 to the buffer. It fills the 2 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 writeUint16( _ buffer: inout [UInt8], offset: Int, value: UInt16) {
buffer[offset + 0] = UInt8(value >> 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)
}
}
+150
View File
@@ -0,0 +1,150 @@
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// 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)
}
}
+143
View File
@@ -0,0 +1,143 @@
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// 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)..<path.endIndex])
if let range = path.range(of: "/") {
path = String(path[range.lowerBound..<path.endIndex])
} else {
path = "/"
if let query = url.query {
path += "?" + query
}
}
var httpBody = "\(request.httpMethod ?? "GET") \(path) HTTP/1.1\r\n"
if let headers = request.allHTTPHeaderFields {
for (key, val) in headers {
httpBody += "\(key): \(val)\r\n"
}
}
httpBody += "\r\n"
guard var data = httpBody.data(using: .utf8) else {
return Data()
}
if let body = request.httpBody {
data.append(body)
}
return data
}
public func parse(data: Data) -> Int {
let offset = findEndOfHTTP(data: data)
if offset > 0 {
buffer.append(data.subdata(in: 0..<offset))
if parseContent(data: buffer) {
buffer = Data()
}
} else {
buffer.append(data)
}
return offset
}
//returns true when the buffer should be cleared
func parseContent(data: Data) -> 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..<data.count {
if pointer[i] == endBytes[k] {
k += 1
if k == 4 {
return i + 1
}
} else {
k = 0
}
}
return -1
}
}
+2 -2
View File
@@ -7,7 +7,7 @@
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>com.vluxe.$(PRODUCT_NAME:rfc1034identifier)</string>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
@@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<string>$(MARKETING_VERSION)</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
+14
View File
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>NSPrivacyTracking</key>
<false/>
<key>NSPrivacyTrackingDomains</key>
<array/>
<key>NSPrivacyCollectedDataTypes</key>
<array/>
<key>NSPrivacyAccessedAPITypes</key>
<array/>
</dict>
</plist>
+99
View File
@@ -0,0 +1,99 @@
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// 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()
}
}
+45
View File
@@ -0,0 +1,45 @@
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// 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?
}
+56
View File
@@ -0,0 +1,56 @@
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// 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?
}
+198
View File
@@ -0,0 +1,198 @@
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// 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
+31
View File
@@ -0,0 +1,31 @@
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// 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 <Foundation/Foundation.h>
//! 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 <Starscream/PublicHeader.h>
+174
View File
@@ -0,0 +1,174 @@
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// 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)
}
}
}
+218
View File
@@ -0,0 +1,218 @@
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// 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<CFReadStream>?
var writeStream: Unmanaged<CFWriteStream>?
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<Int8>) 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
}
}
}
+171
View File
@@ -0,0 +1,171 @@
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// 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
+63
View File
@@ -0,0 +1,63 @@
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// 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 }
}
-19
View File
@@ -1,19 +0,0 @@
//
// Starscream.h
// Starscream
//
// Created by Austin Cherry on 9/25/14.
// Copyright (c) 2014 Vluxe. All rights reserved.
//
#import <Foundation/Foundation.h>
//! 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 <Starscream/PublicHeader.h>
+11 -6
View File
@@ -1,14 +1,19 @@
Pod::Spec.new do |s|
s.name = "Starscream"
s.version = "0.9.6"
s.summary = "A conforming WebSocket RFC 6455 client library in Swift for iOS and OSX."
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 = '8.0'
s.osx.deployment_target = '10.9'
s.source_files = '*.swift'
s.requires_arc = 'true'
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 diff suppressed because it is too large Load Diff
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0630"
version = "1.3">
LastUpgradeVersion = "1530"
version = "1.7">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
@@ -14,7 +14,7 @@
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "6B3E79E519D48B7F006071F7"
BlueprintIdentifier = "33CCF0841F5DDC030099B092"
BuildableName = "Starscream.framework"
BlueprintName = "Starscream"
ReferencedContainer = "container:Starscream.xcodeproj">
@@ -23,44 +23,67 @@
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
buildConfiguration = "Debug">
<Testables>
</Testables>
</TestAction>
<LaunchAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
buildConfiguration = "Debug"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
allowLocationSimulation = "YES">
codeCoverageEnabled = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "6B3E79E519D48B7F006071F7"
BlueprintIdentifier = "33CCF0841F5DDC030099B092"
BuildableName = "Starscream.framework"
BlueprintName = "Starscream"
ReferencedContainer = "container:Starscream.xcodeproj">
</BuildableReference>
</MacroExpansion>
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "335FA1F41F5DF71D00F6D2EC"
BuildableName = "Starscream Tests.xctest"
BlueprintName = "Starscream Tests"
ReferencedContainer = "container:Starscream.xcodeproj">
</BuildableReference>
<LocationScenarioReference
identifier = "com.apple.dt.IDEFoundation.CurrentLocationScenarioIdentifier"
referenceType = "1">
</LocationScenarioReference>
</TestableReference>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "33CCF0841F5DDC030099B092"
BuildableName = "Starscream.framework"
BlueprintName = "Starscream"
ReferencedContainer = "container:Starscream.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
buildConfiguration = "Release"
debugDocumentVersioning = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "6B3E79E519D48B7F006071F7"
BlueprintIdentifier = "33CCF0841F5DDC030099B092"
BuildableName = "Starscream.framework"
BlueprintName = "Starscream"
ReferencedContainer = "container:Starscream.xcodeproj">
@@ -1,110 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0630"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "D9C3E35E19E48FF1009FC285"
BuildableName = "Starscream.framework"
BlueprintName = "StarscreamOSX"
ReferencedContainer = "container:Starscream.xcodeproj">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "NO"
buildForArchiving = "NO"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "D9C3E36819E48FF1009FC285"
BuildableName = "StarscreamOSXTests.xctest"
BlueprintName = "StarscreamOSXTests"
ReferencedContainer = "container:Starscream.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
buildConfiguration = "Debug">
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "D9C3E36819E48FF1009FC285"
BuildableName = "StarscreamOSXTests.xctest"
BlueprintName = "StarscreamOSXTests"
ReferencedContainer = "container:Starscream.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "D9C3E35E19E48FF1009FC285"
BuildableName = "Starscream.framework"
BlueprintName = "StarscreamOSX"
ReferencedContainer = "container:Starscream.xcodeproj">
</BuildableReference>
</MacroExpansion>
</TestAction>
<LaunchAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
buildConfiguration = "Debug"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
allowLocationSimulation = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "D9C3E35E19E48FF1009FC285"
BuildableName = "Starscream.framework"
BlueprintName = "StarscreamOSX"
ReferencedContainer = "container:Starscream.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
buildConfiguration = "Release"
debugDocumentVersioning = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "D9C3E35E19E48FF1009FC285"
BuildableName = "Starscream.framework"
BlueprintName = "StarscreamOSX"
ReferencedContainer = "container:Starscream.xcodeproj">
</BuildableReference>
</MacroExpansion>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
@@ -1,96 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0630"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "NO"
buildForArchiving = "NO"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "6B3E79F019D48B7F006071F7"
BuildableName = "StarscreamTests.xctest"
BlueprintName = "StarscreamTests"
ReferencedContainer = "container:Starscream.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
buildConfiguration = "Debug">
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "6B3E79F019D48B7F006071F7"
BuildableName = "StarscreamTests.xctest"
BlueprintName = "StarscreamTests"
ReferencedContainer = "container:Starscream.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "6B3E79F019D48B7F006071F7"
BuildableName = "StarscreamTests.xctest"
BlueprintName = "StarscreamTests"
ReferencedContainer = "container:Starscream.xcodeproj">
</BuildableReference>
</MacroExpansion>
</TestAction>
<LaunchAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
buildConfiguration = "Debug"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
allowLocationSimulation = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "6B3E79F019D48B7F006071F7"
BuildableName = "StarscreamTests.xctest"
BlueprintName = "StarscreamTests"
ReferencedContainer = "container:Starscream.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
buildConfiguration = "Release"
debugDocumentVersioning = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "6B3E79F019D48B7F006071F7"
BuildableName = "StarscreamTests.xctest"
BlueprintName = "StarscreamTests"
ReferencedContainer = "container:Starscream.xcodeproj">
</BuildableReference>
</MacroExpansion>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
+67
View File
@@ -0,0 +1,67 @@
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// 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<UInt8>) -> Void in
arc4random_buf(ptr, rawDataLen)
}
let compressed = try! compressor.compress(rawData)
let uncompressed = try! decompressor.decompress(compressed, finish: true)
XCTAssert(rawData == uncompressed)
}
}
+201
View File
@@ -0,0 +1,201 @@
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// 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.
}
+1 -1
View File
@@ -7,7 +7,7 @@
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>com.vluxe.$(PRODUCT_NAME:rfc1034identifier)</string>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
+144
View File
@@ -0,0 +1,144 @@
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// 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)
}
}
+79
View File
@@ -0,0 +1,79 @@
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// 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
}
}
-35
View File
@@ -1,35 +0,0 @@
//
// StarscreamTests.swift
// StarscreamTests
//
// Created by Austin Cherry on 9/25/14.
// Copyright (c) 2014 Vluxe. All rights reserved.
//
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.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
@@ -0,0 +1,49 @@
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// 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.
}
}
}
-726
View File
@@ -1,726 +0,0 @@
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// Websocket.swift
//
// Created by Dalton Cherry on 7/16/14.
//
//////////////////////////////////////////////////////////////////////////////////////////////////
import Foundation
import CoreFoundation
public protocol WebSocketDelegate: class {
func websocketDidConnect(socket: WebSocket)
func websocketDidDisconnect(socket: WebSocket, error: NSError?)
func websocketDidReceiveMessage(socket: WebSocket, text: String)
func websocketDidReceiveData(socket: WebSocket, data: NSData)
}
public protocol WebSocketPongDelegate: class {
func websocketDidReceivePong(socket: WebSocket)
}
public class WebSocket : NSObject, NSStreamDelegate {
enum OpCode : 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.
}
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
}
enum InternalErrorCode : UInt16 {
// 0-999 WebSocket status codes not used
case OutputStreamWriteError = 1
}
//Where the callback is executed. It defaults to the main UI thread queue.
public var queue = dispatch_get_main_queue()
var optionalProtocols : Array<String>?
//Constant Values.
let headerWSUpgradeName = "Upgrade"
let headerWSUpgradeValue = "websocket"
let headerWSHostName = "Host"
let headerWSConnectionName = "Connection"
let headerWSConnectionValue = "Upgrade"
let headerWSProtocolName = "Sec-WebSocket-Protocol"
let headerWSVersionName = "Sec-WebSocket-Version"
let headerWSVersionValue = "13"
let headerWSKeyName = "Sec-WebSocket-Key"
let headerOriginName = "Origin"
let headerWSAcceptName = "Sec-WebSocket-Accept"
let BUFFER_MAX = 4096
let FinMask: UInt8 = 0x80
let OpCodeMask: UInt8 = 0x0F
let RSVMask: UInt8 = 0x70
let MaskMask: UInt8 = 0x80
let PayloadLenMask: UInt8 = 0x7F
let MaxFrameSize: Int = 32
class WSResponse {
var isFin = false
var code: OpCode = .ContinueFrame
var bytesLeft = 0
var frameCount = 0
var buffer: NSMutableData?
}
public weak var delegate: WebSocketDelegate?
public weak var pongDelegate: WebSocketPongDelegate?
public var onConnect: ((Void) -> Void)?
public var onDisconnect: ((NSError?) -> Void)?
public var onText: ((String) -> Void)?
public var onData: ((NSData) -> Void)?
public var onPong: ((Void) -> Void)?
public var headers = Dictionary<String,String>()
public var voipEnabled = false
public var selfSignedSSL = false
public var security: Security?
public var isConnected :Bool {
return connected
}
private var url: NSURL
private var inputStream: NSInputStream?
private var outputStream: NSOutputStream?
private var isRunLoop = false
private var connected = false
private var isCreated = false
private var writeQueue: NSOperationQueue?
private var readStack = Array<WSResponse>()
private var inputQueue = Array<NSData>()
private var fragBuffer: NSData?
private var certValidated = false
private var didDisconnect = false
//init the websocket with a url
public init(url: NSURL) {
self.url = url
}
//used for setting protocols.
public convenience init(url: NSURL, protocols: Array<String>) {
self.init(url: url)
optionalProtocols = protocols
}
///Connect to the websocket server on a background thread
public func connect() {
if isCreated {
return
}
dispatch_async(queue,{ [weak self] in
self?.didDisconnect = false
})
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), { [weak self] in
self?.isCreated = true
self?.createHTTPRequest()
self?.isCreated = false
})
}
///disconnect from the websocket server
public func disconnect() {
writeError(CloseCode.Normal.rawValue)
}
///write a string to the websocket. This sends it as a text frame.
public func writeString(str: String) {
dequeueWrite(str.dataUsingEncoding(NSUTF8StringEncoding)!, code: .TextFrame)
}
///write binary data to the websocket. This sends it as a binary frame.
public func writeData(data: NSData) {
dequeueWrite(data, code: .BinaryFrame)
}
//write a ping to the websocket. This sends it as a control frame.
//yodel a sound to the planet. This sends it as an astroid. http://youtu.be/Eu5ZJELRiJ8?t=42s
public func writePing(data: NSData) {
dequeueWrite(data, code: .Ping)
}
//private methods below!
//private method that starts the connection
private func createHTTPRequest() {
let str: NSString = url.absoluteString!
let urlRequest = CFHTTPMessageCreateRequest(kCFAllocatorDefault, "GET",
url, kCFHTTPVersion1_1).takeRetainedValue()
var port = url.port
if port == nil {
if url.scheme == "wss" || url.scheme == "https" {
port = 443
} else {
port = 80
}
}
self.addHeader(urlRequest, key: headerWSUpgradeName, val: headerWSUpgradeValue)
self.addHeader(urlRequest, key: headerWSConnectionName, val: headerWSConnectionValue)
if let protocols = optionalProtocols {
self.addHeader(urlRequest, key: headerWSProtocolName, val: ",".join(protocols))
}
self.addHeader(urlRequest, key: headerWSVersionName, val: headerWSVersionValue)
self.addHeader(urlRequest, key: headerWSKeyName, val: self.generateWebSocketKey())
self.addHeader(urlRequest, key: headerOriginName, val: url.absoluteString!)
self.addHeader(urlRequest, key: headerWSHostName, val: "\(url.host!):\(port!)")
for (key,value) in headers {
self.addHeader(urlRequest, key: key, val: value)
}
let serializedRequest: NSData = CFHTTPMessageCopySerializedMessage(urlRequest).takeRetainedValue()
self.initStreamsWithData(serializedRequest, Int(port!))
}
//Add a header to the CFHTTPMessage by using the NSString bridges to CFString
private func addHeader(urlRequest: CFHTTPMessage,key: String, val: String) {
let nsKey: NSString = key
let nsVal: NSString = val
CFHTTPMessageSetHeaderFieldValue(urlRequest,
nsKey,
nsVal)
}
//generate a websocket key as needed in rfc
private func generateWebSocketKey() -> String {
var key = ""
let seed = 16
for (var i = 0; i < seed; i++) {
let uni = UnicodeScalar(UInt32(97 + arc4random_uniform(25)))
key += "\(Character(uni))"
}
var data = key.dataUsingEncoding(NSUTF8StringEncoding)
var baseKey = data?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(0))
return baseKey!
}
//Start the stream connection and write the data to the output stream
private func initStreamsWithData(data: NSData, _ port: Int) {
//higher level API we will cut over to at some point
//NSStream.getStreamsToHostWithName(url.host, port: url.port.integerValue, inputStream: &inputStream, outputStream: &outputStream)
var readStream: Unmanaged<CFReadStream>?
var writeStream: Unmanaged<CFWriteStream>?
let h: NSString = url.host!
CFStreamCreatePairWithSocketToHost(nil, h, UInt32(port), &readStream, &writeStream)
inputStream = readStream!.takeRetainedValue()
outputStream = writeStream!.takeRetainedValue()
inputStream!.delegate = self
outputStream!.delegate = self
if url.scheme == "wss" || url.scheme == "https" {
inputStream!.setProperty(NSStreamSocketSecurityLevelNegotiatedSSL, forKey: NSStreamSocketSecurityLevelKey)
outputStream!.setProperty(NSStreamSocketSecurityLevelNegotiatedSSL, forKey: NSStreamSocketSecurityLevelKey)
} else {
certValidated = true //not a https session, so no need to check SSL pinning
}
if self.voipEnabled {
inputStream!.setProperty(NSStreamNetworkServiceTypeVoIP, forKey: NSStreamNetworkServiceType)
outputStream!.setProperty(NSStreamNetworkServiceTypeVoIP, forKey: NSStreamNetworkServiceType)
}
if self.selfSignedSSL {
let settings: Dictionary<NSObject, NSObject> = [kCFStreamSSLValidatesCertificateChain: NSNumber(bool:false), kCFStreamSSLPeerName: kCFNull]
inputStream!.setProperty(settings, forKey: kCFStreamPropertySSLSettings as! String)
outputStream!.setProperty(settings, forKey: kCFStreamPropertySSLSettings as! String)
}
isRunLoop = true
inputStream!.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
outputStream!.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
inputStream!.open()
outputStream!.open()
let bytes = UnsafePointer<UInt8>(data.bytes)
outputStream!.write(bytes, maxLength: data.length)
while(isRunLoop) {
NSRunLoop.currentRunLoop().runMode(NSDefaultRunLoopMode, beforeDate: NSDate.distantFuture() as! NSDate)
}
}
//delegate for the stream methods. Processes incoming bytes
public func stream(aStream: NSStream, handleEvent eventCode: NSStreamEvent) {
if let sec = security where !certValidated && (eventCode == .HasBytesAvailable || eventCode == .HasSpaceAvailable) {
var possibleTrust: AnyObject? = aStream.propertyForKey(kCFStreamPropertySSLPeerTrust as! String)
if let trust: AnyObject = possibleTrust {
var domain: AnyObject? = aStream.propertyForKey(kCFStreamSSLPeerName as! String)
if sec.isValid(trust as! SecTrustRef, domain: domain as! String?) {
certValidated = true
} else {
let error = self.errorWithDetail("Invalid SSL certificate", code: 1)
doDisconnect(error)
disconnectStream(error)
return
}
}
}
if eventCode == .HasBytesAvailable {
if(aStream == inputStream) {
processInputStream()
}
} else if eventCode == .ErrorOccurred {
disconnectStream(aStream.streamError)
} else if eventCode == .EndEncountered {
disconnectStream(nil)
}
}
//disconnect the stream object
private func disconnectStream(error: NSError?) {
if writeQueue != nil {
writeQueue!.waitUntilAllOperationsAreFinished()
}
if let stream = inputStream {
stream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
stream.close()
}
if let stream = outputStream {
stream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
stream.close()
}
outputStream = nil
isRunLoop = false
certValidated = false
self.doDisconnect(error)
connected = false
}
///handles the incoming bytes and sending them to the proper processing method
private func processInputStream() {
let buf = NSMutableData(capacity: BUFFER_MAX)
var buffer = UnsafeMutablePointer<UInt8>(buf!.bytes)
let length = inputStream!.read(buffer, maxLength: BUFFER_MAX)
if length > 0 {
if !connected {
let status = processHTTP(buffer, bufferLen: length)
if !status {
doDisconnect(self.errorWithDetail("Invalid HTTP upgrade", code: 1))
}
} else {
var process = false
if inputQueue.count == 0 {
process = true
}
inputQueue.append(NSData(bytes: buffer, length: length))
if process {
dequeueInput()
}
}
}
}
///dequeue the incoming input so it is processed in order
private func dequeueInput() {
if inputQueue.count > 0 {
let data = inputQueue[0]
var work = data
if (fragBuffer != nil) {
var combine = NSMutableData(data: fragBuffer!)
combine.appendData(data)
work = combine
fragBuffer = nil
}
let buffer = UnsafePointer<UInt8>(work.bytes)
processRawMessage(buffer, bufferLen: work.length)
inputQueue = inputQueue.filter{$0 != data}
dequeueInput()
}
}
///Finds the HTTP Packet in the TCP stream, by looking for the CRLF.
private func processHTTP(buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Bool {
let CRLFBytes = [UInt8(ascii: "\r"), UInt8(ascii: "\n"), UInt8(ascii: "\r"), UInt8(ascii: "\n")]
var k = 0
var totalSize = 0
for var i = 0; i < bufferLen; i++ {
if buffer[i] == CRLFBytes[k] {
k++
if k == 3 {
totalSize = i + 1
break
}
} else {
k = 0
}
}
if totalSize > 0 {
if validateResponse(buffer, bufferLen: totalSize) {
dispatch_async(queue,{ [weak self] in
self?.connected = true
if let connectBlock = self?.onConnect {
connectBlock()
}
if let s = self {
s.delegate?.websocketDidConnect(s)
}
})
totalSize += 1 //skip the last \n
let restSize = bufferLen - totalSize
if restSize > 0 {
processRawMessage((buffer+totalSize),bufferLen: restSize)
}
return true
}
}
return false
}
///validates the HTTP is a 101 as per the RFC spec
private func validateResponse(buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Bool {
let response = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, 0).takeRetainedValue()
CFHTTPMessageAppendBytes(response, buffer, bufferLen)
if CFHTTPMessageGetResponseStatusCode(response) != 101 {
return false
}
let cfHeaders = CFHTTPMessageCopyAllHeaderFields(response)
let headers: NSDictionary = cfHeaders.takeRetainedValue()
let acceptKey = headers[headerWSAcceptName] as! NSString
if acceptKey.length > 0 {
return true
}
return false
}
///process the websocket data
private func processRawMessage(buffer: UnsafePointer<UInt8>, bufferLen: Int) {
var response = readStack.last
if response != nil && bufferLen < 2 {
fragBuffer = NSData(bytes: buffer, length: bufferLen)
return
}
if response != nil && response!.bytesLeft > 0 {
let resp = response!
var len = resp.bytesLeft
var extra = bufferLen - resp.bytesLeft
if resp.bytesLeft > bufferLen {
len = bufferLen
extra = 0
}
resp.bytesLeft -= len
resp.buffer?.appendData(NSData(bytes: buffer, length: len))
processResponse(resp)
var offset = bufferLen - extra
if extra > 0 {
processExtra((buffer+offset), bufferLen: extra)
}
return
} else {
let isFin = (FinMask & buffer[0])
let receivedOpcode = (OpCodeMask & buffer[0])
let isMasked = (MaskMask & buffer[1])
let payloadLen = (PayloadLenMask & buffer[1])
var offset = 2
if((isMasked > 0 || (RSVMask & buffer[0]) > 0) && receivedOpcode != OpCode.Pong.rawValue) {
let errCode = CloseCode.ProtocolError.rawValue
let error = self.errorWithDetail("masked and rsv data is not currently supported", code: errCode)
self.doDisconnect(error)
writeError(errCode)
return
}
let isControlFrame = (receivedOpcode == OpCode.ConnectionClose.rawValue || receivedOpcode == OpCode.Ping.rawValue)
if !isControlFrame && (receivedOpcode != OpCode.BinaryFrame.rawValue && receivedOpcode != OpCode.ContinueFrame.rawValue &&
receivedOpcode != OpCode.TextFrame.rawValue && receivedOpcode != OpCode.Pong.rawValue) {
let errCode = CloseCode.ProtocolError.rawValue
let error = self.errorWithDetail("unknown opcode: \(receivedOpcode)", code: errCode)
self.doDisconnect(error)
writeError(errCode)
return
}
if isControlFrame && isFin == 0 {
let errCode = CloseCode.ProtocolError.rawValue
let error = self.errorWithDetail("control frames can't be fragmented", code: errCode)
self.doDisconnect(error)
writeError(errCode)
return
}
if receivedOpcode == OpCode.ConnectionClose.rawValue {
var code = CloseCode.Normal.rawValue
if payloadLen == 1 {
code = CloseCode.ProtocolError.rawValue
} else if payloadLen > 1 {
var codeBuffer = UnsafePointer<UInt16>((buffer+offset))
code = codeBuffer[0].bigEndian
if code < 1000 || (code > 1003 && code < 1007) || (code > 1011 && code < 3000) {
code = CloseCode.ProtocolError.rawValue
}
offset += 2
}
if payloadLen > 2 {
let len = Int(payloadLen-2)
if len > 0 {
let bytes = UnsafePointer<UInt8>((buffer+offset))
var str: NSString? = NSString(data: NSData(bytes: bytes, length: len), encoding: NSUTF8StringEncoding)
if str == nil {
code = CloseCode.ProtocolError.rawValue
}
}
}
let error = self.errorWithDetail("connection closed by server", code: code)
self.doDisconnect(error)
writeError(code)
return
}
if isControlFrame && payloadLen > 125 {
writeError(CloseCode.ProtocolError.rawValue)
return
}
var dataLength = UInt64(payloadLen)
if dataLength == 127 {
let bytes = UnsafePointer<UInt64>((buffer+offset))
dataLength = bytes[0].bigEndian
offset += sizeof(UInt64)
} else if dataLength == 126 {
let bytes = UnsafePointer<UInt16>((buffer+offset))
dataLength = UInt64(bytes[0].bigEndian)
offset += sizeof(UInt16)
}
if bufferLen < offset || UInt64(bufferLen - offset) < dataLength {
fragBuffer = NSData(bytes: buffer, length: bufferLen)
return
}
var len = dataLength
if dataLength > UInt64(bufferLen) {
len = UInt64(bufferLen-offset)
}
var data: NSData!
if len < 0 {
len = 0
data = NSData()
} else {
data = NSData(bytes: UnsafePointer<UInt8>((buffer+offset)), length: Int(len))
}
if receivedOpcode == OpCode.Pong.rawValue {
dispatch_async(queue,{ [weak self] in
if let pongBlock = self?.onPong {
pongBlock()
}
if let s = self {
s.pongDelegate?.websocketDidReceivePong(s)
}
})
let step = Int(offset+numericCast(len))
let extra = bufferLen-step
if extra > 0 {
processRawMessage((buffer+step), bufferLen: extra)
}
return
}
var response = readStack.last
if isControlFrame {
response = nil //don't append pings
}
if isFin == 0 && receivedOpcode == OpCode.ContinueFrame.rawValue && response == nil {
let errCode = CloseCode.ProtocolError.rawValue
let error = self.errorWithDetail("continue frame before a binary or text frame", code: errCode)
self.doDisconnect(error)
writeError(errCode)
return
}
var isNew = false
if(response == nil) {
if receivedOpcode == OpCode.ContinueFrame.rawValue {
let errCode = CloseCode.ProtocolError.rawValue
let error = self.errorWithDetail("first frame can't be a continue frame",
code: errCode)
self.doDisconnect(error)
writeError(errCode)
return
}
isNew = true
response = WSResponse()
response!.code = OpCode(rawValue: receivedOpcode)!
response!.bytesLeft = Int(dataLength)
response!.buffer = NSMutableData(data: data)
} else {
if receivedOpcode == OpCode.ContinueFrame.rawValue {
response!.bytesLeft = Int(dataLength)
} else {
let errCode = CloseCode.ProtocolError.rawValue
let error = self.errorWithDetail("second and beyond of fragment message must be a continue frame",
code: errCode)
self.doDisconnect(error)
writeError(errCode)
return
}
response!.buffer!.appendData(data)
}
if response != nil {
response!.bytesLeft -= Int(len)
response!.frameCount++
response!.isFin = isFin > 0 ? true : false
if(isNew) {
readStack.append(response!)
}
processResponse(response!)
}
let step = Int(offset+numericCast(len))
let extra = bufferLen-step
if(extra > 0) {
processExtra((buffer+step), bufferLen: extra)
}
}
}
///process the extra of a buffer
private func processExtra(buffer: UnsafePointer<UInt8>, bufferLen: Int) {
if bufferLen < 2 {
fragBuffer = NSData(bytes: buffer, length: bufferLen)
} else {
processRawMessage(buffer, bufferLen: bufferLen)
}
}
///process the finished response of a buffer
private func processResponse(response: WSResponse) -> Bool {
if response.isFin && response.bytesLeft <= 0 {
if response.code == .Ping {
let data = response.buffer! //local copy so it is perverse for writing
dequeueWrite(data, code: OpCode.Pong)
} else if response.code == .TextFrame {
var str: NSString? = NSString(data: response.buffer!, encoding: NSUTF8StringEncoding)
if str == nil {
writeError(CloseCode.Encoding.rawValue)
return false
}
dispatch_async(queue,{ [weak self] in
if let textBlock = self?.onText {
textBlock(str! as! String)
}
if let s = self {
s.delegate?.websocketDidReceiveMessage(s, text: str! as! String)
}
})
} else if response.code == .BinaryFrame {
let data = response.buffer! //local copy so it is perverse for writing
dispatch_async(queue,{ [weak self] in
if let dataBlock = self?.onData {
dataBlock(data)
}
if let s = self {
s.delegate?.websocketDidReceiveData(s, data: data)
}
})
}
readStack.removeLast()
return true
}
return false
}
///Create an error
private func errorWithDetail(detail: String, code: UInt16) -> NSError {
var details = Dictionary<String,String>()
details[NSLocalizedDescriptionKey] = detail
return NSError(domain: "Websocket", code: Int(code), userInfo: details)
}
///write a an error to the socket
private func writeError(code: UInt16) {
let buf = NSMutableData(capacity: sizeof(UInt16))
var buffer = UnsafeMutablePointer<UInt16>(buf!.bytes)
buffer[0] = code.bigEndian
dequeueWrite(NSData(bytes: buffer, length: sizeof(UInt16)), code: .ConnectionClose)
}
///used to write things to the stream
private func dequeueWrite(data: NSData, code: OpCode) {
if writeQueue == nil {
writeQueue = NSOperationQueue()
writeQueue!.maxConcurrentOperationCount = 1
}
writeQueue!.addOperationWithBlock { [unowned self] in
//stream isn't ready, let's wait
var tries = 0;
while self.outputStream == nil || !self.connected {
if(tries < 5) {
sleep(1);
} else {
break;
}
tries++;
}
if !self.connected {
return
}
var offset = 2
let bytes = UnsafeMutablePointer<UInt8>(data.bytes)
let dataLength = data.length
let frame = NSMutableData(capacity: dataLength + self.MaxFrameSize)
let buffer = UnsafeMutablePointer<UInt8>(frame!.mutableBytes)
buffer[0] = self.FinMask | code.rawValue
if dataLength < 126 {
buffer[1] = CUnsignedChar(dataLength)
} else if dataLength <= Int(UInt16.max) {
buffer[1] = 126
var sizeBuffer = UnsafeMutablePointer<UInt16>((buffer+offset))
sizeBuffer[0] = UInt16(dataLength).bigEndian
offset += sizeof(UInt16)
} else {
buffer[1] = 127
var sizeBuffer = UnsafeMutablePointer<UInt64>((buffer+offset))
sizeBuffer[0] = UInt64(dataLength).bigEndian
offset += sizeof(UInt64)
}
buffer[1] |= self.MaskMask
var maskKey = UnsafeMutablePointer<UInt8>(buffer + offset)
SecRandomCopyBytes(kSecRandomDefault, Int(sizeof(UInt32)), maskKey)
offset += sizeof(UInt32)
for (var i = 0; i < dataLength; i++) {
buffer[offset] = bytes[i] ^ maskKey[i % sizeof(UInt32)]
offset += 1
}
var total = 0
while true {
if self.outputStream == nil {
break
}
let writeBuffer = UnsafePointer<UInt8>(frame!.bytes+total)
var len = self.outputStream?.write(writeBuffer, maxLength: offset-total)
if len == nil || len! < 0 {
var error: NSError?
if let streamError = self.outputStream?.streamError {
error = streamError
} else {
let errCode = InternalErrorCode.OutputStreamWriteError.rawValue
error = self.errorWithDetail("output stream error during write", code: errCode)
}
self.doDisconnect(error)
break
} else {
total += len!
}
if total >= offset {
break
}
}
}
}
///used to preform the disconnect delegate
private func doDisconnect(error: NSError?) {
if !self.didDisconnect {
dispatch_async(queue,{ [weak self] in
self?.didDisconnect = true
if let disconnect = self?.onDisconnect {
disconnect(error)
}
if let s = self {
s.delegate?.websocketDidDisconnect(s, error: error)
}
})
}
}
}
@@ -3,7 +3,7 @@
archiveVersion = 1;
classes = {
};
objectVersion = 46;
objectVersion = 53;
objects = {
/* Begin PBXBuildFile section */
@@ -12,18 +12,11 @@
5C178E271B62D0B900A97204 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 5C178E251B62D0B900A97204 /* Main.storyboard */; };
5C178E291B62D0B900A97204 /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 5C178E281B62D0B900A97204 /* Images.xcassets */; };
5C178E2C1B62D0B900A97204 /* LaunchScreen.xib in Resources */ = {isa = PBXBuildFile; fileRef = 5C178E2A1B62D0B900A97204 /* LaunchScreen.xib */; };
5C178E381B62D0B900A97204 /* AutobahnTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5C178E371B62D0B900A97204 /* AutobahnTests.swift */; };
5C178E521B62D11200A97204 /* Starscream.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 5C178E491B62D0EF00A97204 /* Starscream.framework */; };
5CF1D07222552B770081C8A8 /* Starscream.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 5C178E491B62D0EF00A97204 /* Starscream.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
5C178E321B62D0B900A97204 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 5C178E141B62D0B900A97204 /* Project object */;
proxyType = 1;
remoteGlobalIDString = 5C178E1B1B62D0B900A97204;
remoteInfo = Autobahn;
};
5C178E481B62D0EF00A97204 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 5C178E411B62D0EF00A97204 /* Starscream.xcodeproj */;
@@ -31,36 +24,43 @@
remoteGlobalIDString = 6B3E79E619D48B7F006071F7;
remoteInfo = Starscream;
};
5C178E4A1B62D0EF00A97204 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 5C178E411B62D0EF00A97204 /* Starscream.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 6B3E79F119D48B7F006071F7;
remoteInfo = StarscreamTests;
};
5C178E4C1B62D0EF00A97204 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 5C178E411B62D0EF00A97204 /* Starscream.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = D9C3E35F19E48FF1009FC285;
remoteInfo = StarscreamOSX;
};
5C178E4E1B62D0EF00A97204 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 5C178E411B62D0EF00A97204 /* Starscream.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = D9C3E36919E48FF1009FC285;
remoteInfo = StarscreamOSXTests;
};
5C178E501B62D10A00A97204 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 5C178E411B62D0EF00A97204 /* Starscream.xcodeproj */;
proxyType = 1;
remoteGlobalIDString = 6B3E79E519D48B7F006071F7;
remoteGlobalIDString = 33CCF0841F5DDC030099B092;
remoteInfo = Starscream;
};
5CF1D06B22552AA30081C8A8 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 5C178E411B62D0EF00A97204 /* Starscream.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 335FA2021F5DF71D00F6D2EC;
remoteInfo = "Starscream Tests";
};
5CF1D07322552B770081C8A8 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 5C178E411B62D0EF00A97204 /* Starscream.xcodeproj */;
proxyType = 1;
remoteGlobalIDString = 33CCF0841F5DDC030099B092;
remoteInfo = Starscream;
};
/* End PBXContainerItemProxy section */
/* Begin PBXCopyFilesBuildPhase section */
5CF1D07522552B770081C8A8 /* Embed Frameworks */ = {
isa = PBXCopyFilesBuildPhase;
buildActionMask = 2147483647;
dstPath = "";
dstSubfolderSpec = 10;
files = (
5CF1D07222552B770081C8A8 /* Starscream.framework in Embed Frameworks */,
);
name = "Embed Frameworks";
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */
5C178E1C1B62D0B900A97204 /* Autobahn.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Autobahn.app; sourceTree = BUILT_PRODUCTS_DIR; };
5C178E201B62D0B900A97204 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
@@ -69,9 +69,6 @@
5C178E261B62D0B900A97204 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = "<group>"; };
5C178E281B62D0B900A97204 /* Images.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Images.xcassets; sourceTree = "<group>"; };
5C178E2B1B62D0B900A97204 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/LaunchScreen.xib; sourceTree = "<group>"; };
5C178E311B62D0B900A97204 /* AutobahnTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = AutobahnTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
5C178E361B62D0B900A97204 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
5C178E371B62D0B900A97204 /* AutobahnTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AutobahnTests.swift; sourceTree = "<group>"; };
5C178E411B62D0EF00A97204 /* Starscream.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = Starscream.xcodeproj; path = ../../Starscream.xcodeproj; sourceTree = "<group>"; };
/* End PBXFileReference section */
@@ -84,13 +81,6 @@
);
runOnlyForDeploymentPostprocessing = 0;
};
5C178E2E1B62D0B900A97204 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
@@ -98,7 +88,6 @@
isa = PBXGroup;
children = (
5C178E1E1B62D0B900A97204 /* Autobahn */,
5C178E341B62D0B900A97204 /* AutobahnTests */,
5C178E1D1B62D0B900A97204 /* Products */,
5C178E411B62D0EF00A97204 /* Starscream.xcodeproj */,
);
@@ -108,7 +97,6 @@
isa = PBXGroup;
children = (
5C178E1C1B62D0B900A97204 /* Autobahn.app */,
5C178E311B62D0B900A97204 /* AutobahnTests.xctest */,
);
name = Products;
sourceTree = "<group>";
@@ -134,30 +122,11 @@
name = "Supporting Files";
sourceTree = "<group>";
};
5C178E341B62D0B900A97204 /* AutobahnTests */ = {
isa = PBXGroup;
children = (
5C178E371B62D0B900A97204 /* AutobahnTests.swift */,
5C178E351B62D0B900A97204 /* Supporting Files */,
);
path = AutobahnTests;
sourceTree = "<group>";
};
5C178E351B62D0B900A97204 /* Supporting Files */ = {
isa = PBXGroup;
children = (
5C178E361B62D0B900A97204 /* Info.plist */,
);
name = "Supporting Files";
sourceTree = "<group>";
};
5C178E421B62D0EF00A97204 /* Products */ = {
isa = PBXGroup;
children = (
5C178E491B62D0EF00A97204 /* Starscream.framework */,
5C178E4B1B62D0EF00A97204 /* StarscreamTests.xctest */,
5C178E4D1B62D0EF00A97204 /* Starscream.framework */,
5C178E4F1B62D0EF00A97204 /* StarscreamOSXTests.xctest */,
5CF1D06C22552AA30081C8A8 /* Starscream Tests.xctest */,
);
name = Products;
sourceTree = "<group>";
@@ -172,56 +141,40 @@
5C178E181B62D0B900A97204 /* Sources */,
5C178E191B62D0B900A97204 /* Frameworks */,
5C178E1A1B62D0B900A97204 /* Resources */,
5CF1D07522552B770081C8A8 /* Embed Frameworks */,
);
buildRules = (
);
dependencies = (
5C178E511B62D10A00A97204 /* PBXTargetDependency */,
5CF1D07422552B770081C8A8 /* PBXTargetDependency */,
);
name = Autobahn;
productName = Autobahn;
productReference = 5C178E1C1B62D0B900A97204 /* Autobahn.app */;
productType = "com.apple.product-type.application";
};
5C178E301B62D0B900A97204 /* AutobahnTests */ = {
isa = PBXNativeTarget;
buildConfigurationList = 5C178E3E1B62D0B900A97204 /* Build configuration list for PBXNativeTarget "AutobahnTests" */;
buildPhases = (
5C178E2D1B62D0B900A97204 /* Sources */,
5C178E2E1B62D0B900A97204 /* Frameworks */,
5C178E2F1B62D0B900A97204 /* Resources */,
);
buildRules = (
);
dependencies = (
5C178E331B62D0B900A97204 /* PBXTargetDependency */,
);
name = AutobahnTests;
productName = AutobahnTests;
productReference = 5C178E311B62D0B900A97204 /* AutobahnTests.xctest */;
productType = "com.apple.product-type.bundle.unit-test";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
5C178E141B62D0B900A97204 /* Project object */ = {
isa = PBXProject;
attributes = {
LastUpgradeCheck = 0640;
BuildIndependentTargetsInParallel = YES;
LastSwiftMigration = 0700;
LastSwiftUpdateCheck = 0700;
LastUpgradeCheck = 1430;
ORGANIZATIONNAME = vluxe;
TargetAttributes = {
5C178E1B1B62D0B900A97204 = {
CreatedOnToolsVersion = 6.4;
};
5C178E301B62D0B900A97204 = {
CreatedOnToolsVersion = 6.4;
TestTargetID = 5C178E1B1B62D0B900A97204;
LastSwiftMigration = 0800;
};
};
};
buildConfigurationList = 5C178E171B62D0B900A97204 /* Build configuration list for PBXProject "Autobahn" */;
compatibilityVersion = "Xcode 3.2";
developmentRegion = English;
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
@@ -239,7 +192,6 @@
projectRoot = "";
targets = (
5C178E1B1B62D0B900A97204 /* Autobahn */,
5C178E301B62D0B900A97204 /* AutobahnTests */,
);
};
/* End PBXProject section */
@@ -252,25 +204,11 @@
remoteRef = 5C178E481B62D0EF00A97204 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
5C178E4B1B62D0EF00A97204 /* StarscreamTests.xctest */ = {
5CF1D06C22552AA30081C8A8 /* Starscream Tests.xctest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = StarscreamTests.xctest;
remoteRef = 5C178E4A1B62D0EF00A97204 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
5C178E4D1B62D0EF00A97204 /* Starscream.framework */ = {
isa = PBXReferenceProxy;
fileType = wrapper.framework;
path = Starscream.framework;
remoteRef = 5C178E4C1B62D0EF00A97204 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
5C178E4F1B62D0EF00A97204 /* StarscreamOSXTests.xctest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = StarscreamOSXTests.xctest;
remoteRef = 5C178E4E1B62D0EF00A97204 /* PBXContainerItemProxy */;
path = "Starscream Tests.xctest";
remoteRef = 5CF1D06B22552AA30081C8A8 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
/* End PBXReferenceProxy section */
@@ -286,13 +224,6 @@
);
runOnlyForDeploymentPostprocessing = 0;
};
5C178E2F1B62D0B900A97204 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
@@ -305,27 +236,19 @@
);
runOnlyForDeploymentPostprocessing = 0;
};
5C178E2D1B62D0B900A97204 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
5C178E381B62D0B900A97204 /* AutobahnTests.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
5C178E331B62D0B900A97204 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = 5C178E1B1B62D0B900A97204 /* Autobahn */;
targetProxy = 5C178E321B62D0B900A97204 /* PBXContainerItemProxy */;
};
5C178E511B62D10A00A97204 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
name = Starscream;
targetProxy = 5C178E501B62D10A00A97204 /* PBXContainerItemProxy */;
};
5CF1D07422552B770081C8A8 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
name = Starscream;
targetProxy = 5CF1D07322552B770081C8A8 /* PBXContainerItemProxy */;
};
/* End PBXTargetDependency section */
/* Begin PBXVariantGroup section */
@@ -352,23 +275,36 @@
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
@@ -384,7 +320,7 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 8.4;
IPHONEOS_DEPLOYMENT_TARGET = 12.0;
MTL_ENABLE_DEBUG_INFO = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
@@ -397,17 +333,29 @@
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
@@ -423,9 +371,10 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 8.4;
IPHONEOS_DEPLOYMENT_TARGET = 12.0;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = iphoneos;
SWIFT_COMPILATION_MODE = wholemodule;
TARGETED_DEVICE_FAMILY = "1,2";
VALIDATE_PRODUCT = YES;
};
@@ -434,54 +383,36 @@
5C178E3C1B62D0B900A97204 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO;
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
DEVELOPMENT_TEAM = "";
INFOPLIST_FILE = Autobahn/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
IPHONEOS_DEPLOYMENT_TARGET = 12.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = "com.vluxe.$(PRODUCT_NAME:rfc1034identifier)";
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
};
name = Debug;
};
5C178E3D1B62D0B900A97204 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO;
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
DEVELOPMENT_TEAM = "";
INFOPLIST_FILE = Autobahn/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
PRODUCT_NAME = "$(TARGET_NAME)";
};
name = Release;
};
5C178E3F1B62D0B900A97204 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
FRAMEWORK_SEARCH_PATHS = (
"$(SDKROOT)/Developer/Library/Frameworks",
IPHONEOS_DEPLOYMENT_TARGET = 12.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
INFOPLIST_FILE = AutobahnTests/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = "com.vluxe.$(PRODUCT_NAME:rfc1034identifier)";
PRODUCT_NAME = "$(TARGET_NAME)";
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Autobahn.app/Autobahn";
};
name = Debug;
};
5C178E401B62D0B900A97204 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
FRAMEWORK_SEARCH_PATHS = (
"$(SDKROOT)/Developer/Library/Frameworks",
"$(inherited)",
);
INFOPLIST_FILE = AutobahnTests/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
PRODUCT_NAME = "$(TARGET_NAME)";
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Autobahn.app/Autobahn";
SWIFT_VERSION = 5.0;
};
name = Release;
};
@@ -506,15 +437,6 @@
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
5C178E3E1B62D0B900A97204 /* Build configuration list for PBXNativeTarget "AutobahnTests" */ = {
isa = XCConfigurationList;
buildConfigurations = (
5C178E3F1B62D0B900A97204 /* Debug */,
5C178E401B62D0B900A97204 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = 5C178E141B62D0B900A97204 /* Project object */;
@@ -14,30 +14,30 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
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) {
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) {
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) {
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) {
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
@@ -1,13 +1,14 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="6211" systemVersion="14A298i" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" initialViewController="BYZ-38-t0r">
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="9531" systemVersion="15C50" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" initialViewController="BYZ-38-t0r">
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="6204"/>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="9529"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="tne-QT-ifu">
<objects>
<viewController id="BYZ-38-t0r" customClass="ViewController" customModuleProvider="target" sceneMemberID="viewController">
<viewController id="BYZ-38-t0r" customClass="ViewController" customModule="Autobahn" customModuleProvider="target" sceneMemberID="viewController">
<layoutGuides>
<viewControllerLayoutGuide type="top" id="y3c-jy-aDJ"/>
<viewControllerLayoutGuide type="bottom" id="wfy-db-euE"/>
@@ -1,5 +1,15 @@
{
"images" : [
{
"idiom" : "iphone",
"size" : "20x20",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "20x20",
"scale" : "3x"
},
{
"idiom" : "iphone",
"size" : "29x29",
@@ -30,6 +40,16 @@
"size" : "60x60",
"scale" : "3x"
},
{
"idiom" : "ipad",
"size" : "20x20",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "20x20",
"scale" : "2x"
},
{
"idiom" : "ipad",
"size" : "29x29",
@@ -59,6 +79,16 @@
"idiom" : "ipad",
"size" : "76x76",
"scale" : "2x"
},
{
"idiom" : "ipad",
"size" : "83.5x83.5",
"scale" : "2x"
},
{
"idiom" : "ios-marketing",
"size" : "1024x1024",
"scale" : "1x"
}
],
"info" : {
+1 -1
View File
@@ -7,7 +7,7 @@
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>com.vluxe.$(PRODUCT_NAME:rfc1034identifier)</string>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
@@ -11,127 +11,174 @@ import Starscream
class ViewController: UIViewController {
static let host = "localhost:9001"
static let scheme = "ws"
var socket = WebSocket(url: NSURL(scheme: scheme, host: host, path: "/getCaseCount")!, protocols: [])
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() {
socket.onText = {(text: String) in
if let c = text.toInt() {
println("number of cases is: \(c)")
self.caseCount = c
}
}
socket.onDisconnect = {(error: NSError?) in
self.getTestInfo(1)
}
socket.connect()
}
func getTestInfo(caseNum: Int) {
socket = createSocket("getCaseInfo",caseNum)
socket.onText = {(text: String) in
var error: NSError?
let data = text.dataUsingEncoding(NSUTF8StringEncoding)
var resp: AnyObject? = NSJSONSerialization.JSONObjectWithData(data!,
options: NSJSONReadingOptions(), error: &error)
if let dict = resp as? Dictionary<String,String> {
let num = dict["id"]
let summary = dict["description"]
if let n = num, let sum = summary {
//println("running case:\(caseNum) id:\(n) summary: \(sum)")
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
}
}
var once = false
socket.onDisconnect = {(error: NSError?) in
if !once {
once = true
self.runTest(caseNum)
}
}
socket.connect()
s.connect()
}
func runTest(caseNum: Int) {
socket = createSocket("runCase",caseNum)
socket.onText = {(text: String) in
self.socket.writeString(text)
}
socket.onData = {(data: NSData) in
self.socket.writeData(data)
}
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<String,String> {
// 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
socket.onDisconnect = {(error: NSError?) in
if !once {
once = true
println("case:\(caseNum) finished")
self.verifyTest(caseNum)
s.onEvent = { [weak self] event in
switch event {
case .disconnected(_, _), .error(_):
if !once {
once = true
self?.runTest(caseNum)
}
self?.removeSocket(s)
default:
break
}
}
socket.connect()
s.connect()
}
func verifyTest(caseNum: Int) {
socket = createSocket("getCaseStatus",caseNum)
socket.onText = {(text: String) in
var error: NSError?
let data = text.dataUsingEncoding(NSUTF8StringEncoding)
var resp: AnyObject? = NSJSONSerialization.JSONObjectWithData(data!,
options: NSJSONReadingOptions(), error: &error)
if let dict = resp as? Dictionary<String,String> {
if let status = dict["behavior"] {
if status == "OK" {
println("SUCCESS: \(caseNum)")
return
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)
}
println("FAILURE: \(caseNum)")
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
}
}
var once = false
socket.onDisconnect = {(error: NSError?) in
if !once {
once = true
let nextCase = caseNum+1
if nextCase <= self.caseCount {
self.getTestInfo(nextCase)
} else {
self.finishReports()
}
}
}
socket.connect()
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<String,String> {
// 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() {
socket = createSocket("updateReports",0)
socket.onDisconnect = {(error: NSError?) in
println("finished all the tests!")
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
}
}
socket.connect()
s.connect()
}
func createSocket(cmd: String, _ caseNum: Int) -> WebSocket {
return WebSocket(url: NSURL(scheme: ViewController.scheme,
host: ViewController.host, path: buildPath(cmd,caseNum))!, protocols: [])
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 {
func buildPath(_ cmd: String, _ caseNum: Int) -> String {
return "/\(cmd)?case=\(caseNum)&agent=Starscream"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
@@ -1,36 +0,0 @@
//
// AutobahnTests.swift
// AutobahnTests
//
// Created by Dalton Cherry on 7/24/15.
// Copyright (c) 2015 vluxe. All rights reserved.
//
import UIKit
import XCTest
class AutobahnTests: 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.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
@@ -1,24 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>com.vluxe.$(PRODUCT_NAME:rfc1034identifier)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>BNDL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1</string>
</dict>
</plist>
@@ -20,23 +20,9 @@
isa = PBXContainerItemProxy;
containerPortal = 6B3E7A0819D48D00006071F7 /* Starscream.xcodeproj */;
proxyType = 1;
remoteGlobalIDString = 6B3E79E519D48B7F006071F7;
remoteGlobalIDString = 33CCF0841F5DDC030099B092;
remoteInfo = Starscream;
};
5C06AE8A1B08044600D41060 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 6B3E7A0819D48D00006071F7 /* Starscream.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = D9C3E35F19E48FF1009FC285;
remoteInfo = StarscreamOSX;
};
5C06AE8C1B08044600D41060 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 6B3E7A0819D48D00006071F7 /* Starscream.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = D9C3E36919E48FF1009FC285;
remoteInfo = StarscreamOSXTests;
};
6B3E7A0D19D48D00006071F7 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 6B3E7A0819D48D00006071F7 /* Starscream.xcodeproj */;
@@ -44,12 +30,12 @@
remoteGlobalIDString = 6B3E79E619D48B7F006071F7;
remoteInfo = Starscream;
};
6B3E7A0F19D48D00006071F7 /* PBXContainerItemProxy */ = {
8AF56D58224A80460020CD2F /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 6B3E7A0819D48D00006071F7 /* Starscream.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 6B3E79F119D48B7F006071F7;
remoteInfo = StarscreamTests;
remoteGlobalIDString = 335FA2021F5DF71D00F6D2EC;
remoteInfo = "Starscream Tests";
};
/* End PBXContainerItemProxy section */
@@ -129,9 +115,7 @@
isa = PBXGroup;
children = (
6B3E7A0E19D48D00006071F7 /* Starscream.framework */,
6B3E7A1019D48D00006071F7 /* StarscreamTests.xctest */,
5C06AE8B1B08044600D41060 /* Starscream.framework */,
5C06AE8D1B08044600D41060 /* StarscreamOSXTests.xctest */,
8AF56D59224A80460020CD2F /* Starscream Tests.xctest */,
);
name = Products;
sourceTree = "<group>";
@@ -165,17 +149,18 @@
isa = PBXProject;
attributes = {
LastSwiftUpdateCheck = 0700;
LastUpgradeCheck = 0600;
LastUpgradeCheck = 1020;
ORGANIZATIONNAME = vluxe;
TargetAttributes = {
5C765ADA199A6DAA003D9110 = {
CreatedOnToolsVersion = 6.0;
LastSwiftMigration = 0800;
};
};
};
buildConfigurationList = 5C765AD6199A6DAA003D9110 /* Build configuration list for PBXProject "SimpleTest" */;
compatibilityVersion = "Xcode 3.2";
developmentRegion = English;
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
@@ -198,20 +183,6 @@
/* End PBXProject section */
/* Begin PBXReferenceProxy section */
5C06AE8B1B08044600D41060 /* Starscream.framework */ = {
isa = PBXReferenceProxy;
fileType = wrapper.framework;
path = Starscream.framework;
remoteRef = 5C06AE8A1B08044600D41060 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
5C06AE8D1B08044600D41060 /* StarscreamOSXTests.xctest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = StarscreamOSXTests.xctest;
remoteRef = 5C06AE8C1B08044600D41060 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
6B3E7A0E19D48D00006071F7 /* Starscream.framework */ = {
isa = PBXReferenceProxy;
fileType = wrapper.framework;
@@ -219,11 +190,11 @@
remoteRef = 6B3E7A0D19D48D00006071F7 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
6B3E7A1019D48D00006071F7 /* StarscreamTests.xctest */ = {
8AF56D59224A80460020CD2F /* Starscream Tests.xctest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = StarscreamTests.xctest;
remoteRef = 6B3E7A0F19D48D00006071F7 /* PBXContainerItemProxy */;
path = "Starscream Tests.xctest";
remoteRef = 8AF56D58224A80460020CD2F /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
/* End PBXReferenceProxy section */
@@ -276,24 +247,37 @@
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
COPY_PHASE_STRIP = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
@@ -319,17 +303,28 @@
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
@@ -337,6 +332,7 @@
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
@@ -346,6 +342,7 @@
IPHONEOS_DEPLOYMENT_TARGET = 8.0;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = iphoneos;
SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
TARGETED_DEVICE_FAMILY = "1,2";
VALIDATE_PRODUCT = YES;
};
@@ -357,8 +354,11 @@
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME = LaunchImage;
INFOPLIST_FILE = SimpleTest/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 12.0;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = "com.vluxe.io.$(PRODUCT_NAME:rfc1034identifier)";
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
};
name = Debug;
};
@@ -368,8 +368,11 @@
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME = LaunchImage;
INFOPLIST_FILE = SimpleTest/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 12.0;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = "com.vluxe.io.$(PRODUCT_NAME:rfc1034identifier)";
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
};
name = Release;
};
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0600"
LastUpgradeVersion = "0900"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -37,10 +37,11 @@
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
buildConfiguration = "Debug">
language = ""
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
skipped = "NO">
@@ -62,17 +63,22 @@
ReferencedContainer = "container:SimpleTest.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
language = ""
launchStyle = "0"
useCustomWorkingDirectory = "NO"
buildConfiguration = "Debug"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<BuildableProductRunnable>
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "5C765ADA199A6DAA003D9110"
@@ -81,16 +87,24 @@
ReferencedContainer = "container:SimpleTest.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
<EnvironmentVariables>
<EnvironmentVariable
key = "OS_ACTIVITY_MODE"
value = "disable"
isEnabled = "YES">
</EnvironmentVariable>
</EnvironmentVariables>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
buildConfiguration = "Release"
debugDocumentVersioning = "YES">
<BuildableProductRunnable>
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "5C765ADA199A6DAA003D9110"
@@ -1,10 +1,24 @@
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// AppDelegate.swift
// SimpleTest
//
// Created by Dalton Cherry on 8/12/14.
// Copyright (c) 2014 vluxe. All rights reserved.
// 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
@@ -14,30 +28,30 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
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) {
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) {
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) {
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) {
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
+6 -1
View File
@@ -7,7 +7,7 @@
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>com.vluxe.io.$(PRODUCT_NAME:rfc1034identifier)</string>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
@@ -22,6 +22,11 @@
<string>1</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
<key>UIMainStoryboardFile</key>
<string>Main</string>
<key>UIRequiredDeviceCapabilities</key>
@@ -1,55 +1,94 @@
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// ViewController.swift
// SimpleTest
//
// Created by Dalton Cherry on 8/12/14.
// Copyright (c) 2014 vluxe. All rights reserved.
// 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(url: NSURL(scheme: "ws", host: "localhost:8080", path: "/")!, protocols: ["chat", "superchat"])
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: Websocket Delegate Methods.
func websocketDidConnect(ws: WebSocket) {
println("websocket is connected")
}
func websocketDidDisconnect(ws: WebSocket, error: NSError?) {
if let e = error {
println("websocket is disconnected: \(e.localizedDescription)")
} else {
println("websocket disconnected")
// 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 websocketDidReceiveMessage(ws: WebSocket, text: String) {
println("Received text: \(text)")
}
func websocketDidReceiveData(ws: WebSocket, data: NSData) {
println("Received data: \(data.length)")
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.writeString("hello there!")
@IBAction func writeText(_ sender: UIBarButtonItem) {
socket.write(string: "hello there!")
}
// MARK: Disconnect Action
@IBAction func disconnect(sender: UIBarButtonItem) {
if socket.isConnected {
@IBAction func disconnect(_ sender: UIBarButtonItem) {
if isConnected {
sender.title = "Connect"
socket.disconnect()
} else {
+2 -2
View File
@@ -19,7 +19,7 @@ EM.run {
ws.onmessage { |msg|
puts "message from client: #{msg}"
ws.send Faker::Hacker.say_something_smart
ws.send +Faker::Hacker.say_something_smart
}
end
}
}
+11
View File
@@ -0,0 +1,11 @@
# 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
+16
View File
@@ -0,0 +1,16 @@
PODS:
- Starscream (3.0.6)
DEPENDENCIES:
- Starscream (from `../../`)
EXTERNAL SOURCES:
Starscream:
:path: "../../"
SPEC CHECKSUMS:
Starscream: 96cd79a6b7ef6a2ff2d00638c73bd195a5322586
PODFILE CHECKSUM: 96d91933fe13671aaa81af8a8675ff7698068845
COCOAPODS: 1.6.0.beta.1
@@ -0,0 +1,24 @@
{
"name": "Starscream",
"version": "3.0.6",
"summary": "A conforming WebSocket RFC 6455 client library in Swift.",
"homepage": "https://github.com/daltoniam/Starscream",
"license": "Apache License, Version 2.0",
"authors": {
"Dalton Cherry": "http://daltoniam.com",
"Austin Cherry": "http://austincherry.me"
},
"source": {
"git": "https://github.com/daltoniam/Starscream.git",
"tag": "3.0.6"
},
"social_media_url": "http://twitter.com/daltoniam",
"platforms": {
"ios": "8.0",
"osx": "10.10",
"tvos": "9.0",
"watchos": "2.0"
},
"source_files": "Sources/**/*.swift",
"swift_version": "4.2"
}
+16
View File
@@ -0,0 +1,16 @@
PODS:
- Starscream (3.0.6)
DEPENDENCIES:
- Starscream (from `../../`)
EXTERNAL SOURCES:
Starscream:
:path: "../../"
SPEC CHECKSUMS:
Starscream: 96cd79a6b7ef6a2ff2d00638c73bd195a5322586
PODFILE CHECKSUM: 96d91933fe13671aaa81af8a8675ff7698068845
COCOAPODS: 1.6.0.beta.1
@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>${EXECUTABLE_NAME}</string>
<key>CFBundleIdentifier</key>
<string>${PRODUCT_BUNDLE_IDENTIFIER}</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>${PRODUCT_NAME}</string>
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>1.0.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>${CURRENT_PROJECT_VERSION}</string>
<key>NSPrincipalClass</key>
<string></string>
</dict>
</plist>
@@ -0,0 +1,182 @@
# Acknowledgements
This application makes use of the following third party libraries:
## Starscream
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
Copyright (c) 2014-2016 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.
Generated by CocoaPods - https://cocoapods.org
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<string></string>
</plist>
@@ -0,0 +1,5 @@
#import <Foundation/Foundation.h>
@interface PodsDummy_Pods_WebSocketsOrgEcho : NSObject
@end
@implementation PodsDummy_Pods_WebSocketsOrgEcho
@end
@@ -0,0 +1,158 @@
#!/bin/sh
set -e
set -u
set -o pipefail
if [ -z ${FRAMEWORKS_FOLDER_PATH+x} ]; then
# If FRAMEWORKS_FOLDER_PATH is not set, then there's nowhere for us to copy
# frameworks to, so exit 0 (signalling the script phase was successful).
exit 0
fi
echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
COCOAPODS_PARALLEL_CODE_SIGN="${COCOAPODS_PARALLEL_CODE_SIGN:-false}"
SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}"
# Used as a return value for each invocation of `strip_invalid_archs` function.
STRIP_BINARY_RETVAL=0
# This protects against multiple targets copying the same framework dependency at the same time. The solution
# was originally proposed here: https://lists.samba.org/archive/rsync/2008-February/020158.html
RSYNC_PROTECT_TMP_FILES=(--filter "P .*.??????")
# Copies and strips a vendored framework
install_framework()
{
if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then
local source="${BUILT_PRODUCTS_DIR}/$1"
elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then
local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")"
elif [ -r "$1" ]; then
local source="$1"
fi
local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
if [ -L "${source}" ]; then
echo "Symlinked..."
source="$(readlink "${source}")"
fi
# Use filter instead of exclude so missing patterns don't throw errors.
echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\""
rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}"
local basename
basename="$(basename -s .framework "$1")"
binary="${destination}/${basename}.framework/${basename}"
if ! [ -r "$binary" ]; then
binary="${destination}/${basename}"
elif [ -L "${binary}" ]; then
echo "Destination binary is symlinked..."
dirname="$(dirname "${binary}")"
binary="${dirname}/$(readlink "${binary}")"
fi
# Strip invalid architectures so "fat" simulator / device frameworks work on device
if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then
strip_invalid_archs "$binary"
fi
# Resign the code if required by the build settings to avoid unstable apps
code_sign_if_enabled "${destination}/$(basename "$1")"
# Embed linked Swift runtime libraries. No longer necessary as of Xcode 7.
if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then
local swift_runtime_libs
swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u && exit ${PIPESTATUS[0]})
for lib in $swift_runtime_libs; do
echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\""
rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}"
code_sign_if_enabled "${destination}/${lib}"
done
fi
}
# Copies and strips a vendored dSYM
install_dsym() {
local source="$1"
if [ -r "$source" ]; then
# Copy the dSYM into a the targets temp dir.
echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${DERIVED_FILES_DIR}\""
rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${DERIVED_FILES_DIR}"
local basename
basename="$(basename -s .framework.dSYM "$source")"
binary="${DERIVED_FILES_DIR}/${basename}.framework.dSYM/Contents/Resources/DWARF/${basename}"
# Strip invalid architectures so "fat" simulator / device frameworks work on device
if [[ "$(file "$binary")" == *"Mach-O dSYM companion"* ]]; then
strip_invalid_archs "$binary"
fi
if [[ $STRIP_BINARY_RETVAL == 1 ]]; then
# Move the stripped file into its final destination.
echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${DERIVED_FILES_DIR}/${basename}.framework.dSYM\" \"${DWARF_DSYM_FOLDER_PATH}\""
rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${DERIVED_FILES_DIR}/${basename}.framework.dSYM" "${DWARF_DSYM_FOLDER_PATH}"
else
# The dSYM was not stripped at all, in this case touch a fake folder so the input/output paths from Xcode do not reexecute this script because the file is missing.
touch "${DWARF_DSYM_FOLDER_PATH}/${basename}.framework.dSYM"
fi
fi
}
# Signs a framework with the provided identity
code_sign_if_enabled() {
if [ -n "${EXPANDED_CODE_SIGN_IDENTITY:-}" -a "${CODE_SIGNING_REQUIRED:-}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then
# Use the current code_sign_identity
echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}"
local code_sign_cmd="/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS:-} --preserve-metadata=identifier,entitlements '$1'"
if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then
code_sign_cmd="$code_sign_cmd &"
fi
echo "$code_sign_cmd"
eval "$code_sign_cmd"
fi
}
# Strip invalid architectures
strip_invalid_archs() {
binary="$1"
# Get architectures for current target binary
binary_archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | awk '{$1=$1;print}' | rev)"
# Intersect them with the architectures we are building for
intersected_archs="$(echo ${ARCHS[@]} ${binary_archs[@]} | tr ' ' '\n' | sort | uniq -d)"
# If there are no archs supported by this binary then warn the user
if [[ -z "$intersected_archs" ]]; then
echo "warning: [CP] Vendored binary '$binary' contains architectures ($binary_archs) none of which match the current build architectures ($ARCHS)."
STRIP_BINARY_RETVAL=0
return
fi
stripped=""
for arch in $binary_archs; do
if ! [[ "${ARCHS}" == *"$arch"* ]]; then
# Strip non-valid architectures in-place
lipo -remove "$arch" -output "$binary" "$binary" || exit 1
stripped="$stripped $arch"
fi
done
if [[ "$stripped" ]]; then
echo "Stripped $binary of architectures:$stripped"
fi
STRIP_BINARY_RETVAL=1
}
if [[ "$CONFIGURATION" == "Debug" ]]; then
install_framework "${BUILT_PRODUCTS_DIR}/Starscream/Starscream.framework"
fi
if [[ "$CONFIGURATION" == "Release" ]]; then
install_framework "${BUILT_PRODUCTS_DIR}/Starscream/Starscream.framework"
fi
if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then
wait
fi
@@ -0,0 +1,16 @@
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#else
#ifndef FOUNDATION_EXPORT
#if defined(__cplusplus)
#define FOUNDATION_EXPORT extern "C"
#else
#define FOUNDATION_EXPORT extern
#endif
#endif
#endif
FOUNDATION_EXPORT double Pods_WebSocketsOrgEchoVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_WebSocketsOrgEchoVersionString[];
@@ -0,0 +1,11 @@
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES
FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Starscream"
GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1
LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks'
OTHER_CFLAGS = $(inherited) -iquote "${PODS_CONFIGURATION_BUILD_DIR}/Starscream/Starscream.framework/Headers"
OTHER_LDFLAGS = $(inherited) -framework "Starscream"
OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS
PODS_BUILD_DIR = ${BUILD_DIR}
PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)
PODS_PODFILE_DIR_PATH = ${SRCROOT}/.
PODS_ROOT = ${SRCROOT}/Pods
@@ -0,0 +1,6 @@
framework module Pods_WebSocketsOrgEcho {
umbrella header "Pods-WebSocketsOrgEcho-umbrella.h"
export *
module * { export * }
}
@@ -0,0 +1,11 @@
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES
FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Starscream"
GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1
LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks'
OTHER_CFLAGS = $(inherited) -iquote "${PODS_CONFIGURATION_BUILD_DIR}/Starscream/Starscream.framework/Headers"
OTHER_LDFLAGS = $(inherited) -framework "Starscream"
OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS
PODS_BUILD_DIR = ${BUILD_DIR}
PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)
PODS_PODFILE_DIR_PATH = ${SRCROOT}/.
PODS_ROOT = ${SRCROOT}/Pods
@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>${EXECUTABLE_NAME}</string>
<key>CFBundleIdentifier</key>
<string>${PRODUCT_BUNDLE_IDENTIFIER}</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>${PRODUCT_NAME}</string>
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>3.0.6</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>${CURRENT_PROJECT_VERSION}</string>
<key>NSPrincipalClass</key>
<string></string>
</dict>
</plist>
@@ -0,0 +1,5 @@
#import <Foundation/Foundation.h>
@interface PodsDummy_Starscream : NSObject
@end
@implementation PodsDummy_Starscream
@end
@@ -0,0 +1,12 @@
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#else
#ifndef FOUNDATION_EXPORT
#if defined(__cplusplus)
#define FOUNDATION_EXPORT extern "C"
#else
#define FOUNDATION_EXPORT extern
#endif
#endif
#endif
@@ -0,0 +1,16 @@
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#else
#ifndef FOUNDATION_EXPORT
#if defined(__cplusplus)
#define FOUNDATION_EXPORT extern "C"
#else
#define FOUNDATION_EXPORT extern
#endif
#endif
#endif
FOUNDATION_EXPORT double StarscreamVersionNumber;
FOUNDATION_EXPORT const unsigned char StarscreamVersionString[];
@@ -0,0 +1,6 @@
framework module Starscream {
umbrella header "Starscream-umbrella.h"
export *
module * { export * }
}
@@ -0,0 +1,9 @@
CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/Starscream
GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1
OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS
PODS_BUILD_DIR = ${BUILD_DIR}
PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)
PODS_ROOT = ${SRCROOT}
PODS_TARGET_SRCROOT = ${PODS_ROOT}/../../..
PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier}
SKIP_INSTALL = YES
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "group:WebSocketsOrgEcho.xcodeproj">
</FileRef>
<FileRef
location = "group:Pods/Pods.xcodeproj">
</FileRef>
</Workspace>
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>IDEDidComputeMac32BitWarning</key>
<true/>
</dict>
</plist>
@@ -0,0 +1,21 @@
//
// 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
}
}
@@ -0,0 +1,98 @@
{
"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"
}
}
@@ -0,0 +1,6 @@
{
"info" : {
"version" : 1,
"author" : "xcode"
}
}
@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="13122.16" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="01J-lp-oVM">
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="13104.12"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="EHf-IW-A2E">
<objects>
<viewController id="01J-lp-oVM" sceneMemberID="viewController">
<view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<viewLayoutGuide key="safeArea" id="6Tk-OE-BBY"/>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="53" y="375"/>
</scene>
</scenes>
</document>
@@ -0,0 +1,40 @@
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="14313.18" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="BYZ-38-t0r">
<device id="retina4_7" orientation="portrait">
<adaptation id="fullscreen"/>
</device>
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="14283.14"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="tne-QT-ifu">
<objects>
<viewController id="BYZ-38-t0r" customClass="ViewController" customModule="WebSocketsOrgEcho" customModuleProvider="target" sceneMemberID="viewController">
<view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="ysb-Wt-xJQ">
<rect key="frame" x="158" y="318.5" width="59" height="30"/>
<state key="normal" title="Connect"/>
<connections>
<action selector="connect:" destination="BYZ-38-t0r" eventType="touchUpInside" id="JK8-oU-5uC"/>
</connections>
</button>
</subviews>
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<constraints>
<constraint firstItem="ysb-Wt-xJQ" firstAttribute="centerX" secondItem="8bC-Xf-vdC" secondAttribute="centerX" id="2YK-eB-LZR"/>
<constraint firstItem="ysb-Wt-xJQ" firstAttribute="centerY" secondItem="8bC-Xf-vdC" secondAttribute="centerY" id="iGG-QS-5FX"/>
</constraints>
<viewLayoutGuide key="safeArea" id="6Tk-OE-BBY"/>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
</objects>
</scene>
</scenes>
</document>
@@ -0,0 +1,45 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIMainStoryboardFile</key>
<string>Main</string>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>armv7</string>
</array>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
</dict>
</plist>
@@ -0,0 +1,19 @@
//
// 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
}
}
@@ -0,0 +1,42 @@
//
// 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()
}
}
+29
View File
@@ -0,0 +1,29 @@
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
+43
View File
@@ -0,0 +1,43 @@
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).