forked from jlopez/win2vnc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ClientConnection.cpp
executable file
·1768 lines (1481 loc) · 48.4 KB
/
ClientConnection.cpp
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
// win2vnc, adapted from vncviewer by Fredrik Hubinette 2001
//
// Original copyright follows:
//
// 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.
// Many thanks to Randy Brown <[email protected]> for providing the 3-button
// emulation code.
// 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.
// #define USE_SNOOPDLL
#include "stdhdrs.h"
#include "vncviewer.h"
#include "omnithread.h"
#include "ClientConnection.h"
#include "SessionDialog.h"
#include "AuthDialog.h"
#include "Menu.h"
#include "Exception.h"
extern "C" {
#include "vncauth.h"
}
#define INITIALNETBUFSIZE 4096
#define MAX_ENCODINGS 10
#define VWR_WND_CLASS_NAME _T("win2vnc")
// static LRESULT CALLBACK ClientConnection::WndProc(HWND hwnd, UINT iMsg, WPARAM wParam, LPARAM lParam);
#ifdef USE_SNOOPDLL
#include "snoopdll.h"
static SnoopDLL *snoopdll;
#endif
// *************************************************************************
// 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;
m_serverInitiated = true;
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, MAX_HOST_NAME_LEN);
m_port = port;
}
void ClientConnection::Init(VNCviewerApp *pApp)
{
m_hKbdHook = 0;
m_onedge = 1;
m_hwnd = 0;
m_edgewindow =0;
m_menu = 0;
m_desktopName = NULL;
m_port = -1;
m_serverInitiated = false;
m_netbuf = NULL;
m_netbufsize = 0;
m_hwndNextViewer = NULL;
m_pApp = pApp;
m_dormant = false;
m_encPasswd[0] = '\0';
// 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_waitingOnEmulateTimer = false;
m_emulatingMiddleButton = false;
// Create a buffer for various network operations
CheckBufferSize(INITIALNETBUFSIZE);
m_pApp->RegisterConnection(this);
}
//
// 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()
{
// 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 windows etc
CreateDisplay();
SendClientInit();
ReadServerInit();
SetupPixelFormat();
SetFormatAndEncodings();
// This starts the worker thread.
// The rest of the processing continues in run_undetached.
start_undetached();
}
ClientConnection *g_clientConnectionInstance = 0;
void ClientConnection::CreateDisplay()
{
m_screenwidth=GetSystemMetrics(SM_CXVIRTUALSCREEN);
m_screenheight=GetSystemMetrics(SM_CYVIRTUALSCREEN);
// 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_NOCURSOR));
wndclass.hbrBackground = (HBRUSH) GetStockObject(BLACK_BRUSH);
wndclass.lpszMenuName = (const TCHAR *) NULL;
wndclass.lpszClassName = VWR_WND_CLASS_NAME;
RegisterClass(&wndclass);
const DWORD winstyle = 0;
m_edgewindow = CreateWindowEx(
WS_EX_TRANSPARENT | WS_EX_TOPMOST | WS_EX_TOOLWINDOW,
VWR_WND_CLASS_NAME,
_T("win2vnc"),
winstyle,
(m_opts.m_edge == M_EDGE_EAST) ? m_screenwidth -1: 0,
(m_opts.m_edge == M_EDGE_SOUTH) ? m_screenheight -1: 0,
!(m_opts.m_edge & M_EDGE_EW) ? m_screenwidth : 1, // x-size
(m_opts.m_edge & M_EDGE_EW) ? m_screenheight: 1, // y-size
NULL, // Parent handle
NULL, // Menu handle
m_pApp->m_instance,
NULL);
m_hwnd = CreateWindowEx(
WS_EX_TRANSPARENT | WS_EX_TOPMOST,
VWR_WND_CLASS_NAME,
_T("win2vnc"),
winstyle,
0,
0,
m_screenwidth, // x-size
m_screenheight, // y-size
m_edgewindow, // Parent handle
NULL, // Menu handle
m_pApp->m_instance,
NULL);
ShowWindow(m_hwnd, SW_HIDE);
ShowWindow(m_edgewindow, SW_HIDE);
// record which client created this window
SetWindowLong(m_hwnd, GWL_USERDATA, (LONG) this);
SetWindowLong(m_edgewindow, GWL_USERDATA, (LONG) this);
// Create a memory DC which we'll use for drawing to
// the local framebuffer
// Set up clipboard watching
#ifndef _WIN32_WCE
// 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
#ifdef USE_SNOOPDLL
snoopdll=new SnoopDLL();
log.Print(1, _T("Starting snoop (%d,%d, %d,%d)\n"),
m_screenwidth,
m_screenheight,
(m_opts.m_edge == M_EDGE_WEST) ? 0 :
(m_opts.m_edge == M_EDGE_EAST) ? m_screenwidth -1 :
-1,
(m_opts.m_edge == M_EDGE_NORTH) ? 0 :
(m_opts.m_edge == M_EDGE_SOUTH) ? m_screenheight -1 :
-1);
snoopdll->start(m_hwnd,
m_screenwidth,
m_screenheight,
(m_opts.m_edge == M_EDGE_WEST) ? 0 :
(m_opts.m_edge == M_EDGE_EAST) ? m_screenwidth -1 :
-1,
(m_opts.m_edge == M_EDGE_NORTH) ? 0 :
(m_opts.m_edge == M_EDGE_SOUTH) ? m_screenheight -1 :
-1);
#endif
m_onedge=0;
MoveWindowToEdge();
m_menu = new vncMenu(m_pApp, this);
// Setup low level keyboard hook to capture alt-tab, alt-esc, ctrl-esc, win & menu keys
RemoveKbdHook();
m_hKbdHook = SetWindowsHookEx(13, ClientConnection::KbdHook, m_pApp->m_instance, 0);
g_clientConnectionInstance = this; // Nasty... :(
}
typedef struct tagKBDLLHOOKSTRUCT {
DWORD vkCode;
DWORD scanCode;
DWORD flags;
DWORD time;
ULONG_PTR dwExtraInfo;
} KBDLLHOOKSTRUCT, *PKBDLLHOOKSTRUCT, *LPKBDLLHOOKSTRUCT;
LRESULT CALLBACK ClientConnection::KbdHook(int nCode, WPARAM wParam, LPARAM lParam) {
if (g_clientConnectionInstance)
return g_clientConnectionInstance->RealKbdHook(nCode, wParam, lParam);
return 0;
}
LRESULT ClientConnection::RealKbdHook(int nCode, WPARAM wParam, LPARAM lParam) {
if (!m_onedge && nCode == HC_ACTION) {
KBDLLHOOKSTRUCT *pkbhs = (KBDLLHOOKSTRUCT *)lParam;
BOOL bControlKeyDown = GetAsyncKeyState(VK_CONTROL) >> 15;
BOOL bAltKeyDown = pkbhs->flags && (KF_ALTDOWN >> 8);
log.Print(3, _T("LLKBD: %08X %08X %08X %08X %p\n"), pkbhs->vkCode,
pkbhs->scanCode, pkbhs->flags, pkbhs->time, pkbhs->dwExtraInfo);
DWORD vkCode = pkbhs->vkCode;
if (vkCode == VK_TAB && bAltKeyDown ||
vkCode == VK_ESCAPE && bAltKeyDown ||
vkCode == VK_ESCAPE && bControlKeyDown ||
vkCode == VK_LWIN || vkCode == VK_RWIN || vkCode == VK_MENU) {
ProcessKeyEvent(vkCode, ((pkbhs->scanCode & 0xFF) << 16) | ((pkbhs->flags & 0xFF) << 24));
return 1;
}
}
return CallNextHookEx(m_hKbdHook, nCode, wParam, lParam);
}
void ClientConnection::RemoveKbdHook() {
if (m_hKbdHook)
UnhookWindowsHookEx(m_hKbdHook);
m_hKbdHook = 0;
}
void ClientConnection::GetConnectDetails()
{
if (m_opts.m_configSpecified) {
LoadConnection(m_opts.m_configFilename);
} else {
SessionDialog sessdlg(&m_opts);
if (!sessdlg.DoDialog()) {
throw QuietException("User Cancelled");
}
_tcsncpy(m_host, sessdlg.m_host, MAX_HOST_NAME_LEN);
m_port = sessdlg.m_port;
}
// This is a bit of a hack:
// The config file may set various things in the app-level defaults which
// we don't want to be used except for the first connection. So we clear them
// in the app defaults here.
m_pApp->m_options.m_host[0] = '\0';
m_pApp->m_options.m_port = -1;
m_pApp->m_options.m_connectionSpecified = false;
m_pApp->m_options.m_configSpecified = false;
}
void ClientConnection::Connect()
{
struct sockaddr_in thataddr;
int res;
m_sock = socket(PF_INET, SOCK_STREAM, 0);
if (m_sock == INVALID_SOCKET)
throw WarningException(_T("Error creating socket"));
int one = 1;
// The host may be specified as a dotted address "a.b.c.d"
// Try that first
thataddr.sin_addr.s_addr = inet_addr(m_host);
// If it wasn't one of those, do gethostbyname
if (thataddr.sin_addr.s_addr == INADDR_NONE) {
LPHOSTENT lphost;
lphost = gethostbyname(m_host);
if (lphost == NULL) {
throw WarningException("Failed to get server address.\n\r"
"Did you type the host name correctly?");
};
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)
throw WarningException("Failed to connect to server");
log.Print(0, _T("Connected to %s port %d\n"), m_host, m_port);
}
void ClientConnection::SetSocketOptions() {
// Disable Nagle's algorithm
BOOL nodelayval = TRUE;
if (setsockopt(m_sock, IPPROTO_TCP, TCP_NODELAY, (const char *) &nodelayval, sizeof(BOOL)))
throw WarningException("Error disabling Nagle's algorithm");
}
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);
} catch (Exception &c) {
log.Print(0, _T("Error reading protocol version: %s\n"), c);
throw QuietException(c.m_info);
}
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!
#ifdef UNDER_CE
m_majorVersion = rfbProtocolMajorVersion;
m_minorVersion = rfbProtocolMinorVersion;
#else
if (sscanf(pv,rfbProtocolVersionFormat,&m_majorVersion,&m_minorVersion) != 2) {
throw WarningException(_T("Invalid protocol"));
}
log.Print(0, _T("RFB server supports protocol version %d.%d\n"),
m_majorVersion,m_minorVersion);
if (m_majorVersion == 3 && m_minorVersion == 889)
m_opts.m_DisableClipboard = true;
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);
throw WarningException(m_netbuf);
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);
throw WarningException("Can't use IDEA authentication any more!");
}
ReadExact((char *)challenge, CHALLENGESIZE);
char passwd[256];
// Was the password already specified in a config file?
if (strlen((const char *) m_encPasswd)>0) {
char *pw = vncDecryptPasswd(m_encPasswd);
strcpy(passwd, pw);
free(pw);
} else {
AuthDialog ad;
ad.DoDialog();
#ifndef UNDER_CE
strcpy(passwd, ad.m_passwd);
#else
int origlen = _tcslen(ad.m_passwd);
int newlen = WideCharToMultiByte(
CP_ACP, // code page
0, // performance and mapping flags
ad.m_passwd, // address of wide-character string
origlen, // number of characters in string
passwd, // address of buffer for new string
255, // size of buffer
NULL, NULL );
passwd[newlen]= '\0';
#endif
if (strlen(passwd) == 0) {
log.Print(0, _T("Password had zero length\n"));
throw WarningException("Empty password");
}
if (strlen(passwd) > 8) {
passwd[8] = '\0';
}
vncEncryptPasswd(m_encPasswd, passwd);
}
vncEncryptBytes(challenge, passwd);
/* Lose the plain-text 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!"));
throw WarningException("VNC authentication failed!");
case rfbVncAuthTooMany:
throw WarningException(
"VNC authentication failed - too many tries!");
default:
log.Print(0, _T("Unknown VNC authentication result: %d\n"),
(int)authResult);
throw ErrorException("Unknown VNC authentication result!");
}
break;
}
default:
log.Print(0, _T("Unknown authentication scheme from RFB server: %d\n"),
(int)authScheme);
throw ErrorException("Unknown authentication scheme!");
}
}
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];
ReadString(m_desktopName, m_si.nameLength);
// SetWindowText(m_edgewindow, m_desktopName);
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_edgewindow, m_desktopName);
}
void ClientConnection::SetupPixelFormat() {
// Normally we just use the sever's format suggestion
m_myFormat = m_si.format;
}
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;
// Put the preferred encoding first, and change it if the
// preferred encoding is not actually usable.
for (int 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 (int 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;
}
}
void ClientConnection::Exit()
{
if (m_hwnd != 0)
{
DestroyWindow(m_hwnd);
m_hwnd=0;
}
if (m_edgewindow != 0)
{
DestroyWindow(m_edgewindow);
m_edgewindow=0;
}
RemoveKbdHook();
if (m_sock != INVALID_SOCKET) {
shutdown(m_sock, SD_BOTH);
closesocket(m_sock);
m_sock = INVALID_SOCKET;
}
if (m_desktopName != NULL)
{
delete [] m_desktopName;
m_desktopName=NULL;
}
if(m_netbuf)
{
delete [] m_netbuf;
m_netbuf=0;
}
if(m_menu)
{
delete m_menu;
m_menu=0;
}
}
ClientConnection::~ClientConnection()
{
Exit();
m_pApp->DeregisterConnection(this);
}
void ClientConnection::MoveWindowToEdge(void)
{
if(m_onedge) return;
log.Print(1,_T("Moving Window to EDGE (%d,%d,%d,%d)\n"),
(m_opts.m_edge == M_EDGE_EAST) ? m_screenwidth -1: 0,
(m_opts.m_edge == M_EDGE_SOUTH) ? m_screenheight -1: 0,
!(m_opts.m_edge & M_EDGE_EW) ? m_screenwidth : 1, // x-size
(m_opts.m_edge & M_EDGE_EW) ? m_screenheight: 1 // y-size
);
SetWindowPos(m_hwnd, HWND_BOTTOM,
0, 0,
m_screenwidth, m_screenheight,
SWP_HIDEWINDOW | SWP_NOREDRAW);
SetWindowPos(m_edgewindow, HWND_TOPMOST,
(m_opts.m_edge == M_EDGE_EAST) ? m_screenwidth -1: 0,
(m_opts.m_edge == M_EDGE_SOUTH) ? m_screenheight -1: 0,
!(m_opts.m_edge & M_EDGE_EW) ? m_screenwidth : 1, // x-size
(m_opts.m_edge & M_EDGE_EW) ? m_screenheight: 1, // y-size
SWP_SHOWWINDOW | SWP_NOREDRAW);
m_onedge=1;
}
void ClientConnection::Deactivate(int x, int y)
{
if(m_onedge) return;
// ShowCursor(1);
log.Print(2,_T("Warp Cursor: %d,%d -> %d, %d\n"),
x,y,
!(m_opts.m_edge & M_EDGE_EW) ? x : x ? 1 : m_screenwidth -2,
(m_opts.m_edge & M_EDGE_EW) ? y : y ? 1 : m_screenheight -2 );
SetCursorPos(
!(m_opts.m_edge & M_EDGE_EW) ? x : x ? 1 : m_screenwidth -2,
(m_opts.m_edge & M_EDGE_EW) ? y : y ? 1 : m_screenheight -2 );
MoveWindowToEdge();
// try to hide slave mouse pointer
if (m_running)
SubProcessPointerEvent(m_si.framebufferWidth-2,
m_si.framebufferHeight-2,
0);
}
void ClientConnection::MoveWindowToScreen(void)
{
if(!m_onedge) return;
log.Print(1,_T("Moving Window to SCREEN (%d,%d)\n"),
m_screenwidth,
m_screenheight);
SetWindowPos(m_hwnd, HWND_TOPMOST,
0, 0,
m_screenwidth, m_screenheight,
SWP_SHOWWINDOW | SWP_NOREDRAW);
/* Really needed ? */
SetForegroundWindow(m_hwnd);
m_onedge=0;
}
void ClientConnection::Activate(int x, int y)
{
if(!m_onedge) return;
// ShowCursor(0);
MoveWindowToScreen();
log.Print(5,_T("Warp Cursor: %d,%d -> %d, %d\n"),
x,y,
!(m_opts.m_edge & M_EDGE_EW) ? x : x ? 1 : m_screenwidth -2,
(m_opts.m_edge & M_EDGE_EW) ? y : y ? 1 : m_screenheight -2 );
SetCursorPos(
!(m_opts.m_edge & M_EDGE_EW) ? x : x ? 1 : m_screenwidth -2,
(m_opts.m_edge & M_EDGE_EW) ? y : y ? 1 : m_screenheight -2 );
}
// Process windows messages
class got_wm_destroy {};
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);
#if 1
switch(iMsg)
{
case WM_PAINT: break;
default:
log.Print(10, _T("MESSAGE: 0x%04x\n"), iMsg);
}
#endif
if(_this)
{
try {
return _this->RealWndProc(hwnd, iMsg, wParam, lParam);
} catch (got_wm_destroy &e) {
// We are currently in the main thread.
// The worker thread should be about to finish if
// it hasn't already. Wait for it.
try {
void *p;
_this->join(&p); // After joining, this is no longer valid
} catch (omni_thread_invalid& e) {
// The thread probably hasn't been started yet,
}
return 0;
}
}else{
return DefWindowProc(hwnd, iMsg, wParam, lParam);
}
}
int ClientConnection::OnMouseEvent(HWND hwnd, UINT iMsg, WPARAM wParam, LPARAM lParam) {
#ifndef USE_SNOOPDLL
POINT pt;
if (GetFocus() != hwnd) return 0;
if (!m_running) return 0;
pt.x = GET_X_LPARAM(lParam);
pt.y = GET_Y_LPARAM(lParam);
ClientToScreen(hwnd, &pt);
int x=pt.x;
int y=pt.y;
if(x<0 || x>32768) x=0;
if(y<0 || y>32768) y=0;
if(x>=m_screenwidth) x=m_screenwidth-1;
if(y>=m_screenheight) y=m_screenheight-1;
if(m_onedge)
{
if(hwnd == m_edgewindow)
{
log.Print(4,"Activated by action: %d\n",iMsg);
Activate(x,y);
}
return 0;
}
if(hwnd == m_hwnd)
{
int back=0;
switch(m_opts.m_edge)
{
case M_EDGE_WEST: back=x==m_screenwidth-1; break;
case M_EDGE_EAST: back=x==0; break;
case M_EDGE_NORTH: back=y==m_screenheight-1; break;
case M_EDGE_SOUTH: back=y==0; break;
}
if(back)
{
Deactivate(x,y);
return 0;
}
}
ProcessPointerEvent(x,y, wParam, iMsg);
#endif
return 0;
}
#define MK_WHEELUP 0x4000
#define MK_WHEELDOWN 0x8000
int ClientConnection::RealWndProc(HWND hwnd, UINT iMsg,
WPARAM wParam, LPARAM lParam)
{
switch (iMsg)
{
case WM_CREATE:
return 0;
case WM_TIMER:
if (wParam == m_emulate3ButtonsTimer)
{
SubProcessPointerEvent(m_emulateButtonPressedX,
m_emulateButtonPressedY,
m_emulateKeyFlags);
KillTimer(m_hwnd, m_emulate3ButtonsTimer);
m_waitingOnEmulateTimer = false;
}
return 0;
case 0x20A:
{
log.Print(0, "Wheel: %08X %08X\n", wParam, lParam);
int delta = ((short)HIWORD(wParam));
wParam |= delta < 0 ? MK_WHEELDOWN : MK_WHEELUP;
return OnMouseEvent(hwnd, iMsg, wParam, lParam);
}
case WM_LBUTTONDOWN:
case WM_LBUTTONUP:
case WM_MBUTTONDOWN:
case WM_MBUTTONUP:
case WM_RBUTTONDOWN:
case WM_RBUTTONUP:
case WM_MOUSEMOVE:
return OnMouseEvent(hwnd, iMsg, wParam, lParam);
#ifdef USE_SNOOPDLL
case SNOOPDLL_MOUSE_UPDATE:
{
if (!m_running) return 0;
int x = LOWORD(lParam);
int y = HIWORD(lParam);
ProcessPointerEvent(x,y, wParam, iMsg);
return 0;
}
case SNOOPDLL_ACTIVE_UPDATE:
{
log.Print(5,_T("ACTIVE=%d , %d\n"), wParam, lParam);
if(!wParam)
{
MoveWindowToEdge();
SubProcessPointerEvent(m_si.framebufferWidth - 2,
m_si.framebufferHeight - 2,
0);
}else{
MoveWindowToScreen();
}
return 0;
}
case SNOOPDLL_KB_UPDATE:
#endif
case WM_KEYDOWN:
case WM_KEYUP:
case WM_SYSKEYDOWN:
case WM_SYSKEYUP:
{
if (!m_running) return 0;
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) {
SendKeyEvent(wParam & 0xff, true);
SendKeyEvent(wParam & 0xff, false);
}
return 0;
}
#endif
case WM_DEADCHAR:
case WM_SYSDEADCHAR:
return 0;