-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathConn.cs
886 lines (780 loc) · 26.1 KB
/
Conn.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
// Copyright (c) 2004-2005, 2007 Rocky Lo. All Rights Reserved.
// Copyright (C) 2002 Ultr@VNC Team Members. All Rights Reserved.
// Copyright (C) 2000-2002 Const Kaplinsky. All Rights Reserved.
// Copyright (C) 2002 RealVNC Ltd. All Rights Reserved.
// Copyright (C) 1999 AT&T Laboratories Cambridge. All Rights Reserved.
//
// This file is part of the VNC system.
//
// The VNC system is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
// USA.
//
// If the source code for the VNC system is not available from the place
// whence you received this file, check http://www.uk.research.att.com/vnc or contact
// the authors on [email protected] for information on obtaining it.
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Drawing;
using System.Reflection;
using System.Windows.Forms;
using System.Collections;
using Vnc.RfbProto;
using Vnc.Security;
using SystemEx.WindowCE.Net;
namespace Vnc.Viewer
{
/// <remarks>
/// This class represents a connection to the server.
/// It prompts a user for the connection details, connects to the server,
/// creates a display, and then handles server messages.
/// </remarks>
internal class Conn
{
/// <summary>
/// This is the version number we report to the server. At the moment we
/// "borrow" this from the UltraVNC viewer.
/// </summary>
// TODO: Have we implemented everything needed in order to say that we are
// compliant to this version?
private const byte ViewerRfbMajorVer = 3;
private const byte ViewerRfbMinorVer = 4;
// These are cleaned up upon termination because they contain initial
// values of a connection object.
private ConnOpts opts = null;
private ViewOpts viewOpts = null;
// These are cleaned up upon termination because they contain
// unmanaged resources.
private TcpClient tcpClient = null;
private NetworkStream stream = null;
private BinaryReader reader = null;
private BinaryWriter writer = null;
private NetworkConn networkConn = null;
// These are set each time a connection is run.
private ServInit servInit = null;
private string desktopName = null;
private int majorVer = -1;
private int minorVer = -1;
private View view = null;
private bool termBgThread = false;
private byte bytesPp = 0;
private byte bpp = 0;
private byte depth = 0;
private bool isBigEndian = false;
private bool isTrueColor = false;
private UInt16 redMax = 0;
private UInt16 greenMax = 0;
private UInt16 blueMax = 0;
private byte redShift = 0;
private byte greenShift = 0;
private byte blueShift = 0;
private UInt16 frameBufWidth = 0;
private UInt16 frameBufHeight = 0;
internal bool IsFmtChgPending = false;
private EventHandler closeHdr = null;
internal Conn()
{
closeHdr = new EventHandler(CloseView);
}
private void CloseView(object sender, EventArgs e)
{
// Do this in the main thread.
view.Close();
}
private void ViewClosed(object sender, EventArgs e)
{
termBgThread = true;
App.RemoveConn(this);
}
private void GetConnDetails()
{
SessDlg sessDlg;
if(viewOpts == null)
sessDlg = SessDlgFactory.Create();
else
sessDlg = SessDlgFactory.Create(viewOpts);
if(sessDlg.ShowDialog() != DialogResult.OK)
throw new QuietEx();
opts = sessDlg.ConnOpts;
}
private void Connect()
{
try
{
try
{
IPAddress ipAdr = IPAddress.Parse(opts.Host);
IPEndPoint ipEndPt = new IPEndPoint(ipAdr, opts.Port);
tcpClient = new TcpClient();
tcpClient.Connect(ipEndPt);
}
catch(FormatException)
{
tcpClient = new TcpClient(opts.Host, opts.Port);
}
stream = tcpClient.GetStream();
reader = new BinaryReader(stream, Encoding.ASCII);
writer = new BinaryWriter(stream, Encoding.ASCII);
}
catch(SocketException)
{
throw new WarnEx(App.GetStr("Unable to connect to the specified server!"));
}
}
private void Listen()
{
TcpListener listener = new TcpListener(IPAddress.Any, opts.Port);
try
{
listener.Start();
ListenDlg listenDlg = new ListenDlg(listener);
if(listenDlg.ShowDialog() != DialogResult.OK)
throw new QuietEx();
tcpClient = listener.AcceptTcpClient();
stream = tcpClient.GetStream();
reader = new BinaryReader(stream, Encoding.ASCII);
writer = new BinaryWriter(stream, Encoding.ASCII);
}
catch(SocketException)
{
throw new WarnEx(App.GetStr("Unable to get an incoming connection from the server!"));
}
finally
{
try
{
listener.Stop();
}
catch
{}
}
}
private string ReadAsciiStr(int numChars)
{
if(numChars == 0)
return String.Empty;
char[] chars = reader.ReadChars(numChars);
return new string(chars);
}
private byte ReadByte()
{
return reader.ReadByte();
}
private byte[] ReadBytes(int numBytes)
{
if(numBytes == 0)
return new byte[0];
return reader.ReadBytes(numBytes);
}
private UInt32 ReadUInt32()
{
Int32 result = reader.ReadInt32();
result = IPAddress.NetworkToHostOrder(result);
return unchecked((UInt32)result);
}
private void WriteAsciiStr(string str)
{
writer.Write(str.ToCharArray());
}
private void WriteBytes(byte[] bytes)
{
writer.Write(bytes);
}
internal void WriteBytes(byte[] bytes, RfbCliMsgType msgType)
{
WriteBytes(bytes);
}
private void NegoProtoVer()
{
string verMsg = ReadAsciiStr(RfbSize.VerMsg);
if(!RfbProtoUtil.IsValidVerMsg(verMsg))
throw new WarnEx(App.GetStr("The server is not a VNC server!"));
RfbProtoUtil.GetVerFromMsg(verMsg, out majorVer, out minorVer);
if(majorVer == 3 && minorVer < 3)
throw new WarnEx(App.GetStr("This server version is not supported!"));
else
{
majorVer = ViewerRfbMajorVer;
minorVer = ViewerRfbMinorVer;
}
verMsg = RfbProtoUtil.GetVerMsg(majorVer, minorVer);
WriteAsciiStr(verMsg);
}
private void CreateDisp()
{
view = ViewFactory.Create(this, opts, frameBufWidth, frameBufHeight);
view.Text = desktopName;
view.Closed += new EventHandler(ViewClosed);
view.Show();
}
private void Auth()
{
RfbAuthScheme authScheme = (RfbAuthScheme)ReadUInt32();
switch(authScheme)
{
case RfbAuthScheme.ConnFailed:
throw new WarnEx(App.GetStr("Connection failed at authentication!"));
case RfbAuthScheme.NoAuth:
break;
case RfbAuthScheme.VncAuth:
if(opts.Passwd == null || opts.Passwd.Length == 0)
{
AuthDlg authDlg = new AuthDlg();
if(authDlg.ShowDialog() != DialogResult.OK)
throw new QuietEx();
if(authDlg.Passwd.Length <= 0)
throw new WarnEx(App.GetStr("Empty password!"));
opts.Passwd = authDlg.Passwd;
}
byte[] challenge = ReadBytes(RfbSize.AuthChallenge);
VncAuth.EncryptBytes(challenge, opts.Passwd);
WriteBytes(challenge);
RfbAuthResult authResult = (RfbAuthResult)ReadUInt32();
switch(authResult)
{
case RfbAuthResult.Ok:
break;
case RfbAuthResult.Failed:
throw new WarnEx(App.GetStr("Authentication failed!"));
case RfbAuthResult.TooMany:
throw new WarnEx(App.GetStr("Too many!"));
default:
throw new WarnEx(App.GetStr("Authentication failed but reason unknown!"));
}
break;
default:
throw new WarnEx(App.GetStr("Authentication scheme unknown!"));
}
}
private void SendCliInit()
{
byte[] msg = RfbProtoUtil.GetCliInitMsg(opts.ViewOpts.ShareServ);
WriteBytes(msg);
}
private void ReadServInit()
{
byte[] msg = ReadBytes(RfbSize.ServInit);
servInit = new ServInit(msg);
frameBufWidth = servInit.Width;
frameBufHeight = servInit.Height;
desktopName = ReadAsciiStr((int)servInit.NameLen);
}
private void SetPixelFormat()
{
byte[] msg;
if(opts.ViewOpts.PixelSize == PixelSize.Force8Bit)
{
bpp = 8;
depth = 8;
isBigEndian = false;
isTrueColor = true;
redMax = 7;
greenMax = 7;
blueMax = 3;
redShift = 0;
greenShift = 3;
blueShift = 6;
bytesPp = 1;
}
else if(opts.ViewOpts.PixelSize == PixelSize.Force16Bit || !servInit.IsTrueColor)
{
bpp = 16;
depth = 16;
isBigEndian = false;
isTrueColor = true;
redMax = 63;
greenMax = 31;
blueMax = 31;
redShift = 0;
greenShift = 6;
blueShift = 11;
bytesPp = 2;
}
else
{
bpp = servInit.Bpp;
depth = servInit.Depth;
isBigEndian = false;
isTrueColor = servInit.IsTrueColor;
redMax = servInit.RedMax;
greenMax = servInit.GreenMax;
blueMax = servInit.BlueMax;
redShift = servInit.RedShift;
greenShift = servInit.GreenShift;
blueShift = servInit.BlueShift;
bytesPp = (byte)((bpp + 7) / 8);
}
msg = RfbProtoUtil.GetSetPixelFormatMsg(bpp, depth, isBigEndian, isTrueColor, redMax, greenMax, blueMax, redShift, greenShift, blueShift);
WriteBytes(msg, RfbCliMsgType.SetPixelFormat);
}
private void SetEncodings()
{
// We use a stack here. The least favored encoding is pushed onto the stack first.
Stack stack = new Stack();
stack.Push(RfbEncoding.Raw);
stack.Push(RfbEncoding.CopyRect);
stack.Push(RfbEncoding.Rre);
// We do support CoRRE encoding.
// However, Ultra-VNC server is broken.
// If we use CoRRE and server-side scaling is enabled, the server will
// send us frame buffer updates with number of rectangles set incorrectly.
// So the morale of the story is not to use CoRRE. If we know the server
// does not scale the buffer, then we can enable CoRRE.
// But this can all be avoided by using Hextile.
//stack.Push(RfbEncoding.CoRre);
stack.Push(RfbEncoding.Hex);
stack.Push(RfbEncoding.NewFBSize);
byte[] msg;
msg = RfbProtoUtil.GetSetEncodingsMsgHdr((UInt16)stack.Count);
WriteBytes(msg, RfbCliMsgType.SetEncodings);
RfbEncoding[] encodings = new RfbEncoding[stack.Count];
stack.ToArray().CopyTo(encodings, 0);
msg = RfbProtoUtil.GetSetEncodingsMsg(encodings);
WriteBytes(msg);
}
private void EstNetworkConn()
{
// We use the connection manager on PPCs and Smartphones.
if(App.DevCap.Lvl >= DevCapLvl.Desktop)
return;
networkConn = new NetworkConn("http://" + opts.Host + "/");
networkConn.Est();
}
private void RelNetworkConn()
{
// We use the connection manager on PPCs and Smartphones.
if(App.DevCap.Lvl >= DevCapLvl.Desktop)
return;
if(networkConn != null)
{
networkConn.Rel();
networkConn = null;
}
}
private void CleanUp()
{
// We don't cleanup majorVer, minorVer, etc. here because
// we will always read them when run is called.
if(writer != null)
{
writer.Close();
writer = null;
}
if(reader != null)
{
reader.Close();
reader = null;
}
if(stream != null)
{
stream.Close();
stream = null;
}
if(tcpClient != null)
{
tcpClient.Close();
tcpClient = null;
}
RelNetworkConn();
opts = null;
viewOpts = null;
}
internal void Run(ViewOpts viewOpts)
{
this.viewOpts = viewOpts;
Run();
}
internal void Run(ConnOpts opts)
{
this.opts = opts;
Run();
}
internal void Run()
{
try
{
// Get connection details from the user.
if(opts == null)
GetConnDetails();
// Establish a network (not VNC) connection with the connection manager.
EstNetworkConn();
// Make a connection to the server.
if(opts.ConnMode == ConnMode.Active)
Connect();
else
Listen();
// Negotiate the protocol version with the server.
NegoProtoVer();
// Authenticate the user.
Auth();
// Send client initialization message.
SendCliInit();
// Read server initialization message.
ReadServInit();
SetPixelFormat();
SetEncodings();
// Create a display locally.
CreateDisp();
// Logically speaking I should send this AFTER sending a refresh request with the
// default width and height. But for some strange reason it does not work on the
// emulator (real devices work fine). I have to send this before the first refresh
// request.
// In addition, a refresh request must be sent here. If we wait until a resize frame
// buffer message, we will wait forever.
if(opts.ViewOpts.ServScaling != ServScaling.Default)
SendSetScale((byte)opts.ViewOpts.ServScaling);
// Ask the server to send us the entire screen.
SendUpdReq(0, 0, frameBufWidth, frameBufHeight, false);
termBgThread = false;
(new Thread(new ThreadStart(Start))).Start();
App.AddConn(this);
}
catch(IOException)
{
CleanUp();
MessageBox.Show(App.GetStr("Unable to communicate with the server!"),
App.GetStr("Error"),
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation,
MessageBoxDefaultButton.Button1);
}
catch(QuietEx)
{
CleanUp();
}
catch(WarnEx ex)
{
CleanUp();
MessageBox.Show(ex.Message,
App.GetStr("Error"),
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation,
MessageBoxDefaultButton.Button1);
}
}
private void SendUpdReq(UInt16 x, UInt16 y, UInt16 width, UInt16 height, bool incremental)
{
byte[] msg = RfbProtoUtil.GetFrameBufUpdReqMsg(x, y, width, height, incremental);
WriteBytes(msg, RfbCliMsgType.FrameBufUpdReq);
}
internal void SendSetScale(byte scale)
{
byte[] msg = RfbProtoUtil.GetSetScaleMsg(scale);
WriteBytes(msg, RfbCliMsgType.SetScale);
}
private Color GetColorFromData(byte[] data, UInt32 offset)
{
return GetColorFromPixel(RfbProtoUtil.GetPixelFromData(data, offset, bytesPp));
}
private Color GetColorFromPixel(UInt32 pixel)
{
int red = (int)((pixel >> redShift) & redMax) * 255 / redMax;
int green = (int)((pixel >> greenShift) & greenMax) * 255 / greenMax;
int blue = (int)((pixel >> blueShift) & blueMax) * 255 / blueMax;
return Color.FromArgb(red, green, blue);
}
private void ReadRawRect(Rectangle rect)
{
byte[] rectBytes = ReadBytes(rect.Width * rect.Height * bytesPp);
view.LockFrameBuf();
try
{
// TODO: Anything faster?
int curPos = 0;
for(int i = 0; i < rect.Height; i++)
{
for(int j = 0; j < rect.Width; j++)
{
view[(UInt16)(rect.X + j), (UInt16)(rect.Y + i)] = GetColorFromData(rectBytes, (UInt32)curPos);
curPos += bytesPp;
}
}
}
catch(OverflowException)
{
// Swallow this exception. For some strange reason UltraVNC sends X and Y > 65K.
}
catch(ArgumentException)
{
// Swallow this exception. For some strange reason UltraVNC sends invalid values.
}
view.UnlockFrameBuf();
}
private void ReadCopyRect(Rectangle rect)
{
byte[] rectBytes = ReadBytes(RfbSize.CopyRect);
CopyRectMsg srcRect = new CopyRectMsg(rectBytes);
view.LockFrameBuf();
view.CopyRect(rect, srcRect.X, srcRect.Y);
view.UnlockFrameBuf();
}
private void FillRreRect(Rectangle rect, Color bgColor, RreSubRectMsg[] subRects)
{
view.LockFrameBuf();
view.FillRect(rect, bgColor);
for(int i = 0; i < subRects.Length; i++)
{
Rectangle subRect = new Rectangle();
subRect.X = rect.X + subRects[i].X;
subRect.Y = rect.Y + subRects[i].Y;
subRect.Width = subRects[i].Width;
subRect.Height = subRects[i].Height;
view.FillRect(subRect, GetColorFromPixel(subRects[i].Pixel));
}
view.UnlockFrameBuf();
}
private void ReadRreRectCore(Rectangle rect, bool isCompact)
{
UInt32 numSubRects = ReadUInt32();
byte[] data = ReadBytes(bytesPp);
Color bgColor = GetColorFromData(data, 0);
int subRectSize = bytesPp;
if(isCompact)
subRectSize += RfbSize.CoRreSubRect;
else
subRectSize += RfbSize.RreSubRect;
RreSubRectMsg[] subRects = new RreSubRectMsg[numSubRects];
for(int i = 0; i < numSubRects; i++)
{
byte[] rectBytes = ReadBytes(subRectSize);
subRects[i] = new RreSubRectMsg(rectBytes, bytesPp, isCompact);
}
FillRreRect(rect, bgColor, subRects);
}
private void ReadRreRect(Rectangle rect)
{
ReadRreRectCore(rect, false);
}
private void ReadCoRreRect(Rectangle rect)
{
ReadRreRectCore(rect, true);
}
private void ReadHexRect(Rectangle rect)
{
Color bgColor = App.Black;
UInt32 fgPixel = 0;
Rectangle tile = new Rectangle();
for(tile.Y = rect.Y; tile.Y < rect.Bottom; tile.Y += 16)
{
for(tile.X = rect.X; tile.X < rect.Right; tile.X += 16)
{
tile.Width = 16;
tile.Height = 16;
tile.Width = Math.Min(tile.Right, rect.Right) - tile.Left;
tile.Height = Math.Min(tile.Bottom, rect.Bottom) - tile.Top;
RfbHexSubEncoding encoding = (RfbHexSubEncoding)ReadByte();
if((encoding & RfbHexSubEncoding.Raw) != 0)
{
ReadRawRect(tile);
if(opts.ViewOpts.ScrnUpdAlgo == ScrnUpdAlgo.Asap)
view.InvalidateRect(tile);
continue;
}
byte[] data;
if((encoding & RfbHexSubEncoding.BgSpec) != 0)
{
data = ReadBytes(bytesPp);
bgColor = GetColorFromData(data, 0);
}
if((encoding & RfbHexSubEncoding.FgSpec) != 0)
{
data = ReadBytes(bytesPp);
fgPixel = RfbProtoUtil.GetPixelFromData(data, 0, bytesPp);
}
byte numSubRects = 0;
if((encoding & RfbHexSubEncoding.AnySubRects) != 0)
numSubRects = ReadByte();
bool subRectsColored = ((encoding & RfbHexSubEncoding.SubRectsColored) != 0);
int subRectSize = RfbSize.HexSubRect;
subRectSize += subRectsColored? (int)bytesPp : 0;
RreSubRectMsg[] subRects = new RreSubRectMsg[numSubRects];
byte[] rectBytes = ReadBytes(subRectSize * numSubRects);
for(int i = 0; i < numSubRects; i++)
subRects[i] = new HexSubRectMsg(rectBytes, (UInt32)(i * subRectSize), bytesPp, subRectsColored, fgPixel);
FillRreRect(tile, bgColor, subRects);
if(opts.ViewOpts.ScrnUpdAlgo == ScrnUpdAlgo.Asap)
view.InvalidateRect(tile);
}
}
}
internal void SendUpdReq(bool incremental)
{
if(IsFmtChgPending)
{
IsFmtChgPending = false;
SetPixelFormat();
SendUpdReq(0, 0, frameBufWidth, frameBufHeight, false);
}
else
SendUpdReq(0, 0, frameBufWidth, frameBufHeight, incremental);
}
private void ReadScrnUpd()
{
byte[] msg = ReadBytes(RfbSize.FrameBufUpd - 1);
UInt16 numRects = RfbProtoUtil.GetNumRectsFromFrameBufUpdMsg(msg);
for(int i = 0; i < numRects; i++)
{
msg = ReadBytes(RfbSize.FrameBufUpdRectHdr);
FrameBufUpdRectMsgHdr frameBufUpdRectHdr = new FrameBufUpdRectMsgHdr(msg);
Rectangle rect = new Rectangle(frameBufUpdRectHdr.X, frameBufUpdRectHdr.Y, frameBufUpdRectHdr.Width, frameBufUpdRectHdr.Height);
if(frameBufUpdRectHdr.Encoding == RfbEncoding.NewFBSize)
{
frameBufWidth = (UInt16)rect.Width;
frameBufHeight = (UInt16)rect.Height;
if(!termBgThread)
view.NewFrameBuf(frameBufWidth, frameBufHeight);
break;
}
switch(frameBufUpdRectHdr.Encoding)
{
case RfbEncoding.Raw:
ReadRawRect(rect);
if(opts.ViewOpts.ScrnUpdAlgo == ScrnUpdAlgo.Asap)
view.InvalidateRect(rect);
break;
case RfbEncoding.CopyRect:
ReadCopyRect(rect);
if(opts.ViewOpts.ScrnUpdAlgo == ScrnUpdAlgo.Asap)
view.InvalidateRect(rect);
break;
case RfbEncoding.Rre:
ReadRreRect(rect);
if(opts.ViewOpts.ScrnUpdAlgo == ScrnUpdAlgo.Asap)
view.InvalidateRect(rect);
break;
case RfbEncoding.CoRre:
ReadCoRreRect(rect);
if(opts.ViewOpts.ScrnUpdAlgo == ScrnUpdAlgo.Asap)
view.InvalidateRect(rect);
break;
case RfbEncoding.Hex:
ReadHexRect(rect);
break;
default:
throw new WarnEx(App.GetStr("Server is using unknown encoding!"));
}
}
if(opts.ViewOpts.ScrnUpdAlgo != ScrnUpdAlgo.Asap)
view.Invalidate();
// Do this in the UI thread so we always send data in one thread.
view.SendUpdReq();
}
private void ReadServCutTxt()
{
// .NET CF does not have built-in support for the clipboard.
// We ignore this message at the moment.
byte[] msg = ReadBytes(RfbSize.ServCutTxt - 1);
UInt32 len = RfbProtoUtil.GetLenFromServCutTxtMsg(msg);
string txt = ReadAsciiStr((int)len);
}
private void ReadResizeFrameBuf()
{
byte[] msg = ReadBytes(RfbSize.ResizeFrameBuf - 1);
ResizeFrameBufMsg resizeFrameBufMsg = new ResizeFrameBufMsg(msg);
frameBufWidth = resizeFrameBufMsg.Width;
frameBufHeight = resizeFrameBufMsg.Height;
// This call actually involves an Invoke, so we need to check termBgThread to make
// sure that it does not hang.
// TODO: Time to reorg the codebase...
if(!termBgThread)
view.ResizeFrameBuf(frameBufWidth, frameBufHeight);
}
/// <summary>
/// This is the entry point of the background thread that handles
/// server messages.
/// </summary>
private void Start()
{
// This is a background thread so the priority should be lower.
Thread.CurrentThread.Priority = ThreadPriority.BelowNormal;
try
{
while(!termBgThread)
{
// Yield to other threads so this thread does not dominate.
Thread.Sleep(App.Delta);
// Avoid the blocking ReadByte() if we have nothing to read.
if(!stream.DataAvailable)
continue;
RfbServMsgType msgType = (RfbServMsgType)ReadByte();
switch(msgType)
{
case RfbServMsgType.FrameBufUpd:
ReadScrnUpd();
break;
case RfbServMsgType.SetColorMapEntries:
throw new WarnEx(App.GetStr("The server is sending SetColorMapEntries!"));
case RfbServMsgType.Bell:
break;
case RfbServMsgType.ServCutTxt:
ReadServCutTxt();
break;
case RfbServMsgType.ResizeFrameBuf:
ReadResizeFrameBuf();
break;
default:
throw new WarnEx(App.GetStr("The server is sending unknown message!"));
}
}
}
catch(SocketException)
{
MessageBox.Show(App.GetStr("Unable to communicate with the server!"),
App.GetStr("Error"),
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation,
MessageBoxDefaultButton.Button1);
// If termBgThread is true then view has been closed.
// Don't Invoke or this thread will hang due to a .NET CF bug.
// Technically speaking there is a slight chance that the view closes before Invoke
// but after checking termBgThread, so this is not bullet proof.
if(!termBgThread)
view.Invoke(closeHdr);
}
catch(IOException)
{
MessageBox.Show(App.GetStr("Unable to communicate with the server!"),
App.GetStr("Error"),
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation,
MessageBoxDefaultButton.Button1);
if(!termBgThread)
view.Invoke(closeHdr);
}
catch(QuietEx)
{
if(!termBgThread)
view.Invoke(closeHdr);
}
catch(WarnEx ex)
{
MessageBox.Show(ex.Message,
App.GetStr("Error"),
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation,
MessageBoxDefaultButton.Button1);
if(!termBgThread)
view.Invoke(closeHdr);
}
finally
{
CleanUp();
}
}
}
}