blob: 89a4caebdad79e02ed82130487b4bdcbe868a4d9 [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
101 final static int
102 EnableContinuousUpdates = 150;
103 final static String
104 SigEnableContinuousUpdates = "CUC_ENCU";
105
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");
502
503 // Supported encoding types
504 encodingCaps.add(EncodingCopyRect, StandardVendor,
505 SigEncodingCopyRect, "Standard CopyRect encoding");
506 encodingCaps.add(EncodingRRE, StandardVendor,
507 SigEncodingRRE, "Standard RRE encoding");
508 encodingCaps.add(EncodingCoRRE, StandardVendor,
509 SigEncodingCoRRE, "Standard CoRRE encoding");
510 encodingCaps.add(EncodingHextile, StandardVendor,
511 SigEncodingHextile, "Standard Hextile encoding");
512 encodingCaps.add(EncodingZRLE, StandardVendor,
513 SigEncodingZRLE, "Standard ZRLE encoding");
514 encodingCaps.add(EncodingZlib, TridiaVncVendor,
515 SigEncodingZlib, "Zlib encoding");
516 encodingCaps.add(EncodingTight, TightVncVendor,
517 SigEncodingTight, "Tight encoding");
518
519 // Supported pseudo-encoding types
520 encodingCaps.add(EncodingCompressLevel0, TightVncVendor,
521 SigEncodingCompressLevel0, "Compression level");
522 encodingCaps.add(EncodingQualityLevel0, TightVncVendor,
523 SigEncodingQualityLevel0, "JPEG quality level");
524 encodingCaps.add(EncodingXCursor, TightVncVendor,
525 SigEncodingXCursor, "X-style cursor shape update");
526 encodingCaps.add(EncodingRichCursor, TightVncVendor,
527 SigEncodingRichCursor, "Rich-color cursor shape update");
528 encodingCaps.add(EncodingPointerPos, TightVncVendor,
529 SigEncodingPointerPos, "Pointer position update");
530 encodingCaps.add(EncodingLastRect, TightVncVendor,
531 SigEncodingLastRect, "LastRect protocol extension");
532 encodingCaps.add(EncodingNewFBSize, TightVncVendor,
533 SigEncodingNewFBSize, "Framebuffer size change");
534 }
535
536 //
537 // Setup tunneling (TightVNC protocol extensions)
538 //
539
540 void setupTunneling() throws IOException {
541 int nTunnelTypes = readU32();
542 if (nTunnelTypes != 0) {
543 readCapabilityList(tunnelCaps, nTunnelTypes);
544
545 // We don't support tunneling yet.
546 writeInt(NoTunneling);
547 }
548 }
549
550 //
551 // Negotiate authentication scheme (TightVNC protocol extensions)
552 //
553
554 int negotiateAuthenticationTight() throws Exception {
555 int nAuthTypes = readU32();
556 if (nAuthTypes == 0)
557 return AuthNone;
558
559 readCapabilityList(authCaps, nAuthTypes);
560 for (int i = 0; i < authCaps.numEnabled(); i++) {
561 int authType = authCaps.getByOrder(i);
562 if (authType == AuthNone || authType == AuthVNC) {
563 writeInt(authType);
564 return authType;
565 }
566 }
567 throw new Exception("No suitable authentication scheme found");
568 }
569
570 //
571 // Read a capability list (TightVNC protocol extensions)
572 //
573
574 void readCapabilityList(CapsContainer caps, int count) throws IOException {
575 int code;
576 byte[] vendor = new byte[4];
577 byte[] name = new byte[8];
578 for (int i = 0; i < count; i++) {
579 code = readU32();
580 readFully(vendor);
581 readFully(name);
582 caps.enable(new CapabilityInfo(code, vendor, name));
583 }
584 }
585
586 //
587 // Write a 32-bit integer into the output stream.
588 //
589
590 void writeInt(int value) throws IOException {
591 byte[] b = new byte[4];
592 b[0] = (byte) ((value >> 24) & 0xff);
593 b[1] = (byte) ((value >> 16) & 0xff);
594 b[2] = (byte) ((value >> 8) & 0xff);
595 b[3] = (byte) (value & 0xff);
596 os.write(b);
597 }
598
599 //
600 // Write the client initialisation message
601 //
602
603 void writeClientInit() throws IOException {
604 if (viewer.options.shareDesktop) {
605 os.write(1);
606 } else {
607 os.write(0);
608 }
609 viewer.options.disableShareDesktop();
610 }
611
612
613 //
614 // Read the server initialisation message
615 //
616
617 String desktopName;
618 int framebufferWidth, framebufferHeight;
619 int bitsPerPixel, depth;
620 boolean bigEndian, trueColour;
621 int redMax, greenMax, blueMax, redShift, greenShift, blueShift;
622
623 void readServerInit() throws IOException {
624 framebufferWidth = readU16();
625 framebufferHeight = readU16();
626 bitsPerPixel = readU8();
627 depth = readU8();
628 bigEndian = (readU8() != 0);
629 trueColour = (readU8() != 0);
630 redMax = readU16();
631 greenMax = readU16();
632 blueMax = readU16();
633 redShift = readU8();
634 greenShift = readU8();
635 blueShift = readU8();
636 byte[] pad = new byte[3];
637 readFully(pad);
638 int nameLength = readU32();
639 byte[] name = new byte[nameLength];
640 readFully(name);
641 desktopName = new String(name);
642
643 // Read interaction capabilities (TightVNC protocol extensions)
644 if (protocolTightVNC) {
645 int nServerMessageTypes = readU16();
646 int nClientMessageTypes = readU16();
647 int nEncodingTypes = readU16();
648 readU16();
649 readCapabilityList(serverMsgCaps, nServerMessageTypes);
650 readCapabilityList(clientMsgCaps, nClientMessageTypes);
651 readCapabilityList(encodingCaps, nEncodingTypes);
652 }
653
654 if (!clientMsgCaps.isEnabled(EnableContinuousUpdates)) {
655 viewer.options.disableContUpdates();
656 }
657
658 inNormalProtocol = true;
659 }
660
661
662 //
663 // Create session file and write initial protocol messages into it.
664 //
665
666 void startSession(String fname) throws IOException {
667 rec = new SessionRecorder(fname);
668 rec.writeHeader();
669 rec.write(versionMsg_3_3.getBytes());
670 rec.writeIntBE(SecTypeNone);
671 rec.writeShortBE(framebufferWidth);
672 rec.writeShortBE(framebufferHeight);
673 byte[] fbsServerInitMsg = {
674 32, 24, 0, 1, 0,
675 (byte)0xFF, 0, (byte)0xFF, 0, (byte)0xFF,
676 16, 8, 0, 0, 0, 0
677 };
678 rec.write(fbsServerInitMsg);
679 rec.writeIntBE(desktopName.length());
680 rec.write(desktopName.getBytes());
681 numUpdatesInSession = 0;
682
683 // FIXME: If there were e.g. ZRLE updates only, that should not
684 // affect recording of Zlib and Tight updates. So, actually
685 // we should maintain separate flags for Zlib, ZRLE and
686 // Tight, instead of one ``wereZlibUpdates'' variable.
687 //
688 if (wereZlibUpdates)
689 recordFromBeginning = false;
690
691 zlibWarningShown = false;
692 tightWarningShown = false;
693 }
694
695 //
696 // Close session file.
697 //
698
699 void closeSession() throws IOException {
700 if (rec != null) {
701 rec.close();
702 rec = null;
703 }
704 }
705
706
707 //
708 // Set new framebuffer size
709 //
710
711 void setFramebufferSize(int width, int height) {
712 framebufferWidth = width;
713 framebufferHeight = height;
714 }
715
716
717 //
718 // Read the server message type
719 //
720
721 int readServerMessageType() throws IOException {
722 int msgType = readU8();
723
724 // If the session is being recorded:
725 if (rec != null) {
726 if (msgType == Bell) { // Save Bell messages in session files.
727 rec.writeByte(msgType);
728 if (numUpdatesInSession > 0)
729 rec.flush();
730 }
731 }
732
733 return msgType;
734 }
735
736
737 //
738 // Read a FramebufferUpdate message
739 //
740
741 int updateNRects;
742
743 void readFramebufferUpdate() throws IOException {
744 skipBytes(1);
745 updateNRects = readU16();
746
747 // If the session is being recorded:
748 if (rec != null) {
749 rec.writeByte(FramebufferUpdate);
750 rec.writeByte(0);
751 rec.writeShortBE(updateNRects);
752 }
753
754 numUpdatesInSession++;
755 }
756
757 // Read a FramebufferUpdate rectangle header
758
759 int updateRectX, updateRectY, updateRectW, updateRectH, updateRectEncoding;
760
761 void readFramebufferUpdateRectHdr() throws Exception {
762 updateRectX = readU16();
763 updateRectY = readU16();
764 updateRectW = readU16();
765 updateRectH = readU16();
766 updateRectEncoding = readU32();
767
768 if (updateRectEncoding == EncodingZlib ||
769 updateRectEncoding == EncodingZRLE ||
770 updateRectEncoding == EncodingTight)
771 wereZlibUpdates = true;
772
773 // If the session is being recorded:
774 if (rec != null) {
775 if (numUpdatesInSession > 1)
776 rec.flush(); // Flush the output on each rectangle.
777 rec.writeShortBE(updateRectX);
778 rec.writeShortBE(updateRectY);
779 rec.writeShortBE(updateRectW);
780 rec.writeShortBE(updateRectH);
781 if (updateRectEncoding == EncodingZlib && !recordFromBeginning) {
782 // Here we cannot write Zlib-encoded rectangles because the
783 // decoder won't be able to reproduce zlib stream state.
784 if (!zlibWarningShown) {
785 System.out.println("Warning: Raw encoding will be used " +
786 "instead of Zlib in recorded session.");
787 zlibWarningShown = true;
788 }
789 rec.writeIntBE(EncodingRaw);
790 } else {
791 rec.writeIntBE(updateRectEncoding);
792 if (updateRectEncoding == EncodingTight && !recordFromBeginning &&
793 !tightWarningShown) {
794 System.out.println("Warning: Re-compressing Tight-encoded " +
795 "updates for session recording.");
796 tightWarningShown = true;
797 }
798 }
799 }
800
801 if (updateRectEncoding < 0 || updateRectEncoding > MaxNormalEncoding)
802 return;
803
804 if (updateRectX + updateRectW > framebufferWidth ||
805 updateRectY + updateRectH > framebufferHeight) {
806 throw new Exception("Framebuffer update rectangle too large: " +
807 updateRectW + "x" + updateRectH + " at (" +
808 updateRectX + "," + updateRectY + ")");
809 }
810 }
811
812 // Read CopyRect source X and Y.
813
814 int copyRectSrcX, copyRectSrcY;
815
816 void readCopyRect() throws IOException {
817 copyRectSrcX = readU16();
818 copyRectSrcY = readU16();
819
820 // If the session is being recorded:
821 if (rec != null) {
822 rec.writeShortBE(copyRectSrcX);
823 rec.writeShortBE(copyRectSrcY);
824 }
825 }
826
827
828 //
829 // Read a ServerCutText message
830 //
831
832 String readServerCutText() throws IOException {
833 skipBytes(3);
834 int len = readU32();
835 byte[] text = new byte[len];
836 readFully(text);
837 return new String(text);
838 }
839
840
841 //
842 // Read an integer in compact representation (1..3 bytes).
843 // Such format is used as a part of the Tight encoding.
844 // Also, this method records data if session recording is active and
845 // the viewer's recordFromBeginning variable is set to true.
846 //
847
848 int readCompactLen() throws IOException {
849 int[] portion = new int[3];
850 portion[0] = readU8();
851 int byteCount = 1;
852 int len = portion[0] & 0x7F;
853 if ((portion[0] & 0x80) != 0) {
854 portion[1] = readU8();
855 byteCount++;
856 len |= (portion[1] & 0x7F) << 7;
857 if ((portion[1] & 0x80) != 0) {
858 portion[2] = readU8();
859 byteCount++;
860 len |= (portion[2] & 0xFF) << 14;
861 }
862 }
863
864 if (rec != null && recordFromBeginning)
865 for (int i = 0; i < byteCount; i++)
866 rec.writeByte(portion[i]);
867
868 return len;
869 }
870
871
872 //
873 // Write a FramebufferUpdateRequest message
874 //
875
876 void writeFramebufferUpdateRequest(int x, int y, int w, int h,
877 boolean incremental)
878 throws IOException
879 {
880 byte[] b = new byte[10];
881
882 b[0] = (byte) FramebufferUpdateRequest;
883 b[1] = (byte) (incremental ? 1 : 0);
884 b[2] = (byte) ((x >> 8) & 0xff);
885 b[3] = (byte) (x & 0xff);
886 b[4] = (byte) ((y >> 8) & 0xff);
887 b[5] = (byte) (y & 0xff);
888 b[6] = (byte) ((w >> 8) & 0xff);
889 b[7] = (byte) (w & 0xff);
890 b[8] = (byte) ((h >> 8) & 0xff);
891 b[9] = (byte) (h & 0xff);
892
893 os.write(b);
894 }
895
896
897 //
898 // Write a SetPixelFormat message
899 //
900
901 void writeSetPixelFormat(int bitsPerPixel, int depth, boolean bigEndian,
902 boolean trueColour,
903 int redMax, int greenMax, int blueMax,
904 int redShift, int greenShift, int blueShift)
905 throws IOException
906 {
907 byte[] b = new byte[20];
908
909 b[0] = (byte) SetPixelFormat;
910 b[4] = (byte) bitsPerPixel;
911 b[5] = (byte) depth;
912 b[6] = (byte) (bigEndian ? 1 : 0);
913 b[7] = (byte) (trueColour ? 1 : 0);
914 b[8] = (byte) ((redMax >> 8) & 0xff);
915 b[9] = (byte) (redMax & 0xff);
916 b[10] = (byte) ((greenMax >> 8) & 0xff);
917 b[11] = (byte) (greenMax & 0xff);
918 b[12] = (byte) ((blueMax >> 8) & 0xff);
919 b[13] = (byte) (blueMax & 0xff);
920 b[14] = (byte) redShift;
921 b[15] = (byte) greenShift;
922 b[16] = (byte) blueShift;
923
924 os.write(b);
925 }
926
927
928 //
929 // Write a FixColourMapEntries message. The values in the red, green and
930 // blue arrays are from 0 to 65535.
931 //
932
933 void writeFixColourMapEntries(int firstColour, int nColours,
934 int[] red, int[] green, int[] blue)
935 throws IOException
936 {
937 byte[] b = new byte[6 + nColours * 6];
938
939 b[0] = (byte) FixColourMapEntries;
940 b[2] = (byte) ((firstColour >> 8) & 0xff);
941 b[3] = (byte) (firstColour & 0xff);
942 b[4] = (byte) ((nColours >> 8) & 0xff);
943 b[5] = (byte) (nColours & 0xff);
944
945 for (int i = 0; i < nColours; i++) {
946 b[6 + i * 6] = (byte) ((red[i] >> 8) & 0xff);
947 b[6 + i * 6 + 1] = (byte) (red[i] & 0xff);
948 b[6 + i * 6 + 2] = (byte) ((green[i] >> 8) & 0xff);
949 b[6 + i * 6 + 3] = (byte) (green[i] & 0xff);
950 b[6 + i * 6 + 4] = (byte) ((blue[i] >> 8) & 0xff);
951 b[6 + i * 6 + 5] = (byte) (blue[i] & 0xff);
952 }
953
954 os.write(b);
955 }
956
957
958 //
959 // Write a SetEncodings message
960 //
961
962 void writeSetEncodings(int[] encs, int len) throws IOException {
963 byte[] b = new byte[4 + 4 * len];
964
965 b[0] = (byte) SetEncodings;
966 b[2] = (byte) ((len >> 8) & 0xff);
967 b[3] = (byte) (len & 0xff);
968
969 for (int i = 0; i < len; i++) {
970 b[4 + 4 * i] = (byte) ((encs[i] >> 24) & 0xff);
971 b[5 + 4 * i] = (byte) ((encs[i] >> 16) & 0xff);
972 b[6 + 4 * i] = (byte) ((encs[i] >> 8) & 0xff);
973 b[7 + 4 * i] = (byte) (encs[i] & 0xff);
974 }
975
976 os.write(b);
977 }
978
979
980 //
981 // Write a ClientCutText message
982 //
983
984 void writeClientCutText(String text) throws IOException {
985 byte[] b = new byte[8 + text.length()];
986
987 b[0] = (byte) ClientCutText;
988 b[4] = (byte) ((text.length() >> 24) & 0xff);
989 b[5] = (byte) ((text.length() >> 16) & 0xff);
990 b[6] = (byte) ((text.length() >> 8) & 0xff);
991 b[7] = (byte) (text.length() & 0xff);
992
993 System.arraycopy(text.getBytes(), 0, b, 8, text.length());
994
995 os.write(b);
996 }
997
998
999 //
1000 // A buffer for putting pointer and keyboard events before being sent. This
1001 // is to ensure that multiple RFB events generated from a single Java Event
1002 // will all be sent in a single network packet. The maximum possible
1003 // length is 4 modifier down events, a single key event followed by 4
1004 // modifier up events i.e. 9 key events or 72 bytes.
1005 //
1006
1007 byte[] eventBuf = new byte[72];
1008 int eventBufLen;
1009
1010
1011 // Useful shortcuts for modifier masks.
1012
1013 final static int CTRL_MASK = InputEvent.CTRL_MASK;
1014 final static int SHIFT_MASK = InputEvent.SHIFT_MASK;
1015 final static int META_MASK = InputEvent.META_MASK;
1016 final static int ALT_MASK = InputEvent.ALT_MASK;
1017
1018
1019 //
1020 // Write a pointer event message. We may need to send modifier key events
1021 // around it to set the correct modifier state.
1022 //
1023
1024 int pointerMask = 0;
1025
1026 void writePointerEvent(MouseEvent evt) throws IOException {
1027 int modifiers = evt.getModifiers();
1028
1029 int mask2 = 2;
1030 int mask3 = 4;
1031 if (viewer.options.reverseMouseButtons2And3) {
1032 mask2 = 4;
1033 mask3 = 2;
1034 }
1035
1036 // Note: For some reason, AWT does not set BUTTON1_MASK on left
1037 // button presses. Here we think that it was the left button if
1038 // modifiers do not include BUTTON2_MASK or BUTTON3_MASK.
1039
1040 if (evt.getID() == MouseEvent.MOUSE_PRESSED) {
1041 if ((modifiers & InputEvent.BUTTON2_MASK) != 0) {
1042 pointerMask = mask2;
1043 modifiers &= ~ALT_MASK;
1044 } else if ((modifiers & InputEvent.BUTTON3_MASK) != 0) {
1045 pointerMask = mask3;
1046 modifiers &= ~META_MASK;
1047 } else {
1048 pointerMask = 1;
1049 }
1050 } else if (evt.getID() == MouseEvent.MOUSE_RELEASED) {
1051 pointerMask = 0;
1052 if ((modifiers & InputEvent.BUTTON2_MASK) != 0) {
1053 modifiers &= ~ALT_MASK;
1054 } else if ((modifiers & InputEvent.BUTTON3_MASK) != 0) {
1055 modifiers &= ~META_MASK;
1056 }
1057 }
1058
1059 eventBufLen = 0;
1060 writeModifierKeyEvents(modifiers);
1061
1062 int x = evt.getX();
1063 int y = evt.getY();
1064
1065 if (x < 0) x = 0;
1066 if (y < 0) y = 0;
1067
1068 eventBuf[eventBufLen++] = (byte) PointerEvent;
1069 eventBuf[eventBufLen++] = (byte) pointerMask;
1070 eventBuf[eventBufLen++] = (byte) ((x >> 8) & 0xff);
1071 eventBuf[eventBufLen++] = (byte) (x & 0xff);
1072 eventBuf[eventBufLen++] = (byte) ((y >> 8) & 0xff);
1073 eventBuf[eventBufLen++] = (byte) (y & 0xff);
1074
1075 //
1076 // Always release all modifiers after an "up" event
1077 //
1078
1079 if (pointerMask == 0) {
1080 writeModifierKeyEvents(0);
1081 }
1082
1083 os.write(eventBuf, 0, eventBufLen);
1084 }
1085
1086
1087 //
1088 // Write a key event message. We may need to send modifier key events
1089 // around it to set the correct modifier state. Also we need to translate
1090 // from the Java key values to the X keysym values used by the RFB protocol.
1091 //
1092
1093 void writeKeyEvent(KeyEvent evt) throws IOException {
1094
1095 int keyChar = evt.getKeyChar();
1096
1097 //
1098 // Ignore event if only modifiers were pressed.
1099 //
1100
1101 // Some JVMs return 0 instead of CHAR_UNDEFINED in getKeyChar().
1102 if (keyChar == 0)
1103 keyChar = KeyEvent.CHAR_UNDEFINED;
1104
1105 if (keyChar == KeyEvent.CHAR_UNDEFINED) {
1106 int code = evt.getKeyCode();
1107 if (code == KeyEvent.VK_CONTROL || code == KeyEvent.VK_SHIFT ||
1108 code == KeyEvent.VK_META || code == KeyEvent.VK_ALT)
1109 return;
1110 }
1111
1112 //
1113 // Key press or key release?
1114 //
1115
1116 boolean down = (evt.getID() == KeyEvent.KEY_PRESSED);
1117
1118 int key;
1119 if (evt.isActionKey()) {
1120
1121 //
1122 // An action key should be one of the following.
1123 // If not then just ignore the event.
1124 //
1125
1126 switch(evt.getKeyCode()) {
1127 case KeyEvent.VK_HOME: key = 0xff50; break;
1128 case KeyEvent.VK_LEFT: key = 0xff51; break;
1129 case KeyEvent.VK_UP: key = 0xff52; break;
1130 case KeyEvent.VK_RIGHT: key = 0xff53; break;
1131 case KeyEvent.VK_DOWN: key = 0xff54; break;
1132 case KeyEvent.VK_PAGE_UP: key = 0xff55; break;
1133 case KeyEvent.VK_PAGE_DOWN: key = 0xff56; break;
1134 case KeyEvent.VK_END: key = 0xff57; break;
1135 case KeyEvent.VK_INSERT: key = 0xff63; break;
1136 case KeyEvent.VK_F1: key = 0xffbe; break;
1137 case KeyEvent.VK_F2: key = 0xffbf; break;
1138 case KeyEvent.VK_F3: key = 0xffc0; break;
1139 case KeyEvent.VK_F4: key = 0xffc1; break;
1140 case KeyEvent.VK_F5: key = 0xffc2; break;
1141 case KeyEvent.VK_F6: key = 0xffc3; break;
1142 case KeyEvent.VK_F7: key = 0xffc4; break;
1143 case KeyEvent.VK_F8: key = 0xffc5; break;
1144 case KeyEvent.VK_F9: key = 0xffc6; break;
1145 case KeyEvent.VK_F10: key = 0xffc7; break;
1146 case KeyEvent.VK_F11: key = 0xffc8; break;
1147 case KeyEvent.VK_F12: key = 0xffc9; break;
1148 default:
1149 return;
1150 }
1151
1152 } else {
1153
1154 //
1155 // A "normal" key press. Ordinary ASCII characters go straight through.
1156 // For CTRL-<letter>, CTRL is sent separately so just send <letter>.
1157 // Backspace, tab, return, escape and delete have special keysyms.
1158 // Anything else we ignore.
1159 //
1160
1161 key = keyChar;
1162
1163 if (key < 0x20) {
1164 if (evt.isControlDown()) {
1165 key += 0x60;
1166 } else {
1167 switch(key) {
1168 case KeyEvent.VK_BACK_SPACE: key = 0xff08; break;
1169 case KeyEvent.VK_TAB: key = 0xff09; break;
1170 case KeyEvent.VK_ENTER: key = 0xff0d; break;
1171 case KeyEvent.VK_ESCAPE: key = 0xff1b; break;
1172 }
1173 }
1174 } else if (key == 0x7f) {
1175 // Delete
1176 key = 0xffff;
1177 } else if (key > 0xff) {
1178 // JDK1.1 on X incorrectly passes some keysyms straight through,
1179 // so we do too. JDK1.1.4 seems to have fixed this.
1180 // The keysyms passed are 0xff00 .. XK_BackSpace .. XK_Delete
1181 // Also, we pass through foreign currency keysyms (0x20a0..0x20af).
1182 if ((key < 0xff00 || key > 0xffff) &&
1183 !(key >= 0x20a0 && key <= 0x20af))
1184 return;
1185 }
1186 }
1187
1188 // Fake keyPresses for keys that only generates keyRelease events
1189 if ((key == 0xe5) || (key == 0xc5) || // XK_aring / XK_Aring
1190 (key == 0xe4) || (key == 0xc4) || // XK_adiaeresis / XK_Adiaeresis
1191 (key == 0xf6) || (key == 0xd6) || // XK_odiaeresis / XK_Odiaeresis
1192 (key == 0xa7) || (key == 0xbd) || // XK_section / XK_onehalf
1193 (key == 0xa3)) { // XK_sterling
1194 // Make sure we do not send keypress events twice on platforms
1195 // with correct JVMs (those that actually report KeyPress for all
1196 // keys)
1197 if (down)
1198 brokenKeyPressed = true;
1199
1200 if (!down && !brokenKeyPressed) {
1201 // We've got a release event for this key, but haven't received
1202 // a press. Fake it.
1203 eventBufLen = 0;
1204 writeModifierKeyEvents(evt.getModifiers());
1205 writeKeyEvent(key, true);
1206 os.write(eventBuf, 0, eventBufLen);
1207 }
1208
1209 if (!down)
1210 brokenKeyPressed = false;
1211 }
1212
1213 eventBufLen = 0;
1214 writeModifierKeyEvents(evt.getModifiers());
1215 writeKeyEvent(key, down);
1216
1217 // Always release all modifiers after an "up" event
1218 if (!down)
1219 writeModifierKeyEvents(0);
1220
1221 os.write(eventBuf, 0, eventBufLen);
1222 }
1223
1224
1225 //
1226 // Add a raw key event with the given X keysym to eventBuf.
1227 //
1228
1229 void writeKeyEvent(int keysym, boolean down) {
1230 eventBuf[eventBufLen++] = (byte) KeyboardEvent;
1231 eventBuf[eventBufLen++] = (byte) (down ? 1 : 0);
1232 eventBuf[eventBufLen++] = (byte) 0;
1233 eventBuf[eventBufLen++] = (byte) 0;
1234 eventBuf[eventBufLen++] = (byte) ((keysym >> 24) & 0xff);
1235 eventBuf[eventBufLen++] = (byte) ((keysym >> 16) & 0xff);
1236 eventBuf[eventBufLen++] = (byte) ((keysym >> 8) & 0xff);
1237 eventBuf[eventBufLen++] = (byte) (keysym & 0xff);
1238 }
1239
1240
1241 //
1242 // Write key events to set the correct modifier state.
1243 //
1244
1245 int oldModifiers = 0;
1246
1247 void writeModifierKeyEvents(int newModifiers) {
1248 if ((newModifiers & CTRL_MASK) != (oldModifiers & CTRL_MASK))
1249 writeKeyEvent(0xffe3, (newModifiers & CTRL_MASK) != 0);
1250
1251 if ((newModifiers & SHIFT_MASK) != (oldModifiers & SHIFT_MASK))
1252 writeKeyEvent(0xffe1, (newModifiers & SHIFT_MASK) != 0);
1253
1254 if ((newModifiers & META_MASK) != (oldModifiers & META_MASK))
1255 writeKeyEvent(0xffe7, (newModifiers & META_MASK) != 0);
1256
1257 if ((newModifiers & ALT_MASK) != (oldModifiers & ALT_MASK))
1258 writeKeyEvent(0xffe9, (newModifiers & ALT_MASK) != 0);
1259
1260 oldModifiers = newModifiers;
1261 }
1262
1263
1264 //
1265 // Enable continuous updates for the specified area of the screen (but
1266 // only if EnableContinuousUpdates message is supported by the server).
1267 //
1268
1269 void tryEnableContinuousUpdates(int x, int y, int w, int h)
1270 throws IOException
1271 {
1272 if (!clientMsgCaps.isEnabled(EnableContinuousUpdates)) {
1273 System.out.println("Continuous updates not supported by the server");
1274 return;
1275 }
1276
1277 if (continuousUpdatesActive) {
1278 System.out.println("Continuous updates already active");
1279 return;
1280 }
1281
1282 byte[] b = new byte[10];
1283
1284 b[0] = (byte) EnableContinuousUpdates;
1285 b[1] = (byte) 1; // enable
1286 b[2] = (byte) ((x >> 8) & 0xff);
1287 b[3] = (byte) (x & 0xff);
1288 b[4] = (byte) ((y >> 8) & 0xff);
1289 b[5] = (byte) (y & 0xff);
1290 b[6] = (byte) ((w >> 8) & 0xff);
1291 b[7] = (byte) (w & 0xff);
1292 b[8] = (byte) ((h >> 8) & 0xff);
1293 b[9] = (byte) (h & 0xff);
1294
1295 os.write(b);
1296
1297 continuousUpdatesActive = true;
1298 System.out.println("Continuous updates activated");
1299 }
1300
1301
1302 //
1303 // Disable continuous updates (only if EnableContinuousUpdates message
1304 // is supported by the server).
1305 //
1306
1307 void tryDisableContinuousUpdates() throws IOException
1308 {
1309 if (!clientMsgCaps.isEnabled(EnableContinuousUpdates)) {
1310 System.out.println("Continuous updates not supported by the server");
1311 return;
1312 }
1313
1314 if (!continuousUpdatesActive) {
1315 System.out.println("Continuous updates already disabled");
1316 return;
1317 }
1318
1319 if (continuousUpdatesEnding)
1320 return;
1321
1322 byte[] b = { (byte)EnableContinuousUpdates, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
1323 os.write(b);
1324
1325 if (!serverMsgCaps.isEnabled(EndOfContinuousUpdates)) {
1326 // If the server did not advertise support for the
1327 // EndOfContinuousUpdates message (should not normally happen
1328 // when EnableContinuousUpdates is supported), then we clear
1329 // 'continuousUpdatesActive' variable immediately. Normally,
1330 // it will be reset on receiving EndOfContinuousUpdates message
1331 // from the server.
1332 continuousUpdatesActive = false;
1333 } else {
1334 // Indicate that we are waiting for EndOfContinuousUpdates.
1335 continuousUpdatesEnding = true;
1336 }
1337 }
1338
1339
1340 //
1341 // Process EndOfContinuousUpdates message received from the server.
1342 //
1343
1344 void endOfContinuousUpdates()
1345 {
1346 continuousUpdatesActive = false;
1347 continuousUpdatesEnding = false;
1348 }
1349
1350
1351 //
1352 // Check if continuous updates are in effect.
1353 //
1354
1355 boolean continuousUpdatesAreActive()
1356 {
1357 return continuousUpdatesActive;
1358 }
1359
1360
1361 //
1362 // Compress and write the data into the recorded session file. This
1363 // method assumes the recording is on (rec != null).
1364 //
1365
1366 void recordCompressedData(byte[] data, int off, int len) throws IOException {
1367 Deflater deflater = new Deflater();
1368 deflater.setInput(data, off, len);
1369 int bufSize = len + len / 100 + 12;
1370 byte[] buf = new byte[bufSize];
1371 deflater.finish();
1372 int compressedSize = deflater.deflate(buf);
1373 recordCompactLen(compressedSize);
1374 rec.write(buf, 0, compressedSize);
1375 }
1376
1377 void recordCompressedData(byte[] data) throws IOException {
1378 recordCompressedData(data, 0, data.length);
1379 }
1380
1381 //
1382 // Write an integer in compact representation (1..3 bytes) into the
1383 // recorded session file. This method assumes the recording is on
1384 // (rec != null).
1385 //
1386
1387 void recordCompactLen(int len) throws IOException {
1388 byte[] buf = new byte[3];
1389 int bytes = 0;
1390 buf[bytes++] = (byte)(len & 0x7F);
1391 if (len > 0x7F) {
1392 buf[bytes-1] |= 0x80;
1393 buf[bytes++] = (byte)(len >> 7 & 0x7F);
1394 if (len > 0x3FFF) {
1395 buf[bytes-1] |= 0x80;
1396 buf[bytes++] = (byte)(len >> 14 & 0xFF);
1397 }
1398 }
1399 rec.write(buf, 0, bytes);
1400 }
1401
1402 public void startTiming() {
1403 timing = true;
1404
1405 // Carry over up to 1s worth of previous rate for smoothing.
1406
1407 if (timeWaitedIn100us > 10000) {
1408 timedKbits = timedKbits * 10000 / timeWaitedIn100us;
1409 timeWaitedIn100us = 10000;
1410 }
1411 }
1412
1413 public void stopTiming() {
1414 timing = false;
1415 if (timeWaitedIn100us < timedKbits/2)
1416 timeWaitedIn100us = timedKbits/2; // upper limit 20Mbit/s
1417 }
1418
1419 public long kbitsPerSecond() {
1420 return timedKbits * 10000 / timeWaitedIn100us;
1421 }
1422
1423 public long timeWaited() {
1424 return timeWaitedIn100us;
1425 }
1426
1427 //
1428 // Methods for reading data via our DataInputStream member variable (is).
1429 //
1430 // In addition to reading data, the readFully() methods updates variables
1431 // used to estimate data throughput.
1432 //
1433
1434 public void readFully(byte b[]) throws IOException {
1435 readFully(b, 0, b.length);
1436 }
1437
1438 public void readFully(byte b[], int off, int len) throws IOException {
1439 long before = 0;
1440 if (timing)
1441 before = System.currentTimeMillis();
1442
1443 is.readFully(b, off, len);
1444
1445 if (timing) {
1446 long after = System.currentTimeMillis();
1447 long newTimeWaited = (after - before) * 10;
1448 int newKbits = len * 8 / 1000;
1449
1450 // limit rate to between 10kbit/s and 40Mbit/s
1451
1452 if (newTimeWaited > newKbits*1000) newTimeWaited = newKbits*1000;
1453 if (newTimeWaited < newKbits/4) newTimeWaited = newKbits/4;
1454
1455 timeWaitedIn100us += newTimeWaited;
1456 timedKbits += newKbits;
1457 }
1458
1459 numBytesRead += len;
1460 }
1461
1462 final int available() throws IOException {
1463 return is.available();
1464 }
1465
1466 // FIXME: DataInputStream::skipBytes() is not guaranteed to skip
1467 // exactly n bytes. Probably we don't want to use this method.
1468 final int skipBytes(int n) throws IOException {
1469 int r = is.skipBytes(n);
1470 numBytesRead += r;
1471 return r;
1472 }
1473
1474 final int readU8() throws IOException {
1475 int r = is.readUnsignedByte();
1476 numBytesRead++;
1477 return r;
1478 }
1479
1480 final int readU16() throws IOException {
1481 int r = is.readUnsignedShort();
1482 numBytesRead += 2;
1483 return r;
1484 }
1485
1486 final int readU32() throws IOException {
1487 int r = is.readInt();
1488 numBytesRead += 4;
1489 return r;
1490 }
1491}
1492