summaryrefslogtreecommitdiffstats
path: root/krfb/krfb/rfbcontroller.cc
blob: 57fb1cbd75d6c2c59eacfba16ff714970a8b9bda (plain)
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
/***************************************************************************
                              rfbcontroller.cpp
                             -------------------
    begin                : Sun Dec 9 2001
    copyright            : (C) 2001-2003 by Tim Jansen
    email                : tim@tjansen.de
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program 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.                                   *
 *                                                                         *
 ***************************************************************************/

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

/*
 * Contains keyboard & pointer handling from libvncserver's x11vnc.c
 */

#include "rfbcontroller.h"
#include "kuser.h"

#include <netinet/tcp.h>
#include <netinet/in.h>
#include <netdb.h>
#include <unistd.h>
#include <fcntl.h>

#ifdef USE_SOLARIS
#include <strings.h>
#endif

#include <tdeapplication.h>
#include <knotifyclient.h>
#include <kdebug.h>
#include <tdemessagebox.h>
#include <tdelocale.h>
#include <kextsock.h>
#include <tqstring.h>
#include <tqcursor.h>
#include <tqwindowdefs.h>
#include <tqtimer.h>
#include <tqcheckbox.h>
#include <tqpushbutton.h>
#include <tqglobal.h>
#include <tqlabel.h>
#include <tqmutex.h>
#include <tqdeepcopy.h>
#include <tqclipboard.h>
#include <tqdesktopwidget.h>

#include <X11/Xutil.h>
#include <X11/extensions/XTest.h>

#ifndef ASSERT
#define ASSERT(x) Q_ASSERT(x)
#endif

#define IDLE_PAUSE (1000/50)
#define MAX_SELECTION_LENGTH (4096)

static XTestDisabler disabler;

static const char* cur=
"                   "
" x                 "
" xx                "
" xxx               "
" xxxx              "
" xxxxx             "
" xxxxxx            "
" xxxxxxx           "
" xxxxxxxx          "
" xxxxxxxxx         "
" xxxxxxxxxx        "
" xxxxx             "
" xx xxx            "
" x  xxx            "
"     xxx           "
"     xxx           "
"      xxx          "
"      xxx          "
"                   ";

static const char* mask=
"xx                 "
"xxx                "
"xxxx               "
"xxxxx              "
"xxxxxx             "
"xxxxxxx            "
"xxxxxxxx           "
"xxxxxxxxx          "
"xxxxxxxxxx         "
"xxxxxxxxxxx        "
"xxxxxxxxxxxx       "
"xxxxxxxxxx         "
"xxxxxxxx           "
"xxxxxxxx           "
"xx  xxxxx          "
"    xxxxx          "
"     xxxxx         "
"     xxxxx         "
"      xxx          ";

static rfbCursorPtr myCursor;

// only one controller exists, so we can do this workaround for functions:
static RFBController *self;

class AppLocker
{
public:
	AppLocker() {
		TDEApplication::kApplication()->lock();
	}

	~AppLocker() {
		TDEApplication::kApplication()->unlock();
	}
};

static enum rfbNewClientAction newClientHook(struct _rfbClientRec *cl)
{
	AppLocker a;
	return self->handleNewClient(cl);
}

static Bool passwordCheck(rfbClientPtr cl,
			  const char* encryptedPassword,
			  int len)
{
	AppLocker a;
	return self->handleCheckPassword(cl, encryptedPassword, len);
}

static void keyboardHook(Bool down, KeySym keySym, rfbClientPtr)
{
	self->handleKeyEvent(down ? true : false, keySym);
}

static void pointerHook(int bm, int x, int y, rfbClientPtr)
{
	self->handlePointerEvent(bm, x, y);
}

static void clientGoneHook(rfbClientPtr)
{
	self->handleClientGone();
}

static void negotiationFinishedHook(rfbClientPtr cl)
{
	self->handleNegotiationFinished(cl);
}

static void inetdDisconnectHook()
{
	self->handleClientGone();
}

