blob: 5aa2af5e93048cdc0c5df9d7c6f785bf9fb4ee04 [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
Constantin Kaplinsky90d8a502008-04-14 09:45:50 +000027package com.tightvnc.vncviewer;
28
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
42 // Vendor signatures: standard VNC/RealVNC, TridiaVNC, and TightVNC
43 final static String
44 StandardVendor = "STDV",
45 TridiaVncVendor = "TRDV",
46 TightVncVendor = "TGHT";
47
48 // Security types
49 final static int
50 SecTypeInvalid = 0,
51 SecTypeNone = 1,
52 SecTypeVncAuth = 2,
53 SecTypeTight = 16;
54
55 // Supported tunneling types
56 final static int
57 NoTunneling = 0;
58 final static String
59 SigNoTunneling = "NOTUNNEL";
60
61 // Supported authentication types
62 final static int
63 AuthNone = 1,
64 AuthVNC = 2,
65 AuthUnixLogin = 129;
66 final static String
67 SigAuthNone = "NOAUTH__",
68 SigAuthVNC = "VNCAUTH_",
69 SigAuthUnixLogin = "ULGNAUTH";
70
71 // VNC authentication results
72 final static int
73 VncAuthOK = 0,
74 VncAuthFailed = 1,
75 VncAuthTooMany = 2;
76
77 // Standard server-to-client messages
78 final static int
79 FramebufferUpdate = 0,
80 SetColourMapEntries = 1,
81 Bell = 2,
82 ServerCutText = 3;
83
84 // Non-standard server-to-client messages
85 final static int
86 EndOfContinuousUpdates = 150;
87 final static String
88 SigEndOfContinuousUpdates = "CUS_EOCU";
89
90 // Standard client-to-server messages
91 final static int
92 SetPixelFormat = 0,
93 FixColourMapEntries = 1,
94 SetEncodings = 2,
95 FramebufferUpdateRequest = 3,
96 KeyboardEvent = 4,
97 PointerEvent = 5,
98 ClientCutText = 6;
99
100 // Non-standard client-to-server messages
Constantin Kaplinskyf7cb2bf2008-05-27 08:38:28 +0000101 final static int EnableContinuousUpdates = 150;
102 final static int VideoRectangleSelection = 151;
103 final static String SigEnableContinuousUpdates = "CUC_ENCU";
104 final static String SigVideoRectangleSelection = "VRECTSEL";
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +0000105
106 // Supported encodings and pseudo-encodings
107 final static int
108 EncodingRaw = 0,
109 EncodingCopyRect = 1,
110 EncodingRRE = 2,
111 EncodingCoRRE = 4,
112 EncodingHextile = 5,
113 EncodingZlib = 6,
114 EncodingTight = 7,
115 EncodingZRLE = 16,
116 EncodingCompressLevel0 = 0xFFFFFF00,
117 EncodingQualityLevel0 = 0xFFFFFFE0,
118 EncodingXCursor = 0xFFFFFF10,
119 EncodingRichCursor = 0xFFFFFF11,
120 EncodingPointerPos = 0xFFFFFF18,
121 EncodingLastRect = 0xFFFFFF20,
122 EncodingNewFBSize = 0xFFFFFF21;
123 final static String
124 SigEncodingRaw = "RAW_____",
125 SigEncodingCopyRect = "COPYRECT",
126 SigEncodingRRE = "RRE_____",
127 SigEncodingCoRRE = "CORRE___",
128 SigEncodingHextile = "HEXTILE_",
129 SigEncodingZlib = "ZLIB____",
130 SigEncodingTight = "TIGHT___",
131 SigEncodingZRLE = "ZRLE____",
132 SigEncodingCompressLevel0 = "COMPRLVL",
133 SigEncodingQualityLevel0 = "JPEGQLVL",
134 SigEncodingXCursor = "X11CURSR",
135 SigEncodingRichCursor = "RCHCURSR",
136 SigEncodingPointerPos = "POINTPOS",
137 SigEncodingLastRect = "LASTRECT",
138 SigEncodingNewFBSize = "NEWFBSIZ";
139
140 final static int MaxNormalEncoding = 255;
141
142 // Contstants used in the Hextile decoder
143 final static int
144 HextileRaw = 1,
145 HextileBackgroundSpecified = 2,
146 HextileForegroundSpecified = 4,
147 HextileAnySubrects = 8,
148 HextileSubrectsColoured = 16;
149
150 // Contstants used in the Tight decoder
151 final static int TightMinToCompress = 12;
152 final static int
153 TightExplicitFilter = 0x04,
154 TightFill = 0x08,
155 TightJpeg = 0x09,
156 TightMaxSubencoding = 0x09,
157 TightFilterCopy = 0x00,
158 TightFilterPalette = 0x01,
159 TightFilterGradient = 0x02;
160
161
162 String host;
163 int port;
164 Socket sock;
165 OutputStream os;
166 SessionRecorder rec;
167 boolean inNormalProtocol = false;
168 VncViewer viewer;
169
170 // Input stream is declared private to make sure it can be accessed
171 // only via RfbProto methods. We have to do this because we want to
172 // count how many bytes were read.
173 private DataInputStream is;
174 private long numBytesRead = 0;
175 public long getNumBytesRead() { return numBytesRead; }
176
177 // Java on UNIX does not call keyPressed() on some keys, for example
178 // swedish keys To prevent our workaround to produce duplicate
179 // keypresses on JVMs that actually works, keep track of if
180 // keyPressed() for a "broken" key was called or not.
181 boolean brokenKeyPressed = false;
182
183 // This will be set to true on the first framebuffer update
184 // containing Zlib-, ZRLE- or Tight-encoded data.
185 boolean wereZlibUpdates = false;
186
187 // This will be set to false if the startSession() was called after
188 // we have received at least one Zlib-, ZRLE- or Tight-encoded
189 // framebuffer update.
190 boolean recordFromBeginning = true;
191
192 // This fields are needed to show warnings about inefficiently saved
193 // sessions only once per each saved session file.
194 boolean zlibWarningShown;
195 boolean tightWarningShown;
196
197 // Before starting to record each saved session, we set this field
198 // to 0, and increment on each framebuffer update. We don't flush
199 // the SessionRecorder data into the file before the second update.
200 // This allows us to write initial framebuffer update with zero
201 // timestamp, to let the player show initial desktop before
202 // playback.
203 int numUpdatesInSession;
204
205 // Measuring network throughput.
206 boolean timing;
207 long timeWaitedIn100us;
208 long timedKbits;
209
210 // Protocol version and TightVNC-specific protocol options.
211 int serverMajor, serverMinor;
212 int clientMajor, clientMinor;
213 boolean protocolTightVNC;
214 CapsContainer tunnelCaps, authCaps;
215 CapsContainer serverMsgCaps, clientMsgCaps;
216 CapsContainer encodingCaps;
217
218 // "Continuous updates" is a TightVNC-specific feature that allows
219 // receiving framebuffer updates continuously, without sending update
220 // requests. The variables below track the state of this feature.
221 // Initially, continuous updates are disabled. They can be enabled
222 // by calling tryEnableContinuousUpdates() method, and only if this
223 // feature is supported by the server. To disable continuous updates,
224 // tryDisableContinuousUpdates() should be called.
225 private boolean continuousUpdatesActive = false;
226 private boolean continuousUpdatesEnding = false;
227
228 // If true, informs that the RFB socket was closed.
229 private boolean closed;
230
231 //
232 // Constructor. Make TCP connection to RFB server.
233 //
234
235 RfbProto(String h, int p, VncViewer v) throws IOException {
236 viewer = v;
237 host = h;
238 port = p;
239
240 if (viewer.socketFactory == null) {
241 sock = new Socket(host, port);
242 } else {
243 try {
244 Class factoryClass = Class.forName(viewer.socketFactory);
245 SocketFactory factory = (SocketFactory)factoryClass.newInstance();
246 if (viewer.inAnApplet)
247 sock = factory.createSocket(host, port, viewer);
248 else
249 sock = factory.createSocket(host, port, viewer.mainArgs);
250 } catch(Exception e) {
251 e.printStackTrace();
252 throw new IOException(e.getMessage());
253 }
254 }
255 is = new DataInputStream(new BufferedInputStream(sock.getInputStream(),
256 16384));
257 os = sock.getOutputStream();
258
259 timing = false;
260 timeWaitedIn100us = 5;
261 timedKbits = 0;
262 }
263
264
265 synchronized void close() {
266 try {
267 sock.close();
268 closed = true;
269 System.out.println("RFB socket closed");
270 if (rec != null) {
271 rec.close();
272 rec = null;
273 }
274 } catch (Exception e) {
275 e.printStackTrace();
276 }
277 }
278
279 synchronized boolean closed() {
280 return closed;
281 }
282
283 //
284 // Read server's protocol version message
285 //
286
287 void readVersionMsg() throws Exception {
288
289 byte[] b = new byte[12];
290
291 readFully(b);
292
293 if ((b[0] != 'R') || (b[1] != 'F') || (b[2] != 'B') || (b[3] != ' ')
294 || (b[4] < '0') || (b[4] > '9') || (b[5] < '0') || (b[5] > '9')
295 || (b[6] < '0') || (b[6] > '9') || (b[7] != '.')
296 || (b[8] < '0') || (b[8] > '9') || (b[9] < '0') || (b[9] > '9')
297 || (b[10] < '0') || (b[10] > '9') || (b[11] != '\n'))
298 {
299 throw new Exception("Host " + host + " port " + port +
300 " is not an RFB server");
301 }
302
303 serverMajor = (b[4] - '0') * 100 + (b[5] - '0') * 10 + (b[6] - '0');
304 serverMinor = (b[8] - '0') * 100 + (b[9] - '0') * 10 + (b[10] - '0');
305
306 if (serverMajor < 3) {
307 throw new Exception("RFB server does not support protocol version 3");
308 }
309 }
310
311
312 //
313 // Write our protocol version message
314 //
315
316 void writeVersionMsg() throws IOException {
317 clientMajor = 3;
318 if (serverMajor > 3 || serverMinor >= 8) {
319 clientMinor = 8;
320 os.write(versionMsg_3_8.getBytes());
321 } else if (serverMinor >= 7) {
322 clientMinor = 7;
323 os.write(versionMsg_3_7.getBytes());
324 } else {
325 clientMinor = 3;
326 os.write(versionMsg_3_3.getBytes());
327 }
328 protocolTightVNC = false;
329 initCapabilities();
330 }
331
332
333 //
334 // Negotiate the authentication scheme.
335 //
336
337 int negotiateSecurity() throws Exception {
338 return (clientMinor >= 7) ?
339 selectSecurityType() : readSecurityType();
340 }
341
342 //
343 // Read security type from the server (protocol version 3.3).
344 //
345
346 int readSecurityType() throws Exception {
347 int secType = readU32();
348
349 switch (secType) {
350 case SecTypeInvalid:
351 readConnFailedReason();
352 return SecTypeInvalid; // should never be executed
353 case SecTypeNone:
354 case SecTypeVncAuth:
355 return secType;
356 default:
357 throw new Exception("Unknown security type from RFB server: " + secType);
358 }
359 }
360
361 //
362 // Select security type from the server's list (protocol versions 3.7/3.8).
363 //
364
365 int selectSecurityType() throws Exception {
366 int secType = SecTypeInvalid;
367
368 // Read the list of secutiry types.
369 int nSecTypes = readU8();
370 if (nSecTypes == 0) {
371 readConnFailedReason();
372 return SecTypeInvalid; // should never be executed
373 }
374 byte[] secTypes = new byte[nSecTypes];
375 readFully(secTypes);
376
377 // Find out if the server supports TightVNC protocol extensions
378 for (int i = 0; i < nSecTypes; i++) {
379 if (secTypes[i] == SecTypeTight) {
380 protocolTightVNC = true;
381 os.write(SecTypeTight);
382 return SecTypeTight;
383 }
384 }
385
386 // Find first supported security type.
387 for (int i = 0; i < nSecTypes; i++) {
388 if (secTypes[i] == SecTypeNone || secTypes[i] == SecTypeVncAuth) {
389 secType = secTypes[i];
390 break;
391 }
392 }
393
394 if (secType == SecTypeInvalid) {
395 throw new Exception("Server did not offer supported security type");
396 } else {
397 os.write(secType);
398 }
399
400 return secType;
401 }
402
403 //
404 // Perform "no authentication".
405 //
406
407 void authenticateNone() throws Exception {
408 if (clientMinor >= 8)
409 readSecurityResult("No authentication");
410 }
411
412 //
413 // Perform standard VNC Authentication.
414 //
415
416 void authenticateVNC(String pw) throws Exception {
417 byte[] challenge = new byte[16];
418 readFully(challenge);
419
420 if (pw.length() > 8)
421 pw = pw.substring(0, 8); // Truncate to 8 chars
422
423 // Truncate password on the first zero byte.
424 int firstZero = pw.indexOf(0);
425 if (firstZero != -1)
426 pw = pw.substring(0, firstZero);
427
428 byte[] key = {0, 0, 0, 0, 0, 0, 0, 0};
429 System.arraycopy(pw.getBytes(), 0, key, 0, pw.length());
430
431 DesCipher des = new DesCipher(key);
432
433 des.encrypt(challenge, 0, challenge, 0);
434 des.encrypt(challenge, 8, challenge, 8);
435
436 os.write(challenge);
437
438 readSecurityResult("VNC authentication");
439 }
440
441 //
442 // Read security result.
443 // Throws an exception on authentication failure.
444 //
445
446 void readSecurityResult(String authType) throws Exception {
447 int securityResult = readU32();
448
449 switch (securityResult) {
450 case VncAuthOK:
451 System.out.println(authType + ": success");
452 break;
453 case VncAuthFailed:
454 if (clientMinor >= 8)
455 readConnFailedReason();
456 throw new Exception(authType + ": failed");
457 case VncAuthTooMany:
458 throw new Exception(authType + ": failed, too many tries");
459 default:
460 throw new Exception(authType + ": unknown result " + securityResult);
461 }
462 }
463
464 //
465 // Read the string describing the reason for a connection failure,
466 // and throw an exception.
467 //
468
469 void readConnFailedReason() throws Exception {
470 int reasonLen = readU32();
471 byte[] reason = new byte[reasonLen];
472 readFully(reason);
473 throw new Exception(new String(reason));
474 }
475
476 //
477 // Initialize capability lists (TightVNC protocol extensions).
478 //
479
480 void initCapabilities() {
481 tunnelCaps = new CapsContainer();
482 authCaps = new CapsContainer();
483 serverMsgCaps = new CapsContainer();
484 clientMsgCaps = new CapsContainer();
485 encodingCaps = new CapsContainer();
486
487 // Supported authentication methods
488 authCaps.add(AuthNone, StandardVendor, SigAuthNone,
489 "No authentication");
490 authCaps.add(AuthVNC, StandardVendor, SigAuthVNC,
491 "Standard VNC password authentication");
492
493 // Supported non-standard server-to-client messages
494 serverMsgCaps.add(EndOfContinuousUpdates, TightVncVendor,
495 SigEndOfContinuousUpdates,
496 "End of continuous updates notification");
497
498 // Supported non-standard client-to-server messages
499 clientMsgCaps.add(EnableContinuousUpdates, TightVncVendor,
500 SigEnableContinuousUpdates,
501 "Enable/disable continuous updates");
Constantin Kaplinskyf7cb2bf2008-05-27 08:38:28 +0000502 clientMsgCaps.add(VideoRectangleSelection, TightVncVendor,
503 SigVideoRectangleSelection,
504 "Select a rectangle to be treated as video");
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +0000505
506 // Supported encoding types
507 encodingCaps.add(EncodingCopyRect, StandardVendor,
508 SigEncodingCopyRect, "Standard CopyRect encoding");
509 encodingCaps.add(EncodingRRE, StandardVendor,
510 SigEncodingRRE, "Standard RRE encoding");
511 encodingCaps.add(EncodingCoRRE, StandardVendor,
512 SigEncodingCoRRE, "Standard CoRRE encoding");
513 encodingCaps.add(EncodingHextile, StandardVendor,
514 SigEncodingHextile, "Standard Hextile encoding");
515 encodingCaps.add(EncodingZRLE, StandardVendor,
516 SigEncodingZRLE, "Standard ZRLE encoding");
517 encodingCaps.add(EncodingZlib, TridiaVncVendor,
518 SigEncodingZlib, "Zlib encoding");
519 encodingCaps.add(EncodingTight, TightVncVendor,
520 SigEncodingTight, "Tight encoding");
521
522 // Supported pseudo-encoding types
523 encodingCaps.add(EncodingCompressLevel0, TightVncVendor,
524 SigEncodingCompressLevel0, "Compression level");
525 encodingCaps.add(EncodingQualityLevel0, TightVncVendor,
526 SigEncodingQualityLevel0, "JPEG quality level");
527 encodingCaps.add(EncodingXCursor, TightVncVendor,
528 SigEncodingXCursor, "X-style cursor shape update");
529 encodingCaps.add(EncodingRichCursor, TightVncVendor,
530 SigEncodingRichCursor, "Rich-color cursor shape update");
531 encodingCaps.add(EncodingPointerPos, TightVncVendor,
532 SigEncodingPointerPos, "Pointer position update");
533 encodingCaps.add(EncodingLastRect, TightVncVendor,
534 SigEncodingLastRect, "LastRect protocol extension");
535 encodingCaps.add(EncodingNewFBSize, TightVncVendor,
536 SigEncodingNewFBSize, "Framebuffer size change");
537 }
538
539 //
540 // Setup tunneling (TightVNC protocol extensions)
541 //
542
543 void setupTunneling() throws IOException {
544 int nTunnelTypes = readU32();
545 if (nTunnelTypes != 0) {
546 readCapabilityList(tunnelCaps, nTunnelTypes);
547
548 // We don't support tunneling yet.
549 writeInt(NoTunneling);
550 }
551 }
552
553 //
554 // Negotiate authentication scheme (TightVNC protocol extensions)
555 //
556
557 int negotiateAuthenticationTight() throws Exception {
558 int nAuthTypes = readU32();
559 if (nAuthTypes == 0)
560 return AuthNone;
561
562 readCapabilityList(authCaps, nAuthTypes);
563 for (int i = 0; i < authCaps.numEnabled(); i++) {
564 int authType = authCaps.getByOrder(i);
565 if (authType == AuthNone || authType == AuthVNC) {
566 writeInt(authType);
567 return authType;
568 }
569 }
570 throw new Exception("No suitable authentication scheme found");
571 }
572
573 //
574 // Read a capability list (TightVNC protocol extensions)
575 //
576
577 void readCapabilityList(CapsContainer caps, int count) throws IOException {
578 int code;
579 byte[] vendor = new byte[4];
580 byte[] name = new byte[8];
581 for (int i = 0; i < count; i++) {
582 code = readU32();
583 readFully(vendor);
584 readFully(name);
585 caps.enable(new CapabilityInfo(code, vendor, name));
586 }
587 }
588
589 //
590 // Write a 32-bit integer into the output stream.
591 //
592
593 void writeInt(int value) throws IOException {
594 byte[] b = new byte[4];
595 b[0] = (byte) ((value >> 24) & 0xff);
596 b[1] = (byte) ((value >> 16) & 0xff);
597 b[2] = (byte) ((value >> 8) & 0xff);
598 b[3] = (byte) (value & 0xff);
599 os.write(b);
600 }
601
602 //
603 // Write the client initialisation message
604 //
605
606 void writeClientInit() throws IOException {
607 if (viewer.options.shareDesktop) {
608 os.write(1);
609 } else {
610 os.write(0);
611 }
612 viewer.options.disableShareDesktop();
613 }
614
615
616 //
617 // Read the server initialisation message
618 //
619
620 String desktopName;
621 int framebufferWidth, framebufferHeight;
622 int bitsPerPixel, depth;
623 boolean bigEndian, trueColour;
624 int redMax, greenMax, blueMax, redShift, greenShift, blueShift;
625
626 void readServerInit() throws IOException {
627 framebufferWidth = readU16();
628 framebufferHeight = readU16();
629 bitsPerPixel = readU8();
630 depth = readU8();
631 bigEndian = (readU8() != 0);
632 trueColour = (readU8() != 0);
633 redMax = readU16();
634 greenMax = readU16();
635 blueMax = readU16();
636 redShift = readU8();
637 greenShift = readU8();
638 blueShift = readU8();
639 byte[] pad = new byte[3];
640 readFully(pad);
641 int nameLength = readU32();
642 byte[] name = new byte[nameLength];
643 readFully(name);
644 desktopName = new String(name);
645
646 // Read interaction capabilities (TightVNC protocol extensions)
647 if (protocolTightVNC) {
648 int nServerMessageTypes = readU16();
649 int nClientMessageTypes = readU16();
650 int nEncodingTypes = readU16();
651 readU16();
652 readCapabilityList(serverMsgCaps, nServerMessageTypes);
653 readCapabilityList(clientMsgCaps, nClientMessageTypes);
654 readCapabilityList(encodingCaps, nEncodingTypes);
655 }
656
657 if (!clientMsgCaps.isEnabled(EnableContinuousUpdates)) {
658 viewer.options.disableContUpdates();
659 }
660
661 inNormalProtocol = true;
662 }
663
664
665 //
666 // Create session file and write initial protocol messages into it.
667 //
668
669 void startSession(String fname) throws IOException {
670 rec = new SessionRecorder(fname);
671 rec.writeHeader();
672 rec.write(versionMsg_3_3.getBytes());
673 rec.writeIntBE(SecTypeNone);
674 rec.writeShortBE(framebufferWidth);
675 rec.writeShortBE(framebufferHeight);
676 byte[] fbsServerInitMsg = {
677 32, 24, 0, 1, 0,
678 (byte)0xFF, 0, (byte)0xFF, 0, (byte)0xFF,
679 16, 8, 0, 0, 0, 0
680 };
681 rec.write(fbsServerInitMsg);
682 rec.writeIntBE(desktopName.length());
683 rec.write(desktopName.getBytes());
684 numUpdatesInSession = 0;
685
686 // FIXME: If there were e.g. ZRLE updates only, that should not
687 // affect recording of Zlib and Tight updates. So, actually
688 // we should maintain separate flags for Zlib, ZRLE and
689 // Tight, instead of one ``wereZlibUpdates'' variable.
690 //
691 if (wereZlibUpdates)
692 recordFromBeginning = false;
693
694 zlibWarningShown = false;
695 tightWarningShown = false;
696 }
697
698 //
699 // Close session file.
700 //
701
702 void closeSession() throws IOException {
703 if (rec != null) {
704 rec.close();
705 rec = null;
706 }
707 }
708
709
710 //
711 // Set new framebuffer size
712 //
713
714 void setFramebufferSize(int width, int height) {
715 framebufferWidth = width;
716 framebufferHeight = height;
717 }
718
719
720 //
721 // Read the server message type
722 //
723
724 int readServerMessageType() throws IOException {
725 int msgType = readU8();
726
727 // If the session is being recorded:
728 if (rec != null) {
729 if (msgType == Bell) { // Save Bell messages in session files.
730 rec.writeByte(msgType);
731 if (numUpdatesInSession > 0)
732 rec.flush();
733 }
734 }
735
736 return msgType;
737 }
738
739
740 //
741 // Read a FramebufferUpdate message
742 //
743
744 int updateNRects;
745
746 void readFramebufferUpdate() throws IOException {
747 skipBytes(1);
748 updateNRects = readU16();
749
750 // If the session is being recorded:
751 if (rec != null) {
752 rec.writeByte(FramebufferUpdate);
753 rec.writeByte(0);
754 rec.writeShortBE(updateNRects);
755 }
756
757 numUpdatesInSession++;
758 }
759
760 // Read a FramebufferUpdate rectangle header
761
762 int updateRectX, updateRectY, updateRectW, updateRectH, updateRectEncoding;
763
764 void readFramebufferUpdateRectHdr() throws Exception {
765 updateRectX = readU16();
766 updateRectY = readU16();
767 updateRectW = readU16();
768 updateRectH = readU16();
769 updateRectEncoding = readU32();
770
771 if (updateRectEncoding == EncodingZlib ||
772 updateRectEncoding == EncodingZRLE ||
773 updateRectEncoding == EncodingTight)
774 wereZlibUpdates = true;
775
776 // If the session is being recorded:
777 if (rec != null) {
778 if (numUpdatesInSession > 1)
779 rec.flush(); // Flush the output on each rectangle.
780 rec.writeShortBE(updateRectX);
781 rec.writeShortBE(updateRectY);
782 rec.writeShortBE(updateRectW);
783 rec.writeShortBE(updateRectH);
784 if (updateRectEncoding == EncodingZlib && !recordFromBeginning) {
785 // Here we cannot write Zlib-encoded rectangles because the
786 // decoder won't be able to reproduce zlib stream state.
787 if (!zlibWarningShown) {
788 System.out.println("Warning: Raw encoding will be used " +
789 "instead of Zlib in recorded session.");
790 zlibWarningShown = true;
791 }
792 rec.writeIntBE(EncodingRaw);
793 } else {
794 rec.writeIntBE(updateRectEncoding);
795 if (updateRectEncoding == EncodingTight && !recordFromBeginning &&
796 !tightWarningShown) {
797 System.out.println("Warning: Re-compressing Tight-encoded " +
798 "updates for session recording.");
799 tightWarningShown = true;
800 }
801 }
802 }
803
804 if (updateRectEncoding < 0 || updateRectEncoding > MaxNormalEncoding)
805 return;
806
807 if (updateRectX + updateRectW > framebufferWidth ||
808 updateRectY + updateRectH > framebufferHeight) {
809 throw new Exception("Framebuffer update rectangle too large: " +
810 updateRectW + "x" + updateRectH + " at (" +
811 updateRectX + "," + updateRectY + ")");
812 }
813 }
814
815 // Read CopyRect source X and Y.
816
817 int copyRectSrcX, copyRectSrcY;
818
819 void readCopyRect() throws IOException {
820 copyRectSrcX = readU16();
821 copyRectSrcY = readU16();
822
823 // If the session is being recorded:
824 if (rec != null) {
825 rec.writeShortBE(copyRectSrcX);
826 rec.writeShortBE(copyRectSrcY);
827 }
828 }
829
830
831 //
832 // Read a ServerCutText message
833 //
834
835 String readServerCutText() throws IOException {
836 skipBytes(3);
837 int len = readU32();
838 byte[] text = new byte[len];
839 readFully(text);
840 return new String(text);
841 }
842
843
844 //
845 // Read an integer in compact representation (1..3 bytes).
846 // Such format is used as a part of the Tight encoding.
847 // Also, this method records data if session recording is active and
848 // the viewer's recordFromBeginning variable is set to true.
849 //
850
851 int readCompactLen() throws IOException {
852 int[] portion = new int[3];
853 portion[0] = readU8();
854 int byteCount = 1;
855 int len = portion[0] & 0x7F;
856 if ((portion[0] & 0x80) != 0) {
857 portion[1] = readU8();
858 byteCount++;
859 len |= (portion[1] & 0x7F) << 7;
860 if ((portion[1] & 0x80) != 0) {
861 portion[2] = readU8();
862 byteCount++;
863 len |= (portion[2] & 0xFF) << 14;
864 }
865 }
866
867 if (rec != null && recordFromBeginning)
868 for (int i = 0; i < byteCount; i++)
869 rec.writeByte(portion[i]);
870
871 return len;
872 }
873
874
875 //
876 // Write a FramebufferUpdateRequest message
877 //
878
879 void writeFramebufferUpdateRequest(int x, int y, int w, int h,
880 boolean incremental)
881 throws IOException
882 {
883 byte[] b = new byte[10];
884
885 b[0] = (byte) FramebufferUpdateRequest;
886 b[1] = (byte) (incremental ? 1 : 0);
887 b[2] = (byte) ((x >> 8) & 0xff);
888 b[3] = (byte) (x & 0xff);
889 b[4] = (byte) ((y >> 8) & 0xff);
890 b[5] = (byte) (y & 0xff);
891 b[6] = (byte) ((w >> 8) & 0xff);
892 b[7] = (byte) (w & 0xff);
893 b[8] = (byte) ((h >> 8) & 0xff);
894 b[9] = (byte) (h & 0xff);
895
896 os.write(b);
897 }
898
899
900 //
901 // Write a SetPixelFormat message
902 //
903
904 void writeSetPixelFormat(int bitsPerPixel, int depth, boolean bigEndian,
905 boolean trueColour,
906 int redMax, int greenMax, int blueMax,
907 int redShift, int greenShift, int blueShift)
908 throws IOException
909 {
910 byte[] b = new byte[20];
911
912 b[0] = (byte) SetPixelFormat;
913 b[4] = (byte) bitsPerPixel;
914 b[5] = (byte) depth;
915 b[6] = (byte) (bigEndian ? 1 : 0);
916 b[7] = (byte) (trueColour ? 1 : 0);
917 b[8] = (byte) ((redMax >> 8) & 0xff);
918 b[9] = (byte) (redMax & 0xff);
919 b[10] = (byte) ((greenMax >> 8) & 0xff);
920 b[11] = (byte) (greenMax & 0xff);
921 b[12] = (byte) ((blueMax >> 8) & 0xff);
922 b[13] = (byte) (blueMax & 0xff);
923 b[14] = (byte) redShift;
924 b[15] = (byte) greenShift;
925 b[16] = (byte) blueShift;
926
927 os.write(b);
928 }
929
930
931 //
932 // Write a FixColourMapEntries message. The values in the red, green and
933 // blue arrays are from 0 to 65535.
934 //
935
936 void writeFixColourMapEntries(int firstColour, int nColours,
937 int[] red, int[] green, int[] blue)
938 throws IOException
939 {
940 byte[] b = new byte[6 + nColours * 6];
941
942 b[0] = (byte) FixColourMapEntries;
943 b[2] = (byte) ((firstColour >> 8) & 0xff);
944 b[3] = (byte) (firstColour & 0xff);
945 b[4] = (byte) ((nColours >> 8) & 0xff);
946 b[5] = (byte) (nColours & 0xff);
947
948 for (int i = 0; i < nColours; i++) {
949 b[6 + i * 6] = (byte) ((red[i] >> 8) & 0xff);
950 b[6 + i * 6 + 1] = (byte) (red[i] & 0xff);
951 b[6 + i * 6 + 2] = (byte) ((green[i] >> 8) & 0xff);
952 b[6 + i * 6 + 3] = (byte) (green[i] & 0xff);
953 b[6 + i * 6 + 4] = (byte) ((blue[i] >> 8) & 0xff);
954 b[6 + i * 6 + 5] = (byte) (blue[i] & 0xff);
955 }
956
957 os.write(b);
958 }
959
960
961 //
962 // Write a SetEncodings message
963 //
964
965 void writeSetEncodings(int[] encs, int len) throws IOException {
966 byte[] b = new byte[4 + 4 * len];
967
968 b[0] = (byte) SetEncodings;
969 b[2] = (byte) ((len >> 8) & 0xff);
970 b[3] = (byte) (len & 0xff);
971
972 for (int i = 0; i < len; i++) {
973 b[4 + 4 * i] = (byte) ((encs[i] >> 24) & 0xff);
974 b[5 + 4 * i] = (byte) ((encs[i] >> 16) & 0xff);
975 b[6 + 4 * i] = (byte) ((encs[i] >> 8) & 0xff);
976 b[7 + 4 * i] = (byte) (encs[i] & 0xff);
977 }
978
979 os.write(b);
980 }
981
982
983 //
984 // Write a ClientCutText message
985 //
986
987 void writeClientCutText(String text) throws IOException {
988 byte[] b = new byte[8 + text.length()];
989
990 b[0] = (byte) ClientCutText;
991 b[4] = (byte) ((text.length() >> 24) & 0xff);
992 b[5] = (byte) ((text.length() >> 16) & 0xff);
993 b[6] = (byte) ((text.length() >> 8) & 0xff);
994 b[7] = (byte) (text.length() & 0xff);
995
996 System.arraycopy(text.getBytes(), 0, b, 8, text.length());
997
998 os.write(b);
999 }
1000
1001
1002 //
1003 // A buffer for putting pointer and keyboard events before being sent. This
1004 // is to ensure that multiple RFB events generated from a single Java Event
1005 // will all be sent in a single network packet. The maximum possible
1006 // length is 4 modifier down events, a single key event followed by 4
1007 // modifier up events i.e. 9 key events or 72 bytes.
1008 //
1009
1010 byte[] eventBuf = new byte[72];
1011 int eventBufLen;
1012
1013
1014 // Useful shortcuts for modifier masks.
1015
1016 final static int CTRL_MASK = InputEvent.CTRL_MASK;
1017 final static int SHIFT_MASK = InputEvent.SHIFT_MASK;
1018 final static int META_MASK = InputEvent.META_MASK;
1019 final static int ALT_MASK = InputEvent.ALT_MASK;
1020
1021
1022 //
1023 // Write a pointer event message. We may need to send modifier key events
1024 // around it to set the correct modifier state.
1025 //
1026
1027 int pointerMask = 0;
1028
1029 void writePointerEvent(MouseEvent evt) throws IOException {
1030 int modifiers = evt.getModifiers();
1031
1032 int mask2 = 2;
1033 int mask3 = 4;
1034 if (viewer.options.reverseMouseButtons2And3) {
1035 mask2 = 4;
1036 mask3 = 2;
1037 }
1038
1039 // Note: For some reason, AWT does not set BUTTON1_MASK on left
1040 // button presses. Here we think that it was the left button if
1041 // modifiers do not include BUTTON2_MASK or BUTTON3_MASK.
1042
1043 if (evt.getID() == MouseEvent.MOUSE_PRESSED) {
1044 if ((modifiers & InputEvent.BUTTON2_MASK) != 0) {
1045 pointerMask = mask2;
1046 modifiers &= ~ALT_MASK;
1047 } else if ((modifiers & InputEvent.BUTTON3_MASK) != 0) {
1048 pointerMask = mask3;
1049 modifiers &= ~META_MASK;
1050 } else {
1051 pointerMask = 1;
1052 }
1053 } else if (evt.getID() == MouseEvent.MOUSE_RELEASED) {
1054 pointerMask = 0;
1055 if ((modifiers & InputEvent.BUTTON2_MASK) != 0) {
1056 modifiers &= ~ALT_MASK;
1057 } else if ((modifiers & InputEvent.BUTTON3_MASK) != 0) {
1058 modifiers &= ~META_MASK;
1059 }
1060 }
1061
1062 eventBufLen = 0;
1063 writeModifierKeyEvents(modifiers);
1064
1065 int x = evt.getX();
1066 int y = evt.getY();
1067
1068 if (x < 0) x = 0;
1069 if (y < 0) y = 0;
1070
1071 eventBuf[eventBufLen++] = (byte) PointerEvent;
1072 eventBuf[eventBufLen++] = (byte) pointerMask;
1073 eventBuf[eventBufLen++] = (byte) ((x >> 8) & 0xff);
1074 eventBuf[eventBufLen++] = (byte) (x & 0xff);
1075 eventBuf[eventBufLen++] = (byte) ((y >> 8) & 0xff);
1076 eventBuf[eventBufLen++] = (byte) (y & 0xff);
1077
1078 //
1079 // Always release all modifiers after an "up" event
1080 //
1081
1082 if (pointerMask == 0) {
1083 writeModifierKeyEvents(0);
1084 }
1085
1086 os.write(eventBuf, 0, eventBufLen);
1087 }
1088
1089
1090 //
1091 // Write a key event message. We may need to send modifier key events
1092 // around it to set the correct modifier state. Also we need to translate
1093 // from the Java key values to the X keysym values used by the RFB protocol.
1094 //
1095
1096 void writeKeyEvent(KeyEvent evt) throws IOException {
1097
1098 int keyChar = evt.getKeyChar();
1099
1100 //
1101 // Ignore event if only modifiers were pressed.
1102 //
1103
1104 // Some JVMs return 0 instead of CHAR_UNDEFINED in getKeyChar().
1105 if (keyChar == 0)
1106 keyChar = KeyEvent.CHAR_UNDEFINED;
1107
1108 if (keyChar == KeyEvent.CHAR_UNDEFINED) {
1109 int code = evt.getKeyCode();
1110 if (code == KeyEvent.VK_CONTROL || code == KeyEvent.VK_SHIFT ||
1111 code == KeyEvent.VK_META || code == KeyEvent.VK_ALT)
1112 return;
1113 }
1114
1115 //
1116 // Key press or key release?
1117 //
1118
1119 boolean down = (evt.getID() == KeyEvent.KEY_PRESSED);
1120
1121 int key;
1122 if (evt.isActionKey()) {
1123
1124 //
1125 // An action key should be one of the following.
1126 // If not then just ignore the event.
1127 //
1128
1129 switch(evt.getKeyCode()) {
1130 case KeyEvent.VK_HOME: key = 0xff50; break;
1131 case KeyEvent.VK_LEFT: key = 0xff51; break;
1132 case KeyEvent.VK_UP: key = 0xff52; break;
1133 case KeyEvent.VK_RIGHT: key = 0xff53; break;
1134 case KeyEvent.VK_DOWN: key = 0xff54; break;
1135 case KeyEvent.VK_PAGE_UP: key = 0xff55; break;
1136 case KeyEvent.VK_PAGE_DOWN: key = 0xff56; break;
1137 case KeyEvent.VK_END: key = 0xff57; break;
1138 case KeyEvent.VK_INSERT: key = 0xff63; break;
1139 case KeyEvent.VK_F1: key = 0xffbe; break;
1140 case KeyEvent.VK_F2: key = 0xffbf; break;
1141 case KeyEvent.VK_F3: key = 0xffc0; break;
1142 case KeyEvent.VK_F4: key = 0xffc1; break;
1143 case KeyEvent.VK_F5: key = 0xffc2; break;
1144 case KeyEvent.VK_F6: key = 0xffc3; break;
1145 case KeyEvent.VK_F7: key = 0xffc4; break;
1146 case KeyEvent.VK_F8: key = 0xffc5; break;
1147 case KeyEvent.VK_F9: key = 0xffc6; break;
1148 case KeyEvent.VK_F10: key = 0xffc7; break;
1149 case KeyEvent.VK_F11: key = 0xffc8; break;
1150 case KeyEvent.VK_F12: key = 0xffc9; break;
1151 default:
1152 return;
1153 }
1154
1155 } else {
1156
1157 //
1158 // A "normal" key press. Ordinary ASCII characters go straight through.
1159 // For CTRL-<letter>, CTRL is sent separately so just send <letter>.
1160 // Backspace, tab, return, escape and delete have special keysyms.
1161 // Anything else we ignore.
1162 //
1163
1164 key = keyChar;
1165
1166 if (key < 0x20) {
1167 if (evt.isControlDown()) {
1168 key += 0x60;
1169 } else {
1170 switch(key) {
1171 case KeyEvent.VK_BACK_SPACE: key = 0xff08; break;
1172 case KeyEvent.VK_TAB: key = 0xff09; break;
1173 case KeyEvent.VK_ENTER: key = 0xff0d; break;
1174 case KeyEvent.VK_ESCAPE: key = 0xff1b; break;
1175 }
1176 }
1177 } else if (key == 0x7f) {
1178 // Delete
1179 key = 0xffff;
1180 } else if (key > 0xff) {
1181 // JDK1.1 on X incorrectly passes some keysyms straight through,
1182 // so we do too. JDK1.1.4 seems to have fixed this.
1183 // The keysyms passed are 0xff00 .. XK_BackSpace .. XK_Delete
1184 // Also, we pass through foreign currency keysyms (0x20a0..0x20af).
1185 if ((key < 0xff00 || key > 0xffff) &&
1186 !(key >= 0x20a0 && key <= 0x20af))
1187 return;
1188 }
1189 }
1190
1191 // Fake keyPresses for keys that only generates keyRelease events
1192 if ((key == 0xe5) || (key == 0xc5) || // XK_aring / XK_Aring
1193 (key == 0xe4) || (key == 0xc4) || // XK_adiaeresis / XK_Adiaeresis
1194 (key == 0xf6) || (key == 0xd6) || // XK_odiaeresis / XK_Odiaeresis
1195 (key == 0xa7) || (key == 0xbd) || // XK_section / XK_onehalf
1196 (key == 0xa3)) { // XK_sterling
1197 // Make sure we do not send keypress events twice on platforms
1198 // with correct JVMs (those that actually report KeyPress for all
1199 // keys)
1200 if (down)
1201 brokenKeyPressed = true;
1202
1203 if (!down && !brokenKeyPressed) {
1204 // We've got a release event for this key, but haven't received
1205 // a press. Fake it.
1206 eventBufLen = 0;
1207 writeModifierKeyEvents(evt.getModifiers());
1208 writeKeyEvent(key, true);
1209 os.write(eventBuf, 0, eventBufLen);
1210 }
1211
1212 if (!down)
1213 brokenKeyPressed = false;
1214 }
1215
1216 eventBufLen = 0;
1217 writeModifierKeyEvents(evt.getModifiers());
1218 writeKeyEvent(key, down);
1219
1220 // Always release all modifiers after an "up" event
1221 if (!down)
1222 writeModifierKeyEvents(0);
1223
1224 os.write(eventBuf, 0, eventBufLen);
1225 }
1226
1227
1228 //
1229 // Add a raw key event with the given X keysym to eventBuf.
1230 //
1231
1232 void writeKeyEvent(int keysym, boolean down) {
1233 eventBuf[eventBufLen++] = (byte) KeyboardEvent;
1234 eventBuf[eventBufLen++] = (byte) (down ? 1 : 0);
1235 eventBuf[eventBufLen++] = (byte) 0;
1236 eventBuf[eventBufLen++] = (byte) 0;
1237 eventBuf[eventBufLen++] = (byte) ((keysym >> 24) & 0xff);
1238 eventBuf[eventBufLen++] = (byte) ((keysym >> 16) & 0xff);
1239 eventBuf[eventBufLen++] = (byte) ((keysym >> 8) & 0xff);
1240 eventBuf[eventBufLen++] = (byte) (keysym & 0xff);
1241 }
1242
1243
1244 //
1245 // Write key events to set the correct modifier state.
1246 //
1247
1248 int oldModifiers = 0;
1249
1250 void writeModifierKeyEvents(int newModifiers) {
1251 if ((newModifiers & CTRL_MASK) != (oldModifiers & CTRL_MASK))
1252 writeKeyEvent(0xffe3, (newModifiers & CTRL_MASK) != 0);
1253
1254 if ((newModifiers & SHIFT_MASK) != (oldModifiers & SHIFT_MASK))
1255 writeKeyEvent(0xffe1, (newModifiers & SHIFT_MASK) != 0);
1256
1257 if ((newModifiers & META_MASK) != (oldModifiers & META_MASK))
1258 writeKeyEvent(0xffe7, (newModifiers & META_MASK) != 0);
1259
1260 if ((newModifiers & ALT_MASK) != (oldModifiers & ALT_MASK))
1261 writeKeyEvent(0xffe9, (newModifiers & ALT_MASK) != 0);
1262
1263 oldModifiers = newModifiers;
1264 }
1265
1266
1267 //
1268 // Enable continuous updates for the specified area of the screen (but
1269 // only if EnableContinuousUpdates message is supported by the server).
1270 //
1271
1272 void tryEnableContinuousUpdates(int x, int y, int w, int h)
1273 throws IOException
1274 {
1275 if (!clientMsgCaps.isEnabled(EnableContinuousUpdates)) {
1276 System.out.println("Continuous updates not supported by the server");
1277 return;
1278 }
1279
1280 if (continuousUpdatesActive) {
1281 System.out.println("Continuous updates already active");
1282 return;
1283 }
1284
1285 byte[] b = new byte[10];
1286
1287 b[0] = (byte) EnableContinuousUpdates;
1288 b[1] = (byte) 1; // enable
1289 b[2] = (byte) ((x >> 8) & 0xff);
1290 b[3] = (byte) (x & 0xff);
1291 b[4] = (byte) ((y >> 8) & 0xff);
1292 b[5] = (byte) (y & 0xff);
1293 b[6] = (byte) ((w >> 8) & 0xff);
1294 b[7] = (byte) (w & 0xff);
1295 b[8] = (byte) ((h >> 8) & 0xff);
1296 b[9] = (byte) (h & 0xff);
1297
1298 os.write(b);
1299
1300 continuousUpdatesActive = true;
1301 System.out.println("Continuous updates activated");
1302 }
1303
1304
1305 //
1306 // Disable continuous updates (only if EnableContinuousUpdates message
1307 // is supported by the server).
1308 //
1309
1310 void tryDisableContinuousUpdates() throws IOException
1311 {
1312 if (!clientMsgCaps.isEnabled(EnableContinuousUpdates)) {
1313 System.out.println("Continuous updates not supported by the server");
1314 return;
1315 }
1316
1317 if (!continuousUpdatesActive) {
1318 System.out.println("Continuous updates already disabled");
1319 return;
1320 }
1321
1322 if (continuousUpdatesEnding)
1323 return;
1324
1325 byte[] b = { (byte)EnableContinuousUpdates, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
1326 os.write(b);
1327
1328 if (!serverMsgCaps.isEnabled(EndOfContinuousUpdates)) {
1329 // If the server did not advertise support for the
1330 // EndOfContinuousUpdates message (should not normally happen
1331 // when EnableContinuousUpdates is supported), then we clear
1332 // 'continuousUpdatesActive' variable immediately. Normally,
1333 // it will be reset on receiving EndOfContinuousUpdates message
1334 // from the server.
1335 continuousUpdatesActive = false;
1336 } else {
1337 // Indicate that we are waiting for EndOfContinuousUpdates.
1338 continuousUpdatesEnding = true;
1339 }
1340 }
1341
1342
1343 //
1344 // Process EndOfContinuousUpdates message received from the server.
1345 //
1346
1347 void endOfContinuousUpdates()
1348 {
1349 continuousUpdatesActive = false;
1350 continuousUpdatesEnding = false;
1351 }
1352
1353
1354 //
1355 // Check if continuous updates are in effect.
1356 //
1357
1358 boolean continuousUpdatesAreActive()
1359 {
1360 return continuousUpdatesActive;
1361 }
1362
Constantin Kaplinskyf7cb2bf2008-05-27 08:38:28 +00001363 /**
1364 * Send a rectangle selection to be treated as video by the server (but
1365 * only if VideoRectangleSelection message is supported by the server).
1366 * @param rect specifies coordinates and size of the rectangule.
1367 * @throws java.io.IOException
1368 */
1369 void trySendVideoSelection(Rectangle rect) throws IOException
1370 {
1371 if (!clientMsgCaps.isEnabled(VideoRectangleSelection)) {
1372 System.out.println("Video area selection is not supported by the server");
1373 return;
1374 }
1375
Constantin Kaplinsky4f652852008-09-05 02:41:15 +00001376 // Send zero coordinates if the rectangle is empty.
1377 if (rect.isEmpty()) {
1378 rect = new Rectangle();
1379 }
1380
Constantin Kaplinskyf7cb2bf2008-05-27 08:38:28 +00001381 int x = rect.x;
1382 int y = rect.y;
1383 int w = rect.width;
1384 int h = rect.height;
1385
1386 byte[] b = new byte[10];
1387
1388 b[0] = (byte) VideoRectangleSelection;
1389 b[1] = (byte) 0; // reserved
1390 b[2] = (byte) ((x >> 8) & 0xff);
1391 b[3] = (byte) (x & 0xff);
1392 b[4] = (byte) ((y >> 8) & 0xff);
1393 b[5] = (byte) (y & 0xff);
1394 b[6] = (byte) ((w >> 8) & 0xff);
1395 b[7] = (byte) (w & 0xff);
1396 b[8] = (byte) ((h >> 8) & 0xff);
1397 b[9] = (byte) (h & 0xff);
1398
1399 os.write(b);
1400
1401 System.out.println("Video rectangle selection message sent");
1402 }
1403
Constantin Kaplinsky2844fd52008-04-14 08:02:25 +00001404
1405 //
1406 // Compress and write the data into the recorded session file. This
1407 // method assumes the recording is on (rec != null).
1408 //
1409
1410 void recordCompressedData(byte[] data, int off, int len) throws IOException {
1411 Deflater deflater = new Deflater();
1412 deflater.setInput(data, off, len);
1413 int bufSize = len + len / 100 + 12;
1414 byte[] buf = new byte[bufSize];
1415 deflater.finish();
1416 int compressedSize = deflater.deflate(buf);
1417 recordCompactLen(compressedSize);
1418 rec.write(buf, 0, compressedSize);
1419 }
1420
1421 void recordCompressedData(byte[] data) throws IOException {
1422 recordCompressedData(data, 0, data.length);
1423 }
1424
1425 //
1426 // Write an integer in compact representation (1..3 bytes) into the
1427 // recorded session file. This method assumes the recording is on
1428 // (rec != null).
1429 //
1430
1431 void recordCompactLen(int len) throws IOException {
1432 byte[] buf = new byte[3];
1433 int bytes = 0;
1434 buf[bytes++] = (byte)(len & 0x7F);
1435 if (len > 0x7F) {
1436 buf[bytes-1] |= 0x80;
1437 buf[bytes++] = (byte)(len >> 7 & 0x7F);
1438 if (len > 0x3FFF) {
1439 buf[bytes-1] |= 0x80;
1440 buf[bytes++] = (byte)(len >> 14 & 0xFF);
1441 }
1442 }
1443 rec.write(buf, 0, bytes);
1444 }
1445
1446 public void startTiming() {
1447 timing = true;
1448
1449 // Carry over up to 1s worth of previous rate for smoothing.
1450
1451 if (timeWaitedIn100us > 10000) {
1452 timedKbits = timedKbits * 10000 / timeWaitedIn100us;
1453 timeWaitedIn100us = 10000;
1454 }
1455 }
1456
1457 public void stopTiming() {
1458 timing = false;
1459 if (timeWaitedIn100us < timedKbits/2)
1460 timeWaitedIn100us = timedKbits/2; // upper limit 20Mbit/s
1461 }
1462
1463 public long kbitsPerSecond() {
1464 return timedKbits * 10000 / timeWaitedIn100us;
1465 }
1466
1467 public long timeWaited() {
1468 return timeWaitedIn100us;
1469 }
1470
1471 //
1472 // Methods for reading data via our DataInputStream member variable (is).
1473 //
1474 // In addition to reading data, the readFully() methods updates variables
1475 // used to estimate data throughput.
1476 //
1477
1478 public void readFully(byte b[]) throws IOException {
1479 readFully(b, 0, b.length);
1480 }
1481
1482 public void readFully(byte b[], int off, int len) throws IOException {
1483 long before = 0;
1484 if (timing)
1485 before = System.currentTimeMillis();
1486
1487 is.readFully(b, off, len);
1488
1489 if (timing) {
1490 long after = System.currentTimeMillis();
1491 long newTimeWaited = (after - before) * 10;
1492 int newKbits = len * 8 / 1000;
1493
1494 // limit rate to between 10kbit/s and 40Mbit/s
1495
1496 if (newTimeWaited > newKbits*1000) newTimeWaited = newKbits*1000;
1497 if (newTimeWaited < newKbits/4) newTimeWaited = newKbits/4;
1498
1499 timeWaitedIn100us += newTimeWaited;
1500 timedKbits += newKbits;
1501 }
1502
1503 numBytesRead += len;
1504 }
1505
1506 final int available() throws IOException {
1507 return is.available();
1508 }
1509
1510 // FIXME: DataInputStream::skipBytes() is not guaranteed to skip
1511 // exactly n bytes. Probably we don't want to use this method.
1512 final int skipBytes(int n) throws IOException {
1513 int r = is.skipBytes(n);
1514 numBytesRead += r;
1515 return r;
1516 }
1517
1518 final int readU8() throws IOException {
1519 int r = is.readUnsignedByte();
1520 numBytesRead++;
1521 return r;
1522 }
1523
1524 final int readU16() throws IOException {
1525 int r = is.readUnsignedShort();
1526 numBytesRead += 2;
1527 return r;
1528 }
1529
1530 final int readU32() throws IOException {
1531 int r = is.readInt();
1532 numBytesRead += 4;
1533 return r;
1534 }
1535}
1536