vncserver.cc (12334:e0ab29a34764) vncserver.cc (12693:4db8d6442b44)
1/*
2 * Copyright (c) 2010, 2015 ARM Limited
3 * All rights reserved
4 *
5 * The license below extends only to copyright in the software and shall
6 * not be construed as granting a license to any other intellectual
7 * property including but not limited to intellectual property relating
8 * to a hardware implementation of the functionality of the software
9 * licensed hereunder. You may use the software subject to the license
10 * terms below provided that you ensure that this notice is replicated
11 * unmodified and in its entirety in all distributions of the software,
12 * modified or unmodified, in source code or in binary form.
13 *
14 * Redistribution and use in source and binary forms, with or without
15 * modification, are permitted provided that the following conditions are
16 * met: redistributions of source code must retain the above copyright
17 * notice, this list of conditions and the following disclaimer;
18 * redistributions in binary form must reproduce the above copyright
19 * notice, this list of conditions and the following disclaimer in the
20 * documentation and/or other materials provided with the distribution;
21 * neither the name of the copyright holders nor the names of its
22 * contributors may be used to endorse or promote products derived from
23 * this software without specific prior written permission.
24 *
25 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
26 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
27 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
28 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
29 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
30 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
31 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
35 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 *
37 * Authors: Ali Saidi
38 * William Wang
39 */
40
41/** @file
42 * Implementiation of a VNC server
43 */
44
45#include <sys/ioctl.h>
46#include <sys/stat.h>
47
48#if defined(__FreeBSD__)
49#include <termios.h>
50
51#else
52#include <sys/termios.h>
53
54#endif
55#include "base/vnc/vncserver.hh"
56
57#include <fcntl.h>
58#include <poll.h>
59#include <sys/types.h>
60#include <unistd.h>
61
62#include <cerrno>
63#include <cstddef>
64#include <cstdio>
65
66#include "base/atomicio.hh"
67#include "base/logging.hh"
68#include "base/output.hh"
69#include "base/socket.hh"
70#include "base/trace.hh"
71#include "debug/VNC.hh"
72#include "sim/byteswap.hh"
73#include "sim/core.hh"
74
75using namespace std;
76
77const PixelConverter VncServer::pixelConverter(
78 4, // 4 bytes / pixel
79 16, 8, 0, // R in [23, 16], G in [15, 8], B in [7, 0]
80 8, 8, 8, // 8 bits / channel
81 LittleEndianByteOrder);
82
83/** @file
84 * Implementiation of a VNC server
85 */
86
87/**
88 * Poll event for the listen socket
89 */
90VncServer::ListenEvent::ListenEvent(VncServer *vs, int fd, int e)
91 : PollEvent(fd, e), vncserver(vs)
92{
93}
94
95void
96VncServer::ListenEvent::process(int revent)
97{
98 vncserver->accept();
99}
100
101/**
102 * Poll event for the data socket
103 */
104VncServer::DataEvent::DataEvent(VncServer *vs, int fd, int e)
105 : PollEvent(fd, e), vncserver(vs)
106{
107}
108
109void
110VncServer::DataEvent::process(int revent)
111{
112 if (revent & POLLIN)
113 vncserver->data();
114 else if (revent & POLLNVAL)
115 vncserver->detach();
116}
117
118/**
119 * VncServer
120 */
121VncServer::VncServer(const Params *p)
122 : VncInput(p), listenEvent(NULL), dataEvent(NULL), number(p->number),
123 dataFd(-1), sendUpdate(false),
124 supportsRawEnc(false), supportsResizeEnc(false)
125{
126 if (p->port)
127 listen(p->port);
128
129 curState = WaitForProtocolVersion;
130
131 // We currently only support one pixel format. Extract the pixel
132 // representation from our PixelConverter instance and keep it
133 // around for telling the client and making sure it cooperates
134 pixelFormat.bpp = 8 * pixelConverter.length;
135 pixelFormat.depth = pixelConverter.depth;
136 pixelFormat.bigendian = pixelConverter.byte_order == BigEndianByteOrder;
137 pixelFormat.truecolor = 1;
138 pixelFormat.redmax = pixelConverter.ch_r.mask;
139 pixelFormat.greenmax = pixelConverter.ch_g.mask;
140 pixelFormat.bluemax = pixelConverter.ch_b.mask;
141 pixelFormat.redshift = pixelConverter.ch_r.offset;
142 pixelFormat.greenshift = pixelConverter.ch_g.offset;
143 pixelFormat.blueshift = pixelConverter.ch_b.offset;
144
145 DPRINTF(VNC, "Vnc server created at port %d\n", p->port);
146}
147
148VncServer::~VncServer()
149{
150 if (dataFd != -1)
151 ::close(dataFd);
152
153 if (listenEvent)
154 delete listenEvent;
155
156 if (dataEvent)
157 delete dataEvent;
158}
159
160
161//socket creation and vnc client attach
162void
163VncServer::listen(int port)
164{
165 if (ListenSocket::allDisabled()) {
166 warn_once("Sockets disabled, not accepting vnc client connections");
167 return;
168 }
169
170 while (!listener.listen(port, true)) {
171 DPRINTF(VNC,
172 "can't bind address vnc server port %d in use PID %d\n",
173 port, getpid());
174 port++;
175 }
176
1/*
2 * Copyright (c) 2010, 2015 ARM Limited
3 * All rights reserved
4 *
5 * The license below extends only to copyright in the software and shall
6 * not be construed as granting a license to any other intellectual
7 * property including but not limited to intellectual property relating
8 * to a hardware implementation of the functionality of the software
9 * licensed hereunder. You may use the software subject to the license
10 * terms below provided that you ensure that this notice is replicated
11 * unmodified and in its entirety in all distributions of the software,
12 * modified or unmodified, in source code or in binary form.
13 *
14 * Redistribution and use in source and binary forms, with or without
15 * modification, are permitted provided that the following conditions are
16 * met: redistributions of source code must retain the above copyright
17 * notice, this list of conditions and the following disclaimer;
18 * redistributions in binary form must reproduce the above copyright
19 * notice, this list of conditions and the following disclaimer in the
20 * documentation and/or other materials provided with the distribution;
21 * neither the name of the copyright holders nor the names of its
22 * contributors may be used to endorse or promote products derived from
23 * this software without specific prior written permission.
24 *
25 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
26 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
27 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
28 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
29 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
30 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
31 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
35 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 *
37 * Authors: Ali Saidi
38 * William Wang
39 */
40
41/** @file
42 * Implementiation of a VNC server
43 */
44
45#include <sys/ioctl.h>
46#include <sys/stat.h>
47
48#if defined(__FreeBSD__)
49#include <termios.h>
50
51#else
52#include <sys/termios.h>
53
54#endif
55#include "base/vnc/vncserver.hh"
56
57#include <fcntl.h>
58#include <poll.h>
59#include <sys/types.h>
60#include <unistd.h>
61
62#include <cerrno>
63#include <cstddef>
64#include <cstdio>
65
66#include "base/atomicio.hh"
67#include "base/logging.hh"
68#include "base/output.hh"
69#include "base/socket.hh"
70#include "base/trace.hh"
71#include "debug/VNC.hh"
72#include "sim/byteswap.hh"
73#include "sim/core.hh"
74
75using namespace std;
76
77const PixelConverter VncServer::pixelConverter(
78 4, // 4 bytes / pixel
79 16, 8, 0, // R in [23, 16], G in [15, 8], B in [7, 0]
80 8, 8, 8, // 8 bits / channel
81 LittleEndianByteOrder);
82
83/** @file
84 * Implementiation of a VNC server
85 */
86
87/**
88 * Poll event for the listen socket
89 */
90VncServer::ListenEvent::ListenEvent(VncServer *vs, int fd, int e)
91 : PollEvent(fd, e), vncserver(vs)
92{
93}
94
95void
96VncServer::ListenEvent::process(int revent)
97{
98 vncserver->accept();
99}
100
101/**
102 * Poll event for the data socket
103 */
104VncServer::DataEvent::DataEvent(VncServer *vs, int fd, int e)
105 : PollEvent(fd, e), vncserver(vs)
106{
107}
108
109void
110VncServer::DataEvent::process(int revent)
111{
112 if (revent & POLLIN)
113 vncserver->data();
114 else if (revent & POLLNVAL)
115 vncserver->detach();
116}
117
118/**
119 * VncServer
120 */
121VncServer::VncServer(const Params *p)
122 : VncInput(p), listenEvent(NULL), dataEvent(NULL), number(p->number),
123 dataFd(-1), sendUpdate(false),
124 supportsRawEnc(false), supportsResizeEnc(false)
125{
126 if (p->port)
127 listen(p->port);
128
129 curState = WaitForProtocolVersion;
130
131 // We currently only support one pixel format. Extract the pixel
132 // representation from our PixelConverter instance and keep it
133 // around for telling the client and making sure it cooperates
134 pixelFormat.bpp = 8 * pixelConverter.length;
135 pixelFormat.depth = pixelConverter.depth;
136 pixelFormat.bigendian = pixelConverter.byte_order == BigEndianByteOrder;
137 pixelFormat.truecolor = 1;
138 pixelFormat.redmax = pixelConverter.ch_r.mask;
139 pixelFormat.greenmax = pixelConverter.ch_g.mask;
140 pixelFormat.bluemax = pixelConverter.ch_b.mask;
141 pixelFormat.redshift = pixelConverter.ch_r.offset;
142 pixelFormat.greenshift = pixelConverter.ch_g.offset;
143 pixelFormat.blueshift = pixelConverter.ch_b.offset;
144
145 DPRINTF(VNC, "Vnc server created at port %d\n", p->port);
146}
147
148VncServer::~VncServer()
149{
150 if (dataFd != -1)
151 ::close(dataFd);
152
153 if (listenEvent)
154 delete listenEvent;
155
156 if (dataEvent)
157 delete dataEvent;
158}
159
160
161//socket creation and vnc client attach
162void
163VncServer::listen(int port)
164{
165 if (ListenSocket::allDisabled()) {
166 warn_once("Sockets disabled, not accepting vnc client connections");
167 return;
168 }
169
170 while (!listener.listen(port, true)) {
171 DPRINTF(VNC,
172 "can't bind address vnc server port %d in use PID %d\n",
173 port, getpid());
174 port++;
175 }
176
177 int p1, p2;
178 p2 = name().rfind('.') - 1;
179 p1 = name().rfind('.', p2);
180 ccprintf(cerr, "Listening for %s connection on port %d\n",
181 name().substr(p1 + 1, p2 - p1), port);
177 ccprintf(cerr, "%s: Listening for connections on port %d\n",
178 name(), port);
182
183 listenEvent = new ListenEvent(this, listener.getfd(), POLLIN);
184 pollQueue.schedule(listenEvent);
185}
186
187// attach a vnc client
188void
189VncServer::accept()
190{
191 // As a consequence of being called from the PollQueue, we might
192 // have been called from a different thread. Migrate to "our"
193 // thread.
194 EventQueue::ScopedMigration migrate(eventQueue());
195
196 if (!listener.islistening())
197 panic("%s: cannot accept a connection if not listening!", name());
198
199 int fd = listener.accept(true);
200 if (fd < 0) {
201 warn("%s: failed to accept VNC connection!", name());
202 return;
203 }
204
205 if (dataFd != -1) {
206 char message[] = "vnc server already attached!\n";
207 atomic_write(fd, message, sizeof(message));
208 ::close(fd);
209 return;
210 }
211
212 dataFd = fd;
213
214 // Send our version number to the client
215 write((uint8_t *)vncVersion(), strlen(vncVersion()));
216
217 // read the client response
218 dataEvent = new DataEvent(this, dataFd, POLLIN);
219 pollQueue.schedule(dataEvent);
220
221 inform("VNC client attached\n");
222}
223
224// data called by data event
225void
226VncServer::data()
227{
228 // We have new data, see if we can handle it
229 DPRINTF(VNC, "Vnc client message recieved\n");
230
231 switch (curState) {
232 case WaitForProtocolVersion:
233 checkProtocolVersion();
234 break;
235 case WaitForSecurityResponse:
236 checkSecurity();
237 break;
238 case WaitForClientInit:
239 // Don't care about shared, just need to read it out of the socket
240 uint8_t shared;
241 if (!read(&shared))
242 return;
243
244 // Send our idea of the frame buffer
245 sendServerInit();
246
247 break;
248 case NormalPhase:
249 uint8_t message_type;
250 if (!read(&message_type))
251 return;
252
253 switch (message_type) {
254 case ClientSetPixelFormat:
255 setPixelFormat();
256 break;
257 case ClientSetEncodings:
258 setEncodings();
259 break;
260 case ClientFrameBufferUpdate:
261 requestFbUpdate();
262 break;
263 case ClientKeyEvent:
264 recvKeyboardInput();
265 break;
266 case ClientPointerEvent:
267 recvPointerInput();
268 break;
269 case ClientCutText:
270 recvCutText();
271 break;
272 default:
273 warn("Unimplemented message type recv from client: %d\n",
274 message_type);
275 detach();
276 break;
277 }
278 break;
279 default:
280 panic("Unknown vnc server state\n");
281 }
282}
283
284
285// read from socket
286bool
287VncServer::read(uint8_t *buf, size_t len)
288{
289 if (dataFd < 0)
290 panic("vnc not properly attached.\n");
291
292 size_t ret;
293 do {
294 ret = ::read(dataFd, buf, len);
295 } while (ret == -1 && errno == EINTR);
296
297
298 if (ret != len) {
299 DPRINTF(VNC, "Read failed %d.\n", ret);
300 detach();
301 return false;
302 }
303
304 return true;
305}
306
307bool
308VncServer::read1(uint8_t *buf, size_t len)
309{
310 return read(buf + 1, len - 1);
311}
312
313
314template<typename T>
315bool
316VncServer::read(T* val)
317{
318 return read((uint8_t *)val, sizeof(T));
319}
320
321// write to socket
322bool
323VncServer::write(const uint8_t *buf, size_t len)
324{
325 if (dataFd < 0)
326 panic("Vnc client not properly attached.\n");
327
328 ssize_t ret = atomic_write(dataFd, buf, len);
329
330 if (ret != len) {
331 DPRINTF(VNC, "Write failed.\n");
332 detach();
333 return false;
334 }
335
336 return true;
337}
338
339template<typename T>
340bool
341VncServer::write(T* val)
342{
343 return write((uint8_t *)val, sizeof(T));
344}
345
346bool
347VncServer::write(const char* str)
348{
349 return write((uint8_t *)str, strlen(str));
350}
351
352// detach a vnc client
353void
354VncServer::detach()
355{
356 if (dataFd != -1) {
357 ::close(dataFd);
358 dataFd = -1;
359 }
360
361 if (!dataEvent || !dataEvent->queued())
362 return;
363
364 pollQueue.remove(dataEvent);
365 delete dataEvent;
366 dataEvent = NULL;
367 curState = WaitForProtocolVersion;
368
369 inform("VNC client detached\n");
370 DPRINTF(VNC, "detach vnc client %d\n", number);
371}
372
373void
374VncServer::sendError(const char* error_msg)
375{
376 uint32_t len = strlen(error_msg);
377 if (!write(&len))
378 return;
379 write(error_msg);
380}
381
382void
383VncServer::checkProtocolVersion()
384{
385 assert(curState == WaitForProtocolVersion);
386
387 size_t len M5_VAR_USED;
388 char version_string[13];
389
390 // Null terminate the message so it's easier to work with
391 version_string[12] = 0;
392
393 if (!read((uint8_t *)version_string, sizeof(version_string) - 1)) {
394 warn("Failed to read protocol version.");
395 return;
396 }
397
398 uint32_t major, minor;
399
400 // Figure out the major/minor numbers
401 if (sscanf(version_string, "RFB %03d.%03d\n", &major, &minor) != 2) {
402 warn(" Malformed protocol version %s\n", version_string);
403 sendError("Malformed protocol version\n");
404 detach();
405 return;
406 }
407
408 DPRINTF(VNC, "Client request protocol version %d.%d\n", major, minor);
409
410 // If it's not 3.X we don't support it
411 if (major != 3 || minor < 2) {
412 warn("Unsupported VNC client version... disconnecting\n");
413 uint8_t err = AuthInvalid;
414 write(&err);
415 detach();
416 return;
417 }
418 // Auth is different based on version number
419 if (minor < 7) {
420 uint32_t sec_type = htobe((uint32_t)AuthNone);
421 if (!write(&sec_type))
422 return;
423 } else {
424 uint8_t sec_cnt = 1;
425 uint8_t sec_type = htobe((uint8_t)AuthNone);
426 if (!write(&sec_cnt) || !write(&sec_type))
427 return;
428 }
429
430 // Wait for client to respond
431 curState = WaitForSecurityResponse;
432}
433
434void
435VncServer::checkSecurity()
436{
437 assert(curState == WaitForSecurityResponse);
438
439 uint8_t security_type;
440 if (!read(&security_type))
441 return;
442
443 if (security_type != AuthNone) {
444 warn("Unknown VNC security type\n");
445 sendError("Unknown security type\n");
446 }
447
448 DPRINTF(VNC, "Sending security auth OK\n");
449
450 uint32_t success = htobe(VncOK);
451 if (!write(&success))
452 return;
453 curState = WaitForClientInit;
454}
455
456void
457VncServer::sendServerInit()
458{
459 ServerInitMsg msg;
460
461 DPRINTF(VNC, "Sending server init message to client\n");
462
463 msg.fbWidth = htobe(videoWidth());
464 msg.fbHeight = htobe(videoHeight());
465
466 msg.px.bpp = htobe(pixelFormat.bpp);
467 msg.px.depth = htobe(pixelFormat.depth);
468 msg.px.bigendian = htobe(pixelFormat.bigendian);
469 msg.px.truecolor = htobe(pixelFormat.truecolor);
470 msg.px.redmax = htobe(pixelFormat.redmax);
471 msg.px.greenmax = htobe(pixelFormat.greenmax);
472 msg.px.bluemax = htobe(pixelFormat.bluemax);
473 msg.px.redshift = htobe(pixelFormat.redshift);
474 msg.px.greenshift = htobe(pixelFormat.greenshift);
475 msg.px.blueshift = htobe(pixelFormat.blueshift);
476 memset(msg.px.padding, 0, 3);
477 msg.namelen = 2;
478 msg.namelen = htobe(msg.namelen);
479 memcpy(msg.name, "M5", 2);
480
481 if (!write(&msg))
482 return;
483 curState = NormalPhase;
484}
485
486void
487VncServer::setPixelFormat()
488{
489 DPRINTF(VNC, "Received pixel format from client message\n");
490
491 PixelFormatMessage pfm;
492 if (!read1((uint8_t *)&pfm, sizeof(PixelFormatMessage)))
493 return;
494
495 DPRINTF(VNC, " -- bpp = %d; depth = %d; be = %d\n", pfm.px.bpp,
496 pfm.px.depth, pfm.px.bigendian);
497 DPRINTF(VNC, " -- true color = %d red,green,blue max = %d,%d,%d\n",
498 pfm.px.truecolor, betoh(pfm.px.redmax), betoh(pfm.px.greenmax),
499 betoh(pfm.px.bluemax));
500 DPRINTF(VNC, " -- red,green,blue shift = %d,%d,%d\n", pfm.px.redshift,
501 pfm.px.greenshift, pfm.px.blueshift);
502
503 if (betoh(pfm.px.bpp) != pixelFormat.bpp ||
504 betoh(pfm.px.depth) != pixelFormat.depth ||
505 betoh(pfm.px.bigendian) != pixelFormat.bigendian ||
506 betoh(pfm.px.truecolor) != pixelFormat.truecolor ||
507 betoh(pfm.px.redmax) != pixelFormat.redmax ||
508 betoh(pfm.px.greenmax) != pixelFormat.greenmax ||
509 betoh(pfm.px.bluemax) != pixelFormat.bluemax ||
510 betoh(pfm.px.redshift) != pixelFormat.redshift ||
511 betoh(pfm.px.greenshift) != pixelFormat.greenshift ||
512 betoh(pfm.px.blueshift) != pixelFormat.blueshift) {
513 warn("VNC client doesn't support true color raw encoding\n");
514 detach();
515 }
516}
517
518void
519VncServer::setEncodings()
520{
521 DPRINTF(VNC, "Received supported encodings from client\n");
522
523 PixelEncodingsMessage pem;
524 if (!read1((uint8_t *)&pem, sizeof(PixelEncodingsMessage)))
525 return;
526
527 pem.num_encodings = betoh(pem.num_encodings);
528
529 DPRINTF(VNC, " -- %d encoding present\n", pem.num_encodings);
530 supportsRawEnc = supportsResizeEnc = false;
531
532 for (int x = 0; x < pem.num_encodings; x++) {
533 int32_t encoding;
534 if (!read(&encoding))
535 return;
536 DPRINTF(VNC, " -- supports %d\n", betoh(encoding));
537
538 switch (betoh(encoding)) {
539 case EncodingRaw:
540 supportsRawEnc = true;
541 break;
542 case EncodingDesktopSize:
543 supportsResizeEnc = true;
544 break;
545 }
546 }
547
548 if (!supportsRawEnc) {
549 warn("VNC clients must always support raw encoding\n");
550 detach();
551 }
552}
553
554void
555VncServer::requestFbUpdate()
556{
557 DPRINTF(VNC, "Received frame buffer update request from client\n");
558
559 FrameBufferUpdateReq fbr;
560 if (!read1((uint8_t *)&fbr, sizeof(FrameBufferUpdateReq)))
561 return;
562
563 fbr.x = betoh(fbr.x);
564 fbr.y = betoh(fbr.y);
565 fbr.width = betoh(fbr.width);
566 fbr.height = betoh(fbr.height);
567
568 DPRINTF(VNC, " -- x = %d y = %d w = %d h = %d\n", fbr.x, fbr.y, fbr.width,
569 fbr.height);
570
571 sendFrameBufferUpdate();
572}
573
574void
575VncServer::recvKeyboardInput()
576{
577 DPRINTF(VNC, "Received keyboard input from client\n");
578 KeyEventMessage kem;
579 if (!read1((uint8_t *)&kem, sizeof(KeyEventMessage)))
580 return;
581
582 kem.key = betoh(kem.key);
583 DPRINTF(VNC, " -- received key code %d (%s)\n", kem.key, kem.down_flag ?
584 "down" : "up");
585
586 if (keyboard)
587 keyboard->keyPress(kem.key, kem.down_flag);
588}
589
590void
591VncServer::recvPointerInput()
592{
593 DPRINTF(VNC, "Received pointer input from client\n");
594 PointerEventMessage pem;
595
596 if (!read1((uint8_t *)&pem, sizeof(PointerEventMessage)))
597 return;
598
599 pem.x = betoh(pem.x);
600 pem.y = betoh(pem.y);
601 DPRINTF(VNC, " -- pointer at x = %d y = %d buttons = %#x\n", pem.x, pem.y,
602 pem.button_mask);
603
604 if (mouse)
605 mouse->mouseAt(pem.x, pem.y, pem.button_mask);
606}
607
608void
609VncServer::recvCutText()
610{
611 DPRINTF(VNC, "Received client copy buffer message\n");
612
613 ClientCutTextMessage cct;
614 if (!read1((uint8_t *)&cct, sizeof(ClientCutTextMessage)))
615 return;
616
617 char str[1025];
618 size_t data_len = betoh(cct.length);
619 DPRINTF(VNC, "String length %d\n", data_len);
620 while (data_len > 0) {
621 size_t bytes_to_read = data_len > 1024 ? 1024 : data_len;
622 if (!read((uint8_t *)&str, bytes_to_read))
623 return;
624 str[bytes_to_read] = 0;
625 data_len -= bytes_to_read;
626 DPRINTF(VNC, "Buffer: %s\n", str);
627 }
628
629}
630
631
632void
633VncServer::sendFrameBufferUpdate()
634{
635
636 if (dataFd <= 0 || curState != NormalPhase || !sendUpdate) {
637 DPRINTF(VNC, "NOT sending framebuffer update\n");
638 return;
639 }
640
641 // The client will request data constantly, unless we throttle it
642 sendUpdate = false;
643
644 DPRINTF(VNC, "Sending framebuffer update\n");
645
646 FrameBufferUpdate fbu;
647 FrameBufferRect fbr;
648
649 fbu.type = ServerFrameBufferUpdate;
650 fbu.num_rects = 1;
651 fbr.x = 0;
652 fbr.y = 0;
653 fbr.width = videoWidth();
654 fbr.height = videoHeight();
655 fbr.encoding = EncodingRaw;
656
657 // fix up endian
658 fbu.num_rects = htobe(fbu.num_rects);
659 fbr.x = htobe(fbr.x);
660 fbr.y = htobe(fbr.y);
661 fbr.width = htobe(fbr.width);
662 fbr.height = htobe(fbr.height);
663 fbr.encoding = htobe(fbr.encoding);
664
665 // send headers to client
666 if (!write(&fbu) || !write(&fbr))
667 return;
668
669 assert(fb);
670
671 std::vector<uint8_t> line_buffer(pixelConverter.length * fb->width());
672 for (int y = 0; y < fb->height(); ++y) {
673 // Convert and send a line at a time
674 uint8_t *raw_pixel(line_buffer.data());
675 for (unsigned x = 0; x < fb->width(); ++x) {
676 pixelConverter.fromPixel(raw_pixel, fb->pixel(x, y));
677 raw_pixel += pixelConverter.length;
678 }
679
680 if (!write(line_buffer.data(), line_buffer.size()))
681 return;
682 }
683}
684
685void
686VncServer::sendFrameBufferResized()
687{
688 assert(fb && dataFd > 0 && curState == NormalPhase);
689 DPRINTF(VNC, "Sending framebuffer resize\n");
690
691 FrameBufferUpdate fbu;
692 FrameBufferRect fbr;
693
694 fbu.type = ServerFrameBufferUpdate;
695 fbu.num_rects = 1;
696 fbr.x = 0;
697 fbr.y = 0;
698 fbr.width = videoWidth();
699 fbr.height = videoHeight();
700 fbr.encoding = EncodingDesktopSize;
701
702 // fix up endian
703 fbu.num_rects = htobe(fbu.num_rects);
704 fbr.x = htobe(fbr.x);
705 fbr.y = htobe(fbr.y);
706 fbr.width = htobe(fbr.width);
707 fbr.height = htobe(fbr.height);
708 fbr.encoding = htobe(fbr.encoding);
709
710 // send headers to client
711 if (!write(&fbu))
712 return;
713 write(&fbr);
714
715 // No actual data is sent in this message
716}
717
718void
719VncServer::setDirty()
720{
721 VncInput::setDirty();
722
723 sendUpdate = true;
724 sendFrameBufferUpdate();
725}
726
727void
728VncServer::frameBufferResized()
729{
730 if (dataFd > 0 && curState == NormalPhase) {
731 if (supportsResizeEnc)
732 sendFrameBufferResized();
733 else
734 // The frame buffer changed size and we can't update the client
735 detach();
736 }
737}
738
739// create the VNC server object
740VncServer *
741VncServerParams::create()
742{
743 return new VncServer(this);
744}
745
179
180 listenEvent = new ListenEvent(this, listener.getfd(), POLLIN);
181 pollQueue.schedule(listenEvent);
182}
183
184// attach a vnc client
185void
186VncServer::accept()
187{
188 // As a consequence of being called from the PollQueue, we might
189 // have been called from a different thread. Migrate to "our"
190 // thread.
191 EventQueue::ScopedMigration migrate(eventQueue());
192
193 if (!listener.islistening())
194 panic("%s: cannot accept a connection if not listening!", name());
195
196 int fd = listener.accept(true);
197 if (fd < 0) {
198 warn("%s: failed to accept VNC connection!", name());
199 return;
200 }
201
202 if (dataFd != -1) {
203 char message[] = "vnc server already attached!\n";
204 atomic_write(fd, message, sizeof(message));
205 ::close(fd);
206 return;
207 }
208
209 dataFd = fd;
210
211 // Send our version number to the client
212 write((uint8_t *)vncVersion(), strlen(vncVersion()));
213
214 // read the client response
215 dataEvent = new DataEvent(this, dataFd, POLLIN);
216 pollQueue.schedule(dataEvent);
217
218 inform("VNC client attached\n");
219}
220
221// data called by data event
222void
223VncServer::data()
224{
225 // We have new data, see if we can handle it
226 DPRINTF(VNC, "Vnc client message recieved\n");
227
228 switch (curState) {
229 case WaitForProtocolVersion:
230 checkProtocolVersion();
231 break;
232 case WaitForSecurityResponse:
233 checkSecurity();
234 break;
235 case WaitForClientInit:
236 // Don't care about shared, just need to read it out of the socket
237 uint8_t shared;
238 if (!read(&shared))
239 return;
240
241 // Send our idea of the frame buffer
242 sendServerInit();
243
244 break;
245 case NormalPhase:
246 uint8_t message_type;
247 if (!read(&message_type))
248 return;
249
250 switch (message_type) {
251 case ClientSetPixelFormat:
252 setPixelFormat();
253 break;
254 case ClientSetEncodings:
255 setEncodings();
256 break;
257 case ClientFrameBufferUpdate:
258 requestFbUpdate();
259 break;
260 case ClientKeyEvent:
261 recvKeyboardInput();
262 break;
263 case ClientPointerEvent:
264 recvPointerInput();
265 break;
266 case ClientCutText:
267 recvCutText();
268 break;
269 default:
270 warn("Unimplemented message type recv from client: %d\n",
271 message_type);
272 detach();
273 break;
274 }
275 break;
276 default:
277 panic("Unknown vnc server state\n");
278 }
279}
280
281
282// read from socket
283bool
284VncServer::read(uint8_t *buf, size_t len)
285{
286 if (dataFd < 0)
287 panic("vnc not properly attached.\n");
288
289 size_t ret;
290 do {
291 ret = ::read(dataFd, buf, len);
292 } while (ret == -1 && errno == EINTR);
293
294
295 if (ret != len) {
296 DPRINTF(VNC, "Read failed %d.\n", ret);
297 detach();
298 return false;
299 }
300
301 return true;
302}
303
304bool
305VncServer::read1(uint8_t *buf, size_t len)
306{
307 return read(buf + 1, len - 1);
308}
309
310
311template<typename T>
312bool
313VncServer::read(T* val)
314{
315 return read((uint8_t *)val, sizeof(T));
316}
317
318// write to socket
319bool
320VncServer::write(const uint8_t *buf, size_t len)
321{
322 if (dataFd < 0)
323 panic("Vnc client not properly attached.\n");
324
325 ssize_t ret = atomic_write(dataFd, buf, len);
326
327 if (ret != len) {
328 DPRINTF(VNC, "Write failed.\n");
329 detach();
330 return false;
331 }
332
333 return true;
334}
335
336template<typename T>
337bool
338VncServer::write(T* val)
339{
340 return write((uint8_t *)val, sizeof(T));
341}
342
343bool
344VncServer::write(const char* str)
345{
346 return write((uint8_t *)str, strlen(str));
347}
348
349// detach a vnc client
350void
351VncServer::detach()
352{
353 if (dataFd != -1) {
354 ::close(dataFd);
355 dataFd = -1;
356 }
357
358 if (!dataEvent || !dataEvent->queued())
359 return;
360
361 pollQueue.remove(dataEvent);
362 delete dataEvent;
363 dataEvent = NULL;
364 curState = WaitForProtocolVersion;
365
366 inform("VNC client detached\n");
367 DPRINTF(VNC, "detach vnc client %d\n", number);
368}
369
370void
371VncServer::sendError(const char* error_msg)
372{
373 uint32_t len = strlen(error_msg);
374 if (!write(&len))
375 return;
376 write(error_msg);
377}
378
379void
380VncServer::checkProtocolVersion()
381{
382 assert(curState == WaitForProtocolVersion);
383
384 size_t len M5_VAR_USED;
385 char version_string[13];
386
387 // Null terminate the message so it's easier to work with
388 version_string[12] = 0;
389
390 if (!read((uint8_t *)version_string, sizeof(version_string) - 1)) {
391 warn("Failed to read protocol version.");
392 return;
393 }
394
395 uint32_t major, minor;
396
397 // Figure out the major/minor numbers
398 if (sscanf(version_string, "RFB %03d.%03d\n", &major, &minor) != 2) {
399 warn(" Malformed protocol version %s\n", version_string);
400 sendError("Malformed protocol version\n");
401 detach();
402 return;
403 }
404
405 DPRINTF(VNC, "Client request protocol version %d.%d\n", major, minor);
406
407 // If it's not 3.X we don't support it
408 if (major != 3 || minor < 2) {
409 warn("Unsupported VNC client version... disconnecting\n");
410 uint8_t err = AuthInvalid;
411 write(&err);
412 detach();
413 return;
414 }
415 // Auth is different based on version number
416 if (minor < 7) {
417 uint32_t sec_type = htobe((uint32_t)AuthNone);
418 if (!write(&sec_type))
419 return;
420 } else {
421 uint8_t sec_cnt = 1;
422 uint8_t sec_type = htobe((uint8_t)AuthNone);
423 if (!write(&sec_cnt) || !write(&sec_type))
424 return;
425 }
426
427 // Wait for client to respond
428 curState = WaitForSecurityResponse;
429}
430
431void
432VncServer::checkSecurity()
433{
434 assert(curState == WaitForSecurityResponse);
435
436 uint8_t security_type;
437 if (!read(&security_type))
438 return;
439
440 if (security_type != AuthNone) {
441 warn("Unknown VNC security type\n");
442 sendError("Unknown security type\n");
443 }
444
445 DPRINTF(VNC, "Sending security auth OK\n");
446
447 uint32_t success = htobe(VncOK);
448 if (!write(&success))
449 return;
450 curState = WaitForClientInit;
451}
452
453void
454VncServer::sendServerInit()
455{
456 ServerInitMsg msg;
457
458 DPRINTF(VNC, "Sending server init message to client\n");
459
460 msg.fbWidth = htobe(videoWidth());
461 msg.fbHeight = htobe(videoHeight());
462
463 msg.px.bpp = htobe(pixelFormat.bpp);
464 msg.px.depth = htobe(pixelFormat.depth);
465 msg.px.bigendian = htobe(pixelFormat.bigendian);
466 msg.px.truecolor = htobe(pixelFormat.truecolor);
467 msg.px.redmax = htobe(pixelFormat.redmax);
468 msg.px.greenmax = htobe(pixelFormat.greenmax);
469 msg.px.bluemax = htobe(pixelFormat.bluemax);
470 msg.px.redshift = htobe(pixelFormat.redshift);
471 msg.px.greenshift = htobe(pixelFormat.greenshift);
472 msg.px.blueshift = htobe(pixelFormat.blueshift);
473 memset(msg.px.padding, 0, 3);
474 msg.namelen = 2;
475 msg.namelen = htobe(msg.namelen);
476 memcpy(msg.name, "M5", 2);
477
478 if (!write(&msg))
479 return;
480 curState = NormalPhase;
481}
482
483void
484VncServer::setPixelFormat()
485{
486 DPRINTF(VNC, "Received pixel format from client message\n");
487
488 PixelFormatMessage pfm;
489 if (!read1((uint8_t *)&pfm, sizeof(PixelFormatMessage)))
490 return;
491
492 DPRINTF(VNC, " -- bpp = %d; depth = %d; be = %d\n", pfm.px.bpp,
493 pfm.px.depth, pfm.px.bigendian);
494 DPRINTF(VNC, " -- true color = %d red,green,blue max = %d,%d,%d\n",
495 pfm.px.truecolor, betoh(pfm.px.redmax), betoh(pfm.px.greenmax),
496 betoh(pfm.px.bluemax));
497 DPRINTF(VNC, " -- red,green,blue shift = %d,%d,%d\n", pfm.px.redshift,
498 pfm.px.greenshift, pfm.px.blueshift);
499
500 if (betoh(pfm.px.bpp) != pixelFormat.bpp ||
501 betoh(pfm.px.depth) != pixelFormat.depth ||
502 betoh(pfm.px.bigendian) != pixelFormat.bigendian ||
503 betoh(pfm.px.truecolor) != pixelFormat.truecolor ||
504 betoh(pfm.px.redmax) != pixelFormat.redmax ||
505 betoh(pfm.px.greenmax) != pixelFormat.greenmax ||
506 betoh(pfm.px.bluemax) != pixelFormat.bluemax ||
507 betoh(pfm.px.redshift) != pixelFormat.redshift ||
508 betoh(pfm.px.greenshift) != pixelFormat.greenshift ||
509 betoh(pfm.px.blueshift) != pixelFormat.blueshift) {
510 warn("VNC client doesn't support true color raw encoding\n");
511 detach();
512 }
513}
514
515void
516VncServer::setEncodings()
517{
518 DPRINTF(VNC, "Received supported encodings from client\n");
519
520 PixelEncodingsMessage pem;
521 if (!read1((uint8_t *)&pem, sizeof(PixelEncodingsMessage)))
522 return;
523
524 pem.num_encodings = betoh(pem.num_encodings);
525
526 DPRINTF(VNC, " -- %d encoding present\n", pem.num_encodings);
527 supportsRawEnc = supportsResizeEnc = false;
528
529 for (int x = 0; x < pem.num_encodings; x++) {
530 int32_t encoding;
531 if (!read(&encoding))
532 return;
533 DPRINTF(VNC, " -- supports %d\n", betoh(encoding));
534
535 switch (betoh(encoding)) {
536 case EncodingRaw:
537 supportsRawEnc = true;
538 break;
539 case EncodingDesktopSize:
540 supportsResizeEnc = true;
541 break;
542 }
543 }
544
545 if (!supportsRawEnc) {
546 warn("VNC clients must always support raw encoding\n");
547 detach();
548 }
549}
550
551void
552VncServer::requestFbUpdate()
553{
554 DPRINTF(VNC, "Received frame buffer update request from client\n");
555
556 FrameBufferUpdateReq fbr;
557 if (!read1((uint8_t *)&fbr, sizeof(FrameBufferUpdateReq)))
558 return;
559
560 fbr.x = betoh(fbr.x);
561 fbr.y = betoh(fbr.y);
562 fbr.width = betoh(fbr.width);
563 fbr.height = betoh(fbr.height);
564
565 DPRINTF(VNC, " -- x = %d y = %d w = %d h = %d\n", fbr.x, fbr.y, fbr.width,
566 fbr.height);
567
568 sendFrameBufferUpdate();
569}
570
571void
572VncServer::recvKeyboardInput()
573{
574 DPRINTF(VNC, "Received keyboard input from client\n");
575 KeyEventMessage kem;
576 if (!read1((uint8_t *)&kem, sizeof(KeyEventMessage)))
577 return;
578
579 kem.key = betoh(kem.key);
580 DPRINTF(VNC, " -- received key code %d (%s)\n", kem.key, kem.down_flag ?
581 "down" : "up");
582
583 if (keyboard)
584 keyboard->keyPress(kem.key, kem.down_flag);
585}
586
587void
588VncServer::recvPointerInput()
589{
590 DPRINTF(VNC, "Received pointer input from client\n");
591 PointerEventMessage pem;
592
593 if (!read1((uint8_t *)&pem, sizeof(PointerEventMessage)))
594 return;
595
596 pem.x = betoh(pem.x);
597 pem.y = betoh(pem.y);
598 DPRINTF(VNC, " -- pointer at x = %d y = %d buttons = %#x\n", pem.x, pem.y,
599 pem.button_mask);
600
601 if (mouse)
602 mouse->mouseAt(pem.x, pem.y, pem.button_mask);
603}
604
605void
606VncServer::recvCutText()
607{
608 DPRINTF(VNC, "Received client copy buffer message\n");
609
610 ClientCutTextMessage cct;
611 if (!read1((uint8_t *)&cct, sizeof(ClientCutTextMessage)))
612 return;
613
614 char str[1025];
615 size_t data_len = betoh(cct.length);
616 DPRINTF(VNC, "String length %d\n", data_len);
617 while (data_len > 0) {
618 size_t bytes_to_read = data_len > 1024 ? 1024 : data_len;
619 if (!read((uint8_t *)&str, bytes_to_read))
620 return;
621 str[bytes_to_read] = 0;
622 data_len -= bytes_to_read;
623 DPRINTF(VNC, "Buffer: %s\n", str);
624 }
625
626}
627
628
629void
630VncServer::sendFrameBufferUpdate()
631{
632
633 if (dataFd <= 0 || curState != NormalPhase || !sendUpdate) {
634 DPRINTF(VNC, "NOT sending framebuffer update\n");
635 return;
636 }
637
638 // The client will request data constantly, unless we throttle it
639 sendUpdate = false;
640
641 DPRINTF(VNC, "Sending framebuffer update\n");
642
643 FrameBufferUpdate fbu;
644 FrameBufferRect fbr;
645
646 fbu.type = ServerFrameBufferUpdate;
647 fbu.num_rects = 1;
648 fbr.x = 0;
649 fbr.y = 0;
650 fbr.width = videoWidth();
651 fbr.height = videoHeight();
652 fbr.encoding = EncodingRaw;
653
654 // fix up endian
655 fbu.num_rects = htobe(fbu.num_rects);
656 fbr.x = htobe(fbr.x);
657 fbr.y = htobe(fbr.y);
658 fbr.width = htobe(fbr.width);
659 fbr.height = htobe(fbr.height);
660 fbr.encoding = htobe(fbr.encoding);
661
662 // send headers to client
663 if (!write(&fbu) || !write(&fbr))
664 return;
665
666 assert(fb);
667
668 std::vector<uint8_t> line_buffer(pixelConverter.length * fb->width());
669 for (int y = 0; y < fb->height(); ++y) {
670 // Convert and send a line at a time
671 uint8_t *raw_pixel(line_buffer.data());
672 for (unsigned x = 0; x < fb->width(); ++x) {
673 pixelConverter.fromPixel(raw_pixel, fb->pixel(x, y));
674 raw_pixel += pixelConverter.length;
675 }
676
677 if (!write(line_buffer.data(), line_buffer.size()))
678 return;
679 }
680}
681
682void
683VncServer::sendFrameBufferResized()
684{
685 assert(fb && dataFd > 0 && curState == NormalPhase);
686 DPRINTF(VNC, "Sending framebuffer resize\n");
687
688 FrameBufferUpdate fbu;
689 FrameBufferRect fbr;
690
691 fbu.type = ServerFrameBufferUpdate;
692 fbu.num_rects = 1;
693 fbr.x = 0;
694 fbr.y = 0;
695 fbr.width = videoWidth();
696 fbr.height = videoHeight();
697 fbr.encoding = EncodingDesktopSize;
698
699 // fix up endian
700 fbu.num_rects = htobe(fbu.num_rects);
701 fbr.x = htobe(fbr.x);
702 fbr.y = htobe(fbr.y);
703 fbr.width = htobe(fbr.width);
704 fbr.height = htobe(fbr.height);
705 fbr.encoding = htobe(fbr.encoding);
706
707 // send headers to client
708 if (!write(&fbu))
709 return;
710 write(&fbr);
711
712 // No actual data is sent in this message
713}
714
715void
716VncServer::setDirty()
717{
718 VncInput::setDirty();
719
720 sendUpdate = true;
721 sendFrameBufferUpdate();
722}
723
724void
725VncServer::frameBufferResized()
726{
727 if (dataFd > 0 && curState == NormalPhase) {
728 if (supportsResizeEnc)
729 sendFrameBufferResized();
730 else
731 // The frame buffer changed size and we can't update the client
732 detach();
733 }
734}
735
736// create the VNC server object
737VncServer *
738VncServerParams::create()
739{
740 return new VncServer(this);
741}
742