blob: da54c56b53cca04b6ae14e30c3e05286311a2586 [file] [log] [blame]
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +00001//
2// Copyright (C) 2001-2004 HorizonLive.com, Inc. All Rights Reserved.
3// Copyright (C) 2001-2006 Constantin Kaplinsky. All Rights Reserved.
4// Copyright (C) 2000 Tridia Corporation. All Rights Reserved.
5// Copyright (C) 1999 AT&T Laboratories Cambridge. All Rights Reserved.
6//
7// This is free software; you can redistribute it and/or modify
8// it under the terms of the GNU General Public License as published by
9// the Free Software Foundation; either version 2 of the License, or
10// (at your option) any later version.
11//
12// This software is distributed in the hope that it will be useful,
13// but WITHOUT ANY WARRANTY; without even the implied warranty of
14// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15// GNU General Public License for more details.
16//
17// You should have received a copy of the GNU General Public License
18// along with this software; if not, write to the Free Software
19// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
20// USA.
21//
22
23//
24// RfbProto.java
25//
26
Adam Tkacf53e62a2009-03-13 13:20:26 +000027package com.tigervnc.vncviewer;
Constantin Kaplinsky90d8a502008-04-14 09:45:50 +000028
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +000029import java.io.*;
30import java.awt.*;
31import java.awt.event.*;
32import java.net.Socket;
33import java.util.zip.*;
34
35class RfbProto {
36
37 final static String
38 versionMsg_3_3 = "RFB 003.003\n",
39 versionMsg_3_7 = "RFB 003.007\n",
40 versionMsg_3_8 = "RFB 003.008\n";
41
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +000042 // Security types
43 final static int
Adam Tkacea79b472010-11-11 11:47:11 +000044 SecTypeInvalid = 0,
45 SecTypeNone = 1,
46 SecTypeVncAuth = 2,
47 SecTypeTight = 16,
48 SecTypeVeNCrypt = 19,
49 SecTypePlain = 256,
50 SecTypeTLSNone = 257,
51 SecTypeTLSVnc = 258,
52 SecTypeTLSPlain = 259,
53 SecTypeX509None = 260,
54 SecTypeX509Vnc = 261,
55 SecTypeX509Plain = 262;
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +000056
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +000057 // VNC authentication results
58 final static int
59 VncAuthOK = 0,
60 VncAuthFailed = 1,
61 VncAuthTooMany = 2;
62
63 // Standard server-to-client messages
64 final static int
65 FramebufferUpdate = 0,
66 SetColourMapEntries = 1,
67 Bell = 2,
68 ServerCutText = 3;
69
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +000070 // Standard client-to-server messages
71 final static int
72 SetPixelFormat = 0,
73 FixColourMapEntries = 1,
74 SetEncodings = 2,
75 FramebufferUpdateRequest = 3,
76 KeyboardEvent = 4,
77 PointerEvent = 5,
78 ClientCutText = 6;
79
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +000080 // Supported encodings and pseudo-encodings
81 final static int
82 EncodingRaw = 0,
83 EncodingCopyRect = 1,
84 EncodingRRE = 2,
85 EncodingCoRRE = 4,
86 EncodingHextile = 5,
87 EncodingZlib = 6,
88 EncodingTight = 7,
89 EncodingZRLE = 16,
90 EncodingCompressLevel0 = 0xFFFFFF00,
91 EncodingQualityLevel0 = 0xFFFFFFE0,
92 EncodingXCursor = 0xFFFFFF10,
93 EncodingRichCursor = 0xFFFFFF11,
94 EncodingPointerPos = 0xFFFFFF18,
95 EncodingLastRect = 0xFFFFFF20,
96 EncodingNewFBSize = 0xFFFFFF21;
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +000097
98 final static int MaxNormalEncoding = 255;
99
100 // Contstants used in the Hextile decoder
101 final static int
102 HextileRaw = 1,
103 HextileBackgroundSpecified = 2,
104 HextileForegroundSpecified = 4,
105 HextileAnySubrects = 8,
106 HextileSubrectsColoured = 16;
107
108 // Contstants used in the Tight decoder
109 final static int TightMinToCompress = 12;
110 final static int
111 TightExplicitFilter = 0x04,
112 TightFill = 0x08,
113 TightJpeg = 0x09,
114 TightMaxSubencoding = 0x09,
115 TightFilterCopy = 0x00,
116 TightFilterPalette = 0x01,
117 TightFilterGradient = 0x02;
118
119
120 String host;
121 int port;
122 Socket sock;
123 OutputStream os;
124 SessionRecorder rec;
125 boolean inNormalProtocol = false;
126 VncViewer viewer;
127
128 // Input stream is declared private to make sure it can be accessed
129 // only via RfbProto methods. We have to do this because we want to
130 // count how many bytes were read.
131 private DataInputStream is;
132 private long numBytesRead = 0;
133 public long getNumBytesRead() { return numBytesRead; }
134
135 // Java on UNIX does not call keyPressed() on some keys, for example
136 // swedish keys To prevent our workaround to produce duplicate
137 // keypresses on JVMs that actually works, keep track of if
enikey2f0294e2008-12-24 08:18:54 +0000138 // keyPressed() for a "broken" key was called or not.
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +0000139 boolean brokenKeyPressed = false;
140
141 // This will be set to true on the first framebuffer update
142 // containing Zlib-, ZRLE- or Tight-encoded data.
143 boolean wereZlibUpdates = false;
144
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +0000145 // This fields are needed to show warnings about inefficiently saved
146 // sessions only once per each saved session file.
147 boolean zlibWarningShown;
148 boolean tightWarningShown;
149
150 // Before starting to record each saved session, we set this field
151 // to 0, and increment on each framebuffer update. We don't flush
enikey2f0294e2008-12-24 08:18:54 +0000152 // the SessionRecorder data into the file before the second update.
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +0000153 // This allows us to write initial framebuffer update with zero
154 // timestamp, to let the player show initial desktop before
155 // playback.
156 int numUpdatesInSession;
157
158 // Measuring network throughput.
159 boolean timing;
160 long timeWaitedIn100us;
161 long timedKbits;
162
163 // Protocol version and TightVNC-specific protocol options.
164 int serverMajor, serverMinor;
165 int clientMajor, clientMinor;
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +0000166
167 // If true, informs that the RFB socket was closed.
168 private boolean closed;
169
170 //
171 // Constructor. Make TCP connection to RFB server.
172 //
173
174 RfbProto(String h, int p, VncViewer v) throws IOException {
175 viewer = v;
176 host = h;
177 port = p;
178
179 if (viewer.socketFactory == null) {
180 sock = new Socket(host, port);
enikey17ac1812008-12-19 11:22:13 +0000181 sock.setTcpNoDelay(true);
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +0000182 } else {
183 try {
184 Class factoryClass = Class.forName(viewer.socketFactory);
185 SocketFactory factory = (SocketFactory)factoryClass.newInstance();
186 if (viewer.inAnApplet)
187 sock = factory.createSocket(host, port, viewer);
188 else
189 sock = factory.createSocket(host, port, viewer.mainArgs);
190 } catch(Exception e) {
191 e.printStackTrace();
192 throw new IOException(e.getMessage());
193 }
194 }
195 is = new DataInputStream(new BufferedInputStream(sock.getInputStream(),
196 16384));
197 os = sock.getOutputStream();
198
199 timing = false;
200 timeWaitedIn100us = 5;
201 timedKbits = 0;
202 }
203
204
205 synchronized void close() {
206 try {
207 sock.close();
208 closed = true;
209 System.out.println("RFB socket closed");
210 if (rec != null) {
211 rec.close();
212 rec = null;
213 }
214 } catch (Exception e) {
215 e.printStackTrace();
216 }
217 }
218
219 synchronized boolean closed() {
220 return closed;
221 }
222
223 //
224 // Read server's protocol version message
225 //
226
227 void readVersionMsg() throws Exception {
228
229 byte[] b = new byte[12];
230
231 readFully(b);
232
233 if ((b[0] != 'R') || (b[1] != 'F') || (b[2] != 'B') || (b[3] != ' ')
234 || (b[4] < '0') || (b[4] > '9') || (b[5] < '0') || (b[5] > '9')
235 || (b[6] < '0') || (b[6] > '9') || (b[7] != '.')
236 || (b[8] < '0') || (b[8] > '9') || (b[9] < '0') || (b[9] > '9')
237 || (b[10] < '0') || (b[10] > '9') || (b[11] != '\n'))
238 {
239 throw new Exception("Host " + host + " port " + port +
240 " is not an RFB server");
241 }
242
243 serverMajor = (b[4] - '0') * 100 + (b[5] - '0') * 10 + (b[6] - '0');
244 serverMinor = (b[8] - '0') * 100 + (b[9] - '0') * 10 + (b[10] - '0');
245
246 if (serverMajor < 3) {
247 throw new Exception("RFB server does not support protocol version 3");
248 }
249 }
250
251
252 //
253 // Write our protocol version message
254 //
255
256 void writeVersionMsg() throws IOException {
257 clientMajor = 3;
258 if (serverMajor > 3 || serverMinor >= 8) {
259 clientMinor = 8;
260 os.write(versionMsg_3_8.getBytes());
261 } else if (serverMinor >= 7) {
262 clientMinor = 7;
263 os.write(versionMsg_3_7.getBytes());
264 } else {
265 clientMinor = 3;
266 os.write(versionMsg_3_3.getBytes());
267 }
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +0000268 }
269
270
271 //
272 // Negotiate the authentication scheme.
273 //
274
275 int negotiateSecurity() throws Exception {
276 return (clientMinor >= 7) ?
277 selectSecurityType() : readSecurityType();
278 }
279
280 //
281 // Read security type from the server (protocol version 3.3).
282 //
283
284 int readSecurityType() throws Exception {
285 int secType = readU32();
286
287 switch (secType) {
288 case SecTypeInvalid:
289 readConnFailedReason();
290 return SecTypeInvalid; // should never be executed
291 case SecTypeNone:
292 case SecTypeVncAuth:
293 return secType;
294 default:
295 throw new Exception("Unknown security type from RFB server: " + secType);
296 }
297 }
298
299 //
300 // Select security type from the server's list (protocol versions 3.7/3.8).
301 //
302
303 int selectSecurityType() throws Exception {
304 int secType = SecTypeInvalid;
305
306 // Read the list of secutiry types.
307 int nSecTypes = readU8();
308 if (nSecTypes == 0) {
309 readConnFailedReason();
310 return SecTypeInvalid; // should never be executed
311 }
312 byte[] secTypes = new byte[nSecTypes];
313 readFully(secTypes);
314
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +0000315 // Find first supported security type.
316 for (int i = 0; i < nSecTypes; i++) {
Adam Tkac053597c2010-11-11 13:21:55 +0000317 if (secTypes[i] == SecTypeNone || secTypes[i] == SecTypeVncAuth
318 || secTypes[i] == SecTypeVeNCrypt) {
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +0000319 secType = secTypes[i];
320 break;
321 }
322 }
323
324 if (secType == SecTypeInvalid) {
325 throw new Exception("Server did not offer supported security type");
326 } else {
327 os.write(secType);
328 }
329
330 return secType;
331 }
332
Adam Tkac053597c2010-11-11 13:21:55 +0000333 int authenticateVeNCrypt() throws Exception {
334 int majorVersion = readU8();
335 int minorVersion = readU8();
336 int Version = (majorVersion << 8) | minorVersion;
337 if (Version < 0x0002) {
338 os.write(0);
339 os.write(0);
340 throw new Exception("Server reported an unsupported VeNCrypt version");
341 }
342 os.write(0);
343 os.write(2);
344 if (readU8() != 0)
345 throw new Exception("Server reported it could not support the VeNCrypt version");
346 int nSecTypes = readU8();
347 int[] secTypes = new int[nSecTypes];
348 for(int i = 0; i < nSecTypes; i++)
349 secTypes[i] = readU32();
350
351 for(int i = 0; i < nSecTypes; i++)
352 switch(secTypes[i])
353 {
354 case SecTypeNone:
355 case SecTypeVncAuth:
Adam Tkac6a663cd2010-11-11 14:06:42 +0000356 case SecTypePlain:
Adam Tkac4be9da82010-11-18 14:00:12 +0000357 case SecTypeTLSNone:
358 case SecTypeTLSVnc:
359 case SecTypeTLSPlain:
Adam Tkac28d83892010-11-18 14:17:49 +0000360 case SecTypeX509None:
361 case SecTypeX509Vnc:
362 case SecTypeX509Plain:
Adam Tkac053597c2010-11-11 13:21:55 +0000363 writeInt(secTypes[i]);
364 return secTypes[i];
365 }
366
367 throw new Exception("No valid VeNCrypt sub-type");
368 }
369
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +0000370 //
371 // Perform "no authentication".
372 //
373
374 void authenticateNone() throws Exception {
375 if (clientMinor >= 8)
376 readSecurityResult("No authentication");
377 }
378
379 //
380 // Perform standard VNC Authentication.
381 //
382
383 void authenticateVNC(String pw) throws Exception {
384 byte[] challenge = new byte[16];
385 readFully(challenge);
386
387 if (pw.length() > 8)
388 pw = pw.substring(0, 8); // Truncate to 8 chars
389
390 // Truncate password on the first zero byte.
391 int firstZero = pw.indexOf(0);
392 if (firstZero != -1)
393 pw = pw.substring(0, firstZero);
394
395 byte[] key = {0, 0, 0, 0, 0, 0, 0, 0};
396 System.arraycopy(pw.getBytes(), 0, key, 0, pw.length());
397
398 DesCipher des = new DesCipher(key);
399
400 des.encrypt(challenge, 0, challenge, 0);
401 des.encrypt(challenge, 8, challenge, 8);
402
403 os.write(challenge);
404
405 readSecurityResult("VNC authentication");
406 }
407
Adam Tkac4be9da82010-11-18 14:00:12 +0000408 void authenticateTLS() throws Exception {
409 TLSTunnel tunnel = new TLSTunnel(sock);
410 tunnel.setup (this);
411 }
412
Adam Tkac28d83892010-11-18 14:17:49 +0000413 void authenticateX509() throws Exception {
414 X509Tunnel tunnel = new X509Tunnel(sock);
415 tunnel.setup (this);
416 }
417
Adam Tkac6a663cd2010-11-11 14:06:42 +0000418 void authenticatePlain(String User, String Password) throws Exception {
419 byte[] user=User.getBytes();
420 byte[] password=Password.getBytes();
421 writeInt(user.length);
422 writeInt(password.length);
423 os.write(user);
424 os.write(password);
425
426 readSecurityResult("Plain authentication");
427 }
428
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +0000429 //
430 // Read security result.
431 // Throws an exception on authentication failure.
432 //
433
434 void readSecurityResult(String authType) throws Exception {
435 int securityResult = readU32();
436
437 switch (securityResult) {
438 case VncAuthOK:
439 System.out.println(authType + ": success");
440 break;
441 case VncAuthFailed:
442 if (clientMinor >= 8)
443 readConnFailedReason();
444 throw new Exception(authType + ": failed");
445 case VncAuthTooMany:
446 throw new Exception(authType + ": failed, too many tries");
447 default:
448 throw new Exception(authType + ": unknown result " + securityResult);
449 }
450 }
451
452 //
453 // Read the string describing the reason for a connection failure,
454 // and throw an exception.
455 //
456
457 void readConnFailedReason() throws Exception {
458 int reasonLen = readU32();
459 byte[] reason = new byte[reasonLen];
460 readFully(reason);
461 throw new Exception(new String(reason));
462 }
463
464 //
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +0000465 // Write a 32-bit integer into the output stream.
466 //
467
468 void writeInt(int value) throws IOException {
469 byte[] b = new byte[4];
470 b[0] = (byte) ((value >> 24) & 0xff);
471 b[1] = (byte) ((value >> 16) & 0xff);
472 b[2] = (byte) ((value >> 8) & 0xff);
473 b[3] = (byte) (value & 0xff);
474 os.write(b);
475 }
476
477 //
478 // Write the client initialisation message
479 //
480
481 void writeClientInit() throws IOException {
482 if (viewer.options.shareDesktop) {
483 os.write(1);
484 } else {
485 os.write(0);
486 }
487 viewer.options.disableShareDesktop();
488 }
489
490
491 //
492 // Read the server initialisation message
493 //
494
495 String desktopName;
496 int framebufferWidth, framebufferHeight;
497 int bitsPerPixel, depth;
498 boolean bigEndian, trueColour;
499 int redMax, greenMax, blueMax, redShift, greenShift, blueShift;
500
501 void readServerInit() throws IOException {
502 framebufferWidth = readU16();
503 framebufferHeight = readU16();
504 bitsPerPixel = readU8();
505 depth = readU8();
506 bigEndian = (readU8() != 0);
507 trueColour = (readU8() != 0);
508 redMax = readU16();
509 greenMax = readU16();
510 blueMax = readU16();
511 redShift = readU8();
512 greenShift = readU8();
513 blueShift = readU8();
514 byte[] pad = new byte[3];
515 readFully(pad);
516 int nameLength = readU32();
517 byte[] name = new byte[nameLength];
518 readFully(name);
519 desktopName = new String(name);
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +0000520 inNormalProtocol = true;
521 }
522
523
524 //
525 // Create session file and write initial protocol messages into it.
526 //
527
528 void startSession(String fname) throws IOException {
529 rec = new SessionRecorder(fname);
530 rec.writeHeader();
531 rec.write(versionMsg_3_3.getBytes());
532 rec.writeIntBE(SecTypeNone);
533 rec.writeShortBE(framebufferWidth);
534 rec.writeShortBE(framebufferHeight);
535 byte[] fbsServerInitMsg = {
536 32, 24, 0, 1, 0,
537 (byte)0xFF, 0, (byte)0xFF, 0, (byte)0xFF,
538 16, 8, 0, 0, 0, 0
539 };
540 rec.write(fbsServerInitMsg);
541 rec.writeIntBE(desktopName.length());
542 rec.write(desktopName.getBytes());
543 numUpdatesInSession = 0;
544
545 // FIXME: If there were e.g. ZRLE updates only, that should not
546 // affect recording of Zlib and Tight updates. So, actually
547 // we should maintain separate flags for Zlib, ZRLE and
548 // Tight, instead of one ``wereZlibUpdates'' variable.
549 //
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +0000550
551 zlibWarningShown = false;
552 tightWarningShown = false;
553 }
554
555 //
556 // Close session file.
557 //
558
559 void closeSession() throws IOException {
560 if (rec != null) {
561 rec.close();
562 rec = null;
563 }
564 }
565
566
567 //
568 // Set new framebuffer size
569 //
570
571 void setFramebufferSize(int width, int height) {
572 framebufferWidth = width;
573 framebufferHeight = height;
574 }
575
576
577 //
578 // Read the server message type
579 //
580
581 int readServerMessageType() throws IOException {
582 int msgType = readU8();
583
584 // If the session is being recorded:
585 if (rec != null) {
586 if (msgType == Bell) { // Save Bell messages in session files.
587 rec.writeByte(msgType);
588 if (numUpdatesInSession > 0)
589 rec.flush();
590 }
591 }
592
593 return msgType;
594 }
595
596
597 //
598 // Read a FramebufferUpdate message
599 //
600
601 int updateNRects;
602
603 void readFramebufferUpdate() throws IOException {
604 skipBytes(1);
605 updateNRects = readU16();
606
607 // If the session is being recorded:
608 if (rec != null) {
609 rec.writeByte(FramebufferUpdate);
610 rec.writeByte(0);
611 rec.writeShortBE(updateNRects);
612 }
613
614 numUpdatesInSession++;
615 }
616
enikey2f0294e2008-12-24 08:18:54 +0000617 //
618 // Returns true if encoding is not pseudo
619 //
620 // FIXME: Find better way to differ pseudo and real encodings
621 //
622
623 boolean isRealDecoderEncoding(int encoding) {
624 if ((encoding >= 1) && (encoding <= 16)) {
625 return true;
626 }
627 return false;
628 }
629
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +0000630 // Read a FramebufferUpdate rectangle header
631
632 int updateRectX, updateRectY, updateRectW, updateRectH, updateRectEncoding;
633
634 void readFramebufferUpdateRectHdr() throws Exception {
635 updateRectX = readU16();
636 updateRectY = readU16();
637 updateRectW = readU16();
638 updateRectH = readU16();
639 updateRectEncoding = readU32();
640
641 if (updateRectEncoding == EncodingZlib ||
642 updateRectEncoding == EncodingZRLE ||
643 updateRectEncoding == EncodingTight)
644 wereZlibUpdates = true;
645
646 // If the session is being recorded:
647 if (rec != null) {
648 if (numUpdatesInSession > 1)
649 rec.flush(); // Flush the output on each rectangle.
650 rec.writeShortBE(updateRectX);
651 rec.writeShortBE(updateRectY);
652 rec.writeShortBE(updateRectW);
653 rec.writeShortBE(updateRectH);
enikey2f0294e2008-12-24 08:18:54 +0000654
655 //
656 // If this is pseudo encoding or CopyRect that write encoding ID
657 // in this place. All real encoding ID will be written to record stream
658 // in decoder classes.
enikey2f0294e2008-12-24 08:18:54 +0000659
enikey7716b712008-12-25 11:45:52 +0000660 if (((!isRealDecoderEncoding(updateRectEncoding))) && (rec != null)) {
enikey2f0294e2008-12-24 08:18:54 +0000661 rec.writeIntBE(updateRectEncoding);
662 }
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +0000663 }
664
665 if (updateRectEncoding < 0 || updateRectEncoding > MaxNormalEncoding)
666 return;
667
668 if (updateRectX + updateRectW > framebufferWidth ||
669 updateRectY + updateRectH > framebufferHeight) {
670 throw new Exception("Framebuffer update rectangle too large: " +
671 updateRectW + "x" + updateRectH + " at (" +
672 updateRectX + "," + updateRectY + ")");
673 }
674 }
675
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +0000676 //
677 // Read a ServerCutText message
678 //
679
680 String readServerCutText() throws IOException {
681 skipBytes(3);
682 int len = readU32();
683 byte[] text = new byte[len];
684 readFully(text);
685 return new String(text);
686 }
687
688
689 //
690 // Read an integer in compact representation (1..3 bytes).
691 // Such format is used as a part of the Tight encoding.
692 // Also, this method records data if session recording is active and
693 // the viewer's recordFromBeginning variable is set to true.
694 //
695
696 int readCompactLen() throws IOException {
697 int[] portion = new int[3];
698 portion[0] = readU8();
699 int byteCount = 1;
700 int len = portion[0] & 0x7F;
701 if ((portion[0] & 0x80) != 0) {
702 portion[1] = readU8();
703 byteCount++;
704 len |= (portion[1] & 0x7F) << 7;
705 if ((portion[1] & 0x80) != 0) {
706 portion[2] = readU8();
707 byteCount++;
708 len |= (portion[2] & 0xFF) << 14;
709 }
710 }
711
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +0000712 return len;
713 }
714
715
716 //
717 // Write a FramebufferUpdateRequest message
718 //
719
720 void writeFramebufferUpdateRequest(int x, int y, int w, int h,
721 boolean incremental)
722 throws IOException
723 {
724 byte[] b = new byte[10];
725
726 b[0] = (byte) FramebufferUpdateRequest;
727 b[1] = (byte) (incremental ? 1 : 0);
728 b[2] = (byte) ((x >> 8) & 0xff);
729 b[3] = (byte) (x & 0xff);
730 b[4] = (byte) ((y >> 8) & 0xff);
731 b[5] = (byte) (y & 0xff);
732 b[6] = (byte) ((w >> 8) & 0xff);
733 b[7] = (byte) (w & 0xff);
734 b[8] = (byte) ((h >> 8) & 0xff);
735 b[9] = (byte) (h & 0xff);
736
737 os.write(b);
738 }
739
740
741 //
742 // Write a SetPixelFormat message
743 //
744
745 void writeSetPixelFormat(int bitsPerPixel, int depth, boolean bigEndian,
746 boolean trueColour,
747 int redMax, int greenMax, int blueMax,
748 int redShift, int greenShift, int blueShift)
749 throws IOException
750 {
751 byte[] b = new byte[20];
752
753 b[0] = (byte) SetPixelFormat;
754 b[4] = (byte) bitsPerPixel;
755 b[5] = (byte) depth;
756 b[6] = (byte) (bigEndian ? 1 : 0);
757 b[7] = (byte) (trueColour ? 1 : 0);
758 b[8] = (byte) ((redMax >> 8) & 0xff);
759 b[9] = (byte) (redMax & 0xff);
760 b[10] = (byte) ((greenMax >> 8) & 0xff);
761 b[11] = (byte) (greenMax & 0xff);
762 b[12] = (byte) ((blueMax >> 8) & 0xff);
763 b[13] = (byte) (blueMax & 0xff);
764 b[14] = (byte) redShift;
765 b[15] = (byte) greenShift;
766 b[16] = (byte) blueShift;
767
768 os.write(b);
769 }
770
771
772 //
773 // Write a FixColourMapEntries message. The values in the red, green and
774 // blue arrays are from 0 to 65535.
775 //
776
777 void writeFixColourMapEntries(int firstColour, int nColours,
778 int[] red, int[] green, int[] blue)
779 throws IOException
780 {
781 byte[] b = new byte[6 + nColours * 6];
782
783 b[0] = (byte) FixColourMapEntries;
784 b[2] = (byte) ((firstColour >> 8) & 0xff);
785 b[3] = (byte) (firstColour & 0xff);
786 b[4] = (byte) ((nColours >> 8) & 0xff);
787 b[5] = (byte) (nColours & 0xff);
788
789 for (int i = 0; i < nColours; i++) {
790 b[6 + i * 6] = (byte) ((red[i] >> 8) & 0xff);
791 b[6 + i * 6 + 1] = (byte) (red[i] & 0xff);
792 b[6 + i * 6 + 2] = (byte) ((green[i] >> 8) & 0xff);
793 b[6 + i * 6 + 3] = (byte) (green[i] & 0xff);
794 b[6 + i * 6 + 4] = (byte) ((blue[i] >> 8) & 0xff);
795 b[6 + i * 6 + 5] = (byte) (blue[i] & 0xff);
796 }
enikey2f0294e2008-12-24 08:18:54 +0000797
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +0000798 os.write(b);
799 }
800
801
802 //
803 // Write a SetEncodings message
804 //
805
806 void writeSetEncodings(int[] encs, int len) throws IOException {
807 byte[] b = new byte[4 + 4 * len];
808
809 b[0] = (byte) SetEncodings;
810 b[2] = (byte) ((len >> 8) & 0xff);
811 b[3] = (byte) (len & 0xff);
812
813 for (int i = 0; i < len; i++) {
814 b[4 + 4 * i] = (byte) ((encs[i] >> 24) & 0xff);
815 b[5 + 4 * i] = (byte) ((encs[i] >> 16) & 0xff);
816 b[6 + 4 * i] = (byte) ((encs[i] >> 8) & 0xff);
817 b[7 + 4 * i] = (byte) (encs[i] & 0xff);
818 }
819
820 os.write(b);
821 }
822
823
824 //
825 // Write a ClientCutText message
826 //
827
828 void writeClientCutText(String text) throws IOException {
829 byte[] b = new byte[8 + text.length()];
830
831 b[0] = (byte) ClientCutText;
832 b[4] = (byte) ((text.length() >> 24) & 0xff);
833 b[5] = (byte) ((text.length() >> 16) & 0xff);
834 b[6] = (byte) ((text.length() >> 8) & 0xff);
835 b[7] = (byte) (text.length() & 0xff);
836
837 System.arraycopy(text.getBytes(), 0, b, 8, text.length());
838
839 os.write(b);
840 }
841
842
843 //
844 // A buffer for putting pointer and keyboard events before being sent. This
enikey2f0294e2008-12-24 08:18:54 +0000845 // is to ensure that multiple RFB events generated from a single Java Event
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +0000846 // will all be sent in a single network packet. The maximum possible
847 // length is 4 modifier down events, a single key event followed by 4
848 // modifier up events i.e. 9 key events or 72 bytes.
849 //
850
851 byte[] eventBuf = new byte[72];
852 int eventBufLen;
853
854
855 // Useful shortcuts for modifier masks.
856
857 final static int CTRL_MASK = InputEvent.CTRL_MASK;
858 final static int SHIFT_MASK = InputEvent.SHIFT_MASK;
859 final static int META_MASK = InputEvent.META_MASK;
860 final static int ALT_MASK = InputEvent.ALT_MASK;
861
862
863 //
864 // Write a pointer event message. We may need to send modifier key events
865 // around it to set the correct modifier state.
866 //
867
868 int pointerMask = 0;
869
870 void writePointerEvent(MouseEvent evt) throws IOException {
871 int modifiers = evt.getModifiers();
872
873 int mask2 = 2;
874 int mask3 = 4;
875 if (viewer.options.reverseMouseButtons2And3) {
876 mask2 = 4;
877 mask3 = 2;
878 }
879
880 // Note: For some reason, AWT does not set BUTTON1_MASK on left
881 // button presses. Here we think that it was the left button if
882 // modifiers do not include BUTTON2_MASK or BUTTON3_MASK.
883
884 if (evt.getID() == MouseEvent.MOUSE_PRESSED) {
885 if ((modifiers & InputEvent.BUTTON2_MASK) != 0) {
886 pointerMask = mask2;
887 modifiers &= ~ALT_MASK;
888 } else if ((modifiers & InputEvent.BUTTON3_MASK) != 0) {
889 pointerMask = mask3;
890 modifiers &= ~META_MASK;
891 } else {
892 pointerMask = 1;
893 }
894 } else if (evt.getID() == MouseEvent.MOUSE_RELEASED) {
895 pointerMask = 0;
896 if ((modifiers & InputEvent.BUTTON2_MASK) != 0) {
897 modifiers &= ~ALT_MASK;
898 } else if ((modifiers & InputEvent.BUTTON3_MASK) != 0) {
899 modifiers &= ~META_MASK;
900 }
901 }
902
903 eventBufLen = 0;
904 writeModifierKeyEvents(modifiers);
905
906 int x = evt.getX();
907 int y = evt.getY();
908
909 if (x < 0) x = 0;
910 if (y < 0) y = 0;
911
912 eventBuf[eventBufLen++] = (byte) PointerEvent;
913 eventBuf[eventBufLen++] = (byte) pointerMask;
914 eventBuf[eventBufLen++] = (byte) ((x >> 8) & 0xff);
915 eventBuf[eventBufLen++] = (byte) (x & 0xff);
916 eventBuf[eventBufLen++] = (byte) ((y >> 8) & 0xff);
917 eventBuf[eventBufLen++] = (byte) (y & 0xff);
918
919 //
920 // Always release all modifiers after an "up" event
921 //
922
923 if (pointerMask == 0) {
924 writeModifierKeyEvents(0);
925 }
926
927 os.write(eventBuf, 0, eventBufLen);
928 }
929
930
931 //
932 // Write a key event message. We may need to send modifier key events
933 // around it to set the correct modifier state. Also we need to translate
934 // from the Java key values to the X keysym values used by the RFB protocol.
935 //
936
937 void writeKeyEvent(KeyEvent evt) throws IOException {
938
939 int keyChar = evt.getKeyChar();
940
941 //
942 // Ignore event if only modifiers were pressed.
943 //
944
945 // Some JVMs return 0 instead of CHAR_UNDEFINED in getKeyChar().
946 if (keyChar == 0)
947 keyChar = KeyEvent.CHAR_UNDEFINED;
948
949 if (keyChar == KeyEvent.CHAR_UNDEFINED) {
950 int code = evt.getKeyCode();
951 if (code == KeyEvent.VK_CONTROL || code == KeyEvent.VK_SHIFT ||
952 code == KeyEvent.VK_META || code == KeyEvent.VK_ALT)
953 return;
954 }
955
956 //
957 // Key press or key release?
958 //
959
960 boolean down = (evt.getID() == KeyEvent.KEY_PRESSED);
961
962 int key;
963 if (evt.isActionKey()) {
964
965 //
966 // An action key should be one of the following.
967 // If not then just ignore the event.
968 //
969
970 switch(evt.getKeyCode()) {
971 case KeyEvent.VK_HOME: key = 0xff50; break;
972 case KeyEvent.VK_LEFT: key = 0xff51; break;
973 case KeyEvent.VK_UP: key = 0xff52; break;
974 case KeyEvent.VK_RIGHT: key = 0xff53; break;
975 case KeyEvent.VK_DOWN: key = 0xff54; break;
976 case KeyEvent.VK_PAGE_UP: key = 0xff55; break;
977 case KeyEvent.VK_PAGE_DOWN: key = 0xff56; break;
978 case KeyEvent.VK_END: key = 0xff57; break;
979 case KeyEvent.VK_INSERT: key = 0xff63; break;
980 case KeyEvent.VK_F1: key = 0xffbe; break;
981 case KeyEvent.VK_F2: key = 0xffbf; break;
982 case KeyEvent.VK_F3: key = 0xffc0; break;
983 case KeyEvent.VK_F4: key = 0xffc1; break;
984 case KeyEvent.VK_F5: key = 0xffc2; break;
985 case KeyEvent.VK_F6: key = 0xffc3; break;
986 case KeyEvent.VK_F7: key = 0xffc4; break;
987 case KeyEvent.VK_F8: key = 0xffc5; break;
988 case KeyEvent.VK_F9: key = 0xffc6; break;
989 case KeyEvent.VK_F10: key = 0xffc7; break;
990 case KeyEvent.VK_F11: key = 0xffc8; break;
991 case KeyEvent.VK_F12: key = 0xffc9; break;
992 default:
993 return;
994 }
995
996 } else {
997
998 //
999 // A "normal" key press. Ordinary ASCII characters go straight through.
1000 // For CTRL-<letter>, CTRL is sent separately so just send <letter>.
1001 // Backspace, tab, return, escape and delete have special keysyms.
1002 // Anything else we ignore.
1003 //
1004
1005 key = keyChar;
1006
1007 if (key < 0x20) {
1008 if (evt.isControlDown()) {
1009 key += 0x60;
1010 } else {
1011 switch(key) {
1012 case KeyEvent.VK_BACK_SPACE: key = 0xff08; break;
1013 case KeyEvent.VK_TAB: key = 0xff09; break;
1014 case KeyEvent.VK_ENTER: key = 0xff0d; break;
1015 case KeyEvent.VK_ESCAPE: key = 0xff1b; break;
1016 }
1017 }
1018 } else if (key == 0x7f) {
1019 // Delete
1020 key = 0xffff;
1021 } else if (key > 0xff) {
1022 // JDK1.1 on X incorrectly passes some keysyms straight through,
1023 // so we do too. JDK1.1.4 seems to have fixed this.
1024 // The keysyms passed are 0xff00 .. XK_BackSpace .. XK_Delete
1025 // Also, we pass through foreign currency keysyms (0x20a0..0x20af).
1026 if ((key < 0xff00 || key > 0xffff) &&
1027 !(key >= 0x20a0 && key <= 0x20af))
1028 return;
1029 }
1030 }
1031
1032 // Fake keyPresses for keys that only generates keyRelease events
1033 if ((key == 0xe5) || (key == 0xc5) || // XK_aring / XK_Aring
1034 (key == 0xe4) || (key == 0xc4) || // XK_adiaeresis / XK_Adiaeresis
1035 (key == 0xf6) || (key == 0xd6) || // XK_odiaeresis / XK_Odiaeresis
1036 (key == 0xa7) || (key == 0xbd) || // XK_section / XK_onehalf
1037 (key == 0xa3)) { // XK_sterling
1038 // Make sure we do not send keypress events twice on platforms
1039 // with correct JVMs (those that actually report KeyPress for all
enikey2f0294e2008-12-24 08:18:54 +00001040 // keys)
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +00001041 if (down)
1042 brokenKeyPressed = true;
1043
1044 if (!down && !brokenKeyPressed) {
1045 // We've got a release event for this key, but haven't received
enikey2f0294e2008-12-24 08:18:54 +00001046 // a press. Fake it.
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +00001047 eventBufLen = 0;
1048 writeModifierKeyEvents(evt.getModifiers());
1049 writeKeyEvent(key, true);
1050 os.write(eventBuf, 0, eventBufLen);
1051 }
1052
1053 if (!down)
enikey2f0294e2008-12-24 08:18:54 +00001054 brokenKeyPressed = false;
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +00001055 }
1056
1057 eventBufLen = 0;
1058 writeModifierKeyEvents(evt.getModifiers());
1059 writeKeyEvent(key, down);
1060
1061 // Always release all modifiers after an "up" event
1062 if (!down)
1063 writeModifierKeyEvents(0);
1064
1065 os.write(eventBuf, 0, eventBufLen);
1066 }
1067
1068
1069 //
1070 // Add a raw key event with the given X keysym to eventBuf.
1071 //
1072
1073 void writeKeyEvent(int keysym, boolean down) {
1074 eventBuf[eventBufLen++] = (byte) KeyboardEvent;
1075 eventBuf[eventBufLen++] = (byte) (down ? 1 : 0);
1076 eventBuf[eventBufLen++] = (byte) 0;
1077 eventBuf[eventBufLen++] = (byte) 0;
1078 eventBuf[eventBufLen++] = (byte) ((keysym >> 24) & 0xff);
1079 eventBuf[eventBufLen++] = (byte) ((keysym >> 16) & 0xff);
1080 eventBuf[eventBufLen++] = (byte) ((keysym >> 8) & 0xff);
1081 eventBuf[eventBufLen++] = (byte) (keysym & 0xff);
1082 }
1083
1084
1085 //
1086 // Write key events to set the correct modifier state.
1087 //
1088
1089 int oldModifiers = 0;
1090
1091 void writeModifierKeyEvents(int newModifiers) {
1092 if ((newModifiers & CTRL_MASK) != (oldModifiers & CTRL_MASK))
1093 writeKeyEvent(0xffe3, (newModifiers & CTRL_MASK) != 0);
1094
1095 if ((newModifiers & SHIFT_MASK) != (oldModifiers & SHIFT_MASK))
1096 writeKeyEvent(0xffe1, (newModifiers & SHIFT_MASK) != 0);
1097
1098 if ((newModifiers & META_MASK) != (oldModifiers & META_MASK))
1099 writeKeyEvent(0xffe7, (newModifiers & META_MASK) != 0);
1100
1101 if ((newModifiers & ALT_MASK) != (oldModifiers & ALT_MASK))
1102 writeKeyEvent(0xffe9, (newModifiers & ALT_MASK) != 0);
1103
1104 oldModifiers = newModifiers;
1105 }
1106
1107
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +00001108 public void startTiming() {
1109 timing = true;
1110
1111 // Carry over up to 1s worth of previous rate for smoothing.
1112
1113 if (timeWaitedIn100us > 10000) {
1114 timedKbits = timedKbits * 10000 / timeWaitedIn100us;
1115 timeWaitedIn100us = 10000;
1116 }
1117 }
1118
1119 public void stopTiming() {
enikey2f0294e2008-12-24 08:18:54 +00001120 timing = false;
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +00001121 if (timeWaitedIn100us < timedKbits/2)
1122 timeWaitedIn100us = timedKbits/2; // upper limit 20Mbit/s
1123 }
1124
1125 public long kbitsPerSecond() {
1126 return timedKbits * 10000 / timeWaitedIn100us;
1127 }
1128
1129 public long timeWaited() {
1130 return timeWaitedIn100us;
1131 }
1132
1133 //
1134 // Methods for reading data via our DataInputStream member variable (is).
1135 //
1136 // In addition to reading data, the readFully() methods updates variables
1137 // used to estimate data throughput.
1138 //
1139
1140 public void readFully(byte b[]) throws IOException {
1141 readFully(b, 0, b.length);
1142 }
1143
1144 public void readFully(byte b[], int off, int len) throws IOException {
1145 long before = 0;
1146 if (timing)
1147 before = System.currentTimeMillis();
1148
1149 is.readFully(b, off, len);
1150
1151 if (timing) {
1152 long after = System.currentTimeMillis();
1153 long newTimeWaited = (after - before) * 10;
1154 int newKbits = len * 8 / 1000;
1155
1156 // limit rate to between 10kbit/s and 40Mbit/s
1157
1158 if (newTimeWaited > newKbits*1000) newTimeWaited = newKbits*1000;
1159 if (newTimeWaited < newKbits/4) newTimeWaited = newKbits/4;
1160
1161 timeWaitedIn100us += newTimeWaited;
1162 timedKbits += newKbits;
1163 }
1164
1165 numBytesRead += len;
1166 }
1167
1168 final int available() throws IOException {
1169 return is.available();
1170 }
1171
1172 // FIXME: DataInputStream::skipBytes() is not guaranteed to skip
1173 // exactly n bytes. Probably we don't want to use this method.
1174 final int skipBytes(int n) throws IOException {
1175 int r = is.skipBytes(n);
1176 numBytesRead += r;
1177 return r;
1178 }
1179
1180 final int readU8() throws IOException {
1181 int r = is.readUnsignedByte();
1182 numBytesRead++;
1183 return r;
1184 }
1185
1186 final int readU16() throws IOException {
1187 int r = is.readUnsignedShort();
1188 numBytesRead += 2;
1189 return r;
1190 }
1191
1192 final int readU32() throws IOException {
1193 int r = is.readInt();
1194 numBytesRead += 4;
1195 return r;
1196 }
Adam Tkac4be9da82010-11-18 14:00:12 +00001197
1198 public void setStreams(InputStream is_, OutputStream os_) {
1199 is = new DataInputStream(is_);
1200 os = os_;
1201 }
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +00001202}