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    ccprintf(cerr, "%s: Listening for connections on port %d\n",
178             name(), port);
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
743