-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClientConnection.cpp
More file actions
executable file
·2002 lines (1682 loc) · 57.4 KB
/
Copy pathClientConnection.cpp
File metadata and controls
executable file
·2002 lines (1682 loc) · 57.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (C) 1997, 1998 Olivetti & Oracle Research Laboratory
// Copyright (C) 2025-2026 RasPython3
//
// 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.orl.co.uk/vnc or contact
// the authors on vnc@orl.co.uk for information on obtaining it.
// This is the main source for a ClientConnection object.
// It handles almost everything to do with a connection to a server.
// The decoding of specific rectangle encodings is done in separate files.
#include "stdhdrs.h"
#include "vncviewer.h"
#include "omnithreadce.h"
#define SD_BOTH 0x02
#include "ClientConnection.h"
#include "SessionDialog.h"
#include "AuthDialog.h"
#include "AboutBox.h"
#include "Exception.h"
extern "C" {
#include "vncauth.h"
}
#define INITIALNETBUFSIZE 4096
#define MAX_ENCODINGS 10
#define VWR_WND_CLASS_NAME _T("VNCviewer")
const rfbPixelFormat vnc8bitFormat = {8, 8, 1, 1, 7,7,3, 0,3,6,0,0};
const rfbPixelFormat vnc16bitFormat = {16, 16, 1, 1, 63, 31, 31, 0,6,11,0,0};
const rfbPixelFormat vnc32bitFormat = {32, 24, 1, 1, 255, 255, 255, 0,8,16,0,0};
#ifndef __MINGW32CE__
static LRESULT CALLBACK ClientConnection::WndProc(HWND hwnd, UINT iMsg, WPARAM wParam, LPARAM lParam);
#endif
// Some handy classes for temporary GDI object selection
// These select objects when constructed and automatically release them when destructed.
class ObjectSelector {
public:
ObjectSelector(HDC hdc, HGDIOBJ hobj) { m_hdc = hdc; m_hOldObj = SelectObject(hdc, hobj); }
~ObjectSelector() { m_hOldObj = SelectObject(m_hdc, m_hOldObj); }
HGDIOBJ m_hOldObj;
HDC m_hdc;
};
class PaletteSelector {
public:
PaletteSelector(HDC hdc, HPALETTE hpal) {
m_hdc = hdc;
m_hOldPal = SelectPalette(hdc, hpal, FALSE);
RealizePalette(hdc);
}
~PaletteSelector() {
m_hOldPal = SelectPalette(m_hdc, m_hOldPal, FALSE);
RealizePalette(m_hdc);
}
HPALETTE m_hOldPal;
HDC m_hdc;
};
class TempDC {
public:
TempDC(HWND hwnd) { m_hdc = GetDC(hwnd); m_hwnd = hwnd; }
~TempDC() { ReleaseDC(m_hwnd, m_hdc); }
operator HDC() {return m_hdc;};
HDC m_hdc;
HWND m_hwnd;
};
// *************************************************************************
// A Client connection involves two threads - the main one which sets up
// connections and processes window messages and inputs, and a
// client-specific one which receives, decodes and draws output data
// from the remote server.
// This first section contains bits which are generally called by the main
// program thread.
// *************************************************************************
ClientConnection::ClientConnection(VNCviewerApp *pApp)
{
Init(pApp);
}
ClientConnection::ClientConnection(VNCviewerApp *pApp, SOCKET sock)
{
Init(pApp);
m_sock = sock;
struct sockaddr_in svraddr;
int sasize = sizeof(svraddr);
if (getpeername(sock, (struct sockaddr *) &svraddr,
&sasize) != SOCKET_ERROR) {
_stprintf(m_host, _T("%d.%d.%d.%d"),
svraddr.sin_addr.S_un.S_un_b.s_b1,
svraddr.sin_addr.S_un.S_un_b.s_b2,
svraddr.sin_addr.S_un.S_un_b.s_b3,
svraddr.sin_addr.S_un.S_un_b.s_b4);
m_port = svraddr.sin_port;
} else {
_tcscpy(m_host,_T("(unknown)"));
m_port = 0;
};
}
ClientConnection::ClientConnection(VNCviewerApp *pApp, LPTSTR host, int port)
{
Init(pApp);
_tcsncpy(m_host, host, 256);
m_port = port;
}
void ClientConnection::Init(VNCviewerApp *pApp)
{
m_hwnd = 0;
m_desktopName = NULL;
m_port = -1;
m_netbuf = NULL;
m_netbufsize = 0;
m_hwndNextViewer = NULL;
m_pApp = pApp;
m_dormant = false;
m_hBitmapDC = NULL;
m_hBitmap = NULL;
m_hTempBitmapDC = NULL;
m_hTempBitmap = NULL;
m_hPalette = NULL;
// We take the initial conn options from the application defaults
m_opts = m_pApp->m_options;
m_sock = INVALID_SOCKET;
m_bKillThread = false;
m_threadStarted = true;
m_running = false;
m_pendingFormatChange = false;
m_hScrollPos = 0; m_vScrollPos = 0; m_barheight=0;
m_fullScreenMode = false;
// Create a buffer for various network operations
CheckBufferSize(INITIALNETBUFSIZE);
m_pApp->RegisterConnection(this);
UpdateWindow(m_hwnd);
}
//
// Run() creates the connection if necessary, does the initial negotiations
// and then starts the thread running which does the output (update) processing.
// If Run throws an Exception, the caller must delete the ClientConnection object.
//
void ClientConnection::Run()
{
int ecode;
__try {
// Get the host name and port if we haven't got it
if (m_port == -1)
GetConnectDetails();
// Connect if we're not already connected
if (m_sock == INVALID_SOCKET)
Connect();
SetSocketOptions();
NegotiateProtocolVersion();
Authenticate();
// Set up widows etc
CreateDisplay();
SendClientInit();
ReadServerInit();
CreateLocalFramebuffer();
SetupPixelFormat();
SetFormatAndEncodings();
// This starts the worker thread.
// The rest of the processing continues in run_undetached.
start_undetached();
} __except ((ecode = GetExceptionCode( ),
(ecode == VNC_EXC_HOSTNAME) ||
(ecode == VNC_EXC_CONNECT) ||
(ecode == VNC_EXC_AUTHFAIL) )) {
switch (ecode) {
case VNC_EXC_HOSTNAME:
MessageBox(NULL, _T("Server address not found"),
_T("Connection failed"), MB_OK | MB_TOPMOST | MB_ICONEXCLAMATION);
break;
case VNC_EXC_CONNECT:
MessageBox(NULL, _T("Could not connect to server"),
_T("Connection failed"), MB_OK | MB_TOPMOST | MB_ICONEXCLAMATION);
break;
case VNC_EXC_AUTHFAIL:
MessageBox(NULL, _T("Authentication failed"),
_T("VNC authentication"), MB_OK | MB_TOPMOST | MB_ICONEXCLAMATION);
break;
}
RaiseException(ecode, 0, 0, 0);
}
}
void ClientConnection::CreateDisplay()
{
// Create the window
WNDCLASS wndclass;
wndclass.style = 0;
wndclass.lpfnWndProc = ClientConnection::WndProc;
wndclass.cbClsExtra = 0;
wndclass.cbWndExtra = 0;
wndclass.hInstance = m_pApp->m_instance;
wndclass.hIcon = LoadIcon(m_pApp->m_instance, MAKEINTRESOURCE(IDI_MAINICON));
wndclass.hCursor = LoadCursor(m_pApp->m_instance, MAKEINTRESOURCE(IDC_DOTCURSOR));
wndclass.hbrBackground = (HBRUSH) GetStockObject(BLACK_BRUSH);
wndclass.lpszMenuName = (const TCHAR *) NULL;
wndclass.lpszClassName = VWR_WND_CLASS_NAME;
RegisterClass(&wndclass);
#ifdef UNDER_CE
const DWORD winstyle = WS_VSCROLL | WS_HSCROLL;
#else
const DWORD winstyle = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU |
WS_MINIMIZEBOX | WS_THICKFRAME | WS_VSCROLL | WS_HSCROLL;
#endif
m_hwnd = CreateWindow(VWR_WND_CLASS_NAME,
_T("VNCviewer"),
winstyle,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT, // x-size
CW_USEDEFAULT, // y-size
NULL, // Parent handle
NULL, // Menu handle
m_pApp->m_instance,
NULL);
ShowWindow(m_hwnd, SW_HIDE);
// record which client created this window
SetWindowLong(m_hwnd, GWL_USERDATA, (LONG) this);
// Create a memory DC which we'll use for drawing to
// the local framebuffer
m_hBitmapDC = CreateCompatibleDC(NULL);
if (m_opts.m_UseTemp) {
m_hTempBitmapDC = CreateCompatibleDC(NULL);
}
#ifndef UNDER_CE
// Set a suitable palette up
if (GetDeviceCaps(m_hBitmapDC, RASTERCAPS) & RC_PALETTE) {
log.Print(3, _T("Palette-based display - %d entries, %d reserved\n"),
GetDeviceCaps(m_hBitmapDC, SIZEPALETTE), GetDeviceCaps(m_hBitmapDC, NUMRESERVED));
BYTE buf[sizeof(LOGPALETTE)+216*sizeof(PALETTEENTRY)];
LOGPALETTE *plp = (LOGPALETTE *) buf;
int pepos = 0;
for (int r = 5; r >= 0; r--) {
for (int g = 5; g >= 0; g--) {
for (int b = 5; b >= 0; b--) {
plp->palPalEntry[pepos].peRed = r * 255 / 5;
plp->palPalEntry[pepos].peGreen = g * 255 / 5;
plp->palPalEntry[pepos].peBlue = b * 255 / 5;
plp->palPalEntry[pepos].peFlags = NULL;
pepos++;
}
}
}
plp->palVersion = 0x300;
plp->palNumEntries = 216;
m_hPalette = CreatePalette(plp);
}
#endif
#ifndef UNDER_CE
// Add stuff to System menu
HMENU hsysmenu = GetSystemMenu(m_hwnd, FALSE);
if (!m_opts.m_restricted) {
AppendMenu(hsysmenu, MF_STRING, IDC_OPTIONBUTTON, _T("Connection &options..."));
AppendMenu(hsysmenu, MF_STRING, ID_CONN_ABOUT, _T("Connection &info"));
AppendMenu(hsysmenu, MF_STRING, ID_REQUEST_REFRESH, _T("Request screen &refresh"));
AppendMenu(hsysmenu, MF_SEPARATOR, NULL, NULL);
AppendMenu(hsysmenu, MF_STRING, ID_FULLSCREEN, _T("&Full screen"));
AppendMenu(hsysmenu, MF_SEPARATOR, NULL, NULL);
AppendMenu(hsysmenu, MF_STRING, ID_CONN_CTLALTDEL, _T("Send Ctl-Alt-Del"));
AppendMenu(hsysmenu, MF_STRING, ID_CONN_CTLDOWN, _T("Ctrl Down"));
AppendMenu(hsysmenu, MF_STRING, ID_CONN_CTLUP, _T("Ctrl Up"));
AppendMenu(hsysmenu, MF_STRING, ID_CONN_ALTDOWN, _T("Alt Down"));
AppendMenu(hsysmenu, MF_STRING, ID_CONN_ALTUP, _T("Alt Up"));
AppendMenu(hsysmenu, MF_SEPARATOR, NULL, NULL);
AppendMenu(hsysmenu, MF_STRING, ID_NEWCONN, _T("Ne&w connection..."));
}
AppendMenu(hsysmenu, MF_SEPARATOR, NULL, NULL);
AppendMenu(hsysmenu, MF_STRING, IDD_APP_ABOUT, _T("&About VNCviewer..."));
if (m_opts.m_listening) {
AppendMenu(hsysmenu, MF_SEPARATOR, NULL, NULL);
AppendMenu(hsysmenu, MF_STRING, ID_CLOSEDAEMON, _T("Close listening &daemon"));
}
DrawMenuBar(m_hwnd);
#else
// CE doesn't have a system menu
// Create a Rebar control instead
m_hbands = CommandBands_Create(m_pApp->m_instance, m_hwnd,
ID_COMMANDBANDS, RBS_VARHEIGHT | RBS_BANDBORDERS, NULL);
REBARBANDINFO arbbi[1];
arbbi[0].cbSize = sizeof(REBARBANDINFO);
arbbi[0].fMask = RBBIM_ID | RBBIM_SIZE ;
arbbi[0].wID = ID_MENUBAND;
arbbi[0].cx = 100;
CommandBands_AddBands(m_hbands, m_pApp->m_instance, 1, arbbi);
HWND hwnd = CommandBands_GetCommandBar(m_hbands, 0);
CommandBar_InsertMenubar(hwnd, m_pApp->m_instance, IDR_COMMANDMENU, 0);
#endif
// Set up clipboard watching
#ifndef UNDER_CE
// We want to know when the clipboard changes, so
// insert ourselves in the viewer chain. But doing
// this will cause us to be notified immediately of
// the current state.
// We don't want to send that.
m_initialClipboardSeen = false;
m_hwndNextViewer = SetClipboardViewer(m_hwnd);
#endif
}
void ClientConnection::GetConnectDetails()
{
SessionDialog sessdlg(&m_opts);
if (!sessdlg.DoDialog()) {
RaiseException( VNC_EXC_QUIETCLOSE, 0, 0, 0);
}
_tcsncpy(m_host, sessdlg.m_host, 256);
m_port = sessdlg.m_port;
}
void ClientConnection::Connect()
{
struct sockaddr_in thataddr;
int res;
m_sock = socket(PF_INET, SOCK_STREAM, 0);
if (m_sock == INVALID_SOCKET) {
RaiseException( VNC_EXC_SOCKET, 0, 0, 0);
}
int one = 1;
__try {
char ansihost[256];
int origlen = _tcslen(m_host);
int newlen = WideCharToMultiByte(
CP_ACP, // code page
0, // performance and mapping flags
m_host, // address of wide-character string
origlen, // number of characters in string
ansihost, // address of buffer for new string
255, // size of buffer
NULL, NULL );
ansihost[newlen]= '\0';
// The host may be specified as a dotted address "a.b.c.d"
// Try that first
thataddr.sin_addr.s_addr = inet_addr(ansihost);
// If it wasn't one of those, do gethostbyname
if (thataddr.sin_addr.s_addr == INADDR_NONE) {
LPHOSTENT lphost;
lphost = gethostbyname(ansihost);
if (lphost == NULL) {
RaiseException( VNC_EXC_HOSTNAME, 0, 0, 0);
};
thataddr.sin_addr.s_addr = ((LPIN_ADDR) lphost->h_addr)->s_addr;
};
thataddr.sin_family = AF_INET;
thataddr.sin_port = htons(m_port);
res = connect(m_sock, (LPSOCKADDR) &thataddr, sizeof(thataddr));
if (res == SOCKET_ERROR) RaiseException( VNC_EXC_CONNECT, 0, 0, 0);
} __except ( EXCEPTION_EXECUTE_HANDLER ) {
if (m_sock) closesocket(m_sock);
m_sock = 0;
m_pApp->DeregisterConnection(this);
SendMessage(m_hwnd, WM_CLOSE,0,0);
RaiseException( GetExceptionCode(), 0, 0, 0);;
}
}
void ClientConnection::SetSocketOptions() {
// Disable Nagle's algorithm
BOOL nodelayval = TRUE;
if (setsockopt(m_sock, IPPROTO_TCP, TCP_NODELAY, (const char *) &nodelayval, sizeof(BOOL)))
RaiseException( VNC_EXC_SOCKET, 0, 0, 0);
}
void ClientConnection::NegotiateProtocolVersion()
{
rfbProtocolVersionMsg pv;
/* if the connection is immediately closed, don't report anything, so
that pmw's monitor can make test connections */
__try {
ReadExact(pv, sz_rfbProtocolVersionMsg);
} __except(EXCEPTION_EXECUTE_HANDLER) {
log.Print(0, _T("Error reading protocol version\n"));
RaiseException(VNC_EXC_QUIETCLOSE,0,0,0);
}
pv[sz_rfbProtocolVersionMsg] = 0;
// XXX This is a hack. Under CE we just return to the server the
// version number it gives us without parsing it.
// Too much hassle replacing sscanf for now. Fix this!
#if defined(UNDER_CE) && (!defined(_WIN32_WCE) || _WIN32_WCE < 0x0200)
m_majorVersion = rfbProtocolMajorVersion;
m_minorVersion = rfbProtocolMinorVersion;
#else
if (sscanf(pv,rfbProtocolVersionFormat,&m_majorVersion,&m_minorVersion) != 2) {
RaiseException(VNC_EXC_INVALID,0,0,0);
}
log.Print(0, _T("RFB server supports protocol version %d.%d\n"),
m_majorVersion,m_minorVersion);
if ((m_majorVersion == 3) && (m_minorVersion < 3)) {
/* if server is 3.2 we can't use the new authentication */
log.Print(0, _T("Can't use IDEA authentication\n"));
/* This will be reported later if authentication is requested*/
} else {
/* any other server version, just tell the server what we want */
m_majorVersion = rfbProtocolMajorVersion;
m_minorVersion = rfbProtocolMinorVersion;
}
sprintf(pv,rfbProtocolVersionFormat,m_majorVersion,m_minorVersion);
#endif
WriteExact(pv, sz_rfbProtocolVersionMsg);
log.Print(0, _T("Connected to RFB server, using protocol version %d.%d\n"),
rfbProtocolMajorVersion, rfbProtocolMinorVersion);
}
void ClientConnection::Authenticate()
{
CARD32 authScheme, reasonLen, authResult;
CARD8 challenge[CHALLENGESIZE];
ReadExact((char *)&authScheme, 4);
authScheme = Swap32IfLE(authScheme);
switch (authScheme) {
case rfbConnFailed:
ReadExact((char *)&reasonLen, 4);
reasonLen = Swap32IfLE(reasonLen);
CheckBufferSize(reasonLen+1);
ReadString(m_netbuf, reasonLen);
log.Print(0, _T("RFB connection failed, reason: %s\n"), m_netbuf);
RaiseException(VNC_EXC_CONNFAIL,0,0,0);
break;
case rfbNoAuth:
log.Print(0, _T("No authentication needed\n"));
break;
case rfbVncAuth:
{
if ((m_majorVersion == 3) && (m_minorVersion < 3)) {
/* if server is 3.2 we can't use the new authentication */
log.Print(0, _T("Can't use IDEA authentication\n"));
MessageBox(NULL,
_T("Sorry - this server uses an older authentication scheme\n\r")
_T("which is no longer supported."),
_T("Protocol Version error"),
MB_OK | MB_ICONSTOP | MB_SETFOREGROUND | MB_TOPMOST);
RaiseException(VNC_EXC_UNIMPLEMENTED,0,0,0);
}
ReadExact((char *)challenge, CHALLENGESIZE);
AuthDialog ad;
ad.DoDialog();
char passwd[256];
#ifndef UNDER_CE
strcpy(passwd, ad.m_passwd);
#else
// CE will return a wide string from dialog box.
int origlen = _tcslen(ad.m_passwd);
int newlen = WideCharToMultiByte(
CP_ACP, 0, ad.m_passwd, origlen, passwd, 255,
NULL, NULL );
passwd[newlen]= '\0';
#endif
if (strlen(passwd) == 0) {
log.Print(0, _T("Password had zero length\n"));
RaiseException(VNC_EXC_USERERROR,0,0,0);
}
if (strlen(passwd) > 8) {
passwd[8] = '\0';
}
vncEncryptBytes(challenge, passwd);
/* Lose the password from memory */
for (int i=0; i< (int) strlen(passwd); i++) {
passwd[i] = '\0';
}
WriteExact((char *) challenge, CHALLENGESIZE);
ReadExact((char *) &authResult, 4);
authResult = Swap32IfLE(authResult);
switch (authResult) {
case rfbVncAuthOK:
log.Print(0, _T("VNC authentication succeeded\n"));
break;
case rfbVncAuthFailed:
log.Print(0, _T("VNC authentication failed!\n"));
RaiseException(VNC_EXC_AUTHFAIL,0,0,0);
case rfbVncAuthTooMany:
log.Print(0, _T("Too many attempts!\n"));
RaiseException(VNC_EXC_AUTHFAIL,0,0,0);
break;
default:
log.Print(0, _T("Unknown VNC authentication result: %d\n"),
(int)authResult);
RaiseException(VNC_EXC_UNIMPLEMENTED,0,0,0);
}
break;
}
default:
log.Print(0, _T("Unknown authentication scheme from RFB server: %d\n"),
(int)authScheme);
RaiseException(VNC_EXC_UNIMPLEMENTED,0,0,0);
}
}
void ClientConnection::SendClientInit()
{
rfbClientInitMsg ci;
ci.shared = m_opts.m_Shared;
WriteExact((char *)&ci, sz_rfbClientInitMsg);
}
void ClientConnection::ReadServerInit()
{
ReadExact((char *)&m_si, sz_rfbServerInitMsg);
m_si.framebufferWidth = Swap16IfLE(m_si.framebufferWidth);
m_si.framebufferHeight = Swap16IfLE(m_si.framebufferHeight);
m_si.format.redMax = Swap16IfLE(m_si.format.redMax);
m_si.format.greenMax = Swap16IfLE(m_si.format.greenMax);
m_si.format.blueMax = Swap16IfLE(m_si.format.blueMax);
m_si.nameLength = Swap32IfLE(m_si.nameLength);
m_desktopName = new TCHAR[m_si.nameLength + 2];
#ifdef UNDER_CE
char *deskNameBuf = new char[m_si.nameLength + 2];
ReadString(deskNameBuf, m_si.nameLength);
MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED,
deskNameBuf, m_si.nameLength,
m_desktopName, m_si.nameLength+1);
delete deskNameBuf;
#else
ReadString(m_desktopName, m_si.nameLength);
#endif
SetWindowText(m_hwnd, m_desktopName);
PaletteSelector p(m_hBitmapDC, m_hPalette);
log.Print(0, _T("Desktop name \"%s\"\n"),m_desktopName);
log.Print(1, _T("Geometry %d x %d depth %d\n"),
m_si.framebufferWidth, m_si.framebufferHeight, m_si.format.depth );
SetWindowText(m_hwnd, m_desktopName);
// Find how large the desktop work area is
RECT workrect;
SystemParametersInfo(SPI_GETWORKAREA, 0, &workrect, 0);
int workwidth = workrect.right - workrect.left;
int workheight = workrect.bottom - workrect.top;
log.Print(2, _T("Screen work area is %d x %d\n"), workwidth, workheight);
// Size the window.
// First we find out how large a window would be needed to hold the whole
// remote screen image.
RECT fullwinrect;
SetRect(&fullwinrect, 0, 0, m_si.framebufferWidth, m_si.framebufferHeight);
AdjustWindowRectEx(&fullwinrect,
GetWindowLong(m_hwnd, GWL_STYLE), GetWindowLong(m_hwnd, GWL_EXSTYLE), FALSE);
UINT bandheight = CommandBands_Height(m_hbands);
m_fullwinwidth = fullwinrect.right - fullwinrect.left;
m_fullwinheight = fullwinrect.bottom - fullwinrect.top + bandheight ;
// Then we use either this, or the screen size, whichever is smaller
m_winwidth = min(m_fullwinwidth, workwidth);
m_winheight = min(m_fullwinheight, workheight);
/* DON'T RESIZE IT
SetWindowPos(m_hwnd, HWND_TOP,
workrect.left + (workwidth-m_winwidth) / 2,
workrect.top + (workheight-m_winheight) / 2,
m_winwidth, m_winheight, SWP_SHOWWINDOW);
*/
ShowWindow(m_hwnd,SW_SHOWNORMAL);
SetForegroundWindow(m_hwnd);
}
// We keep a local copy of the whole screen. This is not sctrictly necessary
// for VNC, but makes scrolling & deiconifying much smoother.
void ClientConnection::CreateLocalFramebuffer() {
// We create a bitmap which has the same pixel characteristics as
// the local display, in the hope that blitting will be faster.
TempDC hdc(m_hwnd);
m_hBitmap = ::CreateCompatibleBitmap(hdc,
m_si.framebufferWidth,
m_si.framebufferHeight);
if (m_hBitmap == NULL)
RaiseException(VNC_EXC_GRAPHICS,0,0,0);
if (m_opts.m_UseTemp) {
m_hTempBitmap = ::CreateCompatibleBitmap(hdc,
m_si.framebufferWidth,
m_si.framebufferHeight);
if (m_hTempBitmap == NULL)
RaiseException(VNC_EXC_GRAPHICS,0,0,0);
}
// Select this bitmap into the DC with an appropriate palette
ObjectSelector b(m_hBitmapDC, m_hBitmap);
PaletteSelector p(m_hBitmapDC, m_hPalette);
// Put a "please wait" message up initially
RECT rect;
SetRect(&rect, 0,0, m_si.framebufferWidth, m_si.framebufferHeight);
COLORREF bgcol = RGB(0xcc, 0xcc, 0xcc);
FillSolidRect(&rect, bgcol);
COLORREF oldbgcol = SetBkColor( m_hBitmapDC, bgcol);
COLORREF oldtxtcol = SetTextColor(m_hBitmapDC, RGB(0,0,64));
rect.right = m_si.framebufferWidth / 2;
rect.bottom = m_si.framebufferHeight / 2;
DrawText (m_hBitmapDC, _T("Please wait - initial screen loading"), -1, &rect,
DT_SINGLELINE | DT_CENTER | DT_VCENTER);
SetBkColor( m_hBitmapDC, oldbgcol);
SetTextColor(m_hBitmapDC, oldtxtcol);
if (m_opts.m_UseTemp) {
ObjectSelector bt(m_hTempBitmapDC, m_hTempBitmap);
PaletteSelector pt(m_hTempBitmapDC, m_hPalette);
if (!BitBlt(m_hTempBitmapDC, 0, 0, m_si.framebufferWidth, m_si.framebufferHeight,
m_hBitmapDC, 0, 0, SRCCOPY)) {
RaiseException(VNC_EXC_GRAPHICS,0,0,0);
}
}
InvalidateRect(m_hwnd, NULL, FALSE);
}
void ClientConnection::SetupPixelFormat() {
#if 0
// Have we requested a reduction to 8-bit?
if (m_opts.m_Use8Bit) {
log.Print(2, _T("Requesting 8-bit truecolour\n"));
m_myFormat = vnc8bitFormat;
#else
// Any preference for color depth?
if (m_opts.m_PreferredDepth > 0) {
log.Print(2, _T("Requesting %d-bit truecolour\n"), m_opts.m_PreferredDepth);
switch (m_opts.m_PreferredDepth) {
case 8:
m_myFormat = vnc8bitFormat;
break;
case 16:
m_myFormat = vnc16bitFormat;
break;
case 32:
m_myFormat = vnc32bitFormat;
break;
default:
log.Print(0, _T("Invalid bit; using server suggestion\n"));
m_myFormat = m_si.format;
}
#endif
// We don't support colormaps so we'll ask the server to convert
} else if (!m_si.format.trueColour) {
// We'll just request a standard 16-bit truecolor
log.Print(2, _T("Requesting 16-bit truecolour\n"));
m_myFormat = vnc16bitFormat;
} else {
// Normally we just use the sever's format suggestion
m_myFormat = m_si.format;
// It's silly requesting more bits than our current display has, but
// in fact it doesn't usually amount to much on the network.
// Windows doesn't support 8-bit truecolour.
// If our display is palette-based, we want more than 8 bit anyway,
// unless we're going to start doing palette stuff at the server.
// So the main use would be a 24-bit true-colour desktop being viewed
// on a 16-bit true-colour display, and unless you have lots of images
// and hence lots of raw-encoded stuff, the size of the pixel is not
// going to make much difference.
// We therefore don't bother with any restrictions, but here's the
// start of the code if we wanted to do it.
if (false) {
// Get a DC for the root window
TempDC hrootdc(NULL);
int localBitsPerPixel = GetDeviceCaps(hrootdc, BITSPIXEL);
int localRasterCaps = GetDeviceCaps(hrootdc, RASTERCAPS);
log.Print(2, _T("Memory DC has depth of %d and %s pallete-based.\n"),
localBitsPerPixel, (localRasterCaps & RC_PALETTE) ? "is" : "is not");
// If we're using truecolor, and the server has more bits than we do
if ( (localBitsPerPixel > m_myFormat.depth) &&
! (localRasterCaps & RC_PALETTE)) {
m_myFormat.depth = localBitsPerPixel;
// create a bitmap compatible with the current display
// call GetDIBits twice to get the colour info.
// set colour masks and shifts
}
}
}
// The endian will be set before sending
}
void ClientConnection::SetFormatAndEncodings()
{
// Set pixel format to myFormat
rfbSetPixelFormatMsg spf;
spf.type = rfbSetPixelFormat;
spf.format = m_myFormat;
spf.format.redMax = Swap16IfLE(spf.format.redMax);
spf.format.greenMax = Swap16IfLE(spf.format.greenMax);
spf.format.blueMax = Swap16IfLE(spf.format.blueMax);
spf.format.bigEndian = 0;
WriteExact((char *)&spf, sz_rfbSetPixelFormatMsg);
// The number of bytes required to hold at least one pixel.
m_minPixelBytes = (m_myFormat.bitsPerPixel + 7) >> 3;
// Set encodings
char buf[sz_rfbSetEncodingsMsg + MAX_ENCODINGS * 4];
rfbSetEncodingsMsg *se = (rfbSetEncodingsMsg *)buf;
CARD32 *encs = (CARD32 *)(&buf[sz_rfbSetEncodingsMsg]);
int len = 0;
se->type = rfbSetEncodings;
se->nEncodings = 0;
int i;
// Put the preferred encoding first, and change it if the
// preferred encoding is not actually usable.
for (i = LASTENCODING; i >= rfbEncodingRaw; i--)
{
if (m_opts.m_PreferredEncoding == i) {
if (m_opts.m_UseEnc[i]) {
encs[se->nEncodings++] = Swap32IfLE(i);
} else {
m_opts.m_PreferredEncoding--;
}
}
}
// Now we go through and put in all the other encodings in order.
// We do rather assume that the most recent encoding is the most
// desirable!
for (i = LASTENCODING; i >= rfbEncodingRaw; i--)
{
if ( (m_opts.m_PreferredEncoding != i) &&
(m_opts.m_UseEnc[i]))
{
encs[se->nEncodings++] = Swap32IfLE(i);
}
}
len = sz_rfbSetEncodingsMsg + se->nEncodings * 4;
se->nEncodings = Swap16IfLE(se->nEncodings);
WriteExact((char *) buf, len);
}
// Closing down the connection.
// Close the socket, kill the thread.
void ClientConnection::KillThread()
{
m_bKillThread = true;
m_running = false;
if (m_sock != INVALID_SOCKET) {
shutdown(m_sock, SD_BOTH);
closesocket(m_sock);
m_sock = INVALID_SOCKET;
}
}
ClientConnection::~ClientConnection()
{
if (m_hwnd != 0)
DestroyWindow(m_hwnd);
if (m_sock != INVALID_SOCKET) {
shutdown(m_sock, SD_BOTH);
closesocket(m_sock);
m_sock = INVALID_SOCKET;
}
if (m_desktopName != NULL) delete [] m_desktopName;
delete [] m_netbuf;
DeleteDC(m_hBitmapDC);
if (m_hBitmap != NULL)
DeleteObject(m_hBitmap);
if (m_hBitmapDC != NULL)
DeleteObject(m_hBitmapDC);
if (m_hPalette != NULL)
DeleteObject(m_hPalette);
m_pApp->DeregisterConnection(this);
}
// You can specify a dx & dy outside the limits; the return value will
// tell you whether it actually scrolled.
bool ClientConnection::ScrollScreen(int dx, int dy)
{
dx = max(dx, -m_hScrollPos);
//dx = min(dx, m_hScrollMax-(m_cliwidth-1)-m_hScrollPos);
dx = min(dx, m_hScrollMax-(m_cliwidth)-m_hScrollPos);
dy = max(dy, -m_vScrollPos);
//dy = min(dy, m_vScrollMax-(m_cliheight-1)-m_vScrollPos);
dy = min(dy, m_vScrollMax-(m_cliheight)-m_vScrollPos);
if (dx || dy) {
m_hScrollPos += dx;
m_vScrollPos += dy;
RECT clirect;
GetClientRect(m_hwnd, &clirect);
ScrollWindowEx(m_hwnd, -dx, -dy, NULL, &clirect, NULL, NULL, SW_INVALIDATE);
UpdateScrollbars();
UpdateWindow(m_hwnd);
return true;
}
return false;
}
// Process windows messages
LRESULT CALLBACK ClientConnection::WndProc(HWND hwnd, UINT iMsg,
WPARAM wParam, LPARAM lParam) {
// This is a static method, so we don't know which instantiation we're
// dealing with. But we've stored a 'pseudo-this' in the window data.
ClientConnection *_this = (ClientConnection *) GetWindowLong(hwnd, GWL_USERDATA);
switch (iMsg) {
case WM_CREATE:
return 0;
case WM_PAINT:
_this->DoBlit();
return 0;
case WM_LBUTTONDOWN:
case WM_LBUTTONUP:
// Alt-click = right click
if (GetKeyState(VK_MENU) < 0) {
wParam = (wParam & ~MK_LBUTTON) | MK_RBUTTON;
}
case WM_MBUTTONDOWN:
case WM_MBUTTONUP:
case WM_RBUTTONDOWN:
case WM_RBUTTONUP:
case WM_MOUSEMOVE:
{
if (!_this->m_running) return 0;
if (GetFocus() != hwnd) return 0;
int x = LOWORD(lParam);
int y = HIWORD(lParam)-_this->m_barheight;
#ifndef UNDER_CE
if (_this->InFullScreenMode()) {
if (_this->BumpScroll(x,y))
return 0;
}
#endif
if ( _this->m_opts.m_ViewOnly) return 0;
_this->ProcessPointerEvent(x,y,wParam);
return 0;
}
case WM_KEYDOWN:
case WM_KEYUP:
case WM_SYSKEYDOWN:
case WM_SYSKEYUP:
{
if (!_this->m_running) return 0;
if ( _this->m_opts.m_ViewOnly) return 0;
_this->ProcessKeyEvent((int) wParam, (DWORD) lParam);
return 0;
}
case WM_CHAR:
case WM_SYSCHAR:
#ifdef UNDER_CE
{
int key = wParam;
log.Print(4,_T("CHAR msg : %02x\n"), key);
// Control keys which are in the Keymap table will already
// have been handled.
if (key == 0x0D || // return
key == 0x20 || // space
key == 0x08) // backspace
return 0;
if (key < 32) key += 64; // map ctrl-keys onto alphabet
if (key > 32 && key < 127) {
_this->SendKeyEvent(wParam & 0xff, true);
_this->SendKeyEvent(wParam & 0xff, false);
}
return 0;
}
#endif