1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
|
define.class(function(require){
var crypto = require('crypto')
var url = require('url')
var http = require('http')
this.atConstructor = function(req, socket, head){
if(arguments.length === 1){
if(typeof req === 'string'){
this.initClient(req)
}
else{
this.initBare(req)
}
}
if(arguments.length === 3) this.initServer(req, socket, head)
}
this.onmessage = function(event){
}
this.onclose = function(){
}
this.onerror = function(error){
}
this.makeJSONSocket = function(){
var binary_buf = []
this.onmessage = function(event){
var message = event.data
if(message instanceof ArrayBuffer){
binary_buf.push(message)
return
}
var jsonmsg = JSON.parse(message)
jsonmsg = define.structFromJSON(jsonmsg, binary_buf)
binary_buf.length = 0
this.atJSONMessage(jsonmsg)
}
this.sendJSON = function(msg){
var binary = []
var newmsg = define.makeJSONSafe(msg, binary)
for(var i = 0; i < binary.length; i++){
var bin = binary[i]
this.send(bin.data.buffer)
}
var jsonmsg = JSON.stringify(newmsg)
this.send(jsonmsg)
}
}
this.initBare = function(socket){
this.socket = socket
this.initState()
}
this.initClient = function(server_url){
this.url = url.parse(server_url)
var host = this.url.hostname + ':' + this.url.port
var key = new Buffer(13 + '-' + Date.now()).toString('base64');
var shasum = crypto.createHash('sha1');
shasum.update(key + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11');
this.expectedServerKey = shasum.digest('base64');
var opt = {
port: this.url.port,
host: this.url.hostname,
path: this.url.path,
headers: {
'connection': 'Upgrade',
'upgrade': 'websocket',
'pragma':'no-cache',
'host': host,
'origin': 'http://' + host,
'sec-websocket-version': 13,
'sec-websocket-key': key,
}
}
var req = http.request(opt)
req.on('error', function(err){
console.log("WebSocket client " + err)
if(this.onError) this.onError(err)
}.bind(this))
req.once('response', function(){
console.log('WebSocket unexpected response')
}.bind(this))
req.once('upgrade', function(res, socket, upgradehead){
if(res.headers['sec-websocket-accept'] != this.expectedServerKey){
console.log('WebSocket unexpected server key')
}
this.socket = socket
this.initState()
if(this.onopen) this.onopen()
}.bind(this))
req.end()
}
this.initServer = function(req, socket){
var version = req.headers['sec-websocket-version']
if(version != 13){
console.log("Incompatible websocket version requested (need 13) " + version)
return socket.destroy()
}
this.socket = socket
var key = req.headers['sec-websocket-key']
var sha1 = crypto.createHash('sha1');
sha1.update(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
var ack = 'HTTP/1.1 101 Switching Protocols\r\n'+
'Upgrade: websocket\r\n'+
'Connection: Upgrade\r\n'+
'Sec-WebSocket-Accept: ' + sha1.digest('base64') +'\r\n\r\n'
this.socket.write(ack)
this.is_server = true
this.initState()
this.first_queue = []
}
this.initState = function(){
this.max = 500000000
this.header = new Buffer(14)
this.output = new Buffer(50000000)
this.state = this.opcode
this.expected = 1
this.written = 0
this.read = 0
this.input = 0
this.maskoff = 0
this.maskcount = 0
this.paylen = 0
this.readyState = 1
this.partial_msg = ''
this.partial_binary = []
this.partial_binary_bytes = 0
this.pingframe = new Buffer(2)
this.pingframe[0] = 9 | 128
this.pingframe[1] = 0
this.pongframe = new Buffer(2)
this.pongframe[0] = 10 | 128
this.pongframe[1] = 0
if(this.is_server){
this.ping_interval = setInterval(function(){
if(!this.socket) clearInterval(this.ping_interval)
else this.socket.write(this.pingframe)
}.bind(this), 10000)
}
this.socket.on('data', function(data){
this.input = data
this.read = 0
while(this.state());
}.bind(this))
this.socket.on('close', function(){
this.close()
}.bind(this))
}
this.error = function(t){
console.log("Error on websocket " + t)
this.onerror(t)
this.close()
}
this.send = function(data, ispartial, iscontinuation, domask){
if(this.first_queue){
if(!this.first_queue.length){
setTimeout(function(){
var q = this.first_queue
this.first_queue = undefined
for(var i = 0;i < q.length;i++){
this.send(q[i])
}
}.bind(this),10)
}
this.first_queue.push(data)
return
}
if(!this.socket) return
var head
var buf = new Buffer(data)
if(buf.length < 126){
head = new Buffer(2)
head[1] = buf.length
}
else if (buf.length<=65535){
head = new Buffer(4)
head[1] = 126
head.writeUInt16BE(buf.length, 2)
}
else {
head = new Buffer(10)
head[1] = 127
head[2] = head[3] = head[4] = head[5] = 0
head.writeUInt32BE(buf.length, 6)
}
var type = 1
if(data instanceof Buffer || data instanceof ArrayBuffer) type = 2
if(iscontinuation) type = 0
head[0] = (ispartial?0:128) | type
this.socket.write(head)
if(domask){
head[1] |= 128
var mask = new Buffer(4)
mask[0] = 0x7f
mask[1] = 0x7f
mask[2] = 0x7f
mask[3] = 0x7f
this.socket.write(mask)
for(var i = 0; i < buf.length; i++){
buf[i] ^= mask[i&3]
}
}
this.socket.write(buf)
}
this.close = function(){
if(this.socket){
this.onclose()
this.socket.destroy()
clearInterval(this.ping_interval)
this.readyState = 3
}
this.socket = undefined
}
this.head = function(){
var se = this.expected
while(this.expected > 0 && this.read < this.input.length && this.written < this.header.length){
this.header[this.written++] = this.input[this.read++], this.expected--
}
if(this.written > this.header.length) return this.err("unexpected data in header"+ se + s.toString())
return this.expected != 0
}
var total = 0
this.data = function(){
if(this.masked){
while(this.expected > 0 && this.read < this.input.length){
this.output[this.written++] = this.input[this.read++] ^ this.header[this.maskoff + (this.maskcount++&3)]
this.expected--
}
}
else{
if(this.written > this.output.length) console.log("NodeWebSocket output buffer overflow "+this.written)
while(this.expected > 0 && this.read < this.input.length){
this.output[this.written++] = this.input[this.read++]
this.expected--
}
}
if(this.expected) return false
if(this.binary){
if(!this.partial && !this.partial_binary_bytes){
var msg = new Uint8Array(this.written)
for(var i = 0; i < this.written; i++) msg[i] = this.output[i]
this.onmessage({data:msg.buffer})
}
else{
var store = new Uint8Array(this.written)
this.partial_binary.push(store)
for(var i = 0; i < this.written; i++){
store[i] = this.output[i]
}
this.partial_binary_bytes += i
if(!this.partial){
var msg = new Uint8Array(this.partial_binary_bytes)
var off = 0
for(var i = 0; i < this.partial_binary.length; i++){
var item = this.partial_binary[i]
for(var j = 0; j < item.length; j++, off++){
msg[off] = item[j]
}
}
this.partial_binary.length = 0
this.partial_binary_bytes = 0
this.onmessage({data:msg.buffer})
}
}
}
else if(!this.partial){
this.onmessage({data:this.partial_msg + this.output.toString('utf8', 0, this.written)})
this.partial_msg = ''
}
else{
this.partial_msg += this.output.toString('utf8', 0, this.written)
}
this.written = 0
this.expected = 1
this.state = this.opcode
return true
}
this.mask = function(){
if(this.head()) return false
if(!this.paylen){
this.expected = 1
this.written = 0
this.state = this.opcode
return true
}
this.maskoff = this.written - 4
this.written = this.maskcount = 0
this.expected = this.paylen
if(this.paylen > this.max) return this.error("buffer size request too large " + l + " > " + max)
if(this.paylen > this.output.length) this.output = new Buffer(this.paylen)
this.state = this.data
return true
}
this.len8 = function(){
if(this.head()) return false
this.paylen = this.header.readUInt32BE(this.written - 4)
if(this.masked){
this.expected = 4
this.state = this.mask
}
else{
this.expected = this.paylen
this.state = this.data
this.written = 0
}
return true
}
this.len2 = function(){
if(this.head()) return
this.paylen = this.header.readUInt16BE(this.written - 2)
if(this.masked){
this.expected = 4
this.state = this.mask
}
else{
this.expected = this.paylen
this.state = this.data
this.written = 0
}
return true
}
this.len1 = function(){
if(this.head()) return false
if(!(this.header[this.written - 1] & 128)){
this.masked = false
}
else{
this.masked = true
}
var type = this.header[this.written - 1] & 127
if(type < 126){
this.paylen = type
if(!this.masked){
this.expected = this.paylen
this.state = this.data
this.written = 0
}
else{
this.expected = 4
this.state = this.mask
}
}
else if(type == 126){
this.expected = 2
this.state = this.len2
}
else if(type == 127){
this.expected = 8
this.state = this.len8
}
return true
}
this.ping = function(){
if(this.head()) return false
if(this.header[this.written - 1] & 128){
this.expected = 4
this.paylen = 0
this.state = this.mask
return true
}
this.expected = 1
this.written = 0
this.state = this.opcode
this.socket.write(this.pongframe)
return true
}
this.pong = function(){
if(this.head()) return false
if(this.header[this.written - 1] & 128){
this.expected = 4
this.paylen = 0
this.state = this.mask
return true
}
this.expected = 1
this.written = 0
this.state = this.opcode
return true
}
this.opcode = function(){
if(this.head()) return
var frame = this.header[0] & 128
var type = this.header[0] & 15
if(type === 0 || type == 1 || type == 2){
if(!frame){
this.partial = true
}
else{
this.partial = false
}
this.binary = type === 2 || type === 0 && this.last_type === 2
this.expected = 1
this.state = this.len1
if(type) this.last_type = type
return true
}
if(type == 8) return this.close()
if(type == 9){
this.expected = 1
this.state = this.ping
return true
}
if(type == 10){
this.expected = 1
this.state = this.pong
return true
}
return this.error("opcode not supported " + type)
}
})
|