gem5 v24.0.0.0
Loading...
Searching...
No Matches
vncserver.cc
Go to the documentation of this file.
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
42#include <sys/ioctl.h>
43#include <sys/stat.h>
44
45#if defined(__FreeBSD__)
46#include <termios.h>
47
48#else
49#include <sys/termios.h>
50
51#endif
52#include "base/vnc/vncserver.hh"
53
54#include <fcntl.h>
55#include <poll.h>
56#include <sys/types.h>
57#include <unistd.h>
58
59#include <cerrno>
60#include <cstddef>
61#include <cstdio>
62
63#include "base/atomicio.hh"
64#include "base/logging.hh"
65#include "base/output.hh"
66#include "base/socket.hh"
67#include "base/trace.hh"
68#include "debug/VNC.hh"
69#include "sim/byteswap.hh"
70
71namespace gem5
72{
73
74const PixelConverter VncServer::pixelConverter(
75 4, // 4 bytes / pixel
76 16, 8, 0, // R in [23, 16], G in [15, 8], B in [7, 0]
77 8, 8, 8, // 8 bits / channel
78 ByteOrder::little);
79
88 : PollEvent(fd, e), vncserver(vs)
89{
90}
91
92void
94{
95 vncserver->accept();
96}
97
102 : PollEvent(fd, e), vncserver(vs)
103{
104}
105
106void
108{
109 if (revent & POLLIN)
110 vncserver->data();
111 else if (revent & POLLNVAL)
112 vncserver->detach();
113}
114
119 : VncInput(p), listenEvent(NULL), dataEvent(NULL), number(p.number),
120 dataFd(-1), listener(p.port.build(p.name)),
121 sendUpdate(false), supportsRawEnc(false), supportsResizeEnc(false)
122{
123 if (p.port)
124 listen();
125
127
128 // We currently only support one pixel format. Extract the pixel
129 // representation from our PixelConverter instance and keep it
130 // around for telling the client and making sure it cooperates
141
142 DPRINTF(VNC, "Vnc server created at port %d\n", p.port);
143}
144
146{
147 if (dataFd != -1)
148 ::close(dataFd);
149
150 if (listenEvent)
151 delete listenEvent;
152
153 if (dataEvent)
154 delete dataEvent;
155}
156
157
158//socket creation and vnc client attach
159void
161{
163 warn_once("Sockets disabled, not accepting vnc client connections");
164 return;
165 }
166
167 listener->listen();
168
169 listenEvent = new ListenEvent(this, listener->getfd(), POLLIN);
171}
172
173// attach a vnc client
174void
176{
177 // As a consequence of being called from the PollQueue, we might
178 // have been called from a different thread. Migrate to "our"
179 // thread.
181
182 if (!listener->islistening())
183 panic("%s: cannot accept a connection if not listening!", name());
184
185 int fd = listener->accept();
186 if (fd < 0) {
187 warn("%s: failed to accept VNC connection!", name());
188 return;
189 }
190
191 if (dataFd != -1) {
192 char message[] = "vnc server already attached!\n";
193 atomic_write(fd, message, sizeof(message));
194 ::close(fd);
195 return;
196 }
197
198 dataFd = fd;
199
200 // Send our version number to the client
201 write((uint8_t *)vncVersion(), strlen(vncVersion()));
202
203 // read the client response
204 dataEvent = new DataEvent(this, dataFd, POLLIN);
206
207 inform("VNC client attached\n");
208}
209
210// data called by data event
211void
213{
214 // We have new data, see if we can handle it
215 DPRINTF(VNC, "Vnc client message recieved\n");
216
217 switch (curState) {
220 break;
223 break;
225 // Don't care about shared, just need to read it out of the socket
226 uint8_t shared;
227 if (!read(&shared))
228 return;
229
230 // Send our idea of the frame buffer
232
233 break;
234 case NormalPhase:
235 uint8_t message_type;
236 if (!read(&message_type))
237 return;
238
239 switch (message_type) {
242 break;
244 setEncodings();
245 break;
248 break;
249 case ClientKeyEvent:
251 break;
254 break;
255 case ClientCutText:
256 recvCutText();
257 break;
258 default:
259 warn("Unimplemented message type recv from client: %d\n",
260 message_type);
261 detach();
262 break;
263 }
264 break;
265 default:
266 panic("Unknown vnc server state\n");
267 }
268}
269
270
271// read from socket
272bool
273VncServer::read(uint8_t *buf, size_t len)
274{
275 if (dataFd < 0)
276 panic("vnc not properly attached.\n");
277
278 size_t ret;
279 do {
280 ret = ::read(dataFd, buf, len);
281 } while (ret == -1 && errno == EINTR);
282
283
284 if (ret != len) {
285 DPRINTF(VNC, "Read failed %d.\n", ret);
286 detach();
287 return false;
288 }
289
290 return true;
291}
292
293bool
294VncServer::read1(uint8_t *buf, size_t len)
295{
296 return read(buf + 1, len - 1);
297}
298
299
300template<typename T>
301bool
303{
304 return read((uint8_t *)val, sizeof(T));
305}
306
307// write to socket
308bool
309VncServer::write(const uint8_t *buf, size_t len)
310{
311 if (dataFd < 0)
312 panic("Vnc client not properly attached.\n");
313
314 ssize_t ret = atomic_write(dataFd, buf, len);
315
316 if (ret != len) {
317 DPRINTF(VNC, "Write failed.\n");
318 detach();
319 return false;
320 }
321
322 return true;
323}
324
325template<typename T>
326bool
328{
329 return write((uint8_t *)val, sizeof(T));
330}
331
332bool
333VncServer::write(const char* str)
334{
335 return write((uint8_t *)str, strlen(str));
336}
337
338// detach a vnc client
339void
341{
342 if (dataFd != -1) {
343 ::close(dataFd);
344 dataFd = -1;
345 }
346
347 if (!dataEvent || !dataEvent->queued())
348 return;
349
351 delete dataEvent;
352 dataEvent = NULL;
354
355 inform("VNC client detached\n");
356 DPRINTF(VNC, "detach vnc client %d\n", number);
357}
358
359void
360VncServer::sendError(const char* error_msg)
361{
362 uint32_t len = strlen(error_msg);
363 if (!write(&len))
364 return;
365 write(error_msg);
366}
367
368void
370{
372
373 [[maybe_unused]] size_t len;
374 char version_string[13];
375
376 // Null terminate the message so it's easier to work with
377 version_string[12] = 0;
378
379 if (!read((uint8_t *)version_string, sizeof(version_string) - 1)) {
380 warn("Failed to read protocol version.");
381 return;
382 }
383
384 uint32_t major_version, minor_version;
385
386 // Figure out the major/minor numbers
387 if (sscanf(version_string, "RFB %03d.%03d\n", &major_version,
388 &minor_version) != 2) {
389 warn(" Malformed protocol version %s\n", version_string);
390 sendError("Malformed protocol version\n");
391 detach();
392 return;
393 }
394
395 DPRINTF(VNC, "Client request protocol version %d.%d\n", major_version,
396 minor_version);
397
398 // If it's not 3.X we don't support it
399 if (major_version != 3 || minor_version < 2) {
400 warn("Unsupported VNC client version... disconnecting\n");
401 uint8_t err = AuthInvalid;
402 write(&err);
403 detach();
404 return;
405 }
406 // Auth is different based on version number
407 if (minor_version < 7) {
408 uint32_t sec_type = htobe((uint32_t)AuthNone);
409 if (!write(&sec_type))
410 return;
411 } else {
412 uint8_t sec_cnt = 1;
413 uint8_t sec_type = htobe((uint8_t)AuthNone);
414 if (!write(&sec_cnt) || !write(&sec_type))
415 return;
416 }
417
418 // Wait for client to respond
420}
421
422void
424{
426
427 uint8_t security_type;
428 if (!read(&security_type))
429 return;
430
431 if (security_type != AuthNone) {
432 warn("Unknown VNC security type\n");
433 sendError("Unknown security type\n");
434 }
435
436 DPRINTF(VNC, "Sending security auth OK\n");
437
438 uint32_t success = htobe(VncOK);
439 if (!write(&success))
440 return;
442}
443
444void
446{
447 ServerInitMsg msg;
448
449 DPRINTF(VNC, "Sending server init message to client\n");
450
451 msg.fbWidth = htobe(videoWidth());
452 msg.fbHeight = htobe(videoHeight());
453
454 msg.px.bpp = htobe(pixelFormat.bpp);
464 memset(msg.px.padding, 0, 3);
465 msg.namelen = 2;
466 msg.namelen = htobe(msg.namelen);
467 std::memcpy(msg.name, "M5", 2);
468
469 if (!write(&msg))
470 return;
472}
473
474void
476{
477 DPRINTF(VNC, "Received pixel format from client message\n");
478
480 if (!read1((uint8_t *)&pfm, sizeof(PixelFormatMessage)))
481 return;
482
483 DPRINTF(VNC, " -- bpp = %d; depth = %d; be = %d\n", pfm.px.bpp,
484 pfm.px.depth, pfm.px.bigendian);
485 DPRINTF(VNC, " -- true color = %d red,green,blue max = %d,%d,%d\n",
486 pfm.px.truecolor, betoh(pfm.px.redmax), betoh(pfm.px.greenmax),
487 betoh(pfm.px.bluemax));
488 DPRINTF(VNC, " -- red,green,blue shift = %d,%d,%d\n", pfm.px.redshift,
489 pfm.px.greenshift, pfm.px.blueshift);
490
491 if (betoh(pfm.px.bpp) != pixelFormat.bpp ||
492 betoh(pfm.px.depth) != pixelFormat.depth ||
495 betoh(pfm.px.redmax) != pixelFormat.redmax ||
501 warn("VNC client doesn't support true color raw encoding\n");
502 detach();
503 }
504}
505
506void
508{
509 DPRINTF(VNC, "Received supported encodings from client\n");
510
512 if (!read1((uint8_t *)&pem, sizeof(PixelEncodingsMessage)))
513 return;
514
516
517 DPRINTF(VNC, " -- %d encoding present\n", pem.num_encodings);
519
520 for (int x = 0; x < pem.num_encodings; x++) {
521 int32_t encoding;
522 if (!read(&encoding))
523 return;
524 DPRINTF(VNC, " -- supports %d\n", betoh(encoding));
525
526 switch (betoh(encoding)) {
527 case EncodingRaw:
528 supportsRawEnc = true;
529 break;
531 supportsResizeEnc = true;
532 break;
533 }
534 }
535
536 if (!supportsRawEnc) {
537 warn("VNC clients must always support raw encoding\n");
538 detach();
539 }
540}
541
542void
544{
545 DPRINTF(VNC, "Received frame buffer update request from client\n");
546
548 if (!read1((uint8_t *)&fbr, sizeof(FrameBufferUpdateReq)))
549 return;
550
551 fbr.x = betoh(fbr.x);
552 fbr.y = betoh(fbr.y);
553 fbr.width = betoh(fbr.width);
554 fbr.height = betoh(fbr.height);
555
556 DPRINTF(VNC, " -- x = %d y = %d w = %d h = %d\n", fbr.x, fbr.y, fbr.width,
557 fbr.height);
558
560}
561
562void
564{
565 DPRINTF(VNC, "Received keyboard input from client\n");
566 KeyEventMessage kem;
567 if (!read1((uint8_t *)&kem, sizeof(KeyEventMessage)))
568 return;
569
570 kem.key = betoh(kem.key);
571 DPRINTF(VNC, " -- received key code %d (%s)\n", kem.key, kem.down_flag ?
572 "down" : "up");
573
574 if (keyboard)
575 keyboard->keyPress(kem.key, kem.down_flag);
576}
577
578void
580{
581 DPRINTF(VNC, "Received pointer input from client\n");
583
584 if (!read1((uint8_t *)&pem, sizeof(PointerEventMessage)))
585 return;
586
587 pem.x = betoh(pem.x);
588 pem.y = betoh(pem.y);
589 DPRINTF(VNC, " -- pointer at x = %d y = %d buttons = %#x\n", pem.x, pem.y,
590 pem.button_mask);
591
592 if (mouse)
593 mouse->mouseAt(pem.x, pem.y, pem.button_mask);
594}
595
596void
598{
599 DPRINTF(VNC, "Received client copy buffer message\n");
600
602 if (!read1((uint8_t *)&cct, sizeof(ClientCutTextMessage)))
603 return;
604
605 char str[1025];
606 size_t data_len = betoh(cct.length);
607 DPRINTF(VNC, "String length %d\n", data_len);
608 while (data_len > 0) {
609 size_t bytes_to_read = data_len > 1024 ? 1024 : data_len;
610 if (!read((uint8_t *)&str, bytes_to_read))
611 return;
612 str[bytes_to_read] = 0;
613 data_len -= bytes_to_read;
614 DPRINTF(VNC, "Buffer: %s\n", str);
615 }
616
617}
618
619
620void
622{
623
624 if (dataFd <= 0 || curState != NormalPhase || !sendUpdate) {
625 DPRINTF(VNC, "NOT sending framebuffer update\n");
626 return;
627 }
628
629 // The client will request data constantly, unless we throttle it
630 sendUpdate = false;
631
632 DPRINTF(VNC, "Sending framebuffer update\n");
633
635 FrameBufferRect fbr;
636
638 fbu.num_rects = 1;
639 fbr.x = 0;
640 fbr.y = 0;
641 fbr.width = videoWidth();
642 fbr.height = videoHeight();
643 fbr.encoding = EncodingRaw;
644
645 // fix up endian
646 fbu.num_rects = htobe(fbu.num_rects);
647 fbr.x = htobe(fbr.x);
648 fbr.y = htobe(fbr.y);
649 fbr.width = htobe(fbr.width);
650 fbr.height = htobe(fbr.height);
651 fbr.encoding = htobe(fbr.encoding);
652
653 // send headers to client
654 if (!write(&fbu) || !write(&fbr))
655 return;
656
657 assert(fb);
658
660 for (int y = 0; y < fb->height(); ++y) {
661 // Convert and send a line at a time
662 uint8_t *raw_pixel(line_buffer.data());
663 for (unsigned x = 0; x < fb->width(); ++x) {
664 pixelConverter.fromPixel(raw_pixel, fb->pixel(x, y));
665 raw_pixel += pixelConverter.length;
666 }
667
668 if (!write(line_buffer.data(), line_buffer.size()))
669 return;
670 }
671}
672
673void
675{
676 assert(fb && dataFd > 0 && curState == NormalPhase);
677 DPRINTF(VNC, "Sending framebuffer resize\n");
678
680 FrameBufferRect fbr;
681
683 fbu.num_rects = 1;
684 fbr.x = 0;
685 fbr.y = 0;
686 fbr.width = videoWidth();
687 fbr.height = videoHeight();
689
690 // fix up endian
691 fbu.num_rects = htobe(fbu.num_rects);
692 fbr.x = htobe(fbr.x);
693 fbr.y = htobe(fbr.y);
694 fbr.width = htobe(fbr.width);
695 fbr.height = htobe(fbr.height);
696 fbr.encoding = htobe(fbr.encoding);
697
698 // send headers to client
699 if (!write(&fbu))
700 return;
701 write(&fbr);
702
703 // No actual data is sent in this message
704}
705
706void
714
715void
717{
718 if (dataFd > 0 && curState == NormalPhase) {
721 else
722 // The frame buffer changed size and we can't update the client
723 detach();
724 }
725}
726
727} // namespace gem5
#define DPRINTF(x,...)
Definition trace.hh:210
unsigned height() const
Frame buffer height in pixels.
const Pixel & pixel(unsigned x, unsigned y) const
Get a pixel from an (x, y) coordinate.
unsigned width() const
Frame buffer width in pixels.
static bool allDisabled()
Definition socket.cc:90
virtual std::string name() const
Definition named.hh:47
ByteOrder byte_order
Byte order when stored to memory.
Definition pixel.hh:192
Channel ch_b
Blue channel conversion helper.
Definition pixel.hh:199
unsigned depth
Number of bits used to represent one pixel value (excluding padding).
Definition pixel.hh:190
unsigned length
Bytes per pixel when stored in memory (including padding)
Definition pixel.hh:184
Channel ch_r
Red channel conversion helper.
Definition pixel.hh:195
uint32_t fromPixel(const Pixel &pixel) const
Convert a Pixel into a color word.
Definition pixel.hh:150
Channel ch_g
Green channel conversion helper.
Definition pixel.hh:197
const FrameBuffer * fb
pointer to the actual data that is stored in the frame buffer device
Definition vncinput.hh:218
virtual void setDirty()
The frame buffer uses this call to notify the vnc server that the frame buffer has been updated and a...
Definition vncinput.cc:93
uint16_t videoHeight() const
What is the height of the screen we're displaying.
Definition vncinput.hh:200
uint16_t videoWidth() const
What is the width of the screen we're displaying.
Definition vncinput.hh:193
VncKeyboard * keyboard
The device to notify when we get key events.
Definition vncinput.hh:212
VncMouse * mouse
The device to notify when we get mouse events.
Definition vncinput.hh:215
@ ClientFrameBufferUpdate
Definition vncinput.hh:98
virtual void keyPress(uint32_t key, bool down)=0
Called when the vnc server receives a key press event from the client.
virtual void mouseAt(uint16_t x, uint16_t y, uint8_t buttons)=0
called whenever the mouse moves or it's button state changes buttons is a simple mask with each butto...
void process(int revent)
Definition vncserver.cc:107
DataEvent(VncServer *vs, int fd, int e)
Poll event for the data socket.
Definition vncserver.cc:101
void process(int revent)
Definition vncserver.cc:93
ListenEvent(VncServer *vs, int fd, int e)
Poll event for the listen socket.
Definition vncserver.cc:87
void recvKeyboardInput()
Receive message from client providing new keyboard input.
Definition vncserver.cc:563
bool read1(uint8_t *buf, size_t len)
Read len -1 bytes from the client into the buffer provided + 1 assert that we read enough bytes.
Definition vncserver.cc:294
void sendServerInit()
Send client our idea about what the frame buffer looks like.
Definition vncserver.cc:445
void setEncodings()
Receive encodings message from client and process it.
Definition vncserver.cc:507
ListenEvent * listenEvent
Definition vncserver.hh:164
bool write(const uint8_t *buf, size_t len)
Write a buffer to the client.
Definition vncserver.cc:309
bool supportsResizeEnc
If the vnc client supports the desktop resize command.
Definition vncserver.hh:212
void frameBufferResized() override
Definition vncserver.cc:716
void sendFrameBufferResized()
Tell the client that the frame buffer resized.
Definition vncserver.cc:674
void setPixelFormat()
Receive pixel foramt message from client and process it.
Definition vncserver.cc:475
DataEvent * dataEvent
Definition vncserver.hh:178
ListenSocketPtr listener
Definition vncserver.hh:183
void checkSecurity()
Check that the security exchange was successful.
Definition vncserver.cc:423
friend class DataEvent
Definition vncserver.hh:177
void requestFbUpdate()
Receive message from client asking for updated frame buffer.
Definition vncserver.cc:543
friend class ListenEvent
Definition vncserver.hh:163
VncServerParams Params
Definition vncserver.hh:191
void sendFrameBufferUpdate()
Send a updated frame buffer to the client.
Definition vncserver.cc:621
void recvPointerInput()
Recv message from client providing new mouse movement or button click.
Definition vncserver.cc:579
void recvCutText()
Receive message from client that there is text in it's paste buffer.
Definition vncserver.cc:597
bool supportsRawEnc
If the vnc client supports receiving raw data.
Definition vncserver.hh:209
void setDirty() override
The frame buffer uses this call to notify the vnc server that the frame buffer has been updated and a...
Definition vncserver.cc:707
static const PixelConverter pixelConverter
Definition vncserver.hh:315
void sendError(const char *error_msg)
vnc client Interface
Definition vncserver.cc:360
void checkProtocolVersion()
Check the client's protocol verion for compatibility and send the security types we support.
Definition vncserver.cc:369
bool read(uint8_t *buf, size_t len)
Read some data from the client.
Definition vncserver.cc:273
PixelFormat pixelFormat
The one and only pixel format we support.
Definition vncserver.hh:206
VncServer(const Params &p)
VncServer.
Definition vncserver.cc:118
ConnectionState curState
The rfb prototol state the connection is in.
Definition vncserver.hh:199
bool sendUpdate
An update needs to be sent to the client.
Definition vncserver.hh:203
STL vector class.
Definition stl.hh:37
static const uint32_t VncOK
Error conditions.
Definition vncserver.hh:75
const char * vncVersion() const
Definition vncserver.hh:103
static const uint32_t AuthInvalid
Authentication modes.
Definition vncserver.hh:71
static const uint32_t AuthNone
Definition vncserver.hh:72
EventQueue * eventQueue() const
Definition eventq.hh:1003
#define panic(...)
This implements a cprintf based panic() function.
Definition logging.hh:188
void remove(PollEvent *event)
Definition pollevent.cc:139
PollQueue pollQueue
Definition pollevent.cc:55
void schedule(PollEvent *event)
Definition pollevent.cc:159
#define warn(...)
Definition logging.hh:256
#define warn_once(...)
Definition logging.hh:260
#define inform(...)
Definition logging.hh:257
Bitfield< 14, 12 > fd
Definition types.hh:150
Bitfield< 18, 16 > len
Bitfield< 6 > err
Bitfield< 9 > e
Definition misc_types.hh:65
Bitfield< 27, 25 > encoding
Definition types.hh:90
Bitfield< 19 > vs
Bitfield< 0 > p
Bitfield< 3 > x
Definition pagetable.hh:73
Bitfield< 63 > val
Definition misc.hh:804
Copyright (c) 2024 - Pranith Kumar Copyright (c) 2020 Inria All rights reserved.
Definition binary32.hh:36
T betoh(T value)
Definition byteswap.hh:175
T htobe(T value)
Definition byteswap.hh:174
ssize_t atomic_write(int fd, const void *s, size_t n)
Definition atomicio.cc:67
unsigned offset
Offset in bits.
Definition pixel.hh:122
unsigned mask
Bit mask (after shifting)
Definition pixel.hh:124
Declaration of a VNC server.

Generated on Tue Jun 18 2024 16:24:01 for gem5 by doxygen 1.11.0