rubysocket-client 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: af6f7040d67393cd43bcc9dc3c5cf4f2ba04c12700f168ea3e66232dfd54e58a
4
+ data.tar.gz: 83601a6fb5eccf3c36b17421c859c06d5c91953eb8baabebb947487335bfe548
5
+ SHA512:
6
+ metadata.gz: 62c924bfb28651865d746f0e63c613cf82d93db493ba43ce11e237987406cda96fdd9d794228b2e0f1df41ea77a9fca00117ed3ed216486fa8e5fbae3fa6e67e
7
+ data.tar.gz: 0270f649e6b304d8b909356135c1881ec020f1ff24187d1f5639690b9a59baaf6ffbd6c4e92bb2d643f8abcbc447950e20d9b3098af005eb6a3195ca7a903ce1
data/.gitignore ADDED
@@ -0,0 +1,61 @@
1
+ *.gem
2
+ *.rbc
3
+ /.config
4
+ /coverage/
5
+ /InstalledFiles
6
+ /pkg/
7
+ /spec/reports/
8
+ /spec/examples.txt
9
+ /test/tmp/
10
+ /test/version_tmp/
11
+ /tmp/
12
+
13
+ # Used by dotenv library to load environment variables.
14
+ # .env
15
+
16
+ # Ignore Byebug command history file.
17
+ .byebug_history
18
+
19
+ ## Specific to RubyMotion:
20
+ .dat*
21
+ .repl_history
22
+ build/
23
+ *.bridgesupport
24
+ build-iPhoneOS/
25
+ build-iPhoneSimulator/
26
+
27
+ ## Specific to RubyMotion (use of CocoaPods):
28
+ #
29
+ # We recommend against adding the Pods directory to your .gitignore. However
30
+ # you should judge for yourself, the pros and cons are mentioned at:
31
+ # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control
32
+ #
33
+ # vendor/Pods/
34
+
35
+ ## Documentation cache and generated files:
36
+ /.yardoc/
37
+ /_yardoc/
38
+ /doc/
39
+ /rdoc/
40
+
41
+ ## Environment normalization:
42
+ /.bundle/
43
+ /vendor/bundle
44
+ /lib/bundler/man/
45
+
46
+ # for a library or gem, you might want to ignore these files since the code is
47
+ # intended to run in multiple environments; otherwise, check them in:
48
+ # Gemfile.lock
49
+ # .ruby-version
50
+ # .ruby-gemset
51
+
52
+ # unless supporting rvm < 1.11.0 or doing something fancy, ignore this:
53
+ .rvmrc
54
+
55
+ # Used by RuboCop. Remote config files pulled in from inherit_from directive.
56
+ # .rubocop-https?--*
57
+
58
+ .DS_Store
59
+
60
+ .vscode/
61
+ .idea/
data/Gemfile ADDED
@@ -0,0 +1,8 @@
1
+ source "http://rubygems.org"
2
+
3
+ group :development do
4
+ gem "rspec"
5
+ end
6
+
7
+ gem 'rest-client'
8
+ gemspec
data/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
data/README.md ADDED
@@ -0,0 +1,2 @@
1
+ # rubysocket
2
+ Socket implementation in ruby
data/Rakefile ADDED
@@ -0,0 +1,7 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ desc "Run all specs"
5
+ RSpec::Core::RakeTask.new('spec') do |t|
6
+ t.rspec_opts = ['--colour --format documentation']
7
+ end
@@ -0,0 +1,6 @@
1
+ module RubySocket
2
+ class Client
3
+ VERSION = "0.0.2"
4
+ end
5
+ end
6
+
data/lib/parser.rb ADDED
@@ -0,0 +1,13 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ module Parser
4
+ @regexp = /([^:]+):([0-9]+)?(\+)?:([^:]+)?:?([\s\S]*)?/
5
+
6
+ def self.decode(string)
7
+ if pieces = string.match(@regexp)
8
+ {type: pieces[1], id: pieces[2], end_point: pieces[4], data: pieces[5]}
9
+ else
10
+ {type: '0'}
11
+ end
12
+ end
13
+ end
data/lib/web_socket.rb ADDED
@@ -0,0 +1,596 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "base64"
4
+ require "socket"
5
+ require "uri"
6
+ require "digest/md5"
7
+ require "digest/sha1"
8
+ require "openssl"
9
+ require "stringio"
10
+
11
+
12
+ class WebSocket
13
+
14
+ class << self
15
+
16
+ attr_accessor(:debug)
17
+
18
+ end
19
+
20
+ class Error < RuntimeError
21
+
22
+ end
23
+
24
+ WEB_SOCKET_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
25
+ OPCODE_CONTINUATION = 0x00
26
+ OPCODE_TEXT = 0x01
27
+ OPCODE_BINARY = 0x02
28
+ OPCODE_CLOSE = 0x08
29
+ OPCODE_PING = 0x09
30
+ OPCODE_PONG = 0x0a
31
+
32
+ def initialize(arg, params = {})
33
+ if params[:server] # server
34
+
35
+ @server = params[:server]
36
+ @socket = arg
37
+ line = gets()
38
+ if !line
39
+ raise(WebSocket::Error, "Client disconnected without sending anything.")
40
+ end
41
+ line = line.chomp()
42
+ if !(line =~ /\AGET (\S+) HTTP\/1.1\z/n)
43
+ raise(WebSocket::Error, "Invalid request: #{line}")
44
+ end
45
+ @path = $1
46
+ read_header()
47
+ if @header["sec-websocket-version"]
48
+ @web_socket_version = @header["sec-websocket-version"]
49
+ @key3 = nil
50
+ elsif @header["sec-websocket-key1"] && @header["sec-websocket-key2"]
51
+ @web_socket_version = "hixie-76"
52
+ @key3 = read(8)
53
+ else
54
+ @web_socket_version = "hixie-75"
55
+ @key3 = nil
56
+ end
57
+ if !@server.accepted_origin?(self.origin)
58
+ raise(WebSocket::Error,
59
+ ("Unaccepted origin: %s (server.accepted_domains = %p)\n\n" +
60
+ "To accept this origin, write e.g. \n" +
61
+ " WebSocketServer.new(..., :accepted_domains => [%p]), or\n" +
62
+ " WebSocketServer.new(..., :accepted_domains => [\"*\"])\n") %
63
+ [self.origin, @server.accepted_domains, @server.origin_to_domain(self.origin)])
64
+ end
65
+ @handshaked = false
66
+
67
+ else # client
68
+
69
+ @web_socket_version = "hixie-76"
70
+ uri = arg.is_a?(String) ? URI.parse(arg) : arg
71
+
72
+ if uri.scheme == "ws"
73
+ default_port = 80
74
+ elsif uri.scheme = "wss"
75
+ default_port = 443
76
+ else
77
+ raise(WebSocket::Error, "unsupported scheme: #{uri.scheme}")
78
+ end
79
+
80
+ @path = (uri.path.empty? ? "/" : uri.path) + (uri.query ? "?" + uri.query : "")
81
+ host = uri.host + ((!uri.port || uri.port == default_port) ? "" : ":#{uri.port}")
82
+ origin = params[:origin] || "http://#{uri.host}"
83
+ key1 = generate_key()
84
+ key2 = generate_key()
85
+ key3 = generate_key3()
86
+
87
+ socket = TCPSocket.new(uri.host, uri.port || default_port)
88
+
89
+ if uri.scheme == "ws"
90
+ @socket = socket
91
+ else
92
+ @socket = ssl_handshake(socket)
93
+ end
94
+
95
+ write(
96
+ "GET #{@path} HTTP/1.1\r\n" +
97
+ "Upgrade: WebSocket\r\n" +
98
+ "Connection: Upgrade\r\n" +
99
+ "Host: #{host}\r\n" +
100
+ "Origin: #{origin}\r\n" +
101
+ "Sec-WebSocket-Key1: #{key1}\r\n" +
102
+ "Sec-WebSocket-Key2: #{key2}\r\n" +
103
+ "\r\n" +
104
+ "#{key3}")
105
+ flush()
106
+
107
+ line = gets().chomp()
108
+ raise(WebSocket::Error, "bad response: #{line}") if !(line =~ /\AHTTP\/1.1 101 /n)
109
+ read_header()
110
+ if (@header["sec-websocket-origin"] || "").downcase() != origin.downcase()
111
+ raise(WebSocket::Error,
112
+ "origin doesn't match: '#{@header["sec-websocket-origin"]}' != '#{origin}'")
113
+ end
114
+ reply_digest = read(16)
115
+ expected_digest = hixie_76_security_digest(key1, key2, key3)
116
+ if reply_digest != expected_digest
117
+ raise(WebSocket::Error,
118
+ "security digest doesn't match: %p != %p" % [reply_digest, expected_digest])
119
+ end
120
+ @handshaked = true
121
+
122
+ end
123
+ @received = []
124
+ @buffer = ""
125
+ @closing_started = false
126
+ end
127
+
128
+ attr_reader(:server, :header, :path)
129
+
130
+ def handshake(status = nil, header = {})
131
+ if @handshaked
132
+ raise(WebSocket::Error, "handshake has already been done")
133
+ end
134
+ status ||= "101 Switching Protocols"
135
+ def_header = {}
136
+ case @web_socket_version
137
+ when "hixie-75"
138
+ def_header["WebSocket-Origin"] = self.origin
139
+ def_header["WebSocket-Location"] = self.location
140
+ extra_bytes = ""
141
+ when "hixie-76"
142
+ def_header["Sec-WebSocket-Origin"] = self.origin
143
+ def_header["Sec-WebSocket-Location"] = self.location
144
+ extra_bytes = hixie_76_security_digest(
145
+ @header["Sec-WebSocket-Key1"], @header["Sec-WebSocket-Key2"], @key3)
146
+ else
147
+ def_header["Sec-WebSocket-Accept"] = security_digest(@header["sec-websocket-key"])
148
+ extra_bytes = ""
149
+ end
150
+ header = def_header.merge(header)
151
+ header_str = header.map(){ |k, v| "#{k}: #{v}\r\n" }.join("")
152
+ # Note that Upgrade and Connection must appear in this order.
153
+ write(
154
+ "HTTP/1.1 #{status}\r\n" +
155
+ "Upgrade: websocket\r\n" +
156
+ "Connection: Upgrade\r\n" +
157
+ "#{header_str}\r\n#{extra_bytes}")
158
+ flush()
159
+ @handshaked = true
160
+ end
161
+
162
+ def send(data)
163
+ if !@handshaked
164
+ raise(WebSocket::Error, "call WebSocket\#handshake first")
165
+ end
166
+ case @web_socket_version
167
+ when "hixie-75", "hixie-76"
168
+ data = force_encoding(data.dup(), "ASCII-8BIT")
169
+ write("\x00#{data}\xff")
170
+ flush()
171
+ else
172
+ send_frame(OPCODE_TEXT, data, !@server)
173
+ end
174
+ end
175
+
176
+ def receive()
177
+ if !@handshaked
178
+ raise(WebSocket::Error, "call WebSocket\#handshake first")
179
+ end
180
+ case @web_socket_version
181
+
182
+ when "hixie-75", "hixie-76"
183
+ packet = gets(force_encoding("\xff", "ASCII-8BIT"))
184
+ return nil if !packet
185
+ if packet =~ /\A\x00(.*)\xff\z/nm
186
+ return force_encoding($1, "UTF-8")
187
+ elsif packet == "\xff" && read(1) == "\x00" # closing
188
+ close(1005, "", :peer)
189
+ return nil
190
+ else
191
+ raise(WebSocket::Error, "input must be either '\\x00...\\xff' or '\\xff\\x00'")
192
+ end
193
+
194
+ else
195
+ while true
196
+ begin
197
+ bytes = read(2).unpack("C*")
198
+ fin = (bytes[0] & 0x80) != 0
199
+ opcode = bytes[0] & 0x0f
200
+ mask = (bytes[1] & 0x80) != 0
201
+ plength = bytes[1] & 0x7f
202
+ if plength == 126
203
+ bytes = read(2)
204
+ plength = bytes.unpack("n")[0]
205
+ elsif plength == 127
206
+ bytes = read(8)
207
+ (high, low) = bytes.unpack("NN")
208
+ plength = high * (2 ** 32) + low
209
+ end
210
+ if @server && !mask
211
+ # Masking is required.
212
+ @socket.close()
213
+ raise(WebSocket::Error, "received unmasked data")
214
+ end
215
+ mask_key = mask ? read(4).unpack("C*") : nil
216
+ payload = read(plength)
217
+ payload = apply_mask(payload, mask_key) if mask
218
+ if WebSocket.debug
219
+ $stderr.printf("recv_frame> opcode:%d fin:%d payload:%p\n" % [opcode, fin ? 1 : 0, payload])
220
+ end
221
+ case opcode
222
+ when OPCODE_TEXT
223
+ return force_encoding(payload, "UTF-8")
224
+ when OPCODE_BINARY
225
+ raise(WebSocket::Error, "received binary data, which is not supported")
226
+ when OPCODE_CLOSE
227
+ close(1005, "", :peer)
228
+ return nil
229
+ when OPCODE_PING
230
+ raise(WebSocket::Error, "received ping, which is not supported")
231
+ when OPCODE_PONG
232
+ next
233
+ else
234
+ raise(WebSocket::Error, "received unknown opcode: %d" % opcode)
235
+ end
236
+ rescue EOFError
237
+ return nil
238
+ end
239
+ end
240
+ end
241
+ end
242
+
243
+ def tcp_socket
244
+ return @socket
245
+ end
246
+
247
+ def host
248
+ return @header["host"]
249
+ end
250
+
251
+ def origin
252
+ case @web_socket_version
253
+ when "7", "8"
254
+ name = "sec-websocket-origin"
255
+ else
256
+ name = "origin"
257
+ end
258
+ if @header[name]
259
+ return @header[name]
260
+ else
261
+ raise(WebSocket::Error, "%s header is missing" % name)
262
+ end
263
+ end
264
+
265
+ def location
266
+ return "ws://#{self.host}#{@path}"
267
+ end
268
+
269
+ # Does closing handshake.
270
+ def close(code = 1005, reason = "", origin = :self)
271
+ if !@closing_started
272
+ case @web_socket_version
273
+ when "hixie-75", "hixie-76"
274
+ write("\xff\x00")
275
+ else
276
+ if code == 1005
277
+ payload = ""
278
+ else
279
+ payload = [code].pack("n") + force_encoding(reason.dup(), "ASCII-8BIT")
280
+ end
281
+ send_frame(OPCODE_CLOSE, payload, false)
282
+ end
283
+ end
284
+ @socket.close() if origin == :peer
285
+ @closing_started = true
286
+ end
287
+
288
+ def close_socket()
289
+ @socket.close()
290
+ end
291
+
292
+ private
293
+
294
+ NOISE_CHARS = ("\x21".."\x2f").to_a() + ("\x3a".."\x7e").to_a()
295
+
296
+ def read_header()
297
+ @header = {}
298
+ while line = gets()
299
+ line = line.chomp()
300
+ break if line.empty?
301
+ if !(line =~ /\A(\S+): (.*)\z/n)
302
+ raise(WebSocket::Error, "invalid request: #{line}")
303
+ end
304
+ @header[$1] = $2
305
+ @header[$1.downcase()] = $2
306
+ end
307
+ if !@header["upgrade"]
308
+ raise(WebSocket::Error, "Upgrade header is missing")
309
+ end
310
+ if !(@header["upgrade"] =~ /\AWebSocket\z/i)
311
+ raise(WebSocket::Error, "invalid Upgrade: " + @header["upgrade"])
312
+ end
313
+ if !@header["connection"]
314
+ raise(WebSocket::Error, "Connection header is missing")
315
+ end
316
+ if @header["connection"].split(/,/).grep(/\A\s*Upgrade\s*\z/i).empty?
317
+ raise(WebSocket::Error, "invalid Connection: " + @header["connection"])
318
+ end
319
+ end
320
+
321
+ def send_frame(opcode, payload, mask)
322
+ if WebSocket.debug
323
+ $stderr.printf("send_frame> opcode:%d masked:%d payload:%p\n" % [opcode, mask ? 1 : 0, payload])
324
+ end
325
+ payload = force_encoding(payload.dup(), "ASCII-8BIT")
326
+ # Setting StringIO's encoding to ASCII-8BIT.
327
+ buffer = StringIO.new(force_encoding("", "ASCII-8BIT"))
328
+ write_byte(buffer, 0x80 | opcode)
329
+ masked_byte = mask ? 0x80 : 0x00
330
+ if payload.bytesize <= 125
331
+ write_byte(buffer, masked_byte | payload.bytesize)
332
+ elsif payload.bytesize < 2 ** 16
333
+ write_byte(buffer, masked_byte | 126)
334
+ buffer.write([payload.bytesize].pack("n"))
335
+ else
336
+ write_byte(buffer, masked_byte | 127)
337
+ buffer.write([payload.bytesize / (2 ** 32), payload.bytesize % (2 ** 32)].pack("NN"))
338
+ end
339
+ if mask
340
+ mask_key = Array.new(4){ rand(256) }
341
+ buffer.write(mask_key.pack("C*"))
342
+ payload = apply_mask(payload, mask_key)
343
+ end
344
+ buffer.write(payload)
345
+ write(buffer.string)
346
+ end
347
+
348
+ def gets(rs = $/)
349
+ line = @socket.gets(rs)
350
+ $stderr.printf("recv> %p\n", line) if WebSocket.debug
351
+ return line
352
+ end
353
+
354
+ def read(num_bytes)
355
+ str = @socket.read(num_bytes)
356
+ $stderr.printf("recv> %p\n", str) if WebSocket.debug
357
+ if str && str.bytesize == num_bytes
358
+ return str
359
+ else
360
+ raise(EOFError)
361
+ end
362
+ end
363
+
364
+ def write(data)
365
+ if WebSocket.debug
366
+ data.scan(/\G(.*?(\n|\z))/n) do
367
+ $stderr.printf("send> %p\n", $&) if !$&.empty?
368
+ end
369
+ end
370
+ @socket.write(data)
371
+ end
372
+
373
+ def flush()
374
+ @socket.flush()
375
+ end
376
+
377
+ def write_byte(buffer, byte)
378
+ buffer.write([byte].pack("C"))
379
+ end
380
+
381
+ def security_digest(key)
382
+ return Base64.encode64(Digest::SHA1.digest(key + WEB_SOCKET_GUID)).gsub(/\n/, "")
383
+ end
384
+
385
+ def hixie_76_security_digest(key1, key2, key3)
386
+ bytes1 = websocket_key_to_bytes(key1)
387
+ bytes2 = websocket_key_to_bytes(key2)
388
+ return Digest::MD5.digest(bytes1 + bytes2 + key3)
389
+ end
390
+
391
+ def apply_mask(payload, mask_key)
392
+ orig_bytes = payload.unpack("C*")
393
+ new_bytes = []
394
+ orig_bytes.each_with_index() do |b, i|
395
+ new_bytes.push(b ^ mask_key[i % 4])
396
+ end
397
+ return new_bytes.pack("C*")
398
+ end
399
+
400
+ def generate_key()
401
+ spaces = 1 + rand(12)
402
+ max = 0xffffffff / spaces
403
+ number = rand(max + 1)
404
+ key = (number * spaces).to_s()
405
+ (1 + rand(12)).times() do
406
+ char = NOISE_CHARS[rand(NOISE_CHARS.size)]
407
+ pos = rand(key.size + 1)
408
+ key[pos...pos] = char
409
+ end
410
+ spaces.times() do
411
+ pos = 1 + rand(key.size - 1)
412
+ key[pos...pos] = " "
413
+ end
414
+ return key
415
+ end
416
+
417
+ def generate_key3()
418
+ return [rand(0x100000000)].pack("N") + [rand(0x100000000)].pack("N")
419
+ end
420
+
421
+ def websocket_key_to_bytes(key)
422
+ num = key.gsub(/[^\d]/n, "").to_i() / key.scan(/ /).size
423
+ return [num].pack("N")
424
+ end
425
+
426
+ def force_encoding(str, encoding)
427
+ if str.respond_to?(:force_encoding)
428
+ return str.force_encoding(encoding)
429
+ else
430
+ return str
431
+ end
432
+ end
433
+
434
+ def ssl_handshake(socket)
435
+ ssl_context = OpenSSL::SSL::SSLContext.new()
436
+ ssl_socket = OpenSSL::SSL::SSLSocket.new(socket, ssl_context)
437
+ ssl_socket.sync_close = true
438
+ ssl_socket.connect()
439
+ return ssl_socket
440
+ end
441
+
442
+ end
443
+
444
+
445
+ class WebSocketServer
446
+
447
+ def initialize(params_or_uri, params = nil)
448
+ if params
449
+ uri = params_or_uri.is_a?(String) ? URI.parse(params_or_uri) : params_or_uri
450
+ params[:port] ||= uri.port
451
+ params[:accepted_domains] ||= [uri.host]
452
+ else
453
+ params = params_or_uri
454
+ end
455
+ @port = params[:port] || 80
456
+ @accepted_domains = params[:accepted_domains]
457
+ if !@accepted_domains
458
+ raise(ArgumentError, "params[:accepted_domains] is required")
459
+ end
460
+ if params[:host]
461
+ @tcp_server = TCPServer.open(params[:host], @port)
462
+ else
463
+ @tcp_server = TCPServer.open(@port)
464
+ end
465
+ end
466
+
467
+ attr_reader(:tcp_server, :port, :accepted_domains)
468
+
469
+ def run(&block)
470
+ while true
471
+ Thread.start(accept()) do |s|
472
+ begin
473
+ ws = create_web_socket(s)
474
+ yield(ws) if ws
475
+ rescue => ex
476
+ print_backtrace(ex)
477
+ ensure
478
+ begin
479
+ ws.close_socket() if ws
480
+ rescue
481
+ end
482
+ end
483
+ end
484
+ end
485
+ end
486
+
487
+ def accept()
488
+ return @tcp_server.accept()
489
+ end
490
+
491
+ def accepted_origin?(origin)
492
+ domain = origin_to_domain(origin)
493
+ return @accepted_domains.any?(){ |d| File.fnmatch(d, domain) }
494
+ end
495
+
496
+ def origin_to_domain(origin)
497
+ if origin == "null" || origin == "file://" # local file
498
+ return "null"
499
+ else
500
+ return URI.parse(origin).host
501
+ end
502
+ end
503
+
504
+ def create_web_socket(socket)
505
+ ch = socket.getc()
506
+ if ch == ?<
507
+ # This is Flash socket policy file request, not an actual Web Socket connection.
508
+ send_flash_socket_policy_file(socket)
509
+ return nil
510
+ else
511
+ socket.ungetc(ch) if ch
512
+ return WebSocket.new(socket, :server => self)
513
+ end
514
+ end
515
+
516
+ private
517
+
518
+ def print_backtrace(ex)
519
+ $stderr.printf("%s: %s (%p)\n", ex.backtrace[0], ex.message, ex.class)
520
+ for s in ex.backtrace[1..-1]
521
+ $stderr.printf(" %s\n", s)
522
+ end
523
+ end
524
+
525
+ # Handles Flash socket policy file request sent when web-socket-js is used:
526
+ # http://github.com/gimite/web-socket-js/tree/master
527
+ def send_flash_socket_policy_file(socket)
528
+ socket.puts('<?xml version="1.0"?>')
529
+ socket.puts('<!DOCTYPE cross-domain-policy SYSTEM ' +
530
+ '"http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">')
531
+ socket.puts('<cross-domain-policy>')
532
+ for domain in @accepted_domains
533
+ next if domain == "file://"
534
+ socket.puts("<allow-access-from domain=\"#{domain}\" to-ports=\"#{@port}\"/>")
535
+ end
536
+ socket.puts('</cross-domain-policy>')
537
+ socket.close()
538
+ end
539
+
540
+ end
541
+
542
+
543
+ if __FILE__ == $0
544
+ Thread.abort_on_exception = true
545
+
546
+ if ARGV[0] == "server" && ARGV.size == 3
547
+
548
+ server = WebSocketServer.new(
549
+ :accepted_domains => [ARGV[1]],
550
+ :port => ARGV[2].to_i())
551
+ puts("Server is running at port %d" % server.port)
552
+ server.run() do |ws|
553
+ puts("Connection accepted")
554
+ puts("Path: #{ws.path}, Origin: #{ws.origin}")
555
+ if ws.path == "/"
556
+ ws.handshake()
557
+ while data = ws.receive()
558
+ printf("Received: %p\n", data)
559
+ ws.send(data)
560
+ printf("Sent: %p\n", data)
561
+ end
562
+ else
563
+ ws.handshake("404 Not Found")
564
+ end
565
+ puts("Connection closed")
566
+ end
567
+
568
+ elsif ARGV[0] == "client" && ARGV.size == 2
569
+
570
+ client = WebSocket.new(ARGV[1])
571
+ puts("Connected")
572
+ Thread.new() do
573
+ while data = client.receive()
574
+ printf("Received: %p\n", data)
575
+ end
576
+ end
577
+ $stdin.each_line() do |line|
578
+ data = line.chomp()
579
+ client.send(data)
580
+ printf("Sent: %p\n", data)
581
+ end
582
+
583
+ else
584
+
585
+ $stderr.puts("Usage:")
586
+ $stderr.puts(" ruby web_socket.rb server ACCEPTED_DOMAIN PORT")
587
+ $stderr.puts(" ruby web_socket.rb client ws://HOST:PORT/")
588
+ exit(1)
589
+
590
+ end
591
+ end
592
+
593
+ # Reference: http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-75
594
+ # Reference: http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76
595
+ # Reference: http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-07
596
+ # Reference: http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-10
@@ -0,0 +1,21 @@
1
+ $:.push File.expand_path("../lib", __FILE__)
2
+ require 'RubySocket/version'
3
+
4
+ Gem::Specification.new do |s|
5
+ s.name = "rubysocket-client"
6
+ s.version = RubySocket::Client::VERSION
7
+ s.authors = ["KrishPranav"]
8
+ s.email = [""]
9
+ s.homepage = "http://github.com/krishpranav/rubysocket"
10
+ s.summary = %q{ruby socket implem}
11
+ s.description = %q{ruby socket implementation}
12
+
13
+ s.rubyforge_project = "rubysocket-client"
14
+
15
+ s.files = `git ls-files`.split("\n")
16
+ s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
17
+ s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
18
+ s.require_paths = ["lib"]
19
+
20
+ s.add_runtime_dependency "rest-client"
21
+ end
@@ -0,0 +1,22 @@
1
+ require 'RubySocket'
2
+
3
+ describe Parser do
4
+
5
+ it 'should be able to decode all valid messages' do
6
+ Parser.decode("0").should == {type: "0"}
7
+ Parser.decode("1::").should == {type: "1", id: nil, end_point: nil, data: ""}
8
+ Parser.decode("2::").should == {type: "2", id: nil, end_point: nil, data: ""}
9
+ Parser.decode("3:::hay you").should == {type: "3", id: nil, end_point: nil, data: "hay you"}
10
+ Parser.decode("4:::{\"can\":\"youcall\"}").should == {type: "4", id: nil, end_point: nil, data: "{\"can\":\"youcall\"}"}
11
+ Parser.decode("5:::hay you").should == {type: "5", id: nil, end_point: nil, data: "hay you"}
12
+ Parser.decode("6:::").should == {type: "6", id: nil, end_point: nil, data: ""}
13
+ Parser.decode("7:::there is an error").should == {type: "7", id: nil, end_point: nil, data: "there is an error"}
14
+ Parser.decode("8:::").should == {type: "8", id: nil, end_point: nil, data: ""}
15
+ end
16
+
17
+ it "should give a disconnect if bad input" do
18
+ Parser.decode("hay dude").should == {type: "0"}
19
+ Parser.decode("9").should == {type: "0"}
20
+ end
21
+
22
+ end
@@ -0,0 +1,45 @@
1
+ describe RubySocket do
2
+
3
+ before :all do
4
+ @client = RubySocket.connect("http://localhost", :sync => true)
5
+ end
6
+
7
+ it "can send a heartbeat" do
8
+ @client.send_heartbeat
9
+ end
10
+
11
+ it "gets a message back when it sends one" do
12
+ count = 0
13
+ @client.on_message do |msg|
14
+ count += 1 if msg == "hay dude"
15
+ end
16
+ @client.send("hay dude")
17
+ sleep 0.5
18
+ count.should == 1
19
+ end
20
+
21
+ it "gets an emit back when it hits the echo" do
22
+ count = 0
23
+ @client.on_event("event") do |data|
24
+ count += 1 if data[0] == {"first"=>"element", "second"=>"guy"}
25
+ end
26
+ @client.emit("event", {first: "element", second: "guy"})
27
+ sleep 0.5
28
+ count.should == 1
29
+ end
30
+
31
+ it "can have a block for every thing" do
32
+ @client.on_disconnect { }
33
+ @client.on_connect { }
34
+ @client.on_heartbeat { }
35
+ @client.on_message { |msg| }
36
+ @client.on_json_message { |json| }
37
+ @client.on_event('en') { |event_hash| }
38
+ @client.on_ack { }
39
+ @client.on_error { |data| }
40
+ @client.on_noop { }
41
+ end
42
+
43
+
44
+
45
+ end
data/spec/setup/io.js ADDED
@@ -0,0 +1,17 @@
1
+ var io = require('socket.io').listen(80);
2
+
3
+ io.sockets.on('connection', function(socket) {
4
+
5
+ socket.on('message', function(msg) {
6
+ socket.send(msg)
7
+ })
8
+
9
+ socket.on('event', function(data) {
10
+ socket.emit('event', data);
11
+ });
12
+
13
+ socket.on('dc', function() {
14
+ socket.close()
15
+ })
16
+
17
+ });
@@ -0,0 +1,6 @@
1
+ echo_server = fork do
2
+ puts `pwd`
3
+ end
4
+
5
+ puts "pid ??? #{echo_server}"
6
+ Process.detach(echo_server)
@@ -0,0 +1,6 @@
1
+ echo_server = fork do
2
+ puts `pwd`
3
+ end
4
+
5
+ puts "pid ??? #{echo_server}"
6
+ Process.detach(echo_server)
metadata ADDED
@@ -0,0 +1,75 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: rubysocket-client
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.2
5
+ platform: ruby
6
+ authors:
7
+ - KrishPranav
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2021-12-28 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: rest-client
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ description: ruby socket implementation
28
+ email:
29
+ - ''
30
+ executables: []
31
+ extensions: []
32
+ extra_rdoc_files: []
33
+ files:
34
+ - ".gitignore"
35
+ - Gemfile
36
+ - LICENSE
37
+ - README.md
38
+ - Rakefile
39
+ - lib/RubySocket/version.rb
40
+ - lib/parser.rb
41
+ - lib/web_socket.rb
42
+ - rubysocket.gemspec
43
+ - spec/parser_spec.rb
44
+ - spec/rubysocket_spec.rb
45
+ - spec/setup/io.js
46
+ - spec/setup/start.rb
47
+ - spec/setup/stop.rb
48
+ homepage: http://github.com/krishpranav/rubysocket
49
+ licenses: []
50
+ metadata: {}
51
+ post_install_message:
52
+ rdoc_options: []
53
+ require_paths:
54
+ - lib
55
+ required_ruby_version: !ruby/object:Gem::Requirement
56
+ requirements:
57
+ - - ">="
58
+ - !ruby/object:Gem::Version
59
+ version: '0'
60
+ required_rubygems_version: !ruby/object:Gem::Requirement
61
+ requirements:
62
+ - - ">="
63
+ - !ruby/object:Gem::Version
64
+ version: '0'
65
+ requirements: []
66
+ rubygems_version: 3.2.22
67
+ signing_key:
68
+ specification_version: 4
69
+ summary: ruby socket implem
70
+ test_files:
71
+ - spec/parser_spec.rb
72
+ - spec/rubysocket_spec.rb
73
+ - spec/setup/io.js
74
+ - spec/setup/start.rb
75
+ - spec/setup/stop.rb