static void clipboardHook(char* str,int len, rfbClientPtr)
{
	self->clipboardToServer(TQString::fromUtf8(str, len));
}

VNCEvent::~VNCEvent() {
}

Display *KeyboardEvent::dpy;
signed char KeyboardEvent::modifiers[0x100];
KeyCode KeyboardEvent::keycodes[0x100];
KeyCode KeyboardEvent::leftShiftCode;
KeyCode KeyboardEvent::rightShiftCode;
KeyCode KeyboardEvent::altGrCode;
const int KeyboardEvent::LEFTSHIFT = 1;
const int KeyboardEvent::RIGHTSHIFT = 2;
const int KeyboardEvent::ALTGR = 4;
char KeyboardEvent::ModifierState;

KeyboardEvent::KeyboardEvent(bool d, KeySym k) :
	down(d),
	keySym(k) {
}

void KeyboardEvent::initKeycodes() {
	KeySym key,*keymap;
	int i,j,minkey,maxkey,syms_per_keycode;

	dpy = tqt_xdisplay();

	memset(modifiers,-1,sizeof(modifiers));

	XDisplayKeycodes(dpy,&minkey,&maxkey);
	ASSERT(minkey >= 8);
	ASSERT(maxkey < 256);
	keymap = (KeySym*) XGetKeyboardMapping(dpy, minkey,
				     (maxkey - minkey + 1),
				     &syms_per_keycode);
	ASSERT(keymap);

	for (i = minkey; i <= maxkey; i++)
		for (j=0; j<syms_per_keycode; j++) {
			key = keymap[(i-minkey)*syms_per_keycode+j];
			if (key>=' ' && key<0x100 && i==XKeysymToKeycode(dpy,key)) {
				keycodes[key]=i;
				modifiers[key]=j;
			}
		}

	leftShiftCode = XKeysymToKeycode(dpy, XK_Shift_L);
	rightShiftCode = XKeysymToKeycode(dpy, XK_Shift_R);
	altGrCode = XKeysymToKeycode(dpy, XK_Mode_switch);

	XFree ((char *)keymap);
}

/* this function adjusts the modifiers according to mod (as from modifiers) and ModifierState */
void KeyboardEvent::tweakModifiers(signed char mod, bool down) {

	bool isShift = ModifierState & (LEFTSHIFT|RIGHTSHIFT);
	if(mod < 0)
		return;

	if(isShift && mod != 1) {
		if(ModifierState & LEFTSHIFT)
			XTestFakeKeyEvent(dpy, leftShiftCode,
					  !down, CurrentTime);
		if(ModifierState & RIGHTSHIFT)
				XTestFakeKeyEvent(dpy, rightShiftCode,
						  !down, CurrentTime);
	}

	if(!isShift && mod==1)
		XTestFakeKeyEvent(dpy, leftShiftCode,
				  down, CurrentTime);

	if((ModifierState&ALTGR) && mod != 2)
		XTestFakeKeyEvent(dpy, altGrCode,
				  !down, CurrentTime);
	if(!(ModifierState&ALTGR) && mod==2)
		XTestFakeKeyEvent(dpy, altGrCode,
				  down, CurrentTime);
}

void KeyboardEvent::exec() {
#define ADJUSTMOD(sym,state) \
  if(keySym==sym) { if(down) ModifierState|=state; else ModifierState&=~state; }

	ADJUSTMOD(XK_Shift_L,LEFTSHIFT);
	ADJUSTMOD(XK_Shift_R,RIGHTSHIFT);
	ADJUSTMOD(XK_Mode_switch,ALTGR);

	if(keySym>=' ' && keySym<0x100) {
		KeyCode k;
		if (down)
			tweakModifiers(modifiers[keySym],True);
		k = keycodes[keySym];
		if (k != NoSymbol)
			XTestFakeKeyEvent(dpy, k, down, CurrentTime);

		if (down)
			tweakModifiers(modifiers[keySym],False);
	} else {
		KeyCode k = XKeysymToKeycode(dpy, keySym );
		if (k != NoSymbol)
			XTestFakeKeyEvent(dpy, k, down, CurrentTime);
	}
}

