-
-
Notifications
You must be signed in to change notification settings - Fork 67
/
VNCConn.cpp
1864 lines (1492 loc) · 49.1 KB
/
VNCConn.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
/*
VNCConn.cpp: VNC connection class implementation.
This file is part of MultiVNC, a multicast-enabled crossplatform
VNC viewer.
Copyright (C) 2009, 2010 Christian Beier <dontmind@freeshell.org>
MultiVNC 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.
MultiVNC 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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <cstdarg>
#include <cerrno>
#include <wx/intl.h>
#include <wx/log.h>
#include <wx/socket.h>
#ifdef __WIN32__
#include <winsock2.h>
#else
#include <arpa/inet.h>
#endif
#include "VNCConn.h"
// use some global address
#define VNCCONN_OBJ_ID (void*)VNCConn::thread_got_update
// logfile name
#define LOGFILE _T("MultiVNC.log")
// pixelformat defaults
// seems 8,3,4 and 5,3,2 are possible with rfbGetClient()
#define BITSPERSAMPLE 8
#define SAMPLESPERPIXEL 3
#define BYTESPERPIXEL 4
// define our new notify events!
DEFINE_EVENT_TYPE(VNCConnListenNOTIFY)
DEFINE_EVENT_TYPE(VNCConnInitNOTIFY)
wxDEFINE_EVENT(VNCConnGetPasswordNOTIFY, wxCommandEvent);
wxDEFINE_EVENT(VNCConnGetCredentialsNOTIFY, wxCommandEvent);
DEFINE_EVENT_TYPE(VNCConnIncomingConnectionNOTIFY)
DEFINE_EVENT_TYPE(VNCConnDisconnectNOTIFY)
DEFINE_EVENT_TYPE(VNCConnUpdateNOTIFY)
DEFINE_EVENT_TYPE(VNCConnFBResizeNOTIFY)
DEFINE_EVENT_TYPE(VNCConnCuttextNOTIFY)
DEFINE_EVENT_TYPE(VNCConnBellNOTIFY)
DEFINE_EVENT_TYPE(VNCConnUniMultiChangedNOTIFY);
DEFINE_EVENT_TYPE(VNCConnReplayFinishedNOTIFY);
BEGIN_EVENT_TABLE(VNCConn, wxEvtHandler)
EVT_TIMER (wxID_ANY, VNCConn::on_stats_timer)
END_EVENT_TABLE();
#ifdef LIBVNCSERVER_WITH_CLIENT_TLS
bool VNCConn::TLS_threading_initialized;
extern "C"
{
#include <gcrypt.h>
#include <errno.h>
/*
* gcrypt thread option wx implementation
*/
static int gcry_wx_mutex_init( void **p )
{
*p = new wxMutex();
return 0;
}
static int gcry_wx_mutex_destroy( void **p )
{
delete (wxMutex*)*p;
return 0;
}
static int gcry_wx_mutex_lock( void **p )
{
if(((wxMutex*)(*p))->Lock() == wxMUTEX_NO_ERROR)
return 0;
else
return 1;
}
static int gcry_wx_mutex_unlock( void **p )
{
if(((wxMutex*)(*p))->Unlock() == wxMUTEX_NO_ERROR)
return 0;
else
return 1;
}
static const struct gcry_thread_cbs gcry_threads_wx =
{
GCRY_THREAD_OPTION_USER,
NULL,
gcry_wx_mutex_init,
gcry_wx_mutex_destroy,
gcry_wx_mutex_lock,
gcry_wx_mutex_unlock
};
}
#endif
/*
constructor/destructor
*/
VNCConn::VNCConn(void* p) : condition_auth(mutex_auth)
{
// save our caller
parent = p;
cl = 0;
multicastStatus = 0;
latency = -1;
rfbClientLog = rfbClientErr = thread_logger;
#ifdef LIBVNCSERVER_WITH_CLIENT_TLS
/* we're using threads in here, tell libgcrypt before TLS
gets initialized by libvncclient! */
if(! TLS_threading_initialized)
{
wxLogDebug(wxT("Initialized libgcrypt threading."));
gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_wx);
gcry_check_version (NULL);
gcry_control (GCRYCTL_DISABLE_SECMEM, 0);
gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
TLS_threading_initialized = true;
}
#endif
// statistics stuff
do_stats = false;
upd_bytes = 0;
upd_bytes_inflated = 0;
upd_count = 0;
stats_timer.SetOwner(this);
// fastrequest stuff
fastrequest_interval = 0;
// record/replay stuff
recording = replaying = false;
require_auth = false;
}
VNCConn::~VNCConn()
{
Shutdown();
wxLogDebug(wxT("VNCConn %p: I'm dead!"), this);
}
/*
private members
*/
void VNCConn::on_stats_timer(wxTimerEvent& event)
{
if(do_stats)
{
wxCriticalSectionLocker lock(mutex_stats);
if(statistics.IsEmpty())
statistics.Add(wxString()
+ wxT("UTC time,")
+ wxT("conn time,")
+ wxT("rcvd bytes,")
+ wxT("rcvd bytes inflated,")
+ wxT("upd count,")
+ wxT("latency,")
+ wxT("nack rate,")
+ wxT("loss rate,")
+ wxT("buf size,")
+ wxT("buf fill,"));
wxString sample;
sample += (wxString() << (int)wxGetUTCTime()); // global UTC time
sample += wxT(",");
sample += (wxString() << (int)conn_stopwatch.Time()); // connection time
sample += wxT(",");
sample += (wxString() << upd_bytes); // rcvd bytes sampling
sample += wxT(",");
sample += (wxString() << upd_bytes_inflated); // rcvd bytes inflated sampling
sample += wxT(",");
sample += (wxString() << upd_count); // number of updates sampling
sample += wxT(",");
sample += (wxString() << latency); // latency sampling
sample += wxT(",");
wxString nackrate_str = wxString::Format(wxT("%.4f"), getMCNACKedRatio());
nackrate_str.Replace(wxT(","), wxT("."));
sample += nackrate_str; // nack rate sampling
sample += wxT(",");
wxString lossrate_str = wxString::Format(wxT("%.4f"), getMCLossRatio());
lossrate_str.Replace(wxT(","), wxT("."));
sample += lossrate_str; // loss rate sampling
sample += wxT(",");
sample += (wxString() << getMCBufSize()); // buffer size sampling
sample += wxT(",");
sample += (wxString() << getMCBufFill()); // buffer fill sampling
// add the sample
statistics.Add(sample);
// reset these
upd_bytes = 0;
upd_bytes_inflated = 0;
upd_count = 0;
latency = -1;
latency_test_trigger = true;
}
}
rfbBool VNCConn::thread_alloc_framebuffer(rfbClient* client)
{
// get VNCConn object belonging to this client
VNCConn* conn = (VNCConn*) rfbClientGetClientData(client, VNCCONN_OBJ_ID);
wxLogDebug(wxT("VNCConn %p: alloc'ing framebuffer w:%i, h:%i"), conn, client->width, client->height);
// assert 32bpp, as requested with GetClient() in Init()
if(client->format.bitsPerPixel != 32)
{
conn->err.Printf(_("Failure setting up framebuffer: wrong BPP!"));
return false;
}
// ensure that we get the whole framebuffer in case of a resize!
client->updateRect.x = client->updateRect.y = 0;
client->updateRect.w = client->width; client->updateRect.h = client->height;
// free
if(client->frameBuffer)
free(client->frameBuffer);
// alloc, zeroed
client->frameBuffer = (uint8_t*)calloc(1, client->width*client->height*client->format.bitsPerPixel/8);
// notify our parent
conn->thread_post_fbresize_notify();
return client->frameBuffer ? TRUE : FALSE;
}
wxThread::ExitCode VNCConn::Entry()
{
// init connection before going into main loop if this is not a listening one
if (!thread_listenmode) {
rfbClientLog("About to connect to '%s', port %d\n", cl->serverHost, cl->serverPort);
// save these for the error case
wxString host = wxString(cl->serverHost);
int port = cl->serverPort;
if (!rfbInitClient(cl, 0, NULL)) {
// rfbInitClient() calls rfbClientCleanup() on failure, but
// this does not zero the ptr
cl = 0;
err.Printf(_("Failure connecting to server at %s:%d!"), host, port);
wxLogDebug("VNCConn %p: rfbInitClient() failed. Cleanup by library.", this);
thread_post_init_notify(1); // TODO add more error codes
wxLogDebug("VNCConn %p: vncthread done", this);
return 0;
}
// set the client sock to blocking again until libvncclient is fixed
#ifdef WIN32
unsigned long block = 0;
if (ioctlsocket(cl->sock, FIONBIO, &block) == SOCKET_ERROR) {
errno = WSAGetLastError();
#else
int flags = fcntl(cl->sock, F_GETFL);
if (flags < 0 || fcntl(cl->sock, F_SETFL, flags & ~O_NONBLOCK) < 0) {
#endif
rfbClientErr("Setting socket to blocking failed: %s\n", strerror(errno));
}
// if there was an error in alloc_framebuffer(), catch that here
// err is set by alloc_framebuffer()
if (!cl->frameBuffer) {
thread_post_init_notify(1); // TODO add more error codes
wxLogDebug("VNCConn %p: vncthread done", this);
return 0;
}
// connect succesful
thread_post_init_notify(0);
}
int i=0;
pointerEvent pe;
keyEvent ke = {0, 0};
bool listen_outcome_posted = false;
while(! GetThread()->TestDestroy())
{
if(thread_listenmode)
{
i=listenForIncomingConnectionsNoFork(cl, 100000); // 100 ms
if (i == 0) {
// just notify about success once
if (!listen_outcome_posted) {
thread_post_listen_notify(0);
listen_outcome_posted = true;
}
}
if(i<0)
{
if(errno==EINTR)
continue;
wxLogDebug(wxT("VNCConn %p: vncthread listen() failed"), this);
thread_post_listen_notify(1); //TODO add more error codes
break;
}
if(i)
{
// have this here in case of immediate connection
// but just notify about success once
if (!listen_outcome_posted) {
thread_post_listen_notify(0);
listen_outcome_posted = true;
}
thread_post_incomingconnection_notify();
break;
}
}
else
{
// userinput replay here
{
wxCriticalSectionLocker lock(mutex_recordreplay);
if(replaying)
{
if(userinput_pos < userinput.GetCount()) // still recorded input there
{
wxString ui_now = userinput[userinput_pos];
// get timestamp and strip it from string
long ts = wxAtol(ui_now.BeforeFirst(','));
ui_now = ui_now.AfterFirst(',');
if(ts <= recordreplay_stopwatch.Time()) // past or now, process it
{
// get type
wxString type = ui_now.BeforeFirst(',');
ui_now = ui_now.AfterFirst(',');
if(type == wxT("p"))
{
// get pointer x,y, buttmask
int x = wxAtoi(ui_now.BeforeFirst(','));
ui_now = ui_now.AfterFirst(',');
int y = wxAtoi(ui_now.BeforeFirst(','));
ui_now = ui_now.AfterFirst(',');
int bmask = wxAtoi(ui_now);
// and send
SendPointerEvent(cl, x, y, bmask);
}
if(type == wxT("k"))
{
// get keysym
rfbKeySym keysym = wxAtoi(ui_now.BeforeFirst(','));
ui_now = ui_now.AfterFirst(',');
bool down = wxAtoi(ui_now);
// and send
SendKeyEvent(cl, keysym, down);
}
// advance to next input
++userinput_pos;
}
}
else if (replay_loop)
{
userinput_pos = 0; // rewind
recordreplay_stopwatch.Start(); // restart
}
else
{
replaying = false; // all done
thread_post_replayfinished_notify();
}
}
}
// send everything that's inside the input queues
while(pointer_event_q.ReceiveTimeout(0, pe) != wxMSGQUEUE_TIMEOUT) // timeout == empty
thread_send_pointer_event(pe);
while(key_event_q.ReceiveTimeout(0, ke) != wxMSGQUEUE_TIMEOUT) // timeout == empty
thread_send_key_event(ke);
{
wxCriticalSectionLocker lock(mutex_stats);
if(latency_test_trigger)
{
latency_test_trigger = false;
thread_send_latency_probe();
}
}
if(fastrequest_interval && (size_t)fastrequest_stopwatch.Time() > fastrequest_interval)
{
if(isMulticast())
SendMulticastFramebufferUpdateRequest(cl, TRUE);
else
SendFramebufferUpdateRequest(cl, 0, 0, cl->width, cl->height, TRUE);
fastrequest_stopwatch.Start(); // restart
}
// request update and handle response
if(!rfbProcessServerMessage(cl, 500))
{
if(errno == EINTR)
continue;
wxLogDebug(wxT("VNCConn %p: vncthread rfbProcessServerMessage() failed"), this);
thread_post_disconnect_notify();
break;
}
/*
Compute nacked/loss ratio: We take a ratio sample every second and put it into a sample queue
of size N. Action is taken when the average sample value of the whole buffer exceeds a per-action
limit. This has advantages over taking a sample every N seconds: First, it's able to catch say a 5sec burst
that could be missed by two adjacent 10sec samples (one catches 2sec, the next one 3sec - no action triggered
although condition present). Second, this way we're able to show a value to the user every second independent
of the sample time frame.
*/
if(isMulticast() && multicastratio_stopwatch.Time() >= 1000)
{
// restart
multicastratio_stopwatch.Start();
/*
take sample
*/
{
// the fifos are read by the GUI thread as well!
wxCriticalSectionLocker lock(mutex_multicastratio);
if(multicastNACKedRatios.size() >= MULTICAST_RATIO_SAMPLES) // make room if size exceeded
multicastNACKedRatios.pop_front();
if(cl->multicastPktsRcvd + cl->multicastPktsNACKed > 0)
multicastNACKedRatios.push_back(cl->multicastPktsNACKed/(double)(cl->multicastPktsRcvd + cl->multicastPktsNACKed));
else
multicastNACKedRatios.push_back(-1); // nothing to measure, add invalid marker
if(multicastLossRatios.size() >= MULTICAST_RATIO_SAMPLES) // make room if size exceeded
multicastLossRatios.pop_front();
if(cl->multicastPktsRcvd + cl->multicastPktsLost > 0)
multicastLossRatios.push_back(cl->multicastPktsLost/(double)(cl->multicastPktsRcvd + cl->multicastPktsLost));
else
multicastLossRatios.push_back(-1); // nothing to measure, add invalid marker
// reset the values we sample
cl->multicastPktsRcvd = cl->multicastPktsNACKed = cl->multicastPktsLost = 0;
}
/*
And act accordingly, but only after the ratio deques are at least half full.
When a client joins a multicast group with heavy traffic going on, it will lose
a lot of packets in the very beginning because there is a considerable time
amount between it's multicast socket creation and the first read. Thus, the socket
buffer is likely to overflow in this start situation, resulting in packet loss.
*/
if(multicastLossRatios.size() >= MULTICAST_RATIO_SAMPLES/2)
{
if(getMCLossRatio() > 0.5)
{
rfbClientLog("MultiVNC: loss ratio > 0.5, falling back to unicast\n");
wxLogDebug(wxT("VNCConn %p: multicast loss ratio > 0.5, falling back to unicast"), this);
cl->multicastDisabled = TRUE;
SendFramebufferUpdateRequest(cl, 0, 0, cl->width, cl->height, FALSE);
}
else if(getMCLossRatio() > 0.2)
{
rfbClientLog("MultiVNC: loss ratio > 0.2, requesting a full multicast framebuffer update\n");
SendMulticastFramebufferUpdateRequest(cl, FALSE);
cl->multicastPktsLost /= 2;
}
}
}
int now = isMulticast();
if(now != multicastStatus)
{
multicastStatus = now;
thread_post_unimultichanged_notify();
}
}
}
wxLogDebug("VNCConn %p: vncthread done", this);
return 0;
}
bool VNCConn::thread_send_pointer_event(pointerEvent &event)
{
int buttonmask = 0;
if(event.LeftIsDown())
buttonmask |= rfbButton1Mask;
if(event.MiddleIsDown())
buttonmask |= rfbButton2Mask;
if(event.RightIsDown())
buttonmask |= rfbButton3Mask;
if(event.GetWheelRotation() > 0)
buttonmask |= rfbWheelUpMask;
if(event.GetWheelRotation() < 0)
buttonmask |= rfbWheelDownMask;
if(event.Entering() && ! cuttext.IsEmpty())
{
wxCriticalSectionLocker lock(mutex_cuttext); // since cuttext can be set from the main thread
// if encoding fails, a NULL pointer is returned!
if(cuttext.mb_str(wxCSConv(wxT("iso-8859-1"))))
{
wxLogDebug(wxT("VNCConn %p: sending cuttext: '%s'"), this, cuttext.c_str());
char* encoded_text = strdup(cuttext.mb_str(wxCSConv(wxT("iso-8859-1"))));
SendClientCutText(cl, encoded_text, strlen(encoded_text));
free(encoded_text);
}
else
wxLogDebug(wxT("VNCConn %p: sending cuttext FAILED, could not convert '%s' to ISO-8859-1"), this, cuttext.c_str());
}
// record here
{
wxCriticalSectionLocker lock(mutex_recordreplay);
if(recording)
{
wxString ui_now;
ui_now += (wxString() << (int)recordreplay_stopwatch.Time());
ui_now += wxT(",");
ui_now += wxT("p"); // is pointer event
ui_now += wxT(",");
ui_now += (wxString() << event.m_x);
ui_now += wxT(",");
ui_now += (wxString() << event.m_y);
ui_now += wxT(",");
ui_now += (wxString() << buttonmask);
userinput.Add(ui_now);
}
}
wxLogDebug(wxT("VNCConn %p: sending pointer event at (%d,%d), buttonmask %d"), this, event.m_x, event.m_y, buttonmask);
return SendPointerEvent(cl, event.m_x, event.m_y, buttonmask);
}
bool VNCConn::thread_send_key_event(keyEvent &event)
{
// record here
{
wxCriticalSectionLocker lock(mutex_recordreplay);
if(recording)
{
wxString ui_now;
ui_now += (wxString() << (int)recordreplay_stopwatch.Time());
ui_now += wxT(",");
ui_now += wxT("k"); // is key event
ui_now += wxT(",");
ui_now += (wxString() << event.keysym);
ui_now += wxT(",");
ui_now += (wxString() << event.down);
userinput.Add(ui_now);
}
}
return SendKeyEvent(cl, event.keysym, event.down);
}
bool VNCConn::thread_send_latency_probe()
{
bool result = TRUE;
// latency check start
if(SupportsClient2Server(cl, rfbXvp)) // favor xvp over the rect check
{
if(!latency_test_xvpmsg_sent)
{
result = SendXvpMsg(cl, LATENCY_TEST_XVP_VER, 2);
latency_test_xvpmsg_sent = true;
latency_stopwatch.Start();
wxLogDebug(wxT("VNCConn %p: xvp message sent to test latency"), this);
}
}
else // check using special rect
{
if(!latency_test_rect_sent)
{
result = SendFramebufferUpdateRequest(cl, LATENCY_TEST_RECT, FALSE);
latency_test_rect_sent = true;
latency_stopwatch.Start();
wxLogDebug(wxT("VNCConn %p: fb update request sent to test latency"), this);
}
}
return result;
}
void VNCConn::thread_post_listen_notify(int error) {
wxLogDebug(wxT("VNCConn %p: post_listen_notify(%d)"), this, error);
wxCommandEvent event(VNCConnListenNOTIFY, wxID_ANY);
event.SetEventObject(this); // set sender
event.SetInt(error);
wxPostEvent((wxEvtHandler*)parent, event);
}
void VNCConn::thread_post_init_notify(int error) {
wxLogDebug(wxT("VNCConn %p: post_init_notify(%d)"), this, error);
wxCommandEvent event(VNCConnInitNOTIFY, wxID_ANY);
event.SetEventObject(this); // set sender
event.SetInt(error);
wxPostEvent((wxEvtHandler*)parent, event);
}
void VNCConn::thread_post_getpasswd_notify() {
wxLogDebug(wxT("VNCConn %p: post_getpasswd_notify()"), this);
wxCommandEvent event(VNCConnGetPasswordNOTIFY, wxID_ANY);
event.SetEventObject(this); // set sender
wxPostEvent((wxEvtHandler*)parent, event);
}
void VNCConn::thread_post_getcreds_notify(bool withUserPrompt) {
wxLogDebug(wxT("VNCConn %p: post_getcreds_notify()"), this);
wxCommandEvent event(VNCConnGetCredentialsNOTIFY, wxID_ANY);
event.SetEventObject(this); // set sender
event.SetInt(withUserPrompt);
wxPostEvent((wxEvtHandler*)parent, event);
}
void VNCConn::thread_post_incomingconnection_notify()
{
wxLogDebug(wxT("VNCConn %p: post_incomingconnection_notify()"), this);
// new NOTIFY event, we got no window id
wxCommandEvent event(VNCConnIncomingConnectionNOTIFY, wxID_ANY);
event.SetEventObject(this); // set sender
// Send it
wxPostEvent((wxEvtHandler*)parent, event);
}
void VNCConn::thread_post_disconnect_notify()
{
wxLogDebug(wxT("VNCConn %p: post_disconnect_notify()"), this);
// new NOTIFY event, we got no window id
wxCommandEvent event(VNCConnDisconnectNOTIFY, wxID_ANY);
event.SetEventObject(this); // set sender
// Send it
wxPostEvent((wxEvtHandler*)parent, event);
}
void VNCConn::thread_post_update_notify(int x, int y, int w, int h)
{
VNCConnUpdateNotifyEvent event(VNCConnUpdateNOTIFY, wxID_ANY);
event.SetEventObject(this); // set sender
// set info about what was updated
event.rect = wxRect(x, y, w, h);
wxLogDebug(wxT("VNCConn %p: post_update_notify(%i,%i,%i,%i)"), this,
event.rect.x,
event.rect.y,
event.rect.width,
event.rect.height);
// Send it
wxPostEvent((wxEvtHandler*)parent, event);
}
void VNCConn::thread_post_fbresize_notify()
{
wxLogDebug(wxT("VNCConn %p: post_fbresize_notify() (%i, %i)"),
this,
getFrameBufferWidth(),
getFrameBufferHeight());
// new NOTIFY event, we got no window id
wxCommandEvent event(VNCConnFBResizeNOTIFY, wxID_ANY);
event.SetEventObject(this); // set sender
// Send it
wxPostEvent((wxEvtHandler*)parent, event);
}
void VNCConn::thread_post_cuttext_notify()
{
// new NOTIFY event, we got no window id
wxCommandEvent event(VNCConnCuttextNOTIFY, wxID_ANY);
event.SetEventObject(this); // set sender
// Send it
wxPostEvent((wxEvtHandler*)parent, event);
}
void VNCConn::thread_post_bell_notify()
{
// new NOTIFY event, we got no window id
wxCommandEvent event(VNCConnBellNOTIFY, wxID_ANY);
event.SetEventObject(this); // set sender
// Send it
wxPostEvent((wxEvtHandler*)parent, event);
}
void VNCConn::thread_post_unimultichanged_notify()
{
wxCommandEvent event(VNCConnUniMultiChangedNOTIFY, wxID_ANY);
event.SetEventObject(this); // set sender
// Send it
wxPostEvent((wxEvtHandler*)parent, event);
}
void VNCConn::thread_post_replayfinished_notify()
{
wxCommandEvent event(VNCConnReplayFinishedNOTIFY, wxID_ANY);
event.SetEventObject(this); // set sender
// Send it
wxPostEvent((wxEvtHandler*)parent, event);
}
char* VNCConn::thread_getpasswd(rfbClient *client) {
VNCConn* conn = (VNCConn*) rfbClientGetClientData(client, VNCCONN_OBJ_ID);
conn->require_auth = true;
#if wxUSE_SECRETSTORE
if (!conn->getPassword().IsOk()) {
#else
if (conn->getPassword().IsEmpty()) {
#endif
// get password from user
conn->thread_post_getpasswd_notify();
// wxMutexes are not recursive under Unix, so test first
if (conn->mutex_auth.TryLock() == wxMUTEX_NO_ERROR) {
conn->mutex_auth.Lock();
}
wxLogDebug("VNCConn %p: vncthread waiting for password", conn);
conn->condition_auth.Wait();
wxLogDebug("VNCConn %p: vncthread done waiting for password", conn);
// we get here once setPassword() was called
}
#if wxUSE_SECRETSTORE
return strdup(conn->getPassword().GetAsString().char_str());
#else
return strdup(conn->getPassword().char_str());
#endif
};
rfbCredential* VNCConn::thread_getcreds(rfbClient *client, int type) {
VNCConn *conn = VNCConn::getVNCConnFromRfbClient(client);
conn->require_auth = true;
if(type == rfbCredentialTypeUser) {
if(conn->getUserName().IsEmpty()
#if wxUSE_SECRETSTORE
|| !conn->getPassword().IsOk()) {
#else
|| conn->getPassword().IsEmpty()) {
#endif
// username and/or password needed
conn->thread_post_getcreds_notify(conn->getUserName().IsEmpty());
// wxMutexes are not recursive under Unix, so test first
if (conn->mutex_auth.TryLock() == wxMUTEX_NO_ERROR) {
conn->mutex_auth.Lock();
}
wxLogDebug("VNCConn %p: vncthread waiting for credentials", conn);
conn->condition_auth.Wait();
wxLogDebug("VNCConn %p: vncthread done waiting for credentials",
conn);
// we get here once setPassword() was called
}
rfbCredential *c = (rfbCredential *)calloc(1, sizeof(rfbCredential));
c->userCredential.username = strdup(conn->getUserName().char_str());
#if wxUSE_SECRETSTORE
c->userCredential.password = strdup(conn->getPassword().GetAsString().char_str());
#else
c->userCredential.password = strdup(conn->getPassword().char_str());
#endif
return c;
}
return NULL;
};
void VNCConn::thread_got_update(rfbClient* client,int x,int y,int w,int h)
{
VNCConn* conn = (VNCConn*) rfbClientGetClientData(client, VNCCONN_OBJ_ID);
if(! conn->GetThread()->TestDestroy())
{
conn->updated_rect.Union(wxRect(x, y, w, h));
// single (partial) multicast updates are small, so when a big region is updated,
// the update notify receiver gets flooded, resulting in way too much cpu load.
// thus, when multicasting, we only notify for logic (whole) framebuffer updates.
if(!conn->isMulticast())
conn->thread_post_update_notify(x, y, w, h);
if(conn->do_stats)
{
wxCriticalSectionLocker lock(conn->mutex_stats);
wxRect this_update_rect = wxRect(x,y,w,h);
// compressed bytes
conn->upd_bytes += conn->cl->bytesRcvd;
conn->upd_bytes += conn->cl->multicastBytesRcvd;
conn->cl->bytesRcvd = conn->cl->multicastBytesRcvd = 0;
// uncompressed bytes
conn->upd_bytes_inflated += w*h*BYTESPERPIXEL;
// latency check, rect case
if(conn->latency_test_rect_sent && this_update_rect.Contains(wxRect(LATENCY_TEST_RECT)))
{
conn->latency_stopwatch.Pause();
conn->latency = conn->latency_stopwatch.Time();
conn->latency_test_rect_sent = false;
wxLogDebug(wxT("VNCConn %p: got update containing latency test rect, took %ims"), conn, conn->latency_stopwatch.Time());
}
}
}
}
void VNCConn::thread_update_finished(rfbClient* client)
{
VNCConn* conn = (VNCConn*) rfbClientGetClientData(client, VNCCONN_OBJ_ID);
if(! conn->GetThread()->TestDestroy())
{
// single (partial) multicast updates are small, so when a big region is updated,
// the update notify receiver gets flooded, resulting in way too much cpu load.
// thus, when multicasting, we only notify for logic (whole) framebuffer updates.
if(conn->isMulticast() && !conn->updated_rect.IsEmpty())
conn->thread_post_update_notify(conn->updated_rect.x, conn->updated_rect.y, conn->updated_rect.width, conn->updated_rect.height);
conn->updated_rect = wxRect();
if(conn->do_stats)
{
wxCriticalSectionLocker lock(conn->mutex_stats);
conn->upd_count++;
}
}
}
void VNCConn::thread_kbd_leds(rfbClient* cl, int value, int pad)
{
VNCConn* conn = (VNCConn*) rfbClientGetClientData(cl, VNCCONN_OBJ_ID);
wxLogDebug(wxT("VNCConn %p: Led State= 0x%02X"), conn, value);
}
void VNCConn::thread_textchat(rfbClient* cl, int value, char *text)
{
VNCConn* conn = (VNCConn*) rfbClientGetClientData(cl, VNCCONN_OBJ_ID);
switch(value)
{
case (int)rfbTextChatOpen:
wxLogDebug(wxT("VNCConn %p: got textchat open\n"), conn);
break;
case (int)rfbTextChatClose:
wxLogDebug(wxT("VNCConn %p: got textchat close\n"), conn);
break;
case (int)rfbTextChatFinished:
wxLogDebug(wxT("VNCConn %p: got textchat finish\n"), conn);
break;
default:
wxLogDebug(wxT("VNCConn %p: got textchat text: '%s'\n"), conn, text);
}
}
void VNCConn::thread_got_cuttext(rfbClient *cl, const char *text, int len)
{
VNCConn* conn = (VNCConn*) rfbClientGetClientData(cl, VNCCONN_OBJ_ID);
wxLogDebug(wxT("VNCConn %p: got cuttext: '%s'"), conn, wxString(text, wxCSConv(wxT("iso-8859-1"))).c_str());
wxCriticalSectionLocker lock(conn->mutex_cuttext); // since cuttext can also be set from the main thread
conn->cuttext = wxString(text, wxCSConv(wxT("iso-8859-1")));
conn->thread_post_cuttext_notify();
}
void VNCConn::thread_bell(rfbClient *cl)
{
VNCConn* conn = (VNCConn*) rfbClientGetClientData(cl, VNCCONN_OBJ_ID);
wxLogDebug(wxT("VNCConn %p: bell"), conn);
conn->thread_post_bell_notify();
}
void VNCConn::thread_handle_xvp(rfbClient *cl, uint8_t ver, uint8_t code)
{
VNCConn* conn = (VNCConn*) rfbClientGetClientData(cl, VNCCONN_OBJ_ID);
wxLogDebug(wxT("VNCConn %p: handling xvp msg version %d code %d"), conn, ver, code);
if(conn->latency_test_xvpmsg_sent && ver == LATENCY_TEST_XVP_VER && code == rfbXvp_Fail)
{
wxCriticalSectionLocker lock(conn->mutex_stats);
conn->latency_stopwatch.Pause();
conn->latency = conn->latency_stopwatch.Time();
conn->latency_test_xvpmsg_sent = false;
wxLogDebug(wxT("VNCConn %p: got latency test xvp message back, took %ims"), conn, conn->latency_stopwatch.Time());
}
}
// there's no per-connection log since we cannot find out which client
// called the logger function :-(