forked from filipecbmoc/vnc-rfb-client
-
Notifications
You must be signed in to change notification settings - Fork 1
/
vncclient.js
898 lines (737 loc) · 30.1 KB
/
vncclient.js
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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
const {versionString, encodings, serverMsgTypes, clientMsgTypes} = require('./constants');
const net = require('net');
const Events = require('events').EventEmitter;
const HextileDecoder = require('./decoders/hextile');
const RawDecoder = require('./decoders/raw');
const ZrleDecoder = require('./decoders/zrle');
// const tightDecoder = require('./decoders/tight');
const CopyrectDecoder = require('./decoders/copyrect');
const SocketBuffer = require('./socketbuffer');
const crypto = require('crypto');
class VncClient extends Events {
static get consts() {
return {encodings};
}
/**
* Return if client is connected
* @returns {boolean}
*/
get connected() {
return this._connected;
}
/**
* Return if client is authenticated
* @returns {boolean}
*/
get authenticated() {
return this._authenticated;
}
/**
* Return negotiated protocol version
* @returns {string}
*/
get protocolVersion() {
return this._version;
}
/**
* Return the local port used by the client
* @returns {number}
*/
get localPort() {
return this._connection ? this._connection.localPort : 0;
}
constructor(options = {debug: false, fps: 0, encodings: [], debugLevel: 1}) {
super();
this._socketBuffer = new SocketBuffer();
this.resetState();
this.debug = options.debug || false;
this.debugLevel = options.debugLevel || 1;
this._fps = Number(options.fps) || 0;
// Calculate interval to meet configured FPS
this._timerInterval = this._fps > 0 ? 1000 / this._fps : 0;
// Default encodings
this.encodings = options.encodings && options.encodings.length ? options.encodings : [
encodings.copyRect,
encodings.zrle,
encodings.hextile,
encodings.raw,
encodings.pseudoDesktopSize
];
this._audioChannels = options.audioChannels || 2;
this._audioFrequency = options.audioFrequency || 22050;
this._rects = 0;
this._decoders = {};
this._decoders[encodings.raw] = new RawDecoder(this.debug, this.debugLevel);
// TODO: Implement tight encoding
// this._decoders[encodings.tight] = new tightDecoder();
this._decoders[encodings.zrle] = new ZrleDecoder(this.debug, this.debugLevel);
this._decoders[encodings.copyRect] = new CopyrectDecoder(this.debug, this.debugLevel);
this._decoders[encodings.hextile] = new HextileDecoder(this.debug, this.debugLevel);
if (this._timerInterval) {
this._fbTimer();
}
}
/**
* Timer used to limit the rate of frame update requests according to configured FPS
* @private
*/
_fbTimer() {
this._timerPointer = setTimeout(() => {
this._fbTimer();
if (this._firstFrameReceived && !this._processingFrame && this._fps > 0) {
this.requestFrameUpdate();
}
}, this._timerInterval)
}
/**
* Adjust the configured FPS
* @param fps {number} - Number of update requests send by second
*/
changeFps(fps) {
if (!Number.isNaN(fps)) {
this._fps = Number(fps);
this._timerInterval = this._fps > 0 ? 1000 / this._fps : 0;
if (this._timerPointer && !this._fps) {
// If FPS was zeroed stop the timer
clearTimeout(this._timerPointer);
this._timerPointer = null;
} else if (this._fps && !this._timerPointer) {
// If FPS was zero and is now set, start the timer
this._fbTimer();
}
} else {
throw new Error('Invalid FPS. Must be a number.');
}
}
/**
* Starts the connection with the VNC server
* @param options
*/
connect(options = {
host: '',
password: '',
set8BitColor: false,
port: 5900
}) {
if (!options.host) {
throw new Error('Host missing.');
}
if (options.password) {
this._password = options.password;
}
this._set8BitColor = options.set8BitColor || false;
this._connection = net.connect(options.port || 5900, options.host);
this._connection.on('connect', () => {
this._connected = true;
this.emit('connected');
});
this._connection.on('close', () => {
this.resetState();
this.emit('closed');
});
this._connection.on('timeout', () => {
this.emit('connectTimeout');
});
this._connection.on('error', (err) => {
this.emit('connectError', err);
})
this._connection.on('data', async (data) => {
this._log(data.toString(), true, 5);
this._socketBuffer.pushData(data);
if (this._processingFrame) {
return;
}
if (!this._handshaked) {
this._handleHandshake();
} else if (this._expectingChallenge) {
await this._handleAuthChallenge();
} else if (this._waitingServerInit) {
await this._handleServerInit();
} else {
await this._handleData();
}
});
}
/**
* Disconnect the client
*/
disconnect() {
if (this._connection) {
this._connection.end();
this.resetState();
this.emit('disconnected');
}
}
/**
* Request the server a frame update
* @param full - If the server should send all the frame buffer or just the last changes
* @param incremental - Incremental number for not full requests
* @param x - X position of the update area desired, usually 0
* @param y - Y position of the update area desired, usually 0
* @param width - Width of the update area desired, usually client width
* @param height - Height of the update area desired, usually client height
*/
requestFrameUpdate(full = false, incremental = 1, x = 0, y = 0, width = this.clientWidth, height = this.clientHeight) {
if ((this._frameBufferReady || full) && this._connection && !this._rects && this._encodingsSent && !this._requestSent) {
this._requestSent = true;
this._log('Requesting frame update.', true, 3);
// Request data
const message = new Buffer(10);
message.writeUInt8(3); // Message type
message.writeUInt8(full ? 0 : incremental, 1); // Incremental
message.writeUInt16BE(x, 2); // X-Position
message.writeUInt16BE(y, 4); // Y-Position
message.writeUInt16BE(width, 6); // Width
message.writeUInt16BE(height, 8); // Height
this.sendData(message);
this._frameBufferReady = true;
}
}
/**
* Handle handshake msg
* @private
*/
_handleHandshake() {
// Handshake, negotiating protocol version
this._log('Received: ' + this._socketBuffer.toString(), true, 2);
this._log(this._socketBuffer.buffer, true, 3);
if (this._socketBuffer.toString() === versionString.V3_003) {
this._log('Sending 3.3', true);
this.sendData(versionString.V3_003);
this._version = '3.3';
} else if (this._socketBuffer.toString() === versionString.V3_007) {
this._log('Sending 3.7', true);
this.sendData(versionString.V3_007);
this._version = '3.7';
} else if (this._socketBuffer.toString() === versionString.V3_008) {
this._log('Sending 3.8', true);
this.sendData(versionString.V3_008);
this._version = '3.8';
} else {
// Negotiating auth mechanism
this._handshaked = true;
if (this._socketBuffer.includes(0x02) && this._password) {
this._log('Password provided and server support VNC auth. Choosing VNC auth.', true);
this._expectingChallenge = true;
this.sendData(new Buffer.from([0x02]));
} else if (this._socketBuffer.includes(1)) {
this._log('Password not provided or server does not support VNC auth. Trying none.', true);
this.sendData(new Buffer.from([0x01]));
if (this._version === '3.7') {
this._sendClientInit();
} else {
this._expectingChallenge = true;
this._challengeResponseSent = true;
}
} else {
this._log('Connection error. Msg: ' + this._socketBuffer.toString());
this.disconnect();
}
}
}
/**
* Send data to the server
* @param data
* @param flush - If true, flush the local buffer before sending
*/
sendData(data, flush = true) {
if (flush) {
this._socketBuffer.flush(false);
}
this._connection.write(data);
}
/**
* Handle VNC auth challenge
* @private
*/
async _handleAuthChallenge() {
if (this._challengeResponseSent) {
// Challenge response already sent. Checking result.
if (this._socketBuffer.readUInt32BE() === 0) {
// Auth success
this._log('Authenticated successfully', true);
this._authenticated = true;
this.emit('authenticated');
this._expectingChallenge = false;
this._sendClientInit();
} else {
// Auth fail
this._log('Authentication failed', true);
this.emit('authError');
this.resetState();
}
} else {
this._log('Challenge received.', true);
await this._socketBuffer.waitBytes(16, 'Auth challenge');
const key = new Buffer(8);
key.fill(0);
key.write(this._password.slice(0, 8));
this.reverseBits(key);
const des1 = crypto.createCipheriv('des', key, new Buffer(8));
const des2 = crypto.createCipheriv('des', key, new Buffer(8));
const response = new Buffer(16);
response.fill(des1.update(this._socketBuffer.buffer.slice(0, 8)), 0, 8);
response.fill(des2.update(this._socketBuffer.buffer.slice(8, 16)), 8, 16);
this._log('Sending response: ' + response.toString(), true, 2);
this.sendData(response);
this._challengeResponseSent = true;
}
}
/**
* Reverse bits order of a byte
* @param buf - Buffer to be flipped
*/
reverseBits(buf) {
for (let x = 0; x < buf.length; x++) {
let newByte = 0;
newByte += buf[x] & 128 ? 1 : 0;
newByte += buf[x] & 64 ? 2 : 0;
newByte += buf[x] & 32 ? 4 : 0;
newByte += buf[x] & 16 ? 8 : 0;
newByte += buf[x] & 8 ? 16 : 0;
newByte += buf[x] & 4 ? 32 : 0;
newByte += buf[x] & 2 ? 64 : 0;
newByte += buf[x] & 1 ? 128 : 0;
buf[x] = newByte;
}
}
/**
* Handle server init msg
* @returns {Promise<void>}
* @private
*/
async _handleServerInit() {
this._waitingServerInit = false;
await this._socketBuffer.waitBytes(24, 'Server init');
this.clientWidth = this._socketBuffer.readUInt16BE();
this.clientHeight = this._socketBuffer.readUInt16BE();
this.pixelFormat.bitsPerPixel = this._socketBuffer.readUInt8();
this.pixelFormat.depth = this._socketBuffer.readUInt8();
this.pixelFormat.bigEndianFlag = this._socketBuffer.readUInt8();
this.pixelFormat.trueColorFlag = this._socketBuffer.readUInt8();
this.pixelFormat.redMax = this.bigEndianFlag ? this._socketBuffer.readUInt16BE() : this._socketBuffer.readUInt16LE();
this.pixelFormat.greenMax = this.bigEndianFlag ? this._socketBuffer.readUInt16BE() : this._socketBuffer.readUInt16LE();
this.pixelFormat.blueMax = this.bigEndianFlag ? this._socketBuffer.readUInt16BE() : this._socketBuffer.readUInt16LE();
this.pixelFormat.redShift = this._socketBuffer.readInt8() / 8;
this.pixelFormat.greenShift = this._socketBuffer.readInt8() / 8;
this.pixelFormat.blueShift = this._socketBuffer.readInt8() / 8;
// Padding
this._socketBuffer.offset += 3;
this.updateFbSize();
const nameSize = this._socketBuffer.readUInt32BE();
await this._socketBuffer.waitBytes(nameSize, 'Name Size');
this.clientName = this._socketBuffer.readNBytesOffset(nameSize).toString();
this._log(`Screen size: ${this.clientWidth}x${this.clientHeight}`);
this._log(`Client name: ${this.clientName}`);
this._log(`pixelFormat: ${JSON.stringify(this.pixelFormat)}`);
if (this._set8BitColor) {
this._log(`8 bit color format requested, only raw encoding is supported.`);
this._setPixelFormatToColorMap();
}
this._sendEncodings();
setTimeout(() => {
this.requestFrameUpdate(true);
}, 1000);
}
/**
* Update the frame buffer size according to client width and height (RGBA)
*/
updateFbSize() {
this._log(`Updating the frame buffer size.`, true);
this.fb = new Buffer(this.clientWidth * this.clientHeight * 4);
}
/**
* Request the server to change to 8bit color format (Color palette). Only works with Raw encoding.
* @private
*/
_setPixelFormatToColorMap() {
this._log(`Requesting PixelFormat change to ColorMap (8 bits).`);
const message = new Buffer(20);
message.writeUInt8(0); // Tipo da mensagem
message.writeUInt8(0, 1); // Padding
message.writeUInt8(0, 2); // Padding
message.writeUInt8(0, 3); // Padding
message.writeUInt8(8, 4); // PixelFormat - BitsPerPixel
message.writeUInt8(8, 5); // PixelFormat - Depth
message.writeUInt8(0, 6); // PixelFormat - BigEndianFlag
message.writeUInt8(0, 7); // PixelFormat - TrueColorFlag
message.writeUInt16BE(255, 8); // PixelFormat - RedMax
message.writeUInt16BE(255, 10); // PixelFormat - GreenMax
message.writeUInt16BE(255, 12); // PixelFormat - BlueMax
message.writeUInt8(0, 14); // PixelFormat - RedShift
message.writeUInt8(8, 15); // PixelFormat - GreenShift
message.writeUInt8(16, 16); // PixelFormat - BlueShift
message.writeUInt8(0, 17); // PixelFormat - Padding
message.writeUInt8(0, 18); // PixelFormat - Padding
message.writeUInt8(0, 19); // PixelFormat - Padding
// Send a request to change pixelFormat to colorMap
this.sendData(message);
this.pixelFormat.bitsPerPixel = 8;
this.pixelFormat.depth = 8;
}
/**
* Send supported encodings
* @private
*/
_sendEncodings() {
this._log('Sending encodings.');
this._encodingsSent = true;
// If this._set8BitColor is set, only copyrect and raw encodings are supported
const message = new Buffer(4 + ((!this._set8BitColor ? this.encodings.length : 2) * 4));
message.writeUInt8(2); // Message type
message.writeUInt8(0, 1); // Padding
message.writeUInt16BE(!this._set8BitColor ? this.encodings.length : 2, 2); // Padding
let offset = 4;
// If 8bits is not set, send all encodings configured
if (!this._set8BitColor) {
for (const e of this.encodings) {
message.writeInt32BE(e, offset);
offset += 4;
}
} else {
message.writeInt32BE(encodings.copyRect, offset);
message.writeInt32BE(encodings.raw, offset + 4);
}
this.sendData(message);
}
/**
* Send client init msg
* @private
*/
_sendClientInit() {
this._log(`Sending clientInit`);
this._waitingServerInit = true;
// Shared bit set
this.sendData(new Buffer.from([1]));
}
/**
* Handle data msg
* @returns {Promise<void>}
* @private
*/
async _handleData() {
if (!this._rects) {
switch (this._socketBuffer.buffer[0]) {
case serverMsgTypes.fbUpdate:
await this._handleFbUpdate();
break;
case serverMsgTypes.setColorMap:
await this._handleSetColorMap();
break;
case serverMsgTypes.bell:
this.emit('bell');
this._socketBuffer.flush();
break;
case serverMsgTypes.cutText:
await this._handleCutText();
break;
case serverMsgTypes.qemuAudio:
await this._handleQemuAudio();
break;
}
}
}
/**
* Cut message (text was copied to clipboard on server)
* @returns {Promise<void>}
* @private
*/
async _handleCutText() {
this._socketBuffer.setOffset(4);
await this._socketBuffer.waitBytes(1, 'Cut text size');
const length = this._socketBuffer.readUInt32BE();
await this._socketBuffer.waitBytes(length, 'Cut text data');
this.emit('cutText', this._socketBuffer.readNBytesOffset(length).toString());
this._socketBuffer.flush();
}
/**
* Handle a rects of update message
*/
async _handleRect() {
const sendFbUpdate = this._rects;
this._processingFrame = true;
while (this._rects) {
await this._socketBuffer.waitBytes(12, 'Rect begin');
const rect = {};
rect.x = this._socketBuffer.readUInt16BE();
rect.y = this._socketBuffer.readUInt16BE();
rect.width = this._socketBuffer.readUInt16BE();
rect.height = this._socketBuffer.readUInt16BE();
rect.encoding = this._socketBuffer.readInt32BE();
if (rect.encoding === encodings.pseudoQemuAudio) {
this.sendAudio(true);
this.sendAudioConfig(this._audioChannels, this._audioFrequency);//todo: future: setFrequency(...) to update mid thing
} else if (rect.encoding === encodings.pseudoQemuPointerMotionChange) {
this._relativePointer = rect.x == 0;
} else if (rect.encoding === encodings.pseudoCursor) {
const dataSize = rect.width * rect.height * (this.pixelFormat.bitsPerPixel / 8);
const bitmaskSize = Math.floor((rect.width + 7) / 8) * rect.height;
this._cursor.width = rect.width;
this._cursor.height = rect.height;
this._cursor.x = rect.x;
this._cursor.y = rect.y;
this._cursor.cursorPixels = this._socketBuffer.readNBytesOffset(dataSize);
this._cursor.bitmask = this._socketBuffer.readNBytesOffset(bitmaskSize);
rect.data = Buffer.concat([this._cursor.cursorPixels, this._cursor.bitmask]);
} else if (rect.encoding === encodings.pseudoDesktopSize) {
this._log('Frame Buffer size change requested by the server', true);
this.clientHeight = rect.height;
this.clientWidth = rect.width;
this.updateFbSize();
this.emit('desktopSizeChanged', {width: this.clientWidth, height: this.clientHeight});
} else if (this._decoders[rect.encoding]) {
await this._decoders[rect.encoding].decode(rect, this.fb, this.pixelFormat.bitsPerPixel, this._colorMap, this.clientWidth, this.clientHeight, this._socketBuffer, this.pixelFormat.depth, this.pixelFormat.redShift, this.pixelFormat.greenShift, this.pixelFormat.blueShift);
} else {
this._log('Non supported update received. Encoding: ' + rect.encoding);
}
this._rects--;
this.emit('rectProcessed', rect);
//
// if (!this._rects) {
// this._socketBuffer.flush(true);
// }
}
if (sendFbUpdate) {
if (!this._firstFrameReceived) {
this._firstFrameReceived = true;
this.emit('firstFrameUpdate', this.fb);
}
this._log('Frame buffer updated.', true, 2);
this.emit('frameUpdated', this.fb);
}
this._processingFrame = false;
if (this._fps === 0) {
// If FPS is not set, request a new update as soon as the last received has been processed
this.requestFrameUpdate();
}
}
async _handleFbUpdate() {
this._socketBuffer.setOffset(2);
this._rects = this._socketBuffer.readUInt16BE();
this._log('Frame update received. Rects: ' + this._rects, true);
await this._handleRect();
this._requestSent = false;
}
/**
* Handle setColorMap msg
* @returns {Promise<void>}
* @private
*/
async _handleSetColorMap() {
this._socketBuffer.setOffset(2);
let firstColor = this._socketBuffer.readUInt16BE();
const numColors = this._socketBuffer.readUInt16BE();
this._log(`ColorMap received. Colors: ${numColors}.`);
await this._socketBuffer.waitBytes(numColors * 6, 'Colormap data');
for (let x = 0; x < numColors; x++) {
this._colorMap[firstColor] = this._socketBuffer.readRgbColorMap(this.pixelFormat.redShift, this.pixelFormat.greenShift, this.pixelFormat.blueShift, this.pixelFormat.redMax, this.pixelFormat.greenMax, this.pixelFormat.blueMax);
firstColor++;
}
this.emit('colorMapUpdated', this._colorMap);
this._socketBuffer.flush();
}
async _handleQemuAudio() {
this._socketBuffer.setOffset(2);
let operation = this._socketBuffer.readUInt16BE();
if (operation == 2) {
const length = this._socketBuffer.readUInt32BE();
//this._log(`Audio received. Length: ${length}.`);
await this._socketBuffer.waitBytes(length);
let audioBuffer = [];
for (let i = 0; i < length / 2; i++) audioBuffer.push(this._socketBuffer.readUInt16BE());
this._audioData = audioBuffer;
}
this.emit('audioStream', this._audioData);
this._socketBuffer.flush();
}
/**
* Reset the class state
*/
resetState() {
if (this._connection) {
this._connection.end();
}
if (this._timerPointer) {
clearInterval(this._timerPointer);
}
this._timerPointer = null;
this._connection = null;
this._connected = false;
this._authenticated = false;
this._version = '';
this._password = '';
this._audioChannels = 2;
this._audioFrequency = 22050;
this._handshaked = false;
this._expectingChallenge = false;
this._challengeResponseSent = false;
this._frameBufferReady = false;
this._firstFrameReceived = false;
this._processingFrame = false;
this._requestSent = false;
this._encodingsSent = false;
this.clientWidth = 0;
this.clientHeight = 0;
this.clientName = '';
this.pixelFormat = {
bitsPerPixel: 0,
depth: 0,
bigEndianFlag: 0,
trueColorFlag: 0,
redMax: 0,
greenMax: 0,
blueMax: 0,
redShift: 0,
blueShift: 0,
greenShift: 0
}
this._rects = 0
this._colorMap = [];
this._audioData = [];
this.fb = null;
this._socketBuffer?.flush(false);
this._cursor = {
width: 0,
height: 0,
x: 0,
y: 0,
cursorPixels: null,
bitmask: null,
posX: 0,
posY: 0
}
}
/**
* Get the frame buffer with de cursor printed to it if using Cursor Pseudo Encoding
* @returns {null|Buffer|*}
*/
getFb() {
if (!this._cursor.width) {
// If there is no cursor, just return de framebuffer
return this.fb;
} else {
// If there is a cursor, draw a cursor on the framebuffer and return the final result
const tempFb = new Buffer.from(this.fb);
for (let h = 0; h < this._cursor.height; h++) {
for (let w = 0; w < this._cursor.width; w++) {
const fbBytePosOffset = this._getPixelBytePos(this._cursor.posX + w, this._cursor.posY + h, this.clientWidth, this.clientHeight);
const cursorBytePosOffset = this._getPixelBytePos(w, h, this._cursor.width, this._cursor.height);
const bitmapByte = this._cursor.bitmask.slice(Math.floor(cursorBytePosOffset / 4 / 8), Math.floor(cursorBytePosOffset / 4 / 8) + 1);
const bitmapBit = (cursorBytePosOffset / 4) % 8;
const activePixel = bitmapBit === 0 ? bitmapByte[0] & 128 : bitmapBit === 1 ? bitmapByte[0] & 64 :
bitmapBit === 2 ? bitmapByte[0] & 32 : bitmapBit === 3 ? bitmapByte[0] & 16 :
bitmapBit === 4 ? bitmapByte[0] & 8 : bitmapBit === 5 ? bitmapByte[0] & 4 :
bitmapBit === 6 ? bitmapByte[0] & 2 : bitmapByte[0] & 1;
if (activePixel) {
if (this.pixelFormat.bitsPerPixel === 8) {
const index = this._cursor.cursorPixels.readUInt8(cursorBytePosOffset);
const color = this._colorMap[index];
tempFb.writeIntBE(color, fbBytePosOffset, 4);
} else {
const bytesLength = this.pixelFormat.bitsPerPixel / 8;
const color = this._cursor.cursorPixels.readIntBE(cursorBytePosOffset, bytesLength);
tempFb.writeIntBE(color, fbBytePosOffset, bytesLength);
}
}
}
}
return tempFb;
}
}
_getPixelBytePos(x, y, width, height) {
return ((y * width) + x) * 4;
}
/**
* Send a key event
* @param key - Key code (keysym) defined by X Window System, check https://wiki.linuxquestions.org/wiki/List_of_keysyms
* @param down - True if the key is pressed, false if it is not
*/
sendKeyEvent(key, down = false) {
const message = new Buffer(8);
message.writeUInt8(clientMsgTypes.keyEvent); // Message type
message.writeUInt8(down ? 1 : 0, 1); // Down flag
message.writeUInt8(0, 2); // Padding
message.writeUInt8(0, 3); // Padding
message.writeUInt32BE(key, 4); // Key code
this.sendData(message, false);
}
/**
* Send pointer event (mouse or touch)
* @param xPosition - X Position
* @param yPosition - Y Position
* @param button1 - True for pressed, false for unpressed - Usually left mouse button
* @param button2 - True for pressed, false for unpressed - Usually middle mouse button
* @param button3 - True for pressed, false for unpressed - Usually right mouse button
* @param button4 - True for pressed, false for unpressed - Usually scroll up mouse event
* @param button5 - True for pressed, false for unpressed - Usually scroll down mouse event
* @param button6 - True for pressed, false for unpressed
* @param button7 - True for pressed, false for unpressed
* @param button8 - True for pressed, false for unpressed
*/
sendPointerEvent(xPosition, yPosition, button1 = false, button2 = false, button3 = false, button4 = false, button5 = false,
button6 = false, button7 = false, button8 = false) {
let buttonMask = 0;
buttonMask += button8 ? 128 : 0;
buttonMask += button7 ? 64 : 0;
buttonMask += button6 ? 32 : 0;
buttonMask += button5 ? 16 : 0;
buttonMask += button4 ? 8 : 0;
buttonMask += button3 ? 4 : 0;
buttonMask += button2 ? 2 : 0;
buttonMask += button1 ? 1 : 0;
const message = new Buffer(6);
message.writeUInt8(clientMsgTypes.pointerEvent); // Message type
message.writeUInt8(buttonMask, 1); // Button Mask
const reladd = this._relativePointer ? 0x7FFF : 0;
message.writeUInt16BE(xPosition + reladd, 2); // X Position
message.writeUInt16BE(yPosition + reladd, 4); // Y Position
this._cursor.posX = xPosition;
this._cursor.posY = yPosition;
this.sendData(message, false);
}
/**
* Send client cut message to server
* @param text - latin1 encoded
*/
clientCutText(text) {
const textBuffer = new Buffer.from(text, 'latin1');
const message = new Buffer(8 + textBuffer.length);
message.writeUInt8(clientMsgTypes.cutText); // Message type
message.writeUInt8(0, 1); // Padding
message.writeUInt8(0, 2); // Padding
message.writeUInt8(0, 3); // Padding
message.writeUInt32BE(textBuffer.length, 4); // Padding
textBuffer.copy(message, 8);
this.sendData(message, false);
}
sendAudio(enable) {
const message = new Buffer(4);
message.writeUInt8(clientMsgTypes.qemuAudio); // Message type
message.writeUInt8(1, 1); // Submessage Type
message.writeUInt16BE(enable ? 0 : 1, 2); // Operation
this.sendData(message);
}
sendAudioConfig(channels, frequency) {
const message = new Buffer(10);
message.writeUInt8(clientMsgTypes.qemuAudio); // Message type
message.writeUInt8(1, 1); // Submessage Type
message.writeUInt16BE(2, 2); // Operation
message.writeUInt8(0/*U8*/, 4); // Sample Format
message.writeUInt8(channels, 5); // Number of Channels
message.writeUInt32BE(frequency, 6); // Frequency
this.sendData(message);
}
/**
* Print log info
* @param text
* @param debug
* @param level
* @private
*/
_log(text, debug = false, level = 1) {
if (!debug || (debug && this.debug && level <= this.debugLevel)) {
console.log(text);
}
}
}
exports = module.exports = VncClient;