bool PointerEvent::initialized = false;
Display *PointerEvent::dpy;
int PointerEvent::buttonMask = 0;

PointerEvent::PointerEvent(int b, int _x, int _y) :
	button_mask(b),
	x(_x),
	y(_y) {
	if (!initialized) {
		initialized = true;
		dpy = tqt_xdisplay();
		buttonMask = 0;
	}
}

void PointerEvent::exec() {
	TQDesktopWidget *desktopWidget = TQApplication::desktop();

	int screen = desktopWidget->screenNumber();
	if (screen < 0)
		screen = 0;
	XTestFakeMotionEvent(dpy, screen, x, y, CurrentTime);
	for(int i = 0; i < 5; i++)
		if ((buttonMask&(1<<i))!=(button_mask&(1<<i)))
			XTestFakeButtonEvent(dpy,
					     i+1,
					     (button_mask&(1<<i))?True:False,
					     CurrentTime);

	buttonMask = button_mask;
}


ClipboardEvent::ClipboardEvent(RFBController *c, const TQString &ctext) :
	controller(c),
	text(TQDeepCopy<TQString>(ctext)) {
}

void ClipboardEvent::exec() {
	if ((controller->lastClipboardDirection == RFBController::LAST_SYNC_TO_CLIENT) &&
	    (controller->lastClipboardText == text)) {
		return;
	}
	controller->lastClipboardDirection = RFBController::LAST_SYNC_TO_SERVER;
	controller->lastClipboardText = text;

	controller->clipboard->setText(text, TQClipboard::Clipboard);
	controller->clipboard->setText(text, TQClipboard::Selection);
}


KNotifyEvent::KNotifyEvent(const TQString &n, const TQString &d) :
	name(n),
	desc(d) {
}

KNotifyEvent::~KNotifyEvent() {
}

void KNotifyEvent::exec() {
	KNotifyClient::event(name, desc);
}

SessionEstablishedEvent::SessionEstablishedEvent(RFBController *c) :
        controller(c)
{ }

void SessionEstablishedEvent::exec() {
        controller->sendSessionEstablished();
}

RFBController::RFBController(Configuration *c) :
	allowDesktopControl(false),
	lastClipboardDirection(LAST_SYNC_TO_SERVER),
	configuration(c),
	dialog( 0, "ConnectionDialog" ),
	disableBackgroundPending(false),
	disableBackgroundState(false),
	closePending(false),
	forcedClose(false)
{
	self = this;
	connect(&dialog, TQT_SIGNAL(okClicked()), TQT_SLOT(dialogAccepted()));
	connect(&dialog, TQT_SIGNAL(cancelClicked()), TQT_SLOT(dialogRefused()));
	connect(&initIdleTimer, TQT_SIGNAL(timeout()), TQT_SLOT(checkAsyncEvents()));
	connect(&idleTimer, TQT_SIGNAL(timeout()), TQT_SLOT(idleSlot()));

	clipboard = TQApplication::clipboard();
	connect(clipboard, TQT_SIGNAL(selectionChanged()), this, TQT_SLOT(selectionChanged()));
	connect(clipboard, TQT_SIGNAL(dataChanged()), this, TQT_SLOT(clipboardChanged()));

	asyncQueue.setAutoDelete(true);

	KeyboardEvent::initKeycodes();

	char hostname[256];
	if (gethostname(hostname, 255))
		hostname[0] = 0;
	hostname[255] = 0;
	desktopName = i18n("%1@%2 (shared desktop)").arg(KUser().loginName()).arg(hostname);
}

RFBController::~RFBController()
{
	stopServer();
}



