fix crash when rfbInitClient() fails
[presencevnc] / src / vncclientthread.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2007-2008 Urs Wolfer <uwolfer @ kde.org>
4 **
5 ** This file is part of KDE.
6 **
7 ** This program is free software; you can redistribute it and/or modify
8 ** it under the terms of the GNU General Public License as published by
9 ** the Free Software Foundation; either version 2 of the License, or
10 ** (at your option) any later version.
11 **
12 ** This program is distributed in the hope that it will be useful,
13 ** but WITHOUT ANY WARRANTY; without even the implied warranty of
14 ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 ** GNU General Public License for more details.
16 **
17 ** You should have received a copy of the GNU General Public License
18 ** along with this program; see the file COPYING. If not, write to
19 ** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
20 ** Boston, MA 02110-1301, USA.
21 **
22 ****************************************************************************/
23
24 #include "vncclientthread.h"
25
26 #include <QCoreApplication>
27 #include <QMutexLocker>
28 #include <QTimer>
29
30 static QString outputErrorMessageString;
31
32 rfbBool VncClientThread::newclient(rfbClient *cl)
33 {
34     VncClientThread *t = (VncClientThread*)rfbClientGetClientData(cl, 0);
35     Q_ASSERT(t);
36
37     const int width = cl->width, height = cl->height, depth = cl->format.bitsPerPixel;
38     const int size = width * height * (depth / 8);
39     if (t->frameBuffer)
40         delete [] t->frameBuffer; // do not leak if we get a new framebuffer size
41     t->frameBuffer = new uint8_t[size];
42     cl->frameBuffer = t->frameBuffer;
43     memset(cl->frameBuffer, '\0', size);
44     cl->format.bitsPerPixel = 32;
45     cl->format.redShift = 16;
46     cl->format.greenShift = 8;
47     cl->format.blueShift = 0;
48     cl->format.redMax = 0xff;
49     cl->format.greenMax = 0xff;
50     cl->format.blueMax = 0xff;
51
52     switch (t->quality()) {
53     case RemoteView::High:
54         cl->appData.useBGR233 = 0;
55         cl->appData.encodingsString = "copyrect hextile raw";
56         cl->appData.compressLevel = 0;
57         cl->appData.qualityLevel = 9;
58         break;
59     case RemoteView::Medium:
60         cl->appData.useBGR233 = 0;
61         cl->appData.encodingsString = "tight zrle ultra copyrect hextile zlib corre rre raw";
62         cl->appData.compressLevel = 5;
63         cl->appData.qualityLevel = 7;
64         break;
65     case RemoteView::Low:
66     case RemoteView::Unknown:
67     default:
68         cl->appData.useBGR233 = 1;
69         cl->appData.encodingsString = "tight zrle ultra copyrect hextile zlib corre rre raw";
70         cl->appData.compressLevel = 9;
71         cl->appData.qualityLevel = 1;
72     }
73
74     SetFormatAndEncodings(cl);
75
76     return true;
77 }
78
79 void VncClientThread::updatefb(rfbClient* cl, int x, int y, int w, int h)
80 {
81 //     kDebug(5011) << "updated client: x: " << x << ", y: " << y << ", w: " << w << ", h: " << h;
82
83     const int width = cl->width, height = cl->height;
84
85     const QImage img(cl->frameBuffer, width, height, QImage::Format_RGB32);
86
87     if (img.isNull()) {
88         kDebug(5011) << "image not loaded";
89     }
90
91     VncClientThread *t = (VncClientThread*)rfbClientGetClientData(cl, 0);
92     Q_ASSERT(t);
93
94     t->setImage(img);
95
96     t->emitUpdated(x, y, w, h);
97 }
98
99 void VncClientThread::cuttext(rfbClient* cl, const char *text, int textlen)
100 {
101     const QString cutText = QString::fromUtf8(text, textlen);
102     kDebug(5011) << cutText;
103
104     if (!cutText.isEmpty()) {
105         VncClientThread *t = (VncClientThread*)rfbClientGetClientData(cl, 0);
106         Q_ASSERT(t);
107
108         t->emitGotCut(cutText);
109     }
110 }
111
112 char *VncClientThread::passwdHandler(rfbClient *cl)
113 {
114     kDebug(5011) << "password request" << kBacktrace();
115
116     VncClientThread *t = (VncClientThread*)rfbClientGetClientData(cl, 0);
117     Q_ASSERT(t);
118
119     t->passwordRequest();
120     t->m_passwordError = true;
121
122     return strdup(t->password().toLocal8Bit());
123 }
124
125 void VncClientThread::outputHandler(const char *format, ...)
126 {
127     va_list args;
128     va_start(args, format);
129
130     QString message;
131     message.vsprintf(format, args);
132
133     va_end(args);
134
135     message = message.trimmed();
136
137     kDebug(5011) << message;
138
139     if ((message.contains("Couldn't convert ")) ||
140             (message.contains("Unable to connect to VNC server")))
141         outputErrorMessageString = i18n("Server not found.");
142
143     if ((message.contains("VNC connection failed: Authentication failed, too many tries")) ||
144             (message.contains("VNC connection failed: Too many authentication failures")))
145         outputErrorMessageString = i18n("VNC authentication failed because of too many authentication tries.");
146
147     if (message.contains("VNC connection failed: Authentication failed"))
148         outputErrorMessageString = i18n("VNC authentication failed.");
149
150     if (message.contains("VNC server closed connection"))
151         outputErrorMessageString = i18n("VNC server closed connection.");
152
153     // internal messages, not displayed to user
154     if (message.contains("VNC server supports protocol version 3.889")) // see http://bugs.kde.org/162640
155         outputErrorMessageString = "INTERNAL:APPLE_VNC_COMPATIBILTY";
156 }
157
158 VncClientThread::VncClientThread(QObject *parent)
159         : QThread(parent)
160         , frameBuffer(0)
161 {
162     QMutexLocker locker(&mutex);
163     m_stopped = false;
164
165     QTimer *outputErrorMessagesCheckTimer = new QTimer(this);
166     outputErrorMessagesCheckTimer->setInterval(500);
167     connect(outputErrorMessagesCheckTimer, SIGNAL(timeout()), this, SLOT(checkOutputErrorMessage()));
168     outputErrorMessagesCheckTimer->start();
169 }
170
171 VncClientThread::~VncClientThread()
172 {
173     stop();
174
175     const bool quitSuccess = wait(500);
176
177     kDebug(5011) << "~VncClientThread(): Quit VNC thread success:" << quitSuccess;
178     
179     delete [] frameBuffer;
180     //cl is free()d when event loop exits.
181 }
182
183 void VncClientThread::checkOutputErrorMessage()
184 {
185     if (!outputErrorMessageString.isEmpty()) {
186         kDebug(5011) << outputErrorMessageString;
187         QString errorMessage = outputErrorMessageString;
188         outputErrorMessageString.clear();
189         // show authentication failure error only after the 3rd unsuccessful try
190         if ((errorMessage != i18n("VNC authentication failed.")) || m_passwordError)
191             outputErrorMessage(errorMessage);
192     }
193 }
194
195 void VncClientThread::setHost(const QString &host)
196 {
197     QMutexLocker locker(&mutex);
198     m_host = host;
199 }
200
201 void VncClientThread::setPort(int port)
202 {
203     QMutexLocker locker(&mutex);
204     m_port = port;
205 }
206
207 void VncClientThread::setQuality(RemoteView::Quality quality)
208 {
209     m_quality = quality;
210 }
211
212 RemoteView::Quality VncClientThread::quality() const
213 {
214     return m_quality;
215 }
216
217 void VncClientThread::setImage(const QImage &img)
218 {
219     QMutexLocker locker(&mutex);
220     m_image = img;
221 }
222
223 const QImage VncClientThread::image(int x, int y, int w, int h)
224 {
225     QMutexLocker locker(&mutex);
226
227     if (w == 0) // full image requested
228         return m_image;
229     else
230         return m_image.copy(x, y, w, h);
231 }
232
233 void VncClientThread::emitUpdated(int x, int y, int w, int h)
234 {
235     emit imageUpdated(x, y, w, h);
236 }
237
238 void VncClientThread::emitGotCut(const QString &text)
239 {
240     emit gotCut(text);
241 }
242
243 void VncClientThread::stop()
244 {
245 //TODO: not locking the mutex leads to a crash, but at least it stops.
246     m_stopped = true;
247 }
248
249 void VncClientThread::run()
250 {
251     QMutexLocker locker(&mutex);
252         bool clean = false;
253
254     int passwd_failures = 0;
255     while (!m_stopped) { // try to connect as long as the server allows
256         m_passwordError = false;
257
258         rfbClientLog = outputHandler;
259         rfbClientErr = outputHandler;
260         cl = rfbGetClient(8, 3, 4);
261         cl->MallocFrameBuffer = newclient;
262         cl->canHandleNewFBSize = true;
263         cl->GetPassword = passwdHandler;
264         cl->GotFrameBufferUpdate = updatefb;
265         cl->GotXCutText = cuttext;
266         rfbClientSetClientData(cl, 0, this);
267
268         cl->serverHost = strdup(m_host.toUtf8().constData());
269
270         if (m_port < 0 || !m_port) // port is invalid or empty...
271             m_port = 5900; // fallback: try an often used VNC port
272
273         if (m_port >= 0 && m_port < 100) // the user most likely used the short form (e.g. :1)
274             m_port += 5900;
275         cl->serverPort = m_port;
276
277         kDebug(5011) << "--------------------- trying init ---------------------";
278
279         if (rfbInitClient(cl, 0, 0))
280             break;
281
282         if (m_passwordError) {
283                         passwd_failures++;
284                         if(passwd_failures > 2) {
285                                 m_stopped = true;
286                                 clean = true; //rfbInitClient cleans up after itself upon failure
287                         }
288                         continue;
289                 }
290
291         return;
292     }
293
294     locker.unlock();
295
296     // Main VNC event loop
297     while (!m_stopped) {
298         const int i = WaitForMessage(cl, 500);
299         if (i < 0)
300             break;
301         if (i)
302             if (!HandleRFBServerMessage(cl))
303                 break;
304
305         locker.relock();
306
307         while (!m_eventQueue.isEmpty()) {
308             ClientEvent* clientEvent = m_eventQueue.dequeue();
309             clientEvent->fire(cl);
310             delete clientEvent;
311         }
312
313         locker.unlock();
314     }
315
316     // Cleanup allocated resources
317     locker.relock();
318         if(!clean)
319                 rfbClientCleanup(cl);
320     m_stopped = true;
321 }
322
323 ClientEvent::~ClientEvent()
324 {
325 }
326
327 void PointerClientEvent::fire(rfbClient* cl)
328 {
329     SendPointerEvent(cl, m_x, m_y, m_buttonMask);
330 }
331
332 void KeyClientEvent::fire(rfbClient* cl)
333 {
334     SendKeyEvent(cl, m_key, m_pressed);
335 }
336
337 void ClientCutEvent::fire(rfbClient* cl)
338 {
339     SendClientCutText(cl, text.toUtf8().data(), text.size());
340 }
341
342 void VncClientThread::mouseEvent(int x, int y, int buttonMask)
343 {
344     QMutexLocker lock(&mutex);
345     if (m_stopped)
346         return;
347
348     m_eventQueue.enqueue(new PointerClientEvent(x, y, buttonMask));
349 }
350
351 void VncClientThread::keyEvent(int key, bool pressed)
352 {
353     QMutexLocker lock(&mutex);
354     if (m_stopped)
355         return;
356
357     m_eventQueue.enqueue(new KeyClientEvent(key, pressed));
358 }
359
360 void VncClientThread::clientCut(const QString &text)
361 {
362     QMutexLocker lock(&mutex);
363     if (m_stopped)
364         return;
365
366     m_eventQueue.enqueue(new ClientCutEvent(text));
367 }
368
369 #include "moc_vncclientthread.cpp"