vncserver.cc revision 10360
1/*
2 * Copyright (c) 2010 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#include <sys/termios.h>
48#include <sys/types.h>
49#include <fcntl.h>
50#include <poll.h>
51#include <unistd.h>
52
53#include <cerrno>
54#include <cstdio>
55
56#include "base/vnc/vncserver.hh"
57#include "base/atomicio.hh"
58#include "base/bitmap.hh"
59#include "base/misc.hh"
60#include "base/output.hh"
61#include "base/socket.hh"
62#include "base/trace.hh"
63#include "debug/VNC.hh"
64#include "sim/byteswap.hh"
65#include "sim/core.hh"
66
67using namespace std;
68
69/** @file
70 * Implementiation of a VNC server
71 */
72
73/**
74 * Poll event for the listen socket
75 */
76VncServer::ListenEvent::ListenEvent(VncServer *vs, int fd, int e)
77    : PollEvent(fd, e), vncserver(vs)
78{
79}
80
81void
82VncServer::ListenEvent::process(int revent)
83{
84    vncserver->accept();
85}
86
87/**
88 * Poll event for the data socket
89 */
90VncServer::DataEvent::DataEvent(VncServer *vs, int fd, int e)
91    : PollEvent(fd, e), vncserver(vs)
92{
93}
94
95void
96VncServer::DataEvent::process(int revent)
97{
98    if (revent & POLLIN)
99        vncserver->data();
100    else if (revent & POLLNVAL)
101        vncserver->detach();
102}
103
104/**
105 * VncServer
106 */
107VncServer::VncServer(const Params *p)
108    : VncInput(p), listenEvent(NULL), dataEvent(NULL), number(p->number),
109      dataFd(-1), sendUpdate(false),
110      supportsRawEnc(false), supportsResizeEnc(false)
111{
112    if (p->port)
113        listen(p->port);
114
115    curState = WaitForProtocolVersion;
116
117    // currently we only support this one pixel format
118    // unpacked 32bit rgb (rgb888 + 8 bits of nothing/alpha)
119    // keep it around for telling the client and making
120    // sure the client cooperates
121    pixelFormat.bpp = 32;
122    pixelFormat.depth = 24;
123    pixelFormat.bigendian = 0;
124    pixelFormat.truecolor = 1;
125    pixelFormat.redmax = 0xff;
126    pixelFormat.greenmax = 0xff;
127    pixelFormat.bluemax = 0xff;
128    pixelFormat.redshift = 16;
129    pixelFormat.greenshift = 8;
130    pixelFormat.blueshift = 0;
131
132    DPRINTF(VNC, "Vnc server created at port %d\n", p->port);
133}
134
135VncServer::~VncServer()
136{
137    if (dataFd != -1)
138        ::close(dataFd);
139
140    if (listenEvent)
141        delete listenEvent;
142
143    if (dataEvent)
144        delete dataEvent;
145}
146
147
148//socket creation and vnc client attach
149void
150VncServer::listen(int port)
151{
152    if (ListenSocket::allDisabled()) {
153        warn_once("Sockets disabled, not accepting vnc client connections");
154        return;
155    }
156
157    while (!listener.listen(port, true)) {
158        DPRINTF(VNC,
159                "can't bind address vnc server port %d in use PID %d\n",
160                port, getpid());
161        port++;
162    }
163
164    int p1, p2;
165    p2 = name().rfind('.') - 1;
166    p1 = name().rfind('.', p2);
167    ccprintf(cerr, "Listening for %s connection on port %d\n",
168             name().substr(p1 + 1, p2 - p1), port);
169
170    listenEvent = new ListenEvent(this, listener.getfd(), POLLIN);
171    pollQueue.schedule(listenEvent);
172}
173
174// attach a vnc client
175void
176VncServer::accept()
177{
178    // As a consequence of being called from the PollQueue, we might
179    // have been called from a different thread. Migrate to "our"
180    // thread.
181    EventQueue::ScopedMigration migrate(eventQueue());
182
183    if (!listener.islistening())
184        panic("%s: cannot accept a connection if not listening!", name());
185
186    int fd = listener.accept(true);
187    if (dataFd != -1) {
188        char message[] = "vnc server already attached!\n";
189        atomic_write(fd, message, sizeof(message));
190        ::close(fd);
191        return;
192    }
193
194    dataFd = fd;
195
196    // Send our version number to the client
197    write((uint8_t*)vncVersion(), strlen(vncVersion()));
198
199    // read the client response
200    dataEvent = new DataEvent(this, dataFd, POLLIN);
201    pollQueue.schedule(dataEvent);
202
203    inform("VNC client attached\n");
204}
205
206// data called by data event
207void
208VncServer::data()
209{
210    // We have new data, see if we can handle it
211    size_t len;
212    DPRINTF(VNC, "Vnc client message recieved\n");
213
214    switch (curState) {
215      case WaitForProtocolVersion:
216        checkProtocolVersion();
217        break;
218      case WaitForSecurityResponse:
219        checkSecurity();
220        break;
221      case WaitForClientInit:
222        // Don't care about shared, just need to read it out of the socket
223        uint8_t shared;
224        len = read(&shared);
225        assert(len == 1);
226
227        // Send our idea of the frame buffer
228        sendServerInit();
229
230        break;
231      case NormalPhase:
232        uint8_t message_type;
233        len = read(&message_type);
234        if (!len) {
235            detach();
236            return;
237        }
238        assert(len == 1);
239
240        switch (message_type) {
241          case ClientSetPixelFormat:
242            setPixelFormat();
243            break;
244          case ClientSetEncodings:
245            setEncodings();
246            break;
247          case ClientFrameBufferUpdate:
248            requestFbUpdate();
249            break;
250          case ClientKeyEvent:
251            recvKeyboardInput();
252            break;
253          case ClientPointerEvent:
254            recvPointerInput();
255            break;
256          case ClientCutText:
257            recvCutText();
258            break;
259          default:
260            panic("Unimplemented message type recv from client: %d\n",
261                  message_type);
262            break;
263        }
264        break;
265      default:
266        panic("Unknown vnc server state\n");
267    }
268}
269
270
271// read from socket
272size_t
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 <= 0){
285        DPRINTF(VNC, "Read failed.\n");
286        detach();
287        return 0;
288    }
289
290    return ret;
291}
292
293size_t
294VncServer::read1(uint8_t *buf, size_t len)
295{
296    size_t read_len M5_VAR_USED;
297    read_len = read(buf + 1, len - 1);
298    assert(read_len == len - 1);
299    return read_len;
300}
301
302
303template<typename T>
304size_t
305VncServer::read(T* val)
306{
307    return read((uint8_t*)val, sizeof(T));
308}
309
310// write to socket
311size_t
312VncServer::write(const uint8_t *buf, size_t len)
313{
314    if (dataFd < 0)
315        panic("Vnc client not properly attached.\n");
316
317    ssize_t ret;
318    ret = atomic_write(dataFd, buf, len);
319
320    if (ret < len)
321        detach();
322
323    return ret;
324}
325
326template<typename T>
327size_t
328VncServer::write(T* val)
329{
330    return write((uint8_t*)val, sizeof(T));
331}
332
333size_t
334VncServer::write(const char* str)
335{
336    return write((uint8_t*)str, strlen(str));
337}
338
339// detach a vnc client
340void
341VncServer::detach()
342{
343    if (dataFd != -1) {
344        ::close(dataFd);
345        dataFd = -1;
346    }
347
348    if (!dataEvent || !dataEvent->queued())
349        return;
350
351    pollQueue.remove(dataEvent);
352    delete dataEvent;
353    dataEvent = NULL;
354    curState = WaitForProtocolVersion;
355
356    inform("VNC client detached\n");
357    DPRINTF(VNC, "detach vnc client %d\n", number);
358}
359
360void
361VncServer::sendError(const char* error_msg)
362{
363   uint32_t len = strlen(error_msg);
364   write(&len);
365   write(error_msg);
366}
367
368void
369VncServer::checkProtocolVersion()
370{
371    assert(curState == WaitForProtocolVersion);
372
373    size_t len M5_VAR_USED;
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    len = read((uint8_t*)version_string, 12);
380    assert(len == 12);
381
382    uint32_t major, minor;
383
384    // Figure out the major/minor numbers
385    if (sscanf(version_string, "RFB %03d.%03d\n", &major, &minor) != 2) {
386        warn(" Malformed protocol version %s\n", version_string);
387        sendError("Malformed protocol version\n");
388        detach();
389    }
390
391    DPRINTF(VNC, "Client request protocol version %d.%d\n", major, minor);
392
393    // If it's not 3.X we don't support it
394    if (major != 3 || minor < 2) {
395        warn("Unsupported VNC client version... disconnecting\n");
396        uint8_t err = AuthInvalid;
397        write(&err);
398        detach();
399    }
400    // Auth is different based on version number
401    if (minor < 7) {
402        uint32_t sec_type = htobe((uint32_t)AuthNone);
403        write(&sec_type);
404    } else {
405        uint8_t sec_cnt = 1;
406        uint8_t sec_type = htobe((uint8_t)AuthNone);
407        write(&sec_cnt);
408        write(&sec_type);
409    }
410
411    // Wait for client to respond
412    curState = WaitForSecurityResponse;
413}
414
415void
416VncServer::checkSecurity()
417{
418    assert(curState == WaitForSecurityResponse);
419
420    uint8_t security_type;
421    size_t len M5_VAR_USED = read(&security_type);
422
423    assert(len == 1);
424
425    if (security_type != AuthNone) {
426        warn("Unknown VNC security type\n");
427        sendError("Unknown security type\n");
428    }
429
430    DPRINTF(VNC, "Sending security auth OK\n");
431
432    uint32_t success = htobe(VncOK);
433    write(&success);
434    curState = WaitForClientInit;
435}
436
437void
438VncServer::sendServerInit()
439{
440    ServerInitMsg msg;
441
442    DPRINTF(VNC, "Sending server init message to client\n");
443
444    msg.fbWidth = htobe(videoWidth());
445    msg.fbHeight = htobe(videoHeight());
446
447    msg.px.bpp = htobe(pixelFormat.bpp);
448    msg.px.depth = htobe(pixelFormat.depth);
449    msg.px.bigendian = htobe(pixelFormat.bigendian);
450    msg.px.truecolor = htobe(pixelFormat.truecolor);
451    msg.px.redmax = htobe(pixelFormat.redmax);
452    msg.px.greenmax = htobe(pixelFormat.greenmax);
453    msg.px.bluemax = htobe(pixelFormat.bluemax);
454    msg.px.redshift = htobe(pixelFormat.redshift);
455    msg.px.greenshift = htobe(pixelFormat.greenshift);
456    msg.px.blueshift = htobe(pixelFormat.blueshift);
457    memset(msg.px.padding, 0, 3);
458    msg.namelen = 2;
459    msg.namelen = htobe(msg.namelen);
460    memcpy(msg.name, "M5", 2);
461
462    write(&msg);
463    curState = NormalPhase;
464}
465
466void
467VncServer::setPixelFormat()
468{
469    DPRINTF(VNC, "Received pixel format from client message\n");
470
471    PixelFormatMessage pfm;
472    read1((uint8_t*)&pfm, sizeof(PixelFormatMessage));
473
474    DPRINTF(VNC, " -- bpp = %d; depth = %d; be = %d\n", pfm.px.bpp,
475            pfm.px.depth, pfm.px.bigendian);
476    DPRINTF(VNC, " -- true color = %d red,green,blue max = %d,%d,%d\n",
477            pfm.px.truecolor, betoh(pfm.px.redmax), betoh(pfm.px.greenmax),
478                betoh(pfm.px.bluemax));
479    DPRINTF(VNC, " -- red,green,blue shift = %d,%d,%d\n", pfm.px.redshift,
480            pfm.px.greenshift, pfm.px.blueshift);
481
482    if (betoh(pfm.px.bpp) != pixelFormat.bpp ||
483        betoh(pfm.px.depth) != pixelFormat.depth ||
484        betoh(pfm.px.bigendian) != pixelFormat.bigendian ||
485        betoh(pfm.px.truecolor) != pixelFormat.truecolor ||
486        betoh(pfm.px.redmax) != pixelFormat.redmax ||
487        betoh(pfm.px.greenmax) != pixelFormat.greenmax ||
488        betoh(pfm.px.bluemax) != pixelFormat.bluemax ||
489        betoh(pfm.px.redshift) != pixelFormat.redshift ||
490        betoh(pfm.px.greenshift) != pixelFormat.greenshift ||
491        betoh(pfm.px.blueshift) != pixelFormat.blueshift)
492        fatal("VNC client doesn't support true color raw encoding\n");
493}
494
495void
496VncServer::setEncodings()
497{
498    DPRINTF(VNC, "Received supported encodings from client\n");
499
500    PixelEncodingsMessage pem;
501    read1((uint8_t*)&pem, sizeof(PixelEncodingsMessage));
502
503    pem.num_encodings = betoh(pem.num_encodings);
504
505    DPRINTF(VNC, " -- %d encoding present\n", pem.num_encodings);
506    supportsRawEnc = supportsResizeEnc = false;
507
508    for (int x = 0; x < pem.num_encodings; x++) {
509        int32_t encoding;
510        size_t len M5_VAR_USED;
511        len = read(&encoding);
512        assert(len == sizeof(encoding));
513        DPRINTF(VNC, " -- supports %d\n", betoh(encoding));
514
515        switch (betoh(encoding)) {
516          case EncodingRaw:
517            supportsRawEnc = true;
518            break;
519          case EncodingDesktopSize:
520            supportsResizeEnc = true;
521            break;
522        }
523    }
524
525    if (!supportsRawEnc)
526        fatal("VNC clients must always support raw encoding\n");
527}
528
529void
530VncServer::requestFbUpdate()
531{
532    DPRINTF(VNC, "Received frame buffer update request from client\n");
533
534    FrameBufferUpdateReq fbr;
535    read1((uint8_t*)&fbr, sizeof(FrameBufferUpdateReq));
536
537    fbr.x = betoh(fbr.x);
538    fbr.y = betoh(fbr.y);
539    fbr.width = betoh(fbr.width);
540    fbr.height = betoh(fbr.height);
541
542    DPRINTF(VNC, " -- x = %d y = %d w = %d h = %d\n", fbr.x, fbr.y, fbr.width,
543            fbr.height);
544
545    sendFrameBufferUpdate();
546}
547
548void
549VncServer::recvKeyboardInput()
550{
551    DPRINTF(VNC, "Received keyboard input from client\n");
552    KeyEventMessage kem;
553    read1((uint8_t*)&kem, sizeof(KeyEventMessage));
554
555    kem.key = betoh(kem.key);
556    DPRINTF(VNC, " -- received key code %d (%s)\n", kem.key, kem.down_flag ?
557            "down" : "up");
558
559    if (keyboard)
560        keyboard->keyPress(kem.key, kem.down_flag);
561}
562
563void
564VncServer::recvPointerInput()
565{
566    DPRINTF(VNC, "Received pointer input from client\n");
567    PointerEventMessage pem;
568
569    read1((uint8_t*)&pem, sizeof(PointerEventMessage));;
570
571    pem.x = betoh(pem.x);
572    pem.y = betoh(pem.y);
573    DPRINTF(VNC, " -- pointer at x = %d y = %d buttons = %#x\n", pem.x, pem.y,
574            pem.button_mask);
575
576    if (mouse)
577        mouse->mouseAt(pem.x, pem.y, pem.button_mask);
578}
579
580void
581VncServer::recvCutText()
582{
583    DPRINTF(VNC, "Received client copy buffer message\n");
584
585    ClientCutTextMessage cct;
586    read1((uint8_t*)&cct, sizeof(ClientCutTextMessage));
587
588    char str[1025];
589    size_t data_len = betoh(cct.length);
590    DPRINTF(VNC, "String length %d\n", data_len);
591    while (data_len > 0) {
592        size_t len;
593        size_t bytes_to_read = data_len > 1024 ? 1024 : data_len;
594        len = read((uint8_t*)&str, bytes_to_read);
595        str[bytes_to_read] = 0;
596        data_len -= len;
597        assert(data_len >= 0);
598        DPRINTF(VNC, "Buffer: %s\n", str);
599    }
600
601}
602
603
604void
605VncServer::sendFrameBufferUpdate()
606{
607
608    if (!fbPtr || dataFd <= 0 || curState != NormalPhase || !sendUpdate) {
609        DPRINTF(VNC, "NOT sending framebuffer update\n");
610        return;
611    }
612
613    assert(vc);
614
615    // The client will request data constantly, unless we throttle it
616    sendUpdate = false;
617
618    DPRINTF(VNC, "Sending framebuffer update\n");
619
620    FrameBufferUpdate fbu;
621    FrameBufferRect fbr;
622
623    fbu.type = ServerFrameBufferUpdate;
624    fbu.num_rects = 1;
625    fbr.x = 0;
626    fbr.y = 0;
627    fbr.width = videoWidth();
628    fbr.height = videoHeight();
629    fbr.encoding = EncodingRaw;
630
631    // fix up endian
632    fbu.num_rects = htobe(fbu.num_rects);
633    fbr.x = htobe(fbr.x);
634    fbr.y = htobe(fbr.y);
635    fbr.width = htobe(fbr.width);
636    fbr.height = htobe(fbr.height);
637    fbr.encoding = htobe(fbr.encoding);
638
639    // send headers to client
640    write(&fbu);
641    write(&fbr);
642
643    assert(fbPtr);
644
645    uint8_t *tmp = vc->convert(fbPtr);
646    write(tmp, videoWidth() * videoHeight() * sizeof(uint32_t));
647    delete [] tmp;
648
649}
650
651void
652VncServer::sendFrameBufferResized()
653{
654    assert(fbPtr && dataFd > 0 && curState == NormalPhase);
655    DPRINTF(VNC, "Sending framebuffer resize\n");
656
657    FrameBufferUpdate fbu;
658    FrameBufferRect fbr;
659
660    fbu.type = ServerFrameBufferUpdate;
661    fbu.num_rects = 1;
662    fbr.x = 0;
663    fbr.y = 0;
664    fbr.width = videoWidth();
665    fbr.height = videoHeight();
666    fbr.encoding = EncodingDesktopSize;
667
668    // fix up endian
669    fbu.num_rects = htobe(fbu.num_rects);
670    fbr.x = htobe(fbr.x);
671    fbr.y = htobe(fbr.y);
672    fbr.width = htobe(fbr.width);
673    fbr.height = htobe(fbr.height);
674    fbr.encoding = htobe(fbr.encoding);
675
676    // send headers to client
677    write(&fbu);
678    write(&fbr);
679
680    // No actual data is sent in this message
681}
682
683void
684VncServer::setFrameBufferParams(VideoConvert::Mode mode, uint16_t width,
685    uint16_t height)
686{
687    VncInput::setFrameBufferParams(mode, width, height);
688
689    if (mode != videoMode || width != videoWidth() || height != videoHeight()) {
690        if (dataFd > 0 && fbPtr && curState == NormalPhase) {
691            if (supportsResizeEnc)
692                sendFrameBufferResized();
693            else
694                // The frame buffer changed size and we can't update the client
695                detach();
696        }
697    }
698}
699
700// create the VNC server object
701VncServer *
702VncServerParams::create()
703{
704    return new VncServer(this);
705}
706
707