void RFBController::startServer(int inetdFd, bool xtestGrab)
{
	framebufferImage = XGetImage(tqt_xdisplay(),
				     TQApplication::desktop()->winId(),
				     0,
				     0,
				     TQApplication::desktop()->width(),
				     TQApplication::desktop()->height(),
				     AllPlanes,
				     ZPixmap);

	int w = framebufferImage->width;
	int h = framebufferImage->height;
	char *fb = framebufferImage->data;

	int bpp = framebufferImage->bits_per_pixel >> 3;
	if (bpp != 1 && bpp != 2 && bpp != 4) bpp = 4;

	rfbLogEnable(0);
	server = rfbGetScreen(0, 0, w, h, (bpp*8), 8, bpp);

	server->paddedWidthInBytes = framebufferImage->bytes_per_line;

	server->rfbServerFormat.bitsPerPixel = framebufferImage->bits_per_pixel;
	server->rfbServerFormat.depth = framebufferImage->depth;
	server->rfbServerFormat.trueColour = (CARD8) TRUE;
	server->rfbServerFormat.bigEndian =  (CARD8) ((framebufferImage->bitmap_bit_order == MSBFirst) ? TRUE : FALSE);

	if ( server->rfbServerFormat.bitsPerPixel == 8 ) {
		server->rfbServerFormat.redShift = 0;
		server->rfbServerFormat.greenShift = 3;
		server->rfbServerFormat.blueShift = 6;
		server->rfbServerFormat.redMax   = 7;
		server->rfbServerFormat.greenMax = 7;
		server->rfbServerFormat.blueMax  = 3;
	} else {
		server->rfbServerFormat.redShift = 0;
		if ( framebufferImage->red_mask )
			while ( ! ( framebufferImage->red_mask & (1 << server->rfbServerFormat.redShift) ) )
				server->rfbServerFormat.redShift++;
		server->rfbServerFormat.greenShift = 0;
		if ( framebufferImage->green_mask )
			while ( ! ( framebufferImage->green_mask & (1 << server->rfbServerFormat.greenShift) ) )
				server->rfbServerFormat.greenShift++;
		server->rfbServerFormat.blueShift = 0;
		if ( framebufferImage->blue_mask )
			while ( ! ( framebufferImage->blue_mask & (1 << server->rfbServerFormat.blueShift) ) )
				server->rfbServerFormat.blueShift++;
		server->rfbServerFormat.redMax   = framebufferImage->red_mask   >> server->rfbServerFormat.redShift;
		server->rfbServerFormat.greenMax = framebufferImage->green_mask >> server->rfbServerFormat.greenShift;
		server->rfbServerFormat.blueMax  = framebufferImage->blue_mask  >> server->rfbServerFormat.blueShift;
	}

	server->frameBuffer = fb;
	server->autoPort = TRUE;
	server->inetdSock = inetdFd;

	server->kbdAddEvent = keyboardHook;
	server->ptrAddEvent = pointerHook;
	server->newClientHook = newClientHook;
	server->inetdDisconnectHook = inetdDisconnectHook;
	server->passwordCheck = passwordCheck;
	server->setXCutText = clipboardHook;

	server->desktopName = desktopName.latin1();

	if (!myCursor)
		myCursor = rfbMakeXCursor(19, 19, (char*) cur, (char*) mask);
	server->cursor = myCursor;

	passwordChanged();

	scanner = new XUpdateScanner(tqt_xdisplay(),
				     TQApplication::desktop()->winId(),
				     (unsigned char*)fb, w, h,
				     server->rfbServerFormat.bitsPerPixel,
				     server->paddedWidthInBytes,
				     !configuration->disableXShm());

	rfbInitServer(server);
	state = RFB_WAITING;

	if (xtestGrab) {
		disabler.disable = false;
		XTestGrabControl(tqt_xdisplay(), true);
	}

	rfbRunEventLoop(server, -1, TRUE);
	initIdleTimer.start(IDLE_PAUSE);
}

void RFBController::stopServer(bool xtestUngrab)
{
	rfbScreenCleanup(server);
	state = RFB_STOPPED;
	delete scanner;

	XDestroyImage(framebufferImage);

	if (xtestUngrab) {
		disabler.disable = true;
		TQTimer::singleShot(0, &disabler, TQT_SLOT(exec()));
	}
}

void RFBController::connectionAccepted(bool aRC)
{
	if (state != RFB_CONNECTING)
		return;

	allowDesktopControl = aRC;
	emit desktopControlSettingChanged(aRC);
	initIdleTimer.stop();
	idleTimer.start(IDLE_PAUSE);

	server->rfbClientHead->clientGoneHook = clientGoneHook;
	state = RFB_CONNECTED;
	if (!server->rfbAuthPasswdData)
	        emit sessionEstablished(remoteIp);
}

void RFBController::acceptConnection(bool aRemoteControl)
{
	KNotifyClient::event("UserAcceptsConnection",
			     i18n("User accepts connection from %1")
			     .arg(remoteIp));

	if (state != RFB_CONNECTING)
		return;

	connectionAccepted(aRemoteControl);
	rfbStartOnHoldClient(server->rfbClientHead);
}

void RFBController::refuseConnection()
{
	KNotifyClient::event("UserRefusesConnection",
			     i18n("User refuses connection from %1")
			     .arg(remoteIp));

	if (state != RFB_CONNECTING)
		return;
	rfbRefuseOnHoldClient(server->rfbClientHead);
	state = RFB_WAITING;
}

// checks async events, returns true if client disconnected
bool RFBController::checkAsyncEvents()
{
	bool closed = false;
	bool backgroundActionRequired = false;
	asyncMutex.lock();
	VNCEvent *e;
	for (e = asyncQueue.first(); e; e = asyncQueue.next())
		e->exec();
	asyncQueue.clear();
	if (closePending) {
		connectionClosed();
		closed = true;
		closePending = false;
	}
	if (disableBackgroundPending != disableBackgroundState)
		backgroundActionRequired = true;
	asyncMutex.unlock();

	if (backgroundActionRequired && (!closed) && !configuration->disableBackground())
		disableBackground(disableBackgroundPending);

	return closed;
}

void RFBController::disableBackground(bool state) {
	if (disableBackgroundState == state)
		return;

	disableBackgroundState = state;
	DCOPRef ref("kdesktop", "KBackgroundIface");
	ref.setDCOPClient(TDEApplication::dcopClient());

	ref.send("setBackgroundEnabled(bool)", bool(!state));
}

void RFBController::connectionClosed()
{
	KNotifyClient::event("ConnectionClosed",
			     i18n("Closed connection: %1.")
			     .arg(remoteIp));

	idleTimer.stop();
	initIdleTimer.stop();
	disableBackground(false);
	state = RFB_WAITING;
	if (forcedClose)
	        emit quitApp();
	else
	        emit sessionFinished();
}

void RFBController::closeConnection()
{
        forcedClose = true;
	if (state == RFB_CONNECTED) {
	        disableBackground(false);

		if (!checkAsyncEvents()) {
			asyncMutex.lock();
			if (!closePending)
				rfbCloseClient(server->rfbClientHead);
			asyncMutex.unlock();
		}
	}
	else if (state == RFB_CONNECTING)
		refuseConnection();
}

void RFBController::enableDesktopControl(bool b) {
	if (b != allowDesktopControl)
		emit desktopControlSettingChanged(b);
	allowDesktopControl = b;
}

void RFBController::idleSlot()
{
	if (state != RFB_CONNECTED)
		return;
	if (checkAsyncEvents() || forcedClose)
		return;

	rfbUndrawCursor(server);

	TQPtrList<Hint> v;
	v.setAutoDelete(true);
	TQPoint p = TQCursor::pos();
	scanner->searchUpdates(v, p.y());

	Hint *h;

	for (h = v.first(); h != 0; h = v.next())
		rfbMarkRectAsModified(server, h->left(),
				      h->top(),
				      h->right(),
				      h->bottom());

	asyncMutex.lock();
	if (!closePending)
		defaultPtrAddEvent(0, p.x(),p.y(), server->rfbClientHead);
	asyncMutex.unlock();

	checkAsyncEvents(); // check 2nd time (see 3rd line)
}

void RFBController::dialogAccepted()
{
	dialog.hide();
	acceptConnection(dialog.allowRemoteControl());
}

void RFBController::dialogRefused()
{
	refuseConnection();
	dialog.hide();
	emit sessionRefused();
}

bool checkPassword(const TQString &p,
	unsigned char *ochallenge,
	const char *response,
	int len) {

	if ((len == 0) && (p.length() == 0))
		return true;

	char passwd[MAXPWLEN];
	unsigned char challenge[CHALLENGESIZE];

	memcpy(challenge, ochallenge, CHALLENGESIZE);
	bzero(passwd, MAXPWLEN);
	if (!p.isNull())
		strncpy(passwd, p.latin1(),
			(MAXPWLEN <= p.length()) ? MAXPWLEN : p.length());

	vncEncryptBytes(challenge, passwd);
	return memcmp(challenge, response, len) == 0;
}

bool RFBController::handleCheckPassword(rfbClientPtr cl,
					const char *response,
					int len)
{

	bool authd = false;

	if (configuration->allowUninvitedConnections())
		authd = checkPassword(configuration->password(),
			cl->authChallenge, response, len);

	if (!authd) {
		TQValueList<Invitation>::iterator it =
			configuration->invitations().begin();
		while (it != configuration->invitations().end()) {
			if (checkPassword((*it).password(),
				cl->authChallenge, response, len) &&
				(*it).isValid()) {
				authd = true;
				configuration->removeInvitation(it);
				break;
			}
			it++;
		}
	}

	if (!authd) {
		if (configuration->invitations().size() > 0) {
			sendKNotifyEvent("InvalidPasswordInvitations",
					i18n("Failed login attempt from %1: wrong password")
					.arg(remoteIp));
}
		else
			sendKNotifyEvent("InvalidPassword",
					i18n("Failed login attempt from %1: wrong password")
					.arg(remoteIp));
		return FALSE;
	}

	asyncMutex.lock();
	asyncQueue.append(new SessionEstablishedEvent(this));
	asyncMutex.unlock();

	return TRUE;
}

enum rfbNewClientAction RFBController::handleNewClient(rfbClientPtr cl)
{
	int socket = cl->sock;
	cl->negotiationFinishedHook = negotiationFinishedHook;

	TQString host, port;
	TDESocketAddress *ksa = KExtendedSocket::peerAddress(socket);
	if (ksa) {
		hostent *he = 0;
		KInetSocketAddress *kisa = (KInetSocketAddress*) ksa;
		in_addr ia4 = kisa->hostV4();
		he = gethostbyaddr((const char*)&ia4,
				   sizeof(ia4),
				   AF_INET);

		if (he && he->h_name)
			host = TQString(he->h_name);
		else
			host = ksa->nodeName();
		delete ksa;
	}

	if (state != RFB_WAITING) {
		sendKNotifyEvent("TooManyConnections",
					i18n("Connection refused from %1, already connected.")
					.arg(host));
		return RFB_CLIENT_REFUSE;
	}
	remoteIp = host;
	state = RFB_CONNECTING;

	if ((!configuration->askOnConnect()) &&
	    (configuration->invitations().size() == 0)) {
		sendKNotifyEvent("NewConnectionAutoAccepted",
					i18n("Accepted uninvited connection from %1")
					.arg(remoteIp));

		connectionAccepted(configuration->allowDesktopControl());
		return RFB_CLIENT_ACCEPT;
	}

	sendKNotifyEvent("NewConnectionOnHold",
				i18n("Received connection from %1, on hold (waiting for confirmation)")
				.arg(remoteIp));

	dialog.setRemoteHost(remoteIp);
	dialog.setAllowRemoteControl( true );
	dialog.setFixedSize(dialog.sizeHint());
	dialog.show();
	return RFB_CLIENT_ON_HOLD;
}

void RFBController::handleClientGone()
{
	asyncMutex.lock();
	closePending = true;
	asyncMutex.unlock();
}

void RFBController::handleNegotiationFinished(rfbClientPtr cl)
{
	asyncMutex.lock();
	disableBackgroundPending = cl->disableBackground;
	asyncMutex.unlock();
}

void RFBController::handleKeyEvent(bool down, KeySym keySym) {
	if (!allowDesktopControl)
		return;

	asyncMutex.lock();
	asyncQueue.append(new KeyboardEvent(down, keySym));
	asyncMutex.unlock();
}

void RFBController::handlePointerEvent(int button_mask, int x, int y) {
	if (!allowDesktopControl)
		return;

	asyncMutex.lock();
	asyncQueue.append(new PointerEvent(button_mask, x, y));
	asyncMutex.unlock();
}


void RFBController::clipboardToServer(const TQString &ctext) {
	if (!allowDesktopControl)
		return;

	asyncMutex.lock();
	asyncQueue.append(new ClipboardEvent(this, ctext));
	asyncMutex.unlock();
}

void RFBController::clipboardChanged() {
	if (state != RFB_CONNECTED)
		return;
	if (clipboard->ownsClipboard())
		return;

	TQString text = clipboard->text(TQClipboard::Clipboard);

	// avoid ping-pong between client&server
	if ((lastClipboardDirection == LAST_SYNC_TO_SERVER) &&
	    (lastClipboardText == text))
		return;
	if ((text.length() > MAX_SELECTION_LENGTH) || text.isNull())
		return;

	lastClipboardDirection = LAST_SYNC_TO_CLIENT;
	lastClipboardText = text;
	TQCString ctext = text.utf8();
	rfbSendServerCutText(server, ctext.data(), ctext.length());
}

void RFBController::selectionChanged() {
	if (state != RFB_CONNECTED)
		return;
	if (clipboard->ownsSelection())
		return;

	TQString text = clipboard->text(TQClipboard::Selection);
	// avoid ping-pong between client&server
	if ((lastClipboardDirection == LAST_SYNC_TO_SERVER) &&
	    (lastClipboardText == text))
		return;
	if ((text.length() > MAX_SELECTION_LENGTH) || text.isNull())
		return;

	lastClipboardDirection = LAST_SYNC_TO_CLIENT;
	lastClipboardText = text;
	TQCString ctext = text.utf8();
	rfbSendServerCutText(server, ctext.data(), ctext.length());
}

void RFBController::passwordChanged() {
	bool authRequired = (!configuration->allowUninvitedConnections()) ||
		(configuration->password().length() != 0) ||
		(configuration->invitations().count() > 0);

	server->rfbAuthPasswdData = (void*) (authRequired ? 1 : 0);
}

void RFBController::sendKNotifyEvent(const TQString &n, const TQString &d)
{
	asyncMutex.lock();
	asyncQueue.append(new KNotifyEvent(n, d));
	asyncMutex.unlock();
}

void RFBController::sendSessionEstablished()
{
	if (configuration->disableBackground())
		disableBackground(true);
        emit sessionEstablished(remoteIp);
}

#ifdef __osf__
extern "C" Bool XShmQueryExtension(Display*);
#endif

bool RFBController::checkX11Capabilities() {
	int bp1, bp2, majorv, minorv;
	Bool r = XTestQueryExtension(tqt_xdisplay(), &bp1, &bp2,
				     &majorv, &minorv);
	if ((!r) || (((majorv*1000)+minorv) < 2002)) {
		KMessageBox::error(0,
		   i18n("Your X11 Server does not support the required XTest extension version 2.2. Sharing your desktop is not possible."),
				   i18n("Desktop Sharing Error"));
		return false;
	}

	return true;
}


XTestDisabler::XTestDisabler() :
	disable(false) {
}

void XTestDisabler::exec() {
	if (disable)
		XTestDiscard(tqt_xdisplay());
}

#include "rfbcontroller.